@beechcms/api 0.5.0 → 0.6.0-preview.2

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 (225) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/Searching.svg +1 -0
  4. package/assets/dashboard/assets/chart-BrJFdsGZ.js +39 -0
  5. package/assets/dashboard/assets/index-CIaoMxuB.css +1 -0
  6. package/assets/dashboard/assets/index-wTKgygsg.js +636 -0
  7. package/assets/dashboard/assets/pie-chart-recharts-BEaE1FOE.js +1 -0
  8. package/assets/dashboard/assets/timeseries-chart-recharts-DmWM6imF.js +1 -0
  9. package/assets/dashboard/beechLogoDark.svg +48 -48
  10. package/assets/dashboard/index.html +18 -18
  11. package/assets/dashboard/noResult.svg +43 -0
  12. package/assets/dashboard/sol.svg +3 -3
  13. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  14. package/assets/dashboard/working.svg +1 -0
  15. package/migrations/0000_v040_base.sql +265 -238
  16. package/migrations/0029_automations.sql +14 -14
  17. package/migrations/0030_test_seeds.sql +125 -125
  18. package/package.json +13 -9
  19. package/src/auth/{in-memory-hash-provider.ts → __fixtures__/in-memory-hash-provider.ts} +17 -13
  20. package/src/auth/{static-token-service.ts → __fixtures__/static-token-service.ts} +22 -18
  21. package/src/auth/bcrypt-hash-provider.ts +24 -20
  22. package/src/auth/constants.ts +14 -10
  23. package/src/auth/generate-refresh-token.test.ts +23 -19
  24. package/src/auth/hash-provider.test.ts +55 -46
  25. package/src/auth/jose-token-service.ts +62 -55
  26. package/src/auth/jwt-claims-passthrough.test.ts +87 -0
  27. package/src/auth/login.test.ts +100 -92
  28. package/src/auth/login.ts +78 -74
  29. package/src/auth/refresh.ts +11 -5
  30. package/src/auth/token-service.test.ts +90 -82
  31. package/src/factory.ts +370 -347
  32. package/src/features/automations/__tests__/action-executors.test.ts +255 -268
  33. package/src/features/automations/__tests__/automation-runner.test.ts +196 -192
  34. package/src/features/automations/__tests__/automation-runner.utils.test.ts +60 -56
  35. package/src/features/automations/__tests__/automations.handler.test.ts +264 -260
  36. package/src/features/automations/__tests__/automations.repository.test.ts +163 -159
  37. package/src/features/automations/__tests__/automations.schema.test.ts +224 -134
  38. package/src/features/automations/__tests__/context-resolver.test.ts +126 -122
  39. package/src/features/automations/__tests__/cron-runner.test.ts +267 -263
  40. package/src/features/automations/__tests__/cron-runner.utils.test.ts +144 -140
  41. package/src/features/automations/__tests__/set-variable.executor.test.ts +383 -306
  42. package/src/features/automations/__tests__/template-grammar.test.ts +308 -304
  43. package/src/features/automations/__tests__/webhook.executor.test.ts +142 -0
  44. package/src/features/automations/__tests__/when-evaluator.test.ts +274 -270
  45. package/src/features/automations/__tests__/when-pushdown.test.ts +281 -277
  46. package/src/features/automations/action-executors/create-entry.executor.ts +27 -23
  47. package/src/features/automations/action-executors/edit-field.executor.ts +26 -22
  48. package/src/features/automations/action-executors/index.ts +37 -33
  49. package/src/features/automations/action-executors/send-mail.executor.ts +53 -42
  50. package/src/features/automations/action-executors/set-variable.executor.ts +159 -146
  51. package/src/features/automations/action-executors/webhook.executor.ts +67 -25
  52. package/src/features/automations/automation-runner.ts +85 -81
  53. package/src/features/automations/automation-runner.utils.ts +47 -43
  54. package/src/features/automations/automations.handler.ts +197 -193
  55. package/src/features/automations/automations.schema.ts +177 -160
  56. package/src/features/automations/context-resolver.ts +152 -148
  57. package/src/features/automations/cron-runner.ts +140 -136
  58. package/src/features/automations/cron-runner.utils.ts +44 -40
  59. package/src/features/automations/filter-translation.ts +46 -42
  60. package/src/features/automations/index.ts +16 -12
  61. package/src/features/automations/template-grammar.ts +245 -241
  62. package/src/features/automations/var-access-resolver.ts +140 -136
  63. package/src/features/automations/when-evaluator.ts +87 -83
  64. package/src/features/automations/when-pushdown.ts +57 -53
  65. package/src/features/backrefs/__tests__/backrefs.handler.test.ts +359 -0
  66. package/src/features/backrefs/backrefs.handler.ts +168 -0
  67. package/src/features/backrefs/d1-backref.repository.ts +84 -0
  68. package/src/features/backrefs/index.ts +5 -0
  69. package/src/features/content/constants.ts +16 -10
  70. package/src/features/content/handlers/bulk.handler.ts +185 -0
  71. package/src/features/content/handlers/create.ts +129 -165
  72. package/src/features/content/handlers/delete.ts +62 -87
  73. package/src/features/content/handlers/facets.ts +49 -45
  74. package/src/features/content/handlers/get.ts +120 -116
  75. package/src/features/content/handlers/helpers.test.ts +180 -0
  76. package/src/features/content/handlers/helpers.ts +93 -0
  77. package/src/features/content/handlers/list.ts +174 -88
  78. package/src/features/content/handlers/update.ts +174 -219
  79. package/src/features/content/index.ts +26 -20
  80. package/src/features/dashboard-layout/__tests__/dashboard-layout.handler.test.ts +388 -0
  81. package/src/features/dashboard-layout/dashboard-layout.handler.ts +206 -0
  82. package/src/features/dashboard-layout/index.ts +5 -0
  83. package/src/features/draft/draft.handler.ts +195 -170
  84. package/src/features/draft/draft.middleware.ts +66 -62
  85. package/src/features/draft/index.ts +5 -1
  86. package/src/features/email/email.provider.ts +42 -38
  87. package/src/features/email/email.service.ts +98 -93
  88. package/src/features/email/email.types.ts +119 -108
  89. package/src/features/email/index.ts +33 -29
  90. package/src/features/email/providers/resend.ts +67 -63
  91. package/src/features/email/providers/smtp.ts +55 -0
  92. package/src/features/email/templates/automation-mail.ts +19 -15
  93. package/src/features/email/templates/password-changed.ts +63 -59
  94. package/src/features/email/templates/password-reset.ts +68 -64
  95. package/src/features/email/templates/shell.ts +96 -92
  96. package/src/features/notifications/index.ts +5 -1
  97. package/src/features/notifications/notifications.handler.ts +105 -101
  98. package/src/features/password-reset/index.ts +19 -15
  99. package/src/features/password-reset/request.ts +92 -82
  100. package/src/features/password-reset/reset.ts +102 -92
  101. package/src/features/rotate-field/index.ts +5 -1
  102. package/src/features/rotate-field/rotate-field.handler.ts +132 -128
  103. package/src/features/rotate-field/rotate-field.schema.ts +17 -13
  104. package/src/features/schema/schema.handler.ts +131 -16
  105. package/src/features/seeds/index.ts +5 -0
  106. package/src/features/seeds/seeds.handler.test.ts +1199 -0
  107. package/src/features/seeds/seeds.handler.ts +558 -0
  108. package/src/features/settings/__tests__/settings.handler.test.ts +555 -0
  109. package/src/features/settings/settings.handler.ts +392 -302
  110. package/src/features/setup/index.ts +288 -91
  111. package/src/features/stats/index.ts +5 -1
  112. package/src/features/stats/stats.handler.ts +420 -430
  113. package/src/features/webhooks/index.ts +63 -0
  114. package/src/index.ts +65 -56
  115. package/src/media-utils.ts +82 -78
  116. package/src/middleware/auth-providers.middleware.test.ts +85 -0
  117. package/src/middleware/auth-providers.middleware.ts +45 -32
  118. package/src/middleware/observability.middleware.test.ts +93 -0
  119. package/src/middleware/observability.middleware.ts +70 -52
  120. package/src/middleware/rate-limit.middleware.ts +45 -41
  121. package/src/middleware/repository.middleware.ts +117 -91
  122. package/src/middleware/seed-registry.middleware.test.ts +97 -0
  123. package/src/middleware/seed-registry.middleware.ts +21 -0
  124. package/src/middleware/storage.middleware.ts +25 -21
  125. package/src/middleware.ts +45 -47
  126. package/src/public/access-policy.ts +27 -23
  127. package/src/public/api-key-middleware.ts +57 -53
  128. package/src/public/cache-utils.ts +38 -34
  129. package/src/public/entry-projection.ts +46 -42
  130. package/src/public/idempotency.ts +23 -19
  131. package/src/public/index.ts +16 -12
  132. package/src/public/problem-details.ts +124 -53
  133. package/src/public/public-add.ts +114 -110
  134. package/src/public/public-edit.ts +163 -159
  135. package/src/public/public-errors.ts +19 -15
  136. package/src/public/public-read.ts +63 -59
  137. package/src/public/public-routes.ts +88 -84
  138. package/src/public/query-builder.test.ts +224 -220
  139. package/src/public/query-builder.ts +156 -152
  140. package/src/public/rate-limit-middleware.ts +34 -30
  141. package/src/public/read-list.ts +54 -50
  142. package/src/public/read-single.ts +48 -44
  143. package/src/public/response-builder.ts +30 -26
  144. package/src/public/sanitize.ts +69 -65
  145. package/src/public/slug-utils.ts +18 -14
  146. package/src/rate-limit/cloudflare-rate-limiter.test.ts +30 -26
  147. package/src/rate-limit/cloudflare-rate-limiter.ts +15 -11
  148. package/src/rate-limit/in-memory-rate-limiter.test.ts +37 -33
  149. package/src/rate-limit/in-memory-rate-limiter.ts +17 -13
  150. package/src/rate-limit/no-op-rate-limiter.test.ts +22 -18
  151. package/src/rate-limit/no-op-rate-limiter.ts +11 -7
  152. package/src/search-utils.test.ts +211 -207
  153. package/src/search-utils.ts +213 -209
  154. package/src/search.ts +65 -61
  155. package/src/shared/apply-policies.test.ts +81 -77
  156. package/src/shared/apply-policies.ts +67 -63
  157. package/src/shared/automations.repository.d1.ts +150 -146
  158. package/src/shared/background-notification-service.test.ts +62 -58
  159. package/src/shared/background-notification-service.ts +52 -48
  160. package/src/shared/base.repository.d1.ts +32 -28
  161. package/src/shared/content-utils.test.ts +165 -161
  162. package/src/shared/content-utils.ts +86 -82
  163. package/src/shared/content.repository.d1.test.ts +507 -312
  164. package/src/shared/content.repository.d1.ts +851 -382
  165. package/src/shared/d1-activity-log.repository.test.ts +140 -136
  166. package/src/shared/d1-activity-log.repository.ts +105 -101
  167. package/src/shared/d1-activity-logger.test.ts +86 -82
  168. package/src/shared/d1-activity-logger.ts +67 -63
  169. package/src/shared/d1-analytics.repository.test.ts +78 -74
  170. package/src/shared/d1-analytics.repository.ts +85 -81
  171. package/src/shared/d1-content-scan.repository.test.ts +80 -76
  172. package/src/shared/d1-content-scan.repository.ts +37 -29
  173. package/src/shared/d1-notification.repository.test.ts +128 -124
  174. package/src/shared/d1-notification.repository.ts +118 -114
  175. package/src/shared/d1-password-reset-token.repository.test.ts +81 -77
  176. package/src/shared/d1-password-reset-token.repository.ts +56 -52
  177. package/src/shared/d1-search.repository.test.ts +87 -83
  178. package/src/shared/d1-search.repository.ts +88 -84
  179. package/src/shared/d1-session.repository.test.ts +125 -121
  180. package/src/shared/d1-session.repository.ts +102 -98
  181. package/src/shared/d1-setup-checklist.repository.ts +36 -0
  182. package/src/shared/d1-user.repository.test.ts +151 -147
  183. package/src/shared/d1-user.repository.ts +119 -109
  184. package/src/shared/d1-widget.repository.test.ts +267 -217
  185. package/src/shared/d1-widget.repository.ts +385 -337
  186. package/src/shared/dashboard-layout.repository.d1.test.ts +135 -0
  187. package/src/shared/dashboard-layout.repository.d1.ts +58 -0
  188. package/src/shared/demo-data-sql.ts +216 -0
  189. package/src/shared/demo-data.repository.d1.ts +20 -0
  190. package/src/shared/execution-context-scheduler.ts +13 -9
  191. package/src/shared/fixed-clock.ts +25 -21
  192. package/src/shared/fts-sync.ts +8 -4
  193. package/src/shared/idempotency.repository.d1.test.ts +83 -79
  194. package/src/shared/idempotency.repository.d1.ts +60 -56
  195. package/src/shared/in-memory-activity-logger.ts +19 -15
  196. package/src/shared/in-memory-notification-service.ts +19 -15
  197. package/src/shared/in-memory-seed.repository.ts +58 -0
  198. package/src/shared/media.repository.d1.test.ts +107 -103
  199. package/src/shared/media.repository.d1.ts +68 -64
  200. package/src/shared/qstash-notification-service.test.ts +67 -0
  201. package/src/shared/qstash-notification-service.ts +55 -0
  202. package/src/shared/query-utils.ts +141 -137
  203. package/src/shared/request-utils.ts +26 -22
  204. package/src/shared/schema-mutator.d1.test.ts +142 -0
  205. package/src/shared/schema-mutator.d1.ts +64 -0
  206. package/src/shared/seed-layout.repository.d1.test.ts +114 -0
  207. package/src/shared/seed-layout.repository.d1.ts +62 -0
  208. package/src/shared/seed-registry-cache.test.ts +68 -0
  209. package/src/shared/seed-registry-cache.ts +49 -0
  210. package/src/shared/seed.repository.d1.test.ts +143 -0
  211. package/src/shared/seed.repository.d1.ts +98 -0
  212. package/src/shared/sequential-id-generator.ts +33 -22
  213. package/src/shared/site-settings.repository.d1.ts +53 -0
  214. package/src/shared/storage/factory.ts +41 -40
  215. package/src/shared/storage/s3-bucket.ts +195 -163
  216. package/src/shared/storage-utils.ts +40 -36
  217. package/src/shared/system-stats.repository.d1.test.ts +58 -54
  218. package/src/shared/system-stats.repository.d1.ts +48 -44
  219. package/src/types.ts +90 -67
  220. package/src/upload.ts +198 -187
  221. package/src/widget.test.ts +85 -0
  222. package/src/widget.ts +251 -208
  223. package/assets/dashboard/assets/index-B1mUfgiK.css +0 -1
  224. package/assets/dashboard/assets/index-CHxxc_id.js +0 -629
  225. package/src/shared/storage/r2-binding-bucket.ts +0 -81
@@ -0,0 +1,1199 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // Copyright (c) 2024–2026 Flavio De Musso. All rights reserved.
3
+ // See LICENSE in the repository root for license terms.
4
+
5
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
6
+ import { Hono } from 'hono'
7
+ import type { Branch, ISeedRepository, ISchemaMutator, Seed, SeedRecord } from '@beechcms/core'
8
+ import { seedsApp } from './seeds.handler'
9
+
10
+ // ─── Fixtures ────────────────────────────────────────────────────────────────
11
+
12
+ const baseSeed: Seed = {
13
+ slug: 'articles',
14
+ label: 'Articles',
15
+ displayNameAlias: 'title',
16
+ branches: [
17
+ { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
18
+ { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
19
+ ],
20
+ }
21
+
22
+ const baseRecord: SeedRecord = {
23
+ slug: 'articles',
24
+ definition: baseSeed,
25
+ status: 'active',
26
+ source: 'runtime',
27
+ createdAt: 0,
28
+ updatedAt: 0,
29
+ }
30
+
31
+ // ─── Fake repositories ────────────────────────────────────────────────────────
32
+
33
+ function makeRepo(overrides: Partial<ISeedRepository> = {}): ISeedRepository {
34
+ return {
35
+ listActive: vi.fn().mockResolvedValue([baseSeed]),
36
+ listAll: vi.fn().mockResolvedValue([baseRecord]),
37
+ get: vi.fn().mockResolvedValue(null),
38
+ upsert: vi.fn().mockResolvedValue(undefined),
39
+ softDelete: vi.fn().mockResolvedValue(undefined),
40
+ hardDelete: vi.fn().mockResolvedValue(undefined),
41
+ getRegistryVersion: vi.fn().mockResolvedValue(1),
42
+ bumpRegistryVersion: vi.fn().mockResolvedValue(2),
43
+ ...overrides,
44
+ }
45
+ }
46
+
47
+ function makeMutator(overrides: Partial<ISchemaMutator> = {}): ISchemaMutator {
48
+ return {
49
+ getColumns: vi.fn().mockResolvedValue(null),
50
+ execDdl: vi.fn().mockResolvedValue(undefined),
51
+ dropTable: vi.fn().mockResolvedValue(undefined),
52
+ dropColumn: vi.fn().mockResolvedValue(undefined),
53
+ renameColumn: vi.fn().mockResolvedValue(undefined),
54
+ execDestructive: vi.fn().mockResolvedValue(undefined),
55
+ ...overrides,
56
+ }
57
+ }
58
+
59
+ function makeActivityLogger() {
60
+ return { log: vi.fn() }
61
+ }
62
+
63
+ // ─── App builder ─────────────────────────────────────────────────────────────
64
+
65
+ function buildApp(opts: {
66
+ role?: string
67
+ jwtPayload?: Record<string, unknown> | null
68
+ repo?: ISeedRepository
69
+ mutator?: ISchemaMutator
70
+ backrefMap?: Map<string, any[]>
71
+ automationRepository?: any
72
+ db?: any
73
+ bucket?: any
74
+ mediaRepository?: any
75
+ systemStatsRepository?: any
76
+ } = {}) {
77
+ const app = new Hono()
78
+ const repo = opts.repo ?? makeRepo()
79
+ const mutator = opts.mutator ?? makeMutator()
80
+ const backrefMap = opts.backrefMap ?? new Map()
81
+ const activityLogger = makeActivityLogger()
82
+ // Default stub DB (used by hard-delete R2 cascade) — no results
83
+ const db = opts.db ?? { prepare: () => ({ all: async () => ({ results: [] }) }) }
84
+ const automationRepository = opts.automationRepository ?? { list: async () => [] }
85
+ const bucket = opts.bucket ?? { delete: vi.fn().mockResolvedValue(undefined) }
86
+ const mediaRepository = opts.mediaRepository ?? { getByKey: vi.fn().mockResolvedValue(null), untrack: vi.fn().mockResolvedValue(undefined) }
87
+ const systemStatsRepository = opts.systemStatsRepository ?? { decrementStorage: vi.fn().mockResolvedValue(undefined) }
88
+
89
+ app.use('*', async (c, next) => {
90
+ const jwtPayload = opts.jwtPayload !== undefined
91
+ ? opts.jwtPayload
92
+ : (opts.role ? { sub: 'u1', email: 'a@b.com', role: opts.role } : null)
93
+ c.set('jwtPayload' as never, jwtPayload)
94
+ c.set('seedRepository' as never, repo)
95
+ c.set('schemaMutator' as never, mutator)
96
+ c.set('backrefMap' as never, backrefMap)
97
+ c.set('activityLogger' as never, activityLogger)
98
+ c.set('automationRepository' as never, automationRepository)
99
+ c.set('env' as never, { ENV: 'test', DB: db })
100
+ c.set('bucket' as never, bucket)
101
+ c.set('mediaRepository' as never, mediaRepository)
102
+ c.set('systemStatsRepository' as never, systemStatsRepository)
103
+ await next()
104
+ })
105
+ app.route('/', seedsApp)
106
+
107
+ // Default `c.env` (used by internalErrorDetail) so error paths don't crash
108
+ // on `context.env.ENV` when the test doesn't pass an explicit env binding.
109
+ const defaultEnv = { ENV: 'test', DB: db }
110
+ const originalRequest = app.request.bind(app)
111
+ app.request = ((input: any, init?: any, env?: any, executionCtx?: any) =>
112
+ originalRequest(input, init, env ?? defaultEnv, executionCtx)) as typeof app.request
113
+
114
+ return { app, repo, mutator, activityLogger, bucket, mediaRepository, systemStatsRepository, db }
115
+ }
116
+
117
+ // ─── Tests ────────────────────────────────────────────────────────────────────
118
+
119
+ describe('GET /', () => {
120
+ it('403 for non-admin', async () => {
121
+ const { app } = buildApp({ role: 'user' })
122
+ const res = await app.request('/', { method: 'GET' })
123
+ expect(res.status).toBe(403)
124
+ })
125
+
126
+ it('200 returns all records', async () => {
127
+ const { app } = buildApp({ role: 'admin' })
128
+ const res = await app.request('/', { method: 'GET' })
129
+ expect(res.status).toBe(200)
130
+ const body = await res.json() as any[]
131
+ expect(body).toHaveLength(1)
132
+ expect(body[0].slug).toBe('articles')
133
+ })
134
+ })
135
+
136
+ describe('GET /:slug', () => {
137
+ it('404 for missing seed', async () => {
138
+ const { app } = buildApp({ role: 'admin' })
139
+ const res = await app.request('/nope', { method: 'GET' })
140
+ expect(res.status).toBe(404)
141
+ })
142
+
143
+ it('200 returns the record', async () => {
144
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
145
+ const { app } = buildApp({ role: 'admin', repo })
146
+ const res = await app.request('/articles', { method: 'GET' })
147
+ expect(res.status).toBe(200)
148
+ const body = await res.json() as any
149
+ expect(body.slug).toBe('articles')
150
+ })
151
+ })
152
+
153
+ describe('POST / (create)', () => {
154
+ it('403 for non-admin', async () => {
155
+ const { app } = buildApp({ role: 'user' })
156
+ const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
157
+ expect(res.status).toBe(403)
158
+ })
159
+
160
+ it('409 when slug already active', async () => {
161
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
162
+ const { app } = buildApp({ role: 'admin', repo })
163
+ const res = await app.request('/', {
164
+ method: 'POST',
165
+ headers: { 'Content-Type': 'application/json' },
166
+ body: JSON.stringify(baseSeed),
167
+ })
168
+ expect(res.status).toBe(409)
169
+ })
170
+
171
+ it('creates new seed: planCreateSeed DDL emitted, upsert called, 201', async () => {
172
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
173
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
174
+ const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
175
+
176
+ const newSeed: Seed = {
177
+ slug: 'notes',
178
+ label: 'Notes',
179
+ displayNameAlias: 'title',
180
+ branches: [{ id: 'br_01', alias: 'title', label: 'Title', type: 'text' }],
181
+ }
182
+ const res = await app.request('/', {
183
+ method: 'POST',
184
+ headers: { 'Content-Type': 'application/json' },
185
+ body: JSON.stringify(newSeed),
186
+ })
187
+ expect(res.status).toBe(201)
188
+
189
+ const ddlCalls = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls
190
+ expect(ddlCalls.length).toBe(1)
191
+ const stmts: string[] = ddlCalls[0][0]
192
+ expect(stmts.some((s: string) => s.includes('CREATE TABLE') && s.includes('content_notes'))).toBe(true)
193
+ expect(stmts.some((s: string) => s.includes('DROP'))).toBe(false)
194
+
195
+ expect((repo.upsert as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
196
+ expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
197
+ expect(activityLogger.log.mock.calls.length).toBe(1)
198
+ expect(activityLogger.log.mock.calls[0][0].action).toBe('create')
199
+
200
+ const body = await res.json() as any
201
+ expect(body.slug).toBe('notes')
202
+ })
203
+
204
+ it('assigns br_NN ids to branches without ids', async () => {
205
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
206
+ const mutator = makeMutator()
207
+ const { app } = buildApp({ role: 'admin', repo, mutator })
208
+
209
+ const noIdSeed = {
210
+ slug: 'tags',
211
+ label: 'Tags',
212
+ displayNameAlias: 'name',
213
+ branches: [{ alias: 'name', label: 'Name', type: 'text' }],
214
+ }
215
+ const res = await app.request('/', {
216
+ method: 'POST',
217
+ headers: { 'Content-Type': 'application/json' },
218
+ body: JSON.stringify(noIdSeed),
219
+ })
220
+ expect(res.status).toBe(201)
221
+ const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
222
+ expect(upsertArg.branches[0].id).toMatch(/^br_\d+$/)
223
+ })
224
+
225
+ it('revives a soft-deleted seed without failing on IF NOT EXISTS', async () => {
226
+ const deletedRecord: SeedRecord = { ...baseRecord, status: 'deleted' }
227
+ const repo = makeRepo({
228
+ get: vi.fn().mockResolvedValue(deletedRecord),
229
+ listActive: vi.fn().mockResolvedValue([]),
230
+ })
231
+ const existingCols = new Set(['id', 'title'])
232
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
233
+ const { app } = buildApp({ role: 'admin', repo, mutator })
234
+
235
+ const res = await app.request('/', {
236
+ method: 'POST',
237
+ headers: { 'Content-Type': 'application/json' },
238
+ body: JSON.stringify(baseSeed),
239
+ })
240
+ expect(res.status).toBe(201)
241
+ // No CREATE TABLE was emitted (table already exists), planExtendSeed path taken
242
+ const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
243
+ expect(stmts.every((s: string) => !s.includes('CREATE TABLE IF NOT EXISTS content_articles') || s.includes('IF NOT EXISTS'))).toBe(true)
244
+ })
245
+
246
+ it('422 for unknown relation target', async () => {
247
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
248
+ const { app } = buildApp({ role: 'admin', repo })
249
+
250
+ const relSeed: Seed = {
251
+ slug: 'posts',
252
+ label: 'Posts',
253
+ displayNameAlias: 'title',
254
+ branches: [
255
+ { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
256
+ { id: 'br_02', alias: 'author', label: 'Author', type: 'relation', targetSeed: 'nonexistent' },
257
+ ],
258
+ }
259
+ const res = await app.request('/', {
260
+ method: 'POST',
261
+ headers: { 'Content-Type': 'application/json' },
262
+ body: JSON.stringify(relSeed),
263
+ })
264
+ expect(res.status).toBe(422)
265
+ })
266
+ })
267
+
268
+ describe('PUT /:slug (edit)', () => {
269
+ it('403 for non-admin', async () => {
270
+ const { app } = buildApp({ role: 'user' })
271
+ const res = await app.request('/articles', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
272
+ expect(res.status).toBe(403)
273
+ })
274
+
275
+ it('422 on alias rename (same id, different alias)', async () => {
276
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
277
+ const { app } = buildApp({ role: 'admin', repo })
278
+
279
+ const renamed: Seed = {
280
+ ...baseSeed,
281
+ branches: [
282
+ { id: 'br_01', alias: 'headline', label: 'Headline', type: 'text' }, // alias changed
283
+ { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
284
+ ],
285
+ }
286
+ const res = await app.request('/articles', {
287
+ method: 'PUT',
288
+ headers: { 'Content-Type': 'application/json' },
289
+ body: JSON.stringify(renamed),
290
+ })
291
+ expect(res.status).toBe(422)
292
+ const body = await res.json() as any
293
+ expect(body.type).toContain('alias-rename-not-supported')
294
+ })
295
+
296
+ it('422 on branch type change', async () => {
297
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
298
+ const { app } = buildApp({ role: 'admin', repo })
299
+
300
+ const typeChanged: Seed = {
301
+ ...baseSeed,
302
+ branches: [
303
+ { id: 'br_01', alias: 'title', label: 'Title', type: 'number' }, // type changed
304
+ { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
305
+ ],
306
+ }
307
+ const res = await app.request('/articles', {
308
+ method: 'PUT',
309
+ headers: { 'Content-Type': 'application/json' },
310
+ body: JSON.stringify(typeChanged),
311
+ })
312
+ expect(res.status).toBe(422)
313
+ const body = await res.json() as any
314
+ expect(body.type).toContain('branch-type-change-not-supported')
315
+ })
316
+
317
+ it('add branch emits ADD COLUMN, no DROP', async () => {
318
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
319
+ const existingCols = new Set(['id', 'title', 'body'])
320
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
321
+ const { app } = buildApp({ role: 'admin', repo, mutator })
322
+
323
+ const withNew: Seed = {
324
+ ...baseSeed,
325
+ branches: [
326
+ ...baseSeed.branches,
327
+ { id: 'br_03', alias: 'summary', label: 'Summary', type: 'text' },
328
+ ],
329
+ }
330
+ const res = await app.request('/articles', {
331
+ method: 'PUT',
332
+ headers: { 'Content-Type': 'application/json' },
333
+ body: JSON.stringify(withNew),
334
+ })
335
+ expect(res.status).toBe(200)
336
+
337
+ const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
338
+ expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('summary'))).toBe(true)
339
+ expect(stmts.every((s: string) => !s.includes('DROP'))).toBe(true)
340
+ })
341
+
342
+ it('removing a branch: no DROP emitted, column retained', async () => {
343
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
344
+ const existingCols = new Set(['id', 'title', 'body'])
345
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
346
+ const { app } = buildApp({ role: 'admin', repo, mutator })
347
+
348
+ const withRemoved: Seed = {
349
+ ...baseSeed,
350
+ branches: [baseSeed.branches[0]], // body removed
351
+ }
352
+ const res = await app.request('/articles', {
353
+ method: 'PUT',
354
+ headers: { 'Content-Type': 'application/json' },
355
+ body: JSON.stringify(withRemoved),
356
+ })
357
+ expect(res.status).toBe(200)
358
+
359
+ const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
360
+ expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
361
+ })
362
+ })
363
+
364
+ describe('POST /:slug/branches (add branch)', () => {
365
+ it('assigns id and emits ADD COLUMN', async () => {
366
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
367
+ const existingCols = new Set(['id', 'title', 'body'])
368
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
369
+ const { app } = buildApp({ role: 'admin', repo, mutator })
370
+
371
+ const res = await app.request('/articles/branches', {
372
+ method: 'POST',
373
+ headers: { 'Content-Type': 'application/json' },
374
+ body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
375
+ })
376
+ expect(res.status).toBe(200)
377
+ const body = await res.json() as any
378
+ expect(body.id).toMatch(/^br_\d+$/)
379
+
380
+ const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
381
+ expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('excerpt'))).toBe(true)
382
+ })
383
+
384
+ it('column already present: no ADD COLUMN emitted', async () => {
385
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
386
+ const existingCols = new Set(['id', 'title', 'body', 'excerpt'])
387
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
388
+ const { app } = buildApp({ role: 'admin', repo, mutator })
389
+
390
+ const res = await app.request('/articles/branches', {
391
+ method: 'POST',
392
+ headers: { 'Content-Type': 'application/json' },
393
+ body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
394
+ })
395
+ expect(res.status).toBe(200)
396
+
397
+ const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
398
+ expect(stmts.every((s: string) => !s.includes('ADD COLUMN'))).toBe(true)
399
+ })
400
+ })
401
+
402
+ describe('DELETE /:slug', () => {
403
+ it('403 for non-admin', async () => {
404
+ const { app } = buildApp({ role: 'user' })
405
+ const res = await app.request('/articles', { method: 'DELETE' })
406
+ expect(res.status).toBe(403)
407
+ })
408
+
409
+ it('soft-deletes: status flips, table not dropped, version bumped', async () => {
410
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
411
+ const mutator = makeMutator()
412
+ const { app } = buildApp({ role: 'admin', repo, mutator })
413
+
414
+ const res = await app.request('/articles', { method: 'DELETE' })
415
+ expect(res.status).toBe(200)
416
+
417
+ expect((repo.softDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
418
+ expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
419
+
420
+ // No DDL involving DROP was emitted
421
+ const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
422
+ expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
423
+ })
424
+
425
+ it('409 when seed is referenced by another seed relation', async () => {
426
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
427
+ const backrefMap = new Map([['articles', [{ seedSlug: 'comments', branchAlias: 'article' }]]])
428
+ const { app } = buildApp({ role: 'admin', repo, backrefMap })
429
+
430
+ const res = await app.request('/articles', { method: 'DELETE' })
431
+ expect(res.status).toBe(409)
432
+ const body = await res.json() as any
433
+ expect(body.type).toContain('seed-referenced')
434
+ })
435
+
436
+ it('404 for non-existent seed', async () => {
437
+ const { app } = buildApp({ role: 'admin' })
438
+ const res = await app.request('/nope', { method: 'DELETE' })
439
+ expect(res.status).toBe(404)
440
+ })
441
+ })
442
+
443
+ // ─── Sprint 06 Danger Zone routes ────────────────────────────────────────────
444
+
445
+ describe('GET /:slug/orphans', () => {
446
+ it('returns orphan columns not in the definition', async () => {
447
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
448
+ // DB has 'id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'
449
+ const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'])
450
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
451
+ const { app } = buildApp({ role: 'admin', repo, mutator })
452
+
453
+ const res = await app.request('/articles/orphans', { method: 'GET' })
454
+ expect(res.status).toBe(200)
455
+ const body = await res.json() as any
456
+ expect(body.orphans).toContain('legacy')
457
+ expect(body.orphans).not.toContain('title')
458
+ })
459
+
460
+ it('returns empty when DB has no orphans', async () => {
461
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
462
+ const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body'])
463
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
464
+ const { app } = buildApp({ role: 'admin', repo, mutator })
465
+
466
+ const res = await app.request('/articles/orphans', { method: 'GET' })
467
+ expect(res.status).toBe(200)
468
+ const body = await res.json() as any
469
+ expect(body.orphans).toHaveLength(0)
470
+ })
471
+ })
472
+
473
+ describe('DELETE /:slug/hard', () => {
474
+ it('400 on confirm mismatch', async () => {
475
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
476
+ const { app } = buildApp({ role: 'admin', repo })
477
+
478
+ const res = await app.request('/articles/hard', {
479
+ method: 'DELETE',
480
+ headers: { 'Content-Type': 'application/json' },
481
+ body: JSON.stringify({ confirm: 'wrong' }),
482
+ })
483
+ expect(res.status).toBe(400)
484
+ const body = await res.json() as any
485
+ expect(body.type).toContain('confirmation-required')
486
+ })
487
+
488
+ it('409 when seed is referenced', async () => {
489
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
490
+ const backrefMap = new Map([['articles', [{ sourceSlug: 'comments' }]]])
491
+ const { app } = buildApp({ role: 'admin', repo, backrefMap })
492
+
493
+ const res = await app.request('/articles/hard', {
494
+ method: 'DELETE',
495
+ headers: { 'Content-Type': 'application/json' },
496
+ body: JSON.stringify({ confirm: 'articles' }),
497
+ })
498
+ expect(res.status).toBe(409)
499
+ })
500
+
501
+ it('hard delete: execDestructive called, hardDelete called, version bumped, audit logged', async () => {
502
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
503
+ const mutator = makeMutator()
504
+ const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
505
+
506
+ const res = await app.request('/articles/hard', {
507
+ method: 'DELETE',
508
+ headers: { 'Content-Type': 'application/json' },
509
+ body: JSON.stringify({ confirm: 'articles' }),
510
+ })
511
+ expect(res.status).toBe(200)
512
+
513
+ expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(0)
514
+ // execDdl must NOT have been called for DROP
515
+ const ddlCalls: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
516
+ expect(ddlCalls.every((s: string) => !s.toUpperCase().includes('DROP'))).toBe(true)
517
+
518
+ expect((repo.hardDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
519
+ expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
520
+ expect(activityLogger.log.mock.calls[0][0].action).toBe('delete')
521
+ expect(activityLogger.log.mock.calls[0][0].details.op).toBe('hard-delete')
522
+ })
523
+ })
524
+
525
+ describe('DELETE /:slug/branches/:branchId', () => {
526
+ it('400 on confirm mismatch', async () => {
527
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
528
+ const { app } = buildApp({ role: 'admin', repo })
529
+
530
+ const res = await app.request('/articles/branches/br_01', {
531
+ method: 'DELETE',
532
+ headers: { 'Content-Type': 'application/json' },
533
+ body: JSON.stringify({ confirm: 'wrong' }),
534
+ })
535
+ expect(res.status).toBe(400)
536
+ })
537
+
538
+ it('drops branch: execDestructive called, definition updated, version bumped', async () => {
539
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
540
+ const mutator = makeMutator()
541
+ const { app } = buildApp({ role: 'admin', repo, mutator })
542
+
543
+ const res = await app.request('/articles/branches/br_02', {
544
+ method: 'DELETE',
545
+ headers: { 'Content-Type': 'application/json' },
546
+ body: JSON.stringify({ confirm: 'articles.body' }),
547
+ })
548
+ expect(res.status).toBe(200)
549
+
550
+ expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
551
+ const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
552
+ expect(upsertArg.branches.find((b: any) => b.id === 'br_02')).toBeUndefined()
553
+ expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
554
+ })
555
+
556
+ it('404 for unknown branchId', async () => {
557
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
558
+ const { app } = buildApp({ role: 'admin', repo })
559
+
560
+ const res = await app.request('/articles/branches/br_99', {
561
+ method: 'DELETE',
562
+ headers: { 'Content-Type': 'application/json' },
563
+ body: JSON.stringify({ confirm: 'articles.unknown' }),
564
+ })
565
+ expect(res.status).toBe(404)
566
+ })
567
+ })
568
+
569
+ describe('PATCH /:slug/branches/:branchId/rename', () => {
570
+ it('400 on confirm mismatch', async () => {
571
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
572
+ const { app } = buildApp({ role: 'admin', repo })
573
+
574
+ const res = await app.request('/articles/branches/br_01/rename', {
575
+ method: 'PATCH',
576
+ headers: { 'Content-Type': 'application/json' },
577
+ body: JSON.stringify({ newAlias: 'headline', confirm: 'wrong' }),
578
+ })
579
+ expect(res.status).toBe(400)
580
+ })
581
+
582
+ it('renames alias: execDestructive called with RENAME, definition updated, automation warnings returned', async () => {
583
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
584
+ const mutator = makeMutator()
585
+ const automationRepository = { list: vi.fn().mockResolvedValue([{ id: 'auto_1', conditions: 'title' }]) }
586
+ const { app } = buildApp({ role: 'admin', repo, mutator, automationRepository })
587
+
588
+ const res = await app.request('/articles/branches/br_01/rename', {
589
+ method: 'PATCH',
590
+ headers: { 'Content-Type': 'application/json' },
591
+ body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.title' }),
592
+ })
593
+ expect(res.status).toBe(200)
594
+
595
+ const destructiveCalls: string[] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
596
+ expect(destructiveCalls.some((s: string) => s.toUpperCase().includes('RENAME COLUMN') || s.toUpperCase().includes('RENAME TO'))).toBe(true)
597
+
598
+ const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
599
+ const renamed = upsertArg.branches.find((b: any) => b.id === 'br_01')
600
+ expect(renamed?.alias).toBe('headline')
601
+
602
+ const body = await res.json() as any
603
+ expect(body.affectedAutomations).toContain('auto_1')
604
+ })
605
+ })
606
+
607
+ describe('PATCH /:slug/branches/:branchId/retype', () => {
608
+ it('400 on confirm mismatch', async () => {
609
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
610
+ const { app } = buildApp({ role: 'admin', repo })
611
+
612
+ const res = await app.request('/articles/branches/br_01/retype', {
613
+ method: 'PATCH',
614
+ headers: { 'Content-Type': 'application/json' },
615
+ body: JSON.stringify({ newType: 'number', confirm: 'wrong' }),
616
+ })
617
+ expect(res.status).toBe(400)
618
+ })
619
+
620
+ it('retypes branch: execDestructive called, definition updated, version bumped', async () => {
621
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
622
+ const mutator = makeMutator()
623
+ const { app } = buildApp({ role: 'admin', repo, mutator })
624
+
625
+ const res = await app.request('/articles/branches/br_01/retype', {
626
+ method: 'PATCH',
627
+ headers: { 'Content-Type': 'application/json' },
628
+ body: JSON.stringify({ newType: 'number', confirm: 'articles.title' }),
629
+ })
630
+ expect(res.status).toBe(200)
631
+
632
+ expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
633
+ const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
634
+ expect(upsertArg.branches.find((b: any) => b.id === 'br_01')?.type).toBe('number')
635
+ expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
636
+ })
637
+
638
+ it('422 retype-not-supported when retyping a repeater branch away', async () => {
639
+ const repeaterRecord: SeedRecord = {
640
+ ...baseRecord,
641
+ definition: {
642
+ ...baseSeed,
643
+ branches: [
644
+ baseSeed.branches[0],
645
+ { id: 'br_02', alias: 'items', label: 'Items', type: 'repeater', fields: [] },
646
+ ],
647
+ },
648
+ }
649
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(repeaterRecord) })
650
+ const { app } = buildApp({ role: 'admin', repo })
651
+
652
+ const res = await app.request('/articles/branches/br_02/retype', {
653
+ method: 'PATCH',
654
+ headers: { 'Content-Type': 'application/json' },
655
+ body: JSON.stringify({ newType: 'text', confirm: 'articles.items' }),
656
+ })
657
+ expect(res.status).toBe(422)
658
+ const problem = await res.json() as any
659
+ expect(problem.type).toContain('retype-not-supported')
660
+ })
661
+
662
+ it('422 retype-not-supported when retyping a branch to repeater', async () => {
663
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
664
+ const { app } = buildApp({ role: 'admin', repo })
665
+
666
+ const res = await app.request('/articles/branches/br_01/retype', {
667
+ method: 'PATCH',
668
+ headers: { 'Content-Type': 'application/json' },
669
+ body: JSON.stringify({ newType: 'repeater', confirm: 'articles.title' }),
670
+ })
671
+ expect(res.status).toBe(422)
672
+ const problem = await res.json() as any
673
+ expect(problem.type).toContain('retype-not-supported')
674
+ })
675
+ })
676
+
677
+ describe('POST /:slug/fts/rebuild', () => {
678
+ it('calls execDestructive with FTS statements and logs audit', async () => {
679
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
680
+ const mutator = makeMutator()
681
+ const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
682
+
683
+ const res = await app.request('/articles/fts/rebuild', { method: 'POST' })
684
+ expect(res.status).toBe(200)
685
+
686
+ expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
687
+ const stmts: string[] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
688
+ expect(stmts.some((s: string) => s.includes('fts_articles'))).toBe(true)
689
+ expect(activityLogger.log.mock.calls[0][0].details.op).toBe('fts-rebuild')
690
+ })
691
+
692
+ it('404 for non-existent seed', async () => {
693
+ const { app } = buildApp({ role: 'admin' })
694
+ const res = await app.request('/nope/fts/rebuild', { method: 'POST' })
695
+ expect(res.status).toBe(404)
696
+ })
697
+ })
698
+
699
+ // ─── Malformed JSON bodies ────────────────────────────────────────────────────
700
+
701
+ describe('Malformed JSON body', () => {
702
+ it('POST / returns 400 invalid-json on bad body', async () => {
703
+ const { app } = buildApp({ role: 'admin' })
704
+ const res = await app.request('/', {
705
+ method: 'POST',
706
+ headers: { 'Content-Type': 'application/json' },
707
+ body: '{not valid json',
708
+ })
709
+ expect(res.status).toBe(400)
710
+ const body = await res.json() as any
711
+ expect(body.type).toContain('invalid-json')
712
+ })
713
+
714
+ it('PUT /:slug returns 400 invalid-json on bad body', async () => {
715
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
716
+ const { app } = buildApp({ role: 'admin', repo })
717
+ const res = await app.request('/articles', {
718
+ method: 'PUT',
719
+ headers: { 'Content-Type': 'application/json' },
720
+ body: '{not valid json',
721
+ })
722
+ expect(res.status).toBe(400)
723
+ })
724
+
725
+ it('POST /:slug/branches returns 400 invalid-json on bad body', async () => {
726
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
727
+ const { app } = buildApp({ role: 'admin', repo })
728
+ const res = await app.request('/articles/branches', {
729
+ method: 'POST',
730
+ headers: { 'Content-Type': 'application/json' },
731
+ body: '{not valid json',
732
+ })
733
+ expect(res.status).toBe(400)
734
+ })
735
+
736
+ it('DELETE /:slug/hard returns 400 invalid-json on bad body', async () => {
737
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
738
+ const { app } = buildApp({ role: 'admin', repo })
739
+ const res = await app.request('/articles/hard', {
740
+ method: 'DELETE',
741
+ headers: { 'Content-Type': 'application/json' },
742
+ body: '{not valid json',
743
+ })
744
+ expect(res.status).toBe(400)
745
+ })
746
+
747
+ it('DELETE /:slug/branches/:branchId returns 400 invalid-json on bad body', async () => {
748
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
749
+ const { app } = buildApp({ role: 'admin', repo })
750
+ const res = await app.request('/articles/branches/br_01', {
751
+ method: 'DELETE',
752
+ headers: { 'Content-Type': 'application/json' },
753
+ body: '{not valid json',
754
+ })
755
+ expect(res.status).toBe(400)
756
+ })
757
+
758
+ it('PATCH rename returns 400 invalid-json on bad body', async () => {
759
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
760
+ const { app } = buildApp({ role: 'admin', repo })
761
+ const res = await app.request('/articles/branches/br_01/rename', {
762
+ method: 'PATCH',
763
+ headers: { 'Content-Type': 'application/json' },
764
+ body: '{not valid json',
765
+ })
766
+ expect(res.status).toBe(400)
767
+ })
768
+
769
+ it('PATCH retype returns 400 invalid-json on bad body', async () => {
770
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
771
+ const { app } = buildApp({ role: 'admin', repo })
772
+ const res = await app.request('/articles/branches/br_01/retype', {
773
+ method: 'PATCH',
774
+ headers: { 'Content-Type': 'application/json' },
775
+ body: '{not valid json',
776
+ })
777
+ expect(res.status).toBe(400)
778
+ })
779
+ })
780
+
781
+ // ─── Additional 404 / validation paths ───────────────────────────────────────
782
+
783
+ describe('Additional validation and 404 paths', () => {
784
+ it('POST / 400 on invalid slug format', async () => {
785
+ const { app } = buildApp({ role: 'admin' })
786
+ const invalid: Seed = { ...baseSeed, slug: 'Invalid Slug!' }
787
+ const res = await app.request('/', {
788
+ method: 'POST',
789
+ headers: { 'Content-Type': 'application/json' },
790
+ body: JSON.stringify(invalid),
791
+ })
792
+ expect(res.status).toBe(400)
793
+ })
794
+
795
+ it('POST / infers displayNameAlias from the first text branch when missing', async () => {
796
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
797
+ const { app, repo: usedRepo } = buildApp({ role: 'admin', repo })
798
+ const noDisplaySeed = {
799
+ slug: 'snippets',
800
+ label: 'Snippets',
801
+ branches: [
802
+ { id: 'br_01', alias: 'amount', label: 'Amount', type: 'number' },
803
+ { id: 'br_02', alias: 'headline', label: 'Headline', type: 'text' },
804
+ ],
805
+ }
806
+ const res = await app.request('/', {
807
+ method: 'POST',
808
+ headers: { 'Content-Type': 'application/json' },
809
+ body: JSON.stringify(noDisplaySeed),
810
+ })
811
+ expect(res.status).toBe(201)
812
+ const upsertArg = (usedRepo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
813
+ expect(upsertArg.displayNameAlias).toBe('headline')
814
+ })
815
+
816
+ it('POST / 400 when displayNameAlias missing and no text branch to infer from', async () => {
817
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
818
+ const { app } = buildApp({ role: 'admin', repo })
819
+ const noTextSeed = {
820
+ slug: 'numbers_only',
821
+ label: 'Numbers',
822
+ branches: [{ id: 'br_01', alias: 'amount', label: 'Amount', type: 'number' }],
823
+ }
824
+ const res = await app.request('/', {
825
+ method: 'POST',
826
+ headers: { 'Content-Type': 'application/json' },
827
+ body: JSON.stringify(noTextSeed),
828
+ })
829
+ expect(res.status).toBe(400)
830
+ })
831
+
832
+ it('POST / 422 ddl-failed when execDdl throws', async () => {
833
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
834
+ const mutator = makeMutator({ execDdl: vi.fn().mockRejectedValue(new Error('boom')) })
835
+ const { app } = buildApp({ role: 'admin', repo, mutator })
836
+
837
+ const newSeed: Seed = {
838
+ slug: 'broken',
839
+ label: 'Broken',
840
+ displayNameAlias: 'title',
841
+ branches: [{ id: 'br_01', alias: 'title', label: 'Title', type: 'text' }],
842
+ }
843
+ const res = await app.request('/', {
844
+ method: 'POST',
845
+ headers: { 'Content-Type': 'application/json' },
846
+ body: JSON.stringify(newSeed),
847
+ })
848
+ expect(res.status).toBe(422)
849
+ const body = await res.json() as any
850
+ expect(body.type).toContain('ddl-failed')
851
+ expect(body.detail).toContain('boom')
852
+ })
853
+
854
+ it('PUT /:slug 404 for non-existent seed', async () => {
855
+ const { app } = buildApp({ role: 'admin' })
856
+ const res = await app.request('/nope', {
857
+ method: 'PUT',
858
+ headers: { 'Content-Type': 'application/json' },
859
+ body: JSON.stringify(baseSeed),
860
+ })
861
+ expect(res.status).toBe(404)
862
+ })
863
+
864
+ it('PUT /:slug assigns an id to a newly added branch without one', async () => {
865
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
866
+ const existingCols = new Set(['id', 'title', 'body'])
867
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
868
+ const { app, repo: usedRepo } = buildApp({ role: 'admin', repo, mutator })
869
+
870
+ const withNewUnidentified: Seed = {
871
+ ...baseSeed,
872
+ branches: [
873
+ ...baseSeed.branches,
874
+ { alias: 'extra', label: 'Extra', type: 'text' } as Branch,
875
+ ],
876
+ }
877
+ const res = await app.request('/articles', {
878
+ method: 'PUT',
879
+ headers: { 'Content-Type': 'application/json' },
880
+ body: JSON.stringify(withNewUnidentified),
881
+ })
882
+ expect(res.status).toBe(200)
883
+ const upsertArg = (usedRepo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
884
+ const extra = upsertArg.branches.find((b) => b.alias === 'extra')
885
+ expect(extra?.id).toMatch(/^br_\d+$/)
886
+ })
887
+
888
+ it('POST /:slug/branches 404 for non-existent seed', async () => {
889
+ const { app } = buildApp({ role: 'admin' })
890
+ const res = await app.request('/nope/branches', {
891
+ method: 'POST',
892
+ headers: { 'Content-Type': 'application/json' },
893
+ body: JSON.stringify({ alias: 'x', label: 'X', type: 'text' }),
894
+ })
895
+ expect(res.status).toBe(404)
896
+ })
897
+
898
+ it('GET /:slug/orphans 404 for non-existent seed', async () => {
899
+ const { app } = buildApp({ role: 'admin' })
900
+ const res = await app.request('/nope/orphans', { method: 'GET' })
901
+ expect(res.status).toBe(404)
902
+ })
903
+
904
+ it('GET /:slug/orphans returns empty when DB columns are unknown (table does not exist)', async () => {
905
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
906
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
907
+ const { app } = buildApp({ role: 'admin', repo, mutator })
908
+
909
+ const res = await app.request('/articles/orphans', { method: 'GET' })
910
+ expect(res.status).toBe(200)
911
+ const body = await res.json() as any
912
+ expect(body.orphans).toEqual([])
913
+ })
914
+ })
915
+
916
+ // ─── Hard delete: media cascade ──────────────────────────────────────────────
917
+
918
+ describe('DELETE /:slug/hard — media cascade (deleteSeedMediaObjects)', () => {
919
+ const seedWithFile: Seed = {
920
+ slug: 'articles',
921
+ label: 'Articles',
922
+ displayNameAlias: 'title',
923
+ branches: [
924
+ { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
925
+ { id: 'br_02', alias: 'cover', label: 'Cover', type: 'file' },
926
+ ],
927
+ }
928
+ const recordWithFile: SeedRecord = { ...baseRecord, definition: seedWithFile }
929
+
930
+ it('400 on confirm mismatch', async () => {
931
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
932
+ const { app } = buildApp({ role: 'admin', repo })
933
+ const res = await app.request('/articles/hard', {
934
+ method: 'DELETE',
935
+ headers: { 'Content-Type': 'application/json' },
936
+ body: JSON.stringify({ confirm: 'wrong' }),
937
+ })
938
+ expect(res.status).toBe(400)
939
+ })
940
+
941
+ it('404 for non-existent seed', async () => {
942
+ const { app } = buildApp({ role: 'admin' })
943
+ const res = await app.request('/nope/hard', {
944
+ method: 'DELETE',
945
+ headers: { 'Content-Type': 'application/json' },
946
+ body: JSON.stringify({ confirm: 'nope' }),
947
+ })
948
+ expect(res.status).toBe(404)
949
+ })
950
+
951
+ it('skips media cleanup when dbCols is null (table missing)', async () => {
952
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
953
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
954
+ const { app, bucket } = buildApp({ role: 'admin', repo, mutator })
955
+
956
+ const res = await app.request('/articles/hard', {
957
+ method: 'DELETE',
958
+ headers: { 'Content-Type': 'application/json' },
959
+ body: JSON.stringify({ confirm: 'articles' }),
960
+ })
961
+ expect(res.status).toBe(200)
962
+ expect(bucket.delete).not.toHaveBeenCalled()
963
+ })
964
+
965
+ it('skips media cleanup when no file column is present in DB', async () => {
966
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
967
+ const dbCols = new Set(['id', 'title']) // 'cover' column absent
968
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
969
+ const { app, bucket } = buildApp({ role: 'admin', repo, mutator })
970
+
971
+ const res = await app.request('/articles/hard', {
972
+ method: 'DELETE',
973
+ headers: { 'Content-Type': 'application/json' },
974
+ body: JSON.stringify({ confirm: 'articles' }),
975
+ })
976
+ expect(res.status).toBe(200)
977
+ expect(bucket.delete).not.toHaveBeenCalled()
978
+ })
979
+
980
+ it('extracts R2 keys from rows and deletes them via deleteR2Objects', async () => {
981
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
982
+ const dbCols = new Set(['id', 'title', 'cover'])
983
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
984
+ const db = {
985
+ prepare: (sql: string) => ({
986
+ all: async () => {
987
+ expect(sql).toContain('cover')
988
+ expect(sql).toContain('content_articles')
989
+ return { results: [{ cover: '/api/media/abc123.png' }, { cover: null }] }
990
+ },
991
+ }),
992
+ }
993
+ const { app, bucket, mediaRepository } = buildApp({ role: 'admin', repo, mutator, db })
994
+
995
+ const res = await app.request(
996
+ '/articles/hard',
997
+ {
998
+ method: 'DELETE',
999
+ headers: { 'Content-Type': 'application/json' },
1000
+ body: JSON.stringify({ confirm: 'articles' }),
1001
+ },
1002
+ { DB: db }
1003
+ )
1004
+ expect(res.status).toBe(200)
1005
+ expect(bucket.delete).toHaveBeenCalledWith('abc123.png')
1006
+ expect(mediaRepository.untrack).toHaveBeenCalledWith('abc123.png')
1007
+ })
1008
+
1009
+ it('non-fatal: swallows errors thrown while gathering media keys', async () => {
1010
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
1011
+ const mutator = makeMutator({ getColumns: vi.fn().mockRejectedValue(new Error('schema unavailable')) })
1012
+ const { app } = buildApp({ role: 'admin', repo, mutator })
1013
+
1014
+ const res = await app.request('/articles/hard', {
1015
+ method: 'DELETE',
1016
+ headers: { 'Content-Type': 'application/json' },
1017
+ body: JSON.stringify({ confirm: 'articles' }),
1018
+ })
1019
+ expect(res.status).toBe(200)
1020
+ })
1021
+
1022
+ it('non-fatal: swallows errors thrown by deleteR2Objects itself', async () => {
1023
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
1024
+ const dbCols = new Set(['id', 'title', 'cover'])
1025
+ const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
1026
+ const db = {
1027
+ prepare: () => ({
1028
+ all: async () => ({ results: [{ cover: '/api/media/abc123.png' }] }),
1029
+ }),
1030
+ }
1031
+ const bucket = { delete: vi.fn().mockRejectedValue(new Error('r2 down')) }
1032
+ const mediaRepository = { getByKey: vi.fn().mockRejectedValue(new Error('lookup failed')), untrack: vi.fn().mockRejectedValue(new Error('untrack failed')) }
1033
+ const { app } = buildApp({ role: 'admin', repo, mutator, db, bucket, mediaRepository })
1034
+
1035
+ const res = await app.request(
1036
+ '/articles/hard',
1037
+ {
1038
+ method: 'DELETE',
1039
+ headers: { 'Content-Type': 'application/json' },
1040
+ body: JSON.stringify({ confirm: 'articles' }),
1041
+ },
1042
+ { DB: db }
1043
+ )
1044
+ expect(res.status).toBe(200)
1045
+ })
1046
+ })
1047
+
1048
+ // ─── DELETE /:slug/branches/:branchId — DDL failure ──────────────────────────
1049
+
1050
+ describe('DELETE /:slug/branches/:branchId — DDL failure', () => {
1051
+ it('404 for non-existent seed', async () => {
1052
+ const { app } = buildApp({ role: 'admin' })
1053
+ const res = await app.request('/nope/branches/br_01', {
1054
+ method: 'DELETE',
1055
+ headers: { 'Content-Type': 'application/json' },
1056
+ body: JSON.stringify({ confirm: 'nope.x' }),
1057
+ })
1058
+ expect(res.status).toBe(404)
1059
+ })
1060
+
1061
+ it('422 ddl-failed when execDestructive throws', async () => {
1062
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1063
+ const mutator = makeMutator({ execDestructive: vi.fn().mockRejectedValue(new Error('drop failed')) })
1064
+ const { app } = buildApp({ role: 'admin', repo, mutator })
1065
+
1066
+ const res = await app.request('/articles/branches/br_02', {
1067
+ method: 'DELETE',
1068
+ headers: { 'Content-Type': 'application/json' },
1069
+ body: JSON.stringify({ confirm: 'articles.body' }),
1070
+ })
1071
+ expect(res.status).toBe(422)
1072
+ const body = await res.json() as any
1073
+ expect(body.type).toContain('ddl-failed')
1074
+ })
1075
+ })
1076
+
1077
+ // ─── PATCH rename — extra validation paths ───────────────────────────────────
1078
+
1079
+ describe('PATCH /:slug/branches/:branchId/rename — extra validation paths', () => {
1080
+ it('400 when newAlias is invalid', async () => {
1081
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1082
+ const { app } = buildApp({ role: 'admin', repo })
1083
+
1084
+ const res = await app.request('/articles/branches/br_01/rename', {
1085
+ method: 'PATCH',
1086
+ headers: { 'Content-Type': 'application/json' },
1087
+ body: JSON.stringify({ newAlias: 'Not Valid!', confirm: 'articles.title' }),
1088
+ })
1089
+ expect(res.status).toBe(400)
1090
+ })
1091
+
1092
+ it('404 for non-existent seed', async () => {
1093
+ const { app } = buildApp({ role: 'admin' })
1094
+ const res = await app.request('/nope/branches/br_01/rename', {
1095
+ method: 'PATCH',
1096
+ headers: { 'Content-Type': 'application/json' },
1097
+ body: JSON.stringify({ newAlias: 'headline', confirm: 'nope.x' }),
1098
+ })
1099
+ expect(res.status).toBe(404)
1100
+ })
1101
+
1102
+ it('404 for unknown branchId', async () => {
1103
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1104
+ const { app } = buildApp({ role: 'admin', repo })
1105
+
1106
+ const res = await app.request('/articles/branches/br_99/rename', {
1107
+ method: 'PATCH',
1108
+ headers: { 'Content-Type': 'application/json' },
1109
+ body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.unknown' }),
1110
+ })
1111
+ expect(res.status).toBe(404)
1112
+ })
1113
+
1114
+ it('non-fatal: swallows errors from automationRepository.list', async () => {
1115
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1116
+ const mutator = makeMutator()
1117
+ const automationRepository = { list: vi.fn().mockRejectedValue(new Error('automations unavailable')) }
1118
+ const { app } = buildApp({ role: 'admin', repo, mutator, automationRepository })
1119
+
1120
+ const res = await app.request('/articles/branches/br_01/rename', {
1121
+ method: 'PATCH',
1122
+ headers: { 'Content-Type': 'application/json' },
1123
+ body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.title' }),
1124
+ })
1125
+ expect(res.status).toBe(200)
1126
+ const body = await res.json() as any
1127
+ expect(body.affectedAutomations).toEqual([])
1128
+ })
1129
+ })
1130
+
1131
+ // ─── PATCH retype — extra validation paths ───────────────────────────────────
1132
+
1133
+ describe('PATCH /:slug/branches/:branchId/retype — extra validation paths', () => {
1134
+ it('400 when newType is invalid', async () => {
1135
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1136
+ const { app } = buildApp({ role: 'admin', repo })
1137
+
1138
+ const res = await app.request('/articles/branches/br_01/retype', {
1139
+ method: 'PATCH',
1140
+ headers: { 'Content-Type': 'application/json' },
1141
+ body: JSON.stringify({ newType: 'not-a-type', confirm: 'articles.title' }),
1142
+ })
1143
+ expect(res.status).toBe(400)
1144
+ })
1145
+
1146
+ it('404 for non-existent seed', async () => {
1147
+ const { app } = buildApp({ role: 'admin' })
1148
+ const res = await app.request('/nope/branches/br_01/retype', {
1149
+ method: 'PATCH',
1150
+ headers: { 'Content-Type': 'application/json' },
1151
+ body: JSON.stringify({ newType: 'number', confirm: 'nope.x' }),
1152
+ })
1153
+ expect(res.status).toBe(404)
1154
+ })
1155
+
1156
+ it('404 for unknown branchId', async () => {
1157
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1158
+ const { app } = buildApp({ role: 'admin', repo })
1159
+
1160
+ const res = await app.request('/articles/branches/br_99/retype', {
1161
+ method: 'PATCH',
1162
+ headers: { 'Content-Type': 'application/json' },
1163
+ body: JSON.stringify({ newType: 'number', confirm: 'articles.unknown' }),
1164
+ })
1165
+ expect(res.status).toBe(404)
1166
+ })
1167
+
1168
+ it('422 ddl-failed when execDestructive throws', async () => {
1169
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1170
+ const mutator = makeMutator({ execDestructive: vi.fn().mockRejectedValue(new Error('retype failed')) })
1171
+ const { app } = buildApp({ role: 'admin', repo, mutator })
1172
+
1173
+ const res = await app.request('/articles/branches/br_01/retype', {
1174
+ method: 'PATCH',
1175
+ headers: { 'Content-Type': 'application/json' },
1176
+ body: JSON.stringify({ newType: 'number', confirm: 'articles.title' }),
1177
+ })
1178
+ expect(res.status).toBe(422)
1179
+ const body = await res.json() as any
1180
+ expect(body.type).toContain('ddl-failed')
1181
+ })
1182
+ })
1183
+
1184
+ // ─── actorFromContext fallbacks ──────────────────────────────────────────────
1185
+
1186
+ describe('actorFromContext fallbacks', () => {
1187
+ it('falls back to "unknown" id/email and null name when JWT lacks those claims', async () => {
1188
+ const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1189
+ const { app, activityLogger } = buildApp({ jwtPayload: { role: 'admin' }, repo })
1190
+
1191
+ const res = await app.request('/articles', { method: 'DELETE' })
1192
+ expect(res.status).toBe(200)
1193
+
1194
+ const actor = activityLogger.log.mock.calls[0][0].actor
1195
+ expect(actor.id).toBe('unknown')
1196
+ expect(actor.email).toBe('unknown')
1197
+ expect(actor.name).toBeNull()
1198
+ })
1199
+ })