@beechcms/api 0.4.1 → 0.4.3

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 (67) hide show
  1. package/assets/dashboard/assets/index-BKWnlvnV.css +1 -0
  2. package/assets/dashboard/assets/index-BMkd1Irh.js +629 -0
  3. package/assets/dashboard/index.html +2 -2
  4. package/migrations/0000_v040_base.sql +25 -0
  5. package/migrations/0029_automations.sql +14 -0
  6. package/package.json +4 -3
  7. package/src/factory.ts +12 -4
  8. package/src/features/automations/__tests__/action-executors.test.ts +268 -0
  9. package/src/features/automations/__tests__/automation-runner.test.ts +192 -0
  10. package/src/features/automations/__tests__/automation-runner.utils.test.ts +56 -0
  11. package/src/features/automations/__tests__/automations.handler.test.ts +260 -0
  12. package/src/features/automations/__tests__/automations.repository.test.ts +159 -0
  13. package/src/features/automations/__tests__/automations.schema.test.ts +134 -0
  14. package/src/features/automations/__tests__/context-resolver.test.ts +122 -0
  15. package/src/features/automations/__tests__/cron-runner.test.ts +263 -0
  16. package/src/features/automations/__tests__/cron-runner.utils.test.ts +140 -0
  17. package/src/features/automations/__tests__/set-variable.executor.test.ts +306 -0
  18. package/src/features/automations/__tests__/template-grammar.test.ts +304 -0
  19. package/src/features/automations/__tests__/when-evaluator.test.ts +270 -0
  20. package/src/features/automations/__tests__/when-pushdown.test.ts +277 -0
  21. package/src/features/automations/action-executors/create-entry.executor.ts +23 -0
  22. package/src/features/automations/action-executors/edit-field.executor.ts +22 -0
  23. package/src/features/automations/action-executors/index.ts +33 -0
  24. package/src/features/automations/action-executors/send-mail.executor.ts +42 -0
  25. package/src/features/automations/action-executors/set-variable.executor.ts +146 -0
  26. package/src/features/automations/action-executors/webhook.executor.ts +25 -0
  27. package/src/features/automations/automation-runner.ts +81 -0
  28. package/src/features/automations/automation-runner.utils.ts +43 -0
  29. package/src/features/automations/automations.handler.ts +193 -0
  30. package/src/features/automations/automations.schema.ts +160 -0
  31. package/src/features/automations/context-resolver.ts +148 -0
  32. package/src/features/automations/cron-runner.ts +136 -0
  33. package/src/features/automations/cron-runner.utils.ts +40 -0
  34. package/src/features/automations/filter-translation.ts +42 -0
  35. package/src/features/automations/index.ts +12 -0
  36. package/src/features/automations/template-grammar.ts +241 -0
  37. package/src/features/automations/var-access-resolver.ts +136 -0
  38. package/src/features/automations/when-evaluator.ts +83 -0
  39. package/src/features/automations/when-pushdown.ts +53 -0
  40. package/src/features/content/handlers/create.ts +8 -0
  41. package/src/features/content/handlers/delete.ts +8 -1
  42. package/src/features/content/handlers/update.ts +8 -0
  43. package/src/features/draft/draft.handler.ts +51 -164
  44. package/src/features/draft/draft.middleware.ts +62 -0
  45. package/src/features/email/email.service.ts +13 -0
  46. package/src/features/email/email.types.ts +10 -0
  47. package/src/features/email/index.ts +2 -1
  48. package/src/features/email/templates/automation-mail.ts +15 -0
  49. package/src/features/settings/settings.handler.ts +2 -1
  50. package/src/index.ts +40 -8
  51. package/src/middleware/repository.middleware.ts +32 -1
  52. package/src/public/cache-utils.ts +34 -0
  53. package/src/public/entry-projection.ts +42 -0
  54. package/src/public/idempotency.ts +19 -0
  55. package/src/public/problem-details.ts +5 -0
  56. package/src/public/public-add.ts +17 -63
  57. package/src/public/public-read.ts +20 -177
  58. package/src/public/read-list.ts +50 -0
  59. package/src/public/read-single.ts +44 -0
  60. package/src/shared/automations.repository.d1.ts +146 -0
  61. package/src/shared/d1-content-scan.repository.test.ts +76 -0
  62. package/src/shared/execution-context-scheduler.ts +9 -0
  63. package/src/shared/storage-utils.ts +3 -3
  64. package/src/types.ts +5 -1
  65. package/src/upload.ts +3 -2
  66. package/assets/dashboard/assets/index-CH13idU1.js +0 -554
  67. package/assets/dashboard/assets/index-CewtCjom.css +0 -1
@@ -9,8 +9,8 @@
9
9
  <!-- Poppins: pesi normali + italic. Inter: fallback con piena copertura degli stili. -->
10
10
  <link href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet" />
11
11
  <title>dashboard</title>
12
- <script type="module" crossorigin src="/admin/assets/index-CH13idU1.js"></script>
13
- <link rel="stylesheet" crossorigin href="/admin/assets/index-CewtCjom.css">
12
+ <script type="module" crossorigin src="/admin/assets/index-BMkd1Irh.js"></script>
13
+ <link rel="stylesheet" crossorigin href="/admin/assets/index-BKWnlvnV.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -211,3 +211,28 @@ CREATE TABLE IF NOT EXISTS content_event_log (
211
211
  CREATE INDEX IF NOT EXISTS idx_event_log_schema_slug ON content_event_log(schema_slug);
212
212
  CREATE INDEX IF NOT EXISTS idx_event_log_created_at ON content_event_log(created_at DESC);
213
213
  CREATE INDEX IF NOT EXISTS idx_event_log_entry_id ON content_event_log(entry_id);
214
+
215
+
216
+ -- =============================================================================
217
+ -- 11. AUTOMATIONS
218
+ -- Event-driven automation rules. Each automation defines one or more
219
+ -- triggers (JSON array of {event, cron?}), optional WhenNode conditions,
220
+ -- and a sequence of actions to execute.
221
+ -- triggers: [{ event: 'create'|'update'|'delete'|'cron', cron?: string }]
222
+ -- Max one cron trigger per automation, enforced at the application layer.
223
+ -- =============================================================================
224
+
225
+ CREATE TABLE IF NOT EXISTS automations (
226
+ id TEXT NOT NULL PRIMARY KEY,
227
+ seed_slug TEXT NOT NULL,
228
+ name TEXT NOT NULL,
229
+ enabled INTEGER NOT NULL DEFAULT 1,
230
+ triggers TEXT NOT NULL DEFAULT '[]',
231
+ trigger_conditions TEXT,
232
+ actions TEXT NOT NULL,
233
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
234
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch())
235
+ );
236
+
237
+ CREATE INDEX IF NOT EXISTS idx_automations_seed_slug ON automations(seed_slug);
238
+ CREATE INDEX IF NOT EXISTS idx_automations_enabled ON automations(enabled);
@@ -0,0 +1,14 @@
1
+ CREATE TABLE IF NOT EXISTS automations (
2
+ id TEXT NOT NULL PRIMARY KEY,
3
+ seed_slug TEXT NOT NULL,
4
+ name TEXT NOT NULL,
5
+ enabled INTEGER NOT NULL DEFAULT 1,
6
+ triggers TEXT NOT NULL DEFAULT '[]',
7
+ trigger_conditions TEXT,
8
+ actions TEXT NOT NULL,
9
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
10
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch())
11
+ );
12
+
13
+ CREATE INDEX IF NOT EXISTS idx_automations_seed_slug ON automations(seed_slug);
14
+ CREATE INDEX IF NOT EXISTS idx_automations_enabled ON automations(enabled);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beechcms/api",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/factory.ts"
@@ -8,12 +8,13 @@
8
8
  "files": [
9
9
  "src/",
10
10
  "migrations/0000_v040_base.sql",
11
+ "migrations/0029_automations.sql",
11
12
  "assets/"
12
13
  ],
13
14
  "scripts": {
14
15
  "dev": "wrangler dev --port 8789",
15
16
  "build": "tsc -p tsconfig.build.json --noEmit",
16
- "db:migrate:local": "wrangler d1 execute beech-db --local --file=./migrations/0000_v040_base.sql",
17
+ "db:migrate:local": "wrangler d1 execute beech-db --local --file=./migrations/0000_v040_base.sql && wrangler d1 execute beech-db --local --file=./migrations/0029_automations.sql",
17
18
  "db:reset:local": "node -e \"require('fs').rmSync('.wrangler/state', {recursive:true,force:true})\" && npm run db:migrate:local && cd ../.. && node bin/cli.mjs seed:load --local && cd apps/api && wrangler d1 execute beech-db --local --file=./migrations/0028_v040_seed_data.sql",
18
19
  "deploy": "wrangler deploy --minify",
19
20
  "cf-typegen": "wrangler types --env-interface CloudflareBindings",
@@ -22,7 +23,7 @@
22
23
  },
23
24
  "dependencies": {
24
25
  "@aws-sdk/client-s3": "^3.995.0",
25
- "@beechcms/core": "^0.4.1",
26
+ "@beechcms/core": "^0.4.3",
26
27
  "bcryptjs": "^2.4.3",
27
28
  "hono": "^4.11.9",
28
29
  "jose": "^6.1.3"
package/src/factory.ts CHANGED
@@ -26,6 +26,7 @@ import { draftApp } from './features/draft'
26
26
  import { settingsApp } from './features/settings/settings.handler'
27
27
  import { schemaApp } from './features/schema/schema.handler'
28
28
  import { notificationsApp } from './features/notifications'
29
+ import { automationsApp } from './features/automations'
29
30
  import { statsApp } from './features/stats'
30
31
  import { uploadRoutes, serveMediaHandler } from './upload'
31
32
  import { publicRoutes, apiKeyMiddleware, publicRateLimitMiddleware } from './public'
@@ -243,11 +244,13 @@ export function createBeechApp(config: BeechConfig): Hono<{ Bindings: Env; Varia
243
244
  if (!activeSession) return context.json({ error: 'Invalid refresh token' }, 401)
244
245
 
245
246
  const user = await context.get('userRepository').findById(activeSession.userId)
246
- if (!user) return context.json({ error: 'User not found' }, 401)
247
-
248
- const revoked = await context.get('sessionRepository').revokeByHash(tokenHash, nowSeconds)
249
- if (!revoked) return context.json({ error: 'Invalid refresh token' }, 401)
247
+ if (!user) {
248
+ await context.get('sessionRepository').revokeByHash(tokenHash, nowSeconds)
249
+ return context.json({ error: 'User not found' }, 401)
250
+ }
250
251
 
252
+ // Issue new tokens before revoking the old one: if saveRefreshToken fails,
253
+ // the old token stays valid and the user is not locked out.
251
254
  const newAccessToken = await context.get('tokenService').issue({ sub: user.id, email: user.email, name: user.name ?? undefined })
252
255
  const newRefreshToken = generateRefreshToken()
253
256
  const newRefreshTokenHash = await sha256hex(newRefreshToken)
@@ -258,6 +261,10 @@ export function createBeechApp(config: BeechConfig): Hono<{ Bindings: Env; Varia
258
261
  tokenHash: newRefreshTokenHash,
259
262
  expiresAt: nowSeconds + REFRESH_TOKEN_EXPIRY_DAYS * SECONDS_PER_DAY,
260
263
  })
264
+
265
+ const revoked = await context.get('sessionRepository').revokeByHash(tokenHash, nowSeconds)
266
+ if (!revoked) return context.json({ error: 'Invalid refresh token' }, 401)
267
+
261
268
  setCookie(context, 'refresh_token', newRefreshToken, getRefreshTokenCookieOptions(isRequestSecure(context.req.url)))
262
269
  return context.json({ token: newAccessToken, expiresIn: '15m' }, 200)
263
270
  } catch (error) {
@@ -296,6 +303,7 @@ export function createBeechApp(config: BeechConfig): Hono<{ Bindings: Env; Varia
296
303
  apiProtected.route('/content', draftApp)
297
304
  apiProtected.route('/content', contentFeature)
298
305
  apiProtected.route('/widget', widgetApp)
306
+ apiProtected.route('/automations', automationsApp)
299
307
  apiProtected.route('/', uploadRoutes)
300
308
 
301
309
  // 6. Public API (must be registered before apiProtected to avoid auth middleware interception)
@@ -0,0 +1,268 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+ import { executeAction } from '../action-executors'
3
+ import type { ActionContext } from '../action-executors'
4
+ import type { ContentRepository, Seed, IIdGenerator } from '@beechcms/core'
5
+
6
+ // ── Shared mock context factory ───────────────────────────────────────────────
7
+
8
+ function makeCtx(overrides: Partial<ActionContext> = {}): ActionContext {
9
+ const { entry: entryOverride, context: contextOverride, ...rest } = overrides
10
+ const entry: Record<string, unknown> = entryOverride ?? { id: 'entry-1', title: 'Test Entry', status: 'published' }
11
+ const context = contextOverride ?? {
12
+ triggerEntry: entry,
13
+ lookup(parsed: import('../template-grammar').ParsedKey, onMissing?: (f: string) => void) {
14
+ if (parsed.kind === 'simple') {
15
+ const val = entry[parsed.path]
16
+ if (val == null && onMissing) onMissing(parsed.path)
17
+ return val
18
+ }
19
+ if (parsed.kind === 'scoped' && parsed.scope === 'this' && parsed.field) {
20
+ return entry[parsed.field]
21
+ }
22
+ return undefined
23
+ },
24
+ }
25
+ return {
26
+ entry,
27
+ env: { RESEND_API_KEY: 'test-key', EMAIL_FROM: 'test@example.com' },
28
+ repository: {
29
+ update: vi.fn().mockResolvedValue(undefined),
30
+ create: vi.fn().mockResolvedValue(undefined),
31
+ } as unknown as ContentRepository,
32
+ getSeed: vi.fn().mockReturnValue({ branches: [] } as unknown as Seed),
33
+ seed: { slug: 'posts', branches: [] } as unknown as Seed,
34
+ idGenerator: { uuid: vi.fn().mockReturnValue('new-id-123') } as unknown as IIdGenerator,
35
+ context,
36
+ variables: {},
37
+ ...rest,
38
+ }
39
+ }
40
+
41
+ // ── webhook ───────────────────────────────────────────────────────────────────
42
+
43
+ describe('webhook executor', () => {
44
+ beforeEach(() => { vi.restoreAllMocks() })
45
+
46
+ it('POSTs to URL with JSON body derived from entry when no body_template', async () => {
47
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 })
48
+ vi.stubGlobal('fetch', fetchMock)
49
+
50
+ const ctx = makeCtx()
51
+ await executeAction({ type: 'webhook', url: 'https://example.com/hook' }, ctx)
52
+
53
+ expect(fetchMock).toHaveBeenCalledOnce()
54
+ const [url, init] = fetchMock.mock.calls[0]
55
+ expect(url).toBe('https://example.com/hook')
56
+ expect(init.method).toBe('POST')
57
+ expect(JSON.parse(init.body)).toMatchObject({ id: 'entry-1', title: 'Test Entry' })
58
+ })
59
+
60
+ it('interpolates body_template with entry values', async () => {
61
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true })
62
+ vi.stubGlobal('fetch', fetchMock)
63
+
64
+ const ctx = makeCtx()
65
+ await executeAction({ type: 'webhook', url: 'https://example.com/hook', body_template: '{"t":"{{title}}"}' }, ctx)
66
+
67
+ const [, init] = fetchMock.mock.calls[0]
68
+ expect(init.body).toBe('{"t":"Test Entry"}')
69
+ })
70
+
71
+ it('merges custom headers', async () => {
72
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true })
73
+ vi.stubGlobal('fetch', fetchMock)
74
+
75
+ const ctx = makeCtx()
76
+ await executeAction({ type: 'webhook', url: 'https://x.com', headers: { 'X-Token': 'abc' } }, ctx)
77
+
78
+ const [, init] = fetchMock.mock.calls[0]
79
+ expect(init.headers['X-Token']).toBe('abc')
80
+ })
81
+
82
+ it('throws when response is not ok', async () => {
83
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 500 }))
84
+ const ctx = makeCtx()
85
+ await expect(executeAction({ type: 'webhook', url: 'https://x.com' }, ctx)).rejects.toThrow('500')
86
+ })
87
+
88
+ it('uses custom HTTP method', async () => {
89
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true })
90
+ vi.stubGlobal('fetch', fetchMock)
91
+ const ctx = makeCtx()
92
+ await executeAction({ type: 'webhook', url: 'https://x.com', method: 'PUT' }, ctx)
93
+ expect(fetchMock.mock.calls[0][1].method).toBe('PUT')
94
+ })
95
+ })
96
+
97
+ // ── send_mail ─────────────────────────────────────────────────────────────────
98
+
99
+ vi.mock('../../email', () => ({
100
+ sendAutomationMail: vi.fn().mockResolvedValue(undefined),
101
+ }))
102
+
103
+ describe('send_mail executor', () => {
104
+ beforeEach(async () => {
105
+ const { sendAutomationMail } = await import('../../email')
106
+ vi.mocked(sendAutomationMail).mockClear()
107
+ })
108
+
109
+ it('interpolates to/subject/body and calls sendAutomationMail', async () => {
110
+ const { sendAutomationMail } = await import('../../email')
111
+ const ctx = makeCtx({ entry: { id: '1', email: 'user@example.com', title: 'Hello' } })
112
+
113
+ await executeAction(
114
+ {
115
+ type: 'send_mail',
116
+ to: '{{email}}',
117
+ subject_template: 'Re: {{title}}',
118
+ body_template: 'Your entry {{title}} was created.',
119
+ },
120
+ ctx,
121
+ )
122
+
123
+ expect(sendAutomationMail).toHaveBeenCalledWith(
124
+ expect.objectContaining({
125
+ to: 'user@example.com',
126
+ subject: 'Re: Hello',
127
+ body: 'Your entry Hello was created.',
128
+ }),
129
+ )
130
+ })
131
+
132
+ it('substitutes default value [missing] and logs a warning when concrete data is absent', async () => {
133
+ const { sendAutomationMail } = await import('../../email')
134
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
135
+ const ctx = makeCtx({ entry: { id: '1' } })
136
+
137
+ await executeAction(
138
+ {
139
+ type: 'send_mail',
140
+ to: '{{email}}',
141
+ subject_template: 'Re: {{title}}',
142
+ body_template: 'Content: {{desc}}',
143
+ },
144
+ ctx,
145
+ )
146
+
147
+ expect(sendAutomationMail).toHaveBeenCalledWith(
148
+ expect.objectContaining({
149
+ to: '[missing]',
150
+ subject: 'Re: [missing]',
151
+ body: 'Content: [missing]',
152
+ }),
153
+ )
154
+ expect(warnSpy).toHaveBeenCalledWith(
155
+ expect.stringContaining('missing concrete data'),
156
+ ['email', 'title', 'desc'],
157
+ )
158
+ })
159
+
160
+ it('skips execution gracefully and logs an error without calling sendAutomationMail if apiKey is missing', async () => {
161
+ const { sendAutomationMail } = await import('../../email')
162
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
163
+ const ctx = makeCtx({ env: {} }) // missing email/resend api keys
164
+
165
+ await executeAction(
166
+ {
167
+ type: 'send_mail',
168
+ to: 'user@beech.io',
169
+ subject_template: 'Hello',
170
+ body_template: 'World',
171
+ },
172
+ ctx,
173
+ )
174
+
175
+ expect(sendAutomationMail).not.toHaveBeenCalled()
176
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('Execution skipped'))
177
+ })
178
+
179
+ it('logs error and rethrows when sendAutomationMail fails', async () => {
180
+ const { sendAutomationMail } = await import('../../email')
181
+ vi.mocked(sendAutomationMail).mockRejectedValueOnce(new Error('provider error'))
182
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
183
+ const ctx = makeCtx()
184
+
185
+ await expect(
186
+ executeAction(
187
+ {
188
+ type: 'send_mail',
189
+ to: 'test@beech.io',
190
+ subject_template: 'Hello',
191
+ body_template: 'World',
192
+ },
193
+ ctx,
194
+ ),
195
+ ).rejects.toThrow('provider error')
196
+
197
+ expect(errSpy).toHaveBeenCalledWith(
198
+ expect.stringContaining('failed to send automation email'),
199
+ expect.any(Error),
200
+ )
201
+ })
202
+ })
203
+
204
+ // ── edit_field ────────────────────────────────────────────────────────────────
205
+
206
+ describe('edit_field executor', () => {
207
+ it('calls repository.update with interpolated string value', async () => {
208
+ const ctx = makeCtx({ entry: { id: 'entry-1', title: 'Old Title' } })
209
+ await executeAction({ type: 'edit_field', field: 'summary', value: 'Based on {{title}}' }, ctx)
210
+ expect(ctx.repository.update).toHaveBeenCalledWith(ctx.seed, 'entry-1', { summary: 'Based on Old Title' })
211
+ })
212
+
213
+ it('calls repository.update with raw non-string value', async () => {
214
+ const ctx = makeCtx({ entry: { id: 'entry-1', title: 'T' } })
215
+ await executeAction({ type: 'edit_field', field: 'count', value: 42 }, ctx)
216
+ expect(ctx.repository.update).toHaveBeenCalledWith(ctx.seed, 'entry-1', { count: 42 })
217
+ })
218
+
219
+ it('throws when entry.id is missing', async () => {
220
+ const ctx = makeCtx({ entry: { title: 'No ID' } })
221
+ await expect(executeAction({ type: 'edit_field', field: 'x', value: 'y' }, ctx)).rejects.toThrow('entry.id missing')
222
+ })
223
+ })
224
+
225
+ // ── create_entry ──────────────────────────────────────────────────────────────
226
+
227
+ describe('create_entry executor', () => {
228
+ it('creates a new entry with field_map values from trigger entry', async () => {
229
+ const ctx = makeCtx({ entry: { id: 'e1', author: 'Alice' } })
230
+ await executeAction(
231
+ { type: 'create_entry', seed_slug: 'comments', field_map: { writer: 'author', fixed: 'literal-value' } },
232
+ ctx,
233
+ )
234
+ expect(ctx.idGenerator.uuid).toHaveBeenCalled()
235
+ expect(ctx.repository.create).toHaveBeenCalledWith(
236
+ expect.anything(),
237
+ 'new-id-123',
238
+ 'new-id-123',
239
+ 'draft',
240
+ { writer: 'Alice', fixed: 'literal-value' },
241
+ )
242
+ })
243
+
244
+ it('uses literal string when source field is not in entry', async () => {
245
+ const ctx = makeCtx({ entry: { id: 'e1' } })
246
+ await executeAction(
247
+ { type: 'create_entry', seed_slug: 'comments', field_map: { tag: 'missing-field' } },
248
+ ctx,
249
+ )
250
+ expect(ctx.repository.create).toHaveBeenCalledWith(
251
+ expect.anything(), 'new-id-123', 'new-id-123', 'draft',
252
+ { tag: 'missing-field' },
253
+ )
254
+ })
255
+
256
+ it('throws when seed not found', async () => {
257
+ const ctx = makeCtx({ getSeed: vi.fn().mockReturnValue(null) })
258
+ await expect(
259
+ executeAction({ type: 'create_entry', seed_slug: 'unknown', field_map: {} }, ctx),
260
+ ).rejects.toThrow('unknown seed unknown')
261
+ })
262
+
263
+ it('throws error for unknown action type to cover exhaustive default check', async () => {
264
+ const ctx = makeCtx()
265
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
266
+ await expect(executeAction({ type: 'unknown_custom_action' } as any, ctx)).rejects.toThrow('unknown action type')
267
+ })
268
+ })
@@ -0,0 +1,192 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+ import { AutomationRunner } from '../automation-runner'
3
+ import type { AutomationRunnerDeps } from '../automation-runner'
4
+ import type { IAutomationRepository, ContentRepository, Seed, IIdGenerator, Automation } from '@beechcms/core'
5
+ import { resolveVarAccess } from '../var-access-resolver'
6
+ import { parseTemplateKey } from '../template-grammar'
7
+
8
+ function makeAutomation(overrides: Partial<Automation> = {}): Automation {
9
+ return {
10
+ id: 'auto-1',
11
+ seed_slug: 'posts',
12
+ name: 'Test Automation',
13
+ enabled: true,
14
+ triggers: [{ event: 'create' as const }],
15
+ trigger_conditions: null,
16
+ actions: [],
17
+ created_at: 0,
18
+ updated_at: 0,
19
+ ...overrides,
20
+ }
21
+ }
22
+
23
+ function makeDeps(overrides: Partial<AutomationRunnerDeps> = {}): AutomationRunnerDeps {
24
+ return {
25
+ automationRepository: {
26
+ findActive: vi.fn().mockResolvedValue([]),
27
+ } as unknown as IAutomationRepository,
28
+ contentRepository: {} as ContentRepository,
29
+ getSeed: vi.fn().mockReturnValue({ slug: 'posts', branches: [] } as unknown as Seed),
30
+ idGenerator: { uuid: vi.fn().mockReturnValue('new-id') } as unknown as IIdGenerator,
31
+ env: {},
32
+ ...overrides,
33
+ }
34
+ }
35
+
36
+ describe('AutomationRunner', () => {
37
+ beforeEach(() => { vi.restoreAllMocks() })
38
+
39
+ it('does nothing when no automations match', async () => {
40
+ const deps = makeDeps()
41
+ const runner = new AutomationRunner(deps)
42
+ await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1' } })
43
+ expect(deps.automationRepository.findActive).toHaveBeenCalledWith('posts', 'create')
44
+ })
45
+
46
+ it('does nothing when getSeed returns null', async () => {
47
+ const deps = makeDeps({ getSeed: vi.fn().mockReturnValue(null) })
48
+ const runner = new AutomationRunner(deps)
49
+ await runner.run({ seedSlug: 'unknown', event: 'create', entry: { id: '1' } })
50
+ expect(deps.automationRepository.findActive).not.toHaveBeenCalled()
51
+ })
52
+
53
+ it('skips actions when trigger conditions are not met', async () => {
54
+ const automation = makeAutomation({
55
+ trigger_conditions: {
56
+ kind: 'group',
57
+ op: 'AND',
58
+ children: [{ kind: 'predicate', left: { kind: 'ref', key: 'this.status' }, op: 'eq', right: { kind: 'literal', value: 'published' } }],
59
+ },
60
+ actions: [{ type: 'webhook', url: 'https://example.com' }],
61
+ })
62
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true })
63
+ vi.stubGlobal('fetch', fetchMock)
64
+
65
+ const deps = makeDeps({
66
+ automationRepository: {
67
+ findActive: vi.fn().mockResolvedValue([automation]),
68
+ } as unknown as IAutomationRepository,
69
+ })
70
+ const runner = new AutomationRunner(deps)
71
+ await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'draft' } })
72
+
73
+ expect(fetchMock).not.toHaveBeenCalled()
74
+ })
75
+
76
+ it('continues to next action when first action throws', async () => {
77
+ const secondActionFetch = vi.fn().mockResolvedValue({ ok: true })
78
+ vi.stubGlobal('fetch', vi.fn()
79
+ .mockRejectedValueOnce(new Error('network error'))
80
+ .mockResolvedValue({ ok: true }),
81
+ )
82
+
83
+ const automation = makeAutomation({
84
+ actions: [
85
+ { type: 'webhook', url: 'https://fail.example.com' },
86
+ { type: 'webhook', url: 'https://success.example.com' },
87
+ ],
88
+ })
89
+
90
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
91
+
92
+ const deps = makeDeps({
93
+ automationRepository: {
94
+ findActive: vi.fn().mockResolvedValue([automation]),
95
+ } as unknown as IAutomationRepository,
96
+ })
97
+ const runner = new AutomationRunner(deps)
98
+ await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'published' } })
99
+
100
+ expect(consoleSpy).toHaveBeenCalledWith('[automations] action failed', expect.objectContaining({
101
+ automationId: 'auto-1',
102
+ actionType: 'webhook',
103
+ }))
104
+
105
+ // fetch was called twice (first failed, second succeeded)
106
+ const fetchCalls = (global.fetch as ReturnType<typeof vi.fn>).mock.calls
107
+ expect(fetchCalls).toHaveLength(2)
108
+ expect(fetchCalls[1][0]).toBe('https://success.example.com')
109
+ })
110
+
111
+ it('runs actions when conditions pass', async () => {
112
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true })
113
+ vi.stubGlobal('fetch', fetchMock)
114
+
115
+ const automation = makeAutomation({
116
+ trigger_conditions: {
117
+ kind: 'group',
118
+ op: 'AND',
119
+ children: [{ kind: 'predicate', left: { kind: 'ref', key: 'this.status' }, op: 'eq', right: { kind: 'literal', value: 'published' } }],
120
+ },
121
+ actions: [{ type: 'webhook', url: 'https://example.com/hook' }],
122
+ })
123
+
124
+ const deps = makeDeps({
125
+ automationRepository: {
126
+ findActive: vi.fn().mockResolvedValue([automation]),
127
+ } as unknown as IAutomationRepository,
128
+ })
129
+ const runner = new AutomationRunner(deps)
130
+ await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'published' } })
131
+
132
+ expect(fetchMock).toHaveBeenCalledOnce()
133
+ expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/hook')
134
+ })
135
+ })
136
+
137
+ // ── Sprint 07: resolveVarAccess unit tests ─────────────────────────────────────
138
+
139
+ describe('resolveVarAccess (Sprint 07)', () => {
140
+ function makeCollectionVar(items: Array<Record<string, unknown>>) {
141
+ const out: Record<string, unknown> = {
142
+ count: items.length,
143
+ firstone: items[0] ?? null,
144
+ lastone: items[items.length - 1] ?? null,
145
+ sum: {},
146
+ avg: {},
147
+ min: {},
148
+ max: {},
149
+ pluck: {},
150
+ }
151
+ Object.defineProperty(out, '_items', { value: items, enumerable: false })
152
+ return out
153
+ }
154
+
155
+ const items = [
156
+ { id: 'a', status: 'paid', amount: 100, created_at: 1 },
157
+ { id: 'b', status: 'draft', amount: 50, created_at: 2 },
158
+ { id: 'c', status: 'paid', amount: 200, created_at: 3 },
159
+ ]
160
+
161
+ it('array[id] selector filters _items and rebuilds collection', () => {
162
+ const variables = { ordini: makeCollectionVar(items) }
163
+ const parsed = parseTemplateKey('ordini.array[a,c].count')!
164
+ expect(parsed.kind).toBe('var_access')
165
+ const result = resolveVarAccess(parsed as any, variables)
166
+ expect(result).toBe(2)
167
+ })
168
+
169
+ it('inline condition (status=paid) reduces count', () => {
170
+ const variables = { ordini: makeCollectionVar(items) }
171
+ const parsed = parseTemplateKey('ordini.count.(status=paid)')!
172
+ const result = resolveVarAccess(parsed as any, variables)
173
+ expect(result).toBe(2)
174
+ })
175
+
176
+ it('conditions on firstone.id return undefined when record fails predicate', () => {
177
+ const variables = { ordini: makeCollectionVar(items) }
178
+ // firstone is items[0] which has status=paid, so (status=draft) should fail
179
+ const parsed = parseTemplateKey('ordini.firstone.status.(status=draft)')!
180
+ const result = resolveVarAccess(parsed as any, variables)
181
+ // firstone.status = 'paid', condition says status=draft → undefined
182
+ expect(result).toBeUndefined()
183
+ })
184
+
185
+ it('returns undefined when variable is missing and calls onMissing', () => {
186
+ const onMissing = vi.fn()
187
+ const parsed = parseTemplateKey('missing.count.(status=paid)')!
188
+ const result = resolveVarAccess(parsed as any, {}, onMissing)
189
+ expect(result).toBeUndefined()
190
+ expect(onMissing).toHaveBeenCalledWith('missing')
191
+ })
192
+ })
@@ -0,0 +1,56 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { interpolate } from '../automation-runner.utils'
3
+ import { resolveAutomationContext } from '../context-resolver'
4
+
5
+ async function makeCtx(entry: Record<string, unknown>) {
6
+ return resolveAutomationContext({} as any, entry, [entry])
7
+ }
8
+
9
+ describe('interpolate', () => {
10
+ it('replaces a single placeholder', async () => {
11
+ expect(interpolate('Hello {{name}}!', await makeCtx({ name: 'World' }))).toBe('Hello World!')
12
+ })
13
+
14
+ it('replaces multiple placeholders', async () => {
15
+ expect(interpolate('{{name}} is {{status}}', await makeCtx({ name: 'Alice', status: 'active' }))).toBe('Alice is active')
16
+ })
17
+
18
+ it('missing field becomes empty string by default', async () => {
19
+ expect(interpolate('Hello {{name}}!', await makeCtx({}))).toBe('Hello !')
20
+ })
21
+
22
+ it('no placeholders returns template unchanged', async () => {
23
+ expect(interpolate('No placeholders here', await makeCtx({ name: 'World' }))).toBe('No placeholders here')
24
+ })
25
+
26
+ it('handles numeric values', async () => {
27
+ expect(interpolate('Count: {{count}}', await makeCtx({ count: 42 }))).toBe('Count: 42')
28
+ })
29
+
30
+ it('supports spaces inside double braces', async () => {
31
+ expect(interpolate('Hello {{ name }}!', await makeCtx({ name: 'DoubleSpace' }))).toBe('Hello DoubleSpace!')
32
+ })
33
+
34
+ it('uses custom default value when a field is missing', async () => {
35
+ expect(interpolate('Hello {{name}}!', await makeCtx({}), '[missing]')).toBe('Hello [missing]!')
36
+ })
37
+
38
+ it('triggers onMissing callback when field is absent', async () => {
39
+ const missing: string[] = []
40
+ const res = interpolate('Hello {{name}}! From {{city}}', await makeCtx({}), '[mancante]', (f) => missing.push(f))
41
+ expect(res).toBe('Hello [mancante]! From [mancante]')
42
+ expect(missing).toEqual(['name', 'city'])
43
+ })
44
+
45
+ it('returns empty string when template is falsy', async () => {
46
+ expect(interpolate('' as any, await makeCtx({}))).toBe('')
47
+ })
48
+
49
+ it('resolves {{this.field}} dot notation against the trigger entry', async () => {
50
+ expect(interpolate('{{this.customer_id}}', await makeCtx({ customer_id: 'cust-42' }))).toBe('cust-42')
51
+ })
52
+
53
+ it('resolves {{this:field}} colon notation against the trigger entry', async () => {
54
+ expect(interpolate('{{this:customer_id}}', await makeCtx({ customer_id: 'cust-42' }))).toBe('cust-42')
55
+ })
56
+ })