Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: centralize email branding and flow catalogue
Richie McIlroy6a564c3a487b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cdb5aff09..b6738cb53 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -90,6 +90,12 @@ jobs:- name: Test workspace toolingrun: node --test scripts/bun-scripts.test.mjs scripts/check-tauri-plugin-versions.test.mjs+ - name: Check email library+ run: |+ bun run emails:check+ bun test scripts/emails scripts/loops/profile.test.ts+ bun run tsc --noEmit --strict --target ESNext --module ESNext --moduleResolution bundler --resolveJsonModule --types bun --skipLibCheck scripts/loops/*.ts scripts/emails/*.ts emails/*.ts emails/marketing/*.ts+- name: Test web React compatibilityrun: >-bun run --cwd apps/web testdiff --git a/emails/AGENTS.md b/emails/AGENTS.mdnew file mode 100644index 000000000..69645cbb7--- /dev/null+++ b/emails/AGENTS.md@@ -0,0 +1,10 @@+# Working on Cap emails++- Start with `README.md` and `CATALOG.md`. Use the catalogue to identify the email, flow, audience and actual send source before editing.+- Keep marketing content in `marketing/`, branding and sender defaults in `brand.ts`, customer-specific prose in `customer-copy.ts`, and ordering/delays in `flows.ts`. Do not add another copy of these definitions under `scripts/`.+- Keep email IDs and existing flow step keys stable. Declare variables and provide appropriate fallbacks. Preserve opt-outs, teammate exclusions, customer segmentation and imported-contact holds.+- Reconcile dashboard edits into source before updating Loops drafts. Use the current content revision for API updates. Version shared branding before changing resources used by live emails.+- Regenerate `CATALOG.md` using `bun run emails:catalog`; never edit it by hand. Run `bun run emails:check`, scoped Biome, and relevant tests. After a remote draft update, run `bun run emails:check-loops` and inspect the rendered email.+- Keep Resend application templates and sending behavior in their current locations; update `application.ts` when introducing or removing a send path. Listing a template does not establish that its handler is reachable or deployed.+- These commands do not authorize sending, publishing, activating flows, enrolling contacts or deploying production schema. Follow the user's current scope.+- Store only nonsecret resource IDs here. Keep credentials, contact exports and suppression registries outside Git.diff --git a/emails/CATALOG.md b/emails/CATALOG.mdnew file mode 100644index 000000000..35a6e9dcf--- /dev/null+++ b/emails/CATALOG.md@@ -0,0 +1,509 @@+# Cap email catalogue++Generated from the email library with `bun run emails:catalog`. Edit the source files, then regenerate. [Editing guide](README.md).++## Lifecycle flows++These are the locally configured draft journeys. This document is not a live status check. Imports remain held; production enrollment is not deployed. Run `bun run emails:check-loops` to verify the actual Loops drafts.++| Flow | Audience | Schedule after entry | Emails |+| --- | --- | --- | --- |+| [Independent free-user onboarding](https://app.loops.so/workflows/cmtvpih6201fp0jznodf8fpwz) | free | Day 0, Day 2, Day 5, Day 9 | 4 |+| [Customer onboarding](https://app.loops.so/workflows/cmtvpilm601f40jzwx3474cko) | customer | Day 0, Day 3, Day 7 | 3 |+| [Teammate onboarding](https://app.loops.so/workflows/cmtvpm0ag01it0j37w02o6wav) | teammate | Day 0, Day 3 | 2 |+| [Former customer follow-up](https://app.loops.so/workflows/cmtvpm8zm01ii0j01cz7d15qr) | former | Day 14 | 1 |++All journeys require global subscription, positive Cap consent, the exact audience, lifecycle enabled and onboarding eligible. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility. Customer and teammate flows still require marketing consent.++Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).++### Independent free-user onboarding++Entry: capLifecycleStage changes into free. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.++Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals free; capTeammate isFalse; capPromotionalEligible isTrue; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.++```mermaid+flowchart TD+ entry["Stage becomes free"] --> guard["Consent and audience guards"]+ guard --> email0["Day 0: welcome"]+ email0 --> wait1["Wait 2 days"]+ wait1 --> branch1{"capHasVideo is false?"}+ branch1 -->|Yes| email1["Day 2: record"]+ branch1 -->|No: skip| next1((Continue))+ email1 --> next1+ next1 --> wait2["Wait 3 days"]+ wait2 --> branch2{"capHasSharedVideo is false?"}+ branch2 -->|Yes| email2["Day 5: share"]+ branch2 -->|No: skip| next2((Continue))+ email2 --> next2+ next2 --> wait3["Wait 4 days"]+ wait3 --> email3["Day 9: plans"]+ email3 --> exit["End"]+```++| Day | Subject and source | Send condition |+| --- | --- | --- |+| 0 | [Your first Cap can be a small one](../emails/marketing/free-welcome.ts) | Journey guards |+| 2 | [Try a 30-second recording](../emails/marketing/free-record.ts) | `capHasVideo=false` |+| 5 | [Give your next Cap a little context](../emails/marketing/free-share.ts) | `capHasSharedVideo=false` |+| 9 | [Choose the Cap setup that fits your work](../emails/marketing/free-plans.ts) | Journey guards |++### Customer onboarding++Entry: capLifecycleStage changes into customer. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.++Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals customer; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.++```mermaid+flowchart TD+ entry["Stage becomes customer"] --> guard["Consent and audience guards"]+ guard --> email0["Day 0: welcome"]+ email0 --> wait1["Wait 3 days"]+ wait1 --> email1["Day 3: workflow"]+ email1 --> wait2["Wait 4 days"]+ wait2 --> email2["Day 7: feedback"]+ email2 --> exit["End"]+```++| Day | Subject and source | Send condition |+| --- | --- | --- |+| 0 | [Thanks for choosing {contact.capPlanName}](../emails/marketing/customer-welcome.ts) | Journey guards |+| 3 | [One explanation you can reuse](../emails/marketing/customer-workflow.ts) | Journey guards |+| 7 | [How is Cap working for you?](../emails/marketing/customer-feedback.ts) | Journey guards |++### Teammate onboarding++Entry: capLifecycleStage changes into teammate. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.++Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals teammate; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.++```mermaid+flowchart TD+ entry["Stage becomes teammate"] --> guard["Consent and audience guards"]+ guard --> email0["Day 0: welcome"]+ email0 --> wait1["Wait 3 days"]+ wait1 --> email1["Day 3: handoff"]+ email1 --> exit["End"]+```++| Day | Subject and source | Send condition |+| --- | --- | --- |+| 0 | [Getting started with your team in Cap](../emails/marketing/teammate-welcome.ts) | Journey guards |+| 3 | [Make your next handoff easier](../emails/marketing/teammate-handoff.ts) | Journey guards |++### Former customer follow-up++Entry: capLifecycleStage changes into former. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.++Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals former; capTeammate isFalse; capPromotionalEligible isTrue; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.++```mermaid+flowchart TD+ entry["Stage becomes former"] --> guard["Consent and audience guards"]+ guard --> wait0["Wait 14 days"]+ wait0 --> email0["Day 14: feedback"]+ email0 --> exit["End"]+```++| Day | Subject and source | Send condition |+| --- | --- | --- |+| 14 | [What could we have done better?](../emails/marketing/former-feedback.ts) | Journey guards |++## Campaign templates++Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, positive consent and their exact audience. The free template also requires promotional eligibility and excludes teammates.++| Campaign | Audience | Subject and source | Loops ID |+| --- | --- | --- | --- |+| Customer product update template | customer | [What is new in Cap](../emails/marketing/customer-update.ts) | `cmtvpmfxc01ls0j0nnlffombv` |+| Noncustomer product update template | free | [Take another look at Cap](../emails/marketing/free-update.ts) | `cmtvpmjej01kr0j18cxoz2n0y` |++## Branding and personalization++Shared theme, header, signature, sender and fallbacks: [emails/brand.ts](../emails/brand.ts).++Sender: Richie from Cap; local part `richie` on the Loops sending domain. Reply-to: [email protected]. Theme: Cap lifecycle v1.++Shared components: Cap lifecycle header v1; Cap lifecycle signature v1.++Customer welcome variations come from [customer-copy.ts](customer-copy.ts); eligibility is resolved from account and license state in the profile sync.++| Plan | Welcome variation |+| --- | --- |+| Cap Pro | Your Cap Pro plan includes cloud sharing and collaboration, plus the desktop commercial license. Open your dashboard to find your organization and manage your setup. |+| Cap Self-hosted | Your self-hosted license supports your own Cap deployment. Use the setup details supplied with your purchase, and reply if you need help. |+| Cap Desktop | Your desktop license covers commercial use of Cap's recorder and editor. Activate it in the desktop app using the license details from your purchase email. |+| Cap | If you need help with your Cap account or access, reply to this email. |++## Marketing email copy++The excerpts below show content, not an email-client render. Branding and required Loops footer content are composed separately.++### free-welcome++Help an independent free user make their first recording.++**Subject:** Your first Cap can be a small one++**Preview:** Pick one thing you would usually explain in a message.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/free-welcome.ts](../emails/marketing/free-welcome.ts)++Hi {contact.firstName},++Thanks for trying Cap. A good first recording is something small: a quick explanation, a bug you spotted, or feedback on a piece of work.++Pick one thing you would normally type out, and record it instead. Use Instant Mode for a shareable link, or Studio Mode when you want to edit before exporting.++Download Cap++If you get stuck, reply to this email. We can help.++### free-record++Offer recording help when no cloud video is known.++**Subject:** Try a 30-second recording++**Preview:** A simple way to get comfortable with Cap.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/free-record.ts](../emails/marketing/free-record.ts)++Hi {contact.firstName},++Here is an easy way to try Cap: open something you are working on and explain one small part of it out loud.++Choose your screen or a single window, check your microphone, and record for about 30 seconds. No script needed.++If you prefer to keep the recording on your device, use Studio Mode and export it locally.++Open the downloads page++Already recording locally? You are all set. Local recordings do not necessarily appear in your cloud library.++### free-share++Offer sharing guidance when no shared cloud video is known.++**Subject:** Give your next Cap a little context++**Preview:** Help the person watching know what to look for.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/free-share.ts](../emails/marketing/free-share.ts)++Hi {contact.firstName},++A recording works best when the person watching knows why you sent it.++Give your Cap a clear title, then send the link with one sentence about what you need: feedback, a decision, or just a quick look.++For a bug report, show what you expected and what happened. For feedback, point to the specific part you want to discuss.++Open your library++### free-plans++Explain current plan options to eligible independent noncustomers.++**Subject:** Choose the Cap setup that fits your work++**Preview:** A desktop license and Cap Pro solve different needs.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/free-plans.ts](../emails/marketing/free-plans.ts)++Hi {contact.firstName},++If the free version covers what you need, keep using it.++If you use Cap for work, a Desktop License covers commercial use of the desktop recorder and editor. Cap Pro adds the cloud sharing and collaboration features, and includes the desktop commercial license.++The plans page has the current features and prices, so you can choose based on how you actually use Cap.++Compare Cap plans++Unsure which one fits? Reply with how you use Cap and we will point you in the right direction.++### customer-welcome++Welcome a paying customer with copy matching their paid plan.++**Subject:** Thanks for choosing {contact.capPlanName}++**Preview:** A few useful things to do first.++**Variables:** `contact.capCustomerWelcome` (fallback: Your paid access is ready. If you need help getting started, reply to this email.); `contact.capPlanName` (fallback: Cap); `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/customer-welcome.ts](../emails/marketing/customer-welcome.ts)++Hi {contact.firstName},++Thank you for supporting Cap.++{contact.capCustomerWelcome}++Start with one recording you need to make this week. A walkthrough, a customer explanation, or feedback for a colleague is plenty.++Get Cap++If anything about your setup or access looks wrong, reply and we will help you sort it out.++### customer-workflow++Help a customer build a repeatable recording habit.++**Subject:** One explanation you can reuse++**Preview:** Turn a recurring question into a short recording.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/customer-workflow.ts](../emails/marketing/customer-workflow.ts)++Hi {contact.firstName},++One of the most useful things to record is an answer you keep giving.++Pick a recurring question, record a short walkthrough, and give it a title you will recognize later. Trim the beginning and end if you need to, then export or share it in the way that suits your work.++The next time the question comes up, you already have the answer ready.++If you have a workflow you would like Cap to make easier, reply and tell us about it.++### customer-feedback++Ask a customer what is useful and what needs improvement.++**Subject:** How is Cap working for you?++**Preview:** Tell us what is useful and what gets in the way.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/customer-feedback.ts](../emails/marketing/customer-feedback.ts)++Hi {contact.firstName},++How has Cap been working for you?++I would love to know what you have been using it for, and whether anything has been confusing or frustrating.++Just reply to this email. Specific examples help us decide what to improve next.++Thanks again for supporting what we are building.++### teammate-welcome++Help an invited teammate find their workspace without promoting upgrades.++**Subject:** Getting started with your team in Cap++**Preview:** Find your workspace and make your first handoff easier.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/teammate-welcome.ts](../emails/marketing/teammate-welcome.ts)++Hi {contact.firstName},++Welcome to your team in Cap.++Open your dashboard and make sure the right organization is selected. That is where you will find the recordings your team shares with you.++If something is missing, check with the person who invited you. They can confirm your workspace and access.++Open your workspace++You can also reply here if you need help getting set up.++### teammate-handoff++Help a teammate share useful context with their organization.++**Subject:** Make your next handoff easier++**Preview:** A short recording can give your teammate the context they need.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/teammate-handoff.ts](../emails/marketing/teammate-handoff.ts)++Hi {contact.firstName},++For your next handoff, try recording the bit that is difficult to explain in writing.++Show the work, explain what changed, and say what you need from the person watching. A clear title and a short note beside the link make it easier to pick up later.++When sharing, check that the recording is available to the right people in your organization.++Open your workspace++If the team workflow feels awkward anywhere, reply and let us know.++### former-feedback++Ask an eligible former cloud customer for feedback after paid access ends.++**Subject:** What could we have done better?++**Preview:** A quick question about your experience with Cap.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/former-feedback.ts](../emails/marketing/former-feedback.ts)++Hi {contact.firstName},++Now that your paid access has ended, I wanted to ask what could have made Cap more useful for you.++Was there something missing, something that did not work properly, or did you just not need it anymore?++Reply if you have a moment. Honest feedback helps us make better decisions.++Thanks for giving Cap a try.++### customer-update++Reusable product update for customers.++**Subject:** What is new in Cap++**Preview:** See the latest improvements in the changelog.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/customer-update.ts](../emails/marketing/customer-update.ts)++Hi {contact.firstName},++We have been working on improvements to Cap. You can find the latest changes and fixes in the changelog.++Read the changelog++If something would make Cap more useful for you, reply and tell us.++### free-update++Reusable product update for eligible independent noncustomers.++**Subject:** Take another look at Cap++**Preview:** Catch up on the latest changes.++**Variables:** `contact.firstName` (fallback: there)++**Edit:** [emails/marketing/free-update.ts](../emails/marketing/free-update.ts)++Hi {contact.firstName},++If you have not tried Cap recently, the changelog is a good place to see what has changed.++Download the latest version when you have a recording to make. You can start small and see whether it fits how you work.++See what is new++## Application emails++These are repository send paths and retained templates, not confirmation of production delivery. They continue through Resend and keep their existing React Email layouts. Loops audience filters do not control them. Shared marketing branding does not automatically restyle these templates.++| Email | Trigger | Recipients | Template |+| --- | --- | --- | --- |+| Login verification code | Web or mobile email authentication request | The person signing in | [otp-email](../packages/database/emails/otp-email.tsx) |+| Organization invitation | An organization invitation is issued through the web action or public API | The invited teammate | [organization-invite](../packages/database/emails/organization-invite.tsx) |+| Requested download links | The person requests download links by email | The requesting email address | [download-link](../packages/database/emails/download-link.tsx) |+| First shareable recording | Desktop API creates the first eligible shareable recording | The recording owner | [first-shareable-link](../packages/database/emails/first-shareable-link.tsx) |+| New comment notification | An eligible comment notification is created | The notification recipient | [new-comment](../packages/database/emails/new-comment.tsx) |+| First view notification | An eligible recording receives its first view | The recording owner | [first-view](../packages/database/emails/first-view.tsx) |+| Payment failed / final retry | Stripe invoice payment fails | The billing account user | [payment-failed](../packages/database/emails/payment-failed.tsx) |+| Signed BAA delivery | A business associate agreement is signed | The signer, with the configured notice recipients copied | [signed-baa](../packages/database/emails/signed-baa.tsx) |+| Desktop feedback notification | Legacy desktop feedback handler | Cap support, with the user copied | [feedback](../packages/database/emails/feedback.tsx) |+| Messenger support notification | An eligible support conversation requests an email notification | Cap support; replies go to the user | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |+| Account deletion request notification | An account deletion request is submitted | Cap support; replies go to the requester | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |+| Mobile content report notification | A mobile content report is submitted | Cap support; replies go to the reporter | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |+| Legacy login link template | No current send call found in this checkout | None configured | [login-link](../packages/database/emails/login-link.tsx) |++### Login verification code++OTP authentication; does not subscribe the recipient to marketing.++Send source: [packages/database/auth/auth-options.ts](../packages/database/auth/auth-options.ts), [apps/web/app/api/mobile/[...route]/route.ts](../apps/web/app/api/mobile/%5B...route%5D/route.ts).++### Organization invitation++An invitation is not permission to send promotions.++Send source: [apps/web/actions/organization/send-invites.ts](../apps/web/actions/organization/send-invites.ts), [apps/web/app/api/v1/[...route]/route.ts](../apps/web/app/api/v1/%5B...route%5D/route.ts).++### Requested download links++Uses the existing Resend marketing sender flag; Loops audience filters do not govern this send.++Send source: [apps/web/actions/send-download-link.ts](../apps/web/actions/send-download-link.ts).++### First shareable recording++Scheduled in Resend for five minutes later; uses the existing marketing sender flag. Check overlap before activating Loops recording reminders.++Send source: [apps/web/app/api/desktop/[...route]/video.ts](../apps/web/app/api/desktop/%5B...route%5D/video.ts).++### New comment notification++Notification preferences and exclusions are applied by Notification.ts.++Send source: [apps/web/lib/Notification.ts](../apps/web/lib/Notification.ts).++### First view notification++Notification preferences and first-view checks are applied by Notification.ts.++Send source: [apps/web/lib/Notification.ts](../apps/web/lib/Notification.ts).++### Payment failed / final retry++Different subject and content for the final attempt; deduplicated by invoice and attempt.++Send source: [apps/web/app/api/webhooks/stripe/route.ts](../apps/web/app/api/webhooks/stripe/route.ts).++### Signed BAA delivery++Includes the signed PDF and tracks delivery state; preserve attachment and CC behavior.++Send source: [apps/web/actions/organization/signed-baa.ts](../apps/web/actions/organization/signed-baa.ts).++### Desktop feedback notification++Source-defined handler; inspect route reachability before relying on it.++Send source: [apps/web/app/api/desktop/[...route]/root.ts](../apps/web/app/api/desktop/%5B...route%5D/root.ts).++### Messenger support notification++The support service reserves notification state before sending.++Send source: [apps/web/lib/messenger/support-email.ts](../apps/web/lib/messenger/support-email.ts).++### Account deletion request notification++Deduplicated by deletion request ID.++Send source: [apps/web/lib/account-deletion-request.ts](../apps/web/lib/account-deletion-request.ts).++### Mobile content report notification++Deduplicated by report ID.++Send source: [apps/web/lib/account-deletion-request.ts](../apps/web/lib/account-deletion-request.ts).++### Legacy login link template++Retained source template; current email login uses verification codes.++Send source: No current call site.diff --git a/emails/README.md b/emails/README.mdnew file mode 100644index 000000000..d518db8c5--- /dev/null+++ b/emails/README.md@@ -0,0 +1,68 @@+# Cap email library++Start with the [email catalogue and flow maps](CATALOG.md). It contains all four Loops journeys, two campaign templates, every marketing email's copy, customer variations, and the existing Resend application email inventory. The catalogue is generated from the same definitions used by the migration tooling.++## Where to make changes++| Change | Source |+| --------------------------------------------------------------------- | ------------------------------------ |+| See all flows, timing and email copy | [CATALOG.md](CATALOG.md) |+| Colours, typography, buttons, header, signature, sender and fallbacks | [brand.ts](brand.ts) |+| Subject, preview, body and purpose of one marketing email | [marketing/](marketing/) |+| Flow order, relative delays and milestone branches | [flows.ts](flows.ts) |+| Campaign definitions and targeting | [campaigns.ts](campaigns.ts) |+| Shared audience filter rules and contact property names | [audiences.ts](audiences.ts) |+| Paid-plan names and customer welcome variations | [customer-copy.ts](customer-copy.ts) |+| Existing application email purposes, triggers and send locations | [application.ts](application.ts) |+| Nonsecret Loops resource and node IDs | [resources.json](resources.json) |++Marketing copy belongs here. `scripts/loops/program.ts` is a compatibility export, not another source to edit. Each marketing file holds its subject, preview, purpose, declared variables and LMX body. Paragraphs are separate strings joined without changing the resulting email. Shared branding is composed around each body by `emailContent()`.++Application emails keep their existing React Email templates under `packages/database/emails/`. This index links to those sources; it does not duplicate their templates or change their provider. Loops audience filters and marketing branding do not automatically apply to Resend sends.++## Edit and inspect locally++From the repository root:++```sh+bun run emails:catalog+bun run emails:check+bun test scripts/emails scripts/loops/profile.test.ts+```++`emails:catalog` rebuilds the readable catalogue and Mermaid diagrams. `emails:check` is offline: it checks catalogue freshness, duplicate/missing email files, declared variables and fallbacks, shared branding use, delays, and the application template/send-source inventory. It does not replace Loops' LMX compiler, Guardian or a rendered preview.++Flow delays are relative to the previous step. The catalogue computes cumulative day numbers automatically. A skipped milestone reminder rejoins the flow and still observes the subsequent delay. The first-recording Resend email is also listed so future changes can account for overlap.++## Compare with Loops++Provide `LOOPS_API_KEY` in the process environment, then run:++```sh+bun run emails:check-loops+```++This command only reads Loops. It checks the expected team, registered resource IDs, draft status, workflow graph, downstream audience guards, branch reconnections, delays, campaign audiences, configured theme styles, shared components, message content, sender fields, fallbacks and Guardian results. It reports a failure when local and remote content differ. Live status is not embedded in the generated catalogue.++Dashboard edits must be reconciled into the local source before updating a managed draft. Read the current email and its `contentRevisionId`, compare it with the proposed local content, and preserve intentional dashboard changes. Updates must include `expectedRevisionId` so an intervening edit causes a conflict. The older provisioner uses a resumable migration receipt and is not a two-way editor or a replacement for this comparison.++Use the official Loops API/LMX skills for draft changes. Review the local diff, update only the intended drafts, run the read-only check again, and inspect the Loops render. Do not send a test or preview email as part of local validation. Sending and workflow activation remain separate actions.++## Branding changes++All marketing messages inherit one theme and shared header/signature components. Keep brand styling in `brand.ts`; individual messages should contain content and layout, not copied colours, fonts or logos.++Shared Loops theme/component updates can affect every email using them. Create a new named branding version for a redesign, attach it to reviewed drafts, then verify the rendered result. The provisioner refuses to silently reuse a same-named theme/component whose content differs. Retain the previous version while any live email uses it.++Changing `customer-copy.ts` changes the copy produced by profile sync; it does not instantly rewrite contact properties already stored in Loops. Review and refresh the intended profiles separately.++## Add an email or flow++1. Add one `marketing/<stable-id>.ts` file implementing `EmailDefinition`; use the same ID as its filename.+2. Declare every contact variable used in the subject, preview and body. Add an appropriate shared fallback and contact property contract when needed. Current journeys use contact-property triggers; event variables need an explicit event-trigger design first.+3. Register it in `flows.ts` or `campaigns.ts`. Keep existing step keys stable because migration receipts identify nodes by these keys.+4. Regenerate and review the catalogue. For a new flow, verify consent, customers, teammate exclusions, downstream guards and re-entry behavior.+5. Create or update the intended Loops draft using the migration/API tooling and record verified resource/node IDs in `resources.json`. Workflow graph editing currently uses the migration beta integration; content checks do not grant activation permission.+6. Run local and remote checks, inspect the render, and commit the source and regenerated catalogue together.++Never add exports, subscriber records, consent hashes or credentials to this directory. The [migration runbook](../scripts/loops/README.md) owns imports, consent seeding, live sync and cutover requirements. No local library command enrolls contacts or sends emails.diff --git a/emails/application.ts b/emails/application.tsnew file mode 100644index 000000000..fed7fbd3f--- /dev/null+++ b/emails/application.ts@@ -0,0 +1,144 @@+export type ApplicationEmail = {+ id: string;+ name: string;+ trigger: string;+ recipients: string;+ notes: string;+ template: string;+ sources: string[];+};++export const applicationEmails: ApplicationEmail[] = [+ {+ id: "verification-code",+ name: "Login verification code",+ trigger: "Web or mobile email authentication request",+ recipients: "The person signing in",+ notes: "OTP authentication; does not subscribe the recipient to marketing.",+ template: "otp-email",+ sources: [+ "packages/database/auth/auth-options.ts",+ "apps/web/app/api/mobile/[...route]/route.ts",+ ],+ },+ {+ id: "organization-invite",+ name: "Organization invitation",+ trigger:+ "An organization invitation is issued through the web action or public API",+ recipients: "The invited teammate",+ notes: "An invitation is not permission to send promotions.",+ template: "organization-invite",+ sources: [+ "apps/web/actions/organization/send-invites.ts",+ "apps/web/app/api/v1/[...route]/route.ts",+ ],+ },+ {+ id: "download-link",+ name: "Requested download links",+ trigger: "The person requests download links by email",+ recipients: "The requesting email address",+ notes:+ "Uses the existing Resend marketing sender flag; Loops audience filters do not govern this send.",+ template: "download-link",+ sources: ["apps/web/actions/send-download-link.ts"],+ },+ {+ id: "first-shareable-link",+ name: "First shareable recording",+ trigger: "Desktop API creates the first eligible shareable recording",+ recipients: "The recording owner",+ notes:+ "Scheduled in Resend for five minutes later; uses the existing marketing sender flag. Check overlap before activating Loops recording reminders.",+ template: "first-shareable-link",+ sources: ["apps/web/app/api/desktop/[...route]/video.ts"],+ },+ {+ id: "new-comment",+ name: "New comment notification",+ trigger: "An eligible comment notification is created",+ recipients: "The notification recipient",+ notes:+ "Notification preferences and exclusions are applied by Notification.ts.",+ template: "new-comment",+ sources: ["apps/web/lib/Notification.ts"],+ },+ {+ id: "first-view",+ name: "First view notification",+ trigger: "An eligible recording receives its first view",+ recipients: "The recording owner",+ notes:+ "Notification preferences and first-view checks are applied by Notification.ts.",+ template: "first-view",+ sources: ["apps/web/lib/Notification.ts"],+ },+ {+ id: "payment-failed",+ name: "Payment failed / final retry",+ trigger: "Stripe invoice payment fails",+ recipients: "The billing account user",+ notes:+ "Different subject and content for the final attempt; deduplicated by invoice and attempt.",+ template: "payment-failed",+ sources: ["apps/web/app/api/webhooks/stripe/route.ts"],+ },+ {+ id: "signed-baa",+ name: "Signed BAA delivery",+ trigger: "A business associate agreement is signed",+ recipients: "The signer, with the configured notice recipients copied",+ notes:+ "Includes the signed PDF and tracks delivery state; preserve attachment and CC behavior.",+ template: "signed-baa",+ sources: ["apps/web/actions/organization/signed-baa.ts"],+ },+ {+ id: "desktop-feedback",+ name: "Desktop feedback notification",+ trigger: "Legacy desktop feedback handler",+ recipients: "Cap support, with the user copied",+ notes:+ "Source-defined handler; inspect route reachability before relying on it.",+ template: "feedback",+ sources: ["apps/web/app/api/desktop/[...route]/root.ts"],+ },+ {+ id: "messenger-support",+ name: "Messenger support notification",+ trigger: "An eligible support conversation requests an email notification",+ recipients: "Cap support; replies go to the user",+ notes: "The support service reserves notification state before sending.",+ template: "messenger-support-email",+ sources: ["apps/web/lib/messenger/support-email.ts"],+ },+ {+ id: "account-deletion",+ name: "Account deletion request notification",+ trigger: "An account deletion request is submitted",+ recipients: "Cap support; replies go to the requester",+ notes: "Deduplicated by deletion request ID.",+ template: "messenger-support-email",+ sources: ["apps/web/lib/account-deletion-request.ts"],+ },+ {+ id: "content-report",+ name: "Mobile content report notification",+ trigger: "A mobile content report is submitted",+ recipients: "Cap support; replies go to the reporter",+ notes: "Deduplicated by report ID.",+ template: "messenger-support-email",+ sources: ["apps/web/lib/account-deletion-request.ts"],+ },+ {+ id: "login-link",+ name: "Legacy login link template",+ trigger: "No current send call found in this checkout",+ recipients: "None configured",+ notes:+ "Retained source template; current email login uses verification codes.",+ template: "login-link",+ sources: [],+ },+];diff --git a/emails/audiences.ts b/emails/audiences.tsnew file mode 100644index 000000000..2d89a52e7--- /dev/null+++ b/emails/audiences.ts@@ -0,0 +1,47 @@+export const contactProperties = {+ capAudience: "string",+ capOrigin: "string",+ capConsent: "string",+ capTeammate: "boolean",+ capCustomer: "boolean",+ capPlanName: "string",+ capCustomerWelcome: "string",+ capPromotionalEligible: "boolean",+ capOnboardingEligible: "boolean",+ capLifecycleEnabled: "boolean",+ capLifecycleStage: "string",+ capHasVideo: "boolean",+ capHasSharedVideo: "boolean",+ capVerifiedAt: "date",+ capImportedAt: "date",+ capSignupAt: "date",+ capSourceTags: "string",+ capSourceGroup: "string",+} as const;++export type Condition = {+ type: "property";+ key: string;+ operator: "equals" | "isTrue" | "isFalse";+ value?: string;+};++export const condition = (key: string, value: string | boolean): Condition =>+ typeof value === "boolean"+ ? { type: "property", key, operator: value ? "isTrue" : "isFalse" }+ : { type: "property", key, operator: "equals", value };++export const audienceFilter = (audience: string, promotional: boolean) => ({+ match: "all" as const,+ conditions: [+ condition("subscribed", true),+ condition("capConsent", "subscribed"),+ condition("capAudience", audience),+ ...(promotional+ ? [+ condition("capTeammate", false),+ condition("capPromotionalEligible", true),+ ]+ : []),+ ],+});diff --git a/emails/brand.ts b/emails/brand.tsnew file mode 100644index 000000000..129a6f28c--- /dev/null+++ b/emails/brand.ts@@ -0,0 +1,65 @@+export const brandingVersion = 1;++export const theme = {+ name: `Cap lifecycle v${brandingVersion}`,+ styles: {+ backgroundColor: "#ffffff",+ bodyColor: "#ffffff",+ bodyXPadding: 28,+ bodyYPadding: 28,+ bodyFontFamily: "Helvetica",+ bodyFontCategory: "sans-serif",+ textBaseColor: "#252525",+ textBaseFontSize: 16,+ textBaseLineHeight: 26,+ textLinkColor: "#3159d6",+ heading1Color: "#171717",+ heading1FontSize: 26,+ heading1LineHeight: 34,+ heading2FontSize: 21,+ buttonBodyColor: "#3159d6",+ buttonTextColor: "#ffffff",+ buttonTextFontSize: 16,+ buttonBorderRadius: 8,+ buttonBodyXPadding: 18,+ buttonBodyYPadding: 12,+ },+};++export const components = [+ {+ name: `Cap lifecycle header v${brandingVersion}`,+ lmx: '<Paragraph fontSize="20" paddingBottom="24"><Strong><Link href="https://cap.so">Cap</Link></Strong></Paragraph>',+ },+ {+ name: `Cap lifecycle signature v${brandingVersion}`,+ lmx: '<Paragraph paddingTop="16">Richie<Br />Founder, Cap</Paragraph>',+ },+];++export const sender = {+ fromName: "Richie from Cap",+ fromEmail: "richie",+ replyToEmail: "[email protected]",+ emailFormat: "styled",+};++export const contactFallbacks = {+ firstName: "there",+ capPlanName: "Cap",+ capCustomerWelcome:+ "Your paid access is ready. If you need help getting started, reply to this email.",+};++export type BrandIds = { theme: string; header: string; signature: string };++export const emailContent = (+ message: { subject: string; previewText: string; body: string },+ ids: BrandIds,+) => ({+ subject: message.subject,+ previewText: message.previewText,+ ...sender,+ lmx: `<Style themeId="${ids.theme}" />\n<Component componentId="${ids.header}" />\n${message.body}\n<Component componentId="${ids.signature}" />`,+ contactPropertiesFallbacks: contactFallbacks,+});diff --git a/emails/campaigns.ts b/emails/campaigns.tsnew file mode 100644index 000000000..978667901--- /dev/null+++ b/emails/campaigns.ts@@ -0,0 +1,18 @@+import { customerUpdate } from "./marketing/customer-update";+import { freeUpdate } from "./marketing/free-update";+import type { Campaign } from "./types";++export const campaignTemplates: Campaign[] = [+ {+ ...customerUpdate,+ name: "Cap | Customer product update template",+ audience: "customer",+ promotional: false,+ },+ {+ ...freeUpdate,+ name: "Cap | Noncustomer product update template",+ audience: "free",+ promotional: true,+ },+];diff --git a/emails/customer-copy.ts b/emails/customer-copy.tsnew file mode 100644index 000000000..23a5eb25b--- /dev/null+++ b/emails/customer-copy.ts@@ -0,0 +1,22 @@+export const customerCopy = {+ pro: {+ plan: "Cap Pro",+ welcome:+ "Your Cap Pro plan includes cloud sharing and collaboration, plus the desktop commercial license. Open your dashboard to find your organization and manage your setup.",+ },+ selfhosted: {+ plan: "Cap Self-hosted",+ welcome:+ "Your self-hosted license supports your own Cap deployment. Use the setup details supplied with your purchase, and reply if you need help.",+ },+ desktop: {+ plan: "Cap Desktop",+ welcome:+ "Your desktop license covers commercial use of Cap's recorder and editor. Activate it in the desktop app using the license details from your purchase email.",+ },+ other: {+ plan: "Cap",+ welcome:+ "If you need help with your Cap account or access, reply to this email.",+ },+};diff --git a/emails/flows.ts b/emails/flows.tsnew file mode 100644index 000000000..6fd19fd0a--- /dev/null+++ b/emails/flows.ts@@ -0,0 +1,62 @@+import { customerFeedback } from "./marketing/customer-feedback";+import { customerWelcome } from "./marketing/customer-welcome";+import { customerWorkflow } from "./marketing/customer-workflow";+import { formerFeedback } from "./marketing/former-feedback";+import { freePlans } from "./marketing/free-plans";+import { freeRecord } from "./marketing/free-record";+import { freeShare } from "./marketing/free-share";+import { freeWelcome } from "./marketing/free-welcome";+import { teammateHandoff } from "./marketing/teammate-handoff";+import { teammateWelcome } from "./marketing/teammate-welcome";+import type { Journey } from "./types";++export const journeys: Journey[] = [+ {+ key: "free",+ name: "Cap | Independent free-user onboarding",+ audience: "free",+ promotional: true,+ messages: [+ { ...freeWelcome, delayDays: 0 },+ {+ ...freeRecord,+ delayDays: 2,+ onlyIf: { property: "capHasVideo", value: false },+ },+ {+ ...freeShare,+ delayDays: 3,+ onlyIf: { property: "capHasSharedVideo", value: false },+ },+ { ...freePlans, delayDays: 4 },+ ],+ },+ {+ key: "customer",+ name: "Cap | Customer onboarding",+ audience: "customer",+ promotional: false,+ messages: [+ { ...customerWelcome, delayDays: 0 },+ { ...customerWorkflow, delayDays: 3 },+ { ...customerFeedback, delayDays: 4 },+ ],+ },+ {+ key: "teammate",+ name: "Cap | Teammate onboarding",+ audience: "teammate",+ promotional: false,+ messages: [+ { ...teammateWelcome, delayDays: 0 },+ { ...teammateHandoff, delayDays: 3 },+ ],+ },+ {+ key: "former",+ name: "Cap | Former customer follow-up",+ audience: "former",+ promotional: true,+ messages: [{ ...formerFeedback, delayDays: 14 }],+ },+];diff --git a/emails/index.ts b/emails/index.tsnew file mode 100644index 000000000..16566da99--- /dev/null+++ b/emails/index.ts@@ -0,0 +1,5 @@+export { audienceFilter, condition, contactProperties } from "./audiences";+export { components, theme } from "./brand";+export { campaignTemplates } from "./campaigns";+export { journeys } from "./flows";+export const programVersion = "cap-lifecycle-v1";diff --git a/emails/marketing/customer-feedback.ts b/emails/marketing/customer-feedback.tsnew file mode 100644index 000000000..84f124d04--- /dev/null+++ b/emails/marketing/customer-feedback.ts@@ -0,0 +1,17 @@+import type { EmailDefinition } from "../types";++export const customerFeedback = {+ id: "customer-feedback",+ key: "feedback",+ purpose: "Ask a customer what is useful and what needs improvement.",+ subject: "How is Cap working for you?",+ previewText: "Tell us what is useful and what gets in the way.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>How has Cap been working for you?</Paragraph>",+ "<Paragraph>I would love to know what you have been using it for, and whether anything has been confusing or frustrating.</Paragraph>",+ "<Paragraph>Just reply to this email. Specific examples help us decide what to improve next.</Paragraph>",+ "<Paragraph>Thanks again for supporting what we are building.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/customer-update.ts b/emails/marketing/customer-update.tsnew file mode 100644index 000000000..8738fa176--- /dev/null+++ b/emails/marketing/customer-update.ts@@ -0,0 +1,16 @@+import type { EmailDefinition } from "../types";++export const customerUpdate = {+ id: "customer-update",+ key: "customer-update",+ purpose: "Reusable product update for customers.",+ subject: "What is new in Cap",+ previewText: "See the latest improvements in the changelog.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>We have been working on improvements to Cap. You can find the latest changes and fixes in the changelog.</Paragraph>",+ '<Button href="https://cap.so/changelog" align="left" paddingTop="16" paddingBottom="16">Read the changelog</Button>',+ "<Paragraph>If something would make Cap more useful for you, reply and tell us.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/customer-welcome.ts b/emails/marketing/customer-welcome.tsnew file mode 100644index 000000000..2bfe98ee7--- /dev/null+++ b/emails/marketing/customer-welcome.ts@@ -0,0 +1,18 @@+import type { EmailDefinition } from "../types";++export const customerWelcome = {+ id: "customer-welcome",+ key: "welcome",+ purpose: "Welcome a paying customer with copy matching their paid plan.",+ subject: "Thanks for choosing {contact.capPlanName}",+ previewText: "A few useful things to do first.",+ variables: ["capCustomerWelcome", "capPlanName", "firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>Thank you for supporting Cap.</Paragraph>",+ "<Paragraph>{contact.capCustomerWelcome}</Paragraph>",+ "<Paragraph>Start with one recording you need to make this week. A walkthrough, a customer explanation, or feedback for a colleague is plenty.</Paragraph>",+ '<Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Get Cap</Button>',+ "<Paragraph>If anything about your setup or access looks wrong, reply and we will help you sort it out.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/customer-workflow.ts b/emails/marketing/customer-workflow.tsnew file mode 100644index 000000000..f6be2aaae--- /dev/null+++ b/emails/marketing/customer-workflow.ts@@ -0,0 +1,17 @@+import type { EmailDefinition } from "../types";++export const customerWorkflow = {+ id: "customer-workflow",+ key: "workflow",+ purpose: "Help a customer build a repeatable recording habit.",+ subject: "One explanation you can reuse",+ previewText: "Turn a recurring question into a short recording.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>One of the most useful things to record is an answer you keep giving.</Paragraph>",+ "<Paragraph>Pick a recurring question, record a short walkthrough, and give it a title you will recognize later. Trim the beginning and end if you need to, then export or share it in the way that suits your work.</Paragraph>",+ "<Paragraph>The next time the question comes up, you already have the answer ready.</Paragraph>",+ "<Paragraph>If you have a workflow you would like Cap to make easier, reply and tell us about it.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/former-feedback.ts b/emails/marketing/former-feedback.tsnew file mode 100644index 000000000..f4c3f77ae--- /dev/null+++ b/emails/marketing/former-feedback.ts@@ -0,0 +1,18 @@+import type { EmailDefinition } from "../types";++export const formerFeedback = {+ id: "former-feedback",+ key: "feedback",+ purpose:+ "Ask an eligible former cloud customer for feedback after paid access ends.",+ subject: "What could we have done better?",+ previewText: "A quick question about your experience with Cap.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>Now that your paid access has ended, I wanted to ask what could have made Cap more useful for you.</Paragraph>",+ "<Paragraph>Was there something missing, something that did not work properly, or did you just not need it anymore?</Paragraph>",+ "<Paragraph>Reply if you have a moment. Honest feedback helps us make better decisions.</Paragraph>",+ "<Paragraph>Thanks for giving Cap a try.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/free-plans.ts b/emails/marketing/free-plans.tsnew file mode 100644index 000000000..d9d3dd903--- /dev/null+++ b/emails/marketing/free-plans.ts@@ -0,0 +1,18 @@+import type { EmailDefinition } from "../types";++export const freePlans = {+ id: "free-plans",+ key: "plans",+ purpose: "Explain current plan options to eligible independent noncustomers.",+ subject: "Choose the Cap setup that fits your work",+ previewText: "A desktop license and Cap Pro solve different needs.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>If the free version covers what you need, keep using it.</Paragraph>",+ "<Paragraph>If you use Cap for work, a <Strong>Desktop License</Strong> covers commercial use of the desktop recorder and editor. <Strong>Cap Pro</Strong> adds the cloud sharing and collaboration features, and includes the desktop commercial license.</Paragraph>",+ "<Paragraph>The plans page has the current features and prices, so you can choose based on how you actually use Cap.</Paragraph>",+ '<Button href="https://cap.so/pricing" align="left" paddingTop="16" paddingBottom="16">Compare Cap plans</Button>',+ "<Paragraph>Unsure which one fits? Reply with how you use Cap and we will point you in the right direction.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/free-record.ts b/emails/marketing/free-record.tsnew file mode 100644index 000000000..381d60e4c--- /dev/null+++ b/emails/marketing/free-record.ts@@ -0,0 +1,18 @@+import type { EmailDefinition } from "../types";++export const freeRecord = {+ id: "free-record",+ key: "record",+ purpose: "Offer recording help when no cloud video is known.",+ subject: "Try a 30-second recording",+ previewText: "A simple way to get comfortable with Cap.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>Here is an easy way to try Cap: open something you are working on and explain one small part of it out loud.</Paragraph>",+ "<Paragraph>Choose your screen or a single window, check your microphone, and record for about 30 seconds. No script needed.</Paragraph>",+ "<Paragraph>If you prefer to keep the recording on your device, use Studio Mode and export it locally.</Paragraph>",+ '<Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Open the downloads page</Button>',+ "<Paragraph>Already recording locally? You are all set. Local recordings do not necessarily appear in your cloud library.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/free-share.ts b/emails/marketing/free-share.tsnew file mode 100644index 000000000..bfd856038--- /dev/null+++ b/emails/marketing/free-share.ts@@ -0,0 +1,17 @@+import type { EmailDefinition } from "../types";++export const freeShare = {+ id: "free-share",+ key: "share",+ purpose: "Offer sharing guidance when no shared cloud video is known.",+ subject: "Give your next Cap a little context",+ previewText: "Help the person watching know what to look for.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>A recording works best when the person watching knows why you sent it.</Paragraph>",+ "<Paragraph>Give your Cap a clear title, then send the link with one sentence about what you need: feedback, a decision, or just a quick look.</Paragraph>",+ "<Paragraph>For a bug report, show what you expected and what happened. For feedback, point to the specific part you want to discuss.</Paragraph>",+ '<Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your library</Button>',+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/free-update.ts b/emails/marketing/free-update.tsnew file mode 100644index 000000000..29afdc3d3--- /dev/null+++ b/emails/marketing/free-update.ts@@ -0,0 +1,16 @@+import type { EmailDefinition } from "../types";++export const freeUpdate = {+ id: "free-update",+ key: "free-update",+ purpose: "Reusable product update for eligible independent noncustomers.",+ subject: "Take another look at Cap",+ previewText: "Catch up on the latest changes.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>If you have not tried Cap recently, the changelog is a good place to see what has changed.</Paragraph>",+ "<Paragraph>Download the latest version when you have a recording to make. You can start small and see whether it fits how you work.</Paragraph>",+ '<Button href="https://cap.so/changelog" align="left" paddingTop="16" paddingBottom="16">See what is new</Button>',+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/free-welcome.ts b/emails/marketing/free-welcome.tsnew file mode 100644index 000000000..d7549f291--- /dev/null+++ b/emails/marketing/free-welcome.ts@@ -0,0 +1,17 @@+import type { EmailDefinition } from "../types";++export const freeWelcome = {+ id: "free-welcome",+ key: "welcome",+ purpose: "Help an independent free user make their first recording.",+ subject: "Your first Cap can be a small one",+ previewText: "Pick one thing you would usually explain in a message.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>Thanks for trying Cap. A good first recording is something small: a quick explanation, a bug you spotted, or feedback on a piece of work.</Paragraph>",+ "<Paragraph><Strong>Pick one thing you would normally type out, and record it instead.</Strong> Use Instant Mode for a shareable link, or Studio Mode when you want to edit before exporting.</Paragraph>",+ '<Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Download Cap</Button>',+ "<Paragraph>If you get stuck, reply to this email. We can help.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/teammate-handoff.ts b/emails/marketing/teammate-handoff.tsnew file mode 100644index 000000000..fbc8ee1a1--- /dev/null+++ b/emails/marketing/teammate-handoff.ts@@ -0,0 +1,19 @@+import type { EmailDefinition } from "../types";++export const teammateHandoff = {+ id: "teammate-handoff",+ key: "handoff",+ purpose: "Help a teammate share useful context with their organization.",+ subject: "Make your next handoff easier",+ previewText:+ "A short recording can give your teammate the context they need.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>For your next handoff, try recording the bit that is difficult to explain in writing.</Paragraph>",+ "<Paragraph>Show the work, explain what changed, and say what you need from the person watching. A clear title and a short note beside the link make it easier to pick up later.</Paragraph>",+ "<Paragraph>When sharing, check that the recording is available to the right people in your organization.</Paragraph>",+ '<Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your workspace</Button>',+ "<Paragraph>If the team workflow feels awkward anywhere, reply and let us know.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/marketing/teammate-welcome.ts b/emails/marketing/teammate-welcome.tsnew file mode 100644index 000000000..6da95b199--- /dev/null+++ b/emails/marketing/teammate-welcome.ts@@ -0,0 +1,19 @@+import type { EmailDefinition } from "../types";++export const teammateWelcome = {+ id: "teammate-welcome",+ key: "welcome",+ purpose:+ "Help an invited teammate find their workspace without promoting upgrades.",+ subject: "Getting started with your team in Cap",+ previewText: "Find your workspace and make your first handoff easier.",+ variables: ["firstName"],+ body: [+ "<Paragraph>Hi {contact.firstName},</Paragraph>",+ "<Paragraph>Welcome to your team in Cap.</Paragraph>",+ "<Paragraph>Open your dashboard and make sure the right organization is selected. That is where you will find the recordings your team shares with you.</Paragraph>",+ "<Paragraph>If something is missing, check with the person who invited you. They can confirm your workspace and access.</Paragraph>",+ '<Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your workspace</Button>',+ "<Paragraph>You can also reply here if you need help getting set up.</Paragraph>",+ ].join(""),+} satisfies EmailDefinition;diff --git a/emails/resources.json b/emails/resources.jsonnew file mode 100644index 000000000..4369903cd--- /dev/null+++ b/emails/resources.json@@ -0,0 +1,43 @@+{+ "version": "cap-lifecycle-v1",+ "teamName": "Cap Software, Inc.",+ "resources": {+ "theme": "cmtvpigqa01cy0jzmygof5f31",+ "Cap lifecycle header v1": "cmtvpigup01e80j0xjmwxqzxu",+ "Cap lifecycle signature v1": "cmtvpih0q01da0j20hgcd7ygv",+ "free": "cmtvpih6201fp0jznodf8fpwz",+ "customer": "cmtvpilm601f40jzwx3474cko",+ "teammate": "cmtvpm0ag01it0j37w02o6wav",+ "former": "cmtvpm8zm01ii0j01cz7d15qr",+ "segment:customer-update": "cmtvpmfc201jw0j1b50wngv06",+ "customer-update": "cmtvpmfxc01ls0j0nnlffombv",+ "segment:free-update": "cmtvpmit001kb0j1v86w1bx2w",+ "free-update": "cmtvpmjej01kr0j18cxoz2n0y",+ "mailingList": "cmtvqgqjj027l0j10fbgb2uvy"+ },+ "operations": {+ "free:guard": "n3",+ "free:welcome:email": "n4",+ "free:record:timer": "n5",+ "free:record:branch": "n6",+ "free:record:email": "n9",+ "free:share:timer": "n10",+ "free:share:branch": "n11",+ "free:share:email": "n14",+ "free:plans:timer": "n15",+ "free:plans:email": "n16",+ "customer:guard": "n3",+ "customer:welcome:email": "n4",+ "customer:workflow:timer": "n5",+ "customer:workflow:email": "n6",+ "customer:feedback:timer": "n7",+ "customer:feedback:email": "n8",+ "teammate:guard": "n3",+ "teammate:welcome:email": "n4",+ "teammate:handoff:timer": "n5",+ "teammate:handoff:email": "n6",+ "former:guard": "n3",+ "former:feedback:timer": "n4",+ "former:feedback:email": "n5"+ }+}diff --git a/emails/types.ts b/emails/types.tsnew file mode 100644index 000000000..dbbe693ec--- /dev/null+++ b/emails/types.ts@@ -0,0 +1,28 @@+import type { contactFallbacks } from "./brand";++export type Audience = "free" | "customer" | "teammate" | "former";+export type EmailDefinition = {+ id: string;+ key: string;+ purpose: string;+ subject: string;+ previewText: string;+ body: string;+ variables: (keyof typeof contactFallbacks)[];+};+export type Message = EmailDefinition & {+ delayDays: number;+ onlyIf?: { property: string; value: boolean };+};+export type Journey = {+ key: string;+ name: string;+ audience: Audience;+ promotional: boolean;+ messages: Message[];+};+export type Campaign = EmailDefinition & {+ name: string;+ audience: Audience;+ promotional: boolean;+};diff --git a/package.json b/package.jsonindex 64b8a6d64..840e4df14 100644--- a/package.json+++ b/package.json@@ -1,6 +1,9 @@{"type": "module","scripts": {+ "emails:catalog": "bun scripts/emails/manage.ts",+ "emails:check": "bun scripts/emails/manage.ts --check",+ "emails:check-loops": "bun scripts/loops/verify.ts","build": "dotenv -e .env -- turbo run build","build:web": "turbo run build:web","build:web:docker": "bun run --filter=@cap/web build:docker",diff --git a/scripts/emails/catalog.test.ts b/scripts/emails/catalog.test.tsnew file mode 100644index 000000000..9172a20a3--- /dev/null+++ b/scripts/emails/catalog.test.ts@@ -0,0 +1,107 @@+import { describe, expect, test } from "bun:test";+import { components, emailContent } from "../../emails/brand";+import { journeys } from "../../emails/flows";+import { freeWelcome } from "../../emails/marketing/free-welcome";+import {+ flowSteps,+ renderCatalog,+ validateCatalog,+ validateEmail,+} from "./catalog";+import { assertEmailContent, normalizeLmx } from "./content";++describe("email library", () => {+ test("every template and known application send source is registered", async () => {+ expect(await validateCatalog()).toEqual([]);+ });+ test("variables in subjects require a declared contract and fallback", () => {+ expect(+ validateEmail({ ...freeWelcome, subject: "Hello {contact.company}" }),+ ).toContain("Undeclared contact variable: contact.company");+ expect(+ validateEmail({ ...freeWelcome, subject: "Hello {data.firstName}" }),+ ).toContain("Undeclared contact variable: data.firstName");+ });+ test("per-email branding overrides and template references are rejected", () => {+ expect(+ validateEmail({+ ...freeWelcome,+ body: `${freeWelcome.body}<Style themeId="other" />`,+ }),+ ).toContain(+ "Use shared branding; do not embed Style or Component in email bodies",+ );+ expect(+ validateEmail({+ ...freeWelcome,+ body: freeWelcome.body.replace(+ "<Paragraph>",+ '<Paragraph textColor="#ff0000">',+ ),+ }),+ ).toContain("Put visual branding in emails/brand.ts");+ });+ test("relative delays become cumulative days, including skipped reminders", () => {+ expect(flowSteps(journeys[0]).map((step) => step.day)).toEqual([+ 0, 2, 5, 9,+ ]);+ const catalogue = renderCatalog();+ expect(catalogue).toContain("branch1 -->|No: skip| next1((Continue))");+ expect(catalogue).toContain('next1 --> wait2["Wait 3 days"]');+ });+});++describe("Loops content comparison", () => {+ const ids = { theme: "theme", header: "header", signature: "signature" };+ const content = emailContent(freeWelcome, ids);+ test("accepts editor formatting while retaining semantic whitespace", () => {+ expect(+ normalizeLmx('<Button align="left" href="https://cap.so">Go</Button>'),+ ).toBe(normalizeLmx('<Button href="https://cap.so">Go</Button>'));+ expect(+ normalizeLmx("<Paragraph><Strong>A</Strong> B</Paragraph>"),+ ).not.toBe(normalizeLmx("<Paragraph><Strong>A</Strong>B</Paragraph>"));+ const expanded = content.lmx+ .replace(+ '<Component componentId="header" />',+ `<Component componentId="header">\n${components[0].lmx}\n</Component>`,+ )+ .replace(+ '<Component componentId="signature" />',+ `<Component componentId="signature">\n${components[1].lmx}\n</Component>`,+ );+ expect(() =>+ assertEmailContent({ ...content, lmx: expanded }, freeWelcome, ids),+ ).not.toThrow();+ });+ test("detects added content, changed links, styling and component overrides", () => {+ for (const lmx of [+ `${content.lmx}<Paragraph>Unexpected promotion</Paragraph>`,+ content.lmx.replace("https://cap.so/download", "https://example.com"),+ content.lmx.replace("<Paragraph>", '<Paragraph textColor="#ff0000">'),+ content.lmx.replace(+ '<Component componentId="header" />',+ '<Component componentId="header"><Paragraph>Changed header</Paragraph></Component>',+ ),+ ])+ expect(() =>+ assertEmailContent({ ...content, lmx }, freeWelcome, ids),+ ).toThrow();+ });+ test("detects changed sender metadata and fallbacks", () => {+ expect(() =>+ assertEmailContent(+ { ...content, fromName: "Another sender" },+ freeWelcome,+ ids,+ ),+ ).toThrow();+ expect(() =>+ assertEmailContent(+ { ...content, contactPropertiesFallbacks: {} },+ freeWelcome,+ ids,+ ),+ ).toThrow();+ });+});diff --git a/scripts/emails/catalog.ts b/scripts/emails/catalog.tsnew file mode 100644index 000000000..569b7af47--- /dev/null+++ b/scripts/emails/catalog.ts@@ -0,0 +1,325 @@+import { readdir, readFile } from "node:fs/promises";+import { fileURLToPath } from "node:url";+import { applicationEmails } from "../../emails/application";+import { audienceFilter, contactProperties } from "../../emails/audiences";+import {+ components,+ contactFallbacks,+ sender,+ theme,+} from "../../emails/brand";+import { campaignTemplates } from "../../emails/campaigns";+import { customerCopy } from "../../emails/customer-copy";+import { journeys } from "../../emails/flows";+import resources from "../../emails/resources.json";+import type { EmailDefinition, Journey } from "../../emails/types";++export const root = new URL("../../", import.meta.url);+export const marketingEmails = [+ ...journeys.flatMap((journey) => journey.messages),+ ...campaignTemplates,+];++export const validateEmail = (email: EmailDefinition) => {+ const errors: string[] = [];+ if (!/^[a-z][a-z0-9-]+$/.test(email.id)) errors.push("Invalid email ID");+ for (const field of ["purpose", "subject", "previewText", "body"] as const) {+ if (!email[field].trim()) errors.push(`Missing ${field}`);+ }+ if (/<(?:Style|Component)\b/.test(email.body))+ errors.push(+ "Use shared branding; do not embed Style or Component in email bodies",+ );+ if (+ /\b(?:bgColor|textColor|fontSize|fontFamily|borderRadius)\s*=/.test(+ email.body,+ )+ )+ errors.push("Put visual branding in emails/brand.ts");+ const content = `${email.subject}\n${email.previewText}\n${email.body}`;+ const variables = [...content.matchAll(/\{([^{}]+)\}/g)].map(+ (match) => match[1],+ );+ const declared = new Set<string>(email.variables);+ for (const variable of variables) {+ const key = variable.replace(/^contact\./, "");+ if (!variable.startsWith("contact.") || !declared.has(key))+ errors.push(`Undeclared contact variable: ${variable}`);+ if (!Object.hasOwn(contactFallbacks, key))+ errors.push(`Missing fallback: ${key}`);+ }+ for (const key of declared) {+ if (!variables.includes(`contact.${key}`))+ errors.push(`Unused declared variable: ${key}`);+ }+ if (new TextEncoder().encode(email.body).length > 95_000)+ errors.push(+ "Email body leaves insufficient space for branding under the 100 KB LMX limit",+ );+ for (const match of email.body.matchAll(/<(?:Button|Link)\b([^>]*)>/g)) {+ const href = /\bhref="([^"]+)"/.exec(match[1])?.[1];+ if (!href || !/^(https:\/\/|mailto:)/.test(href))+ errors.push("Buttons and links need an https or mailto destination");+ }+ return errors;+};++export const flowSteps = (journey: Journey) => {+ let day = 0;+ return journey.messages.map((message) => {+ day += message.delayDays;+ return { ...message, day };+ });+};+const workflowFilter = (journey: Journey) => ({+ ...audienceFilter(journey.audience, journey.promotional),+ conditions: [+ ...audienceFilter(journey.audience, journey.promotional).conditions,+ { type: "property", key: "capLifecycleEnabled", operator: "isTrue" },+ { type: "property", key: "capOnboardingEligible", operator: "isTrue" },+ ],+});++export const validateCatalog = async () => {+ const errors = marketingEmails.flatMap((email) =>+ validateEmail(email).map((error) => `${email.id}: ${error}`),+ );+ const allIds = [...marketingEmails, ...applicationEmails].map(+ (email) => email.id,+ );+ if (new Set(allIds).size !== allIds.length)+ errors.push("Duplicate email IDs");+ for (const journey of journeys) {+ if (!journey.messages.length) errors.push(`Empty journey: ${journey.key}`);+ const keys = journey.messages.map((message) => message.key);+ if (new Set(keys).size !== keys.length)+ errors.push(`Duplicate steps: ${journey.key}`);+ if (journey.audience === "teammate" && journey.promotional)+ errors.push("Teammates cannot receive promotional journeys");+ for (const message of journey.messages) {+ if (!Number.isInteger(message.delayDays) || message.delayDays < 0)+ errors.push(`Invalid delay: ${message.id}`);+ if (+ message.onlyIf &&+ contactProperties[+ message.onlyIf.property as keyof typeof contactProperties+ ] !== "boolean"+ )+ errors.push(`Unknown boolean milestone: ${message.onlyIf.property}`);+ }+ }+ const files = (await readdir(new URL("emails/marketing/", root))).filter(+ (file) => file.endsWith(".ts"),+ );+ const expected = marketingEmails.map((email) => `${email.id}.ts`);+ for (const file of new Set([...files, ...expected])) {+ if (!files.includes(file) || !expected.includes(file))+ errors.push(`Unregistered or missing email: ${file}`);+ }+ const templateFiles = (+ await readdir(new URL("packages/database/emails/", root))+ ).filter((file) => file.endsWith(".tsx"));+ const registeredTemplates = applicationEmails.map(+ (email) => `${email.template}.tsx`,+ );+ for (const file of new Set([...templateFiles, ...registeredTemplates])) {+ if (!templateFiles.includes(file) || !registeredTemplates.includes(file))+ errors.push(`Unregistered or missing application template: ${file}`);+ }+ const sources = new Set(applicationEmails.flatMap((email) => email.sources));+ for (const source of sources) {+ try {+ await readFile(new URL(source, root), "utf8");+ } catch {+ errors.push(`Missing application source: ${source}`);+ }+ }+ for (const folder of [+ "apps/web/actions",+ "apps/web/app",+ "apps/web/lib",+ "packages/database/auth",+ ]) {+ for await (const file of new Bun.Glob("**/*.{ts,tsx}").scan(+ fileURLToPath(new URL(`${folder}/`, root)),+ )) {+ const source = `${folder}/${file}`;+ const text = await readFile(new URL(source, root), "utf8");+ if (/\bsendEmail\s*\(/.test(text) && !sources.has(source))+ errors.push(`Unregistered application send source: ${source}`);+ }+ }+ return errors;+};++const cell = (text: string) =>+ text.replaceAll("|", "\\|").replaceAll("\n", " ");+const sourceLink = (source: string, label = source) =>+ `[${label}](../${source.replaceAll("[", "%5B").replaceAll("]", "%5D")})`;+const sourceFor = (email: EmailDefinition) => `emails/marketing/${email.id}.ts`;+const resourceIds: Record<string, string> = resources.resources;+const flowUrl = (key: string) =>+ `https://app.loops.so/workflows/${resourceIds[key]}`;++export const renderCatalog = () => {+ const lines = [+ "# Cap email catalogue",+ "",+ "Generated from the email library with `bun run emails:catalog`. Edit the source files, then regenerate. [Editing guide](README.md).",+ "",+ "## Lifecycle flows",+ "",+ "These are the locally configured draft journeys. This document is not a live status check. Imports remain held; production enrollment is not deployed. Run `bun run emails:check-loops` to verify the actual Loops drafts.",+ "",+ "| Flow | Audience | Schedule after entry | Emails |",+ "| --- | --- | --- | --- |",+ ...journeys.map(+ (journey) =>+ `| [${cell(journey.name.replace("Cap | ", ""))}](${flowUrl(journey.key)}) | ${journey.audience} | ${flowSteps(+ journey,+ )+ .map((message) => `Day ${message.day}`)+ .join(", ")} | ${journey.messages.length} |`,+ ),+ "",+ "All journeys require global subscription, positive Cap consent, the exact audience, lifecycle enabled and onboarding eligible. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility. Customer and teammate flows still require marketing consent.",+ "",+ "Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).",+ "",+ ];+ for (const journey of journeys) {+ lines.push(+ `### ${journey.name.replace("Cap | ", "")}`,+ "",+ `Entry: capLifecycleStage changes into ${journey.key}. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.`,+ "",+ `Downstream conditions: ${workflowFilter(journey)+ .conditions.map(+ (condition) =>+ `${condition.key} ${condition.operator}${"value" in condition ? ` ${condition.value}` : ""}`,+ )+ .join("; ")}.`,+ "",+ "```mermaid",+ "flowchart TD",+ ` entry["Stage becomes ${journey.key}"] --> guard["Consent and audience guards"]`,+ );+ let previous = "guard";+ for (const [index, message] of flowSteps(journey).entries()) {+ if (message.delayDays) {+ lines.push(+ ` ${previous} --> wait${index}["Wait ${message.delayDays} days"]`,+ );+ previous = `wait${index}`;+ }+ if (message.onlyIf) {+ lines.push(+ ` ${previous} --> branch${index}{"${message.onlyIf.property} is ${message.onlyIf.value}?"}`,+ ` branch${index} -->|Yes| email${index}["Day ${message.day}: ${message.key}"]`,+ ` branch${index} -->|No: skip| next${index}((Continue))`,+ ` email${index} --> next${index}`,+ );+ previous = `next${index}`;+ } else {+ lines.push(+ ` ${previous} --> email${index}["Day ${message.day}: ${message.key}"]`,+ );+ previous = `email${index}`;+ }+ }+ lines.push(+ ` ${previous} --> exit["End"]`,+ "```",+ "",+ "| Day | Subject and source | Send condition |",+ "| --- | --- | --- |",+ ...flowSteps(journey).map(+ (message) =>+ `| ${message.day} | ${sourceLink(sourceFor(message), cell(message.subject))} | ${message.onlyIf ? `\`${message.onlyIf.property}=${message.onlyIf.value}\`` : "Journey guards"} |`,+ ),+ "",+ );+ }+ lines.push(+ "## Campaign templates",+ "",+ "Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, positive consent and their exact audience. The free template also requires promotional eligibility and excludes teammates.",+ "",+ "| Campaign | Audience | Subject and source | Loops ID |",+ "| --- | --- | --- | --- |",+ ...campaignTemplates.map(+ (email) =>+ `| ${cell(email.name.replace("Cap | ", ""))} | ${email.audience} | ${sourceLink(sourceFor(email), cell(email.subject))} | \`${resourceIds[email.key]}\` |`,+ ),+ "",+ "## Branding and personalization",+ "",+ `Shared theme, header, signature, sender and fallbacks: ${sourceLink("emails/brand.ts")}.`,+ "",+ `Sender: ${sender.fromName}; local part \`${sender.fromEmail}\` on the Loops sending domain. Reply-to: ${sender.replyToEmail}. Theme: ${theme.name}.`,+ "",+ `Shared components: ${components.map((component) => component.name).join("; ")}.`,+ "",+ "Customer welcome variations come from [customer-copy.ts](customer-copy.ts); eligibility is resolved from account and license state in the profile sync.",+ "",+ "| Plan | Welcome variation |",+ "| --- | --- |",+ ...Object.values(customerCopy).map(+ (copy) => `| ${copy.plan} | ${cell(copy.welcome)} |`,+ ),+ "",+ "## Marketing email copy",+ "",+ "The excerpts below show content, not an email-client render. Branding and required Loops footer content are composed separately.",+ "",+ );+ for (const email of marketingEmails) {+ lines.push(+ `### ${email.id}`,+ "",+ email.purpose,+ "",+ `**Subject:** ${email.subject}`,+ "",+ `**Preview:** ${email.previewText}`,+ "",+ `**Variables:** ${email.variables.map((key) => `\`contact.${key}\` (fallback: ${contactFallbacks[key]})`).join("; ")}`,+ "",+ `**Edit:** ${sourceLink(sourceFor(email))}`,+ "",+ ...email.body+ .replace(/<\/(Paragraph|Button)>/g, "\n\n")+ .replace(/<Br\s*\/>/g, "\n")+ .replace(/<[^>]+>/g, "")+ .trim()+ .split("\n"),+ "",+ );+ }+ lines.push(+ "## Application emails",+ "",+ "These are repository send paths and retained templates, not confirmation of production delivery. They continue through Resend and keep their existing React Email layouts. Loops audience filters do not control them. Shared marketing branding does not automatically restyle these templates.",+ "",+ "| Email | Trigger | Recipients | Template |",+ "| --- | --- | --- | --- |",+ ...applicationEmails.map(+ (email) =>+ `| ${email.name} | ${cell(email.trigger)} | ${cell(email.recipients)} | ${sourceLink(`packages/database/emails/${email.template}.tsx`, email.template)} |`,+ ),+ "",+ );+ for (const email of applicationEmails) {+ lines.push(+ `### ${email.name}`,+ "",+ email.notes,+ "",+ `Send source: ${email.sources.length ? email.sources.map((source) => sourceLink(source)).join(", ") : "No current call site"}.`,+ "",+ );+ }+ return `${lines.join("\n").trim()}\n`;+};++export const catalogPath = fileURLToPath(new URL("emails/CATALOG.md", root));diff --git a/scripts/emails/content.ts b/scripts/emails/content.tsnew file mode 100644index 000000000..13b6653d1--- /dev/null+++ b/scripts/emails/content.ts@@ -0,0 +1,47 @@+import assert from "node:assert/strict";+import { type BrandIds, components, emailContent } from "../../emails/brand";++export const normalizeLmx = (lmx: string) =>+ lmx+ .trim()+ .replace(/>\s*\n\s*</g, "><")+ .replace(+ /<Strong><Link([^>]*)>([^<]*)<\/Link><\/Strong>/g,+ "<Link$1><Strong>$2</Strong></Link>",+ )+ .replace(+ /<(\w+)((?:\s+[\w]+="[^"]*")*)\s*(\/?)>/g,+ (_, tag: string, attributes: string, closing: string) => {+ const normalized = [...attributes.matchAll(/([\w]+)="([^"]*)"/g)]+ .filter(([, key, value]) => key !== "align" || value !== "left")+ .map(([, key, value]) => `${key}="${value}"`)+ .sort();+ return `<${tag}${normalized.length ? ` ${normalized.join(" ")}` : ""}${closing ? " /" : ""}>`;+ },+ );++export const assertEmailContent = (+ actual: Record<string, unknown>,+ message: { subject: string; previewText: string; body: string },+ ids: BrandIds,+) => {+ const expected = emailContent(message, ids);+ for (const [key, value] of Object.entries(expected)) {+ if (key !== "lmx")+ assert.deepEqual(actual[key], value, `Email ${key} differs`);+ }+ assert.equal(typeof actual.lmx, "string");+ let expanded = expected.lmx;+ for (const [index, id] of [ids.header, ids.signature].entries()) {+ expanded = expanded.replace(+ `<Component componentId="${id}" />`,+ `<Component componentId="${id}">${components[index].lmx}</Component>`,+ );+ }+ const normalized = normalizeLmx(actual.lmx as string);+ assert(+ normalized === normalizeLmx(expanded) ||+ normalized === normalizeLmx(expected.lmx),+ "Email LMX differs from local body, branding references or shared component content",+ );+};diff --git a/scripts/emails/manage.ts b/scripts/emails/manage.tsnew file mode 100644index 000000000..3ab377ad9--- /dev/null+++ b/scripts/emails/manage.ts@@ -0,0 +1,26 @@+import { readFile, writeFile } from "node:fs/promises";+import { parseArgs } from "node:util";+import {+ catalogPath,+ marketingEmails,+ renderCatalog,+ validateCatalog,+} from "./catalog";++const { values } = parseArgs({+ options: { check: { type: "boolean", default: false } },+});+const errors = await validateCatalog();+if (errors.length) throw new Error(errors.join("\n"));+const content = renderCatalog();+if (values.check) {+ const saved = await readFile(catalogPath, "utf8").catch(() => "");+ if (saved !== content)+ throw new Error("Email catalogue is stale. Run bun run emails:catalog.");+ console.log(+ `Email catalogue, ${marketingEmails.length} marketing messages, variables and application source inventory verified.`,+ );+} else {+ await writeFile(catalogPath, content);+ console.log(`Updated ${catalogPath}`);+}diff --git a/scripts/loops/README.md b/scripts/loops/README.mdindex 98799e2d5..6b445a9c4 100644--- a/scripts/loops/README.md+++ b/scripts/loops/README.md@@ -1,5 +1,7 @@# Cap lifecycle email migration+Marketing source and shared branding now live in [emails/](../../emails/README.md). Start with the [email catalogue and flow maps](../../emails/CATALOG.md); regenerate it with `bun run emails:catalog`. Run `bun run emails:check` for local checks and `bun run emails:check-loops` for read-only comparison with the registered Loops drafts.+This prepares Cap's Bento audience and replacement Loops journeys. Provisioning creates drafts only. Importing and syncing keep `capLifecycleEnabled=false`, `capOnboardingEligible=false`, and `capLifecycleStage=idle`. No script activates workflows, sends messages, or replays historical events.The September 2026 repository audit found no Bento SDK, environment variable, or send call to replace. Bento's marketing automations were configured outside this repository. Existing Resend authentication, invitation, billing, notification, support, and BAA emails remain in place.diff --git a/scripts/loops/profile.ts b/scripts/loops/profile.tsindex 2c4119a38..10e6f6adb 100644--- a/scripts/loops/profile.ts+++ b/scripts/loops/profile.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import { customerCopy } from "../../emails/customer-copy";export type Consent = "subscribed" | "unsubscribed" | "suppressed" | "unknown";export type CapUser = {@@ -131,20 +132,16 @@ export function classifyProfile(input: ProfileInput) {: independent && !historicalCustomer && !user?.stripeSubscriptionStatus? "free": "unknown";- const planName = directCustomer- ? "Cap Pro"- : activeLicenses.some((license) => license.kind === "selfhosted")- ? "Cap Self-hosted"- : activeLicenses.length- ? "Cap Desktop"- : "Cap";- const welcome = directCustomer- ? "Your Cap Pro plan includes cloud sharing and collaboration, plus the desktop commercial license. Open your dashboard to find your organization and manage your setup."- : activeLicenses.some((license) => license.kind === "selfhosted")- ? "Your self-hosted license supports your own Cap deployment. Use the setup details supplied with your purchase, and reply if you need help."- : activeLicenses.length- ? "Your desktop license covers commercial use of Cap's recorder and editor. Activate it in the desktop app using the license details from your purchase email."- : "If you need help with your Cap account or access, reply to this email.";+ const copy =+ customerCopy[+ directCustomer+ ? "pro"+ : activeLicenses.some((license) => license.kind === "selfhosted")+ ? "selfhosted"+ : activeLicenses.length+ ? "desktop"+ : "other"+ ];return {email: normalizeEmail(source.email),userId: user?.id ?? `bento:${emailHash(source.email)}`,@@ -163,8 +160,8 @@ export function classifyProfile(input: ProfileInput) {capConsent: consent,capTeammate: teammate,capCustomer: customer,- capPlanName: planName,- capCustomerWelcome: welcome,+ capPlanName: copy.plan,+ capCustomerWelcome: copy.welcome,capPromotionalEligible:consent === "subscribed" &&!teammate &&diff --git a/scripts/loops/program.ts b/scripts/loops/program.tsindex c790a266c..014fee51c 100644--- a/scripts/loops/program.ts+++ b/scripts/loops/program.ts@@ -1,232 +1,10 @@-export const programVersion = "cap-lifecycle-v1";--export const contactProperties = {- capAudience: "string",- capOrigin: "string",- capConsent: "string",- capTeammate: "boolean",- capCustomer: "boolean",- capPlanName: "string",- capCustomerWelcome: "string",- capPromotionalEligible: "boolean",- capOnboardingEligible: "boolean",- capLifecycleEnabled: "boolean",- capLifecycleStage: "string",- capHasVideo: "boolean",- capHasSharedVideo: "boolean",- capVerifiedAt: "date",- capImportedAt: "date",- capSignupAt: "date",- capSourceTags: "string",- capSourceGroup: "string",-} as const;--export type Condition = {- type: "property";- key: string;- operator: "equals" | "isTrue" | "isFalse";- value?: string;-};--export const condition = (key: string, value: string | boolean): Condition =>- typeof value === "boolean"- ? { type: "property", key, operator: value ? "isTrue" : "isFalse" }- : { type: "property", key, operator: "equals", value };--export const audienceFilter = (audience: string, promotional: boolean) => ({- match: "all" as const,- conditions: [- condition("subscribed", true),- condition("capConsent", "subscribed"),- condition("capAudience", audience),- ...(promotional- ? [- condition("capTeammate", false),- condition("capPromotionalEligible", true),- ]- : []),- ],-});--export const theme = {- name: "Cap lifecycle v1",- styles: {- backgroundColor: "#ffffff",- bodyColor: "#ffffff",- bodyXPadding: 28,- bodyYPadding: 28,- bodyFontFamily: "Helvetica",- bodyFontCategory: "sans-serif",- textBaseColor: "#252525",- textBaseFontSize: 16,- textBaseLineHeight: 26,- textLinkColor: "#3159d6",- heading1Color: "#171717",- heading1FontSize: 26,- heading1LineHeight: 34,- heading2FontSize: 21,- buttonBodyColor: "#3159d6",- buttonTextColor: "#ffffff",- buttonTextFontSize: 16,- buttonBorderRadius: 8,- buttonBodyXPadding: 18,- buttonBodyYPadding: 12,- },-};--export const components = [- {- name: "Cap lifecycle header v1",- lmx: '<Paragraph fontSize="20" paddingBottom="24"><Strong><Link href="https://cap.so">Cap</Link></Strong></Paragraph>',- },- {- name: "Cap lifecycle signature v1",- lmx: '<Paragraph paddingTop="16">Richie<Br />Founder, Cap</Paragraph>',- },-];--type Message = {- key: string;- delayDays: number;- subject: string;- previewText: string;- body: string;- onlyIf?: { property: string; value: boolean };-};--type Journey = {- key: string;- name: string;- audience: string;- promotional: boolean;- messages: Message[];-};--export const journeys: Journey[] = [- {- key: "free",- name: "Cap | Independent free-user onboarding",- audience: "free",- promotional: true,- messages: [- {- key: "welcome",- delayDays: 0,- subject: "Your first Cap can be a small one",- previewText: "Pick one thing you would usually explain in a message.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>Thanks for trying Cap. A good first recording is something small: a quick explanation, a bug you spotted, or feedback on a piece of work.</Paragraph><Paragraph><Strong>Pick one thing you would normally type out, and record it instead.</Strong> Use Instant Mode for a shareable link, or Studio Mode when you want to edit before exporting.</Paragraph><Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Download Cap</Button><Paragraph>If you get stuck, reply to this email. We can help.</Paragraph>',- },- {- key: "record",- delayDays: 2,- subject: "Try a 30-second recording",- previewText: "A simple way to get comfortable with Cap.",- onlyIf: { property: "capHasVideo", value: false },- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>Here is an easy way to try Cap: open something you are working on and explain one small part of it out loud.</Paragraph><Paragraph>Choose your screen or a single window, check your microphone, and record for about 30 seconds. No script needed.</Paragraph><Paragraph>If you prefer to keep the recording on your device, use Studio Mode and export it locally.</Paragraph><Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Open the downloads page</Button><Paragraph>Already recording locally? You are all set. Local recordings do not necessarily appear in your cloud library.</Paragraph>',- },- {- key: "share",- delayDays: 3,- subject: "Give your next Cap a little context",- previewText: "Help the person watching know what to look for.",- onlyIf: { property: "capHasSharedVideo", value: false },- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>A recording works best when the person watching knows why you sent it.</Paragraph><Paragraph>Give your Cap a clear title, then send the link with one sentence about what you need: feedback, a decision, or just a quick look.</Paragraph><Paragraph>For a bug report, show what you expected and what happened. For feedback, point to the specific part you want to discuss.</Paragraph><Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your library</Button>',- },- {- key: "plans",- delayDays: 4,- subject: "Choose the Cap setup that fits your work",- previewText: "A desktop license and Cap Pro solve different needs.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>If the free version covers what you need, keep using it.</Paragraph><Paragraph>If you use Cap for work, a <Strong>Desktop License</Strong> covers commercial use of the desktop recorder and editor. <Strong>Cap Pro</Strong> adds the cloud sharing and collaboration features, and includes the desktop commercial license.</Paragraph><Paragraph>The plans page has the current features and prices, so you can choose based on how you actually use Cap.</Paragraph><Button href="https://cap.so/pricing" align="left" paddingTop="16" paddingBottom="16">Compare Cap plans</Button><Paragraph>Unsure which one fits? Reply with how you use Cap and we will point you in the right direction.</Paragraph>',- },- ],- },- {- key: "customer",- name: "Cap | Customer onboarding",- audience: "customer",- promotional: false,- messages: [- {- key: "welcome",- delayDays: 0,- subject: "Thanks for choosing {contact.capPlanName}",- previewText: "A few useful things to do first.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>Thank you for supporting Cap.</Paragraph><Paragraph>{contact.capCustomerWelcome}</Paragraph><Paragraph>Start with one recording you need to make this week. A walkthrough, a customer explanation, or feedback for a colleague is plenty.</Paragraph><Button href="https://cap.so/download" align="left" paddingTop="16" paddingBottom="16">Get Cap</Button><Paragraph>If anything about your setup or access looks wrong, reply and we will help you sort it out.</Paragraph>',- },- {- key: "workflow",- delayDays: 3,- subject: "One explanation you can reuse",- previewText: "Turn a recurring question into a short recording.",- body: "<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>One of the most useful things to record is an answer you keep giving.</Paragraph><Paragraph>Pick a recurring question, record a short walkthrough, and give it a title you will recognize later. Trim the beginning and end if you need to, then export or share it in the way that suits your work.</Paragraph><Paragraph>The next time the question comes up, you already have the answer ready.</Paragraph><Paragraph>If you have a workflow you would like Cap to make easier, reply and tell us about it.</Paragraph>",- },- {- key: "feedback",- delayDays: 4,- subject: "How is Cap working for you?",- previewText: "Tell us what is useful and what gets in the way.",- body: "<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>How has Cap been working for you?</Paragraph><Paragraph>I would love to know what you have been using it for, and whether anything has been confusing or frustrating.</Paragraph><Paragraph>Just reply to this email. Specific examples help us decide what to improve next.</Paragraph><Paragraph>Thanks again for supporting what we are building.</Paragraph>",- },- ],- },- {- key: "teammate",- name: "Cap | Teammate onboarding",- audience: "teammate",- promotional: false,- messages: [- {- key: "welcome",- delayDays: 0,- subject: "Getting started with your team in Cap",- previewText: "Find your workspace and make your first handoff easier.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>Welcome to your team in Cap.</Paragraph><Paragraph>Open your dashboard and make sure the right organization is selected. That is where you will find the recordings your team shares with you.</Paragraph><Paragraph>If something is missing, check with the person who invited you. They can confirm your workspace and access.</Paragraph><Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your workspace</Button><Paragraph>You can also reply here if you need help getting set up.</Paragraph>',- },- {- key: "handoff",- delayDays: 3,- subject: "Make your next handoff easier",- previewText:- "A short recording can give your teammate the context they need.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>For your next handoff, try recording the bit that is difficult to explain in writing.</Paragraph><Paragraph>Show the work, explain what changed, and say what you need from the person watching. A clear title and a short note beside the link make it easier to pick up later.</Paragraph><Paragraph>When sharing, check that the recording is available to the right people in your organization.</Paragraph><Button href="https://cap.so/dashboard" align="left" paddingTop="16" paddingBottom="16">Open your workspace</Button><Paragraph>If the team workflow feels awkward anywhere, reply and let us know.</Paragraph>',- },- ],- },- {- key: "former",- name: "Cap | Former customer follow-up",- audience: "former",- promotional: true,- messages: [- {- key: "feedback",- delayDays: 14,- subject: "What could we have done better?",- previewText: "A quick question about your experience with Cap.",- body: "<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>Now that your paid access has ended, I wanted to ask what could have made Cap more useful for you.</Paragraph><Paragraph>Was there something missing, something that did not work properly, or did you just not need it anymore?</Paragraph><Paragraph>Reply if you have a moment. Honest feedback helps us make better decisions.</Paragraph><Paragraph>Thanks for giving Cap a try.</Paragraph>",- },- ],- },-];--export const campaignTemplates = [- {- key: "customer-update",- name: "Cap | Customer product update template",- audience: "customer",- promotional: false,- subject: "What is new in Cap",- previewText: "See the latest improvements in the changelog.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>We have been working on improvements to Cap. You can find the latest changes and fixes in the changelog.</Paragraph><Button href="https://cap.so/changelog" align="left" paddingTop="16" paddingBottom="16">Read the changelog</Button><Paragraph>If something would make Cap more useful for you, reply and tell us.</Paragraph>',- },- {- key: "free-update",- name: "Cap | Noncustomer product update template",- audience: "free",- promotional: true,- subject: "Take another look at Cap",- previewText: "Catch up on the latest changes.",- body: '<Paragraph>Hi {contact.firstName},</Paragraph><Paragraph>If you have not tried Cap recently, the changelog is a good place to see what has changed.</Paragraph><Paragraph>Download the latest version when you have a recording to make. You can start small and see whether it fits how you work.</Paragraph><Button href="https://cap.so/changelog" align="left" paddingTop="16" paddingBottom="16">See what is new</Button>',- },-];+export {+ audienceFilter,+ campaignTemplates,+ components,+ condition,+ contactProperties,+ journeys,+ programVersion,+ theme,+} from "../../emails";diff --git a/scripts/loops/provision.ts b/scripts/loops/provision.tsindex 10d8ad5d8..7554ca56a 100644--- a/scripts/loops/provision.ts+++ b/scripts/loops/provision.ts@@ -1,6 +1,9 @@+import assert from "node:assert/strict";import { createHash } from "node:crypto";import { readFile, writeFile } from "node:fs/promises";import { parseArgs } from "node:util";+import { emailContent } from "../../emails/brand";+import { normalizeLmx } from "../emails/content";import { LoopsApi, LoopsApiError } from "./api";import {audienceFilter,@@ -159,6 +162,31 @@ try {key: string,) => {const existing = named(rows, definition.name);+ if (existing && path === "themes") {+ const current = await api.request<{ styles: Record<string, unknown> }>(+ `${path}/${existing.id}`,+ );+ for (const [style, value] of Object.entries(theme.styles))+ assert.deepEqual(+ current.styles[style],+ value,+ "Shared theme changed; create a new branding version before updating drafts",+ );+ }+ if (existing && path === "components") {+ const current = await api.request<{ lmx: string }>(+ `${path}/${existing.id}`,+ );+ const expected = components.find(+ (component) => component.name === definition.name,+ );+ assert(expected);+ assert.equal(+ normalizeLmx(current.lmx),+ normalizeLmx(expected.lmx),+ "Shared component changed; create a new branding version before updating drafts",+ );+ }const resource =existing ?? (await api.request<Named>(path, "POST", definition));receipt.resources[key] = resource.id;@@ -172,28 +200,15 @@ try {await ensure("components", sharedComponents, component, component.name),);}- const render = (body: string) =>- `<Style themeId="${themeId}" />\n<Component componentId="${componentIds[0]}" />\n${body}\n<Component componentId="${componentIds[1]}" />`;-const editEmail = async (id: string,message: { subject: string; previewText: string; body: string },) => {- const definition = {- subject: message.subject,- previewText: message.previewText,- fromName: "Richie from Cap",- fromEmail: "richie",- replyToEmail: "[email protected]",- emailFormat: "styled",- lmx: render(message.body),- contactPropertiesFallbacks: {- firstName: "there",- capPlanName: "Cap",- capCustomerWelcome:- "Your paid access is ready. If you need help getting started, reply to this email.",- },- };+ const definition = emailContent(message, {+ theme: themeId,+ header: componentIds[0],+ signature: componentIds[1],+ });const current = await api.request<Email>(`email-messages/${id}`);if (receipt.definitions[id] !== hash(definition) ||diff --git a/scripts/loops/resources.json b/scripts/loops/resources.jsondeleted file mode 100644index baeeb6bdd..000000000--- a/scripts/loops/resources.json+++ /dev/null@@ -1,15 +0,0 @@-{- "version": "cap-lifecycle-v1",- "teamName": "Cap Software, Inc.",- "mailingListId": "cmtvqgqjj027l0j10fbgb2uvy",- "workflows": {- "free": "cmtvpih6201fp0jznodf8fpwz",- "customer": "cmtvpilm601f40jzwx3474cko",- "teammate": "cmtvpm0ag01it0j37w02o6wav",- "former": "cmtvpm8zm01ii0j01cz7d15qr"- },- "campaigns": {- "customer-update": "cmtvpmfxc01ls0j0nnlffombv",- "free-update": "cmtvpmjej01kr0j18cxoz2n0y"- }-}diff --git a/scripts/loops/verify.ts b/scripts/loops/verify.tsindex f2fe2c5d5..9bb266e1f 100644--- a/scripts/loops/verify.ts+++ b/scripts/loops/verify.ts@@ -1,6 +1,10 @@import assert from "node:assert/strict";import { readFile } from "node:fs/promises";+import { fileURLToPath } from "node:url";import { parseArgs } from "node:util";+import { components, theme } from "../../emails/brand";+import registry from "../../emails/resources.json";+import { assertEmailContent, normalizeLmx } from "../emails/content";import { LoopsApi } from "./api";import {audienceFilter,@@ -28,7 +32,7 @@ type Workflow = {rootNodeId: string;nodes: Record<string, Node>;};-type Email = {+type Email = Record<string, unknown> & {subject: string;previewText: string;fromEmail: string;@@ -39,9 +43,14 @@ type Email = {const { values } = parseArgs({options: {- state: { type: "string" },- team: { type: "string" },- "mailing-list": { type: "string" },+ state: {+ type: "string",+ default: fileURLToPath(+ new URL("../../emails/resources.json", import.meta.url),+ ),+ },+ team: { type: "string", default: registry.teamName },+ "mailing-list": { type: "string", default: registry.resources.mailingList },},});assert(values.state && values.team && values["mailing-list"]);@@ -56,13 +65,37 @@ assert.equal(receipt.teamName, values.team);const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "");const identity = await api.request<{ teamName: string }>("api-key");assert.equal(identity.teamName, values.team);-const text = (lmx: string) =>- lmx- .replace(/<[^>]+>/g, " ")- .replace(/\s+/g, " ")- .trim();-const links = (lmx: string) =>- [...lmx.matchAll(/href="([^"]+)"/g)].map((match) => match[1]);+const brandIds = {+ theme: receipt.resources.theme,+ header: receipt.resources[components[0].name],+ signature: receipt.resources[components[1].name],+};+assert(+ brandIds.theme && brandIds.header && brandIds.signature,+ "Brand IDs missing from resources.json",+);+const remoteTheme = await api.request<{+ name: string;+ styles: Record<string, unknown>;+}>(`themes/${brandIds.theme}`);+assert.equal(remoteTheme.name, theme.name);+for (const [key, value] of Object.entries(theme.styles))+ assert.deepEqual(+ remoteTheme.styles[key],+ value,+ `Shared theme differs: ${key}`,+ );+for (const component of components) {+ const remote = await api.request<{ name: string; lmx: string }>(+ `components/${receipt.resources[component.name]}`,+ );+ assert.equal(remote.name, component.name);+ assert.equal(+ normalizeLmx(remote.lmx),+ normalizeLmx(component.lmx),+ `Shared component differs: ${component.name}`,+ );+}let emails = 0;const verifyEmail = async (id: string | undefined,@@ -70,17 +103,7 @@ const verifyEmail = async () => {assert(id);const email = await api.request<Email>(`email-messages/${id}`);- assert.equal(email.subject, expected.subject);- assert.equal(email.previewText, expected.previewText);- assert.equal(email.fromEmail, "richie");- assert.equal(email.replyToEmail, "[email protected]");- assert.equal(email.contactPropertiesFallbacks.firstName, "there");- assert(- text(email.lmx).includes(text(expected.body)),- `Email body changed: ${id}`,- );- for (const link of links(expected.body))- assert(links(email.lmx).includes(link));+ assertEmailContent(email, expected, brandIds);const guardian = await api.request<{errors: unknown[];warnings: unknown[];