@mainsoft/agent-cms 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +359 -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-CRDW6Q72.js +188 -0
- package/dist/chunk-DD56PTZ4.js +78 -0
- package/dist/chunk-DOADAH4L.js +52 -0
- package/dist/chunk-EXV6JNLY.js +251 -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-QQV6VLYJ.js +204 -0
- package/dist/chunk-T66ZKBHF.js +25 -0
- package/dist/chunk-VICZ76TR.js +118 -0
- package/dist/chunk-Y63XQS2J.js +6 -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 +1105 -0
- package/dist/http.d.cts +75 -0
- package/dist/http.d.ts +75 -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 +652 -0
- package/dist/mcp.d.cts +43 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +26 -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/cli.js
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
import {
|
|
2
|
+
loadConfig
|
|
3
|
+
} from "./chunk-T66ZKBHF.js";
|
|
4
|
+
import {
|
|
5
|
+
DrizzleRepo
|
|
6
|
+
} from "./chunk-IGL2V6US.js";
|
|
7
|
+
import {
|
|
8
|
+
docFromMarkdown
|
|
9
|
+
} from "./chunk-DD56PTZ4.js";
|
|
10
|
+
import {
|
|
11
|
+
cmsDdl,
|
|
12
|
+
cmsTables,
|
|
13
|
+
schemaVersionSql,
|
|
14
|
+
splitSql,
|
|
15
|
+
upgradeSteps
|
|
16
|
+
} from "./chunk-IW3D4I7Q.js";
|
|
17
|
+
import {
|
|
18
|
+
VERSION
|
|
19
|
+
} from "./chunk-Y63XQS2J.js";
|
|
20
|
+
import {
|
|
21
|
+
CmsRemoteError,
|
|
22
|
+
createCmsClient,
|
|
23
|
+
isCmsRemoteError
|
|
24
|
+
} from "./chunk-QC2M4NZY.js";
|
|
25
|
+
import {
|
|
26
|
+
SCHEMA_VERSION
|
|
27
|
+
} from "./chunk-OQ55GEF3.js";
|
|
28
|
+
import {
|
|
29
|
+
unifiedDiff
|
|
30
|
+
} from "./chunk-AKN7SUXU.js";
|
|
31
|
+
import "./chunk-VICZ76TR.js";
|
|
32
|
+
import "./chunk-DOADAH4L.js";
|
|
33
|
+
import {
|
|
34
|
+
__dirname
|
|
35
|
+
} from "./chunk-2NTK7H4W.js";
|
|
36
|
+
|
|
37
|
+
// src/cli.ts
|
|
38
|
+
import { spawnSync } from "child_process";
|
|
39
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
40
|
+
import { basename as basename2, dirname as dirname2, join as join2 } from "path";
|
|
41
|
+
|
|
42
|
+
// src/registry.ts
|
|
43
|
+
import { createHash } from "crypto";
|
|
44
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
45
|
+
import { basename, dirname, join, relative, resolve } from "path";
|
|
46
|
+
import { fileURLToPath } from "url";
|
|
47
|
+
var sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
48
|
+
function findRegistryDir() {
|
|
49
|
+
const here = typeof __dirname === "string" ? __dirname : dirname(fileURLToPath(import.meta.url));
|
|
50
|
+
const candidates = [
|
|
51
|
+
[join(here, "registry"), true],
|
|
52
|
+
[join(here, "..", "dist", "registry"), true],
|
|
53
|
+
[join(here, "..", "registry"), false]
|
|
54
|
+
];
|
|
55
|
+
for (const [dir, built] of candidates) if (existsSync(join(dir, "registry.json"))) return { dir, built };
|
|
56
|
+
throw new Error("[agent-cms] registry not found (is the package built?)");
|
|
57
|
+
}
|
|
58
|
+
function loadRegistry(loc = findRegistryDir()) {
|
|
59
|
+
const index = JSON.parse(readFileSync(join(loc.dir, "registry.json"), "utf8"));
|
|
60
|
+
const root = loc.built ? loc.dir : resolve(loc.dir, "..");
|
|
61
|
+
const items = index.items.map((it) => {
|
|
62
|
+
if (loc.built) {
|
|
63
|
+
const full = JSON.parse(readFileSync(join(loc.dir, `${it.name}.json`), "utf8"));
|
|
64
|
+
return full;
|
|
65
|
+
}
|
|
66
|
+
return { ...it, files: it.files.map((f) => ({ ...f, content: readFileSync(join(root, f.path), "utf8") })) };
|
|
67
|
+
});
|
|
68
|
+
return { ...index, items };
|
|
69
|
+
}
|
|
70
|
+
function resolveItems(reg, names) {
|
|
71
|
+
const byName = new Map(reg.items.map((i) => [i.name, i]));
|
|
72
|
+
const out = [];
|
|
73
|
+
const seen = /* @__PURE__ */ new Set();
|
|
74
|
+
const visit = (n, from) => {
|
|
75
|
+
const it = byName.get(n);
|
|
76
|
+
if (!it) throw new Error(`[agent-cms] unknown item "${n}"${from ? ` (needed by ${from})` : ""}. Items: ${reg.items.map((i) => i.name).join(", ")}`);
|
|
77
|
+
if (seen.has(n)) return;
|
|
78
|
+
seen.add(n);
|
|
79
|
+
for (const d of it.registryDependencies ?? []) if (byName.has(d)) visit(d, n);
|
|
80
|
+
out.push(it);
|
|
81
|
+
};
|
|
82
|
+
for (const n of names) visit(n);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
function shadcnParts(reg, items) {
|
|
86
|
+
const own = new Set(reg.items.map((i) => i.name));
|
|
87
|
+
return [...new Set(items.flatMap((i) => i.registryDependencies ?? []).filter((d) => !own.has(d)))].sort();
|
|
88
|
+
}
|
|
89
|
+
function aliasToDir(cwd, alias) {
|
|
90
|
+
let base = ".";
|
|
91
|
+
for (const f of ["tsconfig.json", "jsconfig.json"]) {
|
|
92
|
+
const p = join(cwd, f);
|
|
93
|
+
if (!existsSync(p)) continue;
|
|
94
|
+
try {
|
|
95
|
+
const text = readFileSync(p, "utf8").replace(/\/\*[\s\S]*?\*\/|(^|[^:])\/\/.*$/gm, "$1").replace(/,(\s*[}\]])/g, "$1");
|
|
96
|
+
const paths = JSON.parse(text).compilerOptions?.paths ?? {};
|
|
97
|
+
const target = paths["@/*"]?.[0];
|
|
98
|
+
if (target) base = target.replace(/\/\*$/, "");
|
|
99
|
+
} catch {
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
return alias.startsWith("@/") ? resolve(cwd, base, alias.slice(2)) : resolve(cwd, alias);
|
|
104
|
+
}
|
|
105
|
+
function appLayout(cwd, o = {}) {
|
|
106
|
+
const cj = join(cwd, "components.json");
|
|
107
|
+
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.");
|
|
108
|
+
const aliases = JSON.parse(readFileSync(cj, "utf8")).aliases ?? {};
|
|
109
|
+
const components = aliases.components ?? "@/components";
|
|
110
|
+
const ui = aliases.ui ?? `${components}/ui`;
|
|
111
|
+
const utils = aliases.utils ?? "@/lib/utils";
|
|
112
|
+
return { dir: o.dir ? resolve(cwd, o.dir) : join(aliasToDir(cwd, components), "cms"), uiDir: aliasToDir(cwd, ui), aliases: { ui, utils } };
|
|
113
|
+
}
|
|
114
|
+
function rewriteImports(content, aliases) {
|
|
115
|
+
return content.replace(/(["'])@\/components\/ui\//g, `$1${aliases.ui}/`).replace(/(["'])@\/lib\/utils(["'])/g, `$1${aliases.utils}$2`);
|
|
116
|
+
}
|
|
117
|
+
var LOCK_FILE = "agent-cms.json";
|
|
118
|
+
function readLock(cwd) {
|
|
119
|
+
const p = join(cwd, LOCK_FILE);
|
|
120
|
+
if (!existsSync(p)) return { version: VERSION, files: {} };
|
|
121
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
122
|
+
}
|
|
123
|
+
function addItems(o) {
|
|
124
|
+
const reg = o.registry ?? loadRegistry();
|
|
125
|
+
const layout = appLayout(o.cwd, { dir: o.dir });
|
|
126
|
+
const lock = readLock(o.cwd);
|
|
127
|
+
const names = o.items.length ? o.items : o.mode === "add" ? [] : [...new Set(Object.values(lock.files).map((f) => f.item))];
|
|
128
|
+
if (!names.length) throw new Error(`[agent-cms] name the items to add: ${reg.items.map((i) => i.name).join(", ")}`);
|
|
129
|
+
const items = resolveItems(reg, names);
|
|
130
|
+
const res = { written: [], skipped: [], updated: [], conflicts: [], unchanged: [], missingParts: [], diff: "" };
|
|
131
|
+
const diffs = [];
|
|
132
|
+
for (const it of items) {
|
|
133
|
+
for (const f of it.files) {
|
|
134
|
+
const target = join(layout.dir, basename(f.path));
|
|
135
|
+
const rel = relative(o.cwd, target).split("\\").join("/");
|
|
136
|
+
const next = rewriteImports(f.content ?? "", layout.aliases);
|
|
137
|
+
const exists = existsSync(target);
|
|
138
|
+
const cur = exists ? readFileSync(target, "utf8") : null;
|
|
139
|
+
const locked = lock.files[rel];
|
|
140
|
+
if (o.mode === "diff") {
|
|
141
|
+
if (cur === null) diffs.push(`+++ ${rel} (not installed)`);
|
|
142
|
+
else if (cur !== next) diffs.push(unifiedDiff(cur, next, { from: `${rel} (yours)`, to: `${rel} (${VERSION})` }));
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const write = () => {
|
|
146
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
147
|
+
writeFileSync(target, next);
|
|
148
|
+
lock.files[rel] = { item: it.name, version: VERSION, hash: sha(next) };
|
|
149
|
+
};
|
|
150
|
+
if (cur === next) {
|
|
151
|
+
lock.files[rel] = { item: it.name, version: VERSION, hash: sha(next) };
|
|
152
|
+
res.unchanged.push(rel);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (o.mode === "add") {
|
|
156
|
+
if (exists && !o.overwrite) {
|
|
157
|
+
res.skipped.push({ file: rel, reason: locked ? "already installed (use --diff / --update)" : "a file with this name exists (use --overwrite)" });
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
write();
|
|
161
|
+
res.written.push(rel);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (cur === null) {
|
|
165
|
+
write();
|
|
166
|
+
res.written.push(rel);
|
|
167
|
+
} else if (locked && sha(cur) === locked.hash) {
|
|
168
|
+
write();
|
|
169
|
+
res.updated.push(rel);
|
|
170
|
+
} else {
|
|
171
|
+
writeFileSync(`${target}.new`, next);
|
|
172
|
+
res.conflicts.push(rel);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const parts = shadcnParts(reg, items);
|
|
177
|
+
res.missingParts = parts.filter((p) => !existsSync(join(layout.uiDir, `${p}.tsx`)) && !existsSync(join(layout.uiDir, `${p}.jsx`)));
|
|
178
|
+
res.diff = diffs.filter(Boolean).join("\n\n");
|
|
179
|
+
if (o.mode !== "diff") writeFileSync(join(o.cwd, LOCK_FILE), JSON.stringify({ ...lock, version: VERSION }, null, 2) + "\n");
|
|
180
|
+
return res;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/cli.ts
|
|
184
|
+
var WITH_VALUE = /* @__PURE__ */ new Set(["--env", "--note", "--collections", "--expected-version", "--dir", "--format"]);
|
|
185
|
+
function flag(argv, name) {
|
|
186
|
+
const i = argv.indexOf(`--${name}`);
|
|
187
|
+
if (i >= 0) return argv[i + 1];
|
|
188
|
+
const eq = argv.find((a) => a.startsWith(`--${name}=`));
|
|
189
|
+
return eq?.slice(name.length + 3);
|
|
190
|
+
}
|
|
191
|
+
function positional(argv) {
|
|
192
|
+
const out = [];
|
|
193
|
+
for (let i = 0; i < argv.length; i++) {
|
|
194
|
+
const a = argv[i];
|
|
195
|
+
if (WITH_VALUE.has(a)) {
|
|
196
|
+
i++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (a.startsWith("--")) continue;
|
|
200
|
+
out.push(a);
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
function parseEnvFile(text) {
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const line of text.split(/\r?\n/)) {
|
|
207
|
+
const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/.exec(line);
|
|
208
|
+
if (m) out[m[1]] = m[2].replace(/^["']|["']$/g, "");
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
var USAGE = `agent-cms ${VERSION}
|
|
213
|
+
in your app: init | doctor | migrate <check|print|apply> | add <item...> [--diff|--update]
|
|
214
|
+
with a key: tools | collections | list | get | search | put | patch | publish | call
|
|
215
|
+
see https://github.com/mainsoft-2024/agent-cms#cli`;
|
|
216
|
+
var LOCAL = /* @__PURE__ */ new Set(["init", "doctor", "migrate", "add"]);
|
|
217
|
+
async function runCli(argv, io = {}) {
|
|
218
|
+
const out = io.out ?? ((l) => console.log(l));
|
|
219
|
+
const err = io.err ?? ((l) => console.error(l));
|
|
220
|
+
const read = io.readFile ?? ((p) => readFileSync2(p, "utf8"));
|
|
221
|
+
const cwd = io.cwd ?? process.cwd();
|
|
222
|
+
const [cmd, ...args] = positional(argv);
|
|
223
|
+
if (cmd === "version" || !cmd && argv.includes("--version")) {
|
|
224
|
+
out(VERSION);
|
|
225
|
+
return 0;
|
|
226
|
+
}
|
|
227
|
+
if (!cmd || cmd === "help" || argv.includes("--help")) {
|
|
228
|
+
out(USAGE);
|
|
229
|
+
return cmd ? 0 : 1;
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
if (LOCAL.has(cmd)) return await runLocal(cmd, args, argv, { ...io, cwd, out, err });
|
|
233
|
+
return await runRemote(cmd, args, argv, { ...io, out, err, read });
|
|
234
|
+
} catch (e) {
|
|
235
|
+
err(`[agent-cms] ${isCmsRemoteError(e) ? `${e.code}: ` : ""}${e instanceof Error ? e.message : String(e)}`);
|
|
236
|
+
return 1;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function runRemote(cmd, args, argv, io) {
|
|
240
|
+
const { out, err, read } = io;
|
|
241
|
+
const envFile = flag(argv, "env");
|
|
242
|
+
const env = { ...io.env ?? process.env, ...envFile ? parseEnvFile(read(envFile)) : {} };
|
|
243
|
+
if (!env.AGENT_CMS_URL || !env.AGENT_CMS_KEY) {
|
|
244
|
+
err("[agent-cms] set AGENT_CMS_URL and AGENT_CMS_KEY (or pass --env <file>).");
|
|
245
|
+
return 1;
|
|
246
|
+
}
|
|
247
|
+
const api = createCmsClient({ url: env.AGENT_CMS_URL, key: env.AGENT_CMS_KEY, fetch: io.fetch, clientName: "cli" });
|
|
248
|
+
const print = (v) => out(JSON.stringify(v, null, 2));
|
|
249
|
+
const need = (n) => {
|
|
250
|
+
if (args.length < n) throw new CmsRemoteError(`missing arguments
|
|
251
|
+
${USAGE}`, "usage");
|
|
252
|
+
};
|
|
253
|
+
const expectedVersion = () => {
|
|
254
|
+
const raw = flag(argv, "expected-version");
|
|
255
|
+
const n = raw === void 0 ? void 0 : Number(raw);
|
|
256
|
+
if (n !== void 0 && !(Number.isInteger(n) && n > 0)) throw new CmsRemoteError("--expected-version must be a positive integer", "usage");
|
|
257
|
+
return n;
|
|
258
|
+
};
|
|
259
|
+
switch (cmd) {
|
|
260
|
+
case "tools":
|
|
261
|
+
print((await api.listTools()).map((t) => ({ name: t.name, description: t.description })));
|
|
262
|
+
return 0;
|
|
263
|
+
case "collections":
|
|
264
|
+
print(await api.call("list_collections"));
|
|
265
|
+
return 0;
|
|
266
|
+
case "list":
|
|
267
|
+
need(1);
|
|
268
|
+
print(await api.call("list_documents", { collection: args[0], drafts: argv.includes("--drafts") }));
|
|
269
|
+
return 0;
|
|
270
|
+
case "get":
|
|
271
|
+
need(2);
|
|
272
|
+
print(await api.call("get_document", { collection: args[0], slug: args[1], draft: argv.includes("--draft") }));
|
|
273
|
+
return 0;
|
|
274
|
+
case "search": {
|
|
275
|
+
need(1);
|
|
276
|
+
const cols = flag(argv, "collections");
|
|
277
|
+
print(await api.call("search_documents", { query: args.join(" "), collections: cols ? cols.split(",") : void 0 }));
|
|
278
|
+
return 0;
|
|
279
|
+
}
|
|
280
|
+
case "publish":
|
|
281
|
+
need(2);
|
|
282
|
+
print(await api.call("publish_document", { collection: args[0], slug: args[1] }));
|
|
283
|
+
return 0;
|
|
284
|
+
case "patch": {
|
|
285
|
+
need(3);
|
|
286
|
+
const ops = JSON.parse(read(args[2]));
|
|
287
|
+
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") }));
|
|
288
|
+
return 0;
|
|
289
|
+
}
|
|
290
|
+
case "put": {
|
|
291
|
+
need(2);
|
|
292
|
+
const [collection, file] = args;
|
|
293
|
+
const doc = docFromMarkdown(read(file), basename2(file).replace(/\.(md|markdown)$/i, ""));
|
|
294
|
+
const publish = argv.includes("--publish");
|
|
295
|
+
const note = flag(argv, "note");
|
|
296
|
+
const expected = expectedVersion();
|
|
297
|
+
const current = await api.call("get_document", { collection, slug: doc.slug, draft: true }).catch((e) => {
|
|
298
|
+
if (isCmsRemoteError(e) && e.code === "not_found") return null;
|
|
299
|
+
throw e;
|
|
300
|
+
});
|
|
301
|
+
if (current && expected === void 0 && !argv.includes("--force")) {
|
|
302
|
+
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");
|
|
303
|
+
}
|
|
304
|
+
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 });
|
|
305
|
+
print(result);
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
case "call": {
|
|
309
|
+
need(1);
|
|
310
|
+
const parsed = args[1] ? JSON.parse(args[1]) : {};
|
|
311
|
+
print(await api.call(args[0], parsed));
|
|
312
|
+
return 0;
|
|
313
|
+
}
|
|
314
|
+
default:
|
|
315
|
+
err(`unknown command: ${cmd}
|
|
316
|
+
${USAGE}`);
|
|
317
|
+
return 1;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async function runLocal(cmd, args, argv, io) {
|
|
321
|
+
if (cmd === "init") return init(argv, io);
|
|
322
|
+
if (cmd === "add") return add(args, argv, io);
|
|
323
|
+
const loaded = await loadConfig(io.cwd);
|
|
324
|
+
const tables = cmsTables(loaded?.config.tables);
|
|
325
|
+
if (cmd === "migrate" && args[0] === "print") {
|
|
326
|
+
io.out(cmsDdl(tables));
|
|
327
|
+
return 0;
|
|
328
|
+
}
|
|
329
|
+
let db = io.db;
|
|
330
|
+
if (!db && loaded?.config.db) {
|
|
331
|
+
try {
|
|
332
|
+
db = await loaded.config.db();
|
|
333
|
+
} catch (e) {
|
|
334
|
+
io.err(`[agent-cms] db() in ${loaded.path} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
335
|
+
return 1;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (!db) {
|
|
339
|
+
io.err("[agent-cms] no database: add `db: () => yourDrizzleDb` to agent-cms.config.ts (run `npx agent-cms init` to create it).");
|
|
340
|
+
return 1;
|
|
341
|
+
}
|
|
342
|
+
const repo = new DrizzleRepo(db, { tables });
|
|
343
|
+
if (cmd === "doctor") return doctor(await repo.inspect(), tables.options, io);
|
|
344
|
+
if (cmd === "migrate") {
|
|
345
|
+
const sub = args[0] ?? "check";
|
|
346
|
+
if (sub === "apply") {
|
|
347
|
+
const { sql } = await import("drizzle-orm");
|
|
348
|
+
for (const stmt of splitSql(cmsDdl(tables))) await db.execute(sql.raw(stmt));
|
|
349
|
+
io.out(`[agent-cms] schema is at v${SCHEMA_VERSION}.`);
|
|
350
|
+
return 0;
|
|
351
|
+
}
|
|
352
|
+
if (sub === "check") {
|
|
353
|
+
const r = await repo.inspect();
|
|
354
|
+
const pending = migrationSql(r, tables);
|
|
355
|
+
if (!pending) {
|
|
356
|
+
io.out(`[agent-cms] schema is up to date (v${SCHEMA_VERSION}).`);
|
|
357
|
+
return 0;
|
|
358
|
+
}
|
|
359
|
+
if (flag(argv, "format") === "step") for (const s of pending.steps) io.out(`- ${s}`);
|
|
360
|
+
else io.out(pending.sql);
|
|
361
|
+
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\`.`);
|
|
362
|
+
return 1;
|
|
363
|
+
}
|
|
364
|
+
io.err(`unknown: migrate ${sub} (check | print | apply)`);
|
|
365
|
+
return 1;
|
|
366
|
+
}
|
|
367
|
+
return 1;
|
|
368
|
+
}
|
|
369
|
+
function migrationSql(r, tables) {
|
|
370
|
+
const current = r.schemaVersion ?? 0;
|
|
371
|
+
if (!r.missingTables.length && !r.missingColumns.length && current >= SCHEMA_VERSION) return null;
|
|
372
|
+
if (r.missingTables.some((t) => !t.endsWith("audit") && !t.endsWith("meta"))) return { sql: cmsDdl(tables), steps: ["create the agent-cms tables"] };
|
|
373
|
+
const steps = upgradeSteps(tables).filter((s) => s.version > current || r.missingColumns.length > 0 || r.missingTables.length > 0);
|
|
374
|
+
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());
|
|
375
|
+
` : "";
|
|
376
|
+
return { sql: `${meta}${steps.map((s) => `-- ${s.name}
|
|
377
|
+
${s.sql}`).join("\n\n")}
|
|
378
|
+
${schemaVersionSql(tables)}`, steps: steps.map((s) => s.name) };
|
|
379
|
+
}
|
|
380
|
+
function doctor(r, o, io) {
|
|
381
|
+
const lines = [];
|
|
382
|
+
let bad = false;
|
|
383
|
+
const ok = (m) => lines.push(`ok ${m}`);
|
|
384
|
+
const warn = (m) => lines.push(`warn ${m}`);
|
|
385
|
+
const fail = (m) => {
|
|
386
|
+
bad = true;
|
|
387
|
+
lines.push(`FAIL ${m}`);
|
|
388
|
+
};
|
|
389
|
+
if (r.missingTables.length) fail(`missing tables: ${r.missingTables.join(", ")} (npx agent-cms migrate check)`);
|
|
390
|
+
else ok("all tables exist");
|
|
391
|
+
if (r.missingColumns.length) fail(`missing columns: ${r.missingColumns.join(", ")} (npx agent-cms migrate check)`);
|
|
392
|
+
else if (!r.missingTables.length) ok("all columns exist");
|
|
393
|
+
if (r.schemaVersion === null || r.schemaVersion < r.expectedSchemaVersion) fail(`schema version ${r.schemaVersion ?? "unknown"}, this release needs ${r.expectedSchemaVersion} (npx agent-cms migrate check)`);
|
|
394
|
+
else ok(`schema version ${r.schemaVersion}`);
|
|
395
|
+
if (r.badPublished) fail(`${r.badPublished} document(s) point at a published version that is missing`);
|
|
396
|
+
if (r.orphanVersions) warn(`${r.orphanVersions} version row(s) without a document`);
|
|
397
|
+
if (r.legacyColumns.length) {
|
|
398
|
+
warn(`old columns nothing reads any more: ${r.legacyColumns.join(", ")}. To drop them:`);
|
|
399
|
+
const t = (name) => o.schema ? `"${o.schema}"."${name}"` : `"${name}"`;
|
|
400
|
+
for (const c of r.legacyColumns) {
|
|
401
|
+
const [table, column] = c.split(".");
|
|
402
|
+
lines.push(` ALTER TABLE ${t(table)} DROP COLUMN IF EXISTS "${column}";`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (r.gapsTable) {
|
|
406
|
+
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.`);
|
|
407
|
+
}
|
|
408
|
+
for (const l of lines) io.out(l);
|
|
409
|
+
return bad ? 1 : 0;
|
|
410
|
+
}
|
|
411
|
+
function init(argv, io) {
|
|
412
|
+
const cwd = io.cwd;
|
|
413
|
+
const appDir = existsSync2(join2(cwd, "src", "app")) ? "src/" : "";
|
|
414
|
+
const files = [
|
|
415
|
+
[
|
|
416
|
+
"agent-cms.config.ts",
|
|
417
|
+
`import { defineConfig } from "@mainsoft/agent-cms/config";
|
|
418
|
+
|
|
419
|
+
export default defineConfig({
|
|
420
|
+
// Your Drizzle database (used by \`agent-cms doctor\` and \`migrate\`).
|
|
421
|
+
db: async () => (await import("./${appDir}lib/db")).db,
|
|
422
|
+
});
|
|
423
|
+
`
|
|
424
|
+
],
|
|
425
|
+
[
|
|
426
|
+
`${appDir}lib/cms-schema.ts`,
|
|
427
|
+
`// Re-export the agent-cms tables from your Drizzle schema so drizzle-kit sees them.
|
|
428
|
+
export { cmsApiKeys, cmsAudit, cmsDocuments, cmsHits, cmsMeta, cmsVersions } from "@mainsoft/agent-cms/tables";
|
|
429
|
+
`
|
|
430
|
+
],
|
|
431
|
+
[
|
|
432
|
+
`${appDir}lib/cms.ts`,
|
|
433
|
+
`import { createCms, defineCollection, DrizzleRepo } from "@mainsoft/agent-cms";
|
|
434
|
+
import { db } from "./db";
|
|
435
|
+
|
|
436
|
+
export const posts = defineCollection({
|
|
437
|
+
slug: "posts",
|
|
438
|
+
label: "Posts",
|
|
439
|
+
visibility: "public",
|
|
440
|
+
url: (d) => \`/posts/\${d.slug}\`,
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
export const cms = createCms({
|
|
444
|
+
repo: new DrizzleRepo(db),
|
|
445
|
+
collections: [posts],
|
|
446
|
+
previewSecret: process.env.CMS_PREVIEW_SECRET,
|
|
447
|
+
// Searches that found nothing (when the caller asks): store them if you want.
|
|
448
|
+
onSearchMiss: async (e) => {
|
|
449
|
+
void e;
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
`
|
|
453
|
+
],
|
|
454
|
+
[
|
|
455
|
+
`${appDir}app/api/cms/[...path]/route.ts`,
|
|
456
|
+
`import { createCmsHandler } from "@mainsoft/agent-cms/http";
|
|
457
|
+
import { cms } from "@/lib/cms";
|
|
458
|
+
|
|
459
|
+
const handler = createCmsHandler({
|
|
460
|
+
cms,
|
|
461
|
+
// Return the signed-in user, or null. Admins may do everything.
|
|
462
|
+
resolveUser: async () => null,
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE };
|
|
466
|
+
`
|
|
467
|
+
]
|
|
468
|
+
];
|
|
469
|
+
const created = [];
|
|
470
|
+
for (const [rel, content] of files) {
|
|
471
|
+
const p = join2(cwd, rel);
|
|
472
|
+
if (existsSync2(p)) {
|
|
473
|
+
io.out(`skip ${rel} (exists)`);
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
mkdirSync2(dirname2(p), { recursive: true });
|
|
477
|
+
writeFileSync2(p, content);
|
|
478
|
+
created.push(rel);
|
|
479
|
+
io.out(`write ${rel}`);
|
|
480
|
+
}
|
|
481
|
+
const envPath = join2(cwd, ".env.example");
|
|
482
|
+
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"];
|
|
483
|
+
const env = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
|
|
484
|
+
const missing = envLines.filter((l) => !env.includes(l.split("=")[0] + "="));
|
|
485
|
+
if (missing.length) {
|
|
486
|
+
writeFileSync2(envPath, `${env}${env && !env.endsWith("\n") ? "\n" : ""}${missing.join("\n")}
|
|
487
|
+
`);
|
|
488
|
+
io.out(`write .env.example (${missing.length} line(s))`);
|
|
489
|
+
}
|
|
490
|
+
io.out(`
|
|
491
|
+
next:
|
|
492
|
+
1. point ${appDir}lib/cms.ts and agent-cms.config.ts at your Drizzle db, and resolveUser at your session
|
|
493
|
+
2. npx agent-cms migrate check (SQL for your migration, or: npx agent-cms migrate apply)
|
|
494
|
+
3. npx agent-cms add cms-shell cms-doc-list cms-doc-editor cms-versions cms-keys cms-audit cms-command`);
|
|
495
|
+
void argv;
|
|
496
|
+
return 0;
|
|
497
|
+
}
|
|
498
|
+
function add(args, argv, io) {
|
|
499
|
+
const registry = io.registry ?? loadRegistry();
|
|
500
|
+
if (argv.includes("--list")) {
|
|
501
|
+
for (const it of registry.items) io.out(`${it.name.padEnd(16)} ${it.description ?? ""}`);
|
|
502
|
+
return 0;
|
|
503
|
+
}
|
|
504
|
+
const mode = argv.includes("--diff") ? "diff" : argv.includes("--update") ? "update" : "add";
|
|
505
|
+
const r = addItems({ cwd: io.cwd, items: args, mode, dir: flag(argv, "dir"), overwrite: argv.includes("--overwrite"), registry });
|
|
506
|
+
if (mode === "diff") {
|
|
507
|
+
io.out(r.diff || "[agent-cms] your copies match this version.");
|
|
508
|
+
return 0;
|
|
509
|
+
}
|
|
510
|
+
for (const f of r.written) io.out(`write ${f}`);
|
|
511
|
+
for (const f of r.updated) io.out(`update ${f}`);
|
|
512
|
+
for (const f of r.unchanged) io.out(`same ${f}`);
|
|
513
|
+
for (const s of r.skipped) io.out(`skip ${s.file} (${s.reason})`);
|
|
514
|
+
for (const f of r.conflicts) io.out(`keep ${f} (you changed it; the new version is in ${f}.new)`);
|
|
515
|
+
if (r.missingParts.length) {
|
|
516
|
+
const cmd = ["shadcn@latest", "add", ...r.missingParts];
|
|
517
|
+
if (argv.includes("--yes")) {
|
|
518
|
+
const code = (io.run ?? ((c, a, cwd) => spawnSync(c, a, { cwd, stdio: "inherit", shell: process.platform === "win32" }).status ?? 1))("npx", ["--yes", ...cmd], io.cwd);
|
|
519
|
+
if (code !== 0) {
|
|
520
|
+
io.err(`[agent-cms] \`npx ${cmd.join(" ")}\` failed`);
|
|
521
|
+
return 1;
|
|
522
|
+
}
|
|
523
|
+
} else io.out(`
|
|
524
|
+
these screens use shadcn/ui parts you do not have yet:
|
|
525
|
+
npx ${cmd.join(" ")}
|
|
526
|
+
(or run add again with --yes)`);
|
|
527
|
+
}
|
|
528
|
+
return 0;
|
|
529
|
+
}
|
|
530
|
+
export {
|
|
531
|
+
migrationSql,
|
|
532
|
+
parseEnvFile,
|
|
533
|
+
runCli
|
|
534
|
+
};
|