Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: prepare Loops lifecycle drafts and held audience migration
Richie McIlroy081a337d5643
diff --git a/scripts/loops/README.md b/scripts/loops/README.mdnew file mode 100644index 000000000..98799e2d5--- /dev/null+++ b/scripts/loops/README.md@@ -0,0 +1,93 @@+# Cap lifecycle email migration++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.++## Audience rules++| Audience | Evidence | Draft journey |+| --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |+| Independent free user | Independent signup or a matching personal organization created at signup, with no paid entitlement or uncertain customer history | Welcome, recording help on day 2, sharing help on day 5, plan guidance on day 9 |+| Customer | Active/trialing/paid/past-due Cap Pro, a paid organization seat, or a currently valid desktop/self-hosted license | Plan-specific welcome, a reusable recording idea on day 3, feedback on day 7 |+| Teammate | Invitation, SSO, another owner's organization, third-party subscription, or a previously recorded teammate flag | Workspace setup, then handoff guidance on day 3; no promotional journey |+| Former customer | Canceled cloud subscription with no desktop/self-hosted license history | Feedback request after 14 days |+| Unknown | Missing identity/origin, stale customer tags, expired license evidence, or ambiguous entitlement | No journey or campaign audience |++Teammate evidence takes priority and is retained after membership changes. A future independently initiated purchase does not automatically erase that history. Customer classification uses Cap and the separate license database, not Bento's historical customer tag alone. A license's active flag is insufficient without a future renewal date.++Every journey requires a global subscription, positive consent, the correct audience, and both enrollment flags. Its audience filter applies downstream. Free/former promotional journeys also require `capTeammate=false` and `capPromotionalEligible=true`. Recording/sharing branches skip the corresponding reminder when the known cloud milestone is complete; local-only recordings cannot be observed by this sync.++All imported contacts remain held, including recent signups. Historical contacts must never be enrolled by replaying a contact-created event or bulk changing their lifecycle stage.++## Consent and private data++`prepare.ts` excludes source opt-outs, suppression flags, bounces, complaints, and conflicting negative subscription fields from the positive import. It also produces a normalized-email SHA-256 registry for every source row. Retain that registry even when excluded addresses are not created in Loops. Hashes are sensitive matching identifiers, not anonymous data.++Reconcile opt-outs already present in the destination by setting those existing records to unsubscribed. Do not import excluded addresses as new subscribed contacts. Loops-native global and mailing-list opt-outs must survive migration and later syncs. The normal sync never writes `subscribed=true` to an existing contact and never replaces mailing-list preferences. Missing imported contacts are not recreated.++Keep exports, prepared contacts, CSVs, registry files, receipts, database connection strings, and API keys outside Git, in a private directory. Do not expose license keys; the classifier only needs email, entitlement kind, active status, and renewal date.++## Commands++Run from the repository root with Bun 1.4. Supply `LOOPS_API_KEY` through the process environment. Every API command checks the exact expected team name. Cap's migration account is **Cap Software, Inc.**; a separate Loops account named **Cap** must not be used.++```sh+bun scripts/loops/provision.ts --team 'Cap Software, Inc.' --dry-run+bun scripts/loops/provision.ts --team 'Cap Software, Inc.' --state "$LOOPS_PRIVATE_DIR/provision-state.json" --mailing-list "$LOOPS_MAILING_LIST_ID" --apply+bun scripts/loops/verify.ts --team 'Cap Software, Inc.' --state "$LOOPS_PRIVATE_DIR/provision-state.json" --mailing-list "$LOOPS_MAILING_LIST_ID"+bun scripts/loops/prepare.ts --sources "$LOOPS_PRIVATE_DIR" --output "$LOOPS_PRIVATE_DIR/import"+bun scripts/loops/import.ts --team 'Cap Software, Inc.' --contacts "$LOOPS_PRIVATE_DIR/import/contacts.json" --receipt "$LOOPS_PRIVATE_DIR/import/receipt.jsonl" --mailing-list "$LOOPS_MAILING_LIST_ID"+```++Review the dry-run counts, then add `--apply` to import. Use the same receipt to resume after interruption; existing identities are checked and enriched without resubscribing. Invalid rows are recorded privately. Correct their input before using `--retry-invalid`. A network-interrupted create may have succeeded, so reconcile through the same importer rather than deleting/recreating contacts.++The source directory must contain arrays in `bento-contacts.json`, `cap-users.json`, `cap-memberships.json`, `license-licenses.json`, `cap-invites.json`, `cap-sso.json`, and `cap-videos.json`. Their shapes are defined in `profile.ts`, `prepare.ts`, and `sources.ts`. Preserve original source CSVs. Fresh source snapshots are required; preparation refuses files older than 24 hours.++The native Loops CSV importer can be used for the reviewed positive file. Check every column mapping, select the migration mailing list, and leave **Trigger workflows** off. Loops matches user ID before email; resolve destination identity conflicts first. Export the destination afterward and reconcile all intended addresses, opt-outs, audience fields, and enrollment holds. Native CSV imports and API receipts are separate records.++Provisioning uses revision checks and a private receipt to resume partially created resources. Run `verify.ts` after every provisioning pass: it independently reads the actual graph, downstream filters, branch reconnections, timing, message text/links, fallback, campaign segments, mailing lists, draft states, and Guardian results. Investigate verification failures before editing a managed draft manually or reusing its receipt.++## Repository rollout++The generated migration adds `users.marketingOrigin` and `marketing_contacts`. Apply the schema through the normal reviewed PlanetScale deployment process **before deploying code that selects the new column**. No production database migration is performed by preparation or provisioning.++New signup, invite acceptance, and SSO provisioning record origin without subscribing anyone. Existing invitation/membership/SSO evidence supplements this field for the historical import. The registry has no user foreign key so an opt-out can survive account deletion.++After the schema is deployed, dry-run the registry seed:++```sh+bun scripts/loops/seed.ts --registry "$LOOPS_PRIVATE_DIR/import/consent-registry.json" --contacts "$LOOPS_PRIVATE_DIR/import/contacts.json"+```++Applying requires `DATABASE_URL`, `LOOPS_SYNC_ENABLED=true`, and `--apply`. Registry merges retain existing opt-outs and teammate history. Initial denied records store their hash without a raw email; an already stored email is retained when a later opt-out must be propagated.++The held-contact sync additionally requires read-only `LOOPS_LICENSE_DATABASE_URL`:++```sh+bun scripts/loops/sync.ts --team 'Cap Software, Inc.' --mailing-list "$LOOPS_MAILING_LIST_ID" --limit 100+```++Review the dry run before adding `--apply`. Use a single runner and bounded batches. The sync refreshes entitlement/origin/milestone fields, preserves consent, compares profile fingerprints, rechecks remote consent at least daily when drained, and refuses a source snapshot older than ten minutes. Repeated runs drain pending changes. It remains a held-contact sync, not an enrollment service.++## Before any activation++Activation is deliberately outside this migration's approved scope. These gates remain necessary:++1. Review actual draft copy and audiences, resolve the sending-domain DMARC warning, and configure rotated credentials in the intended environment.+2. Deploy the reviewed schema/code, seed the complete suppression registry, and prove the held sync with real free, paid, licensed, invited, SSO, unsubscribed, deleted, and changed-email cases.+3. Implement and verify explicit new-consent capture, lifecycle enrollment for new eligible contacts, bounded retries, duplicate prevention, and an observed sync schedule. This branch does not infer marketing consent from account creation.+4. Add a freshness mechanism and monitoring before live sends. Downstream filters use the last synced fields; `capVerifiedAt` is evidence, not a native expiry guarantee. Prove purchase/invite/opt-out transitions remove contacts before later promotional steps. Do not enable the current held sync alongside active enrollment because it deliberately returns contacts to idle.+5. Reconcile a fresh Bento delta at cutover. Confirm no campaign/flow is queued to send twice, then disable old Bento marketing automations only as part of the approved cutover. Preserve source history and opt-outs before retiring Bento.++## Validation++```sh+bun test scripts/loops/profile.test.ts+bun run biome check scripts/loops packages/database/schema.ts packages/database/auth/drizzle-adapter.ts packages/database/auth/sso.ts apps/web/app/api/invite/accept/route.ts+bun run tsc -b packages/database+bun run --cwd apps/web next typegen+bun run tsc -b apps/web+```++Unit tests cover consent conflicts, conservative customer classification, teammate suppression, imported enrollment holds, identity preservation, and stable sync fingerprints. They do not prove production email delivery or a live cutover.diff --git a/scripts/loops/api.ts b/scripts/loops/api.tsnew file mode 100644index 000000000..240abab9e--- /dev/null+++ b/scripts/loops/api.ts@@ -0,0 +1,91 @@+export type Json =+ | null+ | boolean+ | number+ | string+ | Json[]+ | { [key: string]: Json };++export class LoopsApiError extends Error {+ constructor(+ public status: number,+ public path: string,+ public details: unknown,+ ) {+ super(`Loops ${status} at ${path}`);+ }+}++export class LoopsApi {+ private nextRequestAt = 0;++ constructor(+ private key: string,+ private intervalMs = 750,+ ) {+ if (!key) throw new Error("LOOPS_API_KEY is required");+ if (intervalMs < 125)+ throw new Error("Keep requests below the Loops team rate limit");+ }++ async request<T>(path: string, method = "GET", body?: unknown): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ const scheduledAt = Math.max(Date.now(), this.nextRequestAt);+ this.nextRequestAt = scheduledAt + this.intervalMs;+ await new Promise((resolve) =>+ setTimeout(resolve, Math.max(0, scheduledAt - Date.now())),+ );+ let response: Response;+ let result: unknown;+ try {+ response = await fetch(`https://app.loops.so/api/v1/${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${this.key}`,+ "Content-Type": "application/json",+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ signal: AbortSignal.timeout(30_000),+ });+ result = await response.json();+ } catch (error) {+ if (attempt >= 4 || (method !== "GET" && method !== "PUT")) throw error;+ this.nextRequestAt = Math.max(+ this.nextRequestAt,+ Date.now() + 1000 * 2 ** attempt,+ );+ continue;+ }+ if (response.ok) return result as T;+ const retryable =+ response.status === 429 ||+ (response.status >= 500 && (method === "GET" || method === "PUT"));+ if (!retryable || attempt >= 4) {+ throw new LoopsApiError(response.status, path, result);+ }+ const retryAfter = Number(response.headers.get("retry-after"));+ this.nextRequestAt = Math.max(+ this.nextRequestAt,+ Date.now() ++ Math.max(+ Number.isFinite(retryAfter) ? retryAfter * 1000 : 0,+ 1000 * 2 ** attempt,+ ),+ );+ }+ }++ async list<T>(path: string): Promise<T[]> {+ const rows: T[] = [];+ let cursor: string | null = null;+ do {+ const page: { data: T[]; pagination: { nextCursor: string | null } } =+ await this.request(+ `${path}?perPage=50${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`,+ );+ rows.push(...page.data);+ cursor = page.pagination.nextCursor;+ } while (cursor);+ return rows;+ }+}diff --git a/scripts/loops/import.ts b/scripts/loops/import.tsnew file mode 100644index 000000000..1e63cf18b--- /dev/null+++ b/scripts/loops/import.ts@@ -0,0 +1,182 @@+import { appendFile, chmod, readFile } from "node:fs/promises";+import { parseArgs } from "node:util";+import { LoopsApi, LoopsApiError } from "./api";+import { type ContactProfile, emailHash } from "./profile";+import { importContactUpdate, type RemoteContact } from "./sync-policy";++type Receipt = {+ hash: string;+ status: "created" | "existing" | "updated" | "invalid";+ id?: string;+ detail?: unknown;+};+const { values } = parseArgs({+ options: {+ contacts: { type: "string" },+ receipt: { type: "string" },+ team: { type: "string" },+ apply: { type: "boolean", default: false },+ limit: { type: "string" },+ "mailing-list": { type: "string" },+ "retry-invalid": { type: "boolean", default: false },+ },+});+if (!values.contacts || !values.receipt || !values.team)+ throw new Error("Pass --contacts, --receipt and --team");+const filename = values.receipt;+const profiles: ContactProfile[] = JSON.parse(+ await readFile(values.contacts, "utf8"),+);+const hashes = new Set<string>();+for (const profile of profiles) {+ const hash = emailHash(profile.email);+ if (+ hashes.has(hash) ||+ !profile.subscribed ||+ profile.capConsent !== "subscribed" ||+ profile.capLifecycleEnabled ||+ profile.capOnboardingEligible ||+ profile.capLifecycleStage !== "idle"+ )+ throw new Error(+ "Import must contain unique, positively subscribed, held contacts",+ );+ hashes.add(hash);+}+const prior: Receipt[] = [];+try {+ for (const line of (await readFile(filename, "utf8"))+ .split("\n")+ .filter(Boolean))+ prior.push(JSON.parse(line));+} catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))+ throw error;+}+const latest = new Map(prior.map((row) => [row.hash, row]));+const done = new Set(+ [...latest.values()]+ .filter(+ (row) =>+ row.status !== "existing" &&+ !(values["retry-invalid"] && row.status === "invalid"),+ )+ .map((row) => row.hash),+);+const limit = values.limit ? Number(values.limit) : profiles.length;+if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("Invalid limit");+const pending = profiles+ .filter((profile) => !done.has(emailHash(profile.email)))+ .slice(0, limit);+const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "", 150);+const identity = await api.request<{ success: boolean; teamName: string }>(+ "api-key",+);+if (!identity.success || identity.teamName !== values.team)+ throw new Error("Wrong Loops team");+const workflows = await api.list<{ id: string }>("workflows");+for (const row of workflows) {+ const workflow = await api.request<{ status: string }>(`workflows/${row.id}`);+ if (workflow.status !== "Draft")+ throw new Error("Contact import requires all workflows to remain drafts");+}+const lists = await api.request<{ id: string; name: string }[]>("lists");+const listId =+ values["mailing-list"] ??+ lists.find((list) => list.name === "Product updates and tips")?.id;+if (listId && !lists.some((list) => list.id === listId))+ throw new Error("Unknown mailing list");+console.log(+ JSON.stringify({+ team: identity.teamName,+ mode: values.apply ? "create missing contacts" : "dry run",+ total: profiles.length,+ alreadyProcessed: done.size,+ pending: pending.length,+ mailingListId: listId ?? null,+ }),+);+if (!values.apply) process.exit(0);+await appendFile(filename, "", { mode: 0o600 });+await chmod(filename, 0o600);+let next = 0;+let stopped = false;+let completed = 0;+const counts = { created: 0, existing: 0, updated: 0, invalid: 0 };+const worker = async () => {+ while (!stopped && next < pending.length) {+ const profile = pending[next++];+ if (!profile) return;+ const hash = emailHash(profile.email);+ let receipt: Receipt;+ try {+ const result = await api.request<{ success: boolean; id: string }>(+ "contacts/create",+ "POST",+ { ...profile, ...(listId ? { mailingLists: { [listId]: true } } : {}) },+ );+ if (!result.success || !result.id)+ throw new Error(+ "Unexpected create response; reconcile before retrying",+ );+ receipt = { hash, status: "created", id: result.id };+ } catch (error) {+ if (error instanceof LoopsApiError && error.status === 409) {+ const contacts = await api.request<RemoteContact[]>(+ `contacts/find?email=${encodeURIComponent(profile.email)}`,+ );+ const contact = contacts[0];+ if (contacts.length !== 1 || !contact) {+ stopped = true;+ throw new Error(+ "Resolve the existing contact identity before resuming",+ );+ }+ await api.request(+ "contacts/update",+ "PUT",+ importContactUpdate(profile, contact, listId),+ );+ receipt = { hash, status: "updated", id: contact.id };+ } else if (error instanceof LoopsApiError && error.status === 400)+ receipt = { hash, status: "invalid", detail: error.details };+ else {+ stopped = true;+ throw error;+ }+ }+ await appendFile(filename, `${JSON.stringify(receipt)}\n`);+ counts[receipt.status]++;+ completed++;+ if (completed % 250 === 0)+ console.log(+ JSON.stringify({ processed: done.size + completed, ...counts }),+ );+ }+};+const results = await Promise.allSettled(+ Array.from({ length: 8 }, async () => {+ try {+ await worker();+ } catch (error) {+ stopped = true;+ throw error;+ }+ }),+);+console.log(+ JSON.stringify({+ processed: done.size + completed,+ ...counts,+ remaining: profiles.length - done.size - completed,+ }),+);+for (const result of results)+ if (result.status === "rejected") {+ console.error(+ result.reason instanceof LoopsApiError+ ? `Import stopped with HTTP ${result.reason.status}; resume with the same receipt`+ : "Import stopped; reconcile the receipt before resuming",+ );+ process.exitCode = 1;+ }diff --git a/scripts/loops/prepare.ts b/scripts/loops/prepare.tsnew file mode 100644index 000000000..e86952156--- /dev/null+++ b/scripts/loops/prepare.ts@@ -0,0 +1,141 @@+import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";+import path from "node:path";+import { parseArgs } from "node:util";+import {+ type CapUser,+ classifyProfile,+ emailHash,+ type License,+ type Membership,+ normalizeEmail,+ type SourceContact,+} from "./profile";++const { values } = parseArgs({+ options: { sources: { type: "string" }, output: { type: "string" } },+});+if (!values.sources || !values.output)+ throw new Error("Pass private --sources and --output directories");+const sourceDirectory = values.sources;+const read = async <T>(name: string): Promise<T[]> => {+ const filename = path.join(sourceDirectory, `${name}.json`);+ if (Date.now() - (await stat(filename)).mtimeMs > 24 * 60 * 60_000)+ throw new Error(`Refresh stale source ${name}`);+ return JSON.parse(await readFile(filename, "utf8"));+};+const [source, users, members, licenses, invites, sso, videos] =+ await Promise.all([+ read<SourceContact>("bento-contacts"),+ read<CapUser>("cap-users"),+ read<Membership>("cap-memberships"),+ read<License>("license-licenses"),+ read<{ invitedEmail: string; status: string; expiresAt: string }>(+ "cap-invites",+ ),+ read<{ userId: string }>("cap-sso"),+ read<{ ownerId: string; total: number; hasPublicVideo: number }>(+ "cap-videos",+ ),+ ]);+const group = <T>(rows: T[], key: (row: T) => string) => {+ const result = new Map<string, T[]>();+ for (const row of rows) {+ const id = key(row);+ result.set(id, [...(result.get(id) ?? []), row]);+ }+ return result;+};+const byEmail = group(users, (user) => normalizeEmail(user.email));+const memberMap = group(members, (member) => member.userId);+const licenseMap = group(licenses, (license) => normalizeEmail(license.email));+const invited = new Set(+ invites.map((invite) => normalizeEmail(invite.invitedEmail)),+);+const ssoUsers = new Set(sso.map((account) => account.userId));+const videoMap = new Map(videos.map((video) => [video.ownerId, video]));+const seen = new Set<string>();+const now = new Date();+const profiles = source.map((contact) => {+ if (+ !["unsubscribed_at", "unsubscribed_reason", "flag"].every(+ (key) => typeof contact[key] === "string",+ )+ )+ throw new Error("Source is missing Bento subscription/suppression columns");+ const email = normalizeEmail(contact.email);+ if (!email || seen.has(email))+ throw new Error("Source contains an empty or duplicate normalized email");+ seen.add(email);+ const matchingUsers = byEmail.get(email) ?? [];+ if (matchingUsers.length > 1)+ throw new Error(+ "Multiple Cap identities match an email; resolve before importing",+ );+ const user = matchingUsers[0];+ const video = user ? videoMap.get(user.id) : undefined;+ return classifyProfile({+ source: contact,+ user,+ memberships: user ? (memberMap.get(user.id) ?? []) : [],+ licenses: licenseMap.get(email) ?? [],+ invited: invited.has(email),+ sso: user ? ssoUsers.has(user.id) : false,+ hasVideo: Boolean(video?.total),+ hasSharedVideo: Boolean(video?.hasPublicVideo),+ now,+ });+});+const positive = profiles.filter((profile) => profile.subscribed);+const registry = profiles.map((profile) => ({+ emailHash: emailHash(profile.email),+ consent: profile.capConsent,+ teammate: profile.capTeammate,+ userId: profile.userId.startsWith("bento:") ? null : profile.userId,+ source: "bento-migration",+ imported: true,+}));+await mkdir(values.output, { recursive: true, mode: 0o700 });+await chmod(values.output, 0o700);+const write = async (name: string, content: string) => {+ const filename = path.join(values.output ?? "", name);+ await writeFile(filename, content, { mode: 0o600 });+ await chmod(filename, 0o600);+};+await write("contacts.json", JSON.stringify(positive));+await write("consent-registry.json", JSON.stringify(registry));+const keys = Object.keys(+ positive[0] ?? {},+) as (keyof (typeof positive)[number])[];+const csvCell = (value: unknown) =>+ `"${String(value ?? "").replaceAll('"', '""')}"`;+await write(+ "contacts.csv",+ [+ keys.map(csvCell).join(","),+ ...positive.map((profile) =>+ keys.map((key) => csvCell(profile[key])).join(","),+ ),+ ].join("\r\n"),+);+const counts = (key: "capAudience" | "capConsent") =>+ profiles.reduce<Record<string, number>>((result, row) => {+ result[row[key]] = (result[row[key]] ?? 0) + 1;+ return result;+ }, {});+const summary = {+ preparedAt: now.toISOString(),+ source: profiles.length,+ import: positive.length,+ excluded: profiles.length - positive.length,+ consent: counts("capConsent"),+ audiences: counts("capAudience"),+ importAudiences: positive.reduce<Record<string, number>>((result, row) => {+ result[row.capAudience] = (result[row.capAudience] ?? 0) + 1;+ return result;+ }, {}),+ allImportsHeld: positive.every(+ (row) => !row.capLifecycleEnabled && row.capLifecycleStage === "idle",+ ),+};+await write("summary.json", JSON.stringify(summary, null, 2));+console.log(JSON.stringify(summary, null, 2));diff --git a/scripts/loops/profile.test.ts b/scripts/loops/profile.test.tsnew file mode 100644index 000000000..7001332c8--- /dev/null+++ b/scripts/loops/profile.test.ts@@ -0,0 +1,297 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import {+ classifyProfile,+ emailHash,+ isoDate,+ type ProfileInput,+ sourceConsent,+} from "./profile";+import { audienceFilter, journeys } from "./program";+import {+ contactUpdate,+ importContactUpdate,+ mergeConsent,+ profileFingerprint,+ type RemoteContact,+} from "./sync-policy";++const input = (): ProfileInput => ({+ source: {+ email: "[email protected]",+ created_at: "2026-01-01 12:00:00 UTC",+ },+ user: {+ id: "cap-user",+ email: "[email protected]",+ name: "Taylor",+ lastName: null,+ stripeSubscriptionStatus: null,+ thirdPartyStripeSubscriptionId: null,+ created_at: "2026-01-01T12:00:00.000Z",+ defaultOrgId: "personal",+ },+ memberships: [+ {+ userId: "cap-user",+ organizationId: "personal",+ ownerId: "cap-user",+ hasProSeat: false,+ tombstoneAt: null,+ workosConnectionId: null,+ createdAt: "2026-01-01T12:00:00.000Z",+ },+ ],+ licenses: [],+ invited: false,+ sso: false,+ hasVideo: false,+ hasSharedVideo: false,+ now: new Date("2026-09-10T12:00:00.000Z"),+});+const remote = (): RemoteContact => ({+ id: "loops-id",+ email: "[email protected]",+ userId: "cap-user",+ subscribed: true,+ mailingLists: { tips: true },+});++test("an explicit source opt-out always wins over a positive custom flag", () => {+ assert.equal(+ sourceConsent({+ email: "[email protected]",+ unsubscribed_at: "2026-01-01",+ subscribed: "true",+ }),+ "unsubscribed",+ );+ assert.equal(+ sourceConsent({ email: "[email protected]", subscribed: "false" }),+ "unsubscribed",+ );+ assert.equal(+ sourceConsent({ email: "[email protected]", flag: "blocked" }),+ "suppressed",+ );+ assert.equal(+ sourceConsent({+ email: "[email protected]",+ unsubscribed_at: "2026-01-01",+ unsubscribed_reason: "hard_bounce",+ }),+ "suppressed",+ );+});++test("opt-out registry merges cannot resubscribe or clear a suppression", () => {+ for (const status of [+ "unknown",+ "subscribed",+ "unsubscribed",+ "suppressed",+ ] as const) {+ assert.equal(mergeConsent("suppressed", status), "suppressed");+ assert.notEqual(mergeConsent("unsubscribed", status), "subscribed");+ }+});++test("email hashes ignore case and surrounding whitespace", () => {+ assert.equal(+ emailHash(" [email protected] "),+ emailHash("[email protected]"),+ );+});++test("historical Bento and MySQL dates become unambiguous API dates", () => {+ assert.equal(isoDate("2024-04-22 13:29:55 UTC"), "2024-04-22T13:29:55.000Z");+ assert.equal(isoDate("2024-04-22 13:29:55"), "2024-04-22T13:29:55.000Z");+ assert.throws(() => isoDate("not-a-date"));+});++test("verified independent free users are eligible but imported onboarding remains held", () => {+ const profile = classifyProfile(input());+ assert.equal(profile.capAudience, "free");+ assert.equal(profile.capPromotionalEligible, true);+ assert.equal(profile.capLifecycleEnabled, false);+ assert.equal(profile.capOnboardingEligible, false);+ assert.equal(profile.capLifecycleStage, "idle");+});++for (const status of ["active", "trialing", "complete", "paid", "past_due"]) {+ test(`${status} direct subscribers never enter the free promotion audience`, () => {+ const value = input();+ if (!value.user) throw new Error("Missing fixture user");+ value.user.stripeSubscriptionStatus = status;+ const profile = classifyProfile(value);+ assert.equal(profile.capAudience, "customer");+ assert.equal(profile.capPromotionalEligible, false);+ });+}++test("a desktop license prevents Pro upsell onboarding even with no cloud subscription", () => {+ const value = input();+ value.licenses = [+ {+ email: value.source.email,+ subscriptionActive: 1,+ nextRenewalDate: "2038-01-01T00:00:00.000Z",+ kind: "desktop",+ },+ ];+ assert.equal(classifyProfile(value).capAudience, "customer");+ assert.equal(classifyProfile(value).capPlanName, "Cap Desktop");+ value.licenses[0].nextRenewalDate = "2025-01-01T00:00:00.000Z";+ assert.equal(classifyProfile(value).capAudience, "unknown");+});++for (const kind of [+ "membership",+ "invite",+ "sso",+ "latch",+ "origin",+ "seat",+] as const) {+ test(`${kind} teammate evidence excludes promotions`, () => {+ const value = input();+ if (!value.user) throw new Error("Missing fixture user");+ if (kind === "membership")+ value.memberships.push({+ ...value.memberships[0],+ organizationId: "team",+ ownerId: "someone-else",+ });+ if (kind === "invite") value.invited = true;+ if (kind === "sso") value.sso = true;+ if (kind === "latch") value.teammateLatch = true;+ if (kind === "origin") value.user.marketingOrigin = "teammate";+ if (kind === "seat") value.user.thirdPartyStripeSubscriptionId = "sub_team";+ const profile = classifyProfile(value);+ assert.equal(profile.capAudience, "teammate");+ assert.equal(profile.capPromotionalEligible, false);+ });+}++test("unknown origin and historic customer tags fail closed", () => {+ const value = input();+ value.memberships = [];+ assert.equal(classifyProfile(value).capAudience, "unknown");+ const customer = input();+ customer.source.tags = "customer";+ assert.equal(classifyProfile(customer).capAudience, "unknown");+});++test("canceled cloud access can enter former audience but an active license overrides it", () => {+ const value = input();+ if (!value.user) throw new Error("Missing fixture user");+ value.user.stripeSubscriptionStatus = "canceled";+ assert.equal(classifyProfile(value).capAudience, "former");+ value.licenses = [+ {+ email: value.source.email,+ subscriptionActive: 1,+ nextRenewalDate: "2038-01-01T00:00:00.000Z",+ kind: "desktop",+ },+ ];+ assert.equal(classifyProfile(value).capAudience, "customer");+});++test("sync never supplies subscribed true or replaces list subscriptions", () => {+ const profile = classifyProfile(input());+ for (const contact of [+ remote(),+ { ...remote(), subscribed: false },+ { ...remote(), mailingLists: {} },+ ]) {+ const update = contactUpdate(profile, contact, "tips");+ assert.equal("subscribed" in update, false);+ assert.equal("mailingLists" in update, false);+ if (!contact.subscribed || !contact.mailingLists.tips)+ assert.equal(update.capPromotionalEligible, false);+ }+ profile.capConsent = "unsubscribed";+ assert.equal(contactUpdate(profile, remote(), "tips").subscribed, false);+});++test("existing teammate evidence and identities survive contact enrichment", () => {+ const profile = classifyProfile(input());+ const update = contactUpdate(+ profile,+ { ...remote(), capTeammate: true },+ "tips",+ );+ assert.equal(update.capAudience, "teammate");+ assert.equal(update.capPromotionalEligible, false);+ assert.throws(() =>+ contactUpdate(profile, { ...remote(), userId: "another-cap-user" }, "tips"),+ );+ profile.userId = `bento:${emailHash(profile.email)}`;+ assert.equal(contactUpdate(profile, remote(), "tips").userId, "cap-user");+});++test("migration joins a new list without overwriting any explicit preference", () => {+ const profile = classifyProfile(input());+ const update = importContactUpdate(profile, remote(), "new-list");+ assert.deepEqual("mailingLists" in update && update.mailingLists, {+ "new-list": true,+ });+ assert.equal(update.capPromotionalEligible, true);+ assert.equal(update.capLifecycleEnabled, false);+ assert.equal("subscribed" in update, false);+ for (const contact of [+ { ...remote(), subscribed: false },+ { ...remote(), mailingLists: { "new-list": false } },+ ]) {+ const held = importContactUpdate(profile, contact, "new-list");+ assert.equal("mailingLists" in held, false);+ assert.equal("subscribed" in held, false);+ assert.equal(held.capPromotionalEligible, false);+ }+});++test("verification timestamps do not churn the sync fingerprint", () => {+ const profile = classifyProfile(input());+ assert.equal(+ profileFingerprint(profile),+ profileFingerprint({+ ...profile,+ capVerifiedAt: "later",+ capImportedAt: "later",+ }),+ );+ assert.notEqual(+ profileFingerprint(profile),+ profileFingerprint({ ...profile, capTeammate: true }),+ );+});++test("every journey requires subscription consent and promotional journeys exclude teammates", () => {+ assert.equal(+ journeys.reduce((count, journey) => count + journey.messages.length, 0),+ 10,+ );+ for (const journey of journeys) {+ const filter = audienceFilter(journey.audience, journey.promotional);+ assert.ok(+ filter.conditions.some(+ (condition) =>+ condition.key === "subscribed" && condition.operator === "isTrue",+ ),+ );+ assert.ok(+ filter.conditions.some(+ (condition) =>+ condition.key === "capConsent" && condition.value === "subscribed",+ ),+ );+ if (journey.promotional)+ assert.ok(+ filter.conditions.some(+ (condition) =>+ condition.key === "capTeammate" && condition.operator === "isFalse",+ ),+ );+ }+});diff --git a/scripts/loops/profile.ts b/scripts/loops/profile.tsnew file mode 100644index 000000000..35bf332fe--- /dev/null+++ b/scripts/loops/profile.ts@@ -0,0 +1,185 @@+import { createHash } from "node:crypto";++export type Consent = "subscribed" | "unsubscribed" | "suppressed" | "unknown";+export type CapUser = {+ id: string;+ email: string;+ name: string | null;+ lastName: string | null;+ stripeSubscriptionStatus: string | null;+ thirdPartyStripeSubscriptionId: string | null;+ created_at: string;+ defaultOrgId: string | null;+ marketingOrigin?: string;+};+export type Membership = {+ userId: string;+ organizationId: string;+ ownerId: string;+ hasProSeat: number | boolean;+ tombstoneAt: string | null;+ workosConnectionId: string | null;+ createdAt: string;+};+export type License = {+ email: string;+ subscriptionActive: number | boolean;+ nextRenewalDate: string | null;+ kind: "desktop" | "selfhosted";+};+export type SourceContact = Record<string, string> & { email: string };+export type ProfileInput = {+ source: SourceContact;+ user?: CapUser;+ memberships: Membership[];+ licenses: License[];+ invited: boolean;+ sso: boolean;+ teammateLatch?: boolean;+ hasVideo: boolean;+ hasSharedVideo: boolean;+ now: Date;+};++export const normalizeEmail = (email: string) => email.trim().toLowerCase();+export const emailHash = (email: string) =>+ createHash("sha256").update(normalizeEmail(email)).digest("hex");++export function isoDate(value: string) {+ const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}( UTC)?$/.test(value)+ ? `${value.replace(" UTC", "").replace(" ", "T")}Z`+ : value;+ const date = new Date(normalized);+ if (!Number.isFinite(date.getTime()))+ throw new Error("Source contains an invalid date");+ return date.toISOString();+}++export function sourceConsent(source: SourceContact): Consent {+ if (source.flag?.trim()) return "suppressed";+ if (source.unsubscribed_at?.trim()) {+ return /bounce|spam|invalid|blocked|undeliver|complaint/i.test(+ source.unsubscribed_reason ?? "",+ )+ ? "suppressed"+ : "unsubscribed";+ }+ if (["false", "0", "no"].includes(source.subscribed?.trim().toLowerCase()))+ return "unsubscribed";+ return "subscribed";+}++export function classifyProfile(input: ProfileInput) {+ const { source, user, licenses, memberships, now } = input;+ const consent = sourceConsent(source);+ const teammate = Boolean(+ input.teammateLatch ||+ input.invited ||+ input.sso ||+ user?.marketingOrigin === "teammate" ||+ user?.thirdPartyStripeSubscriptionId ||+ memberships.some(+ (member) => member.ownerId !== user?.id || member.workosConnectionId,+ ),+ );+ const directCustomer = [+ "active",+ "trialing",+ "complete",+ "paid",+ "past_due",+ ].includes(user?.stripeSubscriptionStatus ?? "");+ const activeLicenses = licenses.filter(+ (license) =>+ Boolean(license.subscriptionActive) &&+ license.nextRenewalDate !== null &&+ Date.parse(isoDate(license.nextRenewalDate)) > now.getTime(),+ );+ const customer =+ directCustomer ||+ activeLicenses.length > 0 ||+ Boolean(user?.thirdPartyStripeSubscriptionId) ||+ memberships.some(+ (member) => !member.tombstoneAt && Boolean(member.hasProSeat),+ );+ const historicalIndependent =+ user &&+ memberships.some(+ (member) =>+ !member.tombstoneAt &&+ member.ownerId === user.id &&+ member.organizationId === user.defaultOrgId &&+ Math.abs(+ Date.parse(isoDate(member.createdAt)) -+ Date.parse(isoDate(user.created_at)),+ ) <+ 5 * 60_000,+ );+ const independent =+ user?.marketingOrigin === "independent" || historicalIndependent;+ const historicalCustomer =+ /(^|[,;|\s])customer([,;|\s]|$)/i.test(source.tags ?? "") ||+ licenses.length > 0;+ const former =+ user?.stripeSubscriptionStatus === "canceled" && licenses.length === 0;+ const audience = teammate+ ? "teammate"+ : customer+ ? "customer"+ : former+ ? "former"+ : 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.";+ return {+ email: normalizeEmail(source.email),+ userId: user?.id ?? `bento:${emailHash(source.email)}`,+ firstName:+ source.first_name ||+ source.firstname ||+ user?.name?.split(/\s+/)[0] ||+ "",+ lastName: source.last_name || source.lastname || user?.lastName || "",+ subscribed: consent === "subscribed",+ source: "Bento migration",+ capAudience: audience,+ capOrigin: teammate ? "teammate" : independent ? "independent" : "unknown",+ capConsent: consent,+ capTeammate: teammate,+ capCustomer: customer,+ capPlanName: planName,+ capCustomerWelcome: welcome,+ capPromotionalEligible:+ consent === "subscribed" &&+ !teammate &&+ (audience === "free" || audience === "former"),+ capOnboardingEligible: false,+ capLifecycleEnabled: false,+ capLifecycleStage: "idle",+ capHasVideo: input.hasVideo,+ capHasSharedVideo: input.hasSharedVideo,+ capVerifiedAt: now.toISOString(),+ capImportedAt: now.toISOString(),+ capSignupAt: isoDate(+ user?.created_at || source.created_at || now.toISOString(),+ ),+ capSourceTags: source.tags || "",+ capSourceGroup: source.userGroup || source.usergroup || "",+ };+}++export type ContactProfile = ReturnType<typeof classifyProfile>;diff --git a/scripts/loops/program.ts b/scripts/loops/program.tsnew file mode 100644index 000000000..c790a266c--- /dev/null+++ b/scripts/loops/program.ts@@ -0,0 +1,232 @@+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>',+ },+];diff --git a/scripts/loops/provision.ts b/scripts/loops/provision.tsnew file mode 100644index 000000000..10d8ad5d8--- /dev/null+++ b/scripts/loops/provision.ts@@ -0,0 +1,452 @@+import { createHash } from "node:crypto";+import { readFile, writeFile } from "node:fs/promises";+import { parseArgs } from "node:util";+import { LoopsApi, LoopsApiError } from "./api";+import {+ audienceFilter,+ campaignTemplates,+ components,+ condition,+ contactProperties,+ journeys,+ programVersion,+ theme,+} from "./program";++type Named = { id: string; name: string };+type Node = {+ id: string;+ typeName: string;+ nextNodeIds: string[];+ emailMessageId?: string;+};+type Workflow = Named & {+ status: string;+ description: string;+ mailingListId: string | null;+ workflowRevisionId: string | null;+ rootNodeId: string;+ nodes: Record<string, Node>;+};+type Email = {+ contentRevisionId: string | null;+ subject: string;+ lmx: string;+};+type Receipt = {+ teamName: string;+ version: string;+ resources: Record<string, string>;+ operations: Record<string, string>;+ definitions: Record<string, string>;+ guardian: Record<string, { errors: unknown[]; warnings: unknown[] }>;+};++const { values } = parseArgs({+ options: {+ apply: { type: "boolean", default: false },+ "dry-run": { type: "boolean", default: false },+ state: { type: "string" },+ team: { type: "string" },+ "mailing-list": { type: "string" },+ },+});++if (values.apply && values["dry-run"])+ throw new Error("Choose --apply or --dry-run");+if (!values.team)+ throw new Error("Pass --team with the expected Loops team name");+if (values.apply && !values.state)+ throw new Error("--apply requires a private --state file");++const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "");+const identity = await api.request<{ success: boolean; teamName: string }>(+ "api-key",+);+if (!identity.success || identity.teamName !== values.team)+ throw new Error("Wrong Loops team");++let receipt: Receipt = {+ teamName: identity.teamName,+ version: programVersion,+ resources: {},+ operations: {},+ definitions: {},+ guardian: {},+};+if (values.state) {+ try {+ receipt = JSON.parse(await readFile(values.state, "utf8"));+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))+ throw error;+ }+}+if (+ receipt.teamName !== identity.teamName ||+ receipt.version !== programVersion+) {+ throw new Error("State file belongs to a different team or program");+}++const save = async () => {+ if (values.apply && values.state) {+ await writeFile(values.state, `${JSON.stringify(receipt, null, 2)}\n`, {+ mode: 0o600,+ });+ }+};+const hash = (value: unknown) =>+ createHash("sha256").update(JSON.stringify(value)).digest("hex");+const named = (rows: Named[], name: string) => {+ const matches = rows.filter((row) => row.name === name);+ if (matches.length > 1) throw new Error(`Duplicate managed name: ${name}`);+ return matches[0];+};++try {+ const existingProperties = await api.request<{ key: string; type: string }[]>(+ "contacts/properties",+ );+ const lists = await api.request<Named[]>("lists");+ const workflows = await api.list<Workflow>("workflows");+ const themes = await api.list<Named>("themes");+ const sharedComponents = await api.list<Named>("components");+ const segments = await api.list<Named>("audience-segments");+ const campaigns = await api.list<+ Named & { status: string; emailMessageId: string }+ >("campaigns");+ const listId =+ values["mailing-list"] ?? named(lists, "Product updates and tips")?.id;+ if (listId && !lists.some((list) => list.id === listId))+ throw new Error("Unknown mailing list");+ console.log(+ JSON.stringify({+ team: identity.teamName,+ mode: values.apply ? "apply drafts" : "dry run",+ workflows: journeys.length,+ emails: journeys.reduce(+ (count, journey) => count + journey.messages.length,+ 0,+ ),+ campaignTemplates: campaignTemplates.length,+ mailingListId:+ listId ?? "Create Product updates and tips in the Loops dashboard",+ }),+ );+ if (!values.apply) process.exit(0);+ if (!listId)+ console.log(+ "Mailing list is pending dashboard setup; resources remain drafts.",+ );+ if (listId) receipt.resources.mailingList = listId;+ await save();++ for (const [name, type] of Object.entries(contactProperties)) {+ const existing = existingProperties.find(+ (property) => property.key === name,+ );+ if (existing && existing.type !== type)+ throw new Error(`Wrong property type: ${name}`);+ if (!existing)+ await api.request("contacts/properties", "POST", { name, type });+ }++ const ensure = async (+ path: string,+ rows: Named[],+ definition: { name: string },+ key: string,+ ) => {+ const existing = named(rows, definition.name);+ const resource =+ existing ?? (await api.request<Named>(path, "POST", definition));+ receipt.resources[key] = resource.id;+ await save();+ return resource.id;+ };+ const themeId = await ensure("themes", themes, theme, "theme");+ const componentIds: string[] = [];+ for (const component of components) {+ componentIds.push(+ 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 current = await api.request<Email>(`email-messages/${id}`);+ if (+ receipt.definitions[id] !== hash(definition) ||+ current.subject !== definition.subject+ ) {+ const result = await api.request<{ warnings?: unknown[] }>(+ `email-messages/${id}`,+ "POST",+ {+ expectedRevisionId: current.contentRevisionId,+ ...definition,+ },+ );+ if (result.warnings?.length)+ console.log(+ JSON.stringify({ email: id, compileWarnings: result.warnings }),+ );+ receipt.definitions[id] = hash(definition);+ await save();+ }+ const guardian = await api.request<{+ errors: unknown[];+ warnings: unknown[];+ }>(`email-messages/${id}/guardian`);+ receipt.guardian[id] = guardian;+ await save();+ if (guardian.errors.length)+ throw new Error(+ `Guardian errors for ${id}: ${JSON.stringify(guardian.errors)}`,+ );+ };++ for (const journey of journeys) {+ const existing = named(workflows, journey.name);+ let workflow = existing+ ? await api.request<Workflow>(`workflows/${existing.id}`)+ : await api.request<Workflow>("workflows", "POST", {+ name: journey.name,+ description: `${programVersion}; managed by scripts/loops/provision.ts. Draft only. ${journey.messages.map((m) => m.delayDays).join(", ")} day relative delays. Imports never enroll.`,+ mailingListId: listId,+ });+ if (workflow.status !== "Draft")+ throw new Error(`Refusing to edit non-draft workflow ${journey.name}`);+ if (!workflow.description.includes(programVersion))+ throw new Error("Existing workflow is not owned by this program");+ if (listId && workflow.mailingListId !== listId) {+ const changed = await api.request<{+ status: string;+ workflow?: Workflow;+ }>(`workflows/${workflow.id}/mailing-list`, "POST", {+ expectedRevisionId: workflow.workflowRevisionId,+ mailingListId: listId,+ });+ if (!changed.workflow)+ throw new Error(+ "Mailing-list assignment needs review; no queued contacts were discarded",+ );+ workflow = changed.workflow;+ }+ receipt.resources[journey.key] = workflow.id;+ await save();+ const exitIds = Object.entries(workflow.nodes)+ .filter(([, n]) => n.typeName === "ExitAction")+ .map(([id]) => id);+ if (exitIds.length !== 1)+ throw new Error(`Expected one shared exit in ${journey.name}`);+ const exitId = exitIds[0];+ const update = async (id: string, payload: unknown, operation: string) => {+ const digest = hash(payload);+ if (receipt.definitions[operation] === digest) return;+ const result = await api.request<{ workflow: Workflow }>(+ `workflows/${workflow.id}/nodes/${id}`,+ "POST",+ {+ expectedRevisionId: workflow.workflowRevisionId,+ payload,+ },+ );+ workflow = result.workflow;+ receipt.definitions[operation] = digest;+ await save();+ };+ const insert = async (+ type: string,+ operation: string,+ fromNodeId?: string,+ ) => {+ const recordedId = receipt.operations[operation];+ if (recordedId) {+ const node = workflow.nodes[recordedId];+ if (!node || node.typeName !== type)+ throw new Error(`Managed node changed: ${operation}`);+ return { ...node, id: recordedId };+ }+ const result = await api.request<{ node: Node; workflow: Workflow }>(+ `workflows/${workflow.id}/nodes`,+ "POST",+ {+ expectedRevisionId: workflow.workflowRevisionId,+ nodeTypeName: type,+ ...(fromNodeId+ ? { insertMode: "between", fromNodeId, toNodeId: exitId }+ : { insertMode: "before", beforeNodeId: exitId }),+ },+ );+ workflow = result.workflow;+ receipt.operations[operation] = result.node.id;+ await save();+ return result.node;+ };+ await update(+ workflow.rootNodeId,+ {+ typeName: "ContactPropertyTrigger",+ contactPropertyQuery: {+ key: "capLifecycleStage",+ is: { operator: "equal", value: journey.key },+ was: { operator: "not_equal", value: journey.key },+ },+ reEligible: false,+ },+ `${journey.key}:trigger`,+ );+ const guard = await insert("AudienceFilter", `${journey.key}:guard`);+ const filter = audienceFilter(journey.audience, journey.promotional);+ filter.conditions.push(+ condition("capLifecycleEnabled", true),+ condition("capOnboardingEligible", true),+ );+ await update(+ guard.id,+ { audienceFilter: filter, appliesDownstream: true },+ `${journey.key}:guard-config`,+ );+ for (const message of journey.messages) {+ const operation = `${journey.key}:${message.key}`;+ if (message.delayDays) {+ const timer = await insert("TimerAction", `${operation}:timer`);+ await update(+ timer.id,+ { amount: message.delayDays, unit: "d" },+ `${operation}:timer-config`,+ );+ }+ let fromNodeId: string | undefined;+ if (message.onlyIf) {+ const branch = await insert("BranchNode", `${operation}:branch`);+ const children = workflow.nodes[branch.id].nextNodeIds;+ if (children.length !== 2)+ throw new Error("Expected two milestone branches");+ for (let index = 0; index < 2; index++) {+ await update(+ children[index],+ {+ audienceFilter: {+ match: "all",+ conditions: [+ condition(+ message.onlyIf.property,+ index === 0 ? message.onlyIf.value : !message.onlyIf.value,+ ),+ ],+ },+ appliesDownstream: false,+ },+ `${operation}:branch-${index}`,+ );+ }+ fromNodeId = children[0];+ }+ const email = await insert(+ "SendEmailAction",+ `${operation}:email`,+ fromNodeId,+ );+ if (!email.emailMessageId) throw new Error("Missing email message ID");+ await editEmail(email.emailMessageId, message);+ }+ const verified = await api.request<Workflow>(`workflows/${workflow.id}`);+ if (verified.status !== "Draft")+ throw new Error("Workflow status changed unexpectedly");+ console.log(+ JSON.stringify({+ name: journey.name,+ id: verified.id,+ status: verified.status,+ nodes: Object.keys(verified.nodes).length,+ }),+ );+ }++ for (const template of campaignTemplates) {+ const segmentName = `${template.name} audience`;+ const segmentId = await ensure(+ "audience-segments",+ segments,+ {+ name: segmentName,+ description:+ "Managed by Cap lifecycle v1. Verify current consent and entitlements before scheduling.",+ filter: audienceFilter(template.audience, template.promotional),+ } as { name: string },+ `segment:${template.key}`,+ );+ const existing = named(campaigns, template.name);+ const campaign = existing+ ? await api.request<{+ id: string;+ status: string;+ emailMessageId: string;+ }>(`campaigns/${existing.id}`)+ : await api.request<{+ id: string;+ status: string;+ emailMessageId: string;+ }>("campaigns", "POST", {+ name: template.name,+ mailingListId: listId,+ audienceSegmentId: segmentId,+ });+ const current = await api.request<{ status: string }>(+ `campaigns/${campaign.id}`,+ );+ if (current.status !== "Draft")+ throw new Error("Refusing to edit a non-draft campaign");+ if (listId)+ await api.request(`campaigns/${campaign.id}`, "POST", {+ mailingListId: listId,+ audienceSegmentId: segmentId,+ });+ receipt.resources[template.key] = campaign.id;+ await save();+ await editEmail(campaign.emailMessageId, template);+ console.log(+ JSON.stringify({ name: template.name, id: campaign.id, status: "Draft" }),+ );+ }+ await save();+ console.log(+ "Verified draft resources. No publish, activation, event, or send request was made.",+ );+} catch (error) {+ if (error instanceof LoopsApiError)+ console.error(+ JSON.stringify({+ status: error.status,+ path: error.path,+ details: error.details,+ }),+ );+ else+ console.error(+ error instanceof Error ? error.message : "Provisioning failed",+ );+ process.exitCode = 1;+}diff --git a/scripts/loops/resources.json b/scripts/loops/resources.jsonnew file mode 100644index 000000000..baeeb6bdd--- /dev/null+++ b/scripts/loops/resources.json@@ -0,0 +1,15 @@+{+ "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/seed.ts b/scripts/loops/seed.tsnew file mode 100644index 000000000..b9073aecb--- /dev/null+++ b/scripts/loops/seed.ts@@ -0,0 +1,117 @@+import { readFile } from "node:fs/promises";+import { parseArgs } from "node:util";+import mysql, { type RowDataPacket } from "mysql2/promise";+import { type Consent, type ContactProfile, emailHash } from "./profile";+import { mergeConsent } from "./sync-policy";++type Entry = {+ emailHash: string;+ consent: Consent;+ teammate: boolean;+ userId: string | null;+ source: string;+ imported: boolean;+};+const { values } = parseArgs({+ options: {+ registry: { type: "string" },+ contacts: { type: "string" },+ apply: { type: "boolean", default: false },+ },+});+if (!values.registry || !values.contacts)+ throw new Error(+ "Pass --registry and --contacts from the private prepared import",+ );+const registry: Entry[] = JSON.parse(await readFile(values.registry, "utf8"));+const profiles: ContactProfile[] = JSON.parse(+ await readFile(values.contacts, "utf8"),+);+const byHash = new Map(+ profiles.map((profile) => [emailHash(profile.email), profile]),+);+if (new Set(registry.map((entry) => entry.emailHash)).size !== registry.length)+ throw new Error("Duplicate consent entries");+for (const row of registry) {+ if (+ !/^[a-f0-9]{64}$/.test(row.emailHash) ||+ !["subscribed", "unsubscribed", "suppressed", "unknown"].includes(+ row.consent,+ )+ )+ throw new Error("Invalid consent registry");+ if (row.consent === "subscribed" && !byHash.has(row.emailHash))+ throw new Error("Missing positive contact");+}+console.log(+ JSON.stringify({+ mode: values.apply ? "apply" : "dry run",+ registry: registry.length,+ positive: profiles.length,+ }),+);+if (!values.apply) process.exit(0);+if (process.env.LOOPS_SYNC_ENABLED !== "true")+ throw new Error("LOOPS_SYNC_ENABLED=true is required for database writes");+if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");+const db = await mysql.createConnection(process.env.DATABASE_URL);+try {+ for (let offset = 0; offset < registry.length; offset += 500) {+ await db.beginTransaction();+ try {+ const batch = registry+ .slice(offset, offset + 500)+ .sort((a, b) => a.emailHash.localeCompare(b.emailHash));+ const [existing] = await db.query<+ (RowDataPacket & {+ emailHash: string;+ email: string | null;+ consent: Consent;+ teammate: number;+ })[]+ >(+ "SELECT emailHash,email,consent,teammate FROM marketing_contacts WHERE emailHash IN (?) ORDER BY emailHash FOR UPDATE",+ [batch.map((entry) => entry.emailHash)],+ );+ const current = new Map(+ existing.map((entry) => [entry.emailHash, entry]),+ );+ const inserts = batch.map((entry) => {+ const previous = current.get(entry.emailHash);+ const consent = mergeConsent(+ previous?.consent ?? "unknown",+ entry.consent,+ );+ const profile = byHash.get(entry.emailHash);+ const email =+ consent === "subscribed"+ ? (profile?.email ?? null)+ : (previous?.email ?? null);+ const teammate = entry.teammate || Boolean(previous?.teammate);+ return [+ entry.emailHash,+ email,+ entry.userId,+ consent,+ entry.source,+ teammate,+ entry.imported,+ profile?.capAudience ?? null,+ ];+ });+ await db.query(+ "INSERT INTO marketing_contacts (emailHash,email,userId,consent,source,teammate,imported,lastAudience) VALUES ? ON DUPLICATE KEY UPDATE email=COALESCE(email,VALUES(email)),consent=CASE WHEN consent='suppressed' OR VALUES(consent)='suppressed' THEN 'suppressed' WHEN consent='unsubscribed' OR VALUES(consent)='unsubscribed' THEN 'unsubscribed' WHEN consent='subscribed' OR VALUES(consent)='subscribed' THEN 'subscribed' ELSE 'unknown' END,teammate=teammate OR VALUES(teammate),imported=imported OR VALUES(imported),updatedAt=CURRENT_TIMESTAMP",+ [inserts],+ );+ await db.commit();+ } catch (error) {+ await db.rollback();+ throw error;+ }+ console.log(+ JSON.stringify({ seeded: Math.min(offset + 500, registry.length) }),+ );+ }+} finally {+ await db.end();+}diff --git a/scripts/loops/sources.ts b/scripts/loops/sources.tsnew file mode 100644index 000000000..1b8a3aa10--- /dev/null+++ b/scripts/loops/sources.ts@@ -0,0 +1,60 @@+import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";+import type { CapUser, License, Membership } from "./profile";++const rows = async <T>(db: Connection, sql: string): Promise<T[]> => {+ const [result] = await db.query<(RowDataPacket & T)[]>(sql);+ return result;+};++export async function readSources(capUrl: string, licenseUrl: string) {+ const cap = await mysql.createConnection({ uri: capUrl, dateStrings: true });+ try {+ const license = await mysql.createConnection({+ uri: licenseUrl,+ dateStrings: true,+ });+ try {+ const users = await rows<CapUser>(+ cap,+ "SELECT id,email,name,lastName,stripeSubscriptionStatus,thirdPartyStripeSubscriptionId,created_at,defaultOrgId,marketingOrigin FROM users",+ );+ const memberships = await rows<Membership>(+ cap,+ "SELECT m.userId,m.organizationId,m.hasProSeat,o.ownerId,o.tombstoneAt,o.workosConnectionId,o.createdAt FROM organization_members m JOIN organizations o ON o.id=m.organizationId",+ );+ const invites = await rows<{ invitedEmail: string }>(+ cap,+ "SELECT invitedEmail FROM organization_invites WHERE status IN ('pending','accepted')",+ );+ const sso = await rows<{ userId: string }>(+ cap,+ "SELECT DISTINCT userId FROM accounts WHERE provider='workos'",+ );+ const videos = await rows<{+ ownerId: string;+ total: number;+ hasPublicVideo: number;+ }>(+ cap,+ "SELECT ownerId,COUNT(*) AS total,MAX(CASE WHEN public=1 THEN 1 ELSE 0 END) AS hasPublicVideo FROM videos GROUP BY ownerId",+ );+ const licenses = await rows<License>(+ license,+ "SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'desktop' AS kind FROM commercialLicenses l JOIN user u ON u.id=l.userId UNION ALL SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'selfhosted' AS kind FROM selfHostedLicenses l JOIN user u ON u.id=l.userId",+ );+ return {+ users,+ memberships,+ invites,+ sso,+ videos,+ licenses,+ verifiedAt: new Date(),+ };+ } finally {+ await license.end();+ }+ } finally {+ await cap.end();+ }+}diff --git a/scripts/loops/sync-policy.ts b/scripts/loops/sync-policy.tsnew file mode 100644index 000000000..346d8d8f2--- /dev/null+++ b/scripts/loops/sync-policy.ts@@ -0,0 +1,93 @@+import { createHash } from "node:crypto";+import type { Consent, ContactProfile } from "./profile";++export type RemoteContact = {+ id: string;+ email: string;+ userId: string | null;+ subscribed: boolean;+ mailingLists: Record<string, boolean>;+ capTeammate?: boolean;+ capLifecycleStage?: string;+ capOnboardingEligible?: boolean;+};++export const mergeConsent = (existing: Consent, incoming: Consent): Consent => {+ if (existing === "suppressed" || incoming === "suppressed")+ return "suppressed";+ if (existing === "unsubscribed" || incoming === "unsubscribed")+ return "unsubscribed";+ return existing === "subscribed" || incoming === "subscribed"+ ? "subscribed"+ : "unknown";+};++export function profileFingerprint(profile: ContactProfile) {+ const {+ capVerifiedAt: _verified,+ capImportedAt: _imported,+ ...stable+ } = profile;+ return createHash("sha256").update(JSON.stringify(stable)).digest("hex");+}++export function contactUpdate(+ profile: ContactProfile,+ remote: RemoteContact,+ listId?: string,+) {+ if (+ remote.userId &&+ remote.userId !== profile.userId &&+ !profile.userId.startsWith("bento:")+ )+ throw new Error("Contact identity conflict");+ const {+ subscribed: _subscribed,+ capImportedAt: _imported,+ source: _source,+ ...attributes+ } = profile;+ const allowed =+ profile.capConsent === "subscribed" &&+ remote.subscribed &&+ (!listId || remote.mailingLists[listId] === true);+ const teammate = profile.capTeammate || remote.capTeammate === true;+ return {+ ...attributes,+ ...(remote.userId && profile.userId.startsWith("bento:")+ ? { userId: remote.userId }+ : {}),+ capTeammate: teammate,+ capAudience: teammate ? "teammate" : profile.capAudience,+ capPromotionalEligible:+ allowed && !teammate && profile.capPromotionalEligible,+ capOnboardingEligible: allowed && profile.capOnboardingEligible,+ capLifecycleEnabled: allowed && profile.capLifecycleEnabled,+ ...(!allowed ? { capLifecycleStage: "idle" } : {}),+ ...(profile.capConsent !== "subscribed" ? { subscribed: false } : {}),+ };+}++export function importContactUpdate(+ profile: ContactProfile,+ remote: RemoteContact,+ listId?: string,+) {+ if (+ listId &&+ profile.capConsent === "subscribed" &&+ remote.subscribed &&+ remote.mailingLists[listId] === undefined+ ) {+ return {+ ...contactUpdate(+ profile,+ { ...remote, mailingLists: { ...remote.mailingLists, [listId]: true } },+ listId,+ ),+ mailingLists: { [listId]: true },+ };+ }+ return contactUpdate(profile, remote, listId);+}diff --git a/scripts/loops/sync.ts b/scripts/loops/sync.tsnew file mode 100644index 000000000..fab58dde2--- /dev/null+++ b/scripts/loops/sync.ts@@ -0,0 +1,189 @@+import { parseArgs } from "node:util";+import mysql, { type RowDataPacket } from "mysql2/promise";+import { LoopsApi, LoopsApiError } from "./api";+import { type Consent, classifyProfile, normalizeEmail } from "./profile";+import { readSources } from "./sources";+import {+ contactUpdate,+ profileFingerprint,+ type RemoteContact,+} from "./sync-policy";++type Record = RowDataPacket & {+ emailHash: string;+ email: string;+ userId: string | null;+ consent: Consent;+ teammate: number;+ imported: number;+ lastAudience: string | null;+ lastProfileHash: string | null;+ lastSyncedAt: string | null;+ createdAt: string;+};+const { values } = parseArgs({+ options: {+ apply: { type: "boolean", default: false },+ team: { type: "string" },+ "mailing-list": { type: "string" },+ limit: { type: "string", default: "100" },+ },+});+const limit = Number(values.limit);+if (+ !values.team ||+ !values["mailing-list"] ||+ !Number.isSafeInteger(limit) ||+ limit < 1 ||+ limit > 1000+)+ throw new Error("Pass --team, --mailing-list and --limit 1..1000");+const listId = values["mailing-list"];+const capUrl = process.env.DATABASE_URL;+const licenseUrl = process.env.LOOPS_LICENSE_DATABASE_URL;+if (!capUrl || !licenseUrl)+ throw new Error(+ "DATABASE_URL and read-only LOOPS_LICENSE_DATABASE_URL are required",+ );+if (values.apply && process.env.LOOPS_SYNC_ENABLED !== "true")+ throw new Error("LOOPS_SYNC_ENABLED=true is required to apply");+const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "");+const identity = await api.request<{ success: boolean; teamName: string }>(+ "api-key",+);+if (!identity.success || identity.teamName !== values.team)+ throw new Error("Wrong Loops team");+const lists = await api.request<{ id: string }[]>("lists");+if (!lists.some((list) => list.id === listId))+ throw new Error("Unknown mailing list");+const source = await readSources(capUrl, licenseUrl);+const group = <T>(items: T[], key: (item: T) => string) => {+ const grouped = new Map<string, T[]>();+ for (const item of items) {+ const id = key(item);+ grouped.set(id, [...(grouped.get(id) ?? []), item]);+ }+ return grouped;+};+const users = new Map(source.users.map((user) => [user.id, user]));+const members = group(source.memberships, (member) => member.userId);+const licenses = group(source.licenses, (license) =>+ normalizeEmail(license.email),+);+const invited = new Set(+ source.invites.map((invite) => normalizeEmail(invite.invitedEmail)),+);+const sso = new Set(source.sso.map((account) => account.userId));+const videos = new Map(source.videos.map((video) => [video.ownerId, video]));+const db = await mysql.createConnection({ uri: capUrl, dateStrings: true });+let updated = 0;+let changed = 0;+try {+ const [records] = await db.query<Record[]>(+ "SELECT * FROM marketing_contacts WHERE email IS NOT NULL ORDER BY lastSyncedAt,emailHash",+ );+ for (const row of records) {+ const user = row.userId ? users.get(row.userId) : undefined;+ const identityMissing =+ Boolean(row.userId) &&+ (!user || normalizeEmail(user.email) !== normalizeEmail(row.email));+ const consent = identityMissing ? "unknown" : row.consent;+ const video = user ? videos.get(user.id) : undefined;+ const profile = classifyProfile({+ source: {+ email: row.email,+ created_at: row.createdAt,+ subscribed: consent === "subscribed" ? "true" : "false",+ tags:+ row.lastAudience === "customer" || row.lastAudience === "unknown"+ ? "customer"+ : "",+ },+ user,+ memberships: user ? (members.get(user.id) ?? []) : [],+ licenses: licenses.get(normalizeEmail(row.email)) ?? [],+ invited: invited.has(normalizeEmail(row.email)),+ sso: user ? sso.has(user.id) : false,+ teammateLatch: Boolean(row.teammate),+ hasVideo: Boolean(video?.total),+ hasSharedVideo: Boolean(video?.hasPublicVideo),+ now: source.verifiedAt,+ });+ profile.capConsent = consent;+ profile.subscribed = consent === "subscribed";+ if (row.userId) profile.userId = row.userId;+ const fingerprint = profileFingerprint(profile);+ const recheckConsent =+ !row.lastSyncedAt ||+ Date.now() - Date.parse(`${row.lastSyncedAt.replace(" ", "T")}Z`) >+ 24 * 60 * 60_000;+ if (row.lastProfileHash === fingerprint && !recheckConsent) continue;+ changed++;+ if (updated >= limit) continue;+ if (!values.apply) {+ updated++;+ continue;+ }+ if (Date.now() - source.verifiedAt.getTime() > 10 * 60_000)+ throw new Error(+ "Source snapshot expired; rerun to refresh remaining contacts",+ );+ const remote = await api.request<RemoteContact[]>(+ `contacts/find?email=${encodeURIComponent(row.email)}`,+ );+ if (remote.length > 1) throw new Error("Ambiguous Loops contact");+ const contact = remote[0];+ if (!contact) {+ if (!row.imported && !row.lastSyncedAt && consent === "subscribed") {+ try {+ await api.request("contacts/create", "POST", {+ ...profile,+ mailingLists: { [listId]: true },+ });+ } catch (error) {+ if (error instanceof LoopsApiError && error.status === 409) continue;+ throw error;+ }+ } else {+ await db.execute(+ "UPDATE marketing_contacts SET consent=CASE WHEN consent IN ('unsubscribed','suppressed') THEN consent ELSE 'unknown' END,lastSyncedAt=CURRENT_TIMESTAMP,lastProfileHash=?,updatedAt=CURRENT_TIMESTAMP WHERE emailHash=?",+ [fingerprint, row.emailHash],+ );+ updated++;+ continue;+ }+ } else {+ await api.request(+ "contacts/update",+ "PUT",+ contactUpdate(profile, contact, listId),+ );+ if (!contact.subscribed) {+ profile.capConsent = "unsubscribed";+ }+ profile.capTeammate ||= contact.capTeammate === true;+ }+ await db.execute(+ "UPDATE marketing_contacts SET consent=CASE WHEN consent IN ('unsubscribed','suppressed') THEN consent ELSE ? END,teammate=teammate OR ?,lastAudience=?,lastProfileHash=?,lastSyncedAt=CURRENT_TIMESTAMP,updatedAt=CURRENT_TIMESTAMP WHERE emailHash=?",+ [+ profile.capConsent,+ profile.capTeammate,+ profile.capTeammate ? "teammate" : profile.capAudience,+ fingerprint,+ row.emailHash,+ ],+ );+ updated++;+ }+ console.log(+ JSON.stringify({+ mode: values.apply ? "apply held contacts" : "dry run",+ changed,+ processed: updated,+ remaining: Math.max(0, changed - updated),+ lifecycleEnabled: false,+ }),+ );+} finally {+ await db.end();+}diff --git a/scripts/loops/verify.ts b/scripts/loops/verify.tsnew file mode 100644index 000000000..f2fe2c5d5--- /dev/null+++ b/scripts/loops/verify.ts@@ -0,0 +1,219 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { parseArgs } from "node:util";+import { LoopsApi } from "./api";+import {+ audienceFilter,+ campaignTemplates,+ condition,+ journeys,+ programVersion,+} from "./program";++type Node = {+ typeName: string;+ nextNodeIds: string[];+ emailMessageId?: string;+ amount?: number;+ unit?: string;+ contactPropertyQuery?: unknown;+ reEligible?: boolean;+ audienceFilter?: unknown;+ appliesDownstream?: boolean;+};+type Workflow = {+ status: string;+ name: string;+ mailingListId: string;+ rootNodeId: string;+ nodes: Record<string, Node>;+};+type Email = {+ subject: string;+ previewText: string;+ fromEmail: string;+ replyToEmail: string;+ lmx: string;+ contactPropertiesFallbacks: Record<string, string>;+};++const { values } = parseArgs({+ options: {+ state: { type: "string" },+ team: { type: "string" },+ "mailing-list": { type: "string" },+ },+});+assert(values.state && values.team && values["mailing-list"]);+const receipt: {+ version: string;+ teamName: string;+ resources: Record<string, string>;+ operations: Record<string, string>;+} = JSON.parse(await readFile(values.state, "utf8"));+assert.equal(receipt.version, programVersion);+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]);+let emails = 0;+const verifyEmail = async (+ id: string | undefined,+ expected: { subject: string; previewText: string; body: string },+) => {+ 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));+ const guardian = await api.request<{+ errors: unknown[];+ warnings: unknown[];+ }>(`email-messages/${id}/guardian`);+ assert.deepEqual(guardian.errors, []);+ assert.deepEqual(guardian.warnings, []);+ emails++;+};++for (const journey of journeys) {+ const id = receipt.resources[journey.key];+ const workflow = await api.request<Workflow>(`workflows/${id}`);+ assert.equal(workflow.status, "Draft");+ assert.equal(workflow.name, journey.name);+ assert.equal(workflow.mailingListId, values["mailing-list"]);+ const visited = new Set<string>();+ const node = (nodeId: string, type: string) => {+ assert(!visited.has(nodeId), `Duplicate managed node: ${nodeId}`);+ visited.add(nodeId);+ const result = workflow.nodes[nodeId];+ assert.equal(result?.typeName, type);+ return result;+ };+ const trigger = node(workflow.rootNodeId, "ContactPropertyTrigger");+ assert.equal(trigger.reEligible, false);+ assert.deepEqual(trigger.contactPropertyQuery, {+ key: "capLifecycleStage",+ is: { value: journey.key, operator: "equal" },+ was: { value: journey.key, operator: "not_equal" },+ });+ let previous = [workflow.rootNodeId];+ const connect = (next: string) => {+ for (const prior of previous)+ assert.deepEqual(workflow.nodes[prior].nextNodeIds, [next]);+ previous = [next];+ };+ const guardId = receipt.operations[`${journey.key}:guard`];+ connect(guardId);+ node(guardId, "AudienceFilter");+ const guard = await api.request<Node>(`workflows/${id}/nodes/${guardId}`);+ const filter = audienceFilter(journey.audience, journey.promotional);+ filter.conditions.push(+ condition("capLifecycleEnabled", true),+ condition("capOnboardingEligible", true),+ );+ assert.deepEqual(guard.audienceFilter, filter);+ assert.equal(guard.appliesDownstream, true);+ for (const message of journey.messages) {+ const operation = `${journey.key}:${message.key}`;+ if (message.delayDays) {+ const timerId = receipt.operations[`${operation}:timer`];+ connect(timerId);+ const timer = node(timerId, "TimerAction");+ assert.equal(timer.amount, message.delayDays);+ assert.equal(timer.unit, "d");+ }+ let skipped: string | undefined;+ if (message.onlyIf) {+ const branchId = receipt.operations[`${operation}:branch`];+ connect(branchId);+ const branch = node(branchId, "BranchNode");+ assert.equal(branch.nextNodeIds.length, 2);+ for (let index = 0; index < 2; index++) {+ const childId = branch.nextNodeIds[index];+ node(childId, "AudienceFilter");+ const child = await api.request<Node>(+ `workflows/${id}/nodes/${childId}`,+ );+ assert.deepEqual(child.audienceFilter, {+ match: "all",+ conditions: [+ condition(+ message.onlyIf.property,+ index === 0 ? message.onlyIf.value : !message.onlyIf.value,+ ),+ ],+ });+ assert.equal(child.appliesDownstream, false);+ }+ previous = [branch.nextNodeIds[0]];+ skipped = branch.nextNodeIds[1];+ }+ const emailId = receipt.operations[`${operation}:email`];+ connect(emailId);+ const email = node(emailId, "SendEmailAction");+ await verifyEmail(email.emailMessageId, message);+ if (skipped) previous.push(skipped);+ }+ const exits = Object.entries(workflow.nodes).filter(+ ([, value]) => value.typeName === "ExitAction",+ );+ assert.equal(exits.length, 1);+ connect(exits[0][0]);+ assert.deepEqual(node(exits[0][0], "ExitAction").nextNodeIds, []);+ assert.equal(visited.size, Object.keys(workflow.nodes).length);+ console.log(+ JSON.stringify({+ workflow: journey.name,+ status: "Draft",+ graphVerified: true,+ }),+ );+}++for (const template of campaignTemplates) {+ const campaign = await api.request<{+ status: string;+ mailingListId: string;+ audienceSegmentId: string;+ emailMessageId: string;+ }>(`campaigns/${receipt.resources[template.key]}`);+ assert.equal(campaign.status, "Draft");+ assert.equal(campaign.mailingListId, values["mailing-list"]);+ assert.equal(+ campaign.audienceSegmentId,+ receipt.resources[`segment:${template.key}`],+ );+ const segment = await api.request<{ filter: unknown }>(+ `audience-segments/${campaign.audienceSegmentId}`,+ );+ assert.deepEqual(+ segment.filter,+ audienceFilter(template.audience, template.promotional),+ );+ await verifyEmail(campaign.emailMessageId, template);+}+console.log(+ JSON.stringify({+ workflows: journeys.length,+ campaigns: campaignTemplates.length,+ emails,+ guardianErrors: 0,+ guardianWarnings: 0,+ allDraft: true,+ }),+);