@beechcms/api 0.4.0-preview.11 → 0.4.0-preview.13

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 (86) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/index-CewtCjom.css +1 -0
  4. package/assets/dashboard/assets/index-FQ6JhvRH.js +554 -0
  5. package/assets/dashboard/beechLogoDark.svg +48 -48
  6. package/assets/dashboard/index.html +18 -18
  7. package/assets/dashboard/sol.svg +3 -3
  8. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  9. package/migrations/0000_v040_base.sql +213 -213
  10. package/package.json +2 -2
  11. package/src/auth/constants.ts +10 -10
  12. package/src/auth/login.ts +91 -91
  13. package/src/auth/refresh.ts +127 -127
  14. package/src/factory.ts +347 -325
  15. package/src/features/content/constants.ts +10 -10
  16. package/src/features/content/handlers/create.ts +153 -163
  17. package/src/features/content/handlers/delete.ts +76 -85
  18. package/src/features/content/handlers/facets.ts +45 -45
  19. package/src/features/content/handlers/get.ts +116 -116
  20. package/src/features/content/handlers/list.ts +88 -88
  21. package/src/features/content/handlers/update.ts +207 -216
  22. package/src/features/content/index.ts +20 -20
  23. package/src/features/draft/draft.handler.ts +272 -272
  24. package/src/features/draft/index.ts +1 -1
  25. package/src/features/email/email.provider.ts +38 -38
  26. package/src/features/email/email.service.ts +80 -80
  27. package/src/features/email/email.types.ts +98 -98
  28. package/src/features/email/index.ts +28 -28
  29. package/src/features/email/providers/resend.ts +63 -63
  30. package/src/features/email/templates/password-changed.ts +59 -59
  31. package/src/features/email/templates/password-reset.ts +64 -64
  32. package/src/features/email/templates/shell.ts +92 -93
  33. package/src/features/notifications/index.ts +1 -1
  34. package/src/features/notifications/notifications.handler.ts +130 -88
  35. package/src/features/password-reset/index.ts +15 -15
  36. package/src/features/password-reset/request.ts +106 -88
  37. package/src/features/password-reset/reset.ts +128 -110
  38. package/src/features/rotate-field/index.ts +1 -1
  39. package/src/features/rotate-field/rotate-field.handler.ts +132 -82
  40. package/src/features/rotate-field/rotate-field.schema.ts +13 -9
  41. package/src/features/schema/schema.handler.ts +16 -16
  42. package/src/features/settings/settings.handler.ts +414 -267
  43. package/src/features/setup/index.ts +96 -59
  44. package/src/features/stats/index.ts +1 -1
  45. package/src/features/stats/stats.handler.ts +458 -395
  46. package/src/index.ts +24 -24
  47. package/src/media-utils.ts +78 -78
  48. package/src/middleware/repository.middleware.ts +24 -18
  49. package/src/middleware/storage.middleware.ts +21 -0
  50. package/src/middleware.ts +67 -67
  51. package/src/public/access-policy.ts +23 -23
  52. package/src/public/api-key-middleware.ts +53 -53
  53. package/src/public/index.ts +12 -12
  54. package/src/public/problem-details.ts +48 -42
  55. package/src/public/public-add.ts +166 -166
  56. package/src/public/public-edit.ts +158 -158
  57. package/src/public/public-errors.ts +15 -15
  58. package/src/public/public-read.ts +216 -216
  59. package/src/public/public-routes.ts +84 -31
  60. package/src/public/query-builder.ts +152 -152
  61. package/src/public/rate-limit-middleware.ts +42 -42
  62. package/src/public/response-builder.ts +26 -26
  63. package/src/public/sanitize.ts +65 -65
  64. package/src/public/slug-utils.ts +14 -14
  65. package/src/search-utils.ts +192 -192
  66. package/src/search.ts +72 -72
  67. package/src/shared/activity-logger.ts +79 -79
  68. package/src/shared/apply-policies.ts +63 -63
  69. package/src/shared/base.repository.d1.ts +28 -28
  70. package/src/shared/content-utils.ts +82 -108
  71. package/src/shared/content.repository.d1.ts +382 -382
  72. package/src/shared/fts-sync.ts +4 -4
  73. package/src/shared/idempotency.repository.d1.ts +56 -45
  74. package/src/shared/media.repository.d1.ts +64 -0
  75. package/src/shared/notification-service.ts +56 -56
  76. package/src/shared/query-utils.ts +137 -137
  77. package/src/shared/storage/factory.ts +40 -0
  78. package/src/shared/storage/r2-binding-bucket.ts +81 -0
  79. package/src/shared/storage/s3-bucket.ts +163 -0
  80. package/src/shared/storage-utils.ts +36 -36
  81. package/src/shared/system-stats.repository.d1.ts +44 -0
  82. package/src/types.ts +46 -41
  83. package/src/upload.ts +179 -331
  84. package/src/widget.ts +349 -349
  85. package/assets/dashboard/assets/index-9Ch2xWJr.js +0 -554
  86. package/assets/dashboard/assets/index-ye3325L9.css +0 -1
@@ -1,395 +1,458 @@
1
- /// <reference types="@cloudflare/workers-types" />
2
- import { Hono } from 'hono'
3
- import { cleanStr } from '../../shared/query-utils'
4
- import { getBucketSize } from '../../shared/storage-utils'
5
- import { createR2Client } from '../../upload'
6
- import { publicProblem } from '../../public/problem-details'
7
- import type { Env, Variables } from '../../types'
8
-
9
- const DATABASE_ERROR = 'Database error'
10
-
11
- const statsApp = new Hono<{ Bindings: Env; Variables: Variables }>()
12
-
13
- // GET /stats/media-library - Lista tutti i file presenti in R2:
14
- // combina media_objects (upload tracciati) + URL /api/media/ nelle colonne file di ogni seed
15
- statsApp.get('/stats/media-library', async (c) => {
16
- try {
17
- const { DB } = c.env
18
- const limit = Math.min(parseInt(c.req.query('limit') ?? '12'), 100)
19
- const offset = parseInt(c.req.query('offset') ?? '0')
20
- const mediaBase = (c.env.MEDIA_BASE_URL?.trim().replace(/\/$/, '')) ?? new URL(c.req.url).origin
21
-
22
- // 1. File tracciati nella media library
23
- const mediaRows = await DB.prepare(
24
- 'SELECT key, filename, mime_type, size_bytes, created_at FROM media_objects ORDER BY created_at DESC'
25
- ).all<{ key: string; filename: string; mime_type: string; size_bytes: number; created_at: number }>()
26
-
27
- const trackedKeys = new Set<string>()
28
- const allItems: Array<{ key: string; filename: string; mime_type: string; size_bytes: number; created_at: number; url: string }> = []
29
-
30
- for (const m of mediaRows.results ?? []) {
31
- trackedKeys.add(m.key)
32
- allItems.push({ ...m, url: `${mediaBase}/api/media/${encodeURIComponent(m.key)}` })
33
- }
34
-
35
- // 2. URL /api/media/ nelle colonne file di ogni seed (v0.4.0 — colonne reali)
36
- const MEDIA_KEY_RE = /\/api\/media\/([^"'\s\\,}\]]+)/g
37
- const seeds = Object.values(c.get('seedRegistry'))
38
-
39
- for (const seed of seeds) {
40
- const fileBranches = seed.branches.filter(b => b.type === 'file')
41
- if (fileBranches.length === 0) continue
42
-
43
- const cols = fileBranches.map(b => b.alias).join(', ')
44
- const whereClause = fileBranches.map(b => `${b.alias} LIKE '%/api/media/%'`).join(' OR ')
45
-
46
- const rows = await DB.prepare(
47
- `SELECT ${cols} FROM content_${seed.slug} WHERE ${whereClause}`
48
- ).all<Record<string, string | null>>()
49
-
50
- for (const row of rows.results ?? []) {
51
- const combined = Object.values(row).filter(Boolean).join(' ')
52
- for (const match of combined.matchAll(MEDIA_KEY_RE)) {
53
- const key = decodeURIComponent(match[1])
54
- if (trackedKeys.has(key)) continue
55
- trackedKeys.add(key)
56
- const filename = key.replace(/^\d+-/, '')
57
- const ext = filename.split('.').pop()?.toLowerCase() ?? ''
58
- const mimeType = ext === 'pdf' ? 'application/pdf' : `image/${ext === 'jpg' ? 'jpeg' : ext || 'jpeg'}`
59
- const createdAt = parseInt(key.split('-')[0]) || 0
60
- allItems.push({ key, filename, mime_type: mimeType, size_bytes: 0, created_at: createdAt, url: `${mediaBase}/api/media/${encodeURIComponent(key)}` })
61
- }
62
- }
63
- }
64
-
65
- allItems.sort((a, b) => b.created_at - a.created_at)
66
- const total = allItems.length
67
- const paginated = allItems.slice(offset, offset + limit)
68
-
69
- return c.json({ items: paginated, total })
70
- } catch (err) {
71
- console.error('Media library error:', err)
72
- return c.json({ error: 'Internal Server Error' }, 500)
73
- }
74
- })
75
-
76
- // GET /stats/unused-media - Trova media in media_objects non referenziati in nessuna colonna file
77
- statsApp.get('/stats/unused-media', async (c) => {
78
- try {
79
- const { DB } = c.env
80
- const seeds = Object.values(c.get('seedRegistry'))
81
-
82
- // Tutte le chiavi media tracciate
83
- const mediaRows = await DB.prepare(
84
- 'SELECT key, filename, mime_type, size_bytes, created_at FROM media_objects ORDER BY created_at DESC'
85
- ).all<{ key: string; filename: string; mime_type: string; size_bytes: number; created_at: number }>()
86
-
87
- if (!mediaRows.results?.length) {
88
- return c.json({ items: [] })
89
- }
90
-
91
- // Raccoglie tutte le chiavi referenziate nelle colonne file di ogni seed
92
- const referencedKeys = new Set<string>()
93
- for (const seed of seeds) {
94
- const fileBranches = seed.branches.filter(b => b.type === 'file')
95
- if (fileBranches.length === 0) continue
96
- const cols = fileBranches.map(b => b.alias).join(', ')
97
- const rows = await DB.prepare(
98
- `SELECT ${cols} FROM content_${seed.slug}`
99
- ).all<Record<string, string | null>>()
100
-
101
- for (const row of rows.results ?? []) {
102
- const combined = Object.values(row).filter(Boolean).join(' ')
103
- for (const match of combined.matchAll(/\/api\/media\/([^"'\s\\,}\]]+)/g)) {
104
- referencedKeys.add(decodeURIComponent(match[1]))
105
- }
106
- }
107
- }
108
-
109
- const unused = (mediaRows.results ?? []).filter(m => !referencedKeys.has(m.key))
110
- return c.json({ items: unused })
111
- } catch (err) {
112
- console.error('Unused media error:', err)
113
- return c.json({ error: 'Internal Server Error' }, 500)
114
- }
115
- })
116
-
117
- // GET /stats/total - Statistiche globali contenuti per dashboard
118
- statsApp.get('/stats/total', async (c) => {
119
- try {
120
- const { DB } = c.env
121
- const now = Math.floor(Date.now() / 1000)
122
- const twentyFourHoursAgo = now - (24 * 60 * 60)
123
- const sevenDaysAgo = now - (7 * 24 * 60 * 60)
124
- const thirtyDaysAgo = now - (30 * 24 * 60 * 60)
125
-
126
- // Total: SUM of per-seed counts (current live entries)
127
- const seeds = Object.values(c.get('seedRegistry'))
128
- const countResults = await Promise.all(
129
- seeds.map(s => DB.prepare(`SELECT COUNT(*) as n FROM content_${s.slug}`).first<{ n: number }>())
130
- )
131
- const total = countResults.reduce((acc, r) => acc + (r?.n ?? 0), 0)
132
-
133
- // today/week/month: create events in content_event_log
134
- const eventRow = await DB.prepare(
135
- `SELECT
136
- COUNT(CASE WHEN created_at >= ? THEN 1 END) as today,
137
- COUNT(CASE WHEN created_at >= ? THEN 1 END) as week,
138
- COUNT(CASE WHEN created_at >= ? THEN 1 END) as month
139
- FROM content_event_log WHERE action = 'create'`
140
- )
141
- .bind(twentyFourHoursAgo, sevenDaysAgo, thirtyDaysAgo)
142
- .first<{ today: number; week: number; month: number }>()
143
-
144
- return c.json({
145
- total,
146
- today: eventRow?.today ?? 0,
147
- week: eventRow?.week ?? 0,
148
- month: eventRow?.month ?? 0,
149
- })
150
- } catch (err) {
151
- console.error('Content stats error:', err)
152
- return publicProblem(c, {
153
- type: 'content-database-error',
154
- title: 'Internal Server Error',
155
- status: 500,
156
- detail: DATABASE_ERROR,
157
- })
158
- }
159
- })
160
-
161
- // GET /stats/recent-activity - Ultime attività registrate nel sistema
162
- // Nessun ETag su questo endpoint: il feed di attività deve sempre essere fresco dopo
163
- // ogni mutazione. Cache-Control: no-store impedisce al browser di conservare una
164
- // risposta che potrebbe essere restituita come 304 stale.
165
- statsApp.get('/stats/recent-activity', async (c) => {
166
- try {
167
- const { DB } = c.env
168
- const slug = cleanStr(c.req.query('slug'))
169
-
170
- let query = `SELECT id, user_id, user_email, user_name, action, entity_type, entity_id, entity_slug, details, created_at
171
- FROM activity_logs`
172
- const params: any[] = []
173
-
174
- if (slug) {
175
- query += ' WHERE entity_slug = ?'
176
- params.push(slug)
177
- }
178
-
179
- query += ' ORDER BY created_at DESC LIMIT 15'
180
-
181
- const result = await DB.prepare(query).bind(...params).all()
182
-
183
- const activities = (result.results ?? []).map((row: any) => ({
184
- ...row,
185
- details: row.details ? JSON.parse(row.details) : null
186
- }))
187
-
188
- c.header('Cache-Control', 'no-store')
189
-
190
- return c.json(activities)
191
- } catch (err) {
192
- console.error('Recent activity error:', err)
193
- return publicProblem(c, {
194
- type: 'content-database-error',
195
- title: 'Internal Server Error',
196
- status: 500,
197
- detail: DATABASE_ERROR,
198
- })
199
- }
200
- })
201
-
202
- // GET /stats/health - Stato salute sistema e quote Cloudflare
203
- statsApp.get('/stats/health', async (c) => {
204
- try {
205
- const { DB } = c.env
206
-
207
- // 1. Recupera storage da system_stats (aggiornato periodicamente o via sync)
208
- let storageUsedBytes = 0
209
- try {
210
- const statsRow = await DB.prepare(
211
- "SELECT value FROM system_stats WHERE id = 'total_storage_bytes'"
212
- ).first<{ value: string }>()
213
- if (statsRow) {
214
- storageUsedBytes = parseInt(statsRow.value, 10)
215
- }
216
- } catch (err) {
217
- console.warn('Health: Could not fetch storage stats from D1:', err)
218
- }
219
-
220
- // 2. Aggregazione richieste D1 (proxy per database health) - ultimi 30 giorni
221
- const thirtyDaysAgo = Math.floor((Date.now() - 30 * 24 * 60 * 60 * 1000) / 1000)
222
- const d1Stats = await DB.prepare(
223
- `SELECT SUM(value) as total_requests FROM analytics WHERE metric = 'requests' AND seed = '' AND day_ts >= ?`
224
- ).bind(thirtyDaysAgo).first<{ total_requests: number }>()
225
-
226
- const totalRequests = d1Stats?.total_requests ?? 0
227
-
228
- // 3. Definizione limiti (Free Tier Cloudflare come riferimento)
229
- const R2_LIMIT = 10 * 1024 * 1024 * 1024 // 10GB
230
- const D1_MONTHLY_LIMIT = 1000000 // Simuliamo un limite di 1M di richieste/mese
231
-
232
- const storagePercentage = Math.min(Math.round((storageUsedBytes / R2_LIMIT) * 1000) / 10, 100)
233
- const d1Percentage = Math.min(Math.round((totalRequests / D1_MONTHLY_LIMIT) * 1000) / 10, 100)
234
-
235
- return c.json({
236
- storage: {
237
- used: storageUsedBytes,
238
- limit: R2_LIMIT,
239
- percentage: storagePercentage
240
- },
241
- database: {
242
- requests30d: totalRequests,
243
- limit: D1_MONTHLY_LIMIT,
244
- percentage: d1Percentage
245
- },
246
- status: (storagePercentage < 90 && d1Percentage < 90) ? 'healthy' : 'warning',
247
- lastUpdate: Math.floor(Date.now() / 1000)
248
- })
249
- } catch (err) {
250
- console.error('System health stats error:', err)
251
- return c.json({ error: 'Failed to calculate system health' }, 500)
252
- }
253
- })
254
-
255
- // GET /stats/cloudflare - Metriche tipo Cloudflare (Richieste, Visitatori, Bandwidth)
256
- statsApp.get('/stats/cloudflare', async (c) => {
257
- try {
258
- const { DB } = c.env
259
- const nowTs = Math.floor(Date.now() / 1000)
260
- const thirtyDaysAgo = Math.floor((Date.now() - 30 * 24 * 60 * 60 * 1000) / 1000)
261
-
262
- // Recupera sum delle metriche negli ultimi 30 giorni
263
- const metrics = await DB.prepare(
264
- `SELECT
265
- metric,
266
- SUM(value) as total_value
267
- FROM analytics
268
- WHERE day_ts >= ? AND seed = ''
269
- GROUP BY metric`
270
- )
271
- .bind(thirtyDaysAgo)
272
- .all<{ metric: string; total_value: number }>()
273
-
274
- const statsMap = Object.fromEntries(
275
- metrics.results?.map(m => [m.metric, m.total_value]) ?? []
276
- )
277
-
278
- // Simuliamo alcune metriche Cloudflare non tracciate direttamente per premium feel
279
- const requests = statsMap['requests'] ?? Math.floor(Math.random() * 5000) + 1000
280
- const visitors = statsMap['visitors'] ?? Math.floor(requests / 12) + 1
281
- const bandwidth = Math.round((requests * 0.15) * 10) / 10
282
-
283
- // Metriche R2 (Dal contatore ottimizzato in D1)
284
- let storageUsedBytes = 0
285
- try {
286
- const statsRow = await DB.prepare(
287
- "SELECT value FROM system_stats WHERE id = 'total_storage_bytes'"
288
- ).first<{ value: string }>()
289
- if (statsRow) {
290
- storageUsedBytes = parseInt(statsRow.value, 10)
291
- }
292
- } catch (err) {
293
- console.warn('Could not fetch storage stats from D1:', err)
294
- }
295
-
296
- const storageUsedMB = Math.round((storageUsedBytes / (1024 * 1024)) * 10) / 10
297
- const storageLimitMB = 10 * 1024 // 10 GB Free Tier
298
-
299
- return c.json({
300
- visitors: {
301
- value: visitors,
302
- trend: 12, // % crescita simulata
303
- isPositive: true
304
- },
305
- requests: {
306
- value: requests,
307
- trend: 8,
308
- isPositive: true
309
- },
310
- bandwidth: {
311
- value: bandwidth,
312
- unit: 'MB',
313
- trend: 5,
314
- isPositive: false
315
- },
316
- cacheRate: {
317
- value: 94.2,
318
- unit: '%',
319
- trend: 0.5,
320
- isPositive: true
321
- },
322
- storage: {
323
- used: storageUsedMB,
324
- limit: storageLimitMB,
325
- unit: 'MB',
326
- percentage: Math.round((storageUsedMB / storageLimitMB) * 1000) / 10
327
- }
328
- })
329
- } catch (err) {
330
- console.error('Cloudflare stats error:', err)
331
- return publicProblem(c, {
332
- type: 'content-database-error',
333
- title: 'Internal Server Error',
334
- status: 500,
335
- detail: DATABASE_ERROR,
336
- })
337
- }
338
- })
339
-
340
- // GET /stats/breakdown - Distribuzione contenuti per il widget Content Pulse
341
- statsApp.get('/stats/breakdown', async (c) => {
342
- try {
343
- const { DB } = c.env
344
- const seeds = Object.values(c.get('seedRegistry'))
345
-
346
- const counts = await Promise.all(
347
- seeds.map(s => DB.prepare(`SELECT COUNT(*) as n FROM content_${s.slug}`).first<{ n: number }>())
348
- )
349
-
350
- const breakdown = seeds.map((seed, i) => ({
351
- slug: seed.slug,
352
- label: seed.labelPlural || seed.label,
353
- count: counts[i]?.n ?? 0,
354
- }))
355
-
356
- return c.json(breakdown)
357
- } catch (err) {
358
- console.error('Breakdown stats error:', err)
359
- return publicProblem(c, {
360
- type: 'content-database-error',
361
- title: 'Internal Server Error',
362
- status: 500,
363
- detail: DATABASE_ERROR,
364
- })
365
- }
366
- })
367
-
368
- // POST /stats/storage/sync - Ricalcola lo spazio occupato su R2 (operazione costosa, usare con cautela)
369
- statsApp.post('/stats/storage/sync', async (c) => {
370
- try {
371
- const { DB } = c.env
372
- const client = createR2Client(c.env as any)
373
- if (!c.env.R2_BUCKET_NAME) {
374
- throw new Error('R2_BUCKET_NAME not configured')
375
- }
376
-
377
- const realSize = await getBucketSize(client, c.env.R2_BUCKET_NAME)
378
-
379
- await DB.prepare(
380
- "UPDATE system_stats SET value = ? WHERE id = 'total_storage_bytes'"
381
- ).bind(String(realSize)).run()
382
-
383
- return c.json({ success: true, size: realSize })
384
- } catch (err) {
385
- console.error('Storage sync error:', err)
386
- return publicProblem(c, {
387
- type: 'content-database-error',
388
- title: 'Internal Server Error',
389
- status: 500,
390
- detail: DATABASE_ERROR,
391
- })
392
- }
393
- })
394
-
395
- export { statsApp }
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import { Hono } from 'hono'
3
+ import type { Env, Variables } from '../../types'
4
+ import { publicProblem } from '../../public/problem-details'
5
+ import { cleanStr } from '../../shared/query-utils'
6
+
7
+ const DATABASE_ERROR = 'Database error'
8
+
9
+ const statsApp = new Hono<{ Bindings: Env; Variables: Variables }>()
10
+
11
+ /**
12
+ * GET /stats/media-library - Lists all files present in R2:
13
+ * combines media_objects (tracked uploads) + /api/media/ URLs found in file columns of each seed
14
+ */
15
+ statsApp.get('/stats/media-library', async (context) => {
16
+ try {
17
+ const { DB } = context.env
18
+ const mediaRepository = context.get('mediaRepository')
19
+ const limit = Math.min(parseInt(context.req.query('limit') ?? '12'), 100)
20
+ const offset = parseInt(context.req.query('offset') ?? '0')
21
+ const mediaBaseUrl = (context.env.MEDIA_BASE_URL?.trim().replace(/\/$/, '')) ?? new URL(context.req.url).origin
22
+
23
+ // 1. Files tracked in the media library
24
+ // Take the first 1000 for cross-scanning
25
+ const { items: mediaRows } = await mediaRepository.list({ limit: 1000, offset: 0 })
26
+
27
+ const trackedKeys = new Set<string>()
28
+ const allItems: Array<{ key: string; filename: string; mime_type: string; size_bytes: number; created_at: number; url: string }> = []
29
+
30
+ for (const mediaRow of mediaRows) {
31
+ trackedKeys.add(mediaRow.key)
32
+ allItems.push({ ...mediaRow, url: `${mediaBaseUrl}/api/media/${encodeURIComponent(mediaRow.key)}` })
33
+ }
34
+
35
+ // 2. /api/media/ URLs in the file columns of each seed (v0.4.0 — real columns)
36
+ const MEDIA_KEY_REGEX = /\/api\/media\/([^"'\s\\,}\]]+)/g
37
+ const seeds = Object.values(context.get('seedRegistry'))
38
+
39
+ for (const seed of seeds) {
40
+ const fileBranches = seed.branches.filter(branch => branch.type === 'file')
41
+ if (fileBranches.length === 0) continue
42
+
43
+ const columns = fileBranches.map(branch => branch.alias).join(', ')
44
+ const whereClause = fileBranches.map(branch => `${branch.alias} LIKE '%/api/media/%'`).join(' OR ')
45
+
46
+ const rows = await DB.prepare(
47
+ `SELECT ${columns} FROM content_${seed.slug} WHERE ${whereClause}`
48
+ ).all<Record<string, string | null>>()
49
+
50
+ for (const row of rows.results ?? []) {
51
+ const combinedValues = Object.values(row).filter(Boolean).join(' ')
52
+ for (const match of combinedValues.matchAll(MEDIA_KEY_REGEX)) {
53
+ const key = decodeURIComponent(match[1])
54
+ if (trackedKeys.has(key)) continue
55
+ trackedKeys.add(key)
56
+ const filename = key.replace(/^\d+-/, '')
57
+ const extension = filename.split('.').pop()?.toLowerCase() ?? ''
58
+ const mimeType = extension === 'pdf' ? 'application/pdf' : `image/${extension === 'jpg' ? 'jpeg' : extension || 'jpeg'}`
59
+ const createdAt = parseInt(key.split('-')[0]) || 0
60
+ allItems.push({
61
+ key,
62
+ filename,
63
+ mime_type: mimeType,
64
+ size_bytes: 0,
65
+ created_at: createdAt,
66
+ url: `${mediaBaseUrl}/api/media/${encodeURIComponent(key)}`
67
+ })
68
+ }
69
+ }
70
+ }
71
+
72
+ allItems.sort((a, b) => b.created_at - a.created_at)
73
+ const total = allItems.length
74
+ const paginatedItems = allItems.slice(offset, offset + limit)
75
+
76
+ return context.json({ items: paginatedItems, total })
77
+ } catch (error) {
78
+ console.error('Media library error:', error)
79
+ return context.json({ error: 'Internal Server Error' }, 500)
80
+ }
81
+ })
82
+
83
+ /**
84
+ * GET /stats/unused-media - Finds media in media_objects not referenced in any file column
85
+ */
86
+ statsApp.get('/stats/unused-media', async (context) => {
87
+ try {
88
+ const { DB } = context.env
89
+ const mediaRepository = context.get('mediaRepository')
90
+ const seeds = Object.values(context.get('seedRegistry'))
91
+
92
+ // All tracked media keys
93
+ const { items: mediaRows } = await mediaRepository.list({ limit: 1000, offset: 0 })
94
+
95
+ if (mediaRows.length === 0) {
96
+ return context.json({ items: [] })
97
+ }
98
+
99
+ // Collect all referenced keys in the file columns of each seed
100
+ const referencedKeys = new Set<string>()
101
+ for (const seed of seeds) {
102
+ const fileBranches = seed.branches.filter(branch => branch.type === 'file')
103
+ if (fileBranches.length === 0) continue
104
+ const columns = fileBranches.map(branch => branch.alias).join(', ')
105
+ const rows = await DB.prepare(
106
+ `SELECT ${columns} FROM content_${seed.slug}`
107
+ ).all<Record<string, string | null>>()
108
+
109
+ for (const row of rows.results ?? []) {
110
+ const combinedValues = Object.values(row).filter(Boolean).join(' ')
111
+ for (const match of combinedValues.matchAll(/\/api\/media\/([^"'\s\\,}\]]+)/g)) {
112
+ referencedKeys.add(decodeURIComponent(match[1]))
113
+ }
114
+ }
115
+ }
116
+
117
+ const unusedMedia = mediaRows.filter(mediaItem => !referencedKeys.has(mediaItem.key))
118
+ return context.json({ items: unusedMedia })
119
+ } catch (error) {
120
+ console.error('Unused media error:', error)
121
+ return context.json({ error: 'Internal Server Error' }, 500)
122
+ }
123
+ })
124
+
125
+ /**
126
+ * GET /stats/setup-checklist - Project setup status for "Project Health" widget
127
+ */
128
+ statsApp.get('/stats/setup-checklist', async (context) => {
129
+ try {
130
+ const { DB } = context.env
131
+ const seeds = Object.values(context.get('seedRegistry'))
132
+
133
+ // 1. System tables present
134
+ const systemTableNames = [
135
+ 'users', 'refresh_tokens', 'media_objects',
136
+ 'analytics', 'system_stats', 'activity_logs',
137
+ ]
138
+ const tablesResult = await DB.prepare(
139
+ `SELECT name FROM sqlite_master WHERE type='table'`
140
+ ).all<{ name: string }>()
141
+ const existingTables = new Set((tablesResult.results ?? []).map(row => row.name))
142
+ const systemTablesOk = systemTableNames.every(tableName => existingTables.has(tableName))
143
+
144
+ // 2. Seeds defined
145
+ const seedsCount = seeds.length
146
+
147
+ // 3. Content tables created (seed:load was run)
148
+ const contentTablesOk = seedsCount > 0 && seeds.every(seed => existingTables.has(`content_${seed.slug}`))
149
+
150
+ // 4. Admin account exists
151
+ let adminExists = false
152
+ try {
153
+ const adminCountResult = await DB.prepare(
154
+ `SELECT COUNT(*) as count FROM users WHERE role = 'admin'`
155
+ ).first<{ count: number }>()
156
+ adminExists = (adminCountResult?.count ?? 0) > 0
157
+ } catch {
158
+ // table may not exist yet
159
+ }
160
+
161
+ // 5. At least one content entry in the first seed's table
162
+ let hasContent = false
163
+ const firstSeedSlug = seeds[0]?.slug ?? null
164
+ if (firstSeedSlug && existingTables.has(`content_${firstSeedSlug}`)) {
165
+ try {
166
+ const contentCountResult = await DB.prepare(
167
+ `SELECT COUNT(*) as count FROM content_${firstSeedSlug}`
168
+ ).first<{ count: number }>()
169
+ hasContent = (contentCountResult?.count ?? 0) > 0
170
+ } catch {
171
+ // ignore
172
+ }
173
+ }
174
+
175
+ return context.json({
176
+ systemTablesOk,
177
+ seedsCount,
178
+ contentTablesOk,
179
+ adminExists,
180
+ hasContent,
181
+ firstSeedSlug,
182
+ })
183
+ } catch (error) {
184
+ console.error('Setup checklist error:', error)
185
+ return context.json({ error: 'Failed to compute setup checklist' }, 500)
186
+ }
187
+ })
188
+
189
+ /**
190
+ * GET /stats/total - Global content statistics for dashboard
191
+ */
192
+ statsApp.get('/stats/total', async (context) => {
193
+ try {
194
+ const { DB } = context.env
195
+ const now = Math.floor(Date.now() / 1000)
196
+ const twentyFourHoursAgo = now - (24 * 60 * 60)
197
+ const sevenDaysAgo = now - (7 * 24 * 60 * 60)
198
+ const thirtyDaysAgo = now - (30 * 24 * 60 * 60)
199
+
200
+ // Total: SUM of per-seed counts (current live entries)
201
+ const seeds = Object.values(context.get('seedRegistry'))
202
+ const countResults = await Promise.all(
203
+ seeds.map(seed => DB.prepare(`SELECT COUNT(*) as count FROM content_${seed.slug}`).first<{ count: number }>())
204
+ )
205
+ const totalEntriesCount = countResults.reduce((accumulator, result) => accumulator + (result?.count ?? 0), 0)
206
+
207
+ // today/week/month: create events in activity_logs (entity_type = 'content')
208
+ const eventRow = await DB.prepare(
209
+ `SELECT
210
+ COUNT(CASE WHEN created_at >= ? THEN 1 END) as today,
211
+ COUNT(CASE WHEN created_at >= ? THEN 1 END) as week,
212
+ COUNT(CASE WHEN created_at >= ? THEN 1 END) as month
213
+ FROM activity_logs WHERE action = 'create' AND entity_type = 'content'`
214
+ )
215
+ .bind(twentyFourHoursAgo, sevenDaysAgo, thirtyDaysAgo)
216
+ .first<{ today: number; week: number; month: number }>()
217
+
218
+ return context.json({
219
+ total: totalEntriesCount,
220
+ today: eventRow?.today ?? 0,
221
+ week: eventRow?.week ?? 0,
222
+ month: eventRow?.month ?? 0,
223
+ })
224
+ } catch (error) {
225
+ console.error('Content stats error:', error)
226
+ return publicProblem(context, {
227
+ type: 'content-database-error',
228
+ title: 'Internal Server Error',
229
+ status: 500,
230
+ detail: DATABASE_ERROR,
231
+ })
232
+ }
233
+ })
234
+
235
+ /**
236
+ * GET /stats/recent-activity - Latest activities registered in the system
237
+ * No ETag on this endpoint: the activity feed must always be fresh after
238
+ * every mutation. Cache-Control: no-store prevents the browser from keeping a
239
+ * response that could be returned as a 304 stale.
240
+ */
241
+ statsApp.get('/stats/recent-activity', async (context) => {
242
+ try {
243
+ const { DB } = context.env
244
+ const slug = cleanStr(context.req.query('slug'))
245
+
246
+ let query = `SELECT id, user_id, user_email, user_name, action, entity_type, entity_id, entity_slug, details, created_at
247
+ FROM activity_logs`
248
+ const queryParameters: any[] = []
249
+
250
+ if (slug) {
251
+ query += ' WHERE entity_slug = ?'
252
+ queryParameters.push(slug)
253
+ }
254
+
255
+ query += ' ORDER BY created_at DESC LIMIT 15'
256
+
257
+ const result = await DB.prepare(query).bind(...queryParameters).all()
258
+
259
+ const activities = (result.results ?? []).map((row: any) => ({
260
+ ...row,
261
+ details: row.details ? JSON.parse(row.details) : null
262
+ }))
263
+
264
+ context.header('Cache-Control', 'no-store')
265
+
266
+ return context.json(activities)
267
+ } catch (error) {
268
+ console.error('Recent activity error:', error)
269
+ return publicProblem(context, {
270
+ type: 'content-database-error',
271
+ title: 'Internal Server Error',
272
+ status: 500,
273
+ detail: DATABASE_ERROR,
274
+ })
275
+ }
276
+ })
277
+
278
+ /**
279
+ * GET /stats/health - System health status and Cloudflare quotas
280
+ */
281
+ statsApp.get('/stats/health', async (context) => {
282
+ try {
283
+ const { DB } = context.env
284
+ const systemStatsRepository = context.get('systemStatsRepository')
285
+
286
+ // 1. Retrieve storage usage from repository (system_stats)
287
+ let storageUsedBytes = 0
288
+ try {
289
+ storageUsedBytes = await systemStatsRepository.getStorageUsage()
290
+ } catch (error) {
291
+ console.warn('Health: Could not fetch storage stats from repo:', error)
292
+ }
293
+
294
+ // 2. Aggregate D1 requests (proxy for database health) - last 30 days
295
+ const thirtyDaysAgo = Math.floor((Date.now() - 30 * 24 * 60 * 60 * 1000) / 1000)
296
+ const d1Stats = await DB.prepare(
297
+ `SELECT SUM(value) as total_requests FROM analytics WHERE metric = 'requests' AND seed = '' AND day_ts >= ?`
298
+ ).bind(thirtyDaysAgo).first<{ total_requests: number }>()
299
+
300
+ const totalRequests = d1Stats?.total_requests ?? 0
301
+
302
+ // 3. Define limits (Cloudflare Free Tier as reference)
303
+ const R2_STORAGE_LIMIT = 10 * 1024 * 1024 * 1024 // 10GB
304
+ const D1_MONTHLY_REQUESTS_LIMIT = 1000000 // Simulate a limit of 1M requests/month
305
+
306
+ const storagePercentage = Math.min(Math.round((storageUsedBytes / R2_STORAGE_LIMIT) * 1000) / 10, 100)
307
+ const d1Percentage = Math.min(Math.round((totalRequests / D1_MONTHLY_REQUESTS_LIMIT) * 1000) / 10, 100)
308
+
309
+ return context.json({
310
+ storage: {
311
+ used: storageUsedBytes,
312
+ limit: R2_STORAGE_LIMIT,
313
+ percentage: storagePercentage
314
+ },
315
+ database: {
316
+ requests30d: totalRequests,
317
+ limit: D1_MONTHLY_REQUESTS_LIMIT,
318
+ percentage: d1Percentage
319
+ },
320
+ status: (storagePercentage < 90 && d1Percentage < 90) ? 'healthy' : 'warning',
321
+ lastUpdate: Math.floor(Date.now() / 1000)
322
+ })
323
+ } catch (error) {
324
+ console.error('System health stats error:', error)
325
+ return context.json({ error: 'Failed to calculate system health' }, 500)
326
+ }
327
+ })
328
+
329
+ /**
330
+ * GET /stats/cloudflare - Cloudflare-like metrics (Visitors, Requests, Bandwidth)
331
+ */
332
+ statsApp.get('/stats/cloudflare', async (context) => {
333
+ try {
334
+ const { DB } = context.env
335
+ const thirtyDaysAgo = Math.floor((Date.now() - 30 * 24 * 60 * 60 * 1000) / 1000)
336
+
337
+ // Retrieve sum of metrics in the last 30 days
338
+ const metricsResult = await DB.prepare(
339
+ `SELECT
340
+ metric,
341
+ SUM(value) as total_value
342
+ FROM analytics
343
+ WHERE day_ts >= ? AND seed = ''
344
+ GROUP BY metric`
345
+ )
346
+ .bind(thirtyDaysAgo)
347
+ .all<{ metric: string; total_value: number }>()
348
+
349
+ const statsMap = Object.fromEntries(
350
+ metricsResult.results?.map(metricRow => [metricRow.metric, metricRow.total_value]) ?? []
351
+ )
352
+
353
+ // Simulate some Cloudflare metrics not directly tracked for a premium feel
354
+ const requestsCount = statsMap['requests'] ?? Math.floor(Math.random() * 5000) + 1000
355
+ const visitorsCount = statsMap['visitors'] ?? Math.floor(requestsCount / 12) + 1
356
+ const bandwidthMB = Math.round((requestsCount * 0.15) * 10) / 10
357
+
358
+ const systemStatsRepository = context.get('systemStatsRepository')
359
+ let storageUsedBytes = 0
360
+ try {
361
+ storageUsedBytes = await systemStatsRepository.getStorageUsage()
362
+ } catch (error) {
363
+ console.warn('Could not fetch storage stats from repo:', error)
364
+ }
365
+
366
+ const storageUsedMB = Math.round((storageUsedBytes / (1024 * 1024)) * 10) / 10
367
+ const storageLimitMB = 10 * 1024 // 10 GB Free Tier
368
+
369
+ return context.json({
370
+ visitors: {
371
+ value: visitorsCount,
372
+ trend: 12, // simulated growth %
373
+ isPositive: true
374
+ },
375
+ requests: {
376
+ value: requestsCount,
377
+ trend: 8,
378
+ isPositive: true
379
+ },
380
+ bandwidth: {
381
+ value: bandwidthMB,
382
+ unit: 'MB',
383
+ trend: 5,
384
+ isPositive: false
385
+ },
386
+ cacheRate: {
387
+ value: 94.2,
388
+ unit: '%',
389
+ trend: 0.5,
390
+ isPositive: true
391
+ },
392
+ storage: {
393
+ used: storageUsedMB,
394
+ limit: storageLimitMB,
395
+ unit: 'MB',
396
+ percentage: Math.round((storageUsedMB / storageLimitMB) * 1000) / 10
397
+ }
398
+ })
399
+ } catch (error) {
400
+ console.error('Cloudflare stats error:', error)
401
+ return publicProblem(context, {
402
+ type: 'content-database-error',
403
+ title: 'Internal Server Error',
404
+ status: 500,
405
+ detail: DATABASE_ERROR,
406
+ })
407
+ }
408
+ })
409
+
410
+ /**
411
+ * GET /stats/breakdown - Content distribution for "Content Pulse" widget
412
+ */
413
+ statsApp.get('/stats/breakdown', async (context) => {
414
+ try {
415
+ const { DB } = context.env
416
+ const seeds = Object.values(context.get('seedRegistry'))
417
+
418
+ const counts = await Promise.all(
419
+ seeds.map(seed => DB.prepare(`SELECT COUNT(*) as count FROM content_${seed.slug}`).first<{ count: number }>())
420
+ )
421
+
422
+ const breakdown = seeds.map((seed, index) => ({
423
+ slug: seed.slug,
424
+ label: seed.labelPlural || seed.label,
425
+ count: counts[index]?.count ?? 0,
426
+ }))
427
+
428
+ return context.json(breakdown)
429
+ } catch (error) {
430
+ console.error('Breakdown stats error:', error)
431
+ return publicProblem(context, {
432
+ type: 'content-database-error',
433
+ title: 'Internal Server Error',
434
+ status: 500,
435
+ detail: DATABASE_ERROR,
436
+ })
437
+ }
438
+ })
439
+
440
+ /**
441
+ * POST /stats/storage/sync - Recalculates space occupied on R2 (expensive operation, use with caution)
442
+ */
443
+ statsApp.post('/stats/storage/sync', async (context) => {
444
+ try {
445
+ const bucket = context.get('bucket')
446
+ const systemStatsRepository = context.get('systemStatsRepository')
447
+
448
+ const realSize = await bucket.getTotalSize()
449
+ await systemStatsRepository.setStorage(realSize)
450
+
451
+ return context.json({ success: true, size: realSize })
452
+ } catch (error) {
453
+ console.error('Storage sync error:', error)
454
+ return context.json({ error: 'Internal Server Error' }, 500)
455
+ }
456
+ })
457
+
458
+ export { statsApp }