@beechcms/api 0.4.0-preview.9 → 0.4.1

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 (140) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/index-CH13idU1.js +554 -0
  4. package/assets/dashboard/assets/index-CewtCjom.css +1 -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/bcrypt-hash-provider.ts +20 -0
  12. package/src/auth/constants.ts +10 -10
  13. package/src/auth/generate-refresh-token.test.ts +19 -0
  14. package/src/auth/hash-provider.test.ts +46 -0
  15. package/src/auth/in-memory-hash-provider.ts +13 -0
  16. package/src/auth/jose-token-service.ts +55 -0
  17. package/src/auth/login.test.ts +92 -0
  18. package/src/auth/login.ts +74 -91
  19. package/src/auth/refresh.ts +5 -127
  20. package/src/auth/static-token-service.ts +18 -0
  21. package/src/auth/token-service.test.ts +82 -0
  22. package/src/factory.ts +339 -303
  23. package/src/features/content/constants.ts +10 -0
  24. package/src/features/content/handlers/create.ts +157 -0
  25. package/src/features/content/handlers/delete.ts +80 -0
  26. package/src/features/content/handlers/facets.ts +45 -0
  27. package/src/features/content/handlers/get.ts +116 -0
  28. package/src/features/content/handlers/list.ts +88 -0
  29. package/src/features/content/handlers/update.ts +211 -0
  30. package/src/features/content/index.ts +20 -0
  31. package/src/features/draft/draft.handler.ts +283 -198
  32. package/src/features/draft/index.ts +1 -1
  33. package/src/features/email/email.provider.ts +38 -38
  34. package/src/features/email/email.service.ts +80 -80
  35. package/src/features/email/email.types.ts +98 -98
  36. package/src/features/email/index.ts +28 -28
  37. package/src/features/email/providers/resend.ts +63 -63
  38. package/src/features/email/templates/password-changed.ts +59 -59
  39. package/src/features/email/templates/password-reset.ts +64 -64
  40. package/src/features/email/templates/shell.ts +92 -93
  41. package/src/features/notifications/index.ts +1 -1
  42. package/src/features/notifications/notifications.handler.ts +101 -88
  43. package/src/features/password-reset/index.ts +15 -15
  44. package/src/features/password-reset/request.ts +82 -88
  45. package/src/features/password-reset/reset.ts +92 -110
  46. package/src/features/rotate-field/index.ts +1 -1
  47. package/src/features/rotate-field/rotate-field.handler.ts +128 -82
  48. package/src/features/rotate-field/rotate-field.schema.ts +13 -9
  49. package/src/features/schema/schema.handler.ts +16 -16
  50. package/src/features/settings/settings.handler.ts +301 -249
  51. package/src/features/setup/index.ts +91 -59
  52. package/src/features/stats/index.ts +1 -1
  53. package/src/features/stats/stats.handler.ts +430 -395
  54. package/src/index.ts +24 -11
  55. package/src/media-utils.ts +78 -78
  56. package/src/middleware/auth-providers.middleware.ts +32 -0
  57. package/src/middleware/observability.middleware.ts +52 -0
  58. package/src/middleware/rate-limit.middleware.ts +41 -0
  59. package/src/middleware/repository.middleware.ts +60 -0
  60. package/src/middleware/storage.middleware.ts +21 -0
  61. package/src/middleware.ts +47 -67
  62. package/src/public/access-policy.ts +23 -23
  63. package/src/public/api-key-middleware.ts +53 -53
  64. package/src/public/index.ts +12 -12
  65. package/src/public/problem-details.ts +48 -42
  66. package/src/public/public-add.ts +156 -183
  67. package/src/public/public-edit.ts +159 -183
  68. package/src/public/public-errors.ts +15 -15
  69. package/src/public/public-read.ts +216 -217
  70. package/src/public/public-routes.ts +84 -31
  71. package/src/public/query-builder.test.ts +220 -0
  72. package/src/public/query-builder.ts +152 -241
  73. package/src/public/rate-limit-middleware.ts +30 -42
  74. package/src/public/response-builder.ts +26 -26
  75. package/src/public/sanitize.ts +65 -65
  76. package/src/public/slug-utils.ts +14 -14
  77. package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
  78. package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
  79. package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
  80. package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
  81. package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
  82. package/src/rate-limit/no-op-rate-limiter.ts +7 -0
  83. package/src/search-utils.test.ts +207 -0
  84. package/src/search-utils.ts +209 -192
  85. package/src/search.ts +61 -72
  86. package/src/shared/apply-policies.test.ts +77 -0
  87. package/src/shared/apply-policies.ts +63 -63
  88. package/src/shared/background-notification-service.test.ts +58 -0
  89. package/src/shared/background-notification-service.ts +48 -0
  90. package/src/shared/base.repository.d1.ts +28 -0
  91. package/src/shared/content-utils.test.ts +161 -0
  92. package/src/shared/content-utils.ts +82 -108
  93. package/src/shared/content.repository.d1.test.ts +312 -0
  94. package/src/shared/content.repository.d1.ts +382 -0
  95. package/src/shared/d1-activity-log.repository.test.ts +136 -0
  96. package/src/shared/d1-activity-log.repository.ts +101 -0
  97. package/src/shared/d1-activity-logger.test.ts +82 -0
  98. package/src/shared/d1-activity-logger.ts +63 -0
  99. package/src/shared/d1-analytics.repository.test.ts +74 -0
  100. package/src/shared/d1-analytics.repository.ts +81 -0
  101. package/src/shared/d1-content-scan.repository.ts +29 -0
  102. package/src/shared/d1-notification.repository.test.ts +124 -0
  103. package/src/shared/d1-notification.repository.ts +114 -0
  104. package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
  105. package/src/shared/d1-password-reset-token.repository.ts +52 -0
  106. package/src/shared/d1-search.repository.test.ts +83 -0
  107. package/src/shared/d1-search.repository.ts +84 -0
  108. package/src/shared/d1-session.repository.test.ts +121 -0
  109. package/src/shared/d1-session.repository.ts +98 -0
  110. package/src/shared/d1-user.repository.test.ts +147 -0
  111. package/src/shared/d1-user.repository.ts +109 -0
  112. package/src/shared/d1-widget.repository.test.ts +217 -0
  113. package/src/shared/d1-widget.repository.ts +337 -0
  114. package/src/shared/fixed-clock.ts +21 -0
  115. package/src/shared/fts-sync.ts +4 -4
  116. package/src/shared/idempotency.repository.d1.test.ts +79 -0
  117. package/src/shared/idempotency.repository.d1.ts +56 -0
  118. package/src/shared/in-memory-activity-logger.ts +15 -0
  119. package/src/shared/in-memory-notification-service.ts +15 -0
  120. package/src/shared/media.repository.d1.test.ts +103 -0
  121. package/src/shared/media.repository.d1.ts +64 -0
  122. package/src/shared/query-utils.ts +137 -137
  123. package/src/shared/request-utils.ts +22 -0
  124. package/src/shared/sequential-id-generator.ts +22 -0
  125. package/src/shared/storage/factory.ts +40 -0
  126. package/src/shared/storage/r2-binding-bucket.ts +81 -0
  127. package/src/shared/storage/s3-bucket.ts +163 -0
  128. package/src/shared/storage-utils.ts +36 -36
  129. package/src/shared/system-stats.repository.d1.test.ts +54 -0
  130. package/src/shared/system-stats.repository.d1.ts +44 -0
  131. package/src/types.ts +63 -36
  132. package/src/upload.ts +186 -335
  133. package/src/widget.ts +208 -349
  134. package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
  135. package/assets/dashboard/assets/index-CQODXprH.css +0 -1
  136. package/src/content.ts +0 -502
  137. package/src/features/draft/draft.test.ts +0 -315
  138. package/src/features/rotate-field/rotate-field.test.ts +0 -297
  139. package/src/shared/activity-logger.ts +0 -79
  140. package/src/shared/notification-service.ts +0 -56
@@ -0,0 +1,136 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1ActivityLogRepository } from './d1-activity-log.repository'
3
+
4
+ function makeMockDb(allResults: unknown[], firstResult: unknown = null) {
5
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
6
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
7
+ const bindMock = vi.fn(() => ({ all: allMock, first: firstMock }))
8
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
9
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, allMock, firstMock }
10
+ }
11
+
12
+ describe('D1ActivityLogRepository', () => {
13
+ it('maps snake_case rows to camelCase records and parses the details JSON', async () => {
14
+ const row = {
15
+ id: 'log-1',
16
+ user_id: 'u1',
17
+ user_email: 'a@b.com',
18
+ user_name: 'Admin',
19
+ action: 'create',
20
+ entity_type: 'content',
21
+ entity_id: 'e1',
22
+ entity_slug: 'posts',
23
+ details: '{"title":"Hello"}',
24
+ created_at: 1234,
25
+ }
26
+ const { db } = makeMockDb([row])
27
+ const result = await new D1ActivityLogRepository(db).list({ limit: 10 })
28
+ expect(result).toEqual([
29
+ {
30
+ id: 'log-1',
31
+ userId: 'u1',
32
+ userEmail: 'a@b.com',
33
+ userName: 'Admin',
34
+ action: 'create',
35
+ entityType: 'content',
36
+ entityId: 'e1',
37
+ entitySlug: 'posts',
38
+ details: { title: 'Hello' },
39
+ createdAt: 1234,
40
+ },
41
+ ])
42
+ })
43
+
44
+ it('returns null details when the column is null', async () => {
45
+ const { db } = makeMockDb([
46
+ {
47
+ id: 'l',
48
+ user_id: 'u',
49
+ user_email: 'a',
50
+ user_name: null,
51
+ action: 'delete',
52
+ entity_type: 'content',
53
+ entity_id: 'e',
54
+ entity_slug: null,
55
+ details: null,
56
+ created_at: 1,
57
+ },
58
+ ])
59
+ const [record] = await new D1ActivityLogRepository(db).list({ limit: 1 })
60
+ expect(record.details).toBeNull()
61
+ expect(record.userName).toBeNull()
62
+ expect(record.entitySlug).toBeNull()
63
+ })
64
+
65
+ it('omits the WHERE clause when no filters are provided', async () => {
66
+ const { db, prepareMock, bindMock } = makeMockDb([])
67
+ await new D1ActivityLogRepository(db).list({ limit: 5 })
68
+ expect(prepareMock.mock.calls[0][0]).not.toMatch(/WHERE/)
69
+ expect(bindMock).toHaveBeenCalledWith(5)
70
+ })
71
+
72
+ it('builds a userId WHERE clause when the option is set', async () => {
73
+ const { db, prepareMock, bindMock } = makeMockDb([])
74
+ await new D1ActivityLogRepository(db).list({ userId: 'u-9', limit: 3 })
75
+ expect(prepareMock.mock.calls[0][0]).toMatch(/WHERE user_id = \?/)
76
+ expect(bindMock).toHaveBeenCalledWith('u-9', 3)
77
+ })
78
+
79
+ it('builds a combined userId + entitySlug WHERE clause with AND', async () => {
80
+ const { db, prepareMock, bindMock } = makeMockDb([])
81
+ await new D1ActivityLogRepository(db).list({ userId: 'u', entitySlug: 'posts', limit: 7 })
82
+ expect(prepareMock.mock.calls[0][0]).toMatch(/WHERE user_id = \? AND entity_slug = \?/)
83
+ expect(bindMock).toHaveBeenCalledWith('u', 'posts', 7)
84
+ })
85
+
86
+ it('always orders by created_at DESC and applies LIMIT', async () => {
87
+ const { db, prepareMock } = makeMockDb([])
88
+ await new D1ActivityLogRepository(db).list({ limit: 1 })
89
+ expect(prepareMock.mock.calls[0][0]).toMatch(/ORDER BY created_at DESC/)
90
+ expect(prepareMock.mock.calls[0][0]).toMatch(/LIMIT \?/)
91
+ })
92
+
93
+ describe('countSince', () => {
94
+ it('binds action, entityType and sinceTimestamp and returns the count', async () => {
95
+ const { db, prepareMock, bindMock } = makeMockDb([], { count: 42 })
96
+ const result = await new D1ActivityLogRepository(db).countSince({
97
+ action: 'create',
98
+ entityType: 'content',
99
+ sinceTimestamp: 1000,
100
+ })
101
+ expect(result).toBe(42)
102
+ expect(prepareMock.mock.calls[0][0]).toMatch(/COUNT\(\*\)/)
103
+ expect(prepareMock.mock.calls[0][0]).toMatch(/WHERE action = \?\s+AND entity_type = \?\s+AND created_at >= \?/)
104
+ expect(bindMock).toHaveBeenCalledWith('create', 'content', 1000)
105
+ })
106
+
107
+ it('returns 0 when no rows match', async () => {
108
+ const { db } = makeMockDb([], null)
109
+ const result = await new D1ActivityLogRepository(db).countSince({
110
+ action: 'delete',
111
+ entityType: 'media',
112
+ sinceTimestamp: 0,
113
+ })
114
+ expect(result).toBe(0)
115
+ })
116
+ })
117
+
118
+ it('returns null details when the JSON payload cannot be parsed', async () => {
119
+ const { db } = makeMockDb([
120
+ {
121
+ id: 'l',
122
+ user_id: 'u',
123
+ user_email: 'a',
124
+ user_name: null,
125
+ action: 'create',
126
+ entity_type: 'content',
127
+ entity_id: 'e',
128
+ entity_slug: null,
129
+ details: 'not-json',
130
+ created_at: 1,
131
+ },
132
+ ])
133
+ const [record] = await new D1ActivityLogRepository(db).list({ limit: 1 })
134
+ expect(record.details).toBeNull()
135
+ })
136
+ })
@@ -0,0 +1,101 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type {
3
+ IActivityLogRepository,
4
+ ActivityLogRecord,
5
+ ActivityLogListOptions,
6
+ ActivityAction,
7
+ EntityType,
8
+ CountSinceOptions,
9
+ } from '@beechcms/core'
10
+
11
+ interface ActivityLogRow {
12
+ id: string
13
+ user_id: string
14
+ user_email: string
15
+ user_name: string | null
16
+ action: string
17
+ entity_type: string
18
+ entity_id: string
19
+ entity_slug: string | null
20
+ details: string | null
21
+ created_at: number
22
+ }
23
+
24
+ /**
25
+ * D1-backed implementation of {@link IActivityLogRepository}.
26
+ *
27
+ * Builds parameterised queries with optional WHERE clauses without nesting
28
+ * conditionals — guard clauses keep the body flat and the SQL deterministic.
29
+ */
30
+ export class D1ActivityLogRepository implements IActivityLogRepository {
31
+ constructor(private readonly database: D1Database) {}
32
+
33
+ async list(options: ActivityLogListOptions): Promise<ActivityLogRecord[]> {
34
+ const whereClauses: string[] = []
35
+ const bindings: unknown[] = []
36
+
37
+ if (options.userId) {
38
+ whereClauses.push('user_id = ?')
39
+ bindings.push(options.userId)
40
+ }
41
+
42
+ if (options.entitySlug) {
43
+ whereClauses.push('entity_slug = ?')
44
+ bindings.push(options.entitySlug)
45
+ }
46
+
47
+ const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : ''
48
+
49
+ const sql =
50
+ `SELECT id, user_id, user_email, user_name, action, entity_type,
51
+ entity_id, entity_slug, details, created_at
52
+ FROM activity_logs
53
+ ${whereSql}
54
+ ORDER BY created_at DESC
55
+ LIMIT ?`
56
+
57
+ bindings.push(options.limit)
58
+
59
+ const queryResult = await this.database.prepare(sql).bind(...bindings).all<ActivityLogRow>()
60
+ return (queryResult.results ?? []).map(mapRowToRecord)
61
+ }
62
+
63
+ async countSince(options: CountSinceOptions): Promise<number> {
64
+ const row = await this.database
65
+ .prepare(
66
+ `SELECT COUNT(*) as count
67
+ FROM activity_logs
68
+ WHERE action = ?
69
+ AND entity_type = ?
70
+ AND created_at >= ?`
71
+ )
72
+ .bind(options.action, options.entityType, options.sinceTimestamp)
73
+ .first<{ count: number }>()
74
+ return row?.count ?? 0
75
+ }
76
+ }
77
+
78
+ function mapRowToRecord(row: ActivityLogRow): ActivityLogRecord {
79
+ return {
80
+ id: row.id,
81
+ userId: row.user_id,
82
+ userEmail: row.user_email,
83
+ userName: row.user_name,
84
+ action: row.action as ActivityAction,
85
+ entityType: row.entity_type as EntityType,
86
+ entityId: row.entity_id,
87
+ entitySlug: row.entity_slug,
88
+ details: parseDetails(row.details),
89
+ createdAt: row.created_at,
90
+ }
91
+ }
92
+
93
+ function parseDetails(raw: string | null): Record<string, unknown> | null {
94
+ if (raw === null) return null
95
+ try {
96
+ const parsed = JSON.parse(raw)
97
+ return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null
98
+ } catch {
99
+ return null
100
+ }
101
+ }
@@ -0,0 +1,82 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1ActivityLogger } from './d1-activity-logger'
3
+ import type { ActivityLogEntry } from '@beechcms/core'
4
+ import { FixedClock } from './fixed-clock'
5
+ import { SequentialIdGenerator } from './sequential-id-generator'
6
+
7
+ const clock = new FixedClock(1700000000_000)
8
+ const makeIdGen = () => new SequentialIdGenerator()
9
+
10
+ function makeMockDb(opts: { runShouldThrow?: boolean } = {}) {
11
+ const runMock = opts.runShouldThrow
12
+ ? vi.fn().mockRejectedValue(new Error('db down'))
13
+ : vi.fn().mockResolvedValue({ success: true })
14
+ const bindMock = vi.fn(() => ({ run: runMock }))
15
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
16
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, runMock }
17
+ }
18
+
19
+ const SAMPLE_ENTRY: ActivityLogEntry = {
20
+ action: 'create',
21
+ entityType: 'content',
22
+ entityId: 'entry-1',
23
+ entitySlug: 'posts',
24
+ details: { title: 'Hello' },
25
+ actor: { id: 'user-1', email: 'admin@example.com', name: 'Admin' },
26
+ }
27
+
28
+ describe('D1ActivityLogger', () => {
29
+ it('inserts into activity_logs with the actor and entry payload bound in order', async () => {
30
+ const { db, prepareMock, bindMock } = makeMockDb()
31
+ const logger = new D1ActivityLogger(db, clock, makeIdGen())
32
+
33
+ await logger.log(SAMPLE_ENTRY)
34
+
35
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO activity_logs'))
36
+ const boundArguments = bindMock.mock.calls[0]
37
+ expect(boundArguments[1]).toBe('user-1')
38
+ expect(boundArguments[2]).toBe('admin@example.com')
39
+ expect(boundArguments[3]).toBe('Admin')
40
+ expect(boundArguments[4]).toBe('create')
41
+ expect(boundArguments[5]).toBe('content')
42
+ expect(boundArguments[6]).toBe('entry-1')
43
+ expect(boundArguments[7]).toBe('posts')
44
+ expect(boundArguments[8]).toBe('{"title":"Hello"}')
45
+ })
46
+
47
+ it('serialises details as null when absent', async () => {
48
+ const { db, bindMock } = makeMockDb()
49
+ await new D1ActivityLogger(db, clock, makeIdGen()).log({ ...SAMPLE_ENTRY, details: undefined })
50
+ expect(bindMock.mock.calls[0][8]).toBeNull()
51
+ })
52
+
53
+ it('falls back to "unknown" when actor email is empty', async () => {
54
+ const { db, bindMock } = makeMockDb()
55
+ await new D1ActivityLogger(db, clock, makeIdGen()).log({
56
+ ...SAMPLE_ENTRY,
57
+ actor: { id: 'u', email: '', name: null },
58
+ })
59
+ expect(bindMock.mock.calls[0][2]).toBe('unknown')
60
+ })
61
+
62
+ it('schedules the insert via the background hook when provided', async () => {
63
+ const { db } = makeMockDb()
64
+ const scheduleBackgroundTask = vi.fn()
65
+ const logger = new D1ActivityLogger(db, clock, makeIdGen(), scheduleBackgroundTask)
66
+
67
+ logger.log(SAMPLE_ENTRY)
68
+
69
+ expect(scheduleBackgroundTask).toHaveBeenCalledTimes(1)
70
+ expect(scheduleBackgroundTask.mock.calls[0][0]).toBeInstanceOf(Promise)
71
+ })
72
+
73
+ it('never throws to the caller when the underlying INSERT fails', async () => {
74
+ const { db } = makeMockDb({ runShouldThrow: true })
75
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
76
+ const logger = new D1ActivityLogger(db, clock, makeIdGen())
77
+
78
+ await expect(logger.log(SAMPLE_ENTRY)).resolves.toBeUndefined()
79
+ expect(consoleSpy).toHaveBeenCalled()
80
+ consoleSpy.mockRestore()
81
+ })
82
+ })
@@ -0,0 +1,63 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type { IActivityLogger, ActivityLogEntry, IClock, IIdGenerator } from '@beechcms/core'
3
+
4
+ const ACTIVITY_LOG_INSERT_SQL =
5
+ `INSERT INTO activity_logs
6
+ (id, user_id, user_email, user_name, action, entity_type, entity_id, entity_slug, details)
7
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
8
+
9
+ const FALLBACK_USER_EMAIL = 'unknown'
10
+
11
+ type ScheduleBackgroundTask = (task: Promise<unknown>) => void
12
+
13
+ /**
14
+ * D1-backed implementation of {@link IActivityLogger}.
15
+ *
16
+ * When `scheduleBackgroundTask` is provided (production path, wired to
17
+ * `c.executionCtx.waitUntil`), the INSERT runs after the response is sent so
18
+ * audit logging never adds latency to the user-facing request. When absent
19
+ * (tests, scripts), the INSERT runs inline and any errors are logged.
20
+ */
21
+ export class D1ActivityLogger implements IActivityLogger {
22
+ constructor(
23
+ private readonly database: D1Database,
24
+ private readonly clock: IClock,
25
+ private readonly idGenerator: IIdGenerator,
26
+ private readonly scheduleBackgroundTask?: ScheduleBackgroundTask
27
+ ) {}
28
+
29
+ log(entry: ActivityLogEntry): Promise<void> | void {
30
+ const insertPromise = this.runInsert(entry)
31
+
32
+ if (this.scheduleBackgroundTask) {
33
+ this.scheduleBackgroundTask(insertPromise)
34
+ return
35
+ }
36
+
37
+ return insertPromise
38
+ }
39
+
40
+ private async runInsert(entry: ActivityLogEntry): Promise<void> {
41
+ try {
42
+ const recordId = this.idGenerator.uuid()
43
+ const serializedDetails = entry.details ? JSON.stringify(entry.details) : null
44
+
45
+ await this.database
46
+ .prepare(ACTIVITY_LOG_INSERT_SQL)
47
+ .bind(
48
+ recordId,
49
+ entry.actor.id,
50
+ entry.actor.email || FALLBACK_USER_EMAIL,
51
+ entry.actor.name ?? null,
52
+ entry.action,
53
+ entry.entityType,
54
+ entry.entityId,
55
+ entry.entitySlug ?? null,
56
+ serializedDetails
57
+ )
58
+ .run()
59
+ } catch (error) {
60
+ console.error('D1ActivityLogger: failed to persist activity entry', error)
61
+ }
62
+ }
63
+ }
@@ -0,0 +1,74 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1AnalyticsRepository } from './d1-analytics.repository'
3
+ import { FixedClock } from './fixed-clock'
4
+
5
+ const FIXED_NOW_MS = 1700000000_000
6
+ const EXPECTED_DAY_BUCKET = Math.floor(FIXED_NOW_MS / 1000 / 86400) * 86400
7
+
8
+ function makeMockDb(allResults: unknown[] = [], firstResult: unknown = null) {
9
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
10
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
11
+ const runMock = vi.fn().mockResolvedValue({ success: true })
12
+ const bindMock = vi.fn(() => ({ all: allMock, first: firstMock, run: runMock }))
13
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
14
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, allMock, firstMock, runMock }
15
+ }
16
+
17
+ describe('D1AnalyticsRepository', () => {
18
+ describe('recordRequest', () => {
19
+ it('issues an INSERT ... ON CONFLICT upsert with seed and computed day bucket', async () => {
20
+ const { db, prepareMock, bindMock, runMock } = makeMockDb()
21
+ await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).recordRequest('posts')
22
+ const sql = prepareMock.mock.calls[0]![0] as string
23
+ expect(sql).toMatch(/INSERT INTO analytics/)
24
+ expect(sql).toMatch(/ON CONFLICT\(day_ts, metric, seed\) DO UPDATE SET value = value \+ 1/)
25
+ expect(bindMock).toHaveBeenCalledWith(EXPECTED_DAY_BUCKET, 'posts')
26
+ expect(runMock).toHaveBeenCalled()
27
+ })
28
+ })
29
+
30
+ describe('sumByMetric', () => {
31
+ it('binds requests metric, seed and since', async () => {
32
+ const { db, prepareMock, bindMock } = makeMockDb([], { total: 99 })
33
+ const total = await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).sumByMetric('requests', 'posts', 1)
34
+ expect(total).toBe(99)
35
+ const sql = prepareMock.mock.calls[0]![0] as string
36
+ expect(sql).toMatch(/SELECT SUM\(value\) as total/)
37
+ expect(sql).toMatch(/WHERE metric = \? AND seed = \? AND day_ts >= \?/)
38
+ expect(bindMock).toHaveBeenCalledWith('requests', 'posts', 1)
39
+ })
40
+
41
+ it('returns 0 when SUM is null', async () => {
42
+ const { db } = makeMockDb([], { total: null })
43
+ const total = await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).sumByMetric('visitors', '', 0)
44
+ expect(total).toBe(0)
45
+ })
46
+
47
+ it('returns 0 when no row matches', async () => {
48
+ const { db } = makeMockDb([], null)
49
+ const total = await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).sumByMetric('requests', '', 0)
50
+ expect(total).toBe(0)
51
+ })
52
+ })
53
+
54
+ describe('groupByMetric', () => {
55
+ it('returns a date_label → count map filtered to metric=requests', async () => {
56
+ const { db, prepareMock, bindMock } = makeMockDb([
57
+ { date_label: '2026-01-01', daily_count: 10 },
58
+ { date_label: '2026-01-02', daily_count: 20 },
59
+ ])
60
+ const result = await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).groupByMetric('posts', 1)
61
+ expect(result).toEqual({ '2026-01-01': 10, '2026-01-02': 20 })
62
+ const sql = prepareMock.mock.calls[0]![0] as string
63
+ expect(sql).toMatch(/strftime\('%Y-%m-%d', day_ts, 'unixepoch'\)/)
64
+ expect(sql).toMatch(/metric = 'requests'/)
65
+ expect(bindMock).toHaveBeenCalledWith('posts', 1)
66
+ })
67
+
68
+ it('skips rows with null date_label', async () => {
69
+ const { db } = makeMockDb([{ date_label: null, daily_count: 5 }])
70
+ const result = await new D1AnalyticsRepository(db, new FixedClock(FIXED_NOW_MS)).groupByMetric('', 0)
71
+ expect(result).toEqual({})
72
+ })
73
+ })
74
+ })
@@ -0,0 +1,81 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type { IAnalyticsRepository, AnalyticsMetric, IClock } from '@beechcms/core'
3
+
4
+ const SECONDS_PER_DAY = 86400
5
+
6
+ /**
7
+ * D1-backed implementation of {@link IAnalyticsRepository}.
8
+ *
9
+ * The underlying schema is long-format:
10
+ * `analytics(day_ts, metric, seed, value)` with UNIQUE(day_ts, metric, seed).
11
+ * Each row stores the counter for one (day, metric, seed) tuple. The
12
+ * IAnalyticsRepository contract is metric-aware (the metric is selected via
13
+ * a switch on the validated enum), and never interpolates user values into
14
+ * SQL — the actual metric name is bound through a parameter.
15
+ */
16
+ export class D1AnalyticsRepository implements IAnalyticsRepository {
17
+ constructor(
18
+ private readonly database: D1Database,
19
+ private readonly clock: IClock,
20
+ ) {}
21
+
22
+ async recordRequest(seedSlug: string): Promise<void> {
23
+ const dayTimestamp = Math.floor(this.clock.nowSeconds() / SECONDS_PER_DAY) * SECONDS_PER_DAY
24
+ await this.database
25
+ .prepare(
26
+ `INSERT INTO analytics (day_ts, metric, seed, value)
27
+ VALUES (?, 'requests', ?, 1)
28
+ ON CONFLICT(day_ts, metric, seed) DO UPDATE SET value = value + 1`,
29
+ )
30
+ .bind(dayTimestamp, seedSlug)
31
+ .run()
32
+ }
33
+
34
+ async sumByMetric(
35
+ metric: AnalyticsMetric,
36
+ seedSlug: string,
37
+ sinceTimestamp: number,
38
+ ): Promise<number> {
39
+ const metricName = this.resolveMetricName(metric)
40
+ const row = await this.database
41
+ .prepare(
42
+ `SELECT SUM(value) as total
43
+ FROM analytics
44
+ WHERE metric = ? AND seed = ? AND day_ts >= ?`,
45
+ )
46
+ .bind(metricName, seedSlug, sinceTimestamp)
47
+ .first<{ total: number | null }>()
48
+ return row?.total ?? 0
49
+ }
50
+
51
+ async groupByMetric(
52
+ seedSlug: string,
53
+ sinceTimestamp: number,
54
+ ): Promise<Record<string, number>> {
55
+ const result = await this.database
56
+ .prepare(
57
+ `SELECT strftime('%Y-%m-%d', day_ts, 'unixepoch') as date_label,
58
+ SUM(value) as daily_count
59
+ FROM analytics
60
+ WHERE metric = 'requests' AND seed = ? AND day_ts >= ?
61
+ GROUP BY date_label
62
+ ORDER BY date_label ASC`,
63
+ )
64
+ .bind(seedSlug, sinceTimestamp)
65
+ .all<{ date_label: string | null; daily_count: number | null }>()
66
+
67
+ const grouped: Record<string, number> = {}
68
+ for (const row of result.results ?? []) {
69
+ if (row.date_label === null) continue
70
+ grouped[row.date_label] = row.daily_count ?? 0
71
+ }
72
+ return grouped
73
+ }
74
+
75
+ private resolveMetricName(metric: AnalyticsMetric): string {
76
+ switch (metric) {
77
+ case 'requests': return 'requests'
78
+ case 'visitors': return 'visitors'
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,29 @@
1
+ import type { D1Database } from '@cloudflare/workers-types'
2
+ import type { IContentScanRepository, Seed } from '@beechcms/core'
3
+
4
+ export class D1ContentScanRepository implements IContentScanRepository {
5
+ constructor(private readonly db: D1Database) {}
6
+
7
+ async getReferencedMediaKeys(seeds: Seed[]): Promise<Set<string>> {
8
+ const referencedMediaKeys = new Set<string>()
9
+
10
+ for (const seed of seeds) {
11
+ const mediaFields = seed.branches.filter(branch => branch.type === 'file')
12
+ if (mediaFields.length === 0) continue
13
+
14
+ const mediaColumns = mediaFields.map(field => field.alias).join(', ')
15
+ const contentData = await this.db.prepare(
16
+ `SELECT ${mediaColumns} FROM content_${seed.slug}`
17
+ ).all<Record<string, string | null>>()
18
+
19
+ for (const contentRow of contentData.results ?? []) {
20
+ const rowContentString = Object.values(contentRow).filter(Boolean).join(' ')
21
+ for (const keyMatch of rowContentString.matchAll(/\/api\/media\/([^"'\s\\,}\]]+)/g)) {
22
+ referencedMediaKeys.add(decodeURIComponent(keyMatch[1]))
23
+ }
24
+ }
25
+ }
26
+
27
+ return referencedMediaKeys
28
+ }
29
+ }