deneljs 0.0.0-stage → 1.0.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/drizzle/0000_lonely_reptil.sql +27 -0
  4. package/drizzle/0001_misty_wendigo.sql +74 -0
  5. package/drizzle/meta/0000_snapshot.json +179 -0
  6. package/drizzle/meta/0001_snapshot.json +492 -0
  7. package/drizzle/meta/_journal.json +20 -0
  8. package/package.json +55 -4
  9. package/src/admin/auth.ts +851 -0
  10. package/src/admin/layout.ts +419 -0
  11. package/src/admin/pages/categories.ts +223 -0
  12. package/src/admin/pages/dashboard.ts +192 -0
  13. package/src/admin/pages/media.ts +270 -0
  14. package/src/admin/pages/posts.ts +804 -0
  15. package/src/admin/pages/settings.ts +169 -0
  16. package/src/admin/pages/themes.ts +461 -0
  17. package/src/admin/pages/users.ts +501 -0
  18. package/src/admin/routes.ts +455 -0
  19. package/src/admin/tiptap-bundle.ts +48 -0
  20. package/src/admin/tiptap-entry.ts +226 -0
  21. package/src/ai/generator.ts +296 -0
  22. package/src/ai/index.ts +22 -0
  23. package/src/ai/schema.ts +13 -0
  24. package/src/ai/spec.ts +193 -0
  25. package/src/cli.ts +151 -0
  26. package/src/db/index.ts +278 -0
  27. package/src/db/schema.ts +115 -0
  28. package/src/engine/index.ts +52 -0
  29. package/src/engine/renderer.ts +533 -0
  30. package/src/engine/sandbox.ts +108 -0
  31. package/src/engine/schema.ts +71 -0
  32. package/src/engine/validator.ts +404 -0
  33. package/src/routes/admin-api.ts +1035 -0
  34. package/src/routes/posts.ts +294 -0
  35. package/src/routes/uploads.ts +119 -0
  36. package/src/server.ts +672 -0
  37. package/src/utils/sanitize-html.ts +145 -0
  38. package/themes/.gitkeep +1 -0
  39. package/themes/default/assets/style.css +799 -0
  40. package/themes/default/layouts/base.liquid +31 -0
  41. package/themes/default/layouts/home.liquid +180 -0
  42. package/themes/default/layouts/page.liquid +21 -0
  43. package/themes/default/layouts/post.liquid +55 -0
  44. package/themes/default/partials/footer.liquid +33 -0
  45. package/themes/default/partials/navbar.liquid +49 -0
  46. package/themes/default/theme.json +59 -0
@@ -0,0 +1,1035 @@
1
+ import { and, asc, desc, eq, ne, sql } from "drizzle-orm";
2
+ import { Elysia, t } from "elysia";
3
+ import { mkdirSync, unlinkSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { resolveCurrentUser, type CurrentUser } from "../admin/auth";
6
+ import { clearSiteSettingsCache, db, getSiteSettings, schema } from "../db";
7
+ import { clearAllThemeCaches } from "../engine";
8
+ import { sanitizeRichHtml } from "../utils/sanitize-html";
9
+ import {
10
+ ALLOWED_MEDIA_EXTENSIONS,
11
+ buildSafeUploadFilename,
12
+ getUploadsRoot,
13
+ MAX_MEDIA_UPLOAD_BYTES,
14
+ resolveSafeUploadPath,
15
+ } from "./uploads";
16
+
17
+ const SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
19
+
20
+ function slugify(value: string): string {
21
+ return value
22
+ .toLowerCase()
23
+ .trim()
24
+ .replace(/[^a-z0-9]+/g, "-")
25
+ .replace(/^-+|-+$/g, "");
26
+ }
27
+
28
+ function parsePositiveId(raw: string): number | null {
29
+ const num = Number(raw);
30
+ return Number.isInteger(num) && num > 0 ? num : null;
31
+ }
32
+
33
+ function requireAdmin(
34
+ user: CurrentUser | null,
35
+ set: { status?: number | string },
36
+ ): boolean {
37
+ if (!user) {
38
+ set.status = 401;
39
+ return false;
40
+ }
41
+ if (user.role !== "admin") {
42
+ set.status = 403;
43
+ return false;
44
+ }
45
+ return true;
46
+ }
47
+
48
+ function extractUploadedFiles(body: unknown): File[] {
49
+ if (!body || typeof body !== "object") {
50
+ return [];
51
+ }
52
+
53
+ const collected: File[] = [];
54
+ for (const val of Object.values(body as Record<string, unknown>)) {
55
+ if (val instanceof File) {
56
+ collected.push(val);
57
+ } else if (Array.isArray(val)) {
58
+ for (const item of val) {
59
+ if (item instanceof File) {
60
+ collected.push(item);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ return collected;
66
+ }
67
+
68
+ /**
69
+ * Authenticated Admin CRUD endpoints mounted at /api/admin.
70
+ */
71
+ export const adminApiRoutes = new Elysia({ prefix: "/api/admin" })
72
+ .derive(({ request }) => ({
73
+ currentUser: resolveCurrentUser(request),
74
+ }))
75
+ .onBeforeHandle(({ currentUser, set }) => {
76
+ set.headers["cache-control"] = "no-store, no-cache, must-revalidate";
77
+ if (!currentUser) {
78
+ set.status = 401;
79
+ return { success: false, errors: ["Authentication required."] };
80
+ }
81
+ })
82
+ // ---------------- POSTS ----------------
83
+ .get(
84
+ "/posts",
85
+ ({ query }) => {
86
+ const rows = db
87
+ .select({
88
+ id: schema.posts.id,
89
+ slug: schema.posts.slug,
90
+ title: schema.posts.title,
91
+ content: schema.posts.content,
92
+ excerpt: schema.posts.excerpt,
93
+ featured_image: schema.posts.featured_image,
94
+ category_id: schema.posts.category_id,
95
+ category_name: schema.categories.name,
96
+ category_slug: schema.categories.slug,
97
+ author_id: schema.posts.author_id,
98
+ author_name: schema.users.name,
99
+ meta_title: schema.posts.meta_title,
100
+ meta_description: schema.posts.meta_description,
101
+ status: schema.posts.status,
102
+ created_at: schema.posts.created_at,
103
+ updated_at: schema.posts.updated_at,
104
+ })
105
+ .from(schema.posts)
106
+ .leftJoin(schema.categories, eq(schema.posts.category_id, schema.categories.id))
107
+ .leftJoin(schema.users, eq(schema.posts.author_id, schema.users.id))
108
+ .orderBy(desc(schema.posts.updated_at), desc(schema.posts.id))
109
+ .all();
110
+
111
+ const search = query.q?.trim().toLowerCase() ?? "";
112
+ const statusFilter = query.status?.trim() ?? "all";
113
+ const categoryFilter = query.category_id ? Number(query.category_id) : null;
114
+
115
+ const filtered = rows.filter((row) => {
116
+ if (statusFilter !== "all" && row.status !== statusFilter) {
117
+ return false;
118
+ }
119
+ if (categoryFilter && Number.isInteger(categoryFilter) && row.category_id !== categoryFilter) {
120
+ return false;
121
+ }
122
+ if (search) {
123
+ const hay = `${row.title} ${row.slug} ${row.excerpt}`.toLowerCase();
124
+ if (!hay.includes(search)) {
125
+ return false;
126
+ }
127
+ }
128
+ return true;
129
+ });
130
+
131
+ return { posts: filtered };
132
+ },
133
+ {
134
+ query: t.Object({
135
+ q: t.Optional(t.String()),
136
+ status: t.Optional(t.String()),
137
+ category_id: t.Optional(t.String()),
138
+ }),
139
+ },
140
+ )
141
+ .get("/posts/:id", ({ params, set }) => {
142
+ const id = parsePositiveId(params.id);
143
+ if (!id) {
144
+ set.status = 400;
145
+ return { success: false, errors: ["Invalid post ID."] };
146
+ }
147
+
148
+ const post = db.select().from(schema.posts).where(eq(schema.posts.id, id)).get();
149
+ if (!post) {
150
+ set.status = 404;
151
+ return { success: false, errors: ["Post not found."] };
152
+ }
153
+
154
+ return { post };
155
+ })
156
+ .post(
157
+ "/posts",
158
+ ({ body, currentUser, set }) => {
159
+ const title = body.title.trim();
160
+ if (!title) {
161
+ set.status = 400;
162
+ return { success: false, errors: ["Post title is required."] };
163
+ }
164
+
165
+ const rawSlug = body.slug?.trim();
166
+ const slug = rawSlug ? rawSlug : slugify(title);
167
+ if (!slug || !SLUG_REGEX.test(slug)) {
168
+ set.status = 400;
169
+ return {
170
+ success: false,
171
+ errors: ["Post slug must be lowercase alphanumeric with hyphens only."],
172
+ };
173
+ }
174
+
175
+ const duplicate = db
176
+ .select({ id: schema.posts.id })
177
+ .from(schema.posts)
178
+ .where(eq(schema.posts.slug, slug))
179
+ .get();
180
+ if (duplicate) {
181
+ set.status = 409;
182
+ return { success: false, errors: [`A post with slug "${slug}" already exists.`] };
183
+ }
184
+
185
+ let categoryId: number | null = null;
186
+ if (typeof body.category_id === "number" && body.category_id > 0) {
187
+ const cat = db
188
+ .select({ id: schema.categories.id })
189
+ .from(schema.categories)
190
+ .where(eq(schema.categories.id, body.category_id))
191
+ .get();
192
+ if (!cat) {
193
+ set.status = 400;
194
+ return { success: false, errors: ["Selected category does not exist."] };
195
+ }
196
+ categoryId = cat.id;
197
+ }
198
+
199
+ const now = Math.floor(Date.now() / 1000);
200
+ const post = db
201
+ .insert(schema.posts)
202
+ .values({
203
+ title,
204
+ slug,
205
+ content: sanitizeRichHtml(body.content),
206
+ excerpt: body.excerpt?.trim() ?? "",
207
+ featured_image: body.featured_image?.trim() ?? "",
208
+ category_id: categoryId,
209
+ author_id: currentUser?.id ?? null,
210
+ meta_title: body.meta_title?.trim() ?? "",
211
+ meta_description: body.meta_description?.trim() ?? "",
212
+ status: body.status ?? "draft",
213
+ created_at: now,
214
+ updated_at: now,
215
+ })
216
+ .returning()
217
+ .get();
218
+
219
+ set.status = 201;
220
+ return { success: true, post };
221
+ },
222
+ {
223
+ body: t.Object({
224
+ title: t.String({ minLength: 1 }),
225
+ slug: t.Optional(t.String()),
226
+ content: t.String(),
227
+ excerpt: t.Optional(t.String()),
228
+ featured_image: t.Optional(t.String()),
229
+ category_id: t.Optional(t.Union([t.Number(), t.Null()])),
230
+ meta_title: t.Optional(t.String()),
231
+ meta_description: t.Optional(t.String()),
232
+ status: t.Optional(t.Union([t.Literal("draft"), t.Literal("published")])),
233
+ }),
234
+ },
235
+ )
236
+ .put(
237
+ "/posts/:id",
238
+ ({ params, body, set }) => {
239
+ const id = parsePositiveId(params.id);
240
+ if (!id) {
241
+ set.status = 400;
242
+ return { success: false, errors: ["Invalid post ID."] };
243
+ }
244
+
245
+ const existing = db.select().from(schema.posts).where(eq(schema.posts.id, id)).get();
246
+ if (!existing) {
247
+ set.status = 404;
248
+ return { success: false, errors: ["Post not found."] };
249
+ }
250
+
251
+ const title = body.title !== undefined ? body.title.trim() : existing.title;
252
+ if (!title) {
253
+ set.status = 400;
254
+ return { success: false, errors: ["Post title cannot be empty."] };
255
+ }
256
+
257
+ const slug = body.slug !== undefined ? body.slug.trim() : existing.slug;
258
+ if (!slug || !SLUG_REGEX.test(slug)) {
259
+ set.status = 400;
260
+ return {
261
+ success: false,
262
+ errors: ["Post slug must be lowercase alphanumeric with hyphens only."],
263
+ };
264
+ }
265
+
266
+ const slugConflict = db
267
+ .select({ id: schema.posts.id })
268
+ .from(schema.posts)
269
+ .where(and(eq(schema.posts.slug, slug), ne(schema.posts.id, id)))
270
+ .get();
271
+ if (slugConflict) {
272
+ set.status = 409;
273
+ return { success: false, errors: [`A post with slug "${slug}" already exists.`] };
274
+ }
275
+
276
+ let categoryId = existing.category_id;
277
+ if (body.category_id !== undefined) {
278
+ if (body.category_id === null || body.category_id === 0) {
279
+ categoryId = null;
280
+ } else {
281
+ const cat = db
282
+ .select({ id: schema.categories.id })
283
+ .from(schema.categories)
284
+ .where(eq(schema.categories.id, body.category_id))
285
+ .get();
286
+ if (!cat) {
287
+ set.status = 400;
288
+ return { success: false, errors: ["Selected category does not exist."] };
289
+ }
290
+ categoryId = cat.id;
291
+ }
292
+ }
293
+
294
+ const post = db
295
+ .update(schema.posts)
296
+ .set({
297
+ title,
298
+ slug,
299
+ content:
300
+ body.content !== undefined ? sanitizeRichHtml(body.content) : existing.content,
301
+ excerpt: body.excerpt !== undefined ? body.excerpt.trim() : existing.excerpt,
302
+ featured_image:
303
+ body.featured_image !== undefined
304
+ ? body.featured_image.trim()
305
+ : existing.featured_image,
306
+ category_id: categoryId,
307
+ meta_title:
308
+ body.meta_title !== undefined ? body.meta_title.trim() : existing.meta_title,
309
+ meta_description:
310
+ body.meta_description !== undefined
311
+ ? body.meta_description.trim()
312
+ : existing.meta_description,
313
+ status: body.status ?? existing.status,
314
+ updated_at: Math.floor(Date.now() / 1000),
315
+ })
316
+ .where(eq(schema.posts.id, id))
317
+ .returning()
318
+ .get();
319
+
320
+ return { success: true, post };
321
+ },
322
+ {
323
+ body: t.Object({
324
+ title: t.Optional(t.String()),
325
+ slug: t.Optional(t.String()),
326
+ content: t.Optional(t.String()),
327
+ excerpt: t.Optional(t.String()),
328
+ featured_image: t.Optional(t.String()),
329
+ category_id: t.Optional(t.Union([t.Number(), t.Null()])),
330
+ meta_title: t.Optional(t.String()),
331
+ meta_description: t.Optional(t.String()),
332
+ status: t.Optional(t.Union([t.Literal("draft"), t.Literal("published")])),
333
+ }),
334
+ },
335
+ )
336
+ .delete("/posts/:id", ({ params, set }) => {
337
+ const id = parsePositiveId(params.id);
338
+ if (!id) {
339
+ set.status = 400;
340
+ return { success: false, errors: ["Invalid post ID."] };
341
+ }
342
+
343
+ const deleted = db
344
+ .delete(schema.posts)
345
+ .where(eq(schema.posts.id, id))
346
+ .returning()
347
+ .get();
348
+ if (!deleted) {
349
+ set.status = 404;
350
+ return { success: false, errors: ["Post not found."] };
351
+ }
352
+
353
+ return { success: true, deletedId: deleted.id };
354
+ })
355
+ // ---------------- CATEGORIES ----------------
356
+ .get("/categories", () => {
357
+ const rows = db
358
+ .select({
359
+ id: schema.categories.id,
360
+ name: schema.categories.name,
361
+ slug: schema.categories.slug,
362
+ description: schema.categories.description,
363
+ created_at: schema.categories.created_at,
364
+ post_count: sql<number>`count(${schema.posts.id})`,
365
+ })
366
+ .from(schema.categories)
367
+ .leftJoin(schema.posts, eq(schema.posts.category_id, schema.categories.id))
368
+ .groupBy(schema.categories.id)
369
+ .orderBy(asc(schema.categories.name))
370
+ .all();
371
+
372
+ return { categories: rows };
373
+ })
374
+ .post(
375
+ "/categories",
376
+ ({ body, set }) => {
377
+ const name = body.name.trim();
378
+ if (!name) {
379
+ set.status = 400;
380
+ return { success: false, errors: ["Category name is required."] };
381
+ }
382
+
383
+ const rawSlug = body.slug?.trim();
384
+ const slug = rawSlug ? rawSlug : slugify(name);
385
+ if (!slug || !SLUG_REGEX.test(slug)) {
386
+ set.status = 400;
387
+ return {
388
+ success: false,
389
+ errors: ["Category slug must be lowercase alphanumeric with hyphens only."],
390
+ };
391
+ }
392
+
393
+ const duplicate = db
394
+ .select({ id: schema.categories.id })
395
+ .from(schema.categories)
396
+ .where(eq(schema.categories.slug, slug))
397
+ .get();
398
+ if (duplicate) {
399
+ set.status = 409;
400
+ return { success: false, errors: [`Category slug "${slug}" already exists.`] };
401
+ }
402
+
403
+ const category = db
404
+ .insert(schema.categories)
405
+ .values({
406
+ name,
407
+ slug,
408
+ description: body.description?.trim() ?? "",
409
+ })
410
+ .returning()
411
+ .get();
412
+
413
+ set.status = 201;
414
+ return { success: true, category };
415
+ },
416
+ {
417
+ body: t.Object({
418
+ name: t.String({ minLength: 1 }),
419
+ slug: t.Optional(t.String()),
420
+ description: t.Optional(t.String()),
421
+ }),
422
+ },
423
+ )
424
+ .put(
425
+ "/categories/:id",
426
+ ({ params, body, set }) => {
427
+ const id = parsePositiveId(params.id);
428
+ if (!id) {
429
+ set.status = 400;
430
+ return { success: false, errors: ["Invalid category ID."] };
431
+ }
432
+
433
+ const existing = db
434
+ .select()
435
+ .from(schema.categories)
436
+ .where(eq(schema.categories.id, id))
437
+ .get();
438
+ if (!existing) {
439
+ set.status = 404;
440
+ return { success: false, errors: ["Category not found."] };
441
+ }
442
+
443
+ const name = body.name !== undefined ? body.name.trim() : existing.name;
444
+ if (!name) {
445
+ set.status = 400;
446
+ return { success: false, errors: ["Category name cannot be empty."] };
447
+ }
448
+
449
+ const slug = body.slug !== undefined ? body.slug.trim() : existing.slug;
450
+ if (!slug || !SLUG_REGEX.test(slug)) {
451
+ set.status = 400;
452
+ return {
453
+ success: false,
454
+ errors: ["Category slug must be lowercase alphanumeric with hyphens only."],
455
+ };
456
+ }
457
+
458
+ const conflict = db
459
+ .select({ id: schema.categories.id })
460
+ .from(schema.categories)
461
+ .where(and(eq(schema.categories.slug, slug), ne(schema.categories.id, id)))
462
+ .get();
463
+ if (conflict) {
464
+ set.status = 409;
465
+ return { success: false, errors: [`Category slug "${slug}" already exists.`] };
466
+ }
467
+
468
+ const category = db
469
+ .update(schema.categories)
470
+ .set({
471
+ name,
472
+ slug,
473
+ description:
474
+ body.description !== undefined ? body.description.trim() : existing.description,
475
+ })
476
+ .where(eq(schema.categories.id, id))
477
+ .returning()
478
+ .get();
479
+
480
+ return { success: true, category };
481
+ },
482
+ {
483
+ body: t.Object({
484
+ name: t.Optional(t.String()),
485
+ slug: t.Optional(t.String()),
486
+ description: t.Optional(t.String()),
487
+ }),
488
+ },
489
+ )
490
+ .delete("/categories/:id", ({ params, set }) => {
491
+ const id = parsePositiveId(params.id);
492
+ if (!id) {
493
+ set.status = 400;
494
+ return { success: false, errors: ["Invalid category ID."] };
495
+ }
496
+
497
+ const deleted = db
498
+ .delete(schema.categories)
499
+ .where(eq(schema.categories.id, id))
500
+ .returning()
501
+ .get();
502
+ if (!deleted) {
503
+ set.status = 404;
504
+ return { success: false, errors: ["Category not found."] };
505
+ }
506
+
507
+ return { success: true, deletedId: deleted.id };
508
+ })
509
+ // ---------------- MEDIA ----------------
510
+ .get("/media", () => {
511
+ const files = db
512
+ .select()
513
+ .from(schema.media)
514
+ .orderBy(desc(schema.media.created_at), desc(schema.media.id))
515
+ .all();
516
+
517
+ return { files };
518
+ })
519
+ .post("/media/upload", async ({ body, currentUser, set }) => {
520
+ const uploadedFiles = extractUploadedFiles(body);
521
+ if (uploadedFiles.length === 0) {
522
+ set.status = 400;
523
+ return {
524
+ success: false,
525
+ errors: ["No files provided in multipart/form-data upload."],
526
+ };
527
+ }
528
+
529
+ const prepared: Array<{
530
+ file: File;
531
+ filename: string;
532
+ originalName: string;
533
+ }> = [];
534
+
535
+ for (const file of uploadedFiles) {
536
+ const sanitized = buildSafeUploadFilename(file.name || "upload");
537
+ if (!sanitized) {
538
+ set.status = 400;
539
+ return {
540
+ success: false,
541
+ errors: [
542
+ `Disallowed file type for "${file.name}". Allowed: ${Array.from(ALLOWED_MEDIA_EXTENSIONS).join(", ")}.`,
543
+ ],
544
+ };
545
+ }
546
+ if (file.size <= 0 || file.size > MAX_MEDIA_UPLOAD_BYTES) {
547
+ set.status = 400;
548
+ return {
549
+ success: false,
550
+ errors: [
551
+ `File "${file.name}" must be between 1 byte and ${MAX_MEDIA_UPLOAD_BYTES} bytes.`,
552
+ ],
553
+ };
554
+ }
555
+ prepared.push({
556
+ file,
557
+ filename: sanitized.filename,
558
+ originalName: sanitized.originalName,
559
+ });
560
+ }
561
+
562
+ const uploadsRoot = getUploadsRoot();
563
+ mkdirSync(uploadsRoot, { recursive: true });
564
+
565
+ const writtenPaths: string[] = [];
566
+ const inserted: Array<typeof schema.media.$inferSelect> = [];
567
+
568
+ try {
569
+ for (const item of prepared) {
570
+ const destPath = resolve(uploadsRoot, item.filename);
571
+ await Bun.write(destPath, item.file);
572
+ writtenPaths.push(destPath);
573
+
574
+ const row = db
575
+ .insert(schema.media)
576
+ .values({
577
+ filename: item.filename,
578
+ original_name: item.originalName,
579
+ mime_type: item.file.type || "application/octet-stream",
580
+ size_bytes: item.file.size,
581
+ url: `/uploads/${item.filename}`,
582
+ alt_text: "",
583
+ uploaded_by: currentUser?.id ?? null,
584
+ })
585
+ .returning()
586
+ .get();
587
+
588
+ inserted.push(row);
589
+ }
590
+ } catch (err) {
591
+ for (const p of writtenPaths) {
592
+ try {
593
+ unlinkSync(p);
594
+ } catch {
595
+ // ignore cleanup failures
596
+ }
597
+ }
598
+ throw err;
599
+ }
600
+
601
+ set.status = 201;
602
+ return { success: true, files: inserted };
603
+ })
604
+ .put(
605
+ "/media/:id",
606
+ ({ params, body, set }) => {
607
+ const id = parsePositiveId(params.id);
608
+ if (!id) {
609
+ set.status = 400;
610
+ return { success: false, errors: ["Invalid media ID."] };
611
+ }
612
+
613
+ const updated = db
614
+ .update(schema.media)
615
+ .set({ alt_text: body.alt_text.trim() })
616
+ .where(eq(schema.media.id, id))
617
+ .returning()
618
+ .get();
619
+
620
+ if (!updated) {
621
+ set.status = 404;
622
+ return { success: false, errors: ["Media item not found."] };
623
+ }
624
+
625
+ return { success: true, file: updated };
626
+ },
627
+ {
628
+ body: t.Object({
629
+ alt_text: t.String(),
630
+ }),
631
+ },
632
+ )
633
+ .delete("/media/:id", ({ params, set }) => {
634
+ const id = parsePositiveId(params.id);
635
+ if (!id) {
636
+ set.status = 400;
637
+ return { success: false, errors: ["Invalid media ID."] };
638
+ }
639
+
640
+ const deleted = db
641
+ .delete(schema.media)
642
+ .where(eq(schema.media.id, id))
643
+ .returning()
644
+ .get();
645
+ if (!deleted) {
646
+ set.status = 404;
647
+ return { success: false, errors: ["Media item not found."] };
648
+ }
649
+
650
+ const diskPath = resolveSafeUploadPath(deleted.filename);
651
+ if (diskPath) {
652
+ try {
653
+ unlinkSync(diskPath);
654
+ } catch {
655
+ // ignore missing file on disk
656
+ }
657
+ }
658
+
659
+ return { success: true, deletedId: deleted.id };
660
+ })
661
+ // ---------------- USERS (ADMIN ONLY) ----------------
662
+ .get("/users", ({ currentUser, set }) => {
663
+ if (!requireAdmin(currentUser, set)) {
664
+ return {
665
+ success: false,
666
+ errors: ["Forbidden: admin role required."],
667
+ };
668
+ }
669
+
670
+ const rows = db
671
+ .select({
672
+ id: schema.users.id,
673
+ name: schema.users.name,
674
+ email: schema.users.email,
675
+ role: schema.users.role,
676
+ avatar_url: schema.users.avatar_url,
677
+ status: schema.users.status,
678
+ created_at: schema.users.created_at,
679
+ })
680
+ .from(schema.users)
681
+ .orderBy(asc(schema.users.id))
682
+ .all();
683
+
684
+ return { users: rows };
685
+ })
686
+ .get("/users/:id", ({ params, currentUser, set }) => {
687
+ if (!requireAdmin(currentUser, set)) {
688
+ return { success: false, errors: ["Forbidden: admin role required."] };
689
+ }
690
+
691
+ const id = parsePositiveId(params.id);
692
+ if (!id) {
693
+ set.status = 400;
694
+ return { success: false, errors: ["Invalid user ID."] };
695
+ }
696
+
697
+ const user = db
698
+ .select({
699
+ id: schema.users.id,
700
+ name: schema.users.name,
701
+ email: schema.users.email,
702
+ role: schema.users.role,
703
+ avatar_url: schema.users.avatar_url,
704
+ status: schema.users.status,
705
+ created_at: schema.users.created_at,
706
+ })
707
+ .from(schema.users)
708
+ .where(eq(schema.users.id, id))
709
+ .get();
710
+
711
+ if (!user) {
712
+ set.status = 404;
713
+ return { success: false, errors: ["User not found."] };
714
+ }
715
+
716
+ const postsCount =
717
+ db
718
+ .select({ count: sql<number>`count(*)` })
719
+ .from(schema.posts)
720
+ .where(eq(schema.posts.author_id, id))
721
+ .get()?.count ?? 0;
722
+
723
+ const publishedCount =
724
+ db
725
+ .select({ count: sql<number>`count(*)` })
726
+ .from(schema.posts)
727
+ .where(and(eq(schema.posts.author_id, id), eq(schema.posts.status, "published")))
728
+ .get()?.count ?? 0;
729
+
730
+ const mediaCount =
731
+ db
732
+ .select({ count: sql<number>`count(*)` })
733
+ .from(schema.media)
734
+ .where(eq(schema.media.uploaded_by, id))
735
+ .get()?.count ?? 0;
736
+
737
+ const recentPosts = db
738
+ .select({
739
+ id: schema.posts.id,
740
+ title: schema.posts.title,
741
+ slug: schema.posts.slug,
742
+ status: schema.posts.status,
743
+ updated_at: schema.posts.updated_at,
744
+ })
745
+ .from(schema.posts)
746
+ .where(eq(schema.posts.author_id, id))
747
+ .orderBy(desc(schema.posts.updated_at), desc(schema.posts.id))
748
+ .limit(5)
749
+ .all();
750
+
751
+ return {
752
+ success: true,
753
+ user,
754
+ stats: {
755
+ postsCount,
756
+ publishedCount,
757
+ draftCount: Math.max(0, postsCount - publishedCount),
758
+ mediaCount,
759
+ },
760
+ recentPosts,
761
+ };
762
+ })
763
+ .post(
764
+ "/users",
765
+ async ({ body, currentUser, set }) => {
766
+ if (!requireAdmin(currentUser, set)) {
767
+ return { success: false, errors: ["Forbidden: admin role required."] };
768
+ }
769
+
770
+ const name = body.name.trim();
771
+ const email = body.email.trim().toLowerCase();
772
+ if (!name) {
773
+ set.status = 400;
774
+ return { success: false, errors: ["Name is required."] };
775
+ }
776
+ if (!EMAIL_REGEX.test(email)) {
777
+ set.status = 400;
778
+ return { success: false, errors: ["Valid email address is required."] };
779
+ }
780
+ if (body.password.length < 6) {
781
+ set.status = 400;
782
+ return { success: false, errors: ["Password must be at least 6 characters."] };
783
+ }
784
+
785
+ const duplicate = db
786
+ .select({ id: schema.users.id })
787
+ .from(schema.users)
788
+ .where(eq(schema.users.email, email))
789
+ .get();
790
+ if (duplicate) {
791
+ set.status = 409;
792
+ return { success: false, errors: [`A user with email "${email}" already exists.`] };
793
+ }
794
+
795
+ const passwordHash = await Bun.password.hash(body.password);
796
+ const user = db
797
+ .insert(schema.users)
798
+ .values({
799
+ name,
800
+ email,
801
+ password_hash: passwordHash,
802
+ role: body.role,
803
+ avatar_url: body.avatar_url?.trim() ?? "",
804
+ status: body.status ?? "active",
805
+ })
806
+ .returning({
807
+ id: schema.users.id,
808
+ name: schema.users.name,
809
+ email: schema.users.email,
810
+ role: schema.users.role,
811
+ avatar_url: schema.users.avatar_url,
812
+ status: schema.users.status,
813
+ created_at: schema.users.created_at,
814
+ })
815
+ .get();
816
+
817
+ set.status = 201;
818
+ return { success: true, user };
819
+ },
820
+ {
821
+ body: t.Object({
822
+ name: t.String({ minLength: 1 }),
823
+ email: t.String({ minLength: 3 }),
824
+ password: t.String({ minLength: 6 }),
825
+ role: t.Union([t.Literal("admin"), t.Literal("editor"), t.Literal("author")]),
826
+ status: t.Optional(t.Union([t.Literal("active"), t.Literal("suspended")])),
827
+ avatar_url: t.Optional(t.String()),
828
+ }),
829
+ },
830
+ )
831
+ .put(
832
+ "/users/:id",
833
+ async ({ params, body, currentUser, set }) => {
834
+ if (!requireAdmin(currentUser, set)) {
835
+ return { success: false, errors: ["Forbidden: admin role required."] };
836
+ }
837
+
838
+ const id = parsePositiveId(params.id);
839
+ if (!id) {
840
+ set.status = 400;
841
+ return { success: false, errors: ["Invalid user ID."] };
842
+ }
843
+
844
+ const existing = db.select().from(schema.users).where(eq(schema.users.id, id)).get();
845
+ if (!existing) {
846
+ set.status = 404;
847
+ return { success: false, errors: ["User not found."] };
848
+ }
849
+
850
+ if (currentUser && id === currentUser.id) {
851
+ if (body.status === "suspended") {
852
+ set.status = 400;
853
+ return { success: false, errors: ["You cannot suspend your own account."] };
854
+ }
855
+ if (body.role && body.role !== "admin") {
856
+ set.status = 400;
857
+ return { success: false, errors: ["You cannot demote your own admin role."] };
858
+ }
859
+ }
860
+
861
+ const name = body.name !== undefined ? body.name.trim() : existing.name;
862
+ if (!name) {
863
+ set.status = 400;
864
+ return { success: false, errors: ["Name cannot be empty."] };
865
+ }
866
+
867
+ const email = body.email !== undefined ? body.email.trim().toLowerCase() : existing.email;
868
+ if (!EMAIL_REGEX.test(email)) {
869
+ set.status = 400;
870
+ return { success: false, errors: ["Valid email address is required."] };
871
+ }
872
+
873
+ const conflict = db
874
+ .select({ id: schema.users.id })
875
+ .from(schema.users)
876
+ .where(and(eq(schema.users.email, email), ne(schema.users.id, id)))
877
+ .get();
878
+ if (conflict) {
879
+ set.status = 409;
880
+ return { success: false, errors: [`A user with email "${email}" already exists.`] };
881
+ }
882
+
883
+ let nextPasswordHash = existing.password_hash;
884
+ if (body.password !== undefined && body.password.length > 0) {
885
+ if (body.password.length < 6) {
886
+ set.status = 400;
887
+ return { success: false, errors: ["New password must be at least 6 characters."] };
888
+ }
889
+ nextPasswordHash = await Bun.password.hash(body.password);
890
+ }
891
+
892
+ const user = db
893
+ .update(schema.users)
894
+ .set({
895
+ name,
896
+ email,
897
+ password_hash: nextPasswordHash,
898
+ role: body.role ?? existing.role,
899
+ status: body.status ?? existing.status,
900
+ avatar_url: body.avatar_url !== undefined ? body.avatar_url.trim() : existing.avatar_url,
901
+ })
902
+ .where(eq(schema.users.id, id))
903
+ .returning({
904
+ id: schema.users.id,
905
+ name: schema.users.name,
906
+ email: schema.users.email,
907
+ role: schema.users.role,
908
+ avatar_url: schema.users.avatar_url,
909
+ status: schema.users.status,
910
+ created_at: schema.users.created_at,
911
+ })
912
+ .get();
913
+
914
+ return { success: true, user };
915
+ },
916
+ {
917
+ body: t.Object({
918
+ name: t.Optional(t.String()),
919
+ email: t.Optional(t.String()),
920
+ password: t.Optional(t.String()),
921
+ role: t.Optional(t.Union([t.Literal("admin"), t.Literal("editor"), t.Literal("author")])),
922
+ status: t.Optional(t.Union([t.Literal("active"), t.Literal("suspended")])),
923
+ avatar_url: t.Optional(t.String()),
924
+ }),
925
+ },
926
+ )
927
+ .delete("/users/:id", ({ params, currentUser, set }) => {
928
+ if (!requireAdmin(currentUser, set)) {
929
+ return { success: false, errors: ["Forbidden: admin role required."] };
930
+ }
931
+
932
+ const id = parsePositiveId(params.id);
933
+ if (!id) {
934
+ set.status = 400;
935
+ return { success: false, errors: ["Invalid user ID."] };
936
+ }
937
+
938
+ if (currentUser && id === currentUser.id) {
939
+ set.status = 400;
940
+ return { success: false, errors: ["You cannot delete your own account."] };
941
+ }
942
+
943
+ const deleted = db
944
+ .delete(schema.users)
945
+ .where(eq(schema.users.id, id))
946
+ .returning({ id: schema.users.id })
947
+ .get();
948
+ if (!deleted) {
949
+ set.status = 404;
950
+ return { success: false, errors: ["User not found."] };
951
+ }
952
+
953
+ return { success: true, deletedId: deleted.id };
954
+ })
955
+ // ---------------- SETTINGS (ADMIN ONLY) ----------------
956
+ .get("/settings", ({ currentUser, set }) => {
957
+ if (!requireAdmin(currentUser, set)) {
958
+ return { success: false, errors: ["Forbidden: admin role required."] };
959
+ }
960
+
961
+ return { settings: getSiteSettings() };
962
+ })
963
+ .post(
964
+ "/settings",
965
+ ({ body, currentUser, set }) => {
966
+ if (!requireAdmin(currentUser, set)) {
967
+ return { success: false, errors: ["Forbidden: admin role required."] };
968
+ }
969
+
970
+ const siteTitle = body.site_title.trim();
971
+ if (!siteTitle) {
972
+ set.status = 400;
973
+ return { success: false, errors: ["Site title cannot be empty."] };
974
+ }
975
+
976
+ const parsedPerPage = Number(body.posts_per_page);
977
+ if (!Number.isInteger(parsedPerPage) || parsedPerPage < 1 || parsedPerPage > 100) {
978
+ set.status = 400;
979
+ return {
980
+ success: false,
981
+ errors: ["Posts per page must be a whole number between 1 and 100."],
982
+ };
983
+ }
984
+
985
+ const aiEnabled =
986
+ typeof body.ai_enabled === "boolean"
987
+ ? body.ai_enabled
988
+ : body.ai_enabled !== "false";
989
+
990
+ const entries: Array<{ key: string; value: string }> = [
991
+ { key: "site_title", value: siteTitle },
992
+ { key: "site_tagline", value: body.site_tagline?.trim() ?? "" },
993
+ { key: "site_logo", value: body.site_logo?.trim() ?? "" },
994
+ { key: "favicon", value: body.favicon?.trim() ?? "" },
995
+ { key: "posts_per_page", value: String(parsedPerPage) },
996
+ { key: "seo_default_desc", value: body.seo_default_desc?.trim() ?? "" },
997
+ { key: "ai_provider", value: body.ai_provider?.trim() || "openai-compatible" },
998
+ { key: "ai_model", value: body.ai_model?.trim() || "gpt-4o-mini" },
999
+ { key: "ai_enabled", value: aiEnabled ? "true" : "false" },
1000
+ ];
1001
+
1002
+ db.transaction((tx) => {
1003
+ for (const entry of entries) {
1004
+ tx.insert(schema.settings)
1005
+ .values(entry)
1006
+ .onConflictDoUpdate({
1007
+ target: schema.settings.key,
1008
+ set: { value: entry.value },
1009
+ })
1010
+ .run();
1011
+ }
1012
+ });
1013
+
1014
+ clearSiteSettingsCache();
1015
+ clearAllThemeCaches();
1016
+
1017
+ return {
1018
+ success: true,
1019
+ settings: getSiteSettings(),
1020
+ };
1021
+ },
1022
+ {
1023
+ body: t.Object({
1024
+ site_title: t.String({ minLength: 1 }),
1025
+ site_tagline: t.Optional(t.String()),
1026
+ site_logo: t.Optional(t.String()),
1027
+ favicon: t.Optional(t.String()),
1028
+ posts_per_page: t.Union([t.Number(), t.String()]),
1029
+ seo_default_desc: t.Optional(t.String()),
1030
+ ai_provider: t.Optional(t.String()),
1031
+ ai_model: t.Optional(t.String()),
1032
+ ai_enabled: t.Optional(t.Union([t.Boolean(), t.String()])),
1033
+ }),
1034
+ },
1035
+ );