easy-cms 0.1.0 → 0.2.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/bin/easy-cms.js +4 -0
- package/dist/bin.js +1 -1
- package/dist/chunk-AAFZW525.js +419 -0
- package/dist/index.d.ts +33 -1
- package/dist/index.js +7 -3
- package/package.json +6 -4
- package/dist/chunk-3JYUADKB.js +0 -220
package/bin/easy-cms.js
ADDED
package/dist/bin.js
CHANGED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { existsSync } from "fs";
|
|
3
|
+
import { writeFile } from "fs/promises";
|
|
4
|
+
import { isAbsolute, join, resolve } from "path";
|
|
5
|
+
import { createInterface } from "readline/promises";
|
|
6
|
+
import { parseArgs } from "util";
|
|
7
|
+
import {
|
|
8
|
+
ConfigError,
|
|
9
|
+
createEasyCMS as createEasyCMS2,
|
|
10
|
+
EasyCMSError,
|
|
11
|
+
generateTypes,
|
|
12
|
+
loadConfig,
|
|
13
|
+
ValidationError
|
|
14
|
+
} from "@easy-cms/core";
|
|
15
|
+
|
|
16
|
+
// src/serve.ts
|
|
17
|
+
import { watch } from "fs";
|
|
18
|
+
import { createServer } from "http";
|
|
19
|
+
import { Readable } from "stream";
|
|
20
|
+
import { pipeline } from "stream/promises";
|
|
21
|
+
import { createAdminHandler } from "@easy-cms/admin";
|
|
22
|
+
import {
|
|
23
|
+
createEasyCMS,
|
|
24
|
+
createRestHandler
|
|
25
|
+
} from "@easy-cms/core";
|
|
26
|
+
function createStandaloneHandler(cms) {
|
|
27
|
+
const config = cms.config;
|
|
28
|
+
const adminPath = `/${config.admin.path.replace(/^\/+|\/+$/g, "")}`;
|
|
29
|
+
const clientIps = /* @__PURE__ */ new WeakMap();
|
|
30
|
+
const api = createRestHandler(cms, { getClientIp: (request) => clientIps.get(request) });
|
|
31
|
+
const admin = createAdminHandler({
|
|
32
|
+
basePath: adminPath,
|
|
33
|
+
apiPath: config.routes.api,
|
|
34
|
+
locale: config.admin.locale
|
|
35
|
+
});
|
|
36
|
+
const under = (path, base) => path === base || path.startsWith(`${base}/`);
|
|
37
|
+
return async (request, clientIp) => {
|
|
38
|
+
const { pathname } = new URL(request.url);
|
|
39
|
+
if (under(pathname, config.routes.api)) {
|
|
40
|
+
clientIps.set(request, clientIp);
|
|
41
|
+
return api(request);
|
|
42
|
+
}
|
|
43
|
+
if (under(pathname, adminPath)) return admin(request);
|
|
44
|
+
if (pathname === "/healthz")
|
|
45
|
+
return new Response("ok", { headers: { "cache-control": "no-store" } });
|
|
46
|
+
if (pathname === "/")
|
|
47
|
+
return new Response(null, { status: 302, headers: { location: `${adminPath}/` } });
|
|
48
|
+
return Response.json({ message: "Not found" }, { status: 404 });
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function toWebRequest(req, trustProxy) {
|
|
52
|
+
const forwardedProto = trustProxy ? header(req, "x-forwarded-proto")?.split(",")[0]?.trim() : void 0;
|
|
53
|
+
const encrypted = req.socket.encrypted === true;
|
|
54
|
+
const protocol = forwardedProto ?? (encrypted ? "https" : "http");
|
|
55
|
+
const url = new URL(req.url ?? "/", `${protocol}://${header(req, "host") ?? "localhost"}`);
|
|
56
|
+
const headers = new Headers();
|
|
57
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
58
|
+
if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
59
|
+
else if (value !== void 0) headers.set(name, value);
|
|
60
|
+
}
|
|
61
|
+
const method = req.method ?? "GET";
|
|
62
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
63
|
+
return new Request(url, {
|
|
64
|
+
method,
|
|
65
|
+
headers,
|
|
66
|
+
...hasBody ? { body: Readable.toWeb(req), duplex: "half" } : {}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
async function sendWebResponse(res, response) {
|
|
70
|
+
res.statusCode = response.status;
|
|
71
|
+
const cookies = response.headers.getSetCookie();
|
|
72
|
+
response.headers.forEach((value, name) => {
|
|
73
|
+
if (name !== "set-cookie") res.setHeader(name, value);
|
|
74
|
+
});
|
|
75
|
+
if (cookies.length > 0) res.setHeader("set-cookie", cookies);
|
|
76
|
+
if (!response.body) {
|
|
77
|
+
res.end();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
await pipeline(Readable.fromWeb(response.body), res);
|
|
81
|
+
}
|
|
82
|
+
function header(req, name) {
|
|
83
|
+
const value = req.headers[name];
|
|
84
|
+
return Array.isArray(value) ? value[0] : value;
|
|
85
|
+
}
|
|
86
|
+
function clientIpOf(req, trustProxy) {
|
|
87
|
+
if (trustProxy) {
|
|
88
|
+
const forwarded = header(req, "x-forwarded-for")?.split(",")[0]?.trim();
|
|
89
|
+
if (forwarded) return forwarded;
|
|
90
|
+
}
|
|
91
|
+
return req.socket.remoteAddress;
|
|
92
|
+
}
|
|
93
|
+
var WATCHED = /\.(?:[cm]?[jt]s)$/;
|
|
94
|
+
var IGNORED = /(?:^|[/\\])(?:node_modules|\.git|dist|\.output|\.next|uploads)(?:[/\\]|$)/;
|
|
95
|
+
async function startServer(options) {
|
|
96
|
+
const { logger, cwd } = options;
|
|
97
|
+
const trustProxy = options.trustProxy ?? false;
|
|
98
|
+
let cms = await createEasyCMS(await options.loadConfig(), { cwd, logger });
|
|
99
|
+
let handler = createStandaloneHandler(cms);
|
|
100
|
+
const server = createServer(async (req, res) => {
|
|
101
|
+
try {
|
|
102
|
+
await sendWebResponse(
|
|
103
|
+
res,
|
|
104
|
+
await handler(toWebRequest(req, trustProxy), clientIpOf(req, trustProxy))
|
|
105
|
+
);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
logger.error(`Request failed: ${error.message}`);
|
|
108
|
+
if (!res.headersSent) {
|
|
109
|
+
res.statusCode = 500;
|
|
110
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
111
|
+
}
|
|
112
|
+
res.end(res.headersSent ? void 0 : JSON.stringify({ message: "Internal server error" }));
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
let watcher;
|
|
116
|
+
if (options.watch) {
|
|
117
|
+
let timer;
|
|
118
|
+
let reloading = Promise.resolve();
|
|
119
|
+
const reload = () => {
|
|
120
|
+
reloading = reloading.then(async () => {
|
|
121
|
+
try {
|
|
122
|
+
const next = await createEasyCMS(await options.loadConfig(), { cwd, logger });
|
|
123
|
+
const previous = cms;
|
|
124
|
+
cms = next;
|
|
125
|
+
handler = createStandaloneHandler(next);
|
|
126
|
+
await previous.destroy();
|
|
127
|
+
logger.info("Config reloaded.");
|
|
128
|
+
} catch (error) {
|
|
129
|
+
logger.error(
|
|
130
|
+
`Reload failed, still serving the previous config:
|
|
131
|
+
${error.message}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
watcher = watch(cwd, { recursive: true }, (_event, file) => {
|
|
137
|
+
if (!file || !WATCHED.test(file) || IGNORED.test(file)) return;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
timer = setTimeout(reload, 150);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
await new Promise((resolveListen, reject) => {
|
|
143
|
+
server.once("error", reject);
|
|
144
|
+
server.listen(options.port, options.host, () => resolveListen());
|
|
145
|
+
});
|
|
146
|
+
const address = server.address();
|
|
147
|
+
const host = !options.host || options.host === "0.0.0.0" || options.host === "::" ? "localhost" : options.host;
|
|
148
|
+
const url = `http://${host.includes(":") ? `[${host}]` : host}:${address.port}`;
|
|
149
|
+
return {
|
|
150
|
+
server,
|
|
151
|
+
url,
|
|
152
|
+
async close() {
|
|
153
|
+
watcher?.close();
|
|
154
|
+
const closed = new Promise((done) => server.close(() => done()));
|
|
155
|
+
server.closeAllConnections();
|
|
156
|
+
await closed;
|
|
157
|
+
await cms.destroy();
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/index.ts
|
|
163
|
+
async function ask(question, options = {}) {
|
|
164
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
165
|
+
if (options.hidden) {
|
|
166
|
+
const output = rl;
|
|
167
|
+
let asked = false;
|
|
168
|
+
output._writeToOutput = (text) => {
|
|
169
|
+
if (!asked) {
|
|
170
|
+
process.stdout.write(text);
|
|
171
|
+
asked = true;
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
return (await rl.question(question)).trim();
|
|
177
|
+
} finally {
|
|
178
|
+
if (options.hidden) process.stdout.write("\n");
|
|
179
|
+
rl.close();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
var defaultIO = {
|
|
183
|
+
out: (line) => console.log(line),
|
|
184
|
+
err: (line) => console.error(line),
|
|
185
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
186
|
+
prompt: ask
|
|
187
|
+
};
|
|
188
|
+
var HELP = `Usage: easy-cms <command> [options]
|
|
189
|
+
|
|
190
|
+
Commands:
|
|
191
|
+
migrate Apply pending migrations
|
|
192
|
+
migrate:create <name> Create a migration from config changes
|
|
193
|
+
migrate:status List migrations and whether they are applied
|
|
194
|
+
generate:types Write TypeScript types for your collections and globals
|
|
195
|
+
create-admin Create an admin user
|
|
196
|
+
serve Run the CMS as its own server (admin + REST API)
|
|
197
|
+
|
|
198
|
+
Options:
|
|
199
|
+
--config <file> Config file (default: easy-cms.config.ts)
|
|
200
|
+
--cwd <dir> Project root (default: current directory); its .env is loaded
|
|
201
|
+
-h, --help Show help
|
|
202
|
+
`;
|
|
203
|
+
var COMMAND_HELP = {
|
|
204
|
+
migrate: `Usage: easy-cms migrate [options]
|
|
205
|
+
|
|
206
|
+
Applies every migration in easy-cms/migrations that the database has not run yet.
|
|
207
|
+
Each migration runs in its own transaction; a failure rolls it back and stops.
|
|
208
|
+
`,
|
|
209
|
+
"migrate:create": `Usage: easy-cms migrate:create <name> [options]
|
|
210
|
+
|
|
211
|
+
Compares the config with the latest migration and writes a new migration
|
|
212
|
+
(easy-cms/migrations/<timestamp>_<name>.sql) if anything changed.
|
|
213
|
+
In a terminal you are asked whether changed fields were renamed.
|
|
214
|
+
`,
|
|
215
|
+
"migrate:status": `Usage: easy-cms migrate:status [options]
|
|
216
|
+
|
|
217
|
+
Lists migration files and whether each has been applied.
|
|
218
|
+
`,
|
|
219
|
+
"generate:types": `Usage: easy-cms generate:types [--out <file>] [options]
|
|
220
|
+
|
|
221
|
+
Writes interfaces for every collection and global (default: easy-cms-types.ts).
|
|
222
|
+
The file has no imports, so a frontend in another repository can copy it.
|
|
223
|
+
`,
|
|
224
|
+
"create-admin": `Usage: easy-cms create-admin [--email <email>] [--name <name>] [--role <role>] [options]
|
|
225
|
+
|
|
226
|
+
Creates a user (role "admin" unless --role is given). The password is asked for in the
|
|
227
|
+
terminal, or read from EASY_CMS_ADMIN_PASSWORD when there is no terminal.
|
|
228
|
+
`,
|
|
229
|
+
serve: `Usage: easy-cms serve [--port <n>] [--host <host>] [--watch] [--trust-proxy] [options]
|
|
230
|
+
|
|
231
|
+
Runs Easy CMS without Nuxt or Next.js: the admin at /admin, the REST API at /api/cms and
|
|
232
|
+
/healthz for load balancers. Frontends on other origins need \`cors\` in the config.
|
|
233
|
+
|
|
234
|
+
--port <n> Port (default: PORT, then 4000)
|
|
235
|
+
--host <host> Interface to listen on (default: HOST, then all interfaces)
|
|
236
|
+
--watch Reload when the config or files it imports change (development)
|
|
237
|
+
--trust-proxy Trust X-Forwarded-For / X-Forwarded-Proto from your reverse proxy
|
|
238
|
+
|
|
239
|
+
In production (NODE_ENV=production) pending migrations stop the server from starting.
|
|
240
|
+
`
|
|
241
|
+
};
|
|
242
|
+
async function run(argv, io = defaultIO) {
|
|
243
|
+
let parsed;
|
|
244
|
+
try {
|
|
245
|
+
parsed = parse(argv);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
io.err(error.message);
|
|
248
|
+
io.err(HELP);
|
|
249
|
+
return 1;
|
|
250
|
+
}
|
|
251
|
+
const { values, positionals } = parsed;
|
|
252
|
+
const [command, ...rest] = positionals;
|
|
253
|
+
if (!command) {
|
|
254
|
+
;
|
|
255
|
+
(values.help ? io.out : io.err)(HELP);
|
|
256
|
+
return values.help ? 0 : 1;
|
|
257
|
+
}
|
|
258
|
+
if (!(command in COMMAND_HELP)) {
|
|
259
|
+
io.err(`Unknown command "${command}".
|
|
260
|
+
`);
|
|
261
|
+
io.err(HELP);
|
|
262
|
+
return 1;
|
|
263
|
+
}
|
|
264
|
+
if (values.help) {
|
|
265
|
+
io.out(COMMAND_HELP[command]);
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
const cwd = values.cwd ?? process.cwd();
|
|
269
|
+
loadDotEnv(cwd);
|
|
270
|
+
const logger = { info: io.out, warn: (m) => io.err(`warning: ${m}`), error: io.err };
|
|
271
|
+
try {
|
|
272
|
+
const load = () => loadConfig({ cwd, ...values.config ? { configFile: values.config } : {} });
|
|
273
|
+
if (command === "serve") return await serve(values, cwd, logger, load, io);
|
|
274
|
+
const config = await load();
|
|
275
|
+
if (command === "generate:types") {
|
|
276
|
+
const out = values.out ?? "easy-cms-types.ts";
|
|
277
|
+
const file = isAbsolute(out) ? out : resolve(cwd, out);
|
|
278
|
+
await writeFile(file, generateTypes(config));
|
|
279
|
+
io.out(`Wrote ${file}`);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
282
|
+
const schema = command === "create-admin" && process.env.NODE_ENV !== "production" ? "push" : "skip";
|
|
283
|
+
const cms = await createEasyCMS2(config, { cwd, schema, logger, interactive: io.interactive });
|
|
284
|
+
try {
|
|
285
|
+
switch (command) {
|
|
286
|
+
case "migrate": {
|
|
287
|
+
const applied = await cms.db.migrate();
|
|
288
|
+
io.out(
|
|
289
|
+
applied.length === 0 ? "No pending migrations." : `Applied ${applied.length} migration(s).`
|
|
290
|
+
);
|
|
291
|
+
return 0;
|
|
292
|
+
}
|
|
293
|
+
case "migrate:create": {
|
|
294
|
+
const name = rest.join(" ").trim();
|
|
295
|
+
if (!name) {
|
|
296
|
+
io.err("Missing migration name.\n");
|
|
297
|
+
io.err(COMMAND_HELP["migrate:create"]);
|
|
298
|
+
return 1;
|
|
299
|
+
}
|
|
300
|
+
const created = await cms.db.createMigration({ name });
|
|
301
|
+
if (!created) {
|
|
302
|
+
io.out("No changes; nothing to migrate.");
|
|
303
|
+
} else {
|
|
304
|
+
io.out(`Created ${created.file} (${created.statements.length} statements).`);
|
|
305
|
+
io.out("Review it, commit it, then run `easy-cms migrate` where you deploy.");
|
|
306
|
+
}
|
|
307
|
+
return 0;
|
|
308
|
+
}
|
|
309
|
+
case "create-admin": {
|
|
310
|
+
const email = values.email ?? (io.interactive && io.prompt ? await io.prompt("Email: ") : "");
|
|
311
|
+
if (!email) {
|
|
312
|
+
io.err("Missing --email.\n");
|
|
313
|
+
io.err(COMMAND_HELP["create-admin"]);
|
|
314
|
+
return 1;
|
|
315
|
+
}
|
|
316
|
+
const password = process.env.EASY_CMS_ADMIN_PASSWORD ?? (io.interactive && io.prompt ? await io.prompt("Password (8+ characters): ", { hidden: true }) : "");
|
|
317
|
+
if (!password) {
|
|
318
|
+
io.err("Missing password: run in a terminal or set EASY_CMS_ADMIN_PASSWORD.");
|
|
319
|
+
return 1;
|
|
320
|
+
}
|
|
321
|
+
try {
|
|
322
|
+
const user = await cms.create("users", {
|
|
323
|
+
email,
|
|
324
|
+
password,
|
|
325
|
+
role: values.role ?? "admin",
|
|
326
|
+
...values.name ? { name: values.name } : {}
|
|
327
|
+
});
|
|
328
|
+
io.out(`Created ${user.role} ${user.email}. Log in at ${cms.config.admin.path}`);
|
|
329
|
+
return 0;
|
|
330
|
+
} catch (error) {
|
|
331
|
+
if (error instanceof ValidationError) {
|
|
332
|
+
for (const e of error.errors) io.err(`${e.field}: ${e.message}`);
|
|
333
|
+
return 1;
|
|
334
|
+
}
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
case "migrate:status": {
|
|
339
|
+
const list = await cms.db.migrationStatus();
|
|
340
|
+
if (list.length === 0)
|
|
341
|
+
io.out("No migrations yet. Create one with `easy-cms migrate:create init`.");
|
|
342
|
+
for (const m of list) io.out(`${m.applied ? "\u2713 applied" : "\u2022 pending"} ${m.name}`);
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return 1;
|
|
347
|
+
} finally {
|
|
348
|
+
await cms.destroy();
|
|
349
|
+
}
|
|
350
|
+
} catch (error) {
|
|
351
|
+
const known = error instanceof ConfigError || error instanceof EasyCMSError;
|
|
352
|
+
if (error instanceof Error)
|
|
353
|
+
io.err(!known && process.env.DEBUG ? error.stack ?? error.message : error.message);
|
|
354
|
+
else io.err(String(error));
|
|
355
|
+
return 1;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
function parse(argv) {
|
|
359
|
+
return parseArgs({
|
|
360
|
+
args: [...argv],
|
|
361
|
+
allowPositionals: true,
|
|
362
|
+
options: {
|
|
363
|
+
config: { type: "string" },
|
|
364
|
+
cwd: { type: "string" },
|
|
365
|
+
out: { type: "string" },
|
|
366
|
+
email: { type: "string" },
|
|
367
|
+
name: { type: "string" },
|
|
368
|
+
role: { type: "string" },
|
|
369
|
+
port: { type: "string" },
|
|
370
|
+
host: { type: "string" },
|
|
371
|
+
watch: { type: "boolean" },
|
|
372
|
+
"trust-proxy": { type: "boolean" },
|
|
373
|
+
help: { type: "boolean", short: "h" }
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async function serve(values, cwd, logger, load, io) {
|
|
378
|
+
const port = Number(values.port ?? process.env.PORT ?? 4e3);
|
|
379
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
380
|
+
io.err(`Invalid port "${values.port ?? process.env.PORT}".`);
|
|
381
|
+
return 1;
|
|
382
|
+
}
|
|
383
|
+
const host = values.host ?? process.env.HOST;
|
|
384
|
+
const server = await startServer({
|
|
385
|
+
port,
|
|
386
|
+
...host ? { host } : {},
|
|
387
|
+
cwd,
|
|
388
|
+
logger,
|
|
389
|
+
loadConfig: load,
|
|
390
|
+
watch: values.watch ?? false,
|
|
391
|
+
trustProxy: values["trust-proxy"] ?? false
|
|
392
|
+
});
|
|
393
|
+
const config = await load();
|
|
394
|
+
io.out(`Easy CMS running at ${server.url}`);
|
|
395
|
+
io.out(` admin ${server.url}/${config.admin.path.replace(/^\/+|\/+$/g, "")}`);
|
|
396
|
+
io.out(` API ${server.url}${config.routes.api}`);
|
|
397
|
+
if (values.watch) io.out(" watching for changes");
|
|
398
|
+
await new Promise((resolveStop) => {
|
|
399
|
+
const stop = (signal) => {
|
|
400
|
+
io.out(`
|
|
401
|
+
${signal} received, shutting down\u2026`);
|
|
402
|
+
resolveStop();
|
|
403
|
+
};
|
|
404
|
+
process.once("SIGINT", () => stop("SIGINT"));
|
|
405
|
+
process.once("SIGTERM", () => stop("SIGTERM"));
|
|
406
|
+
});
|
|
407
|
+
await server.close();
|
|
408
|
+
return 0;
|
|
409
|
+
}
|
|
410
|
+
function loadDotEnv(cwd) {
|
|
411
|
+
const file = join(cwd, ".env");
|
|
412
|
+
if (existsSync(file)) process.loadEnvFile(file);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export {
|
|
416
|
+
createStandaloneHandler,
|
|
417
|
+
startServer,
|
|
418
|
+
run
|
|
419
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
+
import { Server } from 'node:http';
|
|
2
|
+
import { Logger, ResolvedConfig, Config, EasyCMS } from '@easy-cms/core';
|
|
3
|
+
|
|
4
|
+
interface StandaloneOptions {
|
|
5
|
+
/** Use `X-Forwarded-For` / `X-Forwarded-Proto` from a reverse proxy you control. */
|
|
6
|
+
readonly trustProxy?: boolean;
|
|
7
|
+
}
|
|
8
|
+
type Handler = (request: Request, clientIp?: string) => Promise<Response>;
|
|
9
|
+
/**
|
|
10
|
+
* One Web-standard handler for the whole standalone server: the REST API at `routes.api`, the
|
|
11
|
+
* admin at `admin.path`, and `/healthz` for load balancers. `/` redirects to the admin.
|
|
12
|
+
*/
|
|
13
|
+
declare function createStandaloneHandler<C extends Config>(cms: EasyCMS<C>): Handler;
|
|
14
|
+
interface StartOptions extends StandaloneOptions {
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly host?: string;
|
|
17
|
+
readonly cwd: string;
|
|
18
|
+
readonly logger: Logger;
|
|
19
|
+
/** Loads (or reloads) the resolved config. */
|
|
20
|
+
readonly loadConfig: () => Promise<ResolvedConfig>;
|
|
21
|
+
/** Reload when files in `cwd` change (development). */
|
|
22
|
+
readonly watch?: boolean;
|
|
23
|
+
}
|
|
24
|
+
interface RunningServer {
|
|
25
|
+
readonly server: Server;
|
|
26
|
+
readonly url: string;
|
|
27
|
+
/** Stops accepting connections, then closes the database. */
|
|
28
|
+
close(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
/** Starts the standalone HTTP server. */
|
|
31
|
+
declare function startServer(options: StartOptions): Promise<RunningServer>;
|
|
32
|
+
|
|
1
33
|
interface IO {
|
|
2
34
|
readonly out: (line: string) => void;
|
|
3
35
|
readonly err: (line: string) => void;
|
|
@@ -10,4 +42,4 @@ interface IO {
|
|
|
10
42
|
/** Runs the CLI and returns the exit code. */
|
|
11
43
|
declare function run(argv: readonly string[], io?: IO): Promise<number>;
|
|
12
44
|
|
|
13
|
-
export { type IO, run };
|
|
45
|
+
export { type IO, type RunningServer, type StartOptions, createStandaloneHandler, run, startServer };
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easy-cms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Command line tool for Easy CMS",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
|
-
"easy-cms": "./
|
|
8
|
+
"easy-cms": "./bin/easy-cms.js"
|
|
9
9
|
},
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
@@ -14,16 +14,18 @@
|
|
|
14
14
|
}
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
|
+
"bin",
|
|
17
18
|
"dist"
|
|
18
19
|
],
|
|
19
20
|
"engines": {
|
|
20
21
|
"node": ">=22.12"
|
|
21
22
|
},
|
|
22
23
|
"dependencies": {
|
|
23
|
-
"@easy-cms/core": "^0.
|
|
24
|
+
"@easy-cms/core": "^0.2.0",
|
|
25
|
+
"@easy-cms/admin": "^0.2.0"
|
|
24
26
|
},
|
|
25
27
|
"devDependencies": {
|
|
26
|
-
"@easy-cms/db-sqlite": "^0.
|
|
28
|
+
"@easy-cms/db-sqlite": "^0.2.0"
|
|
27
29
|
},
|
|
28
30
|
"publishConfig": {
|
|
29
31
|
"access": "public"
|
package/dist/chunk-3JYUADKB.js
DELETED
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
// src/index.ts
|
|
2
|
-
import { existsSync } from "fs";
|
|
3
|
-
import { writeFile } from "fs/promises";
|
|
4
|
-
import { isAbsolute, join, resolve } from "path";
|
|
5
|
-
import { createInterface } from "readline/promises";
|
|
6
|
-
import { parseArgs } from "util";
|
|
7
|
-
import {
|
|
8
|
-
ConfigError,
|
|
9
|
-
createEasyCMS,
|
|
10
|
-
EasyCMSError,
|
|
11
|
-
generateTypes,
|
|
12
|
-
loadConfig,
|
|
13
|
-
ValidationError
|
|
14
|
-
} from "@easy-cms/core";
|
|
15
|
-
async function ask(question, options = {}) {
|
|
16
|
-
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
17
|
-
if (options.hidden) {
|
|
18
|
-
const output = rl;
|
|
19
|
-
let asked = false;
|
|
20
|
-
output._writeToOutput = (text) => {
|
|
21
|
-
if (!asked) {
|
|
22
|
-
process.stdout.write(text);
|
|
23
|
-
asked = true;
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
try {
|
|
28
|
-
return (await rl.question(question)).trim();
|
|
29
|
-
} finally {
|
|
30
|
-
if (options.hidden) process.stdout.write("\n");
|
|
31
|
-
rl.close();
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
var defaultIO = {
|
|
35
|
-
out: (line) => console.log(line),
|
|
36
|
-
err: (line) => console.error(line),
|
|
37
|
-
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
38
|
-
prompt: ask
|
|
39
|
-
};
|
|
40
|
-
var HELP = `Usage: easy-cms <command> [options]
|
|
41
|
-
|
|
42
|
-
Commands:
|
|
43
|
-
migrate Apply pending migrations
|
|
44
|
-
migrate:create <name> Create a migration from config changes
|
|
45
|
-
migrate:status List migrations and whether they are applied
|
|
46
|
-
generate:types Write TypeScript types for your collections and globals
|
|
47
|
-
create-admin Create an admin user
|
|
48
|
-
|
|
49
|
-
Options:
|
|
50
|
-
--config <file> Config file (default: easy-cms.config.ts)
|
|
51
|
-
--cwd <dir> Project root (default: current directory); its .env is loaded
|
|
52
|
-
-h, --help Show help
|
|
53
|
-
`;
|
|
54
|
-
var COMMAND_HELP = {
|
|
55
|
-
migrate: `Usage: easy-cms migrate [options]
|
|
56
|
-
|
|
57
|
-
Applies every migration in easy-cms/migrations that the database has not run yet.
|
|
58
|
-
Each migration runs in its own transaction; a failure rolls it back and stops.
|
|
59
|
-
`,
|
|
60
|
-
"migrate:create": `Usage: easy-cms migrate:create <name> [options]
|
|
61
|
-
|
|
62
|
-
Compares the config with the latest migration and writes a new migration
|
|
63
|
-
(easy-cms/migrations/<timestamp>_<name>.sql) if anything changed.
|
|
64
|
-
In a terminal you are asked whether changed fields were renamed.
|
|
65
|
-
`,
|
|
66
|
-
"migrate:status": `Usage: easy-cms migrate:status [options]
|
|
67
|
-
|
|
68
|
-
Lists migration files and whether each has been applied.
|
|
69
|
-
`,
|
|
70
|
-
"generate:types": `Usage: easy-cms generate:types [--out <file>] [options]
|
|
71
|
-
|
|
72
|
-
Writes interfaces for every collection and global (default: easy-cms-types.ts).
|
|
73
|
-
The file has no imports, so a frontend in another repository can copy it.
|
|
74
|
-
`,
|
|
75
|
-
"create-admin": `Usage: easy-cms create-admin [--email <email>] [--name <name>] [--role <role>] [options]
|
|
76
|
-
|
|
77
|
-
Creates a user (role "admin" unless --role is given). The password is asked for in the
|
|
78
|
-
terminal, or read from EASY_CMS_ADMIN_PASSWORD when there is no terminal.
|
|
79
|
-
`
|
|
80
|
-
};
|
|
81
|
-
async function run(argv, io = defaultIO) {
|
|
82
|
-
let parsed;
|
|
83
|
-
try {
|
|
84
|
-
parsed = parse(argv);
|
|
85
|
-
} catch (error) {
|
|
86
|
-
io.err(error.message);
|
|
87
|
-
io.err(HELP);
|
|
88
|
-
return 1;
|
|
89
|
-
}
|
|
90
|
-
const { values, positionals } = parsed;
|
|
91
|
-
const [command, ...rest] = positionals;
|
|
92
|
-
if (!command) {
|
|
93
|
-
;
|
|
94
|
-
(values.help ? io.out : io.err)(HELP);
|
|
95
|
-
return values.help ? 0 : 1;
|
|
96
|
-
}
|
|
97
|
-
if (!(command in COMMAND_HELP)) {
|
|
98
|
-
io.err(`Unknown command "${command}".
|
|
99
|
-
`);
|
|
100
|
-
io.err(HELP);
|
|
101
|
-
return 1;
|
|
102
|
-
}
|
|
103
|
-
if (values.help) {
|
|
104
|
-
io.out(COMMAND_HELP[command]);
|
|
105
|
-
return 0;
|
|
106
|
-
}
|
|
107
|
-
const cwd = values.cwd ?? process.cwd();
|
|
108
|
-
loadDotEnv(cwd);
|
|
109
|
-
const logger = { info: io.out, warn: (m) => io.err(`warning: ${m}`), error: io.err };
|
|
110
|
-
try {
|
|
111
|
-
const config = await loadConfig({
|
|
112
|
-
cwd,
|
|
113
|
-
...values.config ? { configFile: values.config } : {}
|
|
114
|
-
});
|
|
115
|
-
if (command === "generate:types") {
|
|
116
|
-
const out = values.out ?? "easy-cms-types.ts";
|
|
117
|
-
const file = isAbsolute(out) ? out : resolve(cwd, out);
|
|
118
|
-
await writeFile(file, generateTypes(config));
|
|
119
|
-
io.out(`Wrote ${file}`);
|
|
120
|
-
return 0;
|
|
121
|
-
}
|
|
122
|
-
const schema = command === "create-admin" && process.env.NODE_ENV !== "production" ? "push" : "skip";
|
|
123
|
-
const cms = await createEasyCMS(config, { cwd, schema, logger, interactive: io.interactive });
|
|
124
|
-
try {
|
|
125
|
-
switch (command) {
|
|
126
|
-
case "migrate": {
|
|
127
|
-
const applied = await cms.db.migrate();
|
|
128
|
-
io.out(
|
|
129
|
-
applied.length === 0 ? "No pending migrations." : `Applied ${applied.length} migration(s).`
|
|
130
|
-
);
|
|
131
|
-
return 0;
|
|
132
|
-
}
|
|
133
|
-
case "migrate:create": {
|
|
134
|
-
const name = rest.join(" ").trim();
|
|
135
|
-
if (!name) {
|
|
136
|
-
io.err("Missing migration name.\n");
|
|
137
|
-
io.err(COMMAND_HELP["migrate:create"]);
|
|
138
|
-
return 1;
|
|
139
|
-
}
|
|
140
|
-
const created = await cms.db.createMigration({ name });
|
|
141
|
-
if (!created) {
|
|
142
|
-
io.out("No changes; nothing to migrate.");
|
|
143
|
-
} else {
|
|
144
|
-
io.out(`Created ${created.file} (${created.statements.length} statements).`);
|
|
145
|
-
io.out("Review it, commit it, then run `easy-cms migrate` where you deploy.");
|
|
146
|
-
}
|
|
147
|
-
return 0;
|
|
148
|
-
}
|
|
149
|
-
case "create-admin": {
|
|
150
|
-
const email = values.email ?? (io.interactive && io.prompt ? await io.prompt("Email: ") : "");
|
|
151
|
-
if (!email) {
|
|
152
|
-
io.err("Missing --email.\n");
|
|
153
|
-
io.err(COMMAND_HELP["create-admin"]);
|
|
154
|
-
return 1;
|
|
155
|
-
}
|
|
156
|
-
const password = process.env.EASY_CMS_ADMIN_PASSWORD ?? (io.interactive && io.prompt ? await io.prompt("Password (8+ characters): ", { hidden: true }) : "");
|
|
157
|
-
if (!password) {
|
|
158
|
-
io.err("Missing password: run in a terminal or set EASY_CMS_ADMIN_PASSWORD.");
|
|
159
|
-
return 1;
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
const user = await cms.create("users", {
|
|
163
|
-
email,
|
|
164
|
-
password,
|
|
165
|
-
role: values.role ?? "admin",
|
|
166
|
-
...values.name ? { name: values.name } : {}
|
|
167
|
-
});
|
|
168
|
-
io.out(`Created ${user.role} ${user.email}. Log in at ${cms.config.admin.path}`);
|
|
169
|
-
return 0;
|
|
170
|
-
} catch (error) {
|
|
171
|
-
if (error instanceof ValidationError) {
|
|
172
|
-
for (const e of error.errors) io.err(`${e.field}: ${e.message}`);
|
|
173
|
-
return 1;
|
|
174
|
-
}
|
|
175
|
-
throw error;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
case "migrate:status": {
|
|
179
|
-
const list = await cms.db.migrationStatus();
|
|
180
|
-
if (list.length === 0)
|
|
181
|
-
io.out("No migrations yet. Create one with `easy-cms migrate:create init`.");
|
|
182
|
-
for (const m of list) io.out(`${m.applied ? "\u2713 applied" : "\u2022 pending"} ${m.name}`);
|
|
183
|
-
return 0;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
return 1;
|
|
187
|
-
} finally {
|
|
188
|
-
await cms.destroy();
|
|
189
|
-
}
|
|
190
|
-
} catch (error) {
|
|
191
|
-
const known = error instanceof ConfigError || error instanceof EasyCMSError;
|
|
192
|
-
if (error instanceof Error)
|
|
193
|
-
io.err(!known && process.env.DEBUG ? error.stack ?? error.message : error.message);
|
|
194
|
-
else io.err(String(error));
|
|
195
|
-
return 1;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
function parse(argv) {
|
|
199
|
-
return parseArgs({
|
|
200
|
-
args: [...argv],
|
|
201
|
-
allowPositionals: true,
|
|
202
|
-
options: {
|
|
203
|
-
config: { type: "string" },
|
|
204
|
-
cwd: { type: "string" },
|
|
205
|
-
out: { type: "string" },
|
|
206
|
-
email: { type: "string" },
|
|
207
|
-
name: { type: "string" },
|
|
208
|
-
role: { type: "string" },
|
|
209
|
-
help: { type: "boolean", short: "h" }
|
|
210
|
-
}
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
function loadDotEnv(cwd) {
|
|
214
|
-
const file = join(cwd, ".env");
|
|
215
|
-
if (existsSync(file)) process.loadEnvFile(file);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
export {
|
|
219
|
-
run
|
|
220
|
-
};
|