@beechcms/api 0.4.1 → 0.4.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 (67) hide show
  1. package/assets/dashboard/assets/index-BKWnlvnV.css +1 -0
  2. package/assets/dashboard/assets/index-C1P9BXnU.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 +110 -156
  57. package/src/public/public-read.ts +59 -216
  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
@@ -0,0 +1,146 @@
1
+ import type { AutomationAction, ContentRepository, Seed } from '@beechcms/core'
2
+ import type { ResolvedContext } from '../context-resolver'
3
+ import { conditionToFilterGroup } from '../filter-translation'
4
+ import { interpolate } from '../automation-runner.utils'
5
+
6
+ type SetVariableAction = Extract<AutomationAction, { type: 'set_variable' }>
7
+
8
+ export async function executeSetVariable(
9
+ action: SetVariableAction,
10
+ ctx: {
11
+ entry: Record<string, unknown>
12
+ variables: Record<string, unknown>
13
+ repository: ContentRepository
14
+ getSeed: (slug: string) => Seed | null
15
+ seed: Seed
16
+ context: ResolvedContext
17
+ },
18
+ ): Promise<void> {
19
+ const seedSlug = action.seed_slug ?? ctx.seed.slug
20
+ const targetSeed = ctx.getSeed(seedSlug)
21
+ if (!targetSeed) {
22
+ console.warn(`[set_variable] seed "${seedSlug}" not found; "${action.name}" → null`)
23
+ ctx.variables[action.name] = null
24
+ return
25
+ }
26
+
27
+ if (action.fixed_id !== undefined) {
28
+ const resolvedId = interpolate(action.fixed_id, ctx.context)
29
+ const { items } = await ctx.repository.findMany(targetSeed, {
30
+ filters: [{ column: 'id', type: 'system', conditions: [{ op: 'eq', value: resolvedId }] }],
31
+ status: null,
32
+ pagination: { limit: 1, offset: 0 },
33
+ })
34
+ const item = items[0] ?? null
35
+ if (!item) console.warn(`[set_variable] "${action.name}": id "${resolvedId}" not found`)
36
+ if (action.column) {
37
+ ctx.variables[action.name] = item ? { _value: item[action.column] } : null
38
+ } else {
39
+ ctx.variables[action.name] = item
40
+ }
41
+ return
42
+ }
43
+
44
+ const resolvedFilters = (action.filters ?? []).map((f) => {
45
+ const value = typeof f.value === 'string' ? interpolate(f.value, ctx.context) : f.value
46
+ return conditionToFilterGroup({ ...f, value }, targetSeed)
47
+ })
48
+
49
+ const orderDir: 'ASC' | 'DESC' = action.order === 'asc' ? 'ASC' : 'DESC'
50
+ const { items } = await ctx.repository.findMany(targetSeed, {
51
+ filters: resolvedFilters,
52
+ status: null,
53
+ pagination: { limit: 1000, offset: 0 },
54
+ orderBy: action.order_by ? { column: action.order_by, dir: orderDir } : undefined,
55
+ })
56
+
57
+ ctx.variables[action.name] = materializeCollection(targetSeed, items, action.column ?? null)
58
+ }
59
+
60
+ export function materializeCollection(
61
+ seed: Seed,
62
+ items: Array<Record<string, unknown>>,
63
+ pinned: string | null,
64
+ ): Record<string, unknown> {
65
+ const firstone = items.length > 0
66
+ ? items.reduce((best, r) => (Number(r['created_at']) < Number(best['created_at']) ? r : best), items[0])
67
+ : null
68
+ const lastone = items.length > 0
69
+ ? items.reduce((best, r) => (Number(r['created_at']) > Number(best['created_at']) ? r : best), items[0])
70
+ : null
71
+
72
+ let out: Record<string, unknown>
73
+
74
+ if (pinned === null) {
75
+ out = calculateGeneralStats(seed, items)
76
+ out.firstone = firstone
77
+ out.lastone = lastone
78
+ } else {
79
+ out = calculatePinnedStats(items, pinned)
80
+ out.firstone = firstone
81
+ out.lastone = lastone
82
+ }
83
+
84
+ Object.defineProperty(out, '_items', { value: items, enumerable: false })
85
+ return out
86
+ }
87
+
88
+ function formatPluckValues(items: Array<Record<string, unknown>>, key: string): string {
89
+ const vals = items.slice(0, 100).map((r) => String(r[key] ?? ''))
90
+ return vals.join(', ') + (items.length > 100 ? ' …' : '')
91
+ }
92
+
93
+ function calculatePinnedStats(items: Array<Record<string, unknown>>, pinned: string): Record<string, unknown> {
94
+ const nonNull = items.filter((r) => r[pinned] != null)
95
+ const nums = nonNull.map((r) => Number(r[pinned]))
96
+ const validNums = nums.filter((n) => !Number.isNaN(n))
97
+ const total = validNums.reduce((a, n) => a + n, 0)
98
+ const pluck = formatPluckValues(items, pinned)
99
+
100
+ return {
101
+ count: nonNull.length,
102
+ sum: validNums.length > 0 ? total : 0,
103
+ avg: validNums.length > 0 ? total / validNums.length : 0,
104
+ min: validNums.length > 0 ? Math.min(...validNums) : 0,
105
+ max: validNums.length > 0 ? Math.max(...validNums) : 0,
106
+ pluck,
107
+ }
108
+ }
109
+
110
+ function extractValidNumbers(items: Array<Record<string, unknown>>, key: string): number[] {
111
+ return items
112
+ .map((r) => {
113
+ const v = r[key]
114
+ const n = Number(v)
115
+ if (!Number.isNaN(n)) return n
116
+ if (typeof v === 'string') {
117
+ const d = Date.parse(v)
118
+ return Number.isNaN(d) ? Number.NaN : d / 1000
119
+ }
120
+ return Number.NaN
121
+ })
122
+ .filter((n) => !Number.isNaN(n))
123
+ }
124
+
125
+ function calculateGeneralStats(seed: Seed, items: Array<Record<string, unknown>>): Record<string, unknown> {
126
+ const sum: Record<string, number> = {}
127
+ const avg: Record<string, number> = {}
128
+ const min: Record<string, number> = {}
129
+ const max: Record<string, number> = {}
130
+ const pluck: Record<string, string> = {}
131
+
132
+ for (const branch of seed.branches) {
133
+ if (branch.type === 'number' || branch.type === 'date') {
134
+ const nums = extractValidNumbers(items, branch.alias)
135
+ const total = nums.reduce((a, n) => a + n, 0)
136
+ sum[branch.alias] = total
137
+ avg[branch.alias] = items.length > 0 ? total / items.length : 0
138
+ min[branch.alias] = nums.length > 0 ? Math.min(...nums) : 0
139
+ max[branch.alias] = nums.length > 0 ? Math.max(...nums) : 0
140
+ } else {
141
+ pluck[branch.alias] = formatPluckValues(items, branch.alias)
142
+ }
143
+ }
144
+
145
+ return { count: items.length, sum, avg, min, max, pluck }
146
+ }
@@ -0,0 +1,25 @@
1
+ import type { AutomationAction } from '@beechcms/core'
2
+ import type { ResolvedContext } from '../context-resolver'
3
+ import { interpolate } from '../automation-runner.utils'
4
+
5
+ type WebhookAction = Extract<AutomationAction, { type: 'webhook' }>
6
+
7
+ export async function executeWebhook(
8
+ action: WebhookAction,
9
+ context: ResolvedContext,
10
+ ): Promise<void> {
11
+ const entry = context.triggerEntry ?? {}
12
+ const body = action.body_template
13
+ ? interpolate(action.body_template, context)
14
+ : JSON.stringify(entry)
15
+
16
+ const response = await fetch(action.url, {
17
+ method: action.method ?? 'POST',
18
+ headers: { 'Content-Type': 'application/json', ...(action.headers ?? {}) },
19
+ body,
20
+ })
21
+
22
+ if (!response.ok) {
23
+ throw new Error(`Webhook ${action.url} responded ${response.status}`)
24
+ }
25
+ }
@@ -0,0 +1,81 @@
1
+ import type {
2
+ IAutomationRunner,
3
+ IAutomationRepository,
4
+ AutomationEventPayload,
5
+ ContentRepository,
6
+ Seed,
7
+ IIdGenerator,
8
+ } from '@beechcms/core'
9
+ import { resolvePath } from './automation-runner.utils'
10
+ import { resolveAutomationContext, type ResolvedContext } from './context-resolver'
11
+ import type { ParsedKey } from './template-grammar'
12
+ import { executeAction } from './action-executors'
13
+ import { evaluateWhen } from './when-evaluator'
14
+ import { resolveVarAccess } from './var-access-resolver'
15
+
16
+ export interface AutomationRunnerDeps {
17
+ automationRepository: IAutomationRepository
18
+ contentRepository: ContentRepository
19
+ getSeed: (slug: string) => Seed | null
20
+ idGenerator: IIdGenerator
21
+ env: Record<string, string | undefined>
22
+ }
23
+
24
+ function withVariables(base: ResolvedContext, variables: Record<string, unknown>): ResolvedContext {
25
+ return {
26
+ triggerEntry: base.triggerEntry,
27
+ lookup(parsed: ParsedKey, onMissing?: (field: string) => void): unknown {
28
+ if (parsed.kind === 'simple') {
29
+ const varVal = resolvePath(variables, parsed.path)
30
+ if (varVal !== undefined) return varVal
31
+ } else if (parsed.kind === 'var_access') {
32
+ return resolveVarAccess(parsed, variables, onMissing)
33
+ }
34
+ return base.lookup(parsed, onMissing)
35
+ },
36
+ }
37
+ }
38
+
39
+ export class AutomationRunner implements IAutomationRunner {
40
+ constructor(private readonly deps: AutomationRunnerDeps) {}
41
+
42
+ async run(payload: AutomationEventPayload): Promise<void> {
43
+ const { seedSlug, event, entry } = payload
44
+ const seed = this.deps.getSeed(seedSlug)
45
+ if (!seed) return
46
+
47
+ const automations = await this.deps.automationRepository.findActive(seedSlug, event)
48
+
49
+ for (const automation of automations) {
50
+ const resolved = await resolveAutomationContext(automation, entry, [entry])
51
+
52
+ // Evaluate conditions with the resolved context (this + batch scopes available).
53
+ // Variables from set_variable actions are not yet available here; use inline refs
54
+ // like {{customers:byid({{this.id}}):field}} for cross-seed conditions in v1.
55
+ if (!evaluateWhen(automation.trigger_conditions, resolved)) continue
56
+
57
+ const variables: Record<string, unknown> = {}
58
+
59
+ for (const action of automation.actions) {
60
+ try {
61
+ await executeAction(action, {
62
+ entry,
63
+ env: this.deps.env,
64
+ repository: this.deps.contentRepository,
65
+ getSeed: this.deps.getSeed,
66
+ seed,
67
+ idGenerator: this.deps.idGenerator,
68
+ context: withVariables(resolved, variables),
69
+ variables,
70
+ })
71
+ } catch (error) {
72
+ console.error('[automations] action failed', {
73
+ automationId: automation.id,
74
+ actionType: action.type,
75
+ error,
76
+ })
77
+ }
78
+ }
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,43 @@
1
+ import type { ResolvedContext } from './context-resolver'
2
+ import { parseTemplateKey } from './template-grammar'
3
+
4
+ export function interpolate(
5
+ template: string,
6
+ context: ResolvedContext,
7
+ defaultValue = '',
8
+ onMissing?: (field: string) => void,
9
+ ): string {
10
+ if (!template) return ''
11
+
12
+ const replacer = (_: string, key: string) => {
13
+ const trimmedKey = key.trim()
14
+ const parsed = parseTemplateKey(trimmedKey)
15
+ if (!parsed) {
16
+ if (onMissing) onMissing(trimmedKey)
17
+ return defaultValue
18
+ }
19
+ const val = context.lookup(parsed, onMissing)
20
+ if (val == null || val === '') {
21
+ return defaultValue
22
+ }
23
+ return String(val)
24
+ }
25
+
26
+ return template.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, replacer)
27
+ }
28
+
29
+ export function resolvePath(obj: Record<string, unknown>, path: string): unknown {
30
+ if (path in obj && obj[path] !== undefined) {
31
+ return obj[path]
32
+ }
33
+ const parts = path.split('.')
34
+ let current: unknown = obj
35
+ for (const part of parts) {
36
+ if (current && typeof current === 'object') {
37
+ current = (current as Record<string, unknown>)[part]
38
+ } else {
39
+ return undefined
40
+ }
41
+ }
42
+ return current
43
+ }
@@ -0,0 +1,193 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import { Hono } from 'hono'
3
+ import type { Env, Variables } from '../../types'
4
+ import { publicProblem } from '../../public/problem-details'
5
+ import {
6
+ createAutomationSchema,
7
+ updateAutomationSchema,
8
+ toggleAutomationSchema,
9
+ } from './automations.schema'
10
+
11
+ const automationsApp = new Hono<{ Bindings: Env; Variables: Variables }>()
12
+
13
+ /**
14
+ * GET /automations?seed=<slug>
15
+ * Returns every automation declared for the given seed, newest first.
16
+ */
17
+ automationsApp.get('/', async (context) => {
18
+ const seedSlug = context.req.query('seed')
19
+ if (!seedSlug) {
20
+ return publicProblem(context, {
21
+ type: 'missing-seed',
22
+ status: 400,
23
+ title: 'Bad Request',
24
+ detail: 'Query param `seed` is required',
25
+ })
26
+ }
27
+ const repository = context.get('automationRepository')
28
+ const automations = await repository.list(seedSlug)
29
+ return context.json(automations)
30
+ })
31
+
32
+ /**
33
+ * POST /automations
34
+ * Creates a new automation. Body validated by `createAutomationSchema`.
35
+ */
36
+ automationsApp.post('/', async (context) => {
37
+ let body: unknown
38
+ try {
39
+ body = await context.req.json()
40
+ } catch {
41
+ return publicProblem(context, {
42
+ type: 'invalid-json',
43
+ status: 400,
44
+ title: 'Bad Request',
45
+ detail: 'Request body is not valid JSON',
46
+ })
47
+ }
48
+
49
+ const parsed = createAutomationSchema.safeParse(body)
50
+ if (!parsed.success) {
51
+ return publicProblem(context, {
52
+ type: 'automation-validation-failed',
53
+ status: 400,
54
+ title: 'Bad Request',
55
+ detail: parsed.error.message,
56
+ })
57
+ }
58
+
59
+ const repository = context.get('automationRepository')
60
+ const id = await repository.create({
61
+ seed_slug: parsed.data.seed_slug,
62
+ name: parsed.data.name,
63
+ triggers: parsed.data.triggers,
64
+ trigger_conditions: parsed.data.trigger_conditions ?? null,
65
+ actions: parsed.data.actions,
66
+ })
67
+ return context.json({ id }, 201)
68
+ })
69
+
70
+ /**
71
+ * GET /automations/:id
72
+ */
73
+ automationsApp.get('/:id', async (context) => {
74
+ const id = context.req.param('id')
75
+ const automation = await context.get('automationRepository').findById(id)
76
+ if (!automation) {
77
+ return publicProblem(context, {
78
+ type: 'automation-not-found',
79
+ status: 404,
80
+ title: 'Not Found',
81
+ detail: `Automation ${id} does not exist`,
82
+ })
83
+ }
84
+ return context.json(automation)
85
+ })
86
+
87
+ /**
88
+ * PUT /automations/:id
89
+ * Full update — partial bodies allowed; cron expression validation
90
+ * is enforced by the triggers array schema.
91
+ */
92
+ automationsApp.put('/:id', async (context) => {
93
+ const id = context.req.param('id')
94
+ const repository = context.get('automationRepository')
95
+ const existing = await repository.findById(id)
96
+ if (!existing) {
97
+ return publicProblem(context, {
98
+ type: 'automation-not-found',
99
+ status: 404,
100
+ title: 'Not Found',
101
+ detail: `Automation ${id} does not exist`,
102
+ })
103
+ }
104
+
105
+ let body: unknown
106
+ try {
107
+ body = await context.req.json()
108
+ } catch {
109
+ return publicProblem(context, {
110
+ type: 'invalid-json',
111
+ status: 400,
112
+ title: 'Bad Request',
113
+ detail: 'Request body is not valid JSON',
114
+ })
115
+ }
116
+
117
+ const parsed = updateAutomationSchema.safeParse(body)
118
+ if (!parsed.success) {
119
+ return publicProblem(context, {
120
+ type: 'automation-validation-failed',
121
+ status: 400,
122
+ title: 'Bad Request',
123
+ detail: parsed.error.message,
124
+ })
125
+ }
126
+
127
+ await repository.update(id, parsed.data)
128
+ return context.body(null, 204)
129
+ })
130
+
131
+ /**
132
+ * PATCH /automations/:id/toggle
133
+ * Atomic single-field flip — does not require sending the full body.
134
+ */
135
+ automationsApp.patch('/:id/toggle', async (context) => {
136
+ const id = context.req.param('id')
137
+ const repository = context.get('automationRepository')
138
+ const existing = await repository.findById(id)
139
+ if (!existing) {
140
+ return publicProblem(context, {
141
+ type: 'automation-not-found',
142
+ status: 404,
143
+ title: 'Not Found',
144
+ detail: `Automation ${id} does not exist`,
145
+ })
146
+ }
147
+
148
+ let body: unknown
149
+ try {
150
+ body = await context.req.json()
151
+ } catch {
152
+ return publicProblem(context, {
153
+ type: 'invalid-json',
154
+ status: 400,
155
+ title: 'Bad Request',
156
+ detail: 'Request body is not valid JSON',
157
+ })
158
+ }
159
+
160
+ const parsed = toggleAutomationSchema.safeParse(body)
161
+ if (!parsed.success) {
162
+ return publicProblem(context, {
163
+ type: 'automation-validation-failed',
164
+ status: 400,
165
+ title: 'Bad Request',
166
+ detail: parsed.error.message,
167
+ })
168
+ }
169
+
170
+ await repository.toggle(id, parsed.data.enabled)
171
+ return context.body(null, 204)
172
+ })
173
+
174
+ /**
175
+ * DELETE /automations/:id
176
+ */
177
+ automationsApp.delete('/:id', async (context) => {
178
+ const id = context.req.param('id')
179
+ const repository = context.get('automationRepository')
180
+ const existing = await repository.findById(id)
181
+ if (!existing) {
182
+ return publicProblem(context, {
183
+ type: 'automation-not-found',
184
+ status: 404,
185
+ title: 'Not Found',
186
+ detail: `Automation ${id} does not exist`,
187
+ })
188
+ }
189
+ await repository.delete(id)
190
+ return context.body(null, 204)
191
+ })
192
+
193
+ export { automationsApp }
@@ -0,0 +1,160 @@
1
+ // Mirror: apps/dashboard/src/features/automations/schema/automation.schema.ts — keep structurally identical.
2
+ import { z } from 'zod'
3
+ import type { WhenNode } from '@beechcms/core'
4
+ import { AUTOMATION_RESERVED_WORDS } from './template-grammar'
5
+
6
+ // ---------------------------------------------------------------------------
7
+ // Trigger conditions — recursive WhenNode schema (Task 14)
8
+ // ---------------------------------------------------------------------------
9
+
10
+ const whenOperandSchema = z.union([
11
+ z.object({ kind: z.literal('literal'), value: z.unknown() }),
12
+ z.object({ kind: z.literal('ref'), key: z.string().min(1) }),
13
+ ])
14
+
15
+ const whenPredicateSchema = z.object({
16
+ kind: z.literal('predicate'),
17
+ left: whenOperandSchema,
18
+ op: z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'contains', 'startswith', 'endswith', 'in', 'notin', 'isempty', 'isnotempty', 'matches']),
19
+ right: whenOperandSchema.optional(),
20
+ })
21
+
22
+ const whenNodeSchema: z.ZodType<WhenNode> = z.lazy(() =>
23
+ z.union([
24
+ whenPredicateSchema,
25
+ z.object({
26
+ kind: z.literal('group'),
27
+ op: z.enum(['AND', 'OR']),
28
+ children: z.array(whenNodeSchema).min(1),
29
+ negate: z.boolean().optional(),
30
+ }).refine(
31
+ (g) => depthOf(g) <= 10,
32
+ { message: 'WhenNode nesting exceeds maximum depth of 10' },
33
+ ),
34
+ ]),
35
+ )
36
+
37
+ function depthOf(node: unknown, d = 0): number {
38
+ if (d > 10) return d
39
+ if (typeof node !== 'object' || !node) return d
40
+ const n = node as Record<string, unknown>
41
+ if (n['kind'] === 'group' && Array.isArray(n['children'])) {
42
+ return Math.max(...(n['children'] as unknown[]).map((c) => depthOf(c, d + 1)))
43
+ }
44
+ return d
45
+ }
46
+
47
+ const triggerConditionsSchema = whenNodeSchema.nullable().optional()
48
+
49
+ const setVariableFilterSchema = z.object({
50
+ field: z.string().min(1),
51
+ op: z.enum(['eq', 'neq', 'contains', 'gt', 'lt', 'isempty', 'isnotempty']),
52
+ value: z.unknown(),
53
+ })
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Action schemas
57
+ // ---------------------------------------------------------------------------
58
+
59
+ const setVariableActionSchema = z.object({
60
+ type: z.literal('set_variable'),
61
+ name: z
62
+ .string()
63
+ .min(1)
64
+ .regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/)
65
+ .refine((v) => !AUTOMATION_RESERVED_WORDS.has(v), {
66
+ message: 'automations.editor.errors.variableNameReserved',
67
+ }),
68
+ seed_slug: z.string().min(1).optional(),
69
+ fixed_id: z.string().min(1).optional(),
70
+ column: z.string().min(1).optional(),
71
+ filters: z.array(setVariableFilterSchema).default([]),
72
+ order_by: z.string().optional(),
73
+ order: z.enum(['asc', 'desc']).optional(),
74
+ })
75
+
76
+ const webhookActionSchema = z.object({
77
+ type: z.literal('webhook'),
78
+ url: z.string().url(),
79
+ method: z.enum(['POST', 'GET', 'PUT']).optional(),
80
+ headers: z.record(z.string(), z.string()).optional(),
81
+ body_template: z.string().optional(),
82
+ })
83
+
84
+ const sendMailActionSchema = z.object({
85
+ type: z.literal('send_mail'),
86
+ to: z.string().email(),
87
+ subject_template: z.string().min(1),
88
+ body_template: z.string().min(1),
89
+ })
90
+
91
+ const editFieldActionSchema = z.object({
92
+ type: z.literal('edit_field'),
93
+ field: z.string().min(1),
94
+ value: z.unknown(),
95
+ })
96
+
97
+ const createEntryActionSchema = z.object({
98
+ type: z.literal('create_entry'),
99
+ seed_slug: z.string().min(1),
100
+ field_map: z.record(z.string(), z.string()),
101
+ })
102
+
103
+ export const automationActionSchema = z.discriminatedUnion('type', [
104
+ setVariableActionSchema,
105
+ webhookActionSchema,
106
+ sendMailActionSchema,
107
+ editFieldActionSchema,
108
+ createEntryActionSchema,
109
+ ])
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Triggers schema
113
+ // ---------------------------------------------------------------------------
114
+
115
+ const automationTriggerSchema = z.object({
116
+ event: z.enum(['create', 'update', 'delete', 'cron']),
117
+ cron: z.string().nullable().optional(),
118
+ })
119
+
120
+ const triggersSchema = z
121
+ .array(automationTriggerSchema)
122
+ .min(1, 'At least one trigger is required')
123
+ .refine(
124
+ (triggers) => triggers.filter((t) => t.event === 'cron').length <= 1,
125
+ { message: 'Only one cron trigger is allowed per automation' },
126
+ )
127
+ .refine(
128
+ (triggers) => {
129
+ const events = triggers.map((t) => t.event)
130
+ return new Set(events).size === events.length
131
+ },
132
+ { message: 'Duplicate trigger events are not allowed' },
133
+ )
134
+ .refine(
135
+ (triggers) => triggers.every((t) => t.event !== 'cron' || !!t.cron),
136
+ { message: 'cron expression is required for cron triggers', path: ['cron'] },
137
+ )
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Automation create/update schemas
141
+ // ---------------------------------------------------------------------------
142
+
143
+ const createAutomationBaseSchema = z.object({
144
+ seed_slug: z.string().min(1),
145
+ name: z.string().min(1).max(100),
146
+ triggers: triggersSchema,
147
+ trigger_conditions: triggerConditionsSchema,
148
+ actions: z.array(automationActionSchema).min(1, 'At least one action is required'),
149
+ })
150
+
151
+ export const createAutomationSchema = createAutomationBaseSchema
152
+
153
+ export const updateAutomationSchema = createAutomationBaseSchema.partial()
154
+
155
+ export const toggleAutomationSchema = z.object({
156
+ enabled: z.boolean(),
157
+ })
158
+
159
+ export type CreateAutomationBody = z.infer<typeof createAutomationSchema>
160
+ export type UpdateAutomationBody = z.infer<typeof updateAutomationSchema>