import { createBrewClient } from '@brew.new/sdk'
const brew = createBrewClient({ apiKey: process.env.BREW_API_KEY! })
// 1. Create the trigger (deterministic shape — provider is hardcoded brew_api).
// Create returns the bare trigger row (HTTP 201).
const trigger = await brew.automations.triggers.create({
title: 'Subscription Renewed',
description: 'Fires when a subscription is renewed.',
payloadSchema: {
type: 'object',
fields: [
{ key: 'email', type: 'string', required: true },
{ key: 'plan', type: 'string', required: true },
{ key: 'amount', type: 'int', required: true },
],
},
})
// 2. Pre-mint each email body. These rows are referenced by sendEmail
// nodes inside the automation graph.
const [welcome, gettingStarted] = await Promise.all([
brew.emails.generate({
prompt: 'Thank-you email for a successful renewal.',
}),
brew.emails.generate({
prompt:
'Getting-started tips for renewed subscribers — focus on the Pro features.',
}),
])
// 3. Assemble the automation graph; sendEmail nodes reference the
// pre-minted emailIds + emailVersionIds.
const automation = await brew.automations.create({
name: 'Renewal welcome flow',
triggerEventId: trigger.triggerEventId,
nodes: [
{
id: 'trg',
label: 'On renewal',
type: 'trigger',
config: { triggerEventId: trigger.triggerEventId },
},
{
id: 'send_welcome',
label: 'Welcome',
type: 'sendEmail',
config: {
emailId: welcome.emailId,
emailVersionId: welcome.emailVersionId,
domainId: 'dom_brand_primary',
subject: 'Welcome back, {{firstName | there}}!',
previewText: 'Quick thanks + 2 things to try first.',
},
},
{
id: 'wait_2d',
label: 'Wait 2 days',
type: 'wait',
config: { duration: 2, unit: 'days' },
},
{
id: 'send_getting_started',
label: 'Getting started',
type: 'sendEmail',
config: {
emailId: gettingStarted.emailId,
emailVersionId: gettingStarted.emailVersionId,
domainId: 'dom_brand_primary',
subject: 'Getting started with Pro',
previewText: 'Three feature tips for your first week.',
},
},
],
connections: [
{ from: 'trg', to: 'send_welcome' },
{ from: 'send_welcome', to: 'wait_2d' },
{ from: 'wait_2d', to: 'send_getting_started' },
],
})
// 4. Publish (convenience wrapper over patch({ published: true })).
await brew.automations.publish({ automationId: automation.automationId })
// 5. Fire the trigger with a real payload.
const fire = await brew.automations.triggers.fire({
triggerEventId: trigger.triggerEventId,
payload: {
email: 'jane@example.com',
plan: 'Pro',
amount: 4200,
},
idempotencyKey: 'renewal-jane-2026-04-08',
})
console.log('Started automation runs:', fire.details?.automationRunIds)
// 6. Poll the run lifecycle (reads live under automations.runs).
const { data: runs } = await brew.automations.runs.list({
automationRunId: fire.details!.automationRunIds[0]!,
include: 'logs',
})
console.log('Status:', runs[0]!.status)