@sonicjs-cms/core 2.2.0 → 2.3.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 (105) hide show
  1. package/README.md +75 -1
  2. package/dist/app-Db0AfT5F.d.cts +100 -0
  3. package/dist/app-Db0AfT5F.d.ts +100 -0
  4. package/dist/{chunk-R57VFNP3.js → chunk-3ZLCMOCM.js} +441 -433
  5. package/dist/chunk-3ZLCMOCM.js.map +1 -0
  6. package/dist/{chunk-ZUK55KZB.js → chunk-4C433FET.js} +5 -3
  7. package/dist/chunk-4C433FET.js.map +1 -0
  8. package/dist/{chunk-OORGXYDA.js → chunk-5TRX2JHU.js} +5 -32
  9. package/dist/chunk-5TRX2JHU.js.map +1 -0
  10. package/dist/{chunk-K4Z3IHOK.js → chunk-7CXL5K7N.js} +5 -248
  11. package/dist/chunk-7CXL5K7N.js.map +1 -0
  12. package/dist/{chunk-WBX5YMTB.cjs → chunk-7KCDFDRI.cjs} +27 -15
  13. package/dist/chunk-7KCDFDRI.cjs.map +1 -0
  14. package/dist/chunk-CAMM3MJV.js +1550 -0
  15. package/dist/chunk-CAMM3MJV.js.map +1 -0
  16. package/dist/{chunk-HKEK7UNV.js → chunk-CPXAVWCU.js} +3 -3
  17. package/dist/{chunk-HKEK7UNV.js.map → chunk-CPXAVWCU.js.map} +1 -1
  18. package/dist/{chunk-F5ESJXI2.cjs → chunk-DTLB6UIH.cjs} +3 -3
  19. package/dist/{chunk-F5ESJXI2.cjs.map → chunk-DTLB6UIH.cjs.map} +1 -1
  20. package/dist/{chunk-AINTFRTC.cjs → chunk-ES3BRZQJ.cjs} +252 -2
  21. package/dist/chunk-ES3BRZQJ.cjs.map +1 -0
  22. package/dist/chunk-HBJU3I2Y.cjs +1552 -0
  23. package/dist/chunk-HBJU3I2Y.cjs.map +1 -0
  24. package/dist/{chunk-UEYMFNBN.cjs → chunk-KP4DVEX5.cjs} +7 -36
  25. package/dist/chunk-KP4DVEX5.cjs.map +1 -0
  26. package/dist/{chunk-2DIWLDCA.cjs → chunk-MPFSSBIY.cjs} +541 -533
  27. package/dist/chunk-MPFSSBIY.cjs.map +1 -0
  28. package/dist/{chunk-HV2I6API.cjs → chunk-NAYD76QF.cjs} +4 -251
  29. package/dist/chunk-NAYD76QF.cjs.map +1 -0
  30. package/dist/{chunk-L232U757.js → chunk-Q52ZQFMB.js} +249 -3
  31. package/dist/chunk-Q52ZQFMB.js.map +1 -0
  32. package/dist/{chunk-NMVOTNSL.js → chunk-RRKXFGIO.js} +28 -16
  33. package/dist/chunk-RRKXFGIO.js.map +1 -0
  34. package/dist/{chunk-YTMFJLJZ.cjs → chunk-TT266RYM.cjs} +5 -3
  35. package/dist/chunk-TT266RYM.cjs.map +1 -0
  36. package/dist/collection-config-FLlGtsh9.d.cts +107 -0
  37. package/dist/collection-config-FLlGtsh9.d.ts +107 -0
  38. package/dist/filter-bar.template-By4jeiw_.d.cts +140 -0
  39. package/dist/filter-bar.template-By4jeiw_.d.ts +140 -0
  40. package/dist/index.cjs +146 -165
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +44 -0
  43. package/dist/index.d.ts +43 -5
  44. package/dist/index.js +19 -14
  45. package/dist/index.js.map +1 -1
  46. package/dist/middleware.cjs +24 -33
  47. package/dist/middleware.d.cts +89 -0
  48. package/dist/middleware.d.ts +89 -2
  49. package/dist/middleware.js +3 -4
  50. package/dist/migrations-B2CDNN76.js +4 -0
  51. package/dist/{migrations-IHERIQVD.js.map → migrations-B2CDNN76.js.map} +1 -1
  52. package/dist/migrations-IBKKBIKR.cjs +13 -0
  53. package/dist/{migrations-POFD5KNG.cjs.map → migrations-IBKKBIKR.cjs.map} +1 -1
  54. package/dist/plugin-bootstrap-C0E3jdz-.d.cts +8339 -0
  55. package/dist/plugin-bootstrap-CDh0JHtW.d.ts +8339 -0
  56. package/dist/plugin-manifest-BCMx9CAq.d.cts +35 -0
  57. package/dist/plugin-manifest-BCMx9CAq.d.ts +35 -0
  58. package/dist/plugin-zvZpaiP5.d.cts +357 -0
  59. package/dist/plugin-zvZpaiP5.d.ts +357 -0
  60. package/dist/plugins.cjs +7 -7
  61. package/dist/plugins.d.cts +330 -0
  62. package/dist/plugins.d.ts +330 -2
  63. package/dist/plugins.js +1 -1
  64. package/dist/routes.cjs +27 -27
  65. package/dist/routes.d.cts +224 -0
  66. package/dist/routes.d.ts +224 -2
  67. package/dist/routes.js +7 -7
  68. package/dist/services.cjs +41 -41
  69. package/dist/services.d.cts +236 -0
  70. package/dist/services.d.ts +236 -2
  71. package/dist/services.js +4 -4
  72. package/dist/telemetry-BFBIjBxK.d.cts +36 -0
  73. package/dist/telemetry-BFBIjBxK.d.ts +36 -0
  74. package/dist/templates.d.cts +133 -0
  75. package/dist/templates.d.ts +133 -2
  76. package/dist/types.d.cts +7 -0
  77. package/dist/types.d.ts +7 -2
  78. package/dist/utils.cjs +27 -27
  79. package/dist/utils.d.cts +53 -0
  80. package/dist/utils.d.ts +53 -2
  81. package/dist/utils.js +2 -2
  82. package/dist/version-vktVAxhe.d.cts +195 -0
  83. package/dist/version-vktVAxhe.d.ts +195 -0
  84. package/migrations/001_initial_schema.sql +1 -1
  85. package/package.json +3 -1
  86. package/dist/chunk-2DIWLDCA.cjs.map +0 -1
  87. package/dist/chunk-AINTFRTC.cjs.map +0 -1
  88. package/dist/chunk-HV2I6API.cjs.map +0 -1
  89. package/dist/chunk-K4Z3IHOK.js.map +0 -1
  90. package/dist/chunk-L232U757.js.map +0 -1
  91. package/dist/chunk-NMVOTNSL.js.map +0 -1
  92. package/dist/chunk-OORGXYDA.js.map +0 -1
  93. package/dist/chunk-R57VFNP3.js.map +0 -1
  94. package/dist/chunk-T7IYBGGO.cjs +0 -746
  95. package/dist/chunk-T7IYBGGO.cjs.map +0 -1
  96. package/dist/chunk-UEYMFNBN.cjs.map +0 -1
  97. package/dist/chunk-WBX5YMTB.cjs.map +0 -1
  98. package/dist/chunk-YTMFJLJZ.cjs.map +0 -1
  99. package/dist/chunk-ZPMFT2JW.js +0 -744
  100. package/dist/chunk-ZPMFT2JW.js.map +0 -1
  101. package/dist/chunk-ZUK55KZB.js.map +0 -1
  102. package/dist/migrations-IHERIQVD.js +0 -4
  103. package/dist/migrations-POFD5KNG.cjs +0 -13
  104. package/migrations/013_code_examples_plugin.sql +0 -177
  105. /package/migrations/{021_add_otp_login.sql → 026_add_otp_login.sql} +0 -0
@@ -1,9 +1,9 @@
1
- import { getCacheService, CACHE_CONFIGS, getLogger, SettingsService } from './chunk-L232U757.js';
2
- import { requireAuth, isPluginActive, requireRole, AuthManager, logActivity } from './chunk-OORGXYDA.js';
3
- import { PluginService } from './chunk-K4Z3IHOK.js';
4
- import { MigrationService } from './chunk-ZPMFT2JW.js';
1
+ import { getCacheService, CACHE_CONFIGS, getLogger, SettingsService } from './chunk-Q52ZQFMB.js';
2
+ import { requireAuth, isPluginActive, requireRole, AuthManager, logActivity } from './chunk-5TRX2JHU.js';
3
+ import { PluginService } from './chunk-7CXL5K7N.js';
4
+ import { MigrationService } from './chunk-CAMM3MJV.js';
5
5
  import { init_admin_layout_catalyst_template, renderDesignPage, renderCheckboxPage, renderTestimonialsList, renderCodeExamplesList, renderAlert, renderTable, renderPagination, renderConfirmationDialog, getConfirmationDialogScript, renderAdminLayoutCatalyst, renderAdminLayout, adminLayoutV2, renderForm } from './chunk-5RKQB2JG.js';
6
- import { QueryFilterBuilder, sanitizeInput, getCoreVersion, escapeHtml } from './chunk-ZUK55KZB.js';
6
+ import { QueryFilterBuilder, sanitizeInput, getCoreVersion, escapeHtml } from './chunk-4C433FET.js';
7
7
  import { metricsTracker } from './chunk-FICTAGD4.js';
8
8
  import { Hono } from 'hono';
9
9
  import { cors } from 'hono/cors';
@@ -17,8 +17,8 @@ var apiContentCrudRoutes = new Hono();
17
17
  apiContentCrudRoutes.get("/:id", async (c) => {
18
18
  try {
19
19
  const id = c.req.param("id");
20
- const db2 = c.env.DB;
21
- const stmt = db2.prepare("SELECT * FROM content WHERE id = ?");
20
+ const db = c.env.DB;
21
+ const stmt = db.prepare("SELECT * FROM content WHERE id = ?");
22
22
  const content = await stmt.bind(id).first();
23
23
  if (!content) {
24
24
  return c.json({ error: "Content not found" }, 404);
@@ -44,7 +44,7 @@ apiContentCrudRoutes.get("/:id", async (c) => {
44
44
  });
45
45
  apiContentCrudRoutes.post("/", requireAuth(), async (c) => {
46
46
  try {
47
- const db2 = c.env.DB;
47
+ const db = c.env.DB;
48
48
  const user = c.get("user");
49
49
  const body = await c.req.json();
50
50
  const { collectionId, title, slug, status, data } = body;
@@ -56,7 +56,7 @@ apiContentCrudRoutes.post("/", requireAuth(), async (c) => {
56
56
  }
57
57
  let finalSlug = slug || title;
58
58
  finalSlug = finalSlug.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
59
- const duplicateCheck = db2.prepare(
59
+ const duplicateCheck = db.prepare(
60
60
  "SELECT id FROM content WHERE collection_id = ? AND slug = ?"
61
61
  );
62
62
  const existing = await duplicateCheck.bind(collectionId, finalSlug).first();
@@ -65,7 +65,7 @@ apiContentCrudRoutes.post("/", requireAuth(), async (c) => {
65
65
  }
66
66
  const contentId = crypto.randomUUID();
67
67
  const now = Date.now();
68
- const insertStmt = db2.prepare(`
68
+ const insertStmt = db.prepare(`
69
69
  INSERT INTO content (
70
70
  id, collection_id, slug, title, data, status,
71
71
  author_id, created_at, updated_at
@@ -86,7 +86,7 @@ apiContentCrudRoutes.post("/", requireAuth(), async (c) => {
86
86
  const cache = getCacheService(CACHE_CONFIGS.api);
87
87
  await cache.invalidate(`content:list:${collectionId}:*`);
88
88
  await cache.invalidate("content-filtered:*");
89
- const getStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
89
+ const getStmt = db.prepare("SELECT * FROM content WHERE id = ?");
90
90
  const createdContent = await getStmt.bind(contentId).first();
91
91
  return c.json({
92
92
  data: {
@@ -111,9 +111,9 @@ apiContentCrudRoutes.post("/", requireAuth(), async (c) => {
111
111
  apiContentCrudRoutes.put("/:id", requireAuth(), async (c) => {
112
112
  try {
113
113
  const id = c.req.param("id");
114
- const db2 = c.env.DB;
114
+ const db = c.env.DB;
115
115
  const body = await c.req.json();
116
- const existingStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
116
+ const existingStmt = db.prepare("SELECT * FROM content WHERE id = ?");
117
117
  const existing = await existingStmt.bind(id).first();
118
118
  if (!existing) {
119
119
  return c.json({ error: "Content not found" }, 404);
@@ -141,7 +141,7 @@ apiContentCrudRoutes.put("/:id", requireAuth(), async (c) => {
141
141
  updates.push("updated_at = ?");
142
142
  params.push(now);
143
143
  params.push(id);
144
- const updateStmt = db2.prepare(`
144
+ const updateStmt = db.prepare(`
145
145
  UPDATE content SET ${updates.join(", ")}
146
146
  WHERE id = ?
147
147
  `);
@@ -150,7 +150,7 @@ apiContentCrudRoutes.put("/:id", requireAuth(), async (c) => {
150
150
  await cache.delete(cache.generateKey("content", id));
151
151
  await cache.invalidate(`content:list:${existing.collection_id}:*`);
152
152
  await cache.invalidate("content-filtered:*");
153
- const getStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
153
+ const getStmt = db.prepare("SELECT * FROM content WHERE id = ?");
154
154
  const updatedContent = await getStmt.bind(id).first();
155
155
  return c.json({
156
156
  data: {
@@ -175,13 +175,13 @@ apiContentCrudRoutes.put("/:id", requireAuth(), async (c) => {
175
175
  apiContentCrudRoutes.delete("/:id", requireAuth(), async (c) => {
176
176
  try {
177
177
  const id = c.req.param("id");
178
- const db2 = c.env.DB;
179
- const existingStmt = db2.prepare("SELECT collection_id FROM content WHERE id = ?");
178
+ const db = c.env.DB;
179
+ const existingStmt = db.prepare("SELECT collection_id FROM content WHERE id = ?");
180
180
  const existing = await existingStmt.bind(id).first();
181
181
  if (!existing) {
182
182
  return c.json({ error: "Content not found" }, 404);
183
183
  }
184
- const deleteStmt = db2.prepare("DELETE FROM content WHERE id = ?");
184
+ const deleteStmt = db.prepare("DELETE FROM content WHERE id = ?");
185
185
  await deleteStmt.bind(id).run();
186
186
  const cache = getCacheService(CACHE_CONFIGS.api);
187
187
  await cache.delete(cache.generateKey("content", id));
@@ -254,7 +254,7 @@ apiRoutes.get("/health", (c) => {
254
254
  apiRoutes.get("/collections", async (c) => {
255
255
  const executionStart = Date.now();
256
256
  try {
257
- const db2 = c.env.DB;
257
+ const db = c.env.DB;
258
258
  const cacheEnabled = c.get("cacheEnabled");
259
259
  const cache = getCacheService(CACHE_CONFIGS.api);
260
260
  const cacheKey = cache.generateKey("collections", "all");
@@ -282,7 +282,7 @@ apiRoutes.get("/collections", async (c) => {
282
282
  }
283
283
  c.header("X-Cache-Status", "MISS");
284
284
  c.header("X-Cache-Source", "database");
285
- const stmt = db2.prepare("SELECT * FROM collections WHERE is_active = 1");
285
+ const stmt = db.prepare("SELECT * FROM collections WHERE is_active = 1");
286
286
  const { results } = await stmt.all();
287
287
  const transformedResults = results.map((row) => ({
288
288
  ...row,
@@ -313,11 +313,11 @@ apiRoutes.get("/collections", async (c) => {
313
313
  apiRoutes.get("/content", async (c) => {
314
314
  const executionStart = Date.now();
315
315
  try {
316
- const db2 = c.env.DB;
316
+ const db = c.env.DB;
317
317
  const queryParams = c.req.query();
318
318
  if (queryParams.collection) {
319
319
  const collectionName = queryParams.collection;
320
- const collectionStmt = db2.prepare("SELECT id FROM collections WHERE name = ? AND is_active = 1");
320
+ const collectionStmt = db.prepare("SELECT id FROM collections WHERE name = ? AND is_active = 1");
321
321
  const collectionResult = await collectionStmt.bind(collectionName).first();
322
322
  if (collectionResult) {
323
323
  queryParams.collection_id = collectionResult.id;
@@ -373,7 +373,7 @@ apiRoutes.get("/content", async (c) => {
373
373
  }
374
374
  c.header("X-Cache-Status", "MISS");
375
375
  c.header("X-Cache-Source", "database");
376
- const stmt = db2.prepare(queryResult.sql);
376
+ const stmt = db.prepare(queryResult.sql);
377
377
  const boundStmt = queryResult.params.length > 0 ? stmt.bind(...queryResult.params) : stmt;
378
378
  const { results } = await boundStmt.all();
379
379
  const transformedResults = results.map((row) => ({
@@ -418,9 +418,9 @@ apiRoutes.get("/collections/:collection/content", async (c) => {
418
418
  const executionStart = Date.now();
419
419
  try {
420
420
  const collection = c.req.param("collection");
421
- const db2 = c.env.DB;
421
+ const db = c.env.DB;
422
422
  const queryParams = c.req.query();
423
- const collectionStmt = db2.prepare("SELECT * FROM collections WHERE name = ? AND is_active = 1");
423
+ const collectionStmt = db.prepare("SELECT * FROM collections WHERE name = ? AND is_active = 1");
424
424
  const collectionResult = await collectionStmt.bind(collection).first();
425
425
  if (!collectionResult) {
426
426
  return c.json({ error: "Collection not found" }, 404);
@@ -476,7 +476,7 @@ apiRoutes.get("/collections/:collection/content", async (c) => {
476
476
  }
477
477
  c.header("X-Cache-Status", "MISS");
478
478
  c.header("X-Cache-Source", "database");
479
- const stmt = db2.prepare(queryResult.sql);
479
+ const stmt = db.prepare(queryResult.sql);
480
480
  const boundStmt = queryResult.params.length > 0 ? stmt.bind(...queryResult.params) : stmt;
481
481
  const { results } = await boundStmt.all();
482
482
  const transformedResults = results.map((row) => ({
@@ -1240,20 +1240,20 @@ apiSystemRoutes.get("/info", (c) => {
1240
1240
  });
1241
1241
  apiSystemRoutes.get("/stats", async (c) => {
1242
1242
  try {
1243
- const db2 = c.env.DB;
1244
- const contentStats = await db2.prepare(`
1243
+ const db = c.env.DB;
1244
+ const contentStats = await db.prepare(`
1245
1245
  SELECT COUNT(*) as total_content
1246
1246
  FROM content
1247
1247
  WHERE deleted_at IS NULL
1248
1248
  `).first();
1249
- const mediaStats = await db2.prepare(`
1249
+ const mediaStats = await db.prepare(`
1250
1250
  SELECT
1251
1251
  COUNT(*) as total_files,
1252
1252
  SUM(size) as total_size
1253
1253
  FROM media
1254
1254
  WHERE deleted_at IS NULL
1255
1255
  `).first();
1256
- const userStats = await db2.prepare(`
1256
+ const userStats = await db.prepare(`
1257
1257
  SELECT COUNT(*) as total_users
1258
1258
  FROM users
1259
1259
  `).first();
@@ -1314,10 +1314,10 @@ adminApiRoutes.use("*", requireAuth());
1314
1314
  adminApiRoutes.use("*", requireRole(["admin", "editor"]));
1315
1315
  adminApiRoutes.get("/stats", async (c) => {
1316
1316
  try {
1317
- const db2 = c.env.DB;
1317
+ const db = c.env.DB;
1318
1318
  let collectionsCount = 0;
1319
1319
  try {
1320
- const collectionsStmt = db2.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1");
1320
+ const collectionsStmt = db.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1");
1321
1321
  const collectionsResult = await collectionsStmt.first();
1322
1322
  collectionsCount = collectionsResult?.count || 0;
1323
1323
  } catch (error) {
@@ -1325,7 +1325,7 @@ adminApiRoutes.get("/stats", async (c) => {
1325
1325
  }
1326
1326
  let contentCount = 0;
1327
1327
  try {
1328
- const contentStmt = db2.prepare("SELECT COUNT(*) as count FROM content WHERE deleted_at IS NULL");
1328
+ const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE deleted_at IS NULL");
1329
1329
  const contentResult = await contentStmt.first();
1330
1330
  contentCount = contentResult?.count || 0;
1331
1331
  } catch (error) {
@@ -1334,7 +1334,7 @@ adminApiRoutes.get("/stats", async (c) => {
1334
1334
  let mediaCount = 0;
1335
1335
  let mediaSize = 0;
1336
1336
  try {
1337
- const mediaStmt = db2.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
1337
+ const mediaStmt = db.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
1338
1338
  const mediaResult = await mediaStmt.first();
1339
1339
  mediaCount = mediaResult?.count || 0;
1340
1340
  mediaSize = mediaResult?.total_size || 0;
@@ -1343,7 +1343,7 @@ adminApiRoutes.get("/stats", async (c) => {
1343
1343
  }
1344
1344
  let usersCount = 0;
1345
1345
  try {
1346
- const usersStmt = db2.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
1346
+ const usersStmt = db.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
1347
1347
  const usersResult = await usersStmt.first();
1348
1348
  usersCount = usersResult?.count || 0;
1349
1349
  } catch (error) {
@@ -1364,17 +1364,17 @@ adminApiRoutes.get("/stats", async (c) => {
1364
1364
  });
1365
1365
  adminApiRoutes.get("/storage", async (c) => {
1366
1366
  try {
1367
- const db2 = c.env.DB;
1367
+ const db = c.env.DB;
1368
1368
  let databaseSize = 0;
1369
1369
  try {
1370
- const result = await db2.prepare("SELECT 1").run();
1370
+ const result = await db.prepare("SELECT 1").run();
1371
1371
  databaseSize = result?.meta?.size_after || 0;
1372
1372
  } catch (error) {
1373
1373
  console.error("Error fetching database size:", error);
1374
1374
  }
1375
1375
  let mediaSize = 0;
1376
1376
  try {
1377
- const mediaStmt = db2.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
1377
+ const mediaStmt = db.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
1378
1378
  const mediaResult = await mediaStmt.first();
1379
1379
  mediaSize = mediaResult?.total_size || 0;
1380
1380
  } catch (error) {
@@ -1393,9 +1393,9 @@ adminApiRoutes.get("/storage", async (c) => {
1393
1393
  });
1394
1394
  adminApiRoutes.get("/activity", async (c) => {
1395
1395
  try {
1396
- const db2 = c.env.DB;
1396
+ const db = c.env.DB;
1397
1397
  const limit = parseInt(c.req.query("limit") || "10");
1398
- const activityStmt = db2.prepare(`
1398
+ const activityStmt = db.prepare(`
1399
1399
  SELECT
1400
1400
  a.id,
1401
1401
  a.action,
@@ -1457,13 +1457,13 @@ var updateCollectionSchema = z.object({
1457
1457
  });
1458
1458
  adminApiRoutes.get("/collections", async (c) => {
1459
1459
  try {
1460
- const db2 = c.env.DB;
1460
+ const db = c.env.DB;
1461
1461
  const search = c.req.query("search") || "";
1462
1462
  const includeInactive = c.req.query("includeInactive") === "true";
1463
1463
  let stmt;
1464
1464
  let results;
1465
1465
  if (search) {
1466
- stmt = db2.prepare(`
1466
+ stmt = db.prepare(`
1467
1467
  SELECT id, name, display_name, description, created_at, updated_at, is_active, managed
1468
1468
  FROM collections
1469
1469
  WHERE ${includeInactive ? "1=1" : "is_active = 1"}
@@ -1474,7 +1474,7 @@ adminApiRoutes.get("/collections", async (c) => {
1474
1474
  const queryResults = await stmt.bind(searchParam, searchParam, searchParam).all();
1475
1475
  results = queryResults.results;
1476
1476
  } else {
1477
- stmt = db2.prepare(`
1477
+ stmt = db.prepare(`
1478
1478
  SELECT id, name, display_name, description, created_at, updated_at, is_active, managed
1479
1479
  FROM collections
1480
1480
  ${includeInactive ? "" : "WHERE is_active = 1"}
@@ -1483,7 +1483,7 @@ adminApiRoutes.get("/collections", async (c) => {
1483
1483
  const queryResults = await stmt.all();
1484
1484
  results = queryResults.results;
1485
1485
  }
1486
- const fieldCountStmt = db2.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id");
1486
+ const fieldCountStmt = db.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id");
1487
1487
  const { results: fieldCountResults } = await fieldCountStmt.all();
1488
1488
  const fieldCounts = new Map((fieldCountResults || []).map((row) => [String(row.collection_id), Number(row.count)]));
1489
1489
  const collections = (results || []).map((row) => ({
@@ -1510,13 +1510,13 @@ adminApiRoutes.get("/collections", async (c) => {
1510
1510
  adminApiRoutes.get("/collections/:id", async (c) => {
1511
1511
  try {
1512
1512
  const id = c.req.param("id");
1513
- const db2 = c.env.DB;
1514
- const stmt = db2.prepare("SELECT * FROM collections WHERE id = ?");
1513
+ const db = c.env.DB;
1514
+ const stmt = db.prepare("SELECT * FROM collections WHERE id = ?");
1515
1515
  const collection = await stmt.bind(id).first();
1516
1516
  if (!collection) {
1517
1517
  return c.json({ error: "Collection not found" }, 404);
1518
1518
  }
1519
- const fieldsStmt = db2.prepare(`
1519
+ const fieldsStmt = db.prepare(`
1520
1520
  SELECT * FROM content_fields
1521
1521
  WHERE collection_id = ?
1522
1522
  ORDER BY field_order ASC
@@ -1565,13 +1565,13 @@ adminApiRoutes.post("/collections", async (c) => {
1565
1565
  }
1566
1566
  const validation = createCollectionSchema.safeParse(body);
1567
1567
  if (!validation.success) {
1568
- return c.json({ error: "Validation failed", details: validation.error.errors }, 400);
1568
+ return c.json({ error: "Validation failed", details: validation.error.issues }, 400);
1569
1569
  }
1570
1570
  const validatedData = validation.data;
1571
- const db2 = c.env.DB;
1571
+ const db = c.env.DB;
1572
1572
  const ____user = c.get("user");
1573
1573
  const displayName = validatedData.displayName || validatedData.display_name || "";
1574
- const existingStmt = db2.prepare("SELECT id FROM collections WHERE name = ?");
1574
+ const existingStmt = db.prepare("SELECT id FROM collections WHERE name = ?");
1575
1575
  const existing = await existingStmt.bind(validatedData.name).first();
1576
1576
  if (existing) {
1577
1577
  return c.json({ error: "A collection with this name already exists" }, 400);
@@ -1600,7 +1600,7 @@ adminApiRoutes.post("/collections", async (c) => {
1600
1600
  };
1601
1601
  const collectionId = crypto.randomUUID();
1602
1602
  const now = Date.now();
1603
- const insertStmt = db2.prepare(`
1603
+ const insertStmt = db.prepare(`
1604
1604
  INSERT INTO collections (id, name, display_name, description, schema, is_active, created_at, updated_at)
1605
1605
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1606
1606
  `);
@@ -1639,11 +1639,11 @@ adminApiRoutes.patch("/collections/:id", async (c) => {
1639
1639
  const body = await c.req.json();
1640
1640
  const validation = updateCollectionSchema.safeParse(body);
1641
1641
  if (!validation.success) {
1642
- return c.json({ error: "Validation failed", details: validation.error.errors }, 400);
1642
+ return c.json({ error: "Validation failed", details: validation.error.issues }, 400);
1643
1643
  }
1644
1644
  const validatedData = validation.data;
1645
- const db2 = c.env.DB;
1646
- const checkStmt = db2.prepare("SELECT * FROM collections WHERE id = ?");
1645
+ const db = c.env.DB;
1646
+ const checkStmt = db.prepare("SELECT * FROM collections WHERE id = ?");
1647
1647
  const existing = await checkStmt.bind(id).first();
1648
1648
  if (!existing) {
1649
1649
  return c.json({ error: "Collection not found" }, 404);
@@ -1668,7 +1668,7 @@ adminApiRoutes.patch("/collections/:id", async (c) => {
1668
1668
  updateFields.push("updated_at = ?");
1669
1669
  updateParams.push(Date.now());
1670
1670
  updateParams.push(id);
1671
- const updateStmt = db2.prepare(`
1671
+ const updateStmt = db.prepare(`
1672
1672
  UPDATE collections
1673
1673
  SET ${updateFields.join(", ")}
1674
1674
  WHERE id = ?
@@ -1689,22 +1689,22 @@ adminApiRoutes.patch("/collections/:id", async (c) => {
1689
1689
  adminApiRoutes.delete("/collections/:id", async (c) => {
1690
1690
  try {
1691
1691
  const id = c.req.param("id");
1692
- const db2 = c.env.DB;
1693
- const collectionStmt = db2.prepare("SELECT name FROM collections WHERE id = ?");
1692
+ const db = c.env.DB;
1693
+ const collectionStmt = db.prepare("SELECT name FROM collections WHERE id = ?");
1694
1694
  const collection = await collectionStmt.bind(id).first();
1695
1695
  if (!collection) {
1696
1696
  return c.json({ error: "Collection not found" }, 404);
1697
1697
  }
1698
- const contentStmt = db2.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?");
1698
+ const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?");
1699
1699
  const contentResult = await contentStmt.bind(id).first();
1700
1700
  if (contentResult && contentResult.count > 0) {
1701
1701
  return c.json({
1702
1702
  error: `Cannot delete collection: it contains ${contentResult.count} content item(s). Delete all content first.`
1703
1703
  }, 400);
1704
1704
  }
1705
- const deleteFieldsStmt = db2.prepare("DELETE FROM content_fields WHERE collection_id = ?");
1705
+ const deleteFieldsStmt = db.prepare("DELETE FROM content_fields WHERE collection_id = ?");
1706
1706
  await deleteFieldsStmt.bind(id).run();
1707
- const deleteStmt = db2.prepare("DELETE FROM collections WHERE id = ?");
1707
+ const deleteStmt = db.prepare("DELETE FROM collections WHERE id = ?");
1708
1708
  await deleteStmt.bind(id).run();
1709
1709
  try {
1710
1710
  await c.env.CACHE_KV.delete("cache:collections:all");
@@ -1720,9 +1720,9 @@ adminApiRoutes.delete("/collections/:id", async (c) => {
1720
1720
  });
1721
1721
  adminApiRoutes.get("/migrations/status", async (c) => {
1722
1722
  try {
1723
- const { MigrationService: MigrationService2 } = await import('./migrations-IHERIQVD.js');
1724
- const db2 = c.env.DB;
1725
- const migrationService = new MigrationService2(db2);
1723
+ const { MigrationService: MigrationService2 } = await import('./migrations-B2CDNN76.js');
1724
+ const db = c.env.DB;
1725
+ const migrationService = new MigrationService2(db);
1726
1726
  const status = await migrationService.getMigrationStatus();
1727
1727
  return c.json({
1728
1728
  success: true,
@@ -1745,9 +1745,9 @@ adminApiRoutes.post("/migrations/run", async (c) => {
1745
1745
  error: "Unauthorized. Admin access required."
1746
1746
  }, 403);
1747
1747
  }
1748
- const { MigrationService: MigrationService2 } = await import('./migrations-IHERIQVD.js');
1749
- const db2 = c.env.DB;
1750
- const migrationService = new MigrationService2(db2);
1748
+ const { MigrationService: MigrationService2 } = await import('./migrations-B2CDNN76.js');
1749
+ const db = c.env.DB;
1750
+ const migrationService = new MigrationService2(db);
1751
1751
  const result = await migrationService.runPendingMigrations();
1752
1752
  return c.json({
1753
1753
  success: result.success,
@@ -1764,9 +1764,9 @@ adminApiRoutes.post("/migrations/run", async (c) => {
1764
1764
  });
1765
1765
  adminApiRoutes.get("/migrations/validate", async (c) => {
1766
1766
  try {
1767
- const { MigrationService: MigrationService2 } = await import('./migrations-IHERIQVD.js');
1768
- const db2 = c.env.DB;
1769
- const migrationService = new MigrationService2(db2);
1767
+ const { MigrationService: MigrationService2 } = await import('./migrations-B2CDNN76.js');
1768
+ const db = c.env.DB;
1769
+ const migrationService = new MigrationService2(db);
1770
1770
  const validation = await migrationService.validateSchema();
1771
1771
  return c.json({
1772
1772
  success: true,
@@ -2117,19 +2117,20 @@ function renderRegisterPage(data) {
2117
2117
  </html>
2118
2118
  `;
2119
2119
  }
2120
+ var baseRegistrationSchema = z.object({
2121
+ email: z.string().email("Valid email is required"),
2122
+ password: z.string().min(8, "Password must be at least 8 characters"),
2123
+ username: z.string().min(3, "Username must be at least 3 characters").optional(),
2124
+ firstName: z.string().min(1, "First name is required").optional(),
2125
+ lastName: z.string().min(1, "Last name is required").optional()
2126
+ });
2120
2127
  var authValidationService = {
2121
2128
  /**
2122
2129
  * Build registration schema dynamically based on auth settings
2123
2130
  * For now, returns a static schema with standard fields
2124
2131
  */
2125
2132
  async buildRegistrationSchema(_db) {
2126
- return z.object({
2127
- email: z.string().email("Valid email is required"),
2128
- password: z.string().min(8, "Password must be at least 8 characters"),
2129
- username: z.string().min(3, "Username must be at least 3 characters").optional(),
2130
- firstName: z.string().min(1, "First name is required").optional(),
2131
- lastName: z.string().min(1, "Last name is required").optional()
2132
- });
2133
+ return baseRegistrationSchema;
2133
2134
  },
2134
2135
  /**
2135
2136
  * Generate default values for optional fields
@@ -2158,10 +2159,10 @@ authRoutes.get("/login", async (c) => {
2158
2159
  message: message || void 0,
2159
2160
  version: c.get("appVersion")
2160
2161
  };
2161
- const db2 = c.env.DB;
2162
+ const db = c.env.DB;
2162
2163
  let demoLoginActive = false;
2163
2164
  try {
2164
- const plugin = await db2.prepare("SELECT * FROM plugins WHERE id = ? AND status = ?").bind("demo-login-prefill", "active").first();
2165
+ const plugin = await db.prepare("SELECT * FROM plugins WHERE id = ? AND status = ?").bind("demo-login-prefill", "active").first();
2165
2166
  demoLoginActive = !!plugin;
2166
2167
  } catch (error2) {
2167
2168
  }
@@ -2182,21 +2183,21 @@ authRoutes.post(
2182
2183
  "/register",
2183
2184
  async (c) => {
2184
2185
  try {
2185
- const db2 = c.env.DB;
2186
+ const db = c.env.DB;
2186
2187
  let requestData;
2187
2188
  try {
2188
2189
  requestData = await c.req.json();
2189
2190
  } catch (parseError) {
2190
2191
  return c.json({ error: "Invalid JSON in request body" }, 400);
2191
2192
  }
2192
- const validationSchema = await authValidationService.buildRegistrationSchema(db2);
2193
+ const validationSchema = await authValidationService.buildRegistrationSchema(db);
2193
2194
  let validatedData;
2194
2195
  try {
2195
2196
  validatedData = await validationSchema.parseAsync(requestData);
2196
2197
  } catch (validationError) {
2197
2198
  return c.json({
2198
2199
  error: "Validation failed",
2199
- details: validationError.errors?.map((e) => e.message) || [validationError.message || "Invalid request data"]
2200
+ details: validationError.issues?.map((e) => e.message) || [validationError.message || "Invalid request data"]
2200
2201
  }, 400);
2201
2202
  }
2202
2203
  const email = validatedData.email;
@@ -2205,14 +2206,14 @@ authRoutes.post(
2205
2206
  const firstName = validatedData.firstName || authValidationService.generateDefaultValue("firstName", validatedData);
2206
2207
  const lastName = validatedData.lastName || authValidationService.generateDefaultValue("lastName", validatedData);
2207
2208
  const normalizedEmail = email.toLowerCase();
2208
- const existingUser = await db2.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first();
2209
+ const existingUser = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first();
2209
2210
  if (existingUser) {
2210
2211
  return c.json({ error: "User with this email or username already exists" }, 400);
2211
2212
  }
2212
2213
  const passwordHash = await AuthManager.hashPassword(password);
2213
2214
  const userId = crypto.randomUUID();
2214
2215
  const now = /* @__PURE__ */ new Date();
2215
- await db2.prepare(`
2216
+ await db.prepare(`
2216
2217
  INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at)
2217
2218
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2218
2219
  `).bind(
@@ -2265,15 +2266,15 @@ authRoutes.post("/login", async (c) => {
2265
2266
  const body = await c.req.json();
2266
2267
  const validation = loginSchema.safeParse(body);
2267
2268
  if (!validation.success) {
2268
- return c.json({ error: "Validation failed", details: validation.error.errors }, 400);
2269
+ return c.json({ error: "Validation failed", details: validation.error.issues }, 400);
2269
2270
  }
2270
2271
  const { email, password } = validation.data;
2271
- const db2 = c.env.DB;
2272
+ const db = c.env.DB;
2272
2273
  const normalizedEmail = email.toLowerCase();
2273
2274
  const cache = getCacheService(CACHE_CONFIGS.user);
2274
2275
  let user = await cache.get(cache.generateKey("user", `email:${normalizedEmail}`));
2275
2276
  if (!user) {
2276
- user = await db2.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first();
2277
+ user = await db.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first();
2277
2278
  if (user) {
2278
2279
  await cache.set(cache.generateKey("user", `email:${normalizedEmail}`), user);
2279
2280
  await cache.set(cache.generateKey("user", user.id), user);
@@ -2294,7 +2295,7 @@ authRoutes.post("/login", async (c) => {
2294
2295
  maxAge: 60 * 60 * 24
2295
2296
  // 24 hours
2296
2297
  });
2297
- await db2.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run();
2298
+ await db.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run();
2298
2299
  await cache.delete(cache.generateKey("user", user.id));
2299
2300
  await cache.delete(cache.generateKey("user", `email:${normalizedEmail}`));
2300
2301
  return c.json({
@@ -2341,8 +2342,8 @@ authRoutes.get("/me", requireAuth(), async (c) => {
2341
2342
  if (!user) {
2342
2343
  return c.json({ error: "Not authenticated" }, 401);
2343
2344
  }
2344
- const db2 = c.env.DB;
2345
- const userData = await db2.prepare("SELECT id, email, username, first_name, last_name, role, created_at FROM users WHERE id = ?").bind(user.userId).first();
2345
+ const db = c.env.DB;
2346
+ const userData = await db.prepare("SELECT id, email, username, first_name, last_name, role, created_at FROM users WHERE id = ?").bind(user.userId).first();
2346
2347
  if (!userData) {
2347
2348
  return c.json({ error: "User not found" }, 404);
2348
2349
  }
@@ -2374,7 +2375,7 @@ authRoutes.post("/refresh", requireAuth(), async (c) => {
2374
2375
  });
2375
2376
  authRoutes.post("/register/form", async (c) => {
2376
2377
  try {
2377
- const db2 = c.env.DB;
2378
+ const db = c.env.DB;
2378
2379
  const formData = await c.req.formData();
2379
2380
  const requestData = {
2380
2381
  email: formData.get("email"),
@@ -2385,12 +2386,12 @@ authRoutes.post("/register/form", async (c) => {
2385
2386
  };
2386
2387
  const normalizedEmail = requestData.email?.toLowerCase();
2387
2388
  requestData.email = normalizedEmail;
2388
- const validationSchema = await authValidationService.buildRegistrationSchema(db2);
2389
+ const validationSchema = await authValidationService.buildRegistrationSchema(db);
2389
2390
  const validation = await validationSchema.safeParseAsync(requestData);
2390
2391
  if (!validation.success) {
2391
2392
  return c.html(html`
2392
2393
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
2393
- ${validation.error.errors.map((err) => err.message).join(", ")}
2394
+ ${validation.error.issues.map((err) => err.message).join(", ")}
2394
2395
  </div>
2395
2396
  `);
2396
2397
  }
@@ -2399,7 +2400,7 @@ authRoutes.post("/register/form", async (c) => {
2399
2400
  const username = validatedData.username || authValidationService.generateDefaultValue("username", validatedData);
2400
2401
  const firstName = validatedData.firstName || authValidationService.generateDefaultValue("firstName", validatedData);
2401
2402
  const lastName = validatedData.lastName || authValidationService.generateDefaultValue("lastName", validatedData);
2402
- const existingUser = await db2.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first();
2403
+ const existingUser = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first();
2403
2404
  if (existingUser) {
2404
2405
  return c.html(html`
2405
2406
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
@@ -2410,7 +2411,7 @@ authRoutes.post("/register/form", async (c) => {
2410
2411
  const passwordHash = await AuthManager.hashPassword(password);
2411
2412
  const userId = crypto.randomUUID();
2412
2413
  const now = /* @__PURE__ */ new Date();
2413
- await db2.prepare(`
2414
+ await db.prepare(`
2414
2415
  INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at)
2415
2416
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2416
2417
  `).bind(
@@ -2465,12 +2466,12 @@ authRoutes.post("/login/form", async (c) => {
2465
2466
  if (!validation.success) {
2466
2467
  return c.html(html`
2467
2468
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
2468
- ${validation.error.errors.map((err) => err.message).join(", ")}
2469
+ ${validation.error.issues.map((err) => err.message).join(", ")}
2469
2470
  </div>
2470
2471
  `);
2471
2472
  }
2472
- const db2 = c.env.DB;
2473
- const user = await db2.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first();
2473
+ const db = c.env.DB;
2474
+ const user = await db.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first();
2474
2475
  if (!user) {
2475
2476
  return c.html(html`
2476
2477
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
@@ -2495,7 +2496,7 @@ authRoutes.post("/login/form", async (c) => {
2495
2496
  maxAge: 60 * 60 * 24
2496
2497
  // 24 hours
2497
2498
  });
2498
- await db2.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run();
2499
+ await db.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run();
2499
2500
  return c.html(html`
2500
2501
  <div id="form-response">
2501
2502
  <div class="rounded-lg bg-green-100 dark:bg-lime-500/10 p-4 ring-1 ring-green-400 dark:ring-lime-500/20">
@@ -2526,8 +2527,8 @@ authRoutes.post("/login/form", async (c) => {
2526
2527
  });
2527
2528
  authRoutes.post("/seed-admin", async (c) => {
2528
2529
  try {
2529
- const db2 = c.env.DB;
2530
- await db2.prepare(`
2530
+ const db = c.env.DB;
2531
+ await db.prepare(`
2531
2532
  CREATE TABLE IF NOT EXISTS users (
2532
2533
  id TEXT PRIMARY KEY,
2533
2534
  email TEXT NOT NULL UNIQUE,
@@ -2543,10 +2544,10 @@ authRoutes.post("/seed-admin", async (c) => {
2543
2544
  updated_at INTEGER NOT NULL
2544
2545
  )
2545
2546
  `).run();
2546
- const existingAdmin = await db2.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind("admin@sonicjs.com", "admin").first();
2547
+ const existingAdmin = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind("admin@sonicjs.com", "admin").first();
2547
2548
  if (existingAdmin) {
2548
2549
  const passwordHash2 = await AuthManager.hashPassword("sonicjs!");
2549
- await db2.prepare("UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?").bind(passwordHash2, Date.now(), existingAdmin.id).run();
2550
+ await db.prepare("UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?").bind(passwordHash2, Date.now(), existingAdmin.id).run();
2550
2551
  return c.json({
2551
2552
  message: "Admin user already exists (password updated)",
2552
2553
  user: {
@@ -2561,7 +2562,7 @@ authRoutes.post("/seed-admin", async (c) => {
2561
2562
  const userId = "admin-user-id";
2562
2563
  const now = Date.now();
2563
2564
  const adminEmail = "admin@sonicjs.com".toLowerCase();
2564
- await db2.prepare(`
2565
+ await db.prepare(`
2565
2566
  INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at)
2566
2567
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2567
2568
  `).bind(
@@ -2608,8 +2609,8 @@ authRoutes.get("/accept-invitation", async (c) => {
2608
2609
  </html>
2609
2610
  `);
2610
2611
  }
2611
- const db2 = c.env.DB;
2612
- const userStmt = db2.prepare(`
2612
+ const db = c.env.DB;
2613
+ const userStmt = db.prepare(`
2613
2614
  SELECT id, email, first_name, last_name, role, invited_at
2614
2615
  FROM users
2615
2616
  WHERE invitation_token = ? AND is_active = 0
@@ -2755,8 +2756,8 @@ authRoutes.post("/accept-invitation", async (c) => {
2755
2756
  if (password.length < 8) {
2756
2757
  return c.json({ error: "Password must be at least 8 characters long" }, 400);
2757
2758
  }
2758
- const db2 = c.env.DB;
2759
- const userStmt = db2.prepare(`
2759
+ const db = c.env.DB;
2760
+ const userStmt = db.prepare(`
2760
2761
  SELECT id, email, first_name, last_name, role, invited_at
2761
2762
  FROM users
2762
2763
  WHERE invitation_token = ? AND is_active = 0
@@ -2770,7 +2771,7 @@ authRoutes.post("/accept-invitation", async (c) => {
2770
2771
  if (invitationAge > maxAge) {
2771
2772
  return c.json({ error: "Invitation has expired" }, 400);
2772
2773
  }
2773
- const existingUsernameStmt = db2.prepare(`
2774
+ const existingUsernameStmt = db.prepare(`
2774
2775
  SELECT id FROM users WHERE username = ? AND id != ?
2775
2776
  `);
2776
2777
  const existingUsername = await existingUsernameStmt.bind(username, invitedUser.id).first();
@@ -2778,7 +2779,7 @@ authRoutes.post("/accept-invitation", async (c) => {
2778
2779
  return c.json({ error: "Username is already taken" }, 400);
2779
2780
  }
2780
2781
  const passwordHash = await AuthManager.hashPassword(password);
2781
- const updateStmt = db2.prepare(`
2782
+ const updateStmt = db.prepare(`
2782
2783
  UPDATE users SET
2783
2784
  username = ?,
2784
2785
  password_hash = ?,
@@ -2821,8 +2822,8 @@ authRoutes.post("/request-password-reset", async (c) => {
2821
2822
  if (!emailRegex.test(email)) {
2822
2823
  return c.json({ error: "Please enter a valid email address" }, 400);
2823
2824
  }
2824
- const db2 = c.env.DB;
2825
- const userStmt = db2.prepare(`
2825
+ const db = c.env.DB;
2826
+ const userStmt = db.prepare(`
2826
2827
  SELECT id, email, first_name, last_name FROM users
2827
2828
  WHERE email = ? AND is_active = 1
2828
2829
  `);
@@ -2835,7 +2836,7 @@ authRoutes.post("/request-password-reset", async (c) => {
2835
2836
  }
2836
2837
  const resetToken = crypto.randomUUID();
2837
2838
  const resetExpires = Date.now() + 60 * 60 * 1e3;
2838
- const updateStmt = db2.prepare(`
2839
+ const updateStmt = db.prepare(`
2839
2840
  UPDATE users SET
2840
2841
  password_reset_token = ?,
2841
2842
  password_reset_expires = ?,
@@ -2875,8 +2876,8 @@ authRoutes.get("/reset-password", async (c) => {
2875
2876
  </html>
2876
2877
  `);
2877
2878
  }
2878
- const db2 = c.env.DB;
2879
- const userStmt = db2.prepare(`
2879
+ const db = c.env.DB;
2880
+ const userStmt = db.prepare(`
2880
2881
  SELECT id, email, first_name, last_name, password_reset_expires
2881
2882
  FROM users
2882
2883
  WHERE password_reset_token = ? AND is_active = 1
@@ -3013,8 +3014,8 @@ authRoutes.post("/reset-password", async (c) => {
3013
3014
  if (password.length < 8) {
3014
3015
  return c.json({ error: "Password must be at least 8 characters long" }, 400);
3015
3016
  }
3016
- const db2 = c.env.DB;
3017
- const userStmt = db2.prepare(`
3017
+ const db = c.env.DB;
3018
+ const userStmt = db.prepare(`
3018
3019
  SELECT id, email, password_hash, password_reset_expires
3019
3020
  FROM users
3020
3021
  WHERE password_reset_token = ? AND is_active = 1
@@ -3028,7 +3029,7 @@ authRoutes.post("/reset-password", async (c) => {
3028
3029
  }
3029
3030
  const newPasswordHash = await AuthManager.hashPassword(password);
3030
3031
  try {
3031
- const historyStmt = db2.prepare(`
3032
+ const historyStmt = db.prepare(`
3032
3033
  INSERT INTO password_history (id, user_id, password_hash, created_at)
3033
3034
  VALUES (?, ?, ?, ?)
3034
3035
  `);
@@ -3041,7 +3042,7 @@ authRoutes.post("/reset-password", async (c) => {
3041
3042
  } catch (historyError) {
3042
3043
  console.warn("Could not store password history:", historyError);
3043
3044
  }
3044
- const updateStmt = db2.prepare(`
3045
+ const updateStmt = db.prepare(`
3045
3046
  UPDATE users SET
3046
3047
  password_hash = ?,
3047
3048
  password_reset_token = NULL,
@@ -3063,20 +3064,20 @@ authRoutes.post("/reset-password", async (c) => {
3063
3064
  var auth_default = authRoutes;
3064
3065
  var app = new Hono();
3065
3066
  app.post("/test-cleanup", async (c) => {
3066
- const db2 = c.env.DB;
3067
+ const db = c.env.DB;
3067
3068
  if (c.env.ENVIRONMENT === "production") {
3068
3069
  return c.json({ error: "Cleanup endpoint not available in production" }, 403);
3069
3070
  }
3070
3071
  try {
3071
3072
  let deletedCount = 0;
3072
- await db2.prepare(`
3073
+ await db.prepare(`
3073
3074
  DELETE FROM content_versions
3074
3075
  WHERE content_id IN (
3075
3076
  SELECT id FROM content
3076
3077
  WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%'
3077
3078
  )
3078
3079
  `).run();
3079
- await db2.prepare(`
3080
+ await db.prepare(`
3080
3081
  DELETE FROM workflow_history
3081
3082
  WHERE content_id IN (
3082
3083
  SELECT id FROM content
@@ -3084,7 +3085,7 @@ app.post("/test-cleanup", async (c) => {
3084
3085
  )
3085
3086
  `).run();
3086
3087
  try {
3087
- await db2.prepare(`
3088
+ await db.prepare(`
3088
3089
  DELETE FROM content_data
3089
3090
  WHERE content_id IN (
3090
3091
  SELECT id FROM content
@@ -3093,32 +3094,32 @@ app.post("/test-cleanup", async (c) => {
3093
3094
  `).run();
3094
3095
  } catch (e) {
3095
3096
  }
3096
- const contentResult = await db2.prepare(`
3097
+ const contentResult = await db.prepare(`
3097
3098
  DELETE FROM content
3098
3099
  WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%'
3099
3100
  `).run();
3100
3101
  deletedCount += contentResult.meta?.changes || 0;
3101
- await db2.prepare(`
3102
+ await db.prepare(`
3102
3103
  DELETE FROM api_tokens
3103
3104
  WHERE user_id IN (
3104
3105
  SELECT id FROM users
3105
3106
  WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%')
3106
3107
  )
3107
3108
  `).run();
3108
- await db2.prepare(`
3109
+ await db.prepare(`
3109
3110
  DELETE FROM media
3110
3111
  WHERE uploaded_by IN (
3111
3112
  SELECT id FROM users
3112
3113
  WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%')
3113
3114
  )
3114
3115
  `).run();
3115
- const usersResult = await db2.prepare(`
3116
+ const usersResult = await db.prepare(`
3116
3117
  DELETE FROM users
3117
3118
  WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%')
3118
3119
  `).run();
3119
3120
  deletedCount += usersResult.meta?.changes || 0;
3120
3121
  try {
3121
- await db2.prepare(`
3122
+ await db.prepare(`
3122
3123
  DELETE FROM collection_fields
3123
3124
  WHERE collection_id IN (
3124
3125
  SELECT id FROM collections
@@ -3127,43 +3128,43 @@ app.post("/test-cleanup", async (c) => {
3127
3128
  `).run();
3128
3129
  } catch (e) {
3129
3130
  }
3130
- await db2.prepare(`
3131
+ await db.prepare(`
3131
3132
  DELETE FROM content
3132
3133
  WHERE collection_id IN (
3133
3134
  SELECT id FROM collections
3134
3135
  WHERE name LIKE 'test_%' OR name IN ('blog_posts', 'test_collection', 'products', 'articles')
3135
3136
  )
3136
3137
  `).run();
3137
- const collectionsResult = await db2.prepare(`
3138
+ const collectionsResult = await db.prepare(`
3138
3139
  DELETE FROM collections
3139
3140
  WHERE name LIKE 'test_%' OR name IN ('blog_posts', 'test_collection', 'products', 'articles')
3140
3141
  `).run();
3141
3142
  deletedCount += collectionsResult.meta?.changes || 0;
3142
3143
  try {
3143
- await db2.prepare(`
3144
+ await db.prepare(`
3144
3145
  DELETE FROM content_data WHERE content_id NOT IN (SELECT id FROM content)
3145
3146
  `).run();
3146
3147
  } catch (e) {
3147
3148
  }
3148
3149
  try {
3149
- await db2.prepare(`
3150
+ await db.prepare(`
3150
3151
  DELETE FROM collection_fields WHERE collection_id NOT IN (SELECT id FROM collections)
3151
3152
  `).run();
3152
3153
  } catch (e) {
3153
3154
  }
3154
3155
  try {
3155
- await db2.prepare(`
3156
+ await db.prepare(`
3156
3157
  DELETE FROM content_versions WHERE content_id NOT IN (SELECT id FROM content)
3157
3158
  `).run();
3158
3159
  } catch (e) {
3159
3160
  }
3160
3161
  try {
3161
- await db2.prepare(`
3162
+ await db.prepare(`
3162
3163
  DELETE FROM workflow_history WHERE content_id NOT IN (SELECT id FROM content)
3163
3164
  `).run();
3164
3165
  } catch (e) {
3165
3166
  }
3166
- await db2.prepare(`
3167
+ await db.prepare(`
3167
3168
  DELETE FROM activity_logs
3168
3169
  WHERE id NOT IN (
3169
3170
  SELECT id FROM activity_logs
@@ -3185,12 +3186,12 @@ app.post("/test-cleanup", async (c) => {
3185
3186
  }
3186
3187
  });
3187
3188
  app.post("/test-cleanup/users", async (c) => {
3188
- const db2 = c.env.DB;
3189
+ const db = c.env.DB;
3189
3190
  if (c.env.ENVIRONMENT === "production") {
3190
3191
  return c.json({ error: "Cleanup endpoint not available in production" }, 403);
3191
3192
  }
3192
3193
  try {
3193
- const result = await db2.prepare(`
3194
+ const result = await db.prepare(`
3194
3195
  DELETE FROM users
3195
3196
  WHERE email != 'admin@sonicjs.com'
3196
3197
  AND (
@@ -3213,13 +3214,13 @@ app.post("/test-cleanup/users", async (c) => {
3213
3214
  }
3214
3215
  });
3215
3216
  app.post("/test-cleanup/collections", async (c) => {
3216
- const db2 = c.env.DB;
3217
+ const db = c.env.DB;
3217
3218
  if (c.env.ENVIRONMENT === "production") {
3218
3219
  return c.json({ error: "Cleanup endpoint not available in production" }, 403);
3219
3220
  }
3220
3221
  try {
3221
3222
  let deletedCount = 0;
3222
- const collections = await db2.prepare(`
3223
+ const collections = await db.prepare(`
3223
3224
  SELECT id FROM collections
3224
3225
  WHERE name LIKE 'test_%'
3225
3226
  OR name IN ('blog_posts', 'test_collection', 'products', 'articles')
@@ -3227,12 +3228,12 @@ app.post("/test-cleanup/collections", async (c) => {
3227
3228
  if (collections.results && collections.results.length > 0) {
3228
3229
  const collectionIds = collections.results.map((c2) => c2.id);
3229
3230
  for (const id of collectionIds) {
3230
- await db2.prepare("DELETE FROM collection_fields WHERE collection_id = ?").bind(id).run();
3231
+ await db.prepare("DELETE FROM collection_fields WHERE collection_id = ?").bind(id).run();
3231
3232
  }
3232
3233
  for (const id of collectionIds) {
3233
- await db2.prepare("DELETE FROM content WHERE collection_id = ?").bind(id).run();
3234
+ await db.prepare("DELETE FROM content WHERE collection_id = ?").bind(id).run();
3234
3235
  }
3235
- const result = await db2.prepare(`
3236
+ const result = await db.prepare(`
3236
3237
  DELETE FROM collections
3237
3238
  WHERE id IN (${collectionIds.map(() => "?").join(",")})
3238
3239
  `).bind(...collectionIds).run();
@@ -3252,19 +3253,19 @@ app.post("/test-cleanup/collections", async (c) => {
3252
3253
  }
3253
3254
  });
3254
3255
  app.post("/test-cleanup/content", async (c) => {
3255
- const db2 = c.env.DB;
3256
+ const db = c.env.DB;
3256
3257
  if (c.env.ENVIRONMENT === "production") {
3257
3258
  return c.json({ error: "Cleanup endpoint not available in production" }, 403);
3258
3259
  }
3259
3260
  try {
3260
- const result = await db2.prepare(`
3261
+ const result = await db.prepare(`
3261
3262
  DELETE FROM content
3262
3263
  WHERE title LIKE 'Test %'
3263
3264
  OR title LIKE '%E2E%'
3264
3265
  OR title LIKE '%Playwright%'
3265
3266
  OR title LIKE '%Sample%'
3266
3267
  `).run();
3267
- await db2.prepare(`
3268
+ await db.prepare(`
3268
3269
  DELETE FROM content_data
3269
3270
  WHERE content_id NOT IN (SELECT id FROM content)
3270
3271
  `).run();
@@ -4231,8 +4232,7 @@ function createQuillEditorPlugin() {
4231
4232
  email: "team@sonicjs.com"
4232
4233
  },
4233
4234
  license: "MIT",
4234
- compatibility: "^2.0.0",
4235
- tags: ["editor", "rich-text", "wysiwyg", "quill"]
4235
+ compatibility: "^2.0.0"
4236
4236
  });
4237
4237
  builder3.lifecycle({
4238
4238
  activate: async () => {
@@ -5073,7 +5073,6 @@ function renderContentFormPage(data) {
5073
5073
  })}</script>` : ""}
5074
5074
 
5075
5075
  ${data.mdxeditorEnabled ? `<script>${getMDXEditorInitScript({
5076
- theme: data.mdxeditorSettings?.theme,
5077
5076
  defaultHeight: data.mdxeditorSettings?.defaultHeight,
5078
5077
  toolbar: data.mdxeditorSettings?.toolbar,
5079
5078
  placeholder: data.mdxeditorSettings?.placeholder
@@ -5107,9 +5106,9 @@ function renderContentListPage(data) {
5107
5106
  name: "model",
5108
5107
  label: "Model",
5109
5108
  options: [
5110
- { __value: "all", label: "All Models", selected: data.modelName === "all" },
5109
+ { value: "all", label: "All Models", selected: data.modelName === "all" },
5111
5110
  ...data.models.map((model) => ({
5112
- __value: model.name,
5111
+ value: model.name,
5113
5112
  label: model.displayName,
5114
5113
  selected: data.modelName === model.name
5115
5114
  }))
@@ -5119,13 +5118,13 @@ function renderContentListPage(data) {
5119
5118
  name: "status",
5120
5119
  label: "Status",
5121
5120
  options: [
5122
- { __value: "all", label: "All Status", selected: data.status === "all" },
5123
- { __value: "draft", label: "Draft", selected: data.status === "draft" },
5124
- { __value: "review", label: "Under Review", selected: data.status === "review" },
5125
- { __value: "scheduled", label: "Scheduled", selected: data.status === "scheduled" },
5126
- { __value: "published", label: "Published", selected: data.status === "published" },
5127
- { __value: "archived", label: "Archived", selected: data.status === "archived" },
5128
- { __value: "deleted", label: "Deleted", selected: data.status === "deleted" }
5121
+ { value: "all", label: "All Status", selected: data.status === "all" },
5122
+ { value: "draft", label: "Draft", selected: data.status === "draft" },
5123
+ { value: "review", label: "Under Review", selected: data.status === "review" },
5124
+ { value: "scheduled", label: "Scheduled", selected: data.status === "scheduled" },
5125
+ { value: "published", label: "Published", selected: data.status === "published" },
5126
+ { value: "archived", label: "Archived", selected: data.status === "archived" },
5127
+ { value: "deleted", label: "Deleted", selected: data.status === "deleted" }
5129
5128
  ]
5130
5129
  }
5131
5130
  ],
@@ -5137,9 +5136,9 @@ function renderContentListPage(data) {
5137
5136
  }
5138
5137
  ],
5139
5138
  bulkActions: [
5140
- { label: "Publish", ___value: "publish", icon: "check-circle" },
5141
- { label: "Unpublish", ___value: "unpublish", icon: "x-circle" },
5142
- { label: "Delete", ___value: "delete", icon: "trash", className: "text-pink-600" }
5139
+ { label: "Publish", value: "publish", icon: "check-circle" },
5140
+ { label: "Unpublish", value: "unpublish", icon: "x-circle" },
5141
+ { label: "Delete", value: "delete", icon: "trash", className: "text-pink-600" }
5143
5142
  ]
5144
5143
  };
5145
5144
  const tableColumns = [
@@ -5391,7 +5390,7 @@ function renderContentListPage(data) {
5391
5390
  class="col-start-1 row-start-1 w-full appearance-none rounded-md bg-white/5 dark:bg-white/5 py-1.5 ${filter.name === "status" ? "pl-8" : "pl-3"} pr-8 text-base text-zinc-950 dark:text-white outline outline-1 -outline-offset-1 outline-cyan-500/30 dark:outline-cyan-400/30 *:bg-white dark:*:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-cyan-500 dark:focus-visible:outline-cyan-400 sm:text-sm/6 min-w-48"
5392
5391
  >
5393
5392
  ${filter.options.map((opt) => `
5394
- <option value="${opt.__value}" ${opt.selected ? "selected" : ""}>${opt.label}</option>
5393
+ <option value="${opt.value}" ${opt.selected ? "selected" : ""}>${opt.label}</option>
5395
5394
  `).join("")}
5396
5395
  </select>
5397
5396
  <svg viewBox="0 0 16 16" fill="currentColor" data-slot="icon" aria-hidden="true" class="pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end text-cyan-600 dark:text-cyan-400 sm:size-4">
@@ -5911,9 +5910,9 @@ function escapeHtml3(text) {
5911
5910
  }
5912
5911
 
5913
5912
  // src/middleware/plugin-middleware.ts
5914
- async function isPluginActive2(db2, pluginId) {
5913
+ async function isPluginActive2(db, pluginId) {
5915
5914
  try {
5916
- const result = await db2.prepare("SELECT status FROM plugins WHERE id = ?").bind(pluginId).first();
5915
+ const result = await db.prepare("SELECT status FROM plugins WHERE id = ?").bind(pluginId).first();
5917
5916
  return result?.status === "active";
5918
5917
  } catch (error) {
5919
5918
  console.error(`[isPluginActive] Error checking plugin status for ${pluginId}:`, error);
@@ -5924,12 +5923,12 @@ async function isPluginActive2(db2, pluginId) {
5924
5923
  // src/routes/admin-content.ts
5925
5924
  var adminContentRoutes = new Hono();
5926
5925
  adminContentRoutes.use("*", requireAuth());
5927
- async function getCollectionFields(db2, collectionId) {
5926
+ async function getCollectionFields(db, collectionId) {
5928
5927
  const cache = getCacheService(CACHE_CONFIGS.collection);
5929
5928
  return cache.getOrSet(
5930
5929
  cache.generateKey("fields", collectionId),
5931
5930
  async () => {
5932
- const collectionStmt = db2.prepare("SELECT schema FROM collections WHERE id = ?");
5931
+ const collectionStmt = db.prepare("SELECT schema FROM collections WHERE id = ?");
5933
5932
  const collectionRow = await collectionStmt.bind(collectionId).first();
5934
5933
  if (collectionRow && collectionRow.schema) {
5935
5934
  try {
@@ -5960,7 +5959,7 @@ async function getCollectionFields(db2, collectionId) {
5960
5959
  console.error("Error parsing collection schema:", e);
5961
5960
  }
5962
5961
  }
5963
- const stmt = db2.prepare(`
5962
+ const stmt = db.prepare(`
5964
5963
  SELECT * FROM content_fields
5965
5964
  WHERE collection_id = ?
5966
5965
  ORDER BY field_order ASC
@@ -5979,12 +5978,12 @@ async function getCollectionFields(db2, collectionId) {
5979
5978
  }
5980
5979
  );
5981
5980
  }
5982
- async function getCollection(db2, collectionId) {
5981
+ async function getCollection(db, collectionId) {
5983
5982
  const cache = getCacheService(CACHE_CONFIGS.collection);
5984
5983
  return cache.getOrSet(
5985
5984
  cache.generateKey("collection", collectionId),
5986
5985
  async () => {
5987
- const stmt = db2.prepare("SELECT * FROM collections WHERE id = ? AND is_active = 1");
5986
+ const stmt = db.prepare("SELECT * FROM collections WHERE id = ? AND is_active = 1");
5988
5987
  const collection = await stmt.bind(collectionId).first();
5989
5988
  if (!collection) return null;
5990
5989
  return {
@@ -6001,14 +6000,14 @@ adminContentRoutes.get("/", async (c) => {
6001
6000
  try {
6002
6001
  const user = c.get("user");
6003
6002
  const url = new URL(c.req.url);
6004
- const db2 = c.env.DB;
6003
+ const db = c.env.DB;
6005
6004
  const page = parseInt(url.searchParams.get("page") || "1");
6006
6005
  const limit = parseInt(url.searchParams.get("limit") || "20");
6007
6006
  const modelName = url.searchParams.get("model") || "all";
6008
6007
  const status = url.searchParams.get("status") || "all";
6009
6008
  const search = url.searchParams.get("search") || "";
6010
6009
  const offset = (page - 1) * limit;
6011
- const collectionsStmt = db2.prepare("SELECT id, name, display_name FROM collections WHERE is_active = 1 ORDER BY display_name");
6010
+ const collectionsStmt = db.prepare("SELECT id, name, display_name FROM collections WHERE is_active = 1 ORDER BY display_name");
6012
6011
  const { results: collectionsResults } = await collectionsStmt.all();
6013
6012
  const models = (collectionsResults || []).map((row) => ({
6014
6013
  name: row.name,
@@ -6034,7 +6033,7 @@ adminContentRoutes.get("/", async (c) => {
6034
6033
  conditions.push("c.status = 'deleted'");
6035
6034
  }
6036
6035
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
6037
- const countStmt = db2.prepare(`
6036
+ const countStmt = db.prepare(`
6038
6037
  SELECT COUNT(*) as count
6039
6038
  FROM content c
6040
6039
  JOIN collections col ON c.collection_id = col.id
@@ -6042,7 +6041,7 @@ adminContentRoutes.get("/", async (c) => {
6042
6041
  `);
6043
6042
  const countResult = await countStmt.bind(...params).first();
6044
6043
  const totalItems = countResult?.count || 0;
6045
- const contentStmt = db2.prepare(`
6044
+ const contentStmt = db.prepare(`
6046
6045
  SELECT c.id, c.title, c.slug, c.status, c.created_at, c.updated_at,
6047
6046
  col.name as collection_name, col.display_name as collection_display_name,
6048
6047
  u.first_name, u.last_name, u.email as author_email
@@ -6143,8 +6142,8 @@ adminContentRoutes.get("/new", async (c) => {
6143
6142
  const url = new URL(c.req.url);
6144
6143
  const collectionId = url.searchParams.get("collection");
6145
6144
  if (!collectionId) {
6146
- const db3 = c.env.DB;
6147
- const collectionsStmt = db3.prepare("SELECT id, name, display_name, description FROM collections WHERE is_active = 1 ORDER BY display_name");
6145
+ const db2 = c.env.DB;
6146
+ const collectionsStmt = db2.prepare("SELECT id, name, display_name, description FROM collections WHERE is_active = 1 ORDER BY display_name");
6148
6147
  const { results } = await collectionsStmt.all();
6149
6148
  const collections = (results || []).map((row) => ({
6150
6149
  id: row.id,
@@ -6185,8 +6184,8 @@ adminContentRoutes.get("/new", async (c) => {
6185
6184
  `;
6186
6185
  return c.html(selectionHTML);
6187
6186
  }
6188
- const db2 = c.env.DB;
6189
- const collection = await getCollection(db2, collectionId);
6187
+ const db = c.env.DB;
6188
+ const collection = await getCollection(db, collectionId);
6190
6189
  if (!collection) {
6191
6190
  const formData2 = {
6192
6191
  collection: { id: "", name: "", display_name: "Unknown", schema: {} },
@@ -6200,26 +6199,26 @@ adminContentRoutes.get("/new", async (c) => {
6200
6199
  };
6201
6200
  return c.html(renderContentFormPage(formData2));
6202
6201
  }
6203
- const fields = await getCollectionFields(db2, collectionId);
6204
- const workflowEnabled = await isPluginActive2(db2, "workflow");
6205
- const tinymceEnabled = await isPluginActive2(db2, "tinymce-plugin");
6202
+ const fields = await getCollectionFields(db, collectionId);
6203
+ const workflowEnabled = await isPluginActive2(db, "workflow");
6204
+ const tinymceEnabled = await isPluginActive2(db, "tinymce-plugin");
6206
6205
  let tinymceSettings;
6207
6206
  if (tinymceEnabled) {
6208
- const pluginService = new PluginService(db2);
6207
+ const pluginService = new PluginService(db);
6209
6208
  const tinymcePlugin2 = await pluginService.getPlugin("tinymce-plugin");
6210
6209
  tinymceSettings = tinymcePlugin2?.settings;
6211
6210
  }
6212
- const quillEnabled = await isPluginActive2(db2, "quill-editor");
6211
+ const quillEnabled = await isPluginActive2(db, "quill-editor");
6213
6212
  let quillSettings;
6214
6213
  if (quillEnabled) {
6215
- const pluginService = new PluginService(db2);
6214
+ const pluginService = new PluginService(db);
6216
6215
  const quillPlugin = await pluginService.getPlugin("quill-editor");
6217
6216
  quillSettings = quillPlugin?.settings;
6218
6217
  }
6219
- const mdxeditorEnabled = await isPluginActive2(db2, "easy-mdx");
6218
+ const mdxeditorEnabled = await isPluginActive2(db, "easy-mdx");
6220
6219
  let mdxeditorSettings;
6221
6220
  if (mdxeditorEnabled) {
6222
- const pluginService = new PluginService(db2);
6221
+ const pluginService = new PluginService(db);
6223
6222
  const mdxeditorPlugin = await pluginService.getPlugin("easy-mdx");
6224
6223
  mdxeditorSettings = mdxeditorPlugin?.settings;
6225
6224
  }
@@ -6266,14 +6265,14 @@ adminContentRoutes.get("/:id/edit", async (c) => {
6266
6265
  try {
6267
6266
  const id = c.req.param("id");
6268
6267
  const user = c.get("user");
6269
- const db2 = c.env.DB;
6268
+ const db = c.env.DB;
6270
6269
  const url = new URL(c.req.url);
6271
6270
  const referrerParams = url.searchParams.get("ref") || "";
6272
6271
  const cache = getCacheService(CACHE_CONFIGS.content);
6273
6272
  const content = await cache.getOrSet(
6274
6273
  cache.generateKey("content", id),
6275
6274
  async () => {
6276
- const contentStmt = db2.prepare(`
6275
+ const contentStmt = db.prepare(`
6277
6276
  SELECT c.*, col.id as collection_id, col.name as collection_name,
6278
6277
  col.display_name as collection_display_name, col.description as collection_description,
6279
6278
  col.schema as collection_schema
@@ -6304,27 +6303,27 @@ adminContentRoutes.get("/:id/edit", async (c) => {
6304
6303
  description: content.collection_description,
6305
6304
  schema: content.collection_schema ? JSON.parse(content.collection_schema) : {}
6306
6305
  };
6307
- const fields = await getCollectionFields(db2, content.collection_id);
6306
+ const fields = await getCollectionFields(db, content.collection_id);
6308
6307
  const contentData = content.data ? JSON.parse(content.data) : {};
6309
- const workflowEnabled = await isPluginActive2(db2, "workflow");
6310
- const tinymceEnabled = await isPluginActive2(db2, "tinymce-plugin");
6308
+ const workflowEnabled = await isPluginActive2(db, "workflow");
6309
+ const tinymceEnabled = await isPluginActive2(db, "tinymce-plugin");
6311
6310
  let tinymceSettings;
6312
6311
  if (tinymceEnabled) {
6313
- const pluginService = new PluginService(db2);
6312
+ const pluginService = new PluginService(db);
6314
6313
  const tinymcePlugin2 = await pluginService.getPlugin("tinymce-plugin");
6315
6314
  tinymceSettings = tinymcePlugin2?.settings;
6316
6315
  }
6317
- const quillEnabled = await isPluginActive2(db2, "quill-editor");
6316
+ const quillEnabled = await isPluginActive2(db, "quill-editor");
6318
6317
  let quillSettings;
6319
6318
  if (quillEnabled) {
6320
- const pluginService = new PluginService(db2);
6319
+ const pluginService = new PluginService(db);
6321
6320
  const quillPlugin = await pluginService.getPlugin("quill-editor");
6322
6321
  quillSettings = quillPlugin?.settings;
6323
6322
  }
6324
- const mdxeditorEnabled = await isPluginActive2(db2, "easy-mdx");
6323
+ const mdxeditorEnabled = await isPluginActive2(db, "easy-mdx");
6325
6324
  let mdxeditorSettings;
6326
6325
  if (mdxeditorEnabled) {
6327
- const pluginService = new PluginService(db2);
6326
+ const pluginService = new PluginService(db);
6328
6327
  const mdxeditorPlugin = await pluginService.getPlugin("easy-mdx");
6329
6328
  mdxeditorSettings = mdxeditorPlugin?.settings;
6330
6329
  }
@@ -6386,8 +6385,8 @@ adminContentRoutes.post("/", async (c) => {
6386
6385
  </div>
6387
6386
  `);
6388
6387
  }
6389
- const db2 = c.env.DB;
6390
- const collection = await getCollection(db2, collectionId);
6388
+ const db = c.env.DB;
6389
+ const collection = await getCollection(db, collectionId);
6391
6390
  if (!collection) {
6392
6391
  return c.html(html`
6393
6392
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
@@ -6395,7 +6394,7 @@ adminContentRoutes.post("/", async (c) => {
6395
6394
  </div>
6396
6395
  `);
6397
6396
  }
6398
- const fields = await getCollectionFields(db2, collectionId);
6397
+ const fields = await getCollectionFields(db, collectionId);
6399
6398
  const data = {};
6400
6399
  const errors = {};
6401
6400
  for (const field of fields) {
@@ -6453,7 +6452,7 @@ adminContentRoutes.post("/", async (c) => {
6453
6452
  const scheduledUnpublishAt = formData.get("scheduled_unpublish_at");
6454
6453
  const contentId = crypto.randomUUID();
6455
6454
  const now = Date.now();
6456
- const insertStmt = db2.prepare(`
6455
+ const insertStmt = db.prepare(`
6457
6456
  INSERT INTO content (
6458
6457
  id, collection_id, slug, title, data, status,
6459
6458
  scheduled_publish_at, scheduled_unpublish_at,
@@ -6479,7 +6478,7 @@ adminContentRoutes.post("/", async (c) => {
6479
6478
  ).run();
6480
6479
  const cache = getCacheService(CACHE_CONFIGS.content);
6481
6480
  await cache.invalidate(`content:list:${collectionId}:*`);
6482
- const versionStmt = db2.prepare(`
6481
+ const versionStmt = db.prepare(`
6483
6482
  INSERT INTO content_versions (id, content_id, version, data, author_id, created_at)
6484
6483
  VALUES (?, ?, ?, ?, ?, ?)
6485
6484
  `);
@@ -6491,7 +6490,7 @@ adminContentRoutes.post("/", async (c) => {
6491
6490
  user?.userId || "unknown",
6492
6491
  now
6493
6492
  ).run();
6494
- const workflowStmt = db2.prepare(`
6493
+ const workflowStmt = db.prepare(`
6495
6494
  INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, created_at)
6496
6495
  VALUES (?, ?, ?, ?, ?, ?, ?)
6497
6496
  `);
@@ -6529,8 +6528,8 @@ adminContentRoutes.put("/:id", async (c) => {
6529
6528
  const user = c.get("user");
6530
6529
  const formData = await c.req.formData();
6531
6530
  const action = formData.get("action");
6532
- const db2 = c.env.DB;
6533
- const contentStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
6531
+ const db = c.env.DB;
6532
+ const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?");
6534
6533
  const existingContent = await contentStmt.bind(id).first();
6535
6534
  if (!existingContent) {
6536
6535
  return c.html(html`
@@ -6539,7 +6538,7 @@ adminContentRoutes.put("/:id", async (c) => {
6539
6538
  </div>
6540
6539
  `);
6541
6540
  }
6542
- const collection = await getCollection(db2, existingContent.collection_id);
6541
+ const collection = await getCollection(db, existingContent.collection_id);
6543
6542
  if (!collection) {
6544
6543
  return c.html(html`
6545
6544
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
@@ -6547,7 +6546,7 @@ adminContentRoutes.put("/:id", async (c) => {
6547
6546
  </div>
6548
6547
  `);
6549
6548
  }
6550
- const fields = await getCollectionFields(db2, existingContent.collection_id);
6549
+ const fields = await getCollectionFields(db, existingContent.collection_id);
6551
6550
  const data = {};
6552
6551
  const errors = {};
6553
6552
  for (const field of fields) {
@@ -6606,7 +6605,7 @@ adminContentRoutes.put("/:id", async (c) => {
6606
6605
  const scheduledPublishAt = formData.get("scheduled_publish_at");
6607
6606
  const scheduledUnpublishAt = formData.get("scheduled_unpublish_at");
6608
6607
  const now = Date.now();
6609
- const updateStmt = db2.prepare(`
6608
+ const updateStmt = db.prepare(`
6610
6609
  UPDATE content SET
6611
6610
  slug = ?, title = ?, data = ?, status = ?,
6612
6611
  scheduled_publish_at = ?, scheduled_unpublish_at = ?,
@@ -6630,10 +6629,10 @@ adminContentRoutes.put("/:id", async (c) => {
6630
6629
  await cache.invalidate(`content:list:${existingContent.collection_id}:*`);
6631
6630
  const existingData = JSON.parse(existingContent.data || "{}");
6632
6631
  if (JSON.stringify(existingData) !== JSON.stringify(data)) {
6633
- const versionCountStmt = db2.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?");
6632
+ const versionCountStmt = db.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?");
6634
6633
  const versionResult = await versionCountStmt.bind(id).first();
6635
6634
  const nextVersion = (versionResult?.max_version || 0) + 1;
6636
- const versionStmt = db2.prepare(`
6635
+ const versionStmt = db.prepare(`
6637
6636
  INSERT INTO content_versions (id, content_id, version, data, author_id, created_at)
6638
6637
  VALUES (?, ?, ?, ?, ?, ?)
6639
6638
  `);
@@ -6647,7 +6646,7 @@ adminContentRoutes.put("/:id", async (c) => {
6647
6646
  ).run();
6648
6647
  }
6649
6648
  if (status !== existingContent.status) {
6650
- const workflowStmt = db2.prepare(`
6649
+ const workflowStmt = db.prepare(`
6651
6650
  INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, created_at)
6652
6651
  VALUES (?, ?, ?, ?, ?, ?, ?)
6653
6652
  `);
@@ -6684,12 +6683,12 @@ adminContentRoutes.post("/preview", async (c) => {
6684
6683
  try {
6685
6684
  const formData = await c.req.formData();
6686
6685
  const collectionId = formData.get("collection_id");
6687
- const db2 = c.env.DB;
6688
- const collection = await getCollection(db2, collectionId);
6686
+ const db = c.env.DB;
6687
+ const collection = await getCollection(db, collectionId);
6689
6688
  if (!collection) {
6690
6689
  return c.html("<p>Collection not found</p>");
6691
6690
  }
6692
- const fields = await getCollectionFields(db2, collectionId);
6691
+ const fields = await getCollectionFields(db, collectionId);
6693
6692
  const data = {};
6694
6693
  for (const field of fields) {
6695
6694
  const value = formData.get(field.field_name);
@@ -6763,8 +6762,8 @@ adminContentRoutes.post("/duplicate", async (c) => {
6763
6762
  if (!originalId) {
6764
6763
  return c.json({ success: false, error: "Content ID required" });
6765
6764
  }
6766
- const db2 = c.env.DB;
6767
- const contentStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
6765
+ const db = c.env.DB;
6766
+ const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?");
6768
6767
  const original = await contentStmt.bind(originalId).first();
6769
6768
  if (!original) {
6770
6769
  return c.json({ success: false, error: "Content not found" });
@@ -6773,7 +6772,7 @@ adminContentRoutes.post("/duplicate", async (c) => {
6773
6772
  const now = Date.now();
6774
6773
  const originalData = JSON.parse(original.data || "{}");
6775
6774
  originalData.title = `${originalData.title || "Untitled"} (Copy)`;
6776
- const insertStmt = db2.prepare(`
6775
+ const insertStmt = db.prepare(`
6777
6776
  INSERT INTO content (
6778
6777
  id, collection_id, slug, title, data, status,
6779
6778
  author_id, created_at, updated_at
@@ -6896,11 +6895,11 @@ adminContentRoutes.post("/bulk-action", async (c) => {
6896
6895
  if (!action || !ids || ids.length === 0) {
6897
6896
  return c.json({ success: false, error: "Action and IDs required" });
6898
6897
  }
6899
- const db2 = c.env.DB;
6898
+ const db = c.env.DB;
6900
6899
  const now = Date.now();
6901
6900
  if (action === "delete") {
6902
6901
  const placeholders = ids.map(() => "?").join(",");
6903
- const stmt = db2.prepare(`
6902
+ const stmt = db.prepare(`
6904
6903
  UPDATE content
6905
6904
  SET status = 'deleted', updated_at = ?
6906
6905
  WHERE id IN (${placeholders})
@@ -6909,7 +6908,7 @@ adminContentRoutes.post("/bulk-action", async (c) => {
6909
6908
  } else if (action === "publish" || action === "draft") {
6910
6909
  const placeholders = ids.map(() => "?").join(",");
6911
6910
  const publishedAt = action === "publish" ? now : null;
6912
- const stmt = db2.prepare(`
6911
+ const stmt = db.prepare(`
6913
6912
  UPDATE content
6914
6913
  SET status = ?, published_at = ?, updated_at = ?
6915
6914
  WHERE id IN (${placeholders})
@@ -6932,15 +6931,15 @@ adminContentRoutes.post("/bulk-action", async (c) => {
6932
6931
  adminContentRoutes.delete("/:id", async (c) => {
6933
6932
  try {
6934
6933
  const id = c.req.param("id");
6935
- const db2 = c.env.DB;
6934
+ const db = c.env.DB;
6936
6935
  const user = c.get("user");
6937
- const contentStmt = db2.prepare("SELECT id, title FROM content WHERE id = ?");
6936
+ const contentStmt = db.prepare("SELECT id, title FROM content WHERE id = ?");
6938
6937
  const content = await contentStmt.bind(id).first();
6939
6938
  if (!content) {
6940
6939
  return c.json({ success: false, error: "Content not found" }, 404);
6941
6940
  }
6942
6941
  const now = Date.now();
6943
- const deleteStmt = db2.prepare(`
6942
+ const deleteStmt = db.prepare(`
6944
6943
  UPDATE content
6945
6944
  SET status = 'deleted', updated_at = ?
6946
6945
  WHERE id = ?
@@ -6969,13 +6968,13 @@ adminContentRoutes.delete("/:id", async (c) => {
6969
6968
  adminContentRoutes.get("/:id/versions", async (c) => {
6970
6969
  try {
6971
6970
  const id = c.req.param("id");
6972
- const db2 = c.env.DB;
6973
- const contentStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
6971
+ const db = c.env.DB;
6972
+ const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?");
6974
6973
  const content = await contentStmt.bind(id).first();
6975
6974
  if (!content) {
6976
6975
  return c.html("<p>Content not found</p>");
6977
6976
  }
6978
- const versionsStmt = db2.prepare(`
6977
+ const versionsStmt = db.prepare(`
6979
6978
  SELECT cv.*, u.first_name, u.last_name, u.email
6980
6979
  FROM content_versions cv
6981
6980
  LEFT JOIN users u ON cv.author_id = u.id
@@ -7012,8 +7011,8 @@ adminContentRoutes.post("/:id/restore/:version", async (c) => {
7012
7011
  const id = c.req.param("id");
7013
7012
  const version = parseInt(c.req.param("version"));
7014
7013
  const user = c.get("user");
7015
- const db2 = c.env.DB;
7016
- const versionStmt = db2.prepare(`
7014
+ const db = c.env.DB;
7015
+ const versionStmt = db.prepare(`
7017
7016
  SELECT * FROM content_versions
7018
7017
  WHERE content_id = ? AND version = ?
7019
7018
  `);
@@ -7021,14 +7020,14 @@ adminContentRoutes.post("/:id/restore/:version", async (c) => {
7021
7020
  if (!versionData) {
7022
7021
  return c.json({ success: false, error: "Version not found" });
7023
7022
  }
7024
- const contentStmt = db2.prepare("SELECT * FROM content WHERE id = ?");
7023
+ const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?");
7025
7024
  const currentContent = await contentStmt.bind(id).first();
7026
7025
  if (!currentContent) {
7027
7026
  return c.json({ success: false, error: "Content not found" });
7028
7027
  }
7029
7028
  const restoredData = JSON.parse(versionData.data);
7030
7029
  const now = Date.now();
7031
- const updateStmt = db2.prepare(`
7030
+ const updateStmt = db.prepare(`
7032
7031
  UPDATE content SET
7033
7032
  title = ?, data = ?, updated_at = ?
7034
7033
  WHERE id = ?
@@ -7039,10 +7038,10 @@ adminContentRoutes.post("/:id/restore/:version", async (c) => {
7039
7038
  now,
7040
7039
  id
7041
7040
  ).run();
7042
- const nextVersionStmt = db2.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?");
7041
+ const nextVersionStmt = db.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?");
7043
7042
  const nextVersionResult = await nextVersionStmt.bind(id).first();
7044
7043
  const nextVersion = (nextVersionResult?.max_version || 0) + 1;
7045
- const newVersionStmt = db2.prepare(`
7044
+ const newVersionStmt = db.prepare(`
7046
7045
  INSERT INTO content_versions (id, content_id, version, data, author_id, created_at)
7047
7046
  VALUES (?, ?, ?, ?, ?, ?)
7048
7047
  `);
@@ -7054,7 +7053,7 @@ adminContentRoutes.post("/:id/restore/:version", async (c) => {
7054
7053
  user?.userId || "unknown",
7055
7054
  now
7056
7055
  ).run();
7057
- const workflowStmt = db2.prepare(`
7056
+ const workflowStmt = db.prepare(`
7058
7057
  INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, comment, created_at)
7059
7058
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
7060
7059
  `);
@@ -7078,8 +7077,8 @@ adminContentRoutes.get("/:id/version/:version/preview", async (c) => {
7078
7077
  try {
7079
7078
  const id = c.req.param("id");
7080
7079
  const version = parseInt(c.req.param("version"));
7081
- const db2 = c.env.DB;
7082
- const versionStmt = db2.prepare(`
7080
+ const db = c.env.DB;
7081
+ const versionStmt = db.prepare(`
7083
7082
  SELECT cv.*, c.collection_id, col.display_name as collection_name
7084
7083
  FROM content_versions cv
7085
7084
  JOIN content c ON cv.content_id = c.id
@@ -9000,9 +8999,9 @@ var ROLES = [
9000
8999
  ];
9001
9000
  userRoutes.get("/profile", async (c) => {
9002
9001
  const user = c.get("user");
9003
- const db2 = c.env.DB;
9002
+ const db = c.env.DB;
9004
9003
  try {
9005
- const userStmt = db2.prepare(`
9004
+ const userStmt = db.prepare(`
9006
9005
  SELECT id, email, username, first_name, last_name, phone, bio, avatar_url,
9007
9006
  timezone, language, theme, email_notifications, two_factor_enabled,
9008
9007
  role, created_at, last_login_at
@@ -9060,7 +9059,7 @@ userRoutes.get("/profile", async (c) => {
9060
9059
  });
9061
9060
  userRoutes.put("/profile", async (c) => {
9062
9061
  const user = c.get("user");
9063
- const db2 = c.env.DB;
9062
+ const db = c.env.DB;
9064
9063
  try {
9065
9064
  const formData = await c.req.formData();
9066
9065
  const firstName = sanitizeInput(formData.get("first_name")?.toString());
@@ -9087,7 +9086,7 @@ userRoutes.put("/profile", async (c) => {
9087
9086
  dismissible: true
9088
9087
  }));
9089
9088
  }
9090
- const checkStmt = db2.prepare(`
9089
+ const checkStmt = db.prepare(`
9091
9090
  SELECT id FROM users
9092
9091
  WHERE (username = ? OR email = ?) AND id != ? AND is_active = 1
9093
9092
  `);
@@ -9099,7 +9098,7 @@ userRoutes.put("/profile", async (c) => {
9099
9098
  dismissible: true
9100
9099
  }));
9101
9100
  }
9102
- const updateStmt = db2.prepare(`
9101
+ const updateStmt = db.prepare(`
9103
9102
  UPDATE users SET
9104
9103
  first_name = ?, last_name = ?, username = ?, email = ?,
9105
9104
  phone = ?, bio = ?, timezone = ?, language = ?,
@@ -9120,7 +9119,7 @@ userRoutes.put("/profile", async (c) => {
9120
9119
  user.userId
9121
9120
  ).run();
9122
9121
  await logActivity(
9123
- db2,
9122
+ db,
9124
9123
  user.userId,
9125
9124
  "profile.update",
9126
9125
  "users",
@@ -9145,7 +9144,7 @@ userRoutes.put("/profile", async (c) => {
9145
9144
  });
9146
9145
  userRoutes.post("/profile/avatar", async (c) => {
9147
9146
  const user = c.get("user");
9148
- const db2 = c.env.DB;
9147
+ const db = c.env.DB;
9149
9148
  try {
9150
9149
  const formData = await c.req.formData();
9151
9150
  const avatarFile = formData.get("avatar");
@@ -9173,17 +9172,17 @@ userRoutes.post("/profile/avatar", async (c) => {
9173
9172
  }));
9174
9173
  }
9175
9174
  const avatarUrl = `/uploads/avatars/${user.userId}-${Date.now()}.${avatarFile.type.split("/")[1]}`;
9176
- const updateStmt = db2.prepare(`
9175
+ const updateStmt = db.prepare(`
9177
9176
  UPDATE users SET avatar_url = ?, updated_at = ?
9178
9177
  WHERE id = ?
9179
9178
  `);
9180
9179
  await updateStmt.bind(avatarUrl, Date.now(), user.userId).run();
9181
- const userStmt = db2.prepare(`
9180
+ const userStmt = db.prepare(`
9182
9181
  SELECT first_name, last_name FROM users WHERE id = ?
9183
9182
  `);
9184
9183
  const userData = await userStmt.bind(user.userId).first();
9185
9184
  await logActivity(
9186
- db2,
9185
+ db,
9187
9186
  user.userId,
9188
9187
  "profile.avatar_update",
9189
9188
  "users",
@@ -9215,7 +9214,7 @@ userRoutes.post("/profile/avatar", async (c) => {
9215
9214
  });
9216
9215
  userRoutes.post("/profile/password", async (c) => {
9217
9216
  const user = c.get("user");
9218
- const db2 = c.env.DB;
9217
+ const db = c.env.DB;
9219
9218
  try {
9220
9219
  const formData = await c.req.formData();
9221
9220
  const currentPassword = formData.get("current_password")?.toString() || "";
@@ -9242,7 +9241,7 @@ userRoutes.post("/profile/password", async (c) => {
9242
9241
  dismissible: true
9243
9242
  }));
9244
9243
  }
9245
- const userStmt = db2.prepare(`
9244
+ const userStmt = db.prepare(`
9246
9245
  SELECT password_hash FROM users WHERE id = ? AND is_active = 1
9247
9246
  `);
9248
9247
  const userData = await userStmt.bind(user.userId).first();
@@ -9262,7 +9261,7 @@ userRoutes.post("/profile/password", async (c) => {
9262
9261
  }));
9263
9262
  }
9264
9263
  const newPasswordHash = await AuthManager.hashPassword(newPassword);
9265
- const historyStmt = db2.prepare(`
9264
+ const historyStmt = db.prepare(`
9266
9265
  INSERT INTO password_history (id, user_id, password_hash, created_at)
9267
9266
  VALUES (?, ?, ?, ?)
9268
9267
  `);
@@ -9272,13 +9271,13 @@ userRoutes.post("/profile/password", async (c) => {
9272
9271
  userData.password_hash,
9273
9272
  Date.now()
9274
9273
  ).run();
9275
- const updateStmt = db2.prepare(`
9274
+ const updateStmt = db.prepare(`
9276
9275
  UPDATE users SET password_hash = ?, updated_at = ?
9277
9276
  WHERE id = ?
9278
9277
  `);
9279
9278
  await updateStmt.bind(newPasswordHash, Date.now(), user.userId).run();
9280
9279
  await logActivity(
9281
- db2,
9280
+ db,
9282
9281
  user.userId,
9283
9282
  "profile.password_change",
9284
9283
  "users",
@@ -9302,7 +9301,7 @@ userRoutes.post("/profile/password", async (c) => {
9302
9301
  }
9303
9302
  });
9304
9303
  userRoutes.get("/users", async (c) => {
9305
- const db2 = c.env.DB;
9304
+ const db = c.env.DB;
9306
9305
  const user = c.get("user");
9307
9306
  try {
9308
9307
  const page = parseInt(c.req.query("page") || "1");
@@ -9329,7 +9328,7 @@ userRoutes.get("/users", async (c) => {
9329
9328
  whereClause += " AND u.role = ?";
9330
9329
  params.push(roleFilter);
9331
9330
  }
9332
- const usersStmt = db2.prepare(`
9331
+ const usersStmt = db.prepare(`
9333
9332
  SELECT u.id, u.email, u.username, u.first_name, u.last_name,
9334
9333
  u.role, u.avatar_url, u.created_at, u.last_login_at, u.updated_at,
9335
9334
  u.email_verified, u.two_factor_enabled, u.is_active
@@ -9339,13 +9338,13 @@ userRoutes.get("/users", async (c) => {
9339
9338
  LIMIT ? OFFSET ?
9340
9339
  `);
9341
9340
  const { results: usersData } = await usersStmt.bind(...params, limit, offset).all();
9342
- const countStmt = db2.prepare(`
9341
+ const countStmt = db.prepare(`
9343
9342
  SELECT COUNT(*) as total FROM users u ${whereClause}
9344
9343
  `);
9345
9344
  const countResult = await countStmt.bind(...params).first();
9346
9345
  const totalUsers = countResult?.total || 0;
9347
9346
  await logActivity(
9348
- db2,
9347
+ db,
9349
9348
  user.userId,
9350
9349
  "users.list_view",
9351
9350
  "users",
@@ -9442,7 +9441,7 @@ userRoutes.get("/users/new", async (c) => {
9442
9441
  }
9443
9442
  });
9444
9443
  userRoutes.post("/users/new", async (c) => {
9445
- const db2 = c.env.DB;
9444
+ const db = c.env.DB;
9446
9445
  const user = c.get("user");
9447
9446
  try {
9448
9447
  const formData = await c.req.formData();
@@ -9486,7 +9485,7 @@ userRoutes.post("/users/new", async (c) => {
9486
9485
  dismissible: true
9487
9486
  }));
9488
9487
  }
9489
- const checkStmt = db2.prepare(`
9488
+ const checkStmt = db.prepare(`
9490
9489
  SELECT id FROM users
9491
9490
  WHERE username = ? OR email = ?
9492
9491
  `);
@@ -9500,7 +9499,7 @@ userRoutes.post("/users/new", async (c) => {
9500
9499
  }
9501
9500
  const passwordHash = await AuthManager.hashPassword(password);
9502
9501
  const userId = crypto.randomUUID();
9503
- const createStmt = db2.prepare(`
9502
+ const createStmt = db.prepare(`
9504
9503
  INSERT INTO users (
9505
9504
  id, email, username, first_name, last_name, phone, bio,
9506
9505
  password_hash, role, is_active, email_verified, created_at, updated_at
@@ -9522,7 +9521,7 @@ userRoutes.post("/users/new", async (c) => {
9522
9521
  Date.now()
9523
9522
  ).run();
9524
9523
  await logActivity(
9525
- db2,
9524
+ db,
9526
9525
  user.userId,
9527
9526
  "user!.create",
9528
9527
  "users",
@@ -9545,11 +9544,11 @@ userRoutes.get("/users/:id", async (c) => {
9545
9544
  if (c.req.path.endsWith("/edit")) {
9546
9545
  return c.notFound();
9547
9546
  }
9548
- const db2 = c.env.DB;
9547
+ const db = c.env.DB;
9549
9548
  const user = c.get("user");
9550
9549
  const userId = c.req.param("id");
9551
9550
  try {
9552
- const userStmt = db2.prepare(`
9551
+ const userStmt = db.prepare(`
9553
9552
  SELECT id, email, username, first_name, last_name, phone, bio, avatar_url,
9554
9553
  role, is_active, email_verified, two_factor_enabled, created_at, last_login_at
9555
9554
  FROM users
@@ -9560,7 +9559,7 @@ userRoutes.get("/users/:id", async (c) => {
9560
9559
  return c.json({ error: "User not found" }, 404);
9561
9560
  }
9562
9561
  await logActivity(
9563
- db2,
9562
+ db,
9564
9563
  user.userId,
9565
9564
  "user!.view",
9566
9565
  "users",
@@ -9593,11 +9592,11 @@ userRoutes.get("/users/:id", async (c) => {
9593
9592
  }
9594
9593
  });
9595
9594
  userRoutes.get("/users/:id/edit", async (c) => {
9596
- const db2 = c.env.DB;
9595
+ const db = c.env.DB;
9597
9596
  const user = c.get("user");
9598
9597
  const userId = c.req.param("id");
9599
9598
  try {
9600
- const userStmt = db2.prepare(`
9599
+ const userStmt = db.prepare(`
9601
9600
  SELECT id, email, username, first_name, last_name, phone, bio, avatar_url,
9602
9601
  role, is_active, email_verified, two_factor_enabled, created_at, last_login_at
9603
9602
  FROM users
@@ -9647,7 +9646,7 @@ userRoutes.get("/users/:id/edit", async (c) => {
9647
9646
  }
9648
9647
  });
9649
9648
  userRoutes.put("/users/:id", async (c) => {
9650
- const db2 = c.env.DB;
9649
+ const db = c.env.DB;
9651
9650
  const user = c.get("user");
9652
9651
  const userId = c.req.param("id");
9653
9652
  try {
@@ -9676,7 +9675,7 @@ userRoutes.put("/users/:id", async (c) => {
9676
9675
  dismissible: true
9677
9676
  }));
9678
9677
  }
9679
- const checkStmt = db2.prepare(`
9678
+ const checkStmt = db.prepare(`
9680
9679
  SELECT id FROM users
9681
9680
  WHERE (username = ? OR email = ?) AND id != ?
9682
9681
  `);
@@ -9688,7 +9687,7 @@ userRoutes.put("/users/:id", async (c) => {
9688
9687
  dismissible: true
9689
9688
  }));
9690
9689
  }
9691
- const updateStmt = db2.prepare(`
9690
+ const updateStmt = db.prepare(`
9692
9691
  UPDATE users SET
9693
9692
  first_name = ?, last_name = ?, username = ?, email = ?,
9694
9693
  phone = ?, bio = ?, role = ?, is_active = ?, email_verified = ?,
@@ -9709,7 +9708,7 @@ userRoutes.put("/users/:id", async (c) => {
9709
9708
  userId
9710
9709
  ).run();
9711
9710
  await logActivity(
9712
- db2,
9711
+ db,
9713
9712
  user.userId,
9714
9713
  "user!.update",
9715
9714
  "users",
@@ -9733,7 +9732,7 @@ userRoutes.put("/users/:id", async (c) => {
9733
9732
  }
9734
9733
  });
9735
9734
  userRoutes.post("/users/:id/toggle", async (c) => {
9736
- const db2 = c.env.DB;
9735
+ const db = c.env.DB;
9737
9736
  const user = c.get("user");
9738
9737
  const userId = c.req.param("id");
9739
9738
  try {
@@ -9742,19 +9741,19 @@ userRoutes.post("/users/:id/toggle", async (c) => {
9742
9741
  if (userId === user.userId && !active) {
9743
9742
  return c.json({ error: "You cannot deactivate your own account" }, 400);
9744
9743
  }
9745
- const userStmt = db2.prepare(`
9744
+ const userStmt = db.prepare(`
9746
9745
  SELECT id, email FROM users WHERE id = ?
9747
9746
  `);
9748
9747
  const userToToggle = await userStmt.bind(userId).first();
9749
9748
  if (!userToToggle) {
9750
9749
  return c.json({ error: "User not found" }, 404);
9751
9750
  }
9752
- const toggleStmt = db2.prepare(`
9751
+ const toggleStmt = db.prepare(`
9753
9752
  UPDATE users SET is_active = ?, updated_at = ? WHERE id = ?
9754
9753
  `);
9755
9754
  await toggleStmt.bind(active ? 1 : 0, Date.now(), userId).run();
9756
9755
  await logActivity(
9757
- db2,
9756
+ db,
9758
9757
  user.userId,
9759
9758
  active ? "user.activate" : "user.deactivate",
9760
9759
  "users",
@@ -9773,7 +9772,7 @@ userRoutes.post("/users/:id/toggle", async (c) => {
9773
9772
  }
9774
9773
  });
9775
9774
  userRoutes.delete("/users/:id", async (c) => {
9776
- const db2 = c.env.DB;
9775
+ const db = c.env.DB;
9777
9776
  const user = c.get("user");
9778
9777
  const userId = c.req.param("id");
9779
9778
  try {
@@ -9782,7 +9781,7 @@ userRoutes.delete("/users/:id", async (c) => {
9782
9781
  if (userId === user.userId) {
9783
9782
  return c.json({ error: "You cannot delete your own account" }, 400);
9784
9783
  }
9785
- const userStmt = db2.prepare(`
9784
+ const userStmt = db.prepare(`
9786
9785
  SELECT id, email FROM users WHERE id = ?
9787
9786
  `);
9788
9787
  const userToDelete = await userStmt.bind(userId).first();
@@ -9790,12 +9789,12 @@ userRoutes.delete("/users/:id", async (c) => {
9790
9789
  return c.json({ error: "User not found" }, 404);
9791
9790
  }
9792
9791
  if (hardDelete) {
9793
- const deleteStmt = db2.prepare(`
9792
+ const deleteStmt = db.prepare(`
9794
9793
  DELETE FROM users WHERE id = ?
9795
9794
  `);
9796
9795
  await deleteStmt.bind(userId).run();
9797
9796
  await logActivity(
9798
- db2,
9797
+ db,
9799
9798
  user.userId,
9800
9799
  "user!.hard_delete",
9801
9800
  "users",
@@ -9809,12 +9808,12 @@ userRoutes.delete("/users/:id", async (c) => {
9809
9808
  message: "User permanently deleted"
9810
9809
  });
9811
9810
  } else {
9812
- const deleteStmt = db2.prepare(`
9811
+ const deleteStmt = db.prepare(`
9813
9812
  UPDATE users SET is_active = 0, updated_at = ? WHERE id = ?
9814
9813
  `);
9815
9814
  await deleteStmt.bind(Date.now(), userId).run();
9816
9815
  await logActivity(
9817
- db2,
9816
+ db,
9818
9817
  user.userId,
9819
9818
  "user!.soft_delete",
9820
9819
  "users",
@@ -9834,7 +9833,7 @@ userRoutes.delete("/users/:id", async (c) => {
9834
9833
  }
9835
9834
  });
9836
9835
  userRoutes.post("/invite-user", async (c) => {
9837
- const db2 = c.env.DB;
9836
+ const db = c.env.DB;
9838
9837
  const user = c.get("user");
9839
9838
  try {
9840
9839
  const formData = await c.req.formData();
@@ -9849,7 +9848,7 @@ userRoutes.post("/invite-user", async (c) => {
9849
9848
  if (!emailRegex.test(email)) {
9850
9849
  return c.json({ error: "Please enter a valid email address" }, 400);
9851
9850
  }
9852
- const existingUserStmt = db2.prepare(`
9851
+ const existingUserStmt = db.prepare(`
9853
9852
  SELECT id FROM users WHERE email = ?
9854
9853
  `);
9855
9854
  const existingUser = await existingUserStmt.bind(email).first();
@@ -9858,7 +9857,7 @@ userRoutes.post("/invite-user", async (c) => {
9858
9857
  }
9859
9858
  const invitationToken = crypto.randomUUID();
9860
9859
  const userId = crypto.randomUUID();
9861
- const createUserStmt = db2.prepare(`
9860
+ const createUserStmt = db.prepare(`
9862
9861
  INSERT INTO users (
9863
9862
  id, email, first_name, last_name, role,
9864
9863
  invitation_token, invited_by, invited_at,
@@ -9880,7 +9879,7 @@ userRoutes.post("/invite-user", async (c) => {
9880
9879
  Date.now()
9881
9880
  ).run();
9882
9881
  await logActivity(
9883
- db2,
9882
+ db,
9884
9883
  user.userId,
9885
9884
  "user!.invite_sent",
9886
9885
  "users",
@@ -9909,11 +9908,11 @@ userRoutes.post("/invite-user", async (c) => {
9909
9908
  }
9910
9909
  });
9911
9910
  userRoutes.post("/resend-invitation/:id", async (c) => {
9912
- const db2 = c.env.DB;
9911
+ const db = c.env.DB;
9913
9912
  const user = c.get("user");
9914
9913
  const userId = c.req.param("id");
9915
9914
  try {
9916
- const userStmt = db2.prepare(`
9915
+ const userStmt = db.prepare(`
9917
9916
  SELECT id, email, first_name, last_name, role, invitation_token
9918
9917
  FROM users
9919
9918
  WHERE id = ? AND is_active = 0 AND invitation_token IS NOT NULL
@@ -9923,7 +9922,7 @@ userRoutes.post("/resend-invitation/:id", async (c) => {
9923
9922
  return c.json({ error: "User not found or invitation not valid" }, 404);
9924
9923
  }
9925
9924
  const newInvitationToken = crypto.randomUUID();
9926
- const updateStmt = db2.prepare(`
9925
+ const updateStmt = db.prepare(`
9927
9926
  UPDATE users SET
9928
9927
  invitation_token = ?,
9929
9928
  invited_at = ?,
@@ -9937,7 +9936,7 @@ userRoutes.post("/resend-invitation/:id", async (c) => {
9937
9936
  userId
9938
9937
  ).run();
9939
9938
  await logActivity(
9940
- db2,
9939
+ db,
9941
9940
  user.userId,
9942
9941
  "user!.invitation_resent",
9943
9942
  "users",
@@ -9958,11 +9957,11 @@ userRoutes.post("/resend-invitation/:id", async (c) => {
9958
9957
  }
9959
9958
  });
9960
9959
  userRoutes.delete("/cancel-invitation/:id", async (c) => {
9961
- const db2 = c.env.DB;
9960
+ const db = c.env.DB;
9962
9961
  const user = c.get("user");
9963
9962
  const userId = c.req.param("id");
9964
9963
  try {
9965
- const userStmt = db2.prepare(`
9964
+ const userStmt = db.prepare(`
9966
9965
  SELECT id, email FROM users
9967
9966
  WHERE id = ? AND is_active = 0 AND invitation_token IS NOT NULL
9968
9967
  `);
@@ -9970,10 +9969,10 @@ userRoutes.delete("/cancel-invitation/:id", async (c) => {
9970
9969
  if (!invitedUser) {
9971
9970
  return c.json({ error: "User not found or invitation not valid" }, 404);
9972
9971
  }
9973
- const deleteStmt = db2.prepare(`DELETE FROM users WHERE id = ?`);
9972
+ const deleteStmt = db.prepare(`DELETE FROM users WHERE id = ?`);
9974
9973
  await deleteStmt.bind(userId).run();
9975
9974
  await logActivity(
9976
- db2,
9975
+ db,
9977
9976
  user.userId,
9978
9977
  "user!.invitation_cancelled",
9979
9978
  "users",
@@ -9992,7 +9991,7 @@ userRoutes.delete("/cancel-invitation/:id", async (c) => {
9992
9991
  }
9993
9992
  });
9994
9993
  userRoutes.get("/activity-logs", async (c) => {
9995
- const db2 = c.env.DB;
9994
+ const db = c.env.DB;
9996
9995
  const user = c.get("user");
9997
9996
  try {
9998
9997
  const page = parseInt(c.req.query("page") || "1");
@@ -10030,7 +10029,7 @@ userRoutes.get("/activity-logs", async (c) => {
10030
10029
  params.push(toTimestamp);
10031
10030
  }
10032
10031
  const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : "";
10033
- const logsStmt = db2.prepare(`
10032
+ const logsStmt = db.prepare(`
10034
10033
  SELECT
10035
10034
  al.id, al.user_id, al.action, al.resource_type, al.resource_id,
10036
10035
  al.details, al.ip_address, al.user_agent, al.created_at,
@@ -10043,7 +10042,7 @@ userRoutes.get("/activity-logs", async (c) => {
10043
10042
  LIMIT ? OFFSET ?
10044
10043
  `);
10045
10044
  const { results: logs } = await logsStmt.bind(...params, limit, offset).all();
10046
- const countStmt = db2.prepare(`
10045
+ const countStmt = db.prepare(`
10047
10046
  SELECT COUNT(*) as total
10048
10047
  FROM activity_logs al
10049
10048
  LEFT JOIN users u ON al.user_id = u.id
@@ -10056,7 +10055,7 @@ userRoutes.get("/activity-logs", async (c) => {
10056
10055
  details: log.details ? JSON.parse(log.details) : null
10057
10056
  }));
10058
10057
  await logActivity(
10059
- db2,
10058
+ db,
10060
10059
  user.userId,
10061
10060
  "activity.logs_viewed",
10062
10061
  void 0,
@@ -10098,7 +10097,7 @@ userRoutes.get("/activity-logs", async (c) => {
10098
10097
  }
10099
10098
  });
10100
10099
  userRoutes.get("/activity-logs/export", async (c) => {
10101
- const db2 = c.env.DB;
10100
+ const db = c.env.DB;
10102
10101
  const user = c.get("user");
10103
10102
  try {
10104
10103
  const filters = {
@@ -10133,7 +10132,7 @@ userRoutes.get("/activity-logs/export", async (c) => {
10133
10132
  params.push(toTimestamp);
10134
10133
  }
10135
10134
  const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : "";
10136
- const logsStmt = db2.prepare(`
10135
+ const logsStmt = db.prepare(`
10137
10136
  SELECT
10138
10137
  al.id, al.user_id, al.action, al.resource_type, al.resource_id,
10139
10138
  al.details, al.ip_address, al.user_agent, al.created_at,
@@ -10163,7 +10162,7 @@ userRoutes.get("/activity-logs/export", async (c) => {
10163
10162
  }
10164
10163
  const csvContent = csvRows.join("\n");
10165
10164
  await logActivity(
10166
- db2,
10165
+ db,
10167
10166
  user.userId,
10168
10167
  "activity.logs_exported",
10169
10168
  void 0,
@@ -11513,7 +11512,7 @@ adminMediaRoutes.get("/", async (c) => {
11513
11512
  const ____cacheBust = searchParams.get("t");
11514
11513
  const limit = 24;
11515
11514
  const offset = (page - 1) * limit;
11516
- const db2 = c.env.DB;
11515
+ const db = c.env.DB;
11517
11516
  let query = "SELECT * FROM media";
11518
11517
  const params = [];
11519
11518
  const conditions = ["deleted_at IS NULL"];
@@ -11541,9 +11540,9 @@ adminMediaRoutes.get("/", async (c) => {
11541
11540
  query += ` WHERE ${conditions.join(" AND ")}`;
11542
11541
  }
11543
11542
  query += ` ORDER BY uploaded_at DESC LIMIT ${limit} OFFSET ${offset}`;
11544
- const stmt = db2.prepare(query);
11543
+ const stmt = db.prepare(query);
11545
11544
  const { results } = await stmt.bind(...params).all();
11546
- const foldersStmt = db2.prepare(`
11545
+ const foldersStmt = db.prepare(`
11547
11546
  SELECT folder, COUNT(*) as count, SUM(size) as totalSize
11548
11547
  FROM media
11549
11548
  WHERE deleted_at IS NULL
@@ -11551,7 +11550,7 @@ adminMediaRoutes.get("/", async (c) => {
11551
11550
  ORDER BY folder
11552
11551
  `);
11553
11552
  const { results: folders } = await foldersStmt.all();
11554
- const typesStmt = db2.prepare(`
11553
+ const typesStmt = db.prepare(`
11555
11554
  SELECT
11556
11555
  CASE
11557
11556
  WHEN mime_type LIKE 'image/%' THEN 'images'
@@ -11617,7 +11616,7 @@ adminMediaRoutes.get("/selector", async (c) => {
11617
11616
  try {
11618
11617
  const { searchParams } = new URL(c.req.url);
11619
11618
  const search = searchParams.get("search") || "";
11620
- const db2 = c.env.DB;
11619
+ const db = c.env.DB;
11621
11620
  let query = "SELECT * FROM media WHERE deleted_at IS NULL";
11622
11621
  const params = [];
11623
11622
  if (search.trim()) {
@@ -11626,7 +11625,7 @@ adminMediaRoutes.get("/selector", async (c) => {
11626
11625
  params.push(searchTerm, searchTerm, searchTerm);
11627
11626
  }
11628
11627
  query += " ORDER BY uploaded_at DESC LIMIT 24";
11629
- const stmt = db2.prepare(query);
11628
+ const stmt = db.prepare(query);
11630
11629
  const { results } = await stmt.bind(...params).all();
11631
11630
  const mediaFiles = results.map((row) => ({
11632
11631
  id: row.id,
@@ -11733,7 +11732,7 @@ adminMediaRoutes.get("/search", async (c) => {
11733
11732
  const search = searchParams.get("search") || "";
11734
11733
  const folder = searchParams.get("folder") || "all";
11735
11734
  const type = searchParams.get("type") || "all";
11736
- const db2 = c.env.DB;
11735
+ const db = c.env.DB;
11737
11736
  let query = "SELECT * FROM media";
11738
11737
  const params = [];
11739
11738
  const conditions = [];
@@ -11766,7 +11765,7 @@ adminMediaRoutes.get("/search", async (c) => {
11766
11765
  query += ` WHERE ${conditions.join(" AND ")}`;
11767
11766
  }
11768
11767
  query += ` ORDER BY uploaded_at DESC LIMIT 24`;
11769
- const stmt = db2.prepare(query);
11768
+ const stmt = db.prepare(query);
11770
11769
  const { results } = await stmt.bind(...params).all();
11771
11770
  const mediaFiles = results.map((row) => ({
11772
11771
  ...row,
@@ -11789,8 +11788,8 @@ adminMediaRoutes.get("/search", async (c) => {
11789
11788
  adminMediaRoutes.get("/:id/details", async (c) => {
11790
11789
  try {
11791
11790
  const id = c.req.param("id");
11792
- const db2 = c.env.DB;
11793
- const stmt = db2.prepare("SELECT * FROM media WHERE id = ?");
11791
+ const db = c.env.DB;
11792
+ const stmt = db.prepare("SELECT * FROM media WHERE id = ?");
11794
11793
  const result = await stmt.bind(id).first();
11795
11794
  if (!result) {
11796
11795
  return c.html('<div class="text-red-500">File not found</div>');
@@ -11827,7 +11826,13 @@ adminMediaRoutes.post("/upload", async (c) => {
11827
11826
  try {
11828
11827
  const user = c.get("user");
11829
11828
  const formData = await c.req.formData();
11830
- const files = formData.getAll("files");
11829
+ const fileEntries = formData.getAll("files");
11830
+ const files = [];
11831
+ for (const entry of fileEntries) {
11832
+ if (entry instanceof File) {
11833
+ files.push(entry);
11834
+ }
11835
+ }
11831
11836
  if (!files || files.length === 0) {
11832
11837
  return c.html(html`
11833
11838
  <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
@@ -11863,7 +11868,7 @@ adminMediaRoutes.post("/upload", async (c) => {
11863
11868
  });
11864
11869
  continue;
11865
11870
  }
11866
- const fileId = globalThis.crypto.randomUUID();
11871
+ const fileId = crypto.randomUUID();
11867
11872
  const fileExtension = file.name.split(".").pop() || "";
11868
11873
  const filename = `${fileId}.${fileExtension}`;
11869
11874
  const folder = formData.get("folder") || "uploads";
@@ -11936,10 +11941,11 @@ adminMediaRoutes.post("/upload", async (c) => {
11936
11941
  });
11937
11942
  }
11938
11943
  }
11939
- let __mediaGridHTML = "";
11944
+ let mediaGridHTML = "";
11940
11945
  if (uploadResults.length > 0) {
11941
11946
  try {
11942
- const folder = formData.get("folder") || "uploads";
11947
+ const folderEntry = formData.get("folder");
11948
+ const folder = typeof folderEntry === "string" ? folderEntry : "uploads";
11943
11949
  const query = "SELECT * FROM media WHERE deleted_at IS NULL ORDER BY uploaded_at DESC LIMIT 24";
11944
11950
  const stmt = c.env.DB.prepare(query);
11945
11951
  const { results } = await stmt.all();
@@ -12082,13 +12088,13 @@ adminMediaRoutes.put("/:id", async (c) => {
12082
12088
  });
12083
12089
  adminMediaRoutes.delete("/cleanup", requireRole("admin"), async (c) => {
12084
12090
  try {
12085
- const db2 = c.env.DB;
12086
- const allMediaStmt = db2.prepare("SELECT id, r2_key, filename FROM media WHERE deleted_at IS NULL");
12091
+ const db = c.env.DB;
12092
+ const allMediaStmt = db.prepare("SELECT id, r2_key, filename FROM media WHERE deleted_at IS NULL");
12087
12093
  const { results: allMedia } = await allMediaStmt.all();
12088
- const contentStmt = db2.prepare("SELECT data FROM content");
12094
+ const contentStmt = db.prepare("SELECT data FROM content");
12089
12095
  const { results: contentRecords } = await contentStmt.all();
12090
12096
  const referencedUrls = /* @__PURE__ */ new Set();
12091
- for (const record of contentRecords) {
12097
+ for (const record of contentRecords || []) {
12092
12098
  if (record.data) {
12093
12099
  const dataStr = typeof record.data === "string" ? record.data : JSON.stringify(record.data);
12094
12100
  const urlMatches = dataStr.matchAll(/\/files\/([^\s"',]+)/g);
@@ -12097,7 +12103,8 @@ adminMediaRoutes.delete("/cleanup", requireRole("admin"), async (c) => {
12097
12103
  }
12098
12104
  }
12099
12105
  }
12100
- const unusedFiles = allMedia.filter((file) => !referencedUrls.has(file.r2_key));
12106
+ const mediaRows = allMedia || [];
12107
+ const unusedFiles = mediaRows.filter((file) => !referencedUrls.has(file.r2_key));
12101
12108
  if (unusedFiles.length === 0) {
12102
12109
  return c.html(html`
12103
12110
  <div class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded">
@@ -12115,7 +12122,7 @@ adminMediaRoutes.delete("/cleanup", requireRole("admin"), async (c) => {
12115
12122
  for (const file of unusedFiles) {
12116
12123
  try {
12117
12124
  await c.env.MEDIA_BUCKET.delete(file.r2_key);
12118
- const deleteStmt = db2.prepare("UPDATE media SET deleted_at = ? WHERE id = ?");
12125
+ const deleteStmt = db.prepare("UPDATE media SET deleted_at = ? WHERE id = ?");
12119
12126
  await deleteStmt.bind(Math.floor(Date.now() / 1e3), file.id).run();
12120
12127
  deletedCount++;
12121
12128
  } catch (error) {
@@ -13781,11 +13788,11 @@ var AVAILABLE_PLUGINS = [
13781
13788
  adminPluginRoutes.get("/", async (c) => {
13782
13789
  try {
13783
13790
  const user = c.get("user");
13784
- const db2 = c.env.DB;
13791
+ const db = c.env.DB;
13785
13792
  if (user?.role !== "admin") {
13786
13793
  return c.text("Access denied", 403);
13787
13794
  }
13788
- const pluginService = new PluginService(db2);
13795
+ const pluginService = new PluginService(db);
13789
13796
  let installedPlugins = [];
13790
13797
  let stats = { total: 0, active: 0, inactive: 0, errors: 0, uninstalled: 0 };
13791
13798
  try {
@@ -13852,12 +13859,12 @@ adminPluginRoutes.get("/", async (c) => {
13852
13859
  adminPluginRoutes.get("/:id", async (c) => {
13853
13860
  try {
13854
13861
  const user = c.get("user");
13855
- const db2 = c.env.DB;
13862
+ const db = c.env.DB;
13856
13863
  const pluginId = c.req.param("id");
13857
13864
  if (user?.role !== "admin") {
13858
13865
  return c.redirect("/admin/plugins");
13859
13866
  }
13860
- const pluginService = new PluginService(db2);
13867
+ const pluginService = new PluginService(db);
13861
13868
  const plugin = await pluginService.getPlugin(pluginId);
13862
13869
  if (!plugin) {
13863
13870
  return c.text("Plugin not found", 404);
@@ -13906,12 +13913,12 @@ adminPluginRoutes.get("/:id", async (c) => {
13906
13913
  adminPluginRoutes.post("/:id/activate", async (c) => {
13907
13914
  try {
13908
13915
  const user = c.get("user");
13909
- const db2 = c.env.DB;
13916
+ const db = c.env.DB;
13910
13917
  const pluginId = c.req.param("id");
13911
13918
  if (user?.role !== "admin") {
13912
13919
  return c.json({ error: "Access denied" }, 403);
13913
13920
  }
13914
- const pluginService = new PluginService(db2);
13921
+ const pluginService = new PluginService(db);
13915
13922
  await pluginService.activatePlugin(pluginId);
13916
13923
  return c.json({ success: true });
13917
13924
  } catch (error) {
@@ -13923,12 +13930,12 @@ adminPluginRoutes.post("/:id/activate", async (c) => {
13923
13930
  adminPluginRoutes.post("/:id/deactivate", async (c) => {
13924
13931
  try {
13925
13932
  const user = c.get("user");
13926
- const db2 = c.env.DB;
13933
+ const db = c.env.DB;
13927
13934
  const pluginId = c.req.param("id");
13928
13935
  if (user?.role !== "admin") {
13929
13936
  return c.json({ error: "Access denied" }, 403);
13930
13937
  }
13931
- const pluginService = new PluginService(db2);
13938
+ const pluginService = new PluginService(db);
13932
13939
  await pluginService.deactivatePlugin(pluginId);
13933
13940
  return c.json({ success: true });
13934
13941
  } catch (error) {
@@ -13940,12 +13947,12 @@ adminPluginRoutes.post("/:id/deactivate", async (c) => {
13940
13947
  adminPluginRoutes.post("/install", async (c) => {
13941
13948
  try {
13942
13949
  const user = c.get("user");
13943
- const db2 = c.env.DB;
13950
+ const db = c.env.DB;
13944
13951
  if (user?.role !== "admin") {
13945
13952
  return c.json({ error: "Access denied" }, 403);
13946
13953
  }
13947
13954
  const body = await c.req.json();
13948
- const pluginService = new PluginService(db2);
13955
+ const pluginService = new PluginService(db);
13949
13956
  if (body.name === "faq-plugin") {
13950
13957
  const faqPlugin = await pluginService.installPlugin({
13951
13958
  id: "third-party-faq",
@@ -14156,12 +14163,12 @@ adminPluginRoutes.post("/install", async (c) => {
14156
14163
  adminPluginRoutes.post("/:id/uninstall", async (c) => {
14157
14164
  try {
14158
14165
  const user = c.get("user");
14159
- const db2 = c.env.DB;
14166
+ const db = c.env.DB;
14160
14167
  const pluginId = c.req.param("id");
14161
14168
  if (user?.role !== "admin") {
14162
14169
  return c.json({ error: "Access denied" }, 403);
14163
14170
  }
14164
- const pluginService = new PluginService(db2);
14171
+ const pluginService = new PluginService(db);
14165
14172
  await pluginService.uninstallPlugin(pluginId);
14166
14173
  return c.json({ success: true });
14167
14174
  } catch (error) {
@@ -14173,13 +14180,13 @@ adminPluginRoutes.post("/:id/uninstall", async (c) => {
14173
14180
  adminPluginRoutes.post("/:id/settings", async (c) => {
14174
14181
  try {
14175
14182
  const user = c.get("user");
14176
- const db2 = c.env.DB;
14183
+ const db = c.env.DB;
14177
14184
  const pluginId = c.req.param("id");
14178
14185
  if (user?.role !== "admin") {
14179
14186
  return c.json({ error: "Access denied" }, 403);
14180
14187
  }
14181
14188
  const settings = await c.req.json();
14182
- const pluginService = new PluginService(db2);
14189
+ const pluginService = new PluginService(db);
14183
14190
  await pluginService.updatePluginSettings(pluginId, settings);
14184
14191
  return c.json({ success: true });
14185
14192
  } catch (error) {
@@ -15640,8 +15647,8 @@ adminTestimonialsRoutes.get("/", async (c) => {
15640
15647
  const currentPage = parseInt(page, 10) || 1;
15641
15648
  const limit = 20;
15642
15649
  const offset = (currentPage - 1) * limit;
15643
- const db2 = c.env?.DB;
15644
- if (!db2) {
15650
+ const db = c.env?.DB;
15651
+ if (!db) {
15645
15652
  return c.html(renderTestimonialsList({
15646
15653
  testimonials: [],
15647
15654
  totalCount: 0,
@@ -15672,7 +15679,7 @@ adminTestimonialsRoutes.get("/", async (c) => {
15672
15679
  params.push(searchTerm, searchTerm, searchTerm);
15673
15680
  }
15674
15681
  const countQuery = `SELECT COUNT(*) as count FROM testimonials ${whereClause}`;
15675
- const { results: countResults } = await db2.prepare(countQuery).bind(...params).all();
15682
+ const { results: countResults } = await db.prepare(countQuery).bind(...params).all();
15676
15683
  const totalCount = countResults?.[0]?.count || 0;
15677
15684
  const dataQuery = `
15678
15685
  SELECT * FROM testimonials
@@ -15680,7 +15687,7 @@ adminTestimonialsRoutes.get("/", async (c) => {
15680
15687
  ORDER BY sortOrder ASC, created_at DESC
15681
15688
  LIMIT ? OFFSET ?
15682
15689
  `;
15683
- const { results: testimonials } = await db2.prepare(dataQuery).bind(...params, limit, offset).all();
15690
+ const { results: testimonials } = await db.prepare(dataQuery).bind(...params, limit, offset).all();
15684
15691
  const totalPages = Math.ceil(totalCount / limit);
15685
15692
  return c.html(renderTestimonialsList({
15686
15693
  testimonials: testimonials || [],
@@ -15728,8 +15735,8 @@ adminTestimonialsRoutes.post("/", async (c) => {
15728
15735
  const data = Object.fromEntries(formData.entries());
15729
15736
  const validatedData = testimonialSchema.parse(data);
15730
15737
  const user = c.get("user");
15731
- const db2 = c.env?.DB;
15732
- if (!db2) {
15738
+ const db = c.env?.DB;
15739
+ if (!db) {
15733
15740
  return c.html(renderTestimonialsForm({
15734
15741
  isEdit: false,
15735
15742
  user: user ? {
@@ -15741,7 +15748,7 @@ adminTestimonialsRoutes.post("/", async (c) => {
15741
15748
  messageType: "error"
15742
15749
  }));
15743
15750
  }
15744
- const { results } = await db2.prepare(`
15751
+ const { results } = await db.prepare(`
15745
15752
  INSERT INTO testimonials (author_name, author_title, author_company, testimonial_text, rating, isPublished, sortOrder)
15746
15753
  VALUES (?, ?, ?, ?, ?, ?, ?)
15747
15754
  RETURNING *
@@ -15773,7 +15780,7 @@ adminTestimonialsRoutes.post("/", async (c) => {
15773
15780
  const user = c.get("user");
15774
15781
  if (error instanceof z.ZodError) {
15775
15782
  const errors = {};
15776
- error.errors.forEach((err) => {
15783
+ error.issues.forEach((err) => {
15777
15784
  const field = err.path[0];
15778
15785
  if (!errors[field]) errors[field] = [];
15779
15786
  errors[field].push(err.message);
@@ -15806,8 +15813,8 @@ adminTestimonialsRoutes.get("/:id", async (c) => {
15806
15813
  try {
15807
15814
  const id = parseInt(c.req.param("id"));
15808
15815
  const user = c.get("user");
15809
- const db2 = c.env?.DB;
15810
- if (!db2) {
15816
+ const db = c.env?.DB;
15817
+ if (!db) {
15811
15818
  return c.html(renderTestimonialsForm({
15812
15819
  isEdit: true,
15813
15820
  user: user ? {
@@ -15819,7 +15826,7 @@ adminTestimonialsRoutes.get("/:id", async (c) => {
15819
15826
  messageType: "error"
15820
15827
  }));
15821
15828
  }
15822
- const { results } = await db2.prepare("SELECT * FROM testimonials WHERE id = ?").bind(id).all();
15829
+ const { results } = await db.prepare("SELECT * FROM testimonials WHERE id = ?").bind(id).all();
15823
15830
  if (!results || results.length === 0) {
15824
15831
  return c.redirect("/admin/testimonials?message=Testimonial not found&type=error");
15825
15832
  }
@@ -15864,8 +15871,8 @@ adminTestimonialsRoutes.put("/:id", async (c) => {
15864
15871
  const data = Object.fromEntries(formData.entries());
15865
15872
  const validatedData = testimonialSchema.parse(data);
15866
15873
  const user = c.get("user");
15867
- const db2 = c.env?.DB;
15868
- if (!db2) {
15874
+ const db = c.env?.DB;
15875
+ if (!db) {
15869
15876
  return c.html(renderTestimonialsForm({
15870
15877
  isEdit: true,
15871
15878
  user: user ? {
@@ -15877,7 +15884,7 @@ adminTestimonialsRoutes.put("/:id", async (c) => {
15877
15884
  messageType: "error"
15878
15885
  }));
15879
15886
  }
15880
- const { results } = await db2.prepare(`
15887
+ const { results } = await db.prepare(`
15881
15888
  UPDATE testimonials
15882
15889
  SET author_name = ?, author_title = ?, author_company = ?, testimonial_text = ?, rating = ?, isPublished = ?, sortOrder = ?
15883
15890
  WHERE id = ?
@@ -15922,7 +15929,7 @@ adminTestimonialsRoutes.put("/:id", async (c) => {
15922
15929
  const id = parseInt(c.req.param("id"));
15923
15930
  if (error instanceof z.ZodError) {
15924
15931
  const errors = {};
15925
- error.errors.forEach((err) => {
15932
+ error.issues.forEach((err) => {
15926
15933
  const field = err.path[0];
15927
15934
  if (!errors[field]) errors[field] = [];
15928
15935
  errors[field].push(err.message);
@@ -15974,11 +15981,11 @@ adminTestimonialsRoutes.put("/:id", async (c) => {
15974
15981
  adminTestimonialsRoutes.delete("/:id", async (c) => {
15975
15982
  try {
15976
15983
  const id = parseInt(c.req.param("id"));
15977
- const db2 = c.env?.DB;
15978
- if (!db2) {
15984
+ const db = c.env?.DB;
15985
+ if (!db) {
15979
15986
  return c.json({ error: "Database not available" }, 500);
15980
15987
  }
15981
- const { changes } = await db2.prepare("DELETE FROM testimonials WHERE id = ?").bind(id).run();
15988
+ const { changes } = await db.prepare("DELETE FROM testimonials WHERE id = ?").bind(id).run();
15982
15989
  if (changes === 0) {
15983
15990
  return c.json({ error: "Testimonial not found" }, 404);
15984
15991
  }
@@ -16310,8 +16317,8 @@ adminCodeExamplesRoutes.get("/", async (c) => {
16310
16317
  const currentPage = parseInt(page, 10) || 1;
16311
16318
  const limit = 20;
16312
16319
  const offset = (currentPage - 1) * limit;
16313
- const db2 = c.env?.DB;
16314
- if (!db2) {
16320
+ const db = c.env?.DB;
16321
+ if (!db) {
16315
16322
  return c.html(renderCodeExamplesList({
16316
16323
  codeExamples: [],
16317
16324
  totalCount: 0,
@@ -16342,7 +16349,7 @@ adminCodeExamplesRoutes.get("/", async (c) => {
16342
16349
  params.push(searchTerm, searchTerm, searchTerm, searchTerm);
16343
16350
  }
16344
16351
  const countQuery = `SELECT COUNT(*) as count FROM code_examples ${whereClause}`;
16345
- const { results: countResults } = await db2.prepare(countQuery).bind(...params).all();
16352
+ const { results: countResults } = await db.prepare(countQuery).bind(...params).all();
16346
16353
  const totalCount = countResults?.[0]?.count || 0;
16347
16354
  const dataQuery = `
16348
16355
  SELECT * FROM code_examples
@@ -16350,7 +16357,7 @@ adminCodeExamplesRoutes.get("/", async (c) => {
16350
16357
  ORDER BY sortOrder ASC, created_at DESC
16351
16358
  LIMIT ? OFFSET ?
16352
16359
  `;
16353
- const { results: codeExamples } = await db2.prepare(dataQuery).bind(...params, limit, offset).all();
16360
+ const { results: codeExamples } = await db.prepare(dataQuery).bind(...params, limit, offset).all();
16354
16361
  const totalPages = Math.ceil(totalCount / limit);
16355
16362
  return c.html(renderCodeExamplesList({
16356
16363
  codeExamples: codeExamples || [],
@@ -16398,8 +16405,8 @@ adminCodeExamplesRoutes.post("/", async (c) => {
16398
16405
  const data = Object.fromEntries(formData.entries());
16399
16406
  const validatedData = codeExampleSchema.parse(data);
16400
16407
  const user = c.get("user");
16401
- const db2 = c.env?.DB;
16402
- if (!db2) {
16408
+ const db = c.env?.DB;
16409
+ if (!db) {
16403
16410
  return c.html(renderCodeExamplesForm({
16404
16411
  isEdit: false,
16405
16412
  user: user ? {
@@ -16411,7 +16418,7 @@ adminCodeExamplesRoutes.post("/", async (c) => {
16411
16418
  messageType: "error"
16412
16419
  }));
16413
16420
  }
16414
- const { results } = await db2.prepare(`
16421
+ const { results } = await db.prepare(`
16415
16422
  INSERT INTO code_examples (title, description, code, language, category, tags, isPublished, sortOrder)
16416
16423
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
16417
16424
  RETURNING *
@@ -16444,7 +16451,7 @@ adminCodeExamplesRoutes.post("/", async (c) => {
16444
16451
  const user = c.get("user");
16445
16452
  if (error instanceof z.ZodError) {
16446
16453
  const errors = {};
16447
- error.errors.forEach((err) => {
16454
+ error.issues.forEach((err) => {
16448
16455
  const field = err.path[0];
16449
16456
  if (!errors[field]) errors[field] = [];
16450
16457
  errors[field].push(err.message);
@@ -16477,8 +16484,8 @@ adminCodeExamplesRoutes.get("/:id", async (c) => {
16477
16484
  try {
16478
16485
  const id = parseInt(c.req.param("id"));
16479
16486
  const user = c.get("user");
16480
- const db2 = c.env?.DB;
16481
- if (!db2) {
16487
+ const db = c.env?.DB;
16488
+ if (!db) {
16482
16489
  return c.html(renderCodeExamplesForm({
16483
16490
  isEdit: true,
16484
16491
  user: user ? {
@@ -16490,7 +16497,7 @@ adminCodeExamplesRoutes.get("/:id", async (c) => {
16490
16497
  messageType: "error"
16491
16498
  }));
16492
16499
  }
16493
- const { results } = await db2.prepare("SELECT * FROM code_examples WHERE id = ?").bind(id).all();
16500
+ const { results } = await db.prepare("SELECT * FROM code_examples WHERE id = ?").bind(id).all();
16494
16501
  if (!results || results.length === 0) {
16495
16502
  return c.redirect("/admin/code-examples?message=Code example not found&type=error");
16496
16503
  }
@@ -16536,8 +16543,8 @@ adminCodeExamplesRoutes.put("/:id", async (c) => {
16536
16543
  const data = Object.fromEntries(formData.entries());
16537
16544
  const validatedData = codeExampleSchema.parse(data);
16538
16545
  const user = c.get("user");
16539
- const db2 = c.env?.DB;
16540
- if (!db2) {
16546
+ const db = c.env?.DB;
16547
+ if (!db) {
16541
16548
  return c.html(renderCodeExamplesForm({
16542
16549
  isEdit: true,
16543
16550
  user: user ? {
@@ -16549,7 +16556,7 @@ adminCodeExamplesRoutes.put("/:id", async (c) => {
16549
16556
  messageType: "error"
16550
16557
  }));
16551
16558
  }
16552
- const { results } = await db2.prepare(`
16559
+ const { results } = await db.prepare(`
16553
16560
  UPDATE code_examples
16554
16561
  SET title = ?, description = ?, code = ?, language = ?, category = ?, tags = ?, isPublished = ?, sortOrder = ?
16555
16562
  WHERE id = ?
@@ -16596,7 +16603,7 @@ adminCodeExamplesRoutes.put("/:id", async (c) => {
16596
16603
  const id = parseInt(c.req.param("id"));
16597
16604
  if (error instanceof z.ZodError) {
16598
16605
  const errors = {};
16599
- error.errors.forEach((err) => {
16606
+ error.issues.forEach((err) => {
16600
16607
  const field = err.path[0];
16601
16608
  if (!errors[field]) errors[field] = [];
16602
16609
  errors[field].push(err.message);
@@ -16650,11 +16657,11 @@ adminCodeExamplesRoutes.put("/:id", async (c) => {
16650
16657
  adminCodeExamplesRoutes.delete("/:id", async (c) => {
16651
16658
  try {
16652
16659
  const id = parseInt(c.req.param("id"));
16653
- const db2 = c.env?.DB;
16654
- if (!db2) {
16660
+ const db = c.env?.DB;
16661
+ if (!db) {
16655
16662
  return c.json({ error: "Database not available" }, 500);
16656
16663
  }
16657
- const { changes } = await db2.prepare("DELETE FROM code_examples WHERE id = ?").bind(id).run();
16664
+ const { changes } = await db.prepare("DELETE FROM code_examples WHERE id = ?").bind(id).run();
16658
16665
  if (changes === 0) {
16659
16666
  return c.json({ error: "Code example not found" }, 404);
16660
16667
  }
@@ -17333,10 +17340,10 @@ router.get("/", async (c) => {
17333
17340
  });
17334
17341
  router.get("/stats", async (c) => {
17335
17342
  try {
17336
- const db2 = c.env.DB;
17343
+ const db = c.env.DB;
17337
17344
  let collectionsCount = 0;
17338
17345
  try {
17339
- const collectionsStmt = db2.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1");
17346
+ const collectionsStmt = db.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1");
17340
17347
  const collectionsResult = await collectionsStmt.first();
17341
17348
  collectionsCount = collectionsResult?.count || 0;
17342
17349
  } catch (error) {
@@ -17344,7 +17351,7 @@ router.get("/stats", async (c) => {
17344
17351
  }
17345
17352
  let contentCount = 0;
17346
17353
  try {
17347
- const contentStmt = db2.prepare("SELECT COUNT(*) as count FROM content");
17354
+ const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content");
17348
17355
  const contentResult = await contentStmt.first();
17349
17356
  contentCount = contentResult?.count || 0;
17350
17357
  } catch (error) {
@@ -17353,7 +17360,7 @@ router.get("/stats", async (c) => {
17353
17360
  let mediaCount = 0;
17354
17361
  let mediaSize = 0;
17355
17362
  try {
17356
- const mediaStmt = db2.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
17363
+ const mediaStmt = db.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
17357
17364
  const mediaResult = await mediaStmt.first();
17358
17365
  mediaCount = mediaResult?.count || 0;
17359
17366
  mediaSize = mediaResult?.total_size || 0;
@@ -17362,7 +17369,7 @@ router.get("/stats", async (c) => {
17362
17369
  }
17363
17370
  let usersCount = 0;
17364
17371
  try {
17365
- const usersStmt = db2.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
17372
+ const usersStmt = db.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
17366
17373
  const usersResult = await usersStmt.first();
17367
17374
  usersCount = usersResult?.count || 0;
17368
17375
  } catch (error) {
@@ -17383,17 +17390,17 @@ router.get("/stats", async (c) => {
17383
17390
  });
17384
17391
  router.get("/storage", async (c) => {
17385
17392
  try {
17386
- const db2 = c.env.DB;
17393
+ const db = c.env.DB;
17387
17394
  let databaseSize = 0;
17388
17395
  try {
17389
- const result = await db2.prepare("SELECT 1").run();
17396
+ const result = await db.prepare("SELECT 1").run();
17390
17397
  databaseSize = result?.meta?.size_after || 0;
17391
17398
  } catch (error) {
17392
17399
  console.error("Error fetching database size:", error);
17393
17400
  }
17394
17401
  let mediaSize = 0;
17395
17402
  try {
17396
- const mediaStmt = db2.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
17403
+ const mediaStmt = db.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL");
17397
17404
  const mediaResult = await mediaStmt.first();
17398
17405
  mediaSize = mediaResult?.total_size || 0;
17399
17406
  } catch (error) {
@@ -17408,9 +17415,9 @@ router.get("/storage", async (c) => {
17408
17415
  });
17409
17416
  router.get("/recent-activity", async (c) => {
17410
17417
  try {
17411
- const db2 = c.env.DB;
17418
+ const db = c.env.DB;
17412
17419
  const limit = parseInt(c.req.query("limit") || "5");
17413
- const activityStmt = db2.prepare(`
17420
+ const activityStmt = db.prepare(`
17414
17421
  SELECT
17415
17422
  a.id,
17416
17423
  a.action,
@@ -19063,13 +19070,13 @@ adminCollectionsRoutes.use("*", requireAuth());
19063
19070
  adminCollectionsRoutes.get("/", async (c) => {
19064
19071
  try {
19065
19072
  const user = c.get("user");
19066
- const db2 = c.env.DB;
19073
+ const db = c.env.DB;
19067
19074
  const url = new URL(c.req.url);
19068
19075
  const search = url.searchParams.get("search") || "";
19069
19076
  let stmt;
19070
19077
  let results;
19071
19078
  if (search) {
19072
- stmt = db2.prepare(`
19079
+ stmt = db.prepare(`
19073
19080
  SELECT id, name, display_name, description, created_at, managed, schema
19074
19081
  FROM collections
19075
19082
  WHERE is_active = 1
@@ -19080,11 +19087,11 @@ adminCollectionsRoutes.get("/", async (c) => {
19080
19087
  const queryResults = await stmt.bind(searchParam, searchParam, searchParam).all();
19081
19088
  results = queryResults.results;
19082
19089
  } else {
19083
- stmt = db2.prepare("SELECT id, name, display_name, description, created_at, managed, schema FROM collections WHERE is_active = 1 ORDER BY created_at DESC");
19090
+ stmt = db.prepare("SELECT id, name, display_name, description, created_at, managed, schema FROM collections WHERE is_active = 1 ORDER BY created_at DESC");
19084
19091
  const queryResults = await stmt.all();
19085
19092
  results = queryResults.results;
19086
19093
  }
19087
- const fieldCountStmt = db2.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id");
19094
+ const fieldCountStmt = db.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id");
19088
19095
  const { results: fieldCountResults } = await fieldCountStmt.all();
19089
19096
  const fieldCounts = new Map((fieldCountResults || []).map((row) => [String(row.collection_id), Number(row.count)]));
19090
19097
  const collections = (results || []).filter((row) => row && row.id).map((row) => {
@@ -19125,16 +19132,17 @@ adminCollectionsRoutes.get("/", async (c) => {
19125
19132
  return c.html(renderCollectionsListPage(pageData));
19126
19133
  } catch (error) {
19127
19134
  console.error("Error fetching collections:", error);
19128
- return c.html(html`<p>Error loading collections</p>`);
19135
+ const errorMessage = error instanceof Error ? error.message : String(error);
19136
+ return c.html(html`<p>Error loading collections: ${errorMessage}</p>`);
19129
19137
  }
19130
19138
  });
19131
19139
  adminCollectionsRoutes.get("/new", async (c) => {
19132
19140
  const user = c.get("user");
19133
- const db2 = c.env.DB;
19141
+ const db = c.env.DB;
19134
19142
  const [tinymceActive, quillActive, mdxeditorActive] = await Promise.all([
19135
- isPluginActive2(db2, "tinymce-plugin"),
19136
- isPluginActive2(db2, "quill-editor"),
19137
- isPluginActive2(db2, "easy-mdx")
19143
+ isPluginActive2(db, "tinymce-plugin"),
19144
+ isPluginActive2(db, "quill-editor"),
19145
+ isPluginActive2(db, "easy-mdx")
19138
19146
  ]);
19139
19147
  console.log("[Collections /new] Editor plugins status:", {
19140
19148
  tinymce: tinymceActive,
@@ -19188,8 +19196,8 @@ adminCollectionsRoutes.post("/", async (c) => {
19188
19196
  return c.redirect("/admin/collections/new");
19189
19197
  }
19190
19198
  }
19191
- const db2 = c.env.DB;
19192
- const existingStmt = db2.prepare("SELECT id FROM collections WHERE name = ?");
19199
+ const db = c.env.DB;
19200
+ const existingStmt = db.prepare("SELECT id FROM collections WHERE name = ?");
19193
19201
  const existing = await existingStmt.bind(name).first();
19194
19202
  if (existing) {
19195
19203
  const errorMsg = "A collection with this name already exists.";
@@ -19225,9 +19233,9 @@ adminCollectionsRoutes.post("/", async (c) => {
19225
19233
  },
19226
19234
  required: ["title"]
19227
19235
  };
19228
- const collectionId = globalThis.crypto.randomUUID();
19236
+ const collectionId = crypto.randomUUID();
19229
19237
  const now = Date.now();
19230
- const insertStmt = db2.prepare(`
19238
+ const insertStmt = db.prepare(`
19231
19239
  INSERT INTO collections (id, name, display_name, description, schema, is_active, created_at, updated_at)
19232
19240
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
19233
19241
  `);
@@ -19279,17 +19287,17 @@ adminCollectionsRoutes.post("/", async (c) => {
19279
19287
  }
19280
19288
  });
19281
19289
  adminCollectionsRoutes.get("/:id", async (c) => {
19290
+ const db = c.env.DB;
19282
19291
  try {
19283
19292
  const id = c.req.param("id");
19284
19293
  const user = c.get("user");
19285
- const db2 = c.env.DB;
19286
- const stmt = db2.prepare("SELECT * FROM collections WHERE id = ?");
19294
+ const stmt = db.prepare("SELECT * FROM collections WHERE id = ?");
19287
19295
  const collection = await stmt.bind(id).first();
19288
19296
  if (!collection) {
19289
19297
  const [tinymceActive2, quillActive2, mdxeditorActive2] = await Promise.all([
19290
- isPluginActive2(db2, "tinymce-plugin"),
19291
- isPluginActive2(db2, "quill-editor"),
19292
- isPluginActive2(db2, "easy-mdx")
19298
+ isPluginActive2(db, "tinymce-plugin"),
19299
+ isPluginActive2(db, "quill-editor"),
19300
+ isPluginActive2(db, "easy-mdx")
19293
19301
  ]);
19294
19302
  const formData2 = {
19295
19303
  isEdit: true,
@@ -19330,7 +19338,7 @@ adminCollectionsRoutes.get("/:id", async (c) => {
19330
19338
  }
19331
19339
  }
19332
19340
  if (fields.length === 0) {
19333
- const fieldsStmt = db2.prepare(`
19341
+ const fieldsStmt = db.prepare(`
19334
19342
  SELECT * FROM content_fields
19335
19343
  WHERE collection_id = ?
19336
19344
  ORDER BY field_order ASC
@@ -19359,9 +19367,9 @@ adminCollectionsRoutes.get("/:id", async (c) => {
19359
19367
  });
19360
19368
  }
19361
19369
  const [tinymceActive, quillActive, mdxeditorActive] = await Promise.all([
19362
- isPluginActive2(db2, "tinymce-plugin"),
19363
- isPluginActive2(db2, "quill-editor"),
19364
- isPluginActive2(db2, "easy-mdx")
19370
+ isPluginActive2(db, "tinymce-plugin"),
19371
+ isPluginActive2(db, "quill-editor"),
19372
+ isPluginActive2(db, "easy-mdx")
19365
19373
  ]);
19366
19374
  console.log("[Collections /:id] Editor plugins status:", {
19367
19375
  tinymce: tinymceActive,
@@ -19428,8 +19436,8 @@ adminCollectionsRoutes.put("/:id", async (c) => {
19428
19436
  </div>
19429
19437
  `);
19430
19438
  }
19431
- const db2 = c.env.DB;
19432
- const updateStmt = db2.prepare(`
19439
+ const db = c.env.DB;
19440
+ const updateStmt = db.prepare(`
19433
19441
  UPDATE collections
19434
19442
  SET display_name = ?, description = ?, updated_at = ?
19435
19443
  WHERE id = ?
@@ -19452,8 +19460,8 @@ adminCollectionsRoutes.put("/:id", async (c) => {
19452
19460
  adminCollectionsRoutes.delete("/:id", async (c) => {
19453
19461
  try {
19454
19462
  const id = c.req.param("id");
19455
- const db2 = c.env.DB;
19456
- const contentStmt = db2.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?");
19463
+ const db = c.env.DB;
19464
+ const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?");
19457
19465
  const contentResult = await contentStmt.bind(id).first();
19458
19466
  if (contentResult && contentResult.count > 0) {
19459
19467
  return c.html(html`
@@ -19462,9 +19470,9 @@ adminCollectionsRoutes.delete("/:id", async (c) => {
19462
19470
  </div>
19463
19471
  `);
19464
19472
  }
19465
- const deleteFieldsStmt = db2.prepare("DELETE FROM content_fields WHERE collection_id = ?");
19473
+ const deleteFieldsStmt = db.prepare("DELETE FROM content_fields WHERE collection_id = ?");
19466
19474
  await deleteFieldsStmt.bind(id).run();
19467
- const deleteStmt = db2.prepare("DELETE FROM collections WHERE id = ?");
19475
+ const deleteStmt = db.prepare("DELETE FROM collections WHERE id = ?");
19468
19476
  await deleteStmt.bind(id).run();
19469
19477
  return c.html(html`
19470
19478
  <script>
@@ -19496,18 +19504,18 @@ adminCollectionsRoutes.post("/:id/fields", async (c) => {
19496
19504
  if (!/^[a-z0-9_]+$/.test(fieldName)) {
19497
19505
  return c.json({ success: false, error: "Field name must contain only lowercase letters, numbers, and underscores." });
19498
19506
  }
19499
- const db2 = c.env.DB;
19500
- const existingStmt = db2.prepare("SELECT id FROM content_fields WHERE collection_id = ? AND field_name = ?");
19507
+ const db = c.env.DB;
19508
+ const existingStmt = db.prepare("SELECT id FROM content_fields WHERE collection_id = ? AND field_name = ?");
19501
19509
  const existing = await existingStmt.bind(collectionId, fieldName).first();
19502
19510
  if (existing) {
19503
19511
  return c.json({ success: false, error: "A field with this name already exists." });
19504
19512
  }
19505
- const orderStmt = db2.prepare("SELECT MAX(field_order) as max_order FROM content_fields WHERE collection_id = ?");
19513
+ const orderStmt = db.prepare("SELECT MAX(field_order) as max_order FROM content_fields WHERE collection_id = ?");
19506
19514
  const orderResult = await orderStmt.bind(collectionId).first();
19507
19515
  const nextOrder = (orderResult?.max_order || 0) + 1;
19508
- const fieldId = globalThis.crypto.randomUUID();
19516
+ const fieldId = crypto.randomUUID();
19509
19517
  const now = Date.now();
19510
- const insertStmt = db2.prepare(`
19518
+ const insertStmt = db.prepare(`
19511
19519
  INSERT INTO content_fields (
19512
19520
  id, collection_id, field_name, field_type, field_label,
19513
19521
  field_options, field_order, is_required, is_searchable,
@@ -19556,11 +19564,11 @@ adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => {
19556
19564
  if (!fieldLabel) {
19557
19565
  return c.json({ success: false, error: "Field label is required." });
19558
19566
  }
19559
- const db2 = c.env.DB;
19567
+ const db = c.env.DB;
19560
19568
  if (fieldId.startsWith("schema-")) {
19561
19569
  const fieldName = fieldId.replace("schema-", "");
19562
19570
  console.log("[Field Update] Updating schema field:", fieldName);
19563
- const getCollectionStmt = db2.prepare("SELECT * FROM collections WHERE id = ?");
19571
+ const getCollectionStmt = db.prepare("SELECT * FROM collections WHERE id = ?");
19564
19572
  const collection = await getCollectionStmt.bind(collectionId).first();
19565
19573
  if (!collection) {
19566
19574
  return c.json({ success: false, error: "Collection not found." });
@@ -19605,7 +19613,7 @@ adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => {
19605
19613
  console.log("[Field Update] Final required array:", schema.required);
19606
19614
  console.log("[Field Update] Final field config:", schema.properties[fieldName]);
19607
19615
  }
19608
- const updateCollectionStmt = db2.prepare(`
19616
+ const updateCollectionStmt = db.prepare(`
19609
19617
  UPDATE collections
19610
19618
  SET schema = ?, updated_at = ?
19611
19619
  WHERE id = ?
@@ -19617,7 +19625,7 @@ adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => {
19617
19625
  });
19618
19626
  return c.json({ success: true });
19619
19627
  }
19620
- const updateStmt = db2.prepare(`
19628
+ const updateStmt = db.prepare(`
19621
19629
  UPDATE content_fields
19622
19630
  SET field_label = ?, field_type = ?, field_options = ?, is_required = ?, is_searchable = ?, updated_at = ?
19623
19631
  WHERE id = ?
@@ -19629,7 +19637,7 @@ adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => {
19629
19637
  changes: result.meta?.changes,
19630
19638
  last_row_id: result.meta?.last_row_id
19631
19639
  });
19632
- const verifyStmt = db2.prepare("SELECT * FROM content_fields WHERE id = ?");
19640
+ const verifyStmt = db.prepare("SELECT * FROM content_fields WHERE id = ?");
19633
19641
  const verifyResult = await verifyStmt.bind(fieldId).first();
19634
19642
  console.log("[Field Update] Verification - field after update:", verifyResult);
19635
19643
  console.log("[Field Update] Successfully updated field with type:", fieldType);
@@ -19642,8 +19650,8 @@ adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => {
19642
19650
  adminCollectionsRoutes.delete("/:collectionId/fields/:fieldId", async (c) => {
19643
19651
  try {
19644
19652
  const fieldId = c.req.param("fieldId");
19645
- const db2 = c.env.DB;
19646
- const deleteStmt = db2.prepare("DELETE FROM content_fields WHERE id = ?");
19653
+ const db = c.env.DB;
19654
+ const deleteStmt = db.prepare("DELETE FROM content_fields WHERE id = ?");
19647
19655
  await deleteStmt.bind(fieldId).run();
19648
19656
  return c.json({ success: true });
19649
19657
  } catch (error) {
@@ -19658,9 +19666,9 @@ adminCollectionsRoutes.post("/:collectionId/fields/reorder", async (c) => {
19658
19666
  if (!Array.isArray(fieldIds)) {
19659
19667
  return c.json({ success: false, error: "Invalid field order data." });
19660
19668
  }
19661
- const db2 = c.env.DB;
19669
+ const db = c.env.DB;
19662
19670
  for (let i = 0; i < fieldIds.length; i++) {
19663
- const updateStmt = db2.prepare("UPDATE content_fields SET field_order = ?, updated_at = ? WHERE id = ?");
19671
+ const updateStmt = db.prepare("UPDATE content_fields SET field_order = ?, updated_at = ? WHERE id = ?");
19664
19672
  await updateStmt.bind(i + 1, Date.now(), fieldIds[i]).run();
19665
19673
  }
19666
19674
  return c.json({ success: true });
@@ -21183,8 +21191,8 @@ adminSettingsRoutes.get("/", (c) => {
21183
21191
  });
21184
21192
  adminSettingsRoutes.get("/general", async (c) => {
21185
21193
  const user = c.get("user");
21186
- const db2 = c.env.DB;
21187
- const settingsService = new SettingsService(db2);
21194
+ const db = c.env.DB;
21195
+ const settingsService = new SettingsService(db);
21188
21196
  const generalSettings = await settingsService.getGeneralSettings(user?.email);
21189
21197
  const mockSettings = getMockSettings(user);
21190
21198
  mockSettings.general = generalSettings;
@@ -21286,8 +21294,8 @@ adminSettingsRoutes.get("/database-tools", (c) => {
21286
21294
  });
21287
21295
  adminSettingsRoutes.get("/api/migrations/status", async (c) => {
21288
21296
  try {
21289
- const db2 = c.env.DB;
21290
- const migrationService = new MigrationService(db2);
21297
+ const db = c.env.DB;
21298
+ const migrationService = new MigrationService(db);
21291
21299
  const status = await migrationService.getMigrationStatus();
21292
21300
  return c.json({
21293
21301
  success: true,
@@ -21310,8 +21318,8 @@ adminSettingsRoutes.post("/api/migrations/run", async (c) => {
21310
21318
  error: "Unauthorized. Admin access required."
21311
21319
  }, 403);
21312
21320
  }
21313
- const db2 = c.env.DB;
21314
- const migrationService = new MigrationService(db2);
21321
+ const db = c.env.DB;
21322
+ const migrationService = new MigrationService(db);
21315
21323
  const result = await migrationService.runPendingMigrations();
21316
21324
  return c.json({
21317
21325
  success: result.success,
@@ -21328,8 +21336,8 @@ adminSettingsRoutes.post("/api/migrations/run", async (c) => {
21328
21336
  });
21329
21337
  adminSettingsRoutes.get("/api/migrations/validate", async (c) => {
21330
21338
  try {
21331
- const db2 = c.env.DB;
21332
- const migrationService = new MigrationService(db2);
21339
+ const db = c.env.DB;
21340
+ const migrationService = new MigrationService(db);
21333
21341
  const validation = await migrationService.validateSchema();
21334
21342
  return c.json({
21335
21343
  success: true,
@@ -21345,8 +21353,8 @@ adminSettingsRoutes.get("/api/migrations/validate", async (c) => {
21345
21353
  });
21346
21354
  adminSettingsRoutes.get("/api/database-tools/stats", async (c) => {
21347
21355
  try {
21348
- const db2 = c.env.DB;
21349
- const tablesQuery = await db2.prepare(`
21356
+ const db = c.env.DB;
21357
+ const tablesQuery = await db.prepare(`
21350
21358
  SELECT name FROM sqlite_master
21351
21359
  WHERE type='table'
21352
21360
  AND name NOT LIKE 'sqlite_%'
@@ -21358,7 +21366,7 @@ adminSettingsRoutes.get("/api/database-tools/stats", async (c) => {
21358
21366
  const tableStats = await Promise.all(
21359
21367
  tables.map(async (table) => {
21360
21368
  try {
21361
- const countResult = await db2.prepare(`SELECT COUNT(*) as count FROM ${table.name}`).first();
21369
+ const countResult = await db.prepare(`SELECT COUNT(*) as count FROM ${table.name}`).first();
21362
21370
  const rowCount = countResult?.count || 0;
21363
21371
  totalRows += rowCount;
21364
21372
  return {
@@ -21395,8 +21403,8 @@ adminSettingsRoutes.get("/api/database-tools/stats", async (c) => {
21395
21403
  });
21396
21404
  adminSettingsRoutes.get("/api/database-tools/validate", async (c) => {
21397
21405
  try {
21398
- const db2 = c.env.DB;
21399
- const integrityResult = await db2.prepare("PRAGMA integrity_check").first();
21406
+ const db = c.env.DB;
21407
+ const integrityResult = await db.prepare("PRAGMA integrity_check").first();
21400
21408
  const isValid = integrityResult?.integrity_check === "ok";
21401
21409
  return c.json({
21402
21410
  success: true,
@@ -21451,11 +21459,11 @@ adminSettingsRoutes.post("/api/database-tools/truncate", async (c) => {
21451
21459
  error: "No tables specified for truncation"
21452
21460
  }, 400);
21453
21461
  }
21454
- const db2 = c.env.DB;
21462
+ const db = c.env.DB;
21455
21463
  const results = [];
21456
21464
  for (const tableName of tablesToTruncate) {
21457
21465
  try {
21458
- await db2.prepare(`DELETE FROM ${tableName}`).run();
21466
+ await db.prepare(`DELETE FROM ${tableName}`).run();
21459
21467
  results.push({ table: tableName, success: true });
21460
21468
  } catch (error) {
21461
21469
  console.error(`Error truncating ${tableName}:`, error);
@@ -21485,8 +21493,8 @@ adminSettingsRoutes.post("/general", async (c) => {
21485
21493
  }, 403);
21486
21494
  }
21487
21495
  const formData = await c.req.formData();
21488
- const db2 = c.env.DB;
21489
- const settingsService = new SettingsService(db2);
21496
+ const db = c.env.DB;
21497
+ const settingsService = new SettingsService(db);
21490
21498
  const settings = {
21491
21499
  siteName: formData.get("siteName"),
21492
21500
  siteDescription: formData.get("siteDescription"),
@@ -21554,5 +21562,5 @@ var ROUTES_INFO = {
21554
21562
  };
21555
21563
 
21556
21564
  export { PluginBuilder, ROUTES_INFO, adminCheckboxRoutes, adminCollectionsRoutes, adminDesignRoutes, adminLogsRoutes, adminMediaRoutes, adminPluginRoutes, adminSettingsRoutes, admin_api_default, admin_code_examples_default, admin_content_default, admin_testimonials_default, api_content_crud_default, api_default, api_media_default, api_system_default, auth_default, router, test_cleanup_default, userRoutes };
21557
- //# sourceMappingURL=chunk-R57VFNP3.js.map
21558
- //# sourceMappingURL=chunk-R57VFNP3.js.map
21565
+ //# sourceMappingURL=chunk-3ZLCMOCM.js.map
21566
+ //# sourceMappingURL=chunk-3ZLCMOCM.js.map