@beechcms/api 0.4.0 → 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.
- package/assets/dashboard/assets/index-CH13idU1.js +554 -0
- package/assets/dashboard/index.html +1 -1
- package/package.json +2 -2
- package/src/auth/bcrypt-hash-provider.ts +20 -0
- package/src/auth/constants.ts +3 -3
- package/src/auth/generate-refresh-token.test.ts +19 -0
- package/src/auth/hash-provider.test.ts +46 -0
- package/src/auth/in-memory-hash-provider.ts +13 -0
- package/src/auth/jose-token-service.ts +55 -0
- package/src/auth/login.test.ts +92 -0
- package/src/auth/login.ts +15 -32
- package/src/auth/refresh.ts +0 -122
- package/src/auth/static-token-service.ts +18 -0
- package/src/auth/token-service.test.ts +82 -0
- package/src/factory.ts +70 -78
- package/src/features/content/handlers/create.ts +14 -10
- package/src/features/content/handlers/delete.ts +13 -9
- package/src/features/content/handlers/update.ts +13 -9
- package/src/features/draft/draft.handler.ts +23 -12
- package/src/features/notifications/notifications.handler.ts +25 -54
- package/src/features/password-reset/request.ts +17 -41
- package/src/features/password-reset/reset.ts +18 -54
- package/src/features/rotate-field/rotate-field.handler.ts +15 -19
- package/src/features/schema/schema.handler.ts +1 -1
- package/src/features/settings/settings.handler.ts +62 -175
- package/src/features/setup/index.ts +12 -17
- package/src/features/stats/stats.handler.ts +110 -138
- package/src/middleware/auth-providers.middleware.ts +32 -0
- package/src/middleware/observability.middleware.ts +52 -0
- package/src/middleware/rate-limit.middleware.ts +41 -0
- package/src/middleware/repository.middleware.ts +41 -5
- package/src/middleware.ts +15 -35
- package/src/public/public-add.ts +5 -15
- package/src/public/public-edit.ts +4 -3
- package/src/public/public-read.ts +3 -3
- package/src/public/public-routes.ts +2 -2
- package/src/public/query-builder.test.ts +220 -0
- package/src/public/rate-limit-middleware.ts +7 -19
- package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
- package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
- package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
- package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
- package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
- package/src/rate-limit/no-op-rate-limiter.ts +7 -0
- package/src/search-utils.test.ts +207 -0
- package/src/search-utils.ts +18 -1
- package/src/search.ts +24 -35
- package/src/shared/apply-policies.test.ts +77 -0
- package/src/shared/background-notification-service.test.ts +58 -0
- package/src/shared/background-notification-service.ts +48 -0
- package/src/shared/content-utils.test.ts +161 -0
- package/src/shared/content.repository.d1.test.ts +312 -0
- package/src/shared/d1-activity-log.repository.test.ts +136 -0
- package/src/shared/d1-activity-log.repository.ts +101 -0
- package/src/shared/d1-activity-logger.test.ts +82 -0
- package/src/shared/d1-activity-logger.ts +63 -0
- package/src/shared/d1-analytics.repository.test.ts +74 -0
- package/src/shared/d1-analytics.repository.ts +81 -0
- package/src/shared/d1-content-scan.repository.ts +29 -0
- package/src/shared/d1-notification.repository.test.ts +124 -0
- package/src/shared/d1-notification.repository.ts +114 -0
- package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
- package/src/shared/d1-password-reset-token.repository.ts +52 -0
- package/src/shared/d1-search.repository.test.ts +83 -0
- package/src/shared/d1-search.repository.ts +84 -0
- package/src/shared/d1-session.repository.test.ts +121 -0
- package/src/shared/d1-session.repository.ts +98 -0
- package/src/shared/d1-user.repository.test.ts +147 -0
- package/src/shared/d1-user.repository.ts +109 -0
- package/src/shared/d1-widget.repository.test.ts +217 -0
- package/src/shared/d1-widget.repository.ts +337 -0
- package/src/shared/fixed-clock.ts +21 -0
- package/src/shared/idempotency.repository.d1.test.ts +79 -0
- package/src/shared/in-memory-activity-logger.ts +15 -0
- package/src/shared/in-memory-notification-service.ts +15 -0
- package/src/shared/media.repository.d1.test.ts +103 -0
- package/src/shared/media.repository.d1.ts +1 -1
- package/src/shared/request-utils.ts +22 -0
- package/src/shared/sequential-id-generator.ts +22 -0
- package/src/shared/system-stats.repository.d1.test.ts +54 -0
- package/src/types.ts +20 -3
- package/src/upload.ts +14 -7
- package/src/widget.ts +112 -253
- package/assets/dashboard/assets/index-FQ6JhvRH.js +0 -554
- package/src/shared/activity-logger.ts +0 -79
- package/src/shared/notification-service.ts +0 -56
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { D1ContentRepository } from './content.repository.d1'
|
|
3
|
+
import { EntryNotFoundError, SlugConflictError } from '@beechcms/core'
|
|
4
|
+
import type { Seed } from '@beechcms/core'
|
|
5
|
+
|
|
6
|
+
const SEED = {
|
|
7
|
+
slug: 'posts',
|
|
8
|
+
displayNameAlias: 'title',
|
|
9
|
+
allowDrafts: true,
|
|
10
|
+
branches: [
|
|
11
|
+
{ id: 'br_01', alias: 'title', type: 'text' },
|
|
12
|
+
{ id: 'br_02', alias: 'body', type: 'text' },
|
|
13
|
+
],
|
|
14
|
+
} as unknown as Seed
|
|
15
|
+
|
|
16
|
+
const NO_DRAFT_SEED = {
|
|
17
|
+
slug: 'produtos',
|
|
18
|
+
displayNameAlias: 'name',
|
|
19
|
+
allowDrafts: false,
|
|
20
|
+
branches: [{ id: 'br_01', alias: 'name', type: 'text' }],
|
|
21
|
+
} as unknown as Seed
|
|
22
|
+
|
|
23
|
+
function makeMockDb(opts: {
|
|
24
|
+
firstResult?: unknown
|
|
25
|
+
allResults?: unknown[]
|
|
26
|
+
runChanges?: number
|
|
27
|
+
batchResults?: unknown[]
|
|
28
|
+
} = {}) {
|
|
29
|
+
const { firstResult = null, allResults = [], runChanges = 1, batchResults = [] } = opts
|
|
30
|
+
const runMock = vi.fn().mockResolvedValue({ success: true, meta: { changes: runChanges } })
|
|
31
|
+
const firstMock = vi.fn().mockResolvedValue(firstResult)
|
|
32
|
+
const allMock = vi.fn().mockResolvedValue({ results: allResults })
|
|
33
|
+
const bindMock = vi.fn(() => ({ run: runMock, first: firstMock, all: allMock }))
|
|
34
|
+
const stmt = { bind: bindMock, run: runMock, first: firstMock, all: allMock }
|
|
35
|
+
const prepareMock = vi.fn(() => stmt)
|
|
36
|
+
const batchMock = vi.fn().mockResolvedValue(batchResults)
|
|
37
|
+
return { db: { prepare: prepareMock, batch: batchMock } as any, prepareMock, bindMock, runMock, firstMock, allMock, batchMock }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ─── findMany ─────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe('D1ContentRepository', () => {
|
|
43
|
+
describe('findMany', () => {
|
|
44
|
+
it('returns mapped items and total from batch results', async () => {
|
|
45
|
+
const row = { id: 'e1', slug: 'post-1', status: 'published', title: 'Hello', body: null, created_at: 1000, updated_at: 1000 }
|
|
46
|
+
const { db } = makeMockDb({
|
|
47
|
+
batchResults: [
|
|
48
|
+
{ results: [row] },
|
|
49
|
+
{ results: [{ total: 1 }] },
|
|
50
|
+
],
|
|
51
|
+
})
|
|
52
|
+
const result = await new D1ContentRepository(db).findMany(SEED, { pagination: { limit: 10, offset: 0 } })
|
|
53
|
+
expect(result.items).toHaveLength(1)
|
|
54
|
+
expect(result.items[0].id).toBe('e1')
|
|
55
|
+
expect(result.total).toBe(1)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('returns empty items and zero total when table is empty', async () => {
|
|
59
|
+
const { db } = makeMockDb({
|
|
60
|
+
batchResults: [{ results: [] }, { results: [{ total: 0 }] }],
|
|
61
|
+
})
|
|
62
|
+
const result = await new D1ContentRepository(db).findMany(SEED, {})
|
|
63
|
+
expect(result.items).toHaveLength(0)
|
|
64
|
+
expect(result.total).toBe(0)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('wraps D1 errors in RepositoryError', async () => {
|
|
68
|
+
const { db } = makeMockDb()
|
|
69
|
+
db.batch = vi.fn().mockRejectedValue(new Error('D1 error'))
|
|
70
|
+
await expect(new D1ContentRepository(db).findMany(SEED, {})).rejects.toThrow('findMany')
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// ─── findById ───────────────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
describe('findById', () => {
|
|
77
|
+
it('returns the entry when found', async () => {
|
|
78
|
+
const row = { id: 'e1', slug: 'p', status: 'draft', title: 'T', body: null, created_at: 0, updated_at: 0 }
|
|
79
|
+
const { db } = makeMockDb({ firstResult: row })
|
|
80
|
+
const result = await new D1ContentRepository(db).findById(SEED, 'e1')
|
|
81
|
+
expect(result.id).toBe('e1')
|
|
82
|
+
expect(result.title).toBe('T')
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('throws EntryNotFoundError when the row does not exist', async () => {
|
|
86
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
87
|
+
await expect(new D1ContentRepository(db).findById(SEED, 'missing')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('queries the correct content table', async () => {
|
|
91
|
+
const { db, prepareMock } = makeMockDb({ firstResult: { id: 'e1', slug: null, status: 'draft', title: null, body: null } })
|
|
92
|
+
await new D1ContentRepository(db).findById(SEED, 'e1')
|
|
93
|
+
expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('content_posts'))
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// ─── findBySlug ─────────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
describe('findBySlug', () => {
|
|
100
|
+
it('returns the entry when the slug is found', async () => {
|
|
101
|
+
const row = { id: 'e1', slug: 'my-post', status: 'published', title: 'T', body: null }
|
|
102
|
+
const { db } = makeMockDb({ firstResult: row })
|
|
103
|
+
const result = await new D1ContentRepository(db).findBySlug(SEED, 'my-post')
|
|
104
|
+
expect(result.slug).toBe('my-post')
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('throws EntryNotFoundError when slug does not exist', async () => {
|
|
108
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
109
|
+
await expect(new D1ContentRepository(db).findBySlug(SEED, 'ghost')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
// ─── getFacets ───────────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
describe('getFacets', () => {
|
|
116
|
+
it('returns status counts mapped from status GROUP BY results', async () => {
|
|
117
|
+
const { db, allMock } = makeMockDb()
|
|
118
|
+
allMock.mockResolvedValueOnce({ results: [{ status: 'published', count: 3 }, { status: 'draft', count: 1 }] })
|
|
119
|
+
const result = await new D1ContentRepository(db).getFacets(SEED)
|
|
120
|
+
expect(result.statuses).toEqual({ published: 3, draft: 1 })
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('returns empty tagsByColumn when seed has no tag branches', async () => {
|
|
124
|
+
const { db, allMock } = makeMockDb()
|
|
125
|
+
allMock.mockResolvedValueOnce({ results: [] })
|
|
126
|
+
const result = await new D1ContentRepository(db).getFacets(SEED)
|
|
127
|
+
expect(result.tagsByColumn).toEqual({})
|
|
128
|
+
})
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
// ─── existsSlug ─────────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
describe('existsSlug', () => {
|
|
134
|
+
it('returns true when the slug row is found', async () => {
|
|
135
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } })
|
|
136
|
+
expect(await new D1ContentRepository(db).existsSlug(SEED, 'existing-slug')).toBe(true)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('returns false when the slug row is not found', async () => {
|
|
140
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
141
|
+
expect(await new D1ContentRepository(db).existsSlug(SEED, 'new-slug')).toBe(false)
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it('appends AND id != ? clause when excludeId is provided', async () => {
|
|
145
|
+
const { db, bindMock } = makeMockDb({ firstResult: null })
|
|
146
|
+
await new D1ContentRepository(db).existsSlug(SEED, 'slug', 'exclude-me')
|
|
147
|
+
expect(bindMock).toHaveBeenCalledWith('slug', 'exclude-me')
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
// ─── create ─────────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
describe('create', () => {
|
|
154
|
+
it('calls INSERT INTO the content table', async () => {
|
|
155
|
+
const { db, prepareMock } = makeMockDb({ firstResult: null }) // existsSlug → null
|
|
156
|
+
await new D1ContentRepository(db).create(SEED, 'new-id', 'my-slug', 'draft', { title: 'Hello' })
|
|
157
|
+
const calls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
158
|
+
expect(calls.some(sql => sql.includes('INSERT INTO content_posts'))).toBe(true)
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
it('throws SlugConflictError when the slug already exists', async () => {
|
|
162
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } }) // existsSlug → found
|
|
163
|
+
await expect(
|
|
164
|
+
new D1ContentRepository(db).create(SEED, 'id', 'taken-slug', 'draft', {}),
|
|
165
|
+
).rejects.toBeInstanceOf(SlugConflictError)
|
|
166
|
+
})
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
// ─── update ─────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
describe('update', () => {
|
|
172
|
+
it('calls UPDATE with provided status and branch data', async () => {
|
|
173
|
+
const { db, prepareMock, runMock } = makeMockDb({ runChanges: 1 })
|
|
174
|
+
runMock.mockResolvedValue({ success: true, meta: { changes: 1 } })
|
|
175
|
+
await new D1ContentRepository(db).update(SEED, 'e1', { title: 'New' }, 'published')
|
|
176
|
+
const calls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
177
|
+
expect(calls.some(sql => sql.includes('UPDATE content_posts'))).toBe(true)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
it('throws EntryNotFoundError when no rows are updated', async () => {
|
|
181
|
+
const { db } = makeMockDb({ runChanges: 0 })
|
|
182
|
+
await expect(new D1ContentRepository(db).update(SEED, 'ghost', { title: 'X' })).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
it('returns early without a DB call when there is nothing to update', async () => {
|
|
186
|
+
const { db, prepareMock } = makeMockDb()
|
|
187
|
+
await new D1ContentRepository(db).update(SEED, 'e1', {}) // no data, no status
|
|
188
|
+
// existsSlug is not called; only prepare calls would be for UPDATE which shouldn't happen
|
|
189
|
+
const updateCalls = prepareMock.mock.calls.filter(c => (c[0] as string).includes('UPDATE content_posts'))
|
|
190
|
+
expect(updateCalls).toHaveLength(0)
|
|
191
|
+
})
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
// ─── delete ─────────────────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
describe('delete', () => {
|
|
197
|
+
it('returns the row data and calls DELETE', async () => {
|
|
198
|
+
const row = { id: 'e1', slug: 'p', status: 'published', title: 'T', body: null }
|
|
199
|
+
const { db, prepareMock } = makeMockDb({ firstResult: row })
|
|
200
|
+
const result = await new D1ContentRepository(db).delete(SEED, 'e1')
|
|
201
|
+
expect(result.row.id).toBe('e1')
|
|
202
|
+
const sqls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
203
|
+
expect(sqls.some(s => s.includes('DELETE FROM content_posts'))).toBe(true)
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
it('throws EntryNotFoundError when the entry does not exist', async () => {
|
|
207
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
208
|
+
await expect(new D1ContentRepository(db).delete(SEED, 'missing')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
209
|
+
})
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
// ─── saveDraft ───────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
describe('saveDraft', () => {
|
|
215
|
+
it('calls INSERT OR REPLACE into the draft table', async () => {
|
|
216
|
+
const { db, prepareMock } = makeMockDb()
|
|
217
|
+
await new D1ContentRepository(db).saveDraft(SEED, 'e1', { title: 'Draft title' })
|
|
218
|
+
const sqls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
219
|
+
expect(sqls.some(s => s.includes('content_posts_drafts'))).toBe(true)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
it('throws RepositoryError when seed does not allow drafts', async () => {
|
|
223
|
+
const { db } = makeMockDb()
|
|
224
|
+
await expect(new D1ContentRepository(db).saveDraft(NO_DRAFT_SEED, 'e1', {})).rejects.toThrow('Drafts not allowed')
|
|
225
|
+
})
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
// ─── getDraft ────────────────────────────────────────────────────────────────
|
|
229
|
+
|
|
230
|
+
describe('getDraft', () => {
|
|
231
|
+
it('returns null when seed does not allow drafts', async () => {
|
|
232
|
+
const { db } = makeMockDb()
|
|
233
|
+
expect(await new D1ContentRepository(db).getDraft(NO_DRAFT_SEED, 'e1')).toBeNull()
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
it('returns null when no draft row exists', async () => {
|
|
237
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
238
|
+
expect(await new D1ContentRepository(db).getDraft(SEED, 'e1')).toBeNull()
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
it('returns deserialized draft data for non-null branch values', async () => {
|
|
242
|
+
const draftRow = { entry_id: 'e1', title: 'Draft T', body: null }
|
|
243
|
+
const { db } = makeMockDb({ firstResult: draftRow })
|
|
244
|
+
const result = await new D1ContentRepository(db).getDraft(SEED, 'e1')
|
|
245
|
+
expect(result).not.toBeNull()
|
|
246
|
+
expect(result!.title).toBe('Draft T')
|
|
247
|
+
expect(result).not.toHaveProperty('body') // null branch values are omitted
|
|
248
|
+
})
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
// ─── hasDraft ─────────────────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
describe('hasDraft', () => {
|
|
254
|
+
it('returns false immediately when seed does not allow drafts', async () => {
|
|
255
|
+
const { db, prepareMock } = makeMockDb()
|
|
256
|
+
expect(await new D1ContentRepository(db).hasDraft(NO_DRAFT_SEED, 'e1')).toBe(false)
|
|
257
|
+
expect(prepareMock).not.toHaveBeenCalled()
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
it('returns true when a draft exists', async () => {
|
|
261
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } })
|
|
262
|
+
expect(await new D1ContentRepository(db).hasDraft(SEED, 'e1')).toBe(true)
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
it('returns false when no draft exists', async () => {
|
|
266
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
267
|
+
expect(await new D1ContentRepository(db).hasDraft(SEED, 'e1')).toBe(false)
|
|
268
|
+
})
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
// ─── publishDraft ─────────────────────────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
describe('publishDraft', () => {
|
|
274
|
+
it('returns early when seed does not allow drafts', async () => {
|
|
275
|
+
const { db, batchMock } = makeMockDb()
|
|
276
|
+
await new D1ContentRepository(db).publishDraft(NO_DRAFT_SEED, 'e1')
|
|
277
|
+
expect(batchMock).not.toHaveBeenCalled()
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
it('throws EntryNotFoundError when no draft exists', async () => {
|
|
281
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
282
|
+
await expect(new D1ContentRepository(db).publishDraft(SEED, 'e1')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
it('calls batch with UPDATE and DELETE statements when draft exists', async () => {
|
|
286
|
+
const draftRow = { entry_id: 'e1', title: 'Draft', body: null }
|
|
287
|
+
const { db, batchMock, firstMock } = makeMockDb()
|
|
288
|
+
firstMock.mockResolvedValueOnce(draftRow)
|
|
289
|
+
batchMock.mockResolvedValueOnce([{}, {}])
|
|
290
|
+
await new D1ContentRepository(db).publishDraft(SEED, 'e1')
|
|
291
|
+
expect(batchMock).toHaveBeenCalledTimes(1)
|
|
292
|
+
const batchArgs: any[] = batchMock.mock.calls[0][0]
|
|
293
|
+
expect(batchArgs).toHaveLength(2)
|
|
294
|
+
})
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
// ─── deleteDraft ─────────────────────────────────────────────────────────────
|
|
298
|
+
|
|
299
|
+
describe('deleteDraft', () => {
|
|
300
|
+
it('returns early when seed does not allow drafts', async () => {
|
|
301
|
+
const { db, prepareMock } = makeMockDb()
|
|
302
|
+
await new D1ContentRepository(db).deleteDraft(NO_DRAFT_SEED, 'e1')
|
|
303
|
+
expect(prepareMock).not.toHaveBeenCalled()
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
it('calls DELETE on the draft table when drafts are allowed', async () => {
|
|
307
|
+
const { db, prepareMock } = makeMockDb()
|
|
308
|
+
await new D1ContentRepository(db).deleteDraft(SEED, 'e1')
|
|
309
|
+
expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('content_posts_drafts'))
|
|
310
|
+
})
|
|
311
|
+
})
|
|
312
|
+
})
|
|
@@ -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
|
+
})
|