Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: sync Loops audiences reliably through Stripe
Richie McIlroy94b8e7457560
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b6738cb53..d4bc896e1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -93,8 +93,8 @@ jobs:- name: Check email libraryrun: |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+ bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts+ bun run tsc --noEmit --strict --jsx react-jsx --allowImportingTsExtensions --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: >-diff --git a/apps/web/app/api/cron/sync-loops/route.ts b/apps/web/app/api/cron/sync-loops/route.tsnew file mode 100644index 000000000..f6d3ce158--- /dev/null+++ b/apps/web/app/api/cron/sync-loops/route.ts@@ -0,0 +1,60 @@+import { timingSafeEqual } from "node:crypto";+import { runLoopsSync } from "@cap/database/loops/worker";+import {+ HttpApi,+ HttpApiBuilder,+ HttpApiEndpoint,+ HttpApiError,+ HttpApiGroup,+ HttpServerRequest,+} from "@effect/platform";+import { Effect, Layer, Schema } from "effect";+import { apiToHandler } from "@/lib/server";+import { customerCopy } from "../../../../../../emails/customer-copy";++class Api extends HttpApi.make("LoopsSyncApi").add(+ HttpApiGroup.make("root").add(+ HttpApiEndpoint.get("sync")`/api/cron/sync-loops`+ .addSuccess(+ Schema.Struct({+ enabled: Schema.Boolean,+ processed: Schema.Number,+ failed: Schema.Number,+ }),+ )+ .addError(HttpApiError.Unauthorized)+ .addError(HttpApiError.InternalServerError),+ ),+) {}++const ApiLive = HttpApiBuilder.api(Api).pipe(+ Layer.provide(+ HttpApiBuilder.group(Api, "root", (handlers) =>+ handlers.handle("sync", () =>+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const secret = process.env.CRON_SECRET;+ if (!secret) return yield* new HttpApiError.InternalServerError();+ const expected = Buffer.from(`Bearer ${secret}`);+ const actual = Buffer.from(request.headers.authorization ?? "");+ if (+ actual.length !== expected.length ||+ !timingSafeEqual(actual, expected)+ )+ return yield* new HttpApiError.Unauthorized();+ const result = yield* Effect.tryPromise({+ try: () => runLoopsSync(customerCopy),+ catch: () => new HttpApiError.InternalServerError(),+ });+ if (result.failed)+ return yield* new HttpApiError.InternalServerError();+ return result;+ }),+ ),+ ),+ ),+);++export const GET = apiToHandler(ApiLive);+export const maxDuration = 120;+export const dynamic = "force-dynamic";diff --git a/apps/web/app/api/invite/accept/route.ts b/apps/web/app/api/invite/accept/route.tsindex 16d74c722..02576e7c2 100644--- a/apps/web/app/api/invite/accept/route.ts+++ b/apps/web/app/api/invite/accept/route.ts@@ -1,6 +1,7 @@import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";import { nanoId } from "@cap/database/helpers";+import { enqueueLoopsSync } from "@cap/database/loops/queue";import {organizationInvites,organizationMembers,@@ -149,6 +150,7 @@ export async function POST(request: NextRequest) {await tx.update(users).set(userUpdate).where(eq(users.id, user.id));+ await enqueueLoopsSync(tx, user.id, true);await tx.delete(organizationInvites).where(eq(organizationInvites.id, inviteId));diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.tsindex 2e34a900a..8ec560627 100644--- a/apps/web/app/api/webhooks/stripe/route.ts+++ b/apps/web/app/api/webhooks/stripe/route.ts@@ -2,6 +2,7 @@ import { db } from "@cap/database";import { sendEmail } from "@cap/database/emails/config";import { PaymentFailed } from "@cap/database/emails/payment-failed";import { nanoId } from "@cap/database/helpers";+import { enqueueLoopsSync } from "@cap/database/loops/queue";import {developerCreditTransactions,signedBaas,@@ -608,6 +609,7 @@ export const POST = async (req: Request) => {onboarding_completed_at: isOnBoarding ? new Date() : undefined,}).where(eq(users.id, dbUser.id));+ await enqueueLoopsSync(db(), dbUser.id);console.log("Successfully updated user in database");@@ -767,6 +769,7 @@ export const POST = async (req: Request) => {inviteQuota: inviteQuota,}).where(eq(users.id, dbUser.id));+ await enqueueLoopsSync(db(), dbUser.id);console.log("Successfully updated user in database with new invite quota:",@@ -942,6 +945,7 @@ export const POST = async (req: Request) => {inviteQuota: 1,}).where(eq(users.id, foundUserId));+ await enqueueLoopsSync(db(), foundUserId);console.log("User updated successfully", {foundUserId,diff --git a/apps/web/lib/organization-provisioning.ts b/apps/web/lib/organization-provisioning.tsindex fa31617ac..117f8e45c 100644--- a/apps/web/lib/organization-provisioning.ts+++ b/apps/web/lib/organization-provisioning.ts@@ -2,6 +2,7 @@ import "server-only";import { db } from "@cap/database";import { nanoId } from "@cap/database/helpers";+import { enqueueLoopsSync } from "@cap/database/loops/queue";import {organizationInvites,organizationMembers,@@ -49,7 +50,9 @@ export async function provisionOrganizationInvitee({const userId = existingUser?.id ?? User.UserId.make(nanoId());if (existingUser) {- const userUpdate: Partial<typeof users.$inferInsert> = {};+ const userUpdate: Partial<typeof users.$inferInsert> = {+ marketingOrigin: "teammate",+ };if (!existingUser.name) {userUpdate.name = getProvisionedUserName(normalizedEmail);@@ -68,12 +71,14 @@ export async function provisionOrganizationInvitee({await tx.insert(users).values({id: userId,email: normalizedEmail,+ marketingOrigin: "teammate",name: getProvisionedUserName(normalizedEmail),activeOrganizationId: organizationId,defaultOrgId: organizationId,});}+ await enqueueLoopsSync(tx, userId);const [existingMember] = await tx.select({id: organizationMembers.id,diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 0f8785435..8b04012a8 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -1,6 +1,7 @@{"$schema": "https://openapi.vercel.sh/vercel.json","crons": [+ { "path": "/api/cron/sync-loops", "schedule": "* * * * *" },{"path": "/api/cron/cleanup-agent-api","schedule": "17 3 * * *"diff --git a/emails/CATALOG.md b/emails/CATALOG.mdindex 3f29748ad..7d7450866 100644--- a/emails/CATALOG.md+++ b/emails/CATALOG.md@@ -13,7 +13,9 @@ These are the locally configured draft journeys. This document is not a live sta| [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.+Completed signups reach Loops through Stripe; SSO uses a small direct fallback. Cap supplies targeting through a durable sync queue, without a separate marketing opt-in step. Existing opt-outs and suppressions take precedence. The integration is not deployed. Historical imports stay held; a new accepted invitation can start teammate help only.++Current draft journeys require global subscription, capConsent=subscribed, the exact audience, lifecycle enabled and onboarding eligible. capConsent is a legacy migration guard, not a separate consent-capture requirement for new signups. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility.Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).@@ -112,7 +114,7 @@ flowchart TD## 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.+Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, capConsent=subscribed and their exact audience. The free template also requires promotional eligibility and excludes teammates.| Campaign | Audience | Subject and source | Loops ID || --- | --- | --- | --- |diff --git a/emails/QA.md b/emails/QA.mdindex 3c132ee07..55d9897c6 100644--- a/emails/QA.md+++ b/emails/QA.md@@ -43,7 +43,15 @@ The local suite checks consent precedence, suppression preservation, customer an## Remaining gate before switching-The deployed Cap signup/purchase/invite/opt-out path through an enrollment dispatcher and into an inbox has not been proven. The reviewed schema is not deployed, new explicit consent capture/enrollment and retry/deduplication dispatch need implementation, and the current sync intentionally keeps contacts held. Freshness expiry and scheduler monitoring are also required: an old `capVerifiedAt` value does not automatically prevent a Loops send.+The new implementation uses native Stripe imports, a held SSO fallback, and `loops_sync_jobs` for durable enrichment. Local routing tests cover missing Stripe imports, incomplete billing bootstrap, teammate persistence, an existing account accepting a new invite, global/list opt-outs, missing list membership, replay, identity conflicts and imported holds. The full email-script, profile and lifecycle suites passed 54 tests; existing SSO and Stripe subscription suites passed another 83. Database and web TypeScript checks passed.++Five integration checks passed on an isolated PlanetScale branch: transactional rollback, overlapping claims, expired lease recovery, newer work surviving an older completion, and an indexed due query. A full `db:push` attempt hit the repository's unrelated storage prefix-index quoting bug; the exact generated Loops migration was then applied and independently checked on the empty test branch. No production schema or data changed. The owned schema-only test branch was deleted after verification.++The worker was exercised from synthetic database records through the real Loops API, including a simulated HTTP 429 followed by a successful retry, free and SSO teammate classification, a free-to-teammate transition, and a later unsubscribe surviving a billing change. Separate live checks cover imported holds and list removals. Loops omits an API-removed list from the returned map; the runtime now treats missing membership as ineligible and never re-adds lists during updates. All owned test contacts were read back held and globally unsubscribed. These checks sent no email and kept production workflows in Draft.++The native Stripe integration is connected to Cap Software, Inc. and enabled for customer creation and updates only. A new owned live Stripe customer appeared in Loops; two later name changes updated that same contact. Name import and Product updates and tips list assignment were verified, and a global unsubscribe survived the final Stripe update. No payments, subscriptions or emails were created. The test contact remains held and globally unsubscribed. Both saved event mappings were checked after reload. A separate test-mode Stripe customer did not import through this live connection, is not counted as a passing native test, and was deleted after verification.++The deployed Cap signup/purchase/invite path has not yet been proven end to end. Production schema/code deployment, recipient Preference Center list-opt-out preservation across native Stripe updates, the final Bento suppression delta, and scheduler monitoring remain cutover gates. The Cap-worker API list-removal check above does not independently prove native Stripe handling of a recipient list opt-out. The worker retries failed updates, but Loops still uses the last successfully synced values during an outage; `capVerifiedAt` is not a native expiry rule.Follow the [cutover runbook](../scripts/loops/README.md#before-any-activation). Test that deployed path using owned inboxes, including outages and retries, before requesting production activation. Keep imported history held, preserve all opt-outs, reconcile fresh Bento changes, check Resend overlap and disable duplicate Bento automation only during the approved cutover.diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.tsindex 6efac175a..810b6b75e 100644--- a/packages/database/auth/drizzle-adapter.ts+++ b/packages/database/auth/drizzle-adapter.ts@@ -1,11 +1,11 @@import { createHash } from "node:crypto";-import { isProSubscription, STRIPE_AVAILABLE, stripe } from "@cap/utils";+import { STRIPE_AVAILABLE } from "@cap/utils";import { type ImageUpload, Organisation, User } from "@cap/web-domain";import { and, eq } from "drizzle-orm";import type { MySql2Database } from "drizzle-orm/mysql2";import type { Adapter } from "next-auth/adapters";-import type Stripe from "stripe";import { nanoId } from "../helpers.ts";+import { enqueueLoopsSync } from "../loops/queue.ts";import {accounts,organizationInvites,@@ -16,6 +16,7 @@ import {verificationTokens,} from "../schema.ts";import type { ValidatedSsoIdentity } from "./sso.ts";+import { provisionStripeCustomer } from "./stripe-customer.ts";type CreateUserData = Parameters<NonNullable<Adapter["createUser"]>>[0];type LinkAccountData = Parameters<NonNullable<Adapter["linkAccount"]>>[0];@@ -118,6 +119,7 @@ export function DrizzleAdapter(await tx.update(users).set(userUpdate).where(eq(users.id, userId));}+ await enqueueLoopsSync(tx, userId);return;}@@ -157,6 +159,7 @@ export function DrizzleAdapter(await insertUser;}+ await enqueueLoopsSync(tx, userId);if (pendingInvite || ssoIdentity) {return;}@@ -194,69 +197,7 @@ export function DrizzleAdapter(if (!row) throw new Error("User not found");if (STRIPE_AVAILABLE() && !ssoIdentity) {- const existingCustomers = await stripe().customers.list({- email: normalizedEmail,- limit: 1,- });-- let customer: Stripe.Customer;- if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {- customer = existingCustomers.data[0];-- customer = await stripe().customers.update(customer.id, {- metadata: {- ...customer.metadata,- userId: row.id,- },- });- } else {- customer = await stripe().customers.create({- email: normalizedEmail,- metadata: {- userId: row.id,- },- });- }-- const subscriptions = await stripe().subscriptions.list({- customer: customer.id,- status: "active",- limit: 100,- });-- const proSubscriptions = subscriptions.data.filter(isProSubscription);- const inviteQuota = proSubscriptions.reduce((total, sub) => {- return (- total +- sub.items.data.reduce(- (subTotal, item) => subTotal + (item.quantity || 1),- 0,- )- );- }, 0);-- const mostRecentSubscription = proSubscriptions[0];-- await db- .update(users)- .set({- stripeCustomerId: customer.id,- ...(mostRecentSubscription && {- stripeSubscriptionId: mostRecentSubscription.id,- stripeSubscriptionStatus: mostRecentSubscription.status,- inviteQuota: inviteQuota || 1,- }),- })- .where(eq(users.id, row.id));-- const [updatedRow] = await db- .select()- .from(users)- .where(eq(users.id, row.id))- .limit(1);- if (updatedRow) {- row = updatedRow;- }+ row = await provisionStripeCustomer(db, row);}return row;@@ -309,13 +250,16 @@ export function DrizzleAdapter(},async updateUser({ id, image, ...userData }) {if (!id) throw new Error("User not found");- await db- .update(users)- .set({- ...userData,- image: image as ImageUpload.ImageUrlOrKey | null,- })- .where(eq(users.id, User.UserId.make(id)));+ await db.transaction(async (tx) => {+ await tx+ .update(users)+ .set({+ ...userData,+ image: image as ImageUpload.ImageUrlOrKey | null,+ })+ .where(eq(users.id, User.UserId.make(id)));+ await enqueueLoopsSync(tx, User.UserId.make(id));+ });const rows = await db.select().from(users)diff --git a/packages/database/auth/sso.ts b/packages/database/auth/sso.tsindex 9d8429185..97b5047b0 100644--- a/packages/database/auth/sso.ts+++ b/packages/database/auth/sso.ts@@ -6,6 +6,7 @@ import { WorkOS } from "@workos-inc/node";import { and, eq, isNull } from "drizzle-orm";import { nanoId } from "../helpers.ts";import { db } from "../index.ts";+import { enqueueLoopsSync } from "../loops/queue.ts";import {accounts,organizationInvites,@@ -273,5 +274,10 @@ export async function provisionSsoMembership(},}).where(eq(users.id, userId));+ await enqueueLoopsSync(+ tx,+ userId,+ !member || !user.onboarding_completed_at,+ );});}diff --git a/packages/database/auth/stripe-customer.ts b/packages/database/auth/stripe-customer.tsnew file mode 100644index 000000000..91527d3c1--- /dev/null+++ b/packages/database/auth/stripe-customer.ts@@ -0,0 +1,84 @@+import { isProSubscription, stripe } from "@cap/utils";+import { eq } from "drizzle-orm";+import type { MySql2Database } from "drizzle-orm/mysql2";+import type Stripe from "stripe";+import { users } from "../schema";++export async function provisionStripeCustomer(+ db: MySql2Database,+ row: typeof users.$inferSelect,+) {+ const existingCustomers = await stripe().customers.list({+ email: row.email,+ limit: 1,+ });++ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];++ customer = await stripe().customers.update(customer.id, {+ ...(row.name?.trim()+ ? { name: [row.name, row.lastName].filter(Boolean).join(" ") }+ : {}),+ metadata: {+ ...customer.metadata,+ userId: row.id,+ },+ });+ } else {+ customer = await stripe().customers.create(+ {+ email: row.email,+ ...(row.name?.trim()+ ? { name: [row.name, row.lastName].filter(Boolean).join(" ") }+ : {}),+ metadata: {+ userId: row.id,+ },+ },+ { idempotencyKey: `cap-signup-${row.id}` },+ );+ }++ const subscriptions = await stripe().subscriptions.list({+ customer: customer.id,+ status: "active",+ limit: 100,+ });++ const proSubscriptions = subscriptions.data.filter(isProSubscription);+ const inviteQuota = proSubscriptions.reduce((total, sub) => {+ return (+ total ++ sub.items.data.reduce(+ (subTotal, item) => subTotal + (item.quantity || 1),+ 0,+ )+ );+ }, 0);++ const mostRecentSubscription = proSubscriptions[0];++ await db+ .update(users)+ .set({+ stripeCustomerId: customer.id,+ ...(mostRecentSubscription && {+ stripeSubscriptionId: mostRecentSubscription.id,+ stripeSubscriptionStatus: mostRecentSubscription.status,+ inviteQuota: inviteQuota || 1,+ }),+ })+ .where(eq(users.id, row.id));++ const [updatedRow] = await db+ .select()+ .from(users)+ .where(eq(users.id, row.id))+ .limit(1);+ if (updatedRow) {+ row = updatedRow;+ }+ return row;+}diff --git a/packages/database/loops/client.ts b/packages/database/loops/client.tsnew file mode 100644index 000000000..40ed72fd0--- /dev/null+++ b/packages/database/loops/client.ts@@ -0,0 +1,28 @@+export class LoopsRequestError extends Error {+ constructor(public status: number) {+ super(`Loops request failed (${status})`);+ }+}++export interface LoopsClient {+ request<T>(path: string, method?: string, body?: unknown): Promise<T>;+}++export function createLoopsClient(key: string): LoopsClient {+ if (!key) throw new Error("LOOPS_API_KEY is required");+ return {+ async request<T>(path: string, method = "GET", body?: unknown) {+ const response = await fetch(`https://app.loops.so/api/v1/${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${key}`,+ "Content-Type": "application/json",+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ signal: AbortSignal.timeout(10_000),+ });+ if (!response.ok) throw new LoopsRequestError(response.status);+ return (await response.json()) as T;+ },+ };+}diff --git a/packages/database/loops/lifecycle.ts b/packages/database/loops/lifecycle.tsnew file mode 100644index 000000000..5eb5d0fe1--- /dev/null+++ b/packages/database/loops/lifecycle.ts@@ -0,0 +1,99 @@+import {+ type ContactProfile,+ type CustomerCopy,+ classifyProfile,+ isoDate,+} from "./profile";+import type { LoopsProfileSource } from "./sources";+import type { RemoteContact } from "./sync-policy";++export type LifecycleContact = RemoteContact & {+ capImportedAt?: string;+ capConsent?: string;+ capLifecycleEnabled?: boolean;+ capSignupAt?: string;+};++export type LoopsRuntimeConfig = {+ listId: string;+ enrollmentAfter: Date;+ enrollmentEnabled: boolean;+ allowedEmails: Set<string> | null;+ teammateJoinedAt?: string | null;+};++export function lifecycleUpdate(+ source: LoopsProfileSource,+ remote: LifecycleContact,+ config: LoopsRuntimeConfig,+ customerCopy: CustomerCopy,+) {+ const profile = classifyProfile(source.input, customerCopy);+ if (+ remote.userId &&+ remote.userId !== profile.userId &&+ !remote.userId.startsWith("bento:")+ )+ throw new Error("identity_conflict");+ const teammate = profile.capTeammate || remote.capTeammate === true;+ const audience = teammate ? "teammate" : profile.capAudience;+ const globallySubscribed =+ remote.subscribed &&+ !["unsubscribed", "suppressed"].includes(remote.capConsent ?? "");+ const subscribed =+ globallySubscribed && remote.mailingLists[config.listId] === true;+ const recentSignup =+ Date.parse(profile.capSignupAt) >= config.enrollmentAfter.getTime();+ const imported = Boolean(remote.capImportedAt);+ const recentJoin =+ teammate &&+ Boolean(config.teammateJoinedAt) &&+ Date.parse(isoDate(config.teammateJoinedAt ?? "")) >=+ config.enrollmentAfter.getTime();+ const eligible =+ config.enrollmentEnabled &&+ source.signedUp &&+ subscribed &&+ !source.pendingInvite &&+ ((!imported && recentSignup) || recentJoin) &&+ audience !== "unknown";+ const {+ subscribed: _subscribed,+ capImportedAt: _imported,+ source: _source,+ capSourceTags: _tags,+ capSourceGroup: _group,+ ...attributes+ } = profile;+ return {+ ...attributes,+ capTeammate: teammate,+ capAudience: audience,+ capOrigin: teammate ? "teammate" : profile.capOrigin,+ capConsent: globallySubscribed+ ? "subscribed"+ : remote.capConsent === "suppressed"+ ? "suppressed"+ : "unsubscribed",+ capPromotionalEligible:+ subscribed && !teammate && profile.capPromotionalEligible,+ capLifecycleEnabled: eligible,+ capOnboardingEligible: eligible,+ capLifecycleStage: eligible ? audience : "idle",+ };+}++export function nextProfileCheck(+ profile: Pick<ContactProfile, "capSignupAt">,+ now: Date,+) {+ const age = now.getTime() - Date.parse(isoDate(profile.capSignupAt));+ return new Date(+ now.getTime() ++ (age < 16 * 24 * 60 * 60_000 ? 60 * 60_000 : 24 * 60 * 60_000),+ );+}++export function retryDelay(failures: number) {+ return Math.min(60 * 60_000, 30_000 * 2 ** Math.min(failures, 7));+}diff --git a/packages/database/loops/profile.ts b/packages/database/loops/profile.tsnew file mode 100644index 000000000..5adf8bbfb--- /dev/null+++ b/packages/database/loops/profile.ts@@ -0,0 +1,192 @@+import { createHash } from "node:crypto";+export type CustomerCopy = Record<+ "pro" | "selfhosted" | "desktop" | "other",+ { plan: string; welcome: string }+>;++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,+ customerCopy: CustomerCopy,+) {+ 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 copy =+ customerCopy[+ directCustomer+ ? "pro"+ : activeLicenses.some((license) => license.kind === "selfhosted")+ ? "selfhosted"+ : activeLicenses.length+ ? "desktop"+ : "other"+ ];+ const firstName =+ [source.first_name, source.firstname, user?.name?.trim().split(/\s+/)[0]]+ .map((value) => value?.trim())+ .find((value) => value && value.toLowerCase() !== "null") ?? "";+ return {+ email: normalizeEmail(source.email),+ userId: user?.id ?? `bento:${emailHash(source.email)}`,+ firstName,+ capGreeting: firstName ? `Hey ${firstName},` : "Hey,",+ lastName:+ [source.last_name, source.lastname, user?.lastName]+ .map((value) => value?.trim())+ .find((value) => value && value !== "null") ?? "",+ subscribed: consent === "subscribed",+ source: "Bento migration",+ capAudience: audience,+ capOrigin: teammate ? "teammate" : independent ? "independent" : "unknown",+ capConsent: consent,+ capTeammate: teammate,+ capCustomer: customer,+ capPlanName: copy.plan,+ capCustomerWelcome: copy.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/packages/database/loops/queue.ts b/packages/database/loops/queue.tsnew file mode 100644index 000000000..06141f22c--- /dev/null+++ b/packages/database/loops/queue.ts@@ -0,0 +1,26 @@+import type { User } from "@cap/web-domain";+import { sql } from "drizzle-orm";+import type { MySql2Database } from "drizzle-orm/mysql2";+import { loopsSyncJobs } from "../schema";++export async function enqueueLoopsSync(+ database: Pick<MySql2Database, "insert">,+ userId: User.UserId,+ teammateJoined = false,+) {+ if (process.env.LOOPS_SYNC_ENABLED !== "true") return;+ await database+ .insert(loopsSyncJobs)+ .values({+ userId,+ nextAttemptAt: sql`UTC_TIMESTAMP()`,+ ...(teammateJoined ? { teammateJoinedAt: sql`UTC_TIMESTAMP()` } : {}),+ })+ .onDuplicateKeyUpdate({+ set: {+ revision: sql`${loopsSyncJobs.revision} + 1`,+ nextAttemptAt: sql`UTC_TIMESTAMP()`,+ ...(teammateJoined ? { teammateJoinedAt: sql`UTC_TIMESTAMP()` } : {}),+ },+ });+}diff --git a/packages/database/loops/sources.ts b/packages/database/loops/sources.tsnew file mode 100644index 000000000..b552ca56a--- /dev/null+++ b/packages/database/loops/sources.ts@@ -0,0 +1,78 @@+import type { Connection, RowDataPacket } from "mysql2/promise";+import type { CapUser, License, Membership, ProfileInput } from "./profile";++type RuntimeUser = CapUser & {+ emailVerified: string | null;+ stripeCustomerId: string | null;+};++export type LoopsProfileSource = {+ input: ProfileInput & { user: CapUser };+ signedUp: boolean;+ pendingInvite: boolean;+ stripeCustomerId: string | null;+};++async function rows<T>(database: Connection, query: string, values: string[]) {+ const [result] = await database.execute<(RowDataPacket & T)[]>(query, values);+ return result;+}++export async function readLoopsProfile(+ cap: Connection,+ licenses: Connection,+ userId: string,+): Promise<LoopsProfileSource | null> {+ const [user] = await rows<RuntimeUser>(+ cap,+ "SELECT id,email,name,lastName,emailVerified,stripeCustomerId,stripeSubscriptionStatus,thirdPartyStripeSubscriptionId,created_at,defaultOrgId,marketingOrigin FROM users WHERE id=?",+ [userId],+ );+ if (!user) return null;+ 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 WHERE m.userId=?",+ [userId],+ );+ const accounts = await rows<{ provider: string }>(+ cap,+ "SELECT provider FROM accounts WHERE userId=?",+ [userId],+ );+ const invites = await rows<{ status: string }>(+ cap,+ "SELECT status FROM organization_invites WHERE invitedEmail=? AND status IN ('pending','accepted')",+ [user.email],+ );+ const [video] = await rows<{ id: string }>(+ cap,+ "SELECT id FROM videos WHERE ownerId=? LIMIT 1",+ [userId],+ );+ const [shared] = await rows<{ id: string }>(+ cap,+ "SELECT id FROM videos WHERE ownerId=? AND public=1 LIMIT 1",+ [userId],+ );+ const entitlement = await rows<License>(+ licenses,+ "SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'desktop' AS kind FROM commercialLicenses l JOIN user u ON u.id=l.userId WHERE u.email=? UNION ALL SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'selfhosted' AS kind FROM selfHostedLicenses l JOIN user u ON u.id=l.userId WHERE u.email=?",+ [user.email, user.email],+ );+ return {+ input: {+ source: { email: user.email },+ user,+ memberships,+ licenses: entitlement,+ invited: invites.length > 0,+ sso: accounts.some((account) => account.provider === "workos"),+ hasVideo: Boolean(video),+ hasSharedVideo: Boolean(shared),+ now: new Date(),+ },+ signedUp: Boolean(user.emailVerified || accounts.length),+ pendingInvite: invites.some((invite) => invite.status === "pending"),+ stripeCustomerId: user.stripeCustomerId,+ };+}diff --git a/packages/database/loops/sync-policy.ts b/packages/database/loops/sync-policy.tsnew file mode 100644index 000000000..346d8d8f2--- /dev/null+++ b/packages/database/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/packages/database/loops/worker.ts b/packages/database/loops/worker.tsnew file mode 100644index 000000000..69fbffa15--- /dev/null+++ b/packages/database/loops/worker.ts@@ -0,0 +1,304 @@+import { createHash, randomUUID } from "node:crypto";+import { STRIPE_AVAILABLE } from "@cap/utils";+import { User } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";+import { provisionStripeCustomer } from "../auth/stripe-customer";+import { db } from "../index";+import { users } from "../schema";+import {+ createLoopsClient,+ type LoopsClient,+ LoopsRequestError,+} from "./client";+import {+ type LifecycleContact,+ type LoopsRuntimeConfig,+ lifecycleUpdate,+ nextProfileCheck,+ retryDelay,+} from "./lifecycle";+import { type CustomerCopy, classifyProfile, normalizeEmail } from "./profile";+import { type LoopsProfileSource, readLoopsProfile } from "./sources";+import { profileFingerprint } from "./sync-policy";++type Job = RowDataPacket & {+ userId: string;+ revision: number;+ failures: number;+ syncedEmail: string | null;+ lastSyncedAt: string | null;+ profileHash: string | null;+ teammateJoinedAt: string | null;+};++export async function syncLoopsContact(+ api: LoopsClient,+ source: LoopsProfileSource,+ previous: { syncedEmail: string | null; lastSyncedAt: string | null },+ config: LoopsRuntimeConfig,+ customerCopy: CustomerCopy,+) {+ const email = normalizeEmail(source.input.source.email);+ if (config.allowedEmails && !config.allowedEmails.has(email))+ throw new Error("outside_test_allowlist");+ if (!source.signedUp) throw new Error("signup_not_complete");+ if (!source.input.sso && !source.stripeCustomerId)+ throw new Error("stripe_signup_not_complete");+ if (previous.syncedEmail && previous.syncedEmail !== email)+ throw new Error("email_changed_requires_reconciliation");+ const contacts = await api.request<LifecycleContact[]>(+ `contacts/find?email=${encodeURIComponent(email)}`,+ );+ if (contacts.length > 1) throw new Error("ambiguous_contact");+ let remote = contacts[0];+ if (!remote) {+ if (previous.lastSyncedAt) throw new Error("remote_contact_removed");+ if (!source.input.sso) throw new Error("awaiting_stripe_contact");+ await api.request("contacts/create", "POST", {+ email,+ mailingLists: { [config.listId]: true },+ userId: source.input.user?.id,+ source: "Cap SSO signup",+ capTeammate: true,+ capAudience: "teammate",+ capPromotionalEligible: false,+ capOnboardingEligible: false,+ capLifecycleEnabled: false,+ capLifecycleStage: "idle",+ });+ const created = await api.request<LifecycleContact[]>(+ `contacts/find?email=${encodeURIComponent(email)}`,+ );+ if (created.length !== 1) throw new Error("created_contact_not_found");+ remote = created[0];+ }+ const update = lifecycleUpdate(source, remote, config, customerCopy);+ await api.request("contacts/update", "PUT", update);+ return update;+}++async function holdRemovedIdentity(+ api: LoopsClient,+ email: string,+ userId: string,+) {+ const contacts = await api.request<LifecycleContact[]>(+ `contacts/find?email=${encodeURIComponent(email)}`,+ );+ if (contacts.length > 1) throw new Error("ambiguous_contact");+ const contact = contacts[0];+ if (!contact) return;+ if (contact.userId && contact.userId !== userId)+ throw new Error("identity_conflict");+ await api.request("contacts/update", "PUT", {+ email,+ subscribed: false,+ capPromotionalEligible: false,+ capLifecycleEnabled: false,+ capOnboardingEligible: false,+ capLifecycleStage: "idle",+ });+}++export async function claimJob(+ database: Connection,+ token: string,+ allowedUserIds: string[] | null,+) {+ await database.beginTransaction();+ try {+ const [jobs] = await database.query<Job[]>(+ `SELECT * FROM loops_sync_jobs WHERE nextAttemptAt<=UTC_TIMESTAMP() AND (leaseUntil IS NULL OR leaseUntil<UTC_TIMESTAMP()) ${allowedUserIds ? "AND userId IN (?)" : ""} ORDER BY nextAttemptAt LIMIT 1 FOR UPDATE SKIP LOCKED`,+ allowedUserIds ? [allowedUserIds] : [],+ );+ const job = jobs[0];+ if (job)+ await database.execute(+ "UPDATE loops_sync_jobs SET leaseToken=?,leaseUntil=DATE_ADD(UTC_TIMESTAMP(),INTERVAL 2 MINUTE) WHERE userId=?",+ [token, job.userId],+ );+ await database.commit();+ return job;+ } catch (error) {+ await database.rollback();+ throw error;+ }+}++export function loopsRuntimeConfig(env: NodeJS.ProcessEnv): LoopsRuntimeConfig {+ const listId = env.LOOPS_MAILING_LIST_ID;+ const enrollmentAfter = new Date(env.LOOPS_ENROLLMENT_AFTER ?? "");+ if (!listId || !Number.isFinite(enrollmentAfter.getTime()))+ throw new Error("Loops list and cutover date are required");+ const production = env.LOOPS_SYNC_MODE === "production";+ const allowedEmails = production+ ? null+ : new Set(+ (env.LOOPS_TEST_EMAILS ?? "")+ .split(",")+ .map(normalizeEmail)+ .filter(Boolean),+ );+ if (allowedEmails && !allowedEmails.size)+ throw new Error("Test mode requires LOOPS_TEST_EMAILS");+ return {+ listId,+ enrollmentAfter,+ allowedEmails,+ enrollmentEnabled: env.LOOPS_ENROLLMENT_ENABLED === "true",+ };+}++export async function runLoopsSync(customerCopy: CustomerCopy) {+ if (process.env.LOOPS_SYNC_ENABLED !== "true")+ return { enabled: false, processed: 0, failed: 0 };+ const config = loopsRuntimeConfig(process.env);+ const capUrl = process.env.DATABASE_URL;+ const licenseUrl = process.env.LOOPS_LICENSE_DATABASE_URL;+ if (!capUrl || !licenseUrl)+ throw new Error("Loops source databases are required");+ const api = createLoopsClient(process.env.LOOPS_API_KEY ?? "");+ const identity = await api.request<{ success: boolean; teamName: string }>(+ "api-key",+ );+ if (!identity.success || identity.teamName !== "Cap Software, Inc.")+ throw new Error("Wrong Loops team");+ const cap = await mysql.createConnection({+ uri: capUrl,+ dateStrings: true,+ timezone: "Z",+ });+ let processed = 0;+ let failed = 0;+ try {+ const license = await mysql.createConnection({+ uri: licenseUrl,+ dateStrings: true,+ timezone: "Z",+ });+ try {+ let allowedUserIds: string[] | null = null;+ if (config.allowedEmails) {+ const [owned] = await cap.query<(RowDataPacket & { id: string })[]>(+ "SELECT id FROM users WHERE email IN (?)",+ [[...config.allowedEmails]],+ );+ allowedUserIds = owned.map((user) => user.id);+ if (!allowedUserIds.length) return { enabled: true, processed, failed };+ }+ const deadline = Date.now() + 40_000;+ while (processed + failed < 500 && Date.now() < deadline) {+ const token = randomUUID();+ const job = await claimJob(cap, token, allowedUserIds);+ if (!job) break;+ try {+ let source = await readLoopsProfile(cap, license, job.userId);+ if (+ job.syncedEmail &&+ (!source ||+ normalizeEmail(source.input.source.email) !== job.syncedEmail)+ ) {+ await holdRemovedIdentity(api, job.syncedEmail, job.userId);+ throw new Error("identity_change_held");+ }+ if (!source) throw new Error("user_removed");+ if (+ source.signedUp &&+ !source.input.sso &&+ !source.stripeCustomerId &&+ STRIPE_AVAILABLE()+ ) {+ const [user] = await db()+ .select()+ .from(users)+ .where(eq(users.id, User.UserId.make(job.userId)))+ .limit(1);+ if (!user) throw new Error("user_removed");+ await provisionStripeCustomer(db(), user);+ source = await readLoopsProfile(cap, license, job.userId);+ if (!source) throw new Error("user_removed");+ }+ const localProfile = classifyProfile(source.input, customerCopy);+ const jobConfig = {+ ...config,+ teammateJoinedAt: job.teammateJoinedAt,+ };+ const hash = createHash("sha256")+ .update(+ JSON.stringify({+ profile: profileFingerprint(localProfile),+ signedUp: source.signedUp,+ pendingInvite: source.pendingInvite,+ enrollmentEnabled: config.enrollmentEnabled,+ enrollmentAfter: config.enrollmentAfter.toISOString(),+ listId: config.listId,+ teammateJoinedAt: job.teammateJoinedAt,+ }),+ )+ .digest("hex");+ if (job.profileHash === hash) {+ await cap.execute(+ "UPDATE loops_sync_jobs SET nextAttemptAt=CASE WHEN revision=? THEN ? ELSE UTC_TIMESTAMP() END,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",+ [+ job.revision,+ nextProfileCheck(localProfile, new Date()),+ job.userId,+ token,+ ],+ );+ processed++;+ continue;+ }+ const update = await syncLoopsContact(+ api,+ source,+ job,+ jobConfig,+ customerCopy,+ );+ if (update.capTeammate)+ await cap.execute(+ "UPDATE users SET marketingOrigin='teammate' WHERE id=? AND marketingOrigin<>'teammate'",+ [job.userId],+ );+ const next = nextProfileCheck(update, new Date());+ await cap.execute(+ "UPDATE loops_sync_jobs SET syncedEmail=?,profileHash=?,lastSyncedAt=UTC_TIMESTAMP(),failures=0,lastError=NULL,nextAttemptAt=CASE WHEN revision=? THEN ? ELSE UTC_TIMESTAMP() END,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",+ [update.email, hash, job.revision, next, job.userId, token],+ );+ processed++;+ } catch (error) {+ const reason =+ error instanceof LoopsRequestError+ ? `loops_http_${error.status}`+ : error instanceof Error && /^[a-z_]+$/.test(error.message)+ ? error.message+ : "sync_failed";+ await cap.execute(+ "UPDATE loops_sync_jobs SET failures=failures+1,lastError=?,nextAttemptAt=?,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",+ [+ reason,+ new Date(Date.now() + retryDelay(job.failures)),+ job.userId,+ token,+ ],+ );+ console.error("Loops sync deferred", { userId: job.userId, reason });+ failed++;+ if (+ error instanceof LoopsRequestError &&+ [401, 403, 429].includes(error.status)+ )+ break;+ }+ await new Promise((resolve) => setTimeout(resolve, 750));+ }+ return { enabled: true, processed, failed };+ } finally {+ await license.end();+ }+ } finally {+ await cap.end();+ }+}diff --git a/packages/database/migrations/0044_awesome_sugar_man.sql b/packages/database/migrations/0044_awesome_sugar_man.sqlnew file mode 100644index 000000000..46ed3b0d5--- /dev/null+++ b/packages/database/migrations/0044_awesome_sugar_man.sql@@ -0,0 +1,16 @@+CREATE TABLE `loops_sync_jobs` (+ `userId` varchar(15) NOT NULL,+ `revision` int NOT NULL DEFAULT 1,+ `nextAttemptAt` datetime NOT NULL,+ `leaseToken` varchar(36),+ `leaseUntil` datetime,+ `failures` int NOT NULL DEFAULT 0,+ `lastError` varchar(64),+ `profileHash` varchar(64),+ `syncedEmail` varchar(255),+ `lastSyncedAt` datetime,+ CONSTRAINT `loops_sync_jobs_userId` PRIMARY KEY(`userId`)+);+--> statement-breakpoint+ALTER TABLE `users` ADD `marketingOrigin` varchar(20) DEFAULT 'unknown' NOT NULL;--> statement-breakpoint+CREATE INDEX `loops_sync_due_idx` ON `loops_sync_jobs` (`nextAttemptAt`);\ No newline at end of filediff --git a/packages/database/migrations/0044_calm_boomer.sql b/packages/database/migrations/0044_calm_boomer.sqldeleted file mode 100644index b8858446e..000000000--- a/packages/database/migrations/0044_calm_boomer.sql+++ /dev/null@@ -1,19 +0,0 @@-CREATE TABLE `marketing_contacts` (- `emailHash` varchar(64) NOT NULL,- `email` varchar(255),- `userId` varchar(15),- `consent` varchar(20) NOT NULL DEFAULT 'unknown',- `source` varchar(64) NOT NULL,- `teammate` boolean NOT NULL DEFAULT false,- `imported` boolean NOT NULL DEFAULT false,- `lastAudience` varchar(20),- `lastProfileHash` varchar(64),- `lastSyncedAt` datetime,- `createdAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,- `updatedAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,- CONSTRAINT `marketing_contacts_emailHash` PRIMARY KEY(`emailHash`)-);---> statement-breakpoint-ALTER TABLE `users` ADD `marketingOrigin` varchar(20) DEFAULT 'unknown' NOT NULL;--> statement-breakpoint-CREATE INDEX `marketing_contacts_user_idx` ON `marketing_contacts` (`userId`);--> statement-breakpoint-CREATE INDEX `marketing_contacts_sync_idx` ON `marketing_contacts` (`lastSyncedAt`);\ No newline at end of filediff --git a/packages/database/migrations/0045_steep_forge.sql b/packages/database/migrations/0045_steep_forge.sqlnew file mode 100644index 000000000..311096962--- /dev/null+++ b/packages/database/migrations/0045_steep_forge.sql@@ -0,0 +1 @@+ALTER TABLE `loops_sync_jobs` ADD `teammateJoinedAt` datetime;\ No newline at end of filediff --git a/packages/database/migrations/meta/0044_snapshot.json b/packages/database/migrations/meta/0044_snapshot.jsonindex ecab166a4..d74a921ee 100644--- a/packages/database/migrations/meta/0044_snapshot.json+++ b/packages/database/migrations/meta/0044_snapshot.json@@ -1,7 +1,7 @@{"version": "5","dialect": "mysql",- "id": "8f4bc716-0a33-41e4-b769-cdb52046264d",+ "id": "391928e7-ff33-46e9-8786-670008cee581","prevId": "abd5c5ee-0381-4c1d-a6c7-257c04d094ed","tables": {"accounts": {@@ -1694,116 +1694,94 @@"uniqueConstraints": {},"checkConstraint": {}},- "marketing_contacts": {- "name": "marketing_contacts",+ "loops_sync_jobs": {+ "name": "loops_sync_jobs","columns": {- "emailHash": {- "name": "emailHash",- "type": "varchar(64)",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },- "email": {- "name": "email",- "type": "varchar(255)",- "primaryKey": false,- "notNull": false,- "autoincrement": false- },"userId": {"name": "userId","type": "varchar(15)","primaryKey": false,- "notNull": false,+ "notNull": true,"autoincrement": false},- "consent": {- "name": "consent",- "type": "varchar(20)",+ "revision": {+ "name": "revision",+ "type": "int","primaryKey": false,"notNull": true,"autoincrement": false,- "default": "'unknown'"+ "default": 1},- "source": {- "name": "source",- "type": "varchar(64)",+ "nextAttemptAt": {+ "name": "nextAttemptAt",+ "type": "datetime","primaryKey": false,"notNull": true,"autoincrement": false},- "teammate": {- "name": "teammate",- "type": "boolean",+ "leaseToken": {+ "name": "leaseToken",+ "type": "varchar(36)","primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": false+ "notNull": false,+ "autoincrement": false},- "imported": {- "name": "imported",- "type": "boolean",+ "leaseUntil": {+ "name": "leaseUntil",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failures": {+ "name": "failures",+ "type": "int","primaryKey": false,"notNull": true,"autoincrement": false,- "default": false+ "default": 0},- "lastAudience": {- "name": "lastAudience",- "type": "varchar(20)",+ "lastError": {+ "name": "lastError",+ "type": "varchar(64)","primaryKey": false,"notNull": false,"autoincrement": false},- "lastProfileHash": {- "name": "lastProfileHash",+ "profileHash": {+ "name": "profileHash","type": "varchar(64)","primaryKey": false,"notNull": false,"autoincrement": false},- "lastSyncedAt": {- "name": "lastSyncedAt",- "type": "datetime",+ "syncedEmail": {+ "name": "syncedEmail",+ "type": "varchar(255)","primaryKey": false,"notNull": false,"autoincrement": false},- "createdAt": {- "name": "createdAt",- "type": "datetime",- "primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"- },- "updatedAt": {- "name": "updatedAt",+ "lastSyncedAt": {+ "name": "lastSyncedAt","type": "datetime","primaryKey": false,- "notNull": true,- "autoincrement": false,- "default": "CURRENT_TIMESTAMP"+ "notNull": false,+ "autoincrement": false}},"indexes": {- "marketing_contacts_user_idx": {- "name": "marketing_contacts_user_idx",- "columns": ["userId"],- "isUnique": false- },- "marketing_contacts_sync_idx": {- "name": "marketing_contacts_sync_idx",- "columns": ["lastSyncedAt"],+ "loops_sync_due_idx": {+ "name": "loops_sync_due_idx",+ "columns": ["nextAttemptAt"],"isUnique": false}},"foreignKeys": {},"compositePrimaryKeys": {- "marketing_contacts_emailHash": {- "name": "marketing_contacts_emailHash",- "columns": ["emailHash"]+ "loops_sync_jobs_userId": {+ "name": "loops_sync_jobs_userId",+ "columns": ["userId"]}},"uniqueConstraints": {},diff --git a/packages/database/migrations/meta/0045_snapshot.json b/packages/database/migrations/meta/0045_snapshot.jsonnew file mode 100644index 000000000..e22f9b795--- /dev/null+++ b/packages/database/migrations/meta/0045_snapshot.json@@ -0,0 +1,4575 @@+{+ "version": "5",+ "dialect": "mysql",+ "id": "0d80e4e5-6d93-4d28-b235-bf1231baa7a9",+ "prevId": "391928e7-ff33-46e9-8786-670008cee581",+ "tables": {+ "accounts": {+ "name": "accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerAccountId": {+ "name": "providerAccountId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_in": {+ "name": "expires_in",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_in": {+ "name": "refresh_token_expires_in",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "tempColumn": {+ "name": "tempColumn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_id_idx": {+ "name": "user_id_idx",+ "columns": ["userId"],+ "isUnique": false+ },+ "provider_account_id_idx": {+ "name": "provider_account_id_idx",+ "columns": ["providerAccountId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "accounts_id": {+ "name": "accounts_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_api_authorization_codes": {+ "name": "agent_api_authorization_codes",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "codeHash": {+ "name": "codeHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "codeChallenge": {+ "name": "codeChallenge",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "redirectUri": {+ "name": "redirectUri",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scopes": {+ "name": "scopes",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "consumedAt": {+ "name": "consumedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "code_hash_idx": {+ "name": "code_hash_idx",+ "columns": ["codeHash"],+ "isUnique": true+ },+ "expires_at_idx": {+ "name": "expires_at_idx",+ "columns": ["expiresAt"],+ "isUnique": false+ },+ "user_created_at_idx": {+ "name": "user_created_at_idx",+ "columns": ["userId", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "agent_api_authorization_codes_id": {+ "name": "agent_api_authorization_codes_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_api_idempotency": {+ "name": "agent_api_idempotency",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "operation": {+ "name": "operation",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyHash": {+ "name": "keyHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "requestHash": {+ "name": "requestHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "statusCode": {+ "name": "statusCode",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "response": {+ "name": "response",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "user_operation_key_idx": {+ "name": "user_operation_key_idx",+ "columns": ["userId", "operation", "keyHash"],+ "isUnique": true+ },+ "expires_at_idx": {+ "name": "expires_at_idx",+ "columns": ["expiresAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "agent_api_idempotency_id": {+ "name": "agent_api_idempotency_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_api_keys": {+ "name": "agent_api_keys",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tokenHash": {+ "name": "tokenHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(100)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'Cap CLI'"+ },+ "scopes": {+ "name": "scopes",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revokedAt": {+ "name": "revokedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "lastUsedAt": {+ "name": "lastUsedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "token_hash_idx": {+ "name": "token_hash_idx",+ "columns": ["tokenHash"],+ "isUnique": true+ },+ "user_created_at_idx": {+ "name": "user_created_at_idx",+ "columns": ["userId", "createdAt"],+ "isUnique": false+ },+ "expires_at_idx": {+ "name": "expires_at_idx",+ "columns": ["expiresAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "agent_api_keys_id": {+ "name": "agent_api_keys_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "agent_api_operations": {+ "name": "agent_api_operations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resourceId": {+ "name": "resourceId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "resultResourceId": {+ "name": "resultResourceId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'queued'"+ },+ "payload": {+ "name": "payload",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "result": {+ "name": "result",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "errorCode": {+ "name": "errorCode",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "errorMessage": {+ "name": "errorMessage",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "completedAt": {+ "name": "completedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_created_at_idx": {+ "name": "user_created_at_idx",+ "columns": ["userId", "createdAt"],+ "isUnique": false+ },+ "state_updated_at_idx": {+ "name": "state_updated_at_idx",+ "columns": ["state", "updatedAt"],+ "isUnique": false+ },+ "resource_id_idx": {+ "name": "resource_id_idx",+ "columns": ["resourceId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "agent_api_operations_id": {+ "name": "agent_api_operations_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "auth_api_keys": {+ "name": "auth_api_keys",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(36)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "user_id_created_at_idx": {+ "name": "user_id_created_at_idx",+ "columns": ["userId", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "auth_api_keys_id": {+ "name": "auth_api_keys_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "comments": {+ "name": "comments",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(6)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "float",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "authorId": {+ "name": "authorId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "videoId": {+ "name": "videoId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "parentCommentId": {+ "name": "parentCommentId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mediaKey": {+ "name": "mediaKey",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mediaDuration": {+ "name": "mediaDuration",+ "type": "float",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mediaMeta": {+ "name": "mediaMeta",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "video_type_created_idx": {+ "name": "video_type_created_idx",+ "columns": ["videoId", "type", "createdAt", "id"],+ "isUnique": false+ },+ "author_id_idx": {+ "name": "author_id_idx",+ "columns": ["authorId"],+ "isUnique": false+ },+ "parent_comment_id_idx": {+ "name": "parent_comment_id_idx",+ "columns": ["parentCommentId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "comments_id": {+ "name": "comments_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "developer_api_keys": {+ "name": "developer_api_keys",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "appId": {+ "name": "appId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyType": {+ "name": "keyType",+ "type": "varchar(8)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyPrefix": {+ "name": "keyPrefix",+ "type": "varchar(12)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyHash": {+ "name": "keyHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "encryptedKey": {+ "name": "encryptedKey",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "lastUsedAt": {+ "name": "lastUsedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "revokedAt": {+ "name": "revokedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "key_hash_idx": {+ "name": "key_hash_idx",+ "columns": ["keyHash"],+ "isUnique": true+ },+ "app_key_type_idx": {+ "name": "app_key_type_idx",+ "columns": ["appId", "keyType"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "developer_api_keys_appId_developer_apps_id_fk": {+ "name": "developer_api_keys_appId_developer_apps_id_fk",+ "tableFrom": "developer_api_keys",+ "tableTo": "developer_apps",+ "columnsFrom": ["appId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_api_keys_id": {+ "name": "developer_api_keys_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "developer_app_domains": {+ "name": "developer_app_domains",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "appId": {+ "name": "appId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "varchar(253)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "developer_app_domains_appId_developer_apps_id_fk": {+ "name": "developer_app_domains_appId_developer_apps_id_fk",+ "tableFrom": "developer_app_domains",+ "tableTo": "developer_apps",+ "columnsFrom": ["appId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_app_domains_id": {+ "name": "developer_app_domains_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {+ "app_domain_unique": {+ "name": "app_domain_unique",+ "columns": ["appId", "domain"]+ }+ },+ "checkConstraint": {}+ },+ "developer_apps": {+ "name": "developer_apps",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "environment": {+ "name": "environment",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logoUrl": {+ "name": "logoUrl",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deletedAt": {+ "name": "deletedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "owner_deleted_idx": {+ "name": "owner_deleted_idx",+ "columns": ["ownerId", "deletedAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "developer_apps_id": {+ "name": "developer_apps_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "developer_credit_accounts": {+ "name": "developer_credit_accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "appId": {+ "name": "appId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "balanceMicroCredits": {+ "name": "balanceMicroCredits",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripePaymentMethodId": {+ "name": "stripePaymentMethodId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "autoTopUpEnabled": {+ "name": "autoTopUpEnabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "autoTopUpThresholdMicroCredits": {+ "name": "autoTopUpThresholdMicroCredits",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "autoTopUpAmountCents": {+ "name": "autoTopUpAmountCents",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "app_id_unique": {+ "name": "app_id_unique",+ "columns": ["appId"],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "developer_credit_accounts_appId_developer_apps_id_fk": {+ "name": "developer_credit_accounts_appId_developer_apps_id_fk",+ "tableFrom": "developer_credit_accounts",+ "tableTo": "developer_apps",+ "columnsFrom": ["appId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_credit_accounts_id": {+ "name": "developer_credit_accounts_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "developer_credit_transactions": {+ "name": "developer_credit_transactions",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "accountId": {+ "name": "accountId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "amountMicroCredits": {+ "name": "amountMicroCredits",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "balanceAfterMicroCredits": {+ "name": "balanceAfterMicroCredits",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "referenceId": {+ "name": "referenceId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "referenceType": {+ "name": "referenceType",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "account_type_created_idx": {+ "name": "account_type_created_idx",+ "columns": ["accountId", "type", "createdAt"],+ "isUnique": false+ },+ "account_ref_dedup_idx": {+ "name": "account_ref_dedup_idx",+ "columns": ["accountId", "referenceId", "referenceType"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "dev_credit_txn_account_fk": {+ "name": "dev_credit_txn_account_fk",+ "tableFrom": "developer_credit_transactions",+ "tableTo": "developer_credit_accounts",+ "columnsFrom": ["accountId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_credit_transactions_id": {+ "name": "developer_credit_transactions_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "developer_daily_storage_snapshots": {+ "name": "developer_daily_storage_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "appId": {+ "name": "appId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "snapshotDate": {+ "name": "snapshotDate",+ "type": "varchar(10)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "totalDurationMinutes": {+ "name": "totalDurationMinutes",+ "type": "float",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "videoCount": {+ "name": "videoCount",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "microCreditsCharged": {+ "name": "microCreditsCharged",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "processedAt": {+ "name": "processedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "developer_daily_storage_snapshots_appId_developer_apps_id_fk": {+ "name": "developer_daily_storage_snapshots_appId_developer_apps_id_fk",+ "tableFrom": "developer_daily_storage_snapshots",+ "tableTo": "developer_apps",+ "columnsFrom": ["appId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_daily_storage_snapshots_id": {+ "name": "developer_daily_storage_snapshots_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {+ "app_date_unique": {+ "name": "app_date_unique",+ "columns": ["appId", "snapshotDate"]+ }+ },+ "checkConstraint": {}+ },+ "developer_videos": {+ "name": "developer_videos",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "appId": {+ "name": "appId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "externalUserId": {+ "name": "externalUserId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'Untitled'"+ },+ "duration": {+ "name": "duration",+ "type": "float",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "width": {+ "name": "width",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fps": {+ "name": "fps",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "s3Key": {+ "name": "s3Key",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "transcriptionStatus": {+ "name": "transcriptionStatus",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deletedAt": {+ "name": "deletedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "app_created_idx": {+ "name": "app_created_idx",+ "columns": ["appId", "createdAt"],+ "isUnique": false+ },+ "app_user_idx": {+ "name": "app_user_idx",+ "columns": ["appId", "externalUserId"],+ "isUnique": false+ },+ "app_deleted_idx": {+ "name": "app_deleted_idx",+ "columns": ["appId", "deletedAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "developer_videos_appId_developer_apps_id_fk": {+ "name": "developer_videos_appId_developer_apps_id_fk",+ "tableFrom": "developer_videos",+ "tableTo": "developer_apps",+ "columnsFrom": ["appId"],+ "columnsTo": ["id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "developer_videos_id": {+ "name": "developer_videos_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "folders": {+ "name": "folders",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'normal'"+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "settings": {+ "name": "settings",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdById": {+ "name": "createdById",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "parentId": {+ "name": "parentId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "spaceId": {+ "name": "spaceId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "created_by_id_idx": {+ "name": "created_by_id_idx",+ "columns": ["createdById"],+ "isUnique": false+ },+ "parent_id_idx": {+ "name": "parent_id_idx",+ "columns": ["parentId"],+ "isUnique": false+ },+ "space_id_idx": {+ "name": "space_id_idx",+ "columns": ["spaceId"],+ "isUnique": false+ },+ "public_parent_id_idx": {+ "name": "public_parent_id_idx",+ "columns": ["public", "parentId"],+ "isUnique": false+ },+ "public_space_parent_id_idx": {+ "name": "public_space_parent_id_idx",+ "columns": ["public", "spaceId", "parentId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "folders_id": {+ "name": "folders_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "imported_videos": {+ "name": "imported_videos",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "orgId": {+ "name": "orgId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "id_idx": {+ "name": "id_idx",+ "columns": ["id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "imported_videos_orgId_source_source_id_pk": {+ "name": "imported_videos_orgId_source_source_id_pk",+ "columns": ["orgId", "source", "source_id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "integration_installations": {+ "name": "integration_installations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "externalId": {+ "name": "externalId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "displayName": {+ "name": "displayName",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "installedByUserId": {+ "name": "installedByUserId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "encryptedCredentials": {+ "name": "encryptedCredentials",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "provider_external_id_idx": {+ "name": "provider_external_id_idx",+ "columns": ["provider", "externalId"],+ "isUnique": true+ },+ "organization_provider_display_name_idx": {+ "name": "organization_provider_display_name_idx",+ "columns": ["organizationId", "provider", "displayName"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "integration_installations_id": {+ "name": "integration_installations_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "loops_sync_jobs": {+ "name": "loops_sync_jobs",+ "columns": {+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "nextAttemptAt": {+ "name": "nextAttemptAt",+ "type": "datetime",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "leaseToken": {+ "name": "leaseToken",+ "type": "varchar(36)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "leaseUntil": {+ "name": "leaseUntil",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failures": {+ "name": "failures",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lastError": {+ "name": "lastError",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "profileHash": {+ "name": "profileHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "teammateJoinedAt": {+ "name": "teammateJoinedAt",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "syncedEmail": {+ "name": "syncedEmail",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lastSyncedAt": {+ "name": "lastSyncedAt",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "loops_sync_due_idx": {+ "name": "loops_sync_due_idx",+ "columns": ["nextAttemptAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "loops_sync_jobs_userId": {+ "name": "loops_sync_jobs_userId",+ "columns": ["userId"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "media_processing_budgets": {+ "name": "media_processing_budgets",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reserved_bytes": {+ "name": "reserved_bytes",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "limit_bytes": {+ "name": "limit_bytes",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "datetime(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_budget_expiry_idx": {+ "name": "media_budget_expiry_idx",+ "columns": ["expires_at"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "media_processing_budgets_id": {+ "name": "media_processing_budgets_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "messenger_conversations": {+ "name": "messenger_conversations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent": {+ "name": "agent",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mode": {+ "name": "mode",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'agent'"+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "anonymousId": {+ "name": "anonymousId",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "takeoverByUserId": {+ "name": "takeoverByUserId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "takeoverAt": {+ "name": "takeoverAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "lastMessageAt": {+ "name": "lastMessageAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "user_last_message_idx": {+ "name": "user_last_message_idx",+ "columns": ["userId", "lastMessageAt"],+ "isUnique": false+ },+ "anonymous_last_message_idx": {+ "name": "anonymous_last_message_idx",+ "columns": ["anonymousId", "lastMessageAt"],+ "isUnique": false+ },+ "mode_last_message_idx": {+ "name": "mode_last_message_idx",+ "columns": ["mode", "lastMessageAt"],+ "isUnique": false+ },+ "updated_at_idx": {+ "name": "updated_at_idx",+ "columns": ["updatedAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "messenger_conversations_id": {+ "name": "messenger_conversations_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "messenger_messages": {+ "name": "messenger_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "conversationId": {+ "name": "conversationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "anonymousId": {+ "name": "anonymousId",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "conversation_created_at_idx": {+ "name": "conversation_created_at_idx",+ "columns": ["conversationId", "createdAt"],+ "isUnique": false+ },+ "role_created_at_idx": {+ "name": "role_created_at_idx",+ "columns": ["role", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messenger_messages_conversationId_messenger_conversations_id_fk": {+ "name": "messenger_messages_conversationId_messenger_conversations_id_fk",+ "tableFrom": "messenger_messages",+ "tableTo": "messenger_conversations",+ "columnsFrom": ["conversationId"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "messenger_messages_id": {+ "name": "messenger_messages_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "messenger_support_emails": {+ "name": "messenger_support_emails",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "conversationId": {+ "name": "conversationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userEmail": {+ "name": "userEmail",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "subject": {+ "name": "subject",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "support_email_user_created_at_idx": {+ "name": "support_email_user_created_at_idx",+ "columns": ["userId", "createdAt"],+ "isUnique": false+ },+ "support_email_conversation_created_at_idx": {+ "name": "support_email_conversation_created_at_idx",+ "columns": ["conversationId", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "support_email_conversation_fk": {+ "name": "support_email_conversation_fk",+ "tableFrom": "messenger_support_emails",+ "tableTo": "messenger_conversations",+ "columnsFrom": ["conversationId"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "messenger_support_emails_id": {+ "name": "messenger_support_emails_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "notifications": {+ "name": "notifications",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "orgId": {+ "name": "orgId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recipientId": {+ "name": "recipientId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "varchar(16)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "videoId": {+ "name": "videoId",+ "type": "varchar(50)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dedupKey": {+ "name": "dedupKey",+ "type": "varchar(128)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "readAt": {+ "name": "readAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "org_id_idx": {+ "name": "org_id_idx",+ "columns": ["orgId"],+ "isUnique": false+ },+ "type_idx": {+ "name": "type_idx",+ "columns": ["type"],+ "isUnique": false+ },+ "read_at_idx": {+ "name": "read_at_idx",+ "columns": ["readAt"],+ "isUnique": false+ },+ "created_at_idx": {+ "name": "created_at_idx",+ "columns": ["createdAt"],+ "isUnique": false+ },+ "recipient_read_idx": {+ "name": "recipient_read_idx",+ "columns": ["recipientId", "readAt"],+ "isUnique": false+ },+ "recipient_created_idx": {+ "name": "recipient_created_idx",+ "columns": ["recipientId", "createdAt"],+ "isUnique": false+ },+ "dedup_key_idx": {+ "name": "dedup_key_idx",+ "columns": ["dedupKey"],+ "isUnique": true+ },+ "type_recipient_created_idx": {+ "name": "type_recipient_created_idx",+ "columns": ["type", "recipientId", "createdAt"],+ "isUnique": false+ },+ "type_recipient_video_created_idx": {+ "name": "type_recipient_video_created_idx",+ "columns": ["type", "recipientId", "videoId", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "notifications_id": {+ "name": "notifications_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "organization_invites": {+ "name": "organization_invites",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "invitedEmail": {+ "name": "invitedEmail",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "invitedByUserId": {+ "name": "invitedByUserId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "invited_email_idx": {+ "name": "invited_email_idx",+ "columns": ["invitedEmail"],+ "isUnique": false+ },+ "invited_by_user_id_idx": {+ "name": "invited_by_user_id_idx",+ "columns": ["invitedByUserId"],+ "isUnique": false+ },+ "status_idx": {+ "name": "status_idx",+ "columns": ["status"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "organization_invites_id": {+ "name": "organization_invites_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "organization_members": {+ "name": "organization_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hasProSeat": {+ "name": "hasProSeat",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "user_id_organization_id_idx": {+ "name": "user_id_organization_id_idx",+ "columns": ["userId", "organizationId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "organization_members_id": {+ "name": "organization_members_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "organization_sso": {+ "name": "organization_sso",+ "columns": {+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "purchasedByUserId": {+ "name": "purchasedByUserId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripeSubscriptionId": {+ "name": "stripeSubscriptionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripePriceId": {+ "name": "stripePriceId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unpaid'"+ },+ "paidThrough": {+ "name": "paidThrough",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "currentPeriodEnd": {+ "name": "currentPeriodEnd",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cancelAtPeriodEnd": {+ "name": "cancelAtPeriodEnd",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "checkoutAttemptId": {+ "name": "checkoutAttemptId",+ "type": "varchar(36)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkoutCurrency": {+ "name": "checkoutCurrency",+ "type": "varchar(3)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkoutPriceId": {+ "name": "checkoutPriceId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkoutSessionId": {+ "name": "checkoutSessionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkoutStartedAt": {+ "name": "checkoutStartedAt",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "sso_stripe_subscription_id_idx": {+ "name": "sso_stripe_subscription_id_idx",+ "columns": ["stripeSubscriptionId"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "organization_sso_organizationId": {+ "name": "organization_sso_organizationId",+ "columns": ["organizationId"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "organizations": {+ "name": "organizations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tombstoneAt": {+ "name": "tombstoneAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allowedEmailDomain": {+ "name": "allowedEmailDomain",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "customDomain": {+ "name": "customDomain",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "domainVerified": {+ "name": "domainVerified",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "settings": {+ "name": "settings",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "iconUrl": {+ "name": "iconUrl",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shareableLinkIconUrl": {+ "name": "shareableLinkIconUrl",+ "type": "varchar(1024)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "workosOrganizationId": {+ "name": "workosOrganizationId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workosConnectionId": {+ "name": "workosConnectionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "owner_id_tombstone_idx": {+ "name": "owner_id_tombstone_idx",+ "columns": ["ownerId", "tombstoneAt"],+ "isUnique": false+ },+ "custom_domain_idx": {+ "name": "custom_domain_idx",+ "columns": ["customDomain"],+ "isUnique": false+ },+ "workos_organization_id_idx": {+ "name": "workos_organization_id_idx",+ "columns": ["workosOrganizationId"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "organizations_id": {+ "name": "organizations_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "s3_buckets": {+ "name": "s3_buckets",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "endpoint": {+ "name": "endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "bucketName": {+ "name": "bucketName",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "accessKeyId": {+ "name": "accessKeyId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "secretAccessKey": {+ "name": "secretAccessKey",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('aws')"+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "owner_organization_idx": {+ "name": "owner_organization_idx",+ "columns": ["ownerId", "organizationId"],+ "isUnique": false+ },+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "organization_active_idx": {+ "name": "organization_active_idx",+ "columns": ["organizationId", "active", "updatedAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "s3_buckets_id": {+ "name": "s3_buckets_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sessionToken": {+ "name": "sessionToken",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "datetime",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "session_token_idx": {+ "name": "session_token_idx",+ "columns": ["sessionToken"],+ "isUnique": true+ },+ "user_id_idx": {+ "name": "user_id_idx",+ "columns": ["userId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "sessions_id": {+ "name": "sessions_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "shared_videos": {+ "name": "shared_videos",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "videoId": {+ "name": "videoId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "folderId": {+ "name": "folderId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sharedByUserId": {+ "name": "sharedByUserId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sharedAt": {+ "name": "sharedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "folder_id_idx": {+ "name": "folder_id_idx",+ "columns": ["folderId"],+ "isUnique": false+ },+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "shared_by_user_id_idx": {+ "name": "shared_by_user_id_idx",+ "columns": ["sharedByUserId"],+ "isUnique": false+ },+ "video_id_organization_id_idx": {+ "name": "video_id_organization_id_idx",+ "columns": ["videoId", "organizationId"],+ "isUnique": false+ },+ "video_id_folder_id_idx": {+ "name": "video_id_folder_id_idx",+ "columns": ["videoId", "folderId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "shared_videos_id": {+ "name": "shared_videos_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "signed_baas": {+ "name": "signed_baas",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "stripeSubscriptionId": {+ "name": "stripeSubscriptionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "entityName": {+ "name": "entityName",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entityType": {+ "name": "entityType",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entityAddress": {+ "name": "entityAddress",+ "type": "varchar(500)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signerName": {+ "name": "signerName",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signerTitle": {+ "name": "signerTitle",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "noticesEmail": {+ "name": "noticesEmail",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signatureData": {+ "name": "signatureData",+ "type": "longtext",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "signedAt": {+ "name": "signedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "emailSentAt": {+ "name": "emailSentAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "signed_baa_organization_id_idx": {+ "name": "signed_baa_organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": true+ },+ "signed_baa_stripe_subscription_idx": {+ "name": "signed_baa_stripe_subscription_idx",+ "columns": ["stripeSubscriptionId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "signed_baas_id": {+ "name": "signed_baas_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "space_members": {+ "name": "space_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "spaceId": {+ "name": "spaceId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "userId": {+ "name": "userId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "user_id_idx": {+ "name": "user_id_idx",+ "columns": ["userId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "space_members_id": {+ "name": "space_members_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {+ "space_id_user_id_unique": {+ "name": "space_id_user_id_unique",+ "columns": ["spaceId", "userId"]+ }+ },+ "checkConstraint": {}+ },+ "space_videos": {+ "name": "space_videos",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "spaceId": {+ "name": "spaceId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "folderId": {+ "name": "folderId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "videoId": {+ "name": "videoId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "addedById": {+ "name": "addedById",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "addedAt": {+ "name": "addedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ }+ },+ "indexes": {+ "folder_id_idx": {+ "name": "folder_id_idx",+ "columns": ["folderId"],+ "isUnique": false+ },+ "video_id_idx": {+ "name": "video_id_idx",+ "columns": ["videoId"],+ "isUnique": false+ },+ "added_by_id_idx": {+ "name": "added_by_id_idx",+ "columns": ["addedById"],+ "isUnique": false+ },+ "space_id_video_id_idx": {+ "name": "space_id_video_id_idx",+ "columns": ["spaceId", "videoId"],+ "isUnique": false+ },+ "space_id_folder_id_idx": {+ "name": "space_id_folder_id_idx",+ "columns": ["spaceId", "folderId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "space_videos_id": {+ "name": "space_videos_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "spaces": {+ "name": "spaces",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "primary": {+ "name": "primary",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdById": {+ "name": "createdById",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "iconUrl": {+ "name": "iconUrl",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "varchar(1000)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "settings": {+ "name": "settings",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "privacy": {+ "name": "privacy",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'Private'"+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {+ "organization_id_idx": {+ "name": "organization_id_idx",+ "columns": ["organizationId"],+ "isUnique": false+ },+ "created_by_id_idx": {+ "name": "created_by_id_idx",+ "columns": ["createdById"],+ "isUnique": false+ },+ "public_organization_id_idx": {+ "name": "public_organization_id_idx",+ "columns": ["public", "organizationId"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "spaces_id": {+ "name": "spaces_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "storage_integrations": {+ "name": "storage_integrations",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "displayName": {+ "name": "displayName",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "encryptedConfig": {+ "name": "encryptedConfig",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "googleDriveAccessToken": {+ "name": "googleDriveAccessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "googleDriveAccessTokenExpiresAt": {+ "name": "googleDriveAccessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "googleDriveTokenRefreshLeaseId": {+ "name": "googleDriveTokenRefreshLeaseId",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "googleDriveTokenRefreshLeaseExpiresAt": {+ "name": "googleDriveTokenRefreshLeaseExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "googleDriveStorageQuotaCache": {+ "name": "googleDriveStorageQuotaCache",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "owner_provider_idx": {+ "name": "owner_provider_idx",+ "columns": ["ownerId", "provider"],+ "isUnique": false+ },+ "owner_active_idx": {+ "name": "owner_active_idx",+ "columns": ["ownerId", "active"],+ "isUnique": false+ },+ "organization_provider_idx": {+ "name": "organization_provider_idx",+ "columns": ["organizationId", "provider"],+ "isUnique": false+ },+ "organization_active_idx": {+ "name": "organization_active_idx",+ "columns": ["organizationId", "active", "status"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "storage_integrations_id": {+ "name": "storage_integrations_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "storage_objects": {+ "name": "storage_objects",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "integrationId": {+ "name": "integrationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "videoId": {+ "name": "videoId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "objectKey": {+ "name": "objectKey",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "objectKeyHash": {+ "name": "objectKeyHash",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerObjectId": {+ "name": "providerObjectId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "uploadSessionUrl": {+ "name": "uploadSessionUrl",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "uploadStatus": {+ "name": "uploadStatus",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "contentType": {+ "name": "contentType",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "contentLength": {+ "name": "contentLength",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {+ "integration_key_hash_idx": {+ "name": "integration_key_hash_idx",+ "columns": ["integrationId", "objectKeyHash"],+ "isUnique": true+ },+ "integration_status_idx": {+ "name": "integration_status_idx",+ "columns": ["integrationId", "uploadStatus"],+ "isUnique": false+ },+ "integration_object_key_prefix_idx": {+ "name": "integration_object_key_prefix_idx",+ "columns": ["integrationId", "`objectKey`(191)"],+ "isUnique": false+ },+ "video_id_idx": {+ "name": "video_id_idx",+ "columns": ["videoId"],+ "isUnique": false+ },+ "owner_id_idx": {+ "name": "owner_id_idx",+ "columns": ["ownerId"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "storage_objects_integrationId_storage_integrations_id_fk": {+ "name": "storage_objects_integrationId_storage_integrations_id_fk",+ "tableFrom": "storage_objects",+ "tableTo": "storage_integrations",+ "columnsFrom": ["integrationId"],+ "columnsTo": ["id"],+ "onDelete": "restrict",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "storage_objects_id": {+ "name": "storage_objects_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lastName": {+ "name": "lastName",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripeSubscriptionId": {+ "name": "stripeSubscriptionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thirdPartyStripeSubscriptionId": {+ "name": "thirdPartyStripeSubscriptionId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripeSubscriptionStatus": {+ "name": "stripeSubscriptionStatus",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripeSubscriptionPriceId": {+ "name": "stripeSubscriptionPriceId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "preferences": {+ "name": "preferences",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "('null')"+ },+ "activeOrganizationId": {+ "name": "activeOrganizationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "onboardingSteps": {+ "name": "onboardingSteps",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "onboarding_completed_at": {+ "name": "onboarding_completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "customBucket": {+ "name": "customBucket",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "inviteQuota": {+ "name": "inviteQuota",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "defaultOrgId": {+ "name": "defaultOrgId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "authSessionVersion": {+ "name": "authSessionVersion",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "marketingOrigin": {+ "name": "marketingOrigin",+ "type": "varchar(20)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ }+ },+ "indexes": {+ "email_idx": {+ "name": "email_idx",+ "columns": ["email"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "users_id": {+ "name": "users_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "verification_tokens": {+ "name": "verification_tokens",+ "columns": {+ "identifier": {+ "name": "identifier",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "datetime",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "verification_tokens_identifier": {+ "name": "verification_tokens_identifier",+ "columns": ["identifier"]+ }+ },+ "uniqueConstraints": {+ "verification_tokens_token_unique": {+ "name": "verification_tokens_token_unique",+ "columns": ["token"]+ }+ },+ "checkConstraint": {}+ },+ "video_edits": {+ "name": "video_edits",+ "columns": {+ "videoId": {+ "name": "videoId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sourceKey": {+ "name": "sourceKey",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "editSpec": {+ "name": "editSpec",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "video_edits_videoId_videos_id_fk": {+ "name": "video_edits_videoId_videos_id_fk",+ "tableFrom": "video_edits",+ "tableTo": "videos",+ "columnsFrom": ["videoId"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "video_edits_videoId": {+ "name": "video_edits_videoId",+ "columns": ["videoId"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "video_processing_jobs": {+ "name": "video_processing_jobs",+ "columns": {+ "video_id": {+ "name": "video_id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "generation": {+ "name": "generation",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "manifest_sha256": {+ "name": "manifest_sha256",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'committing'"+ },+ "attempt_id": {+ "name": "attempt_id",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lease_expires_at": {+ "name": "lease_expires_at",+ "type": "datetime(3)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "datetime(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workflow_run_id": {+ "name": "workflow_run_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_job_id": {+ "name": "remote_job_id",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "verification": {+ "name": "verification",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "output": {+ "name": "output",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_code": {+ "name": "error_code",+ "type": "varchar(64)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "datetime(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "datetime(3)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "processing_state_retry_video_idx": {+ "name": "processing_state_retry_video_idx",+ "columns": ["state", "next_retry_at", "video_id"],+ "isUnique": false+ },+ "processing_state_lease_video_idx": {+ "name": "processing_state_lease_video_idx",+ "columns": ["state", "lease_expires_at", "video_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "video_processing_jobs_video_id": {+ "name": "video_processing_jobs_video_id",+ "columns": ["video_id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "video_uploads": {+ "name": "video_uploads",+ "columns": {+ "video_id": {+ "name": "video_id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "uploaded": {+ "name": "uploaded",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "total": {+ "name": "total",+ "type": "bigint unsigned",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "mode": {+ "name": "mode",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "phase": {+ "name": "phase",+ "type": "varchar(32)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'uploading'"+ },+ "processing_progress": {+ "name": "processing_progress",+ "type": "int",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "processing_message": {+ "name": "processing_message",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "processing_error": {+ "name": "processing_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "raw_file_key": {+ "name": "raw_file_key",+ "type": "varchar(512)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "phase_updated_at_video_id_idx": {+ "name": "phase_updated_at_video_id_idx",+ "columns": ["phase", "updated_at", "video_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "video_uploads_video_id": {+ "name": "video_uploads_video_id",+ "columns": ["video_id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ },+ "videos": {+ "name": "videos",+ "columns": {+ "id": {+ "name": "id",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ownerId": {+ "name": "ownerId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "orgId": {+ "name": "orgId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'My Video'"+ },+ "bucket": {+ "name": "bucket",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "storageIntegrationId": {+ "name": "storageIntegrationId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "duration": {+ "name": "duration",+ "type": "float",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "width": {+ "name": "width",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fps": {+ "name": "fps",+ "type": "int",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "settings": {+ "name": "settings",+ "type": "json",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "transcriptionStatus": {+ "name": "transcriptionStatus",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "json",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "('{\"type\":\"MediaConvert\"}')"+ },+ "folderId": {+ "name": "folderId",+ "type": "varchar(15)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(now())"+ },+ "effectiveCreatedAt": {+ "name": "effectiveCreatedAt",+ "type": "datetime",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "generated": {+ "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )",+ "type": "stored"+ }+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "onUpdate": true,+ "default": "(now())"+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "xStreamInfo": {+ "name": "xStreamInfo",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "firstViewEmailSentAt": {+ "name": "firstViewEmailSentAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "isScreenshot": {+ "name": "isScreenshot",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "awsRegion": {+ "name": "awsRegion",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "awsBucket": {+ "name": "awsBucket",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "videoStartTime": {+ "name": "videoStartTime",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "audioStartTime": {+ "name": "audioStartTime",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "jobId": {+ "name": "jobId",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "jobStatus": {+ "name": "jobStatus",+ "type": "varchar(255)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skipProcessing": {+ "name": "skipProcessing",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {+ "owner_id_idx": {+ "name": "owner_id_idx",+ "columns": ["ownerId"],+ "isUnique": false+ },+ "is_public_idx": {+ "name": "is_public_idx",+ "columns": ["public"],+ "isUnique": false+ },+ "folder_id_idx": {+ "name": "folder_id_idx",+ "columns": ["folderId"],+ "isUnique": false+ },+ "storage_integration_id_idx": {+ "name": "storage_integration_id_idx",+ "columns": ["storageIntegrationId"],+ "isUnique": false+ },+ "org_owner_folder_idx": {+ "name": "org_owner_folder_idx",+ "columns": ["orgId", "ownerId", "folderId"],+ "isUnique": false+ },+ "org_effective_created_idx": {+ "name": "org_effective_created_idx",+ "columns": ["orgId", "effectiveCreatedAt"],+ "isUnique": false+ },+ "screenshot_transcription_created_idx": {+ "name": "screenshot_transcription_created_idx",+ "columns": ["isScreenshot", "transcriptionStatus", "createdAt"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "videos_storageIntegrationId_storage_integrations_id_fk": {+ "name": "videos_storageIntegrationId_storage_integrations_id_fk",+ "tableFrom": "videos",+ "tableTo": "storage_integrations",+ "columnsFrom": ["storageIntegrationId"],+ "columnsTo": ["id"],+ "onDelete": "restrict",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "videos_id": {+ "name": "videos_id",+ "columns": ["id"]+ }+ },+ "uniqueConstraints": {},+ "checkConstraint": {}+ }+ },+ "views": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "tables": {},+ "indexes": {+ "integration_object_key_prefix_idx": {+ "columns": {+ "`objectKey`(191)": {+ "isExpression": true+ }+ }+ }+ }+ }+}diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.jsonindex cf7591c36..014bc42ce 100644--- a/packages/database/migrations/meta/_journal.json+++ b/packages/database/migrations/meta/_journal.json@@ -313,8 +313,15 @@{"idx": 44,"version": "5",- "when": 1789058455302,- "tag": "0044_calm_boomer",+ "when": 1789135858521,+ "tag": "0044_awesome_sugar_man",+ "breakpoints": true+ },+ {+ "idx": 45,+ "version": "5",+ "when": 1789136779085,+ "tag": "0045_steep_forge","breakpoints": true}]diff --git a/packages/database/package.json b/packages/database/package.jsonindex 470731c77..878d989c5 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -64,6 +64,7 @@"./auth/sso": "./auth/sso.ts","./auth/sso-state": "./auth/sso-state.ts","./schema": "./schema.ts",+ "./loops/*": "./loops/*.ts","./crypto": "./crypto.ts","./helpers": "./helpers.ts","./emails/config": "./emails/config.ts",diff --git a/packages/database/schema.ts b/packages/database/schema.tsindex a77ba475c..7df0825ed 100644--- a/packages/database/schema.ts+++ b/packages/database/schema.ts@@ -138,29 +138,23 @@ export const users = mysqlTable(}),);-export const marketingContacts = mysqlTable(- "marketing_contacts",+export const loopsSyncJobs = mysqlTable(+ "loops_sync_jobs",{- emailHash: varchar("emailHash", { length: 64 }).notNull().primaryKey(),- email: varchar("email", { length: 255 }),- userId: nanoIdNullable("userId").$type<User.UserId>(),- consent: varchar("consent", { length: 20 }).notNull().default("unknown"),- source: varchar("source", { length: 64 }).notNull(),- teammate: boolean("teammate").notNull().default(false),- imported: boolean("imported").notNull().default(false),- lastAudience: varchar("lastAudience", { length: 20 }),- lastProfileHash: varchar("lastProfileHash", { length: 64 }),+ userId: nanoId("userId").notNull().primaryKey().$type<User.UserId>(),+ revision: int("revision").notNull().default(1),+ nextAttemptAt: datetime("nextAttemptAt", { mode: "date" }).notNull(),+ leaseToken: varchar("leaseToken", { length: 36 }),+ leaseUntil: datetime("leaseUntil", { mode: "date" }),+ failures: int("failures").notNull().default(0),+ lastError: varchar("lastError", { length: 64 }),+ profileHash: varchar("profileHash", { length: 64 }),+ teammateJoinedAt: datetime("teammateJoinedAt", { mode: "date" }),+ syncedEmail: varchar("syncedEmail", { length: 255 }),lastSyncedAt: datetime("lastSyncedAt", { mode: "date" }),- createdAt: datetime("createdAt", { mode: "date" })- .notNull()- .default(sql`CURRENT_TIMESTAMP`),- updatedAt: datetime("updatedAt", { mode: "date" })- .notNull()- .default(sql`CURRENT_TIMESTAMP`),},(table) => ({- userIndex: index("marketing_contacts_user_idx").on(table.userId),- syncIndex: index("marketing_contacts_sync_idx").on(table.lastSyncedAt),+ dueIndex: index("loops_sync_due_idx").on(table.nextAttemptAt),}),);diff --git a/scripts/emails/catalog.ts b/scripts/emails/catalog.tsindex 6e67247bf..a67d8365d 100644--- a/scripts/emails/catalog.ts+++ b/scripts/emails/catalog.ts@@ -199,7 +199,9 @@ export const renderCatalog = () => {.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.",+ "Completed signups reach Loops through Stripe; SSO uses a small direct fallback. Cap supplies targeting through a durable sync queue, without a separate marketing opt-in step. Existing opt-outs and suppressions take precedence. The integration is not deployed. Historical imports stay held; a new accepted invitation can start teammate help only.",+ "",+ "Current draft journeys require global subscription, capConsent=subscribed, the exact audience, lifecycle enabled and onboarding eligible. capConsent is a legacy migration guard, not a separate consent-capture requirement for new signups. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility.","","Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).","",@@ -260,7 +262,7 @@ export const renderCatalog = () => {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.",+ "Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, capConsent=subscribed and their exact audience. The free template also requires promotional eligibility and excludes teammates.","","| Campaign | Audience | Subject and source | Loops ID |","| --- | --- | --- | --- |",diff --git a/scripts/loops/README.md b/scripts/loops/README.mdindex d997c87f8..c7dae6bd4 100644--- a/scripts/loops/README.md+++ b/scripts/loops/README.md@@ -18,7 +18,9 @@ The September 2026 repository audit found no Bento SDK, environment variable, orTeammate 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.+The production enrollment policy is automatic addition to Loops on completed Cap signup, including completed teammate signup. No separate marketing opt-in checkbox or consent-evidence record is required by this product policy. Existing global unsubscribes, mailing-list opt-outs, bounces and suppressions still take precedence; another signup or profile update must not resubscribe an existing contact. Creating an invitation alone does not enroll its recipient. Teammates receive workspace help only, while independent users and customers receive their matching journeys.++The current draft journeys require a global subscription, `capConsent=subscribed`, the correct audience, and both enrollment flags. `capConsent` is a legacy migration guard; it must not introduce a separate consent-capture step for new signups. The 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.@@ -51,50 +53,56 @@ The legacy native provisioner uses revision checks and a private receipt, but no## 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.+Normal completed signups create or reuse a Stripe customer. The native Loops Stripe integration is connected and enabled for `customer.created` and `customer.updated`. Both import names and assign the Product updates and tips list; additional custom events are blank. All other Stripe event types are disabled and production email workflows remain drafts. Cap then supplies the audience, greeting, paid/license entitlement and recording milestones. A contact cannot enter onboarding until Cap has completed its billing bootstrap and supplied the audience. SSO skips Stripe, so the worker creates those contacts directly, held and marked as teammates before enrollment.-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.+`users.marketingOrigin` permanently identifies teammates. Invitation provisioning excludes sales immediately in local state; accepting an invite queues helpful onboarding. SSO provisioning does the same when a membership or onboarding is new. An existing imported account accepting a new invite after cutover can receive teammate help; importing historical records alone never starts a sequence. Every workflow has re-entry disabled and checks its audience downstream. Teammates cannot move back into a sales audience after leaving an organisation or buying a plan.-After the schema is deployed, dry-run the registry seed:+There is no `marketing_contacts` table. The small `loops_sync_jobs` table stores a user ID, pending revision, retry/lease state, a profile hash, the last synced email and a teammate-join timestamp. It is operational delivery state, not a second subscription database. Queue writes are transactional with signup/invite/SSO changes. Billing webhooks queue updates after persisting billing state; Stripe retries an unsuccessful webhook. Interrupted workers release through expiring leases; completing an older job cannot discard a newer request.-```sh-bun scripts/loops/seed.ts --registry "$LOOPS_PRIVATE_DIR/import/consent-registry.json" --contacts "$LOOPS_PRIVATE_DIR/import/contacts.json"-```+`/api/cron/sync-loops` runs every minute with `CRON_SECRET` authentication. A run has a bounded processing window and stops on rate limiting. Failures stay pending with exponential backoff up to an hour; failed runs return HTTP 500 and log a user ID and a nonsecret reason. Fresh source queries run hourly for recent signups and daily for older accounts, providing reconciliation for milestones and external license changes. Unchanged profile hashes avoid redundant Loops requests. Signup, invite, SSO and billing hooks make relevant changes due immediately. This is eventual synchronization; configure backlog/failure alerts and prove latency before activation. If the scheduler stops, Loops does not automatically expire `capVerifiedAt` or stop already queued emails.-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.+Loops owns subscription preferences. Normal updates never send `subscribed: true` or change list membership. API list removal can disappear from the returned `mailingLists` map; absence is treated as a hold, never an invitation to re-add the list. Configure list assignment for native imports and retain unsubscribe records in Loops. An SSO contact joins the list only in its initial create request. Keep the private Bento suppression archive and reconcile all negative records into Loops before enabling email workflows. Native contact imports are already enabled; imported contacts cannot enter the managed draft journeys without Cap eligibility fields. Contacts that were removed after a successful sync are not recreated. Changed/deleted Cap identities have their previously synced Loops contact held and are surfaced for reconciliation.-The held-contact sync additionally requires read-only `LOOPS_LICENSE_DATABASE_URL`:+Deploy the generated schema before code that selects the new columns. The unshipped migration containing `marketing_contacts` was replaced using Drizzle's migration tooling; no production table was dropped. The implementation is currently behind disabled environment gates:-```sh-bun scripts/loops/sync.ts --team 'Cap Software, Inc.' --mailing-list "$LOOPS_MAILING_LIST_ID" --limit 100-```+| Variable | Purpose |+| ------------------------------- | ------------------------------------------------------------------------ |+| `LOOPS_SYNC_ENABLED=true` | Enables queue writes and processing; otherwise both are off |+| `LOOPS_SYNC_MODE=test` | Default mode; restricts processing to the explicit owned-email allowlist |+| `LOOPS_TEST_EMAILS` | Comma-separated owned test addresses |+| `LOOPS_API_KEY` | Loops API key for Cap Software, Inc. |+| `LOOPS_MAILING_LIST_ID` | Product updates and tips list |+| `LOOPS_LICENSE_DATABASE_URL` | Read-only license database connection |+| `LOOPS_ENROLLMENT_AFTER` | Explicit ISO cutover timestamp; historical signups stay held |+| `LOOPS_ENROLLMENT_ENABLED=true` | Allows eligible lifecycle stages; leave false until approved cutover |+| `CRON_SECRET` | Authenticates the scheduled endpoint |-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.+With the schema available and test configuration set, `bun scripts/loops/seed.ts` reports how many completed signups would be queued. `--apply` queues them without sending anything. `bun scripts/loops/sync.ts --apply` processes a bounded batch using the same worker as the cron route. Test mode fails closed without an allowlist. Set `LOOPS_SYNC_MODE=production` only as part of the reviewed cutover. Seed old completed accounts once after the final suppression reconciliation; subsequent signups enter the queue through the application.## Before any activation### Optional sender profile picture-For Richie's existing photo on `[email protected]`, Loops recommends adding `mail.cap.so` as a **user alias domain** in Google Workspace: Admin console → Account → Domains → Manage domains → Add a domain → User alias domain. Verify ownership using the supplied DNS record. The alias inherits the primary `[email protected]` account and its profile photo without a new paid seat. This affects aliases for all primary-domain users, so inspect the existing domain configuration first. Preserve Loops' sending, bounce and authentication records; do not replace DNS records while following a generic Gmail setup wizard.+On September 11, 2026, `mail.cap.so` was added in Google Workspace as a **user alias domain for cap.so**. Google verified it automatically without a DNS change or a new paid seat. Richie's existing `[email protected]` photo was already visible to anyone. Gmail was not activated for the alias domain; incoming mail still uses Cloudflare Email Routing, and Loops' SES envelope MX/SPF and the inherited DMARC policy were independently checked unchanged after setup.-Avatar display is client-specific and can take time to update. Test a newly sent owned-inbox preview after setup. See [Loops' sending-avatar guide](https://loops.so/docs/deliverability/adding-a-sending-avatar). No Google Workspace domain or DNS changes were made during draft preparation.+The existing photo was visibly confirmed beside `Richie from Cap <[email protected]>` on the received `[PREVIEW] Take another look at Cap` email in Richie's Gmail inbox after setup. No additional email was sent for this check. Avatar display remains client-specific, and other recipients may see a cached picture until their client updates. See [Loops' sending-avatar guide](https://loops.so/docs/deliverability/adding-a-sending-avatar). This setup did not activate any Loops flow or change the production cutover gates below.### Production cutoverActivation is deliberately outside this migration's approved scope. These gates remain necessary:1. Review the final custom drafts and audiences, and configure rotated credentials in the intended environment. September 11 controlled deliveries passed SPF, DKIM and DMARC with inherited `p=quarantine`; the earlier DMARC warning is no longer an observed blocker. Recheck sending-domain status at cutover.-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.+2. The native Stripe connection passed an owned live-customer creation/update test, including name sync, list assignment and global unsubscribe preservation. Independently test a recipient Preference Center list opt-out across a Stripe update; the separate Cap-worker API list-removal check is not proof of that native behavior. Import/reconcile the remaining Bento negative records with workflows off. Then deploy the reviewed schema/code in test mode and prove the actual signup, purchase and invite routes with owned accounts.+3. Set the explicit cutover timestamp, verify the cron schedule and permissions in the deployed environment, and seed the completed-account sync jobs. Keep enrollment disabled while inspecting the resulting contacts. Preserve existing opt-outs and suppressions; no separate consent-capture step is needed.+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. Pause the workflows during a sustained sync outage; changing an application environment flag alone cannot stop messages already queued in Loops.5. Reconcile a fresh Bento delta at cutover, including all opt-outs and changed entitlements. Confirm no campaign/flow is queued to send twice, check overlap with Resend recording emails, then disable old Bento marketing automations only as part of the approved cutover. Preserve source history and suppression evidence.6. Test the deployed Cap signup/purchase/invite/opt-out path through Loops to an owned inbox, including a sync outage and retries. The completed synthetic profile-to-Loops tests do not replace this production integration check.-7. After explicit activation approval, enable one small cohort of newly consenting eligible contacts, monitor deliveries, complaints, opt-outs and duplicate suppression, then expand. Do not bulk enroll imported history. Rollback stops new enrollment and pauses Loops before considering re-enabling Bento; never run both senders for the same journey. Retire Bento and rotate remaining credentials after reconciliation.+7. After explicit activation approval, enable one small cohort of new Cap signups without an existing opt-out or suppression, monitor deliveries, complaints, opt-outs and duplicate suppression, then expand. Do not bulk enroll imported history. Rollback stops new enrollment and pauses Loops before considering re-enabling Bento; never run both senders for the same journey. Retire Bento and rotate remaining credentials after reconciliation.## Validation```sh-bun test scripts/loops/profile.test.ts+bun test scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/emails/catalog.test.tsbun 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.tsbun run tsc -b packages/databasebun run --cwd apps/web next typegendiff --git a/scripts/loops/database.test.ts b/scripts/loops/database.test.tsnew file mode 100644index 000000000..d6bcb9fc3--- /dev/null+++ b/scripts/loops/database.test.ts@@ -0,0 +1,106 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { randomUUID } from "node:crypto";+import { User } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { drizzle } from "drizzle-orm/mysql2";+import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";+import { enqueueLoopsSync } from "../../packages/database/loops/queue";+import { claimJob } from "../../packages/database/loops/worker";+import { loopsSyncJobs } from "../../packages/database/schema";++const url = process.env.LOOPS_TEST_DATABASE_URL;+const ids = Array.from({ length: 4 }, () =>+ User.UserId.make(randomUUID().replaceAll("-", "").slice(0, 15)),+);++describe.skipIf(!url)("durable Loops queue on an isolated database", () => {+ let database: Connection;+ let other: Connection;+ const previousEnabled = process.env.LOOPS_SYNC_ENABLED;+ beforeAll(async () => {+ if (!url || process.env.LOOPS_TEST_BRANCH !== "loops-reliability-20260911")+ throw new Error("Pass the isolated Loops test branch explicitly");+ database = await mysql.createConnection({+ uri: url,+ timezone: "Z",+ dateStrings: true,+ });+ other = await mysql.createConnection({+ uri: url,+ timezone: "Z",+ dateStrings: true,+ });+ process.env.LOOPS_SYNC_ENABLED = "true";+ });+ afterAll(async () => {+ if (previousEnabled === undefined) delete process.env.LOOPS_SYNC_ENABLED;+ else process.env.LOOPS_SYNC_ENABLED = previousEnabled;+ if (database) {+ await database.query("DELETE FROM loops_sync_jobs WHERE userId IN (?)", [+ ids,+ ]);+ await database.end();+ }+ if (other) await other.end();+ });++ test("rolling back a signup rolls back its queued update", async () => {+ const orm = drizzle(database);+ await expect(+ orm.transaction(async (tx) => {+ await enqueueLoopsSync(tx, ids[0]);+ throw new Error("abort_signup");+ }),+ ).rejects.toThrow("abort_signup");+ expect(+ await orm+ .select()+ .from(loopsSyncJobs)+ .where(eq(loopsSyncJobs.userId, ids[0])),+ ).toHaveLength(0);+ });++ test("overlapping runners cannot claim the same update", async () => {+ await enqueueLoopsSync(drizzle(database), ids[1]);+ await enqueueLoopsSync(drizzle(database), ids[1]);+ const [first, second] = await Promise.all([+ claimJob(database, "runner-one", [ids[1]]),+ claimJob(other, "runner-two", [ids[1]]),+ ]);+ expect([first, second].filter(Boolean)).toHaveLength(1);+ expect((first ?? second)?.revision).toBe(2);+ });++ test("an interrupted worker's expired lease becomes claimable", async () => {+ await database.execute(+ "UPDATE loops_sync_jobs SET leaseUntil=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 1 SECOND) WHERE userId=?",+ [ids[1]],+ );+ const claimed = await claimJob(other, "replacement-runner", [ids[1]]);+ expect(claimed?.userId).toBe(ids[1]);+ });++ test("an invite queued during a sync remains due after the older update completes", async () => {+ await enqueueLoopsSync(drizzle(database), ids[2]);+ const old = await claimJob(database, "in-flight", [ids[2]]);+ if (!old) throw new Error("Test job was not claimed");+ await enqueueLoopsSync(drizzle(other), ids[2]);+ await database.execute(+ "UPDATE loops_sync_jobs SET nextAttemptAt=CASE WHEN revision=? THEN DATE_ADD(UTC_TIMESTAMP(),INTERVAL 1 DAY) ELSE UTC_TIMESTAMP() END,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",+ [old.revision, ids[2], "in-flight"],+ );+ const next = await claimJob(other, "newer-update", [ids[2]]);+ expect(next?.revision).toBe(old.revision + 1);+ });++ test("the due query uses the due-time index", async () => {+ const [plan] = await database.query<RowDataPacket[]>(+ "EXPLAIN SELECT * FROM loops_sync_jobs WHERE nextAttemptAt<=UTC_TIMESTAMP() AND (leaseUntil IS NULL OR leaseUntil<UTC_TIMESTAMP()) ORDER BY nextAttemptAt LIMIT 1",+ );+ expect(+ plan.some((row) =>+ String(row.possible_keys).includes("loops_sync_due_idx"),+ ),+ ).toBe(true);+ });+});diff --git a/scripts/loops/lifecycle.test.ts b/scripts/loops/lifecycle.test.tsnew file mode 100644index 000000000..d1363a805--- /dev/null+++ b/scripts/loops/lifecycle.test.ts@@ -0,0 +1,326 @@+import { describe, expect, test } from "bun:test";+import { customerCopy } from "../../emails/customer-copy";+import type { LoopsClient } from "../../packages/database/loops/client";+import {+ type LifecycleContact,+ type LoopsRuntimeConfig,+ lifecycleUpdate,+ retryDelay,+} from "../../packages/database/loops/lifecycle";+import type { LoopsProfileSource } from "../../packages/database/loops/sources";+import {+ loopsRuntimeConfig,+ syncLoopsContact,+} from "../../packages/database/loops/worker";++const email = "[email protected]";+const config: LoopsRuntimeConfig = {+ listId: "test-list",+ enrollmentAfter: new Date("2026-09-11T00:00:00Z"),+ enrollmentEnabled: true,+ allowedEmails: new Set([email]),+};++function fixture(): LoopsProfileSource {+ return {+ input: {+ source: { email },+ user: {+ id: "test-user",+ email,+ name: null,+ lastName: null,+ stripeSubscriptionStatus: null,+ thirdPartyStripeSubscriptionId: null,+ created_at: "2026-09-11T10:00:00Z",+ defaultOrgId: "personal-org",+ marketingOrigin: "independent",+ },+ memberships: [],+ licenses: [],+ invited: false,+ sso: false,+ hasVideo: false,+ hasSharedVideo: false,+ now: new Date("2026-09-11T11:00:00Z"),+ },+ signedUp: true,+ pendingInvite: false,+ stripeCustomerId: "cus_test",+ };+}++function remote(): LifecycleContact {+ return {+ id: "contact-test",+ email,+ userId: null,+ subscribed: true,+ mailingLists: { "test-list": true },+ };+}++function fakeApi(initial: LifecycleContact | undefined) {+ let contact = initial;+ const calls: { path: string; method: string; body: unknown }[] = [];+ const api: LoopsClient = {+ async request<T>(path: string, method = "GET", body?: unknown) {+ calls.push({ path, method, body });+ if (path.startsWith("contacts/find"))+ return (contact ? [contact] : []) as T;+ if (path === "contacts/create")+ contact = { ...remote(), ...(body as Partial<LifecycleContact>) };+ if (path === "contacts/update")+ contact = {+ ...remote(),+ ...contact,+ ...(body as Partial<LifecycleContact>),+ };+ return { success: true, id: "contact-test" } as T;+ },+ };+ return { api, calls, read: () => contact };+}++describe("signup routing", () => {+ test("Stripe import is enriched before entering free onboarding", async () => {+ const fake = fakeApi(remote());+ const update = await syncLoopsContact(+ fake.api,+ fixture(),+ { syncedEmail: null, lastSyncedAt: null },+ config,+ customerCopy,+ );+ expect(fake.calls.map((call) => call.method)).toEqual(["GET", "PUT"]);+ expect(update).toMatchObject({+ capAudience: "free",+ capLifecycleStage: "free",+ capGreeting: "Hey,",+ capOnboardingEligible: true,+ });+ expect(update).not.toHaveProperty("subscribed");+ });+ test("missing Stripe import is retried without creating a Loops contact", async () => {+ const fake = fakeApi(undefined);+ await expect(+ syncLoopsContact(+ fake.api,+ fixture(),+ { syncedEmail: null, lastSyncedAt: null },+ config,+ customerCopy,+ ),+ ).rejects.toThrow("awaiting_stripe_contact");+ expect(fake.calls.every((call) => call.method === "GET")).toBe(true);+ });+ test("Stripe import cannot enroll while signup billing bootstrap is incomplete", async () => {+ const source = fixture();+ source.stripeCustomerId = null;+ const fake = fakeApi(remote());+ await expect(+ syncLoopsContact(+ fake.api,+ source,+ { syncedEmail: null, lastSyncedAt: null },+ config,+ customerCopy,+ ),+ ).rejects.toThrow("stripe_signup_not_complete");+ expect(fake.calls).toHaveLength(0);+ });+ test("SSO fallback creates a held teammate before enabling helpful onboarding", async () => {+ const source = fixture();+ source.input.sso = true;+ source.stripeCustomerId = null;+ const fake = fakeApi(undefined);+ await syncLoopsContact(+ fake.api,+ source,+ { syncedEmail: null, lastSyncedAt: null },+ config,+ customerCopy,+ );+ expect(+ fake.calls.find((call) => call.path === "contacts/create")?.body,+ ).toMatchObject({+ capAudience: "teammate",+ capLifecycleEnabled: false,+ capPromotionalEligible: false,+ });+ expect(fake.read()).toMatchObject({+ capAudience: "teammate",+ capLifecycleStage: "teammate",+ capPromotionalEligible: false,+ });+ });+ test("invitation provisioning is held until the recipient signs up and accepts", () => {+ const source = fixture();+ source.input.invited = true;+ source.pendingInvite = true;+ expect(+ lifecycleUpdate(source, remote(), config, customerCopy),+ ).toMatchObject({+ capAudience: "teammate",+ capPromotionalEligible: false,+ capLifecycleStage: "idle",+ });+ source.pendingInvite = false;+ source.input.invited = false;+ source.input.user.marketingOrigin = "teammate";+ expect(+ lifecycleUpdate(source, remote(), config, customerCopy),+ ).toMatchObject({+ capAudience: "teammate",+ capPromotionalEligible: false,+ capLifecycleStage: "teammate",+ });+ });+ test("a member joining during a free flow can never return to sales after leaving or paying", () => {+ const source = fixture();+ const contact = remote();+ Object.assign(+ contact,+ lifecycleUpdate(source, contact, config, customerCopy),+ );+ source.input.user.marketingOrigin = "teammate";+ Object.assign(+ contact,+ lifecycleUpdate(source, contact, config, customerCopy),+ );+ source.input.user.marketingOrigin = "independent";+ source.input.user.stripeSubscriptionStatus = "active";+ expect(+ lifecycleUpdate(source, contact, config, customerCopy),+ ).toMatchObject({+ capAudience: "teammate",+ capPromotionalEligible: false,+ capLifecycleStage: "teammate",+ });+ });+ test("paid customers skip the free sales flow", () => {+ const source = fixture();+ source.input.user.stripeSubscriptionStatus = "active";+ expect(+ lifecycleUpdate(source, remote(), config, customerCopy),+ ).toMatchObject({+ capAudience: "customer",+ capPromotionalEligible: false,+ capLifecycleStage: "customer",+ });+ });+});++describe("delivery boundaries", () => {+ test("an existing imported user who accepts a new invite receives only teammate help", () => {+ const source = fixture();+ source.input.user.created_at = "2025-01-01T00:00:00Z";+ source.input.user.marketingOrigin = "teammate";+ const update = lifecycleUpdate(+ source,+ { ...remote(), capImportedAt: "2026-09-10T00:00:00Z" },+ { ...config, teammateJoinedAt: "2026-09-11 11:00:00" },+ customerCopy,+ );+ expect(update).toMatchObject({+ capLifecycleStage: "teammate",+ capPromotionalEligible: false,+ capOnboardingEligible: true,+ });+ });+ for (const [name, patch] of [+ ["global unsubscribe", { subscribed: false }],+ ["removed mailing-list membership", { mailingLists: {} }],+ ["list unsubscribe", { mailingLists: { "test-list": false } }],+ ["suppression", { capConsent: "suppressed" }],+ ] as const)+ test(`${name} survives profile and billing updates`, () => {+ const update = lifecycleUpdate(+ fixture(),+ { ...remote(), ...patch },+ config,+ customerCopy,+ );+ expect(update.capOnboardingEligible).toBe(false);+ expect(update.capPromotionalEligible).toBe(false);+ expect(update).not.toHaveProperty("subscribed");+ expect(update).not.toHaveProperty("mailingLists");+ });+ test("imports and pre-cutover signups remain held", () => {+ expect(+ lifecycleUpdate(+ fixture(),+ { ...remote(), capImportedAt: "2026-09-10T00:00:00Z" },+ config,+ customerCopy,+ ).capLifecycleStage,+ ).toBe("idle");+ const source = fixture();+ source.input.user.created_at = "2026-09-01T00:00:00Z";+ expect(+ lifecycleUpdate(source, remote(), config, customerCopy).capLifecycleStage,+ ).toBe("idle");+ });+ test("repeated updates retain the same stage and never resubscribe", () => {+ const contact = remote();+ const source = fixture();+ const first = lifecycleUpdate(source, contact, config, customerCopy);+ Object.assign(contact, first);+ const second = lifecycleUpdate(source, contact, config, customerCopy);+ expect(second.capLifecycleStage).toBe(first.capLifecycleStage);+ expect(second).not.toHaveProperty("subscribed");+ });+ test("removed contacts and different account identities are not recreated or overwritten", async () => {+ const fake = fakeApi(undefined);+ await expect(+ syncLoopsContact(+ fake.api,+ fixture(),+ { syncedEmail: email, lastSyncedAt: "2026-09-11" },+ config,+ customerCopy,+ ),+ ).rejects.toThrow("remote_contact_removed");+ expect(() =>+ lifecycleUpdate(+ fixture(),+ { ...remote(), userId: "someone-else" },+ config,+ customerCopy,+ ),+ ).toThrow("identity_conflict");+ });+ test("test mode refuses non-owned contacts before any provider request", async () => {+ const source = fixture();+ source.input.source.email = "[email protected]";+ const fake = fakeApi(remote());+ await expect(+ syncLoopsContact(+ fake.api,+ source,+ { syncedEmail: null, lastSyncedAt: null },+ config,+ customerCopy,+ ),+ ).rejects.toThrow("outside_test_allowlist");+ expect(fake.calls).toHaveLength(0);+ });+ test("configuration requires explicit cutover and an allowlist by default", () => {+ expect(() => loopsRuntimeConfig({})).toThrow();+ expect(() =>+ loopsRuntimeConfig({+ LOOPS_MAILING_LIST_ID: "test-list",+ LOOPS_ENROLLMENT_AFTER: "2026-09-11",+ }),+ ).toThrow("LOOPS_TEST_EMAILS");+ expect(+ loopsRuntimeConfig({+ LOOPS_MAILING_LIST_ID: "test-list",+ LOOPS_ENROLLMENT_AFTER: "2026-09-11",+ LOOPS_TEST_EMAILS: email,+ }).enrollmentEnabled,+ ).toBe(false);+ expect(retryDelay(0)).toBe(30_000);+ expect(retryDelay(100)).toBe(3_600_000);+ });+});diff --git a/scripts/loops/profile.test.ts b/scripts/loops/profile.test.tsindex d1302476a..e1b661061 100644--- a/scripts/loops/profile.test.ts+++ b/scripts/loops/profile.test.ts@@ -64,7 +64,8 @@ test("greetings include a name only when a nonblank name is known", () => {assert.equal(classifyProfile(fixture).capGreeting, "Hey Sam,");fixture.user = undefined;for (const firstName of [undefined, "", " ", "null", "NULL"]) {- fixture.source.first_name = firstName;+ if (firstName === undefined) delete fixture.source.first_name;+ else fixture.source.first_name = firstName;assert.equal(classifyProfile(fixture).capGreeting, "Hey,");}});diff --git a/scripts/loops/profile.ts b/scripts/loops/profile.tsindex 54c287566..b57d824e8 100644--- a/scripts/loops/profile.ts+++ b/scripts/loops/profile.ts@@ -1,186 +1,9 @@-import { createHash } from "node:crypto";import { customerCopy } from "../../emails/customer-copy";--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 copy =- customerCopy[- directCustomer- ? "pro"- : activeLicenses.some((license) => license.kind === "selfhosted")- ? "selfhosted"- : activeLicenses.length- ? "desktop"- : "other"- ];- const firstName =- [source.first_name, source.firstname, user?.name?.trim().split(/\s+/)[0]]- .map((value) => value?.trim())- .find((value) => value && value.toLowerCase() !== "null") ?? "";- return {- email: normalizeEmail(source.email),- userId: user?.id ?? `bento:${emailHash(source.email)}`,- firstName,- capGreeting: firstName ? `Hey ${firstName},` : "Hey,",- lastName:- [source.last_name, source.lastname, user?.lastName]- .map((value) => value?.trim())- .find((value) => value && value !== "null") ?? "",- subscribed: consent === "subscribed",- source: "Bento migration",- capAudience: audience,- capOrigin: teammate ? "teammate" : independent ? "independent" : "unknown",- capConsent: consent,- capTeammate: teammate,- capCustomer: customer,- capPlanName: copy.plan,- capCustomerWelcome: copy.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>;+import {+ classifyProfile as classify,+ type ProfileInput,+} from "../../packages/database/loops/profile";++export * from "../../packages/database/loops/profile";+export const classifyProfile = (input: ProfileInput) =>+ classify(input, customerCopy);diff --git a/scripts/loops/seed.ts b/scripts/loops/seed.tsindex b9073aecb..11b5e478c 100644--- a/scripts/loops/seed.ts+++ b/scripts/loops/seed.ts@@ -1,117 +1,34 @@-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";+import { loopsRuntimeConfig } from "../../packages/database/loops/worker";-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 },- },+ options: { 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");+const config = loopsRuntimeConfig(process.env);if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");-const db = await mysql.createConnection(process.env.DATABASE_URL);+if (values.apply && process.env.LOOPS_SYNC_ENABLED !== "true")+ throw new Error("LOOPS_SYNC_ENABLED=true is required");+const database = 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) }),+ const eligibility = `(u.emailVerified IS NOT NULL OR EXISTS (SELECT 1 FROM accounts a WHERE a.userId=u.id)) ${config.allowedEmails ? "AND u.email IN (?)" : ""}`;+ const params = config.allowedEmails ? [[...config.allowedEmails]] : [];+ const [counts] = await database.query<(RowDataPacket & { total: number })[]>(+ `SELECT COUNT(*) AS total FROM users u WHERE ${eligibility}`,+ params,+ );+ console.log(+ JSON.stringify({+ mode: values.apply ? "seed sync jobs" : "dry run",+ users: counts[0]?.total,+ enrollsContacts: false,+ }),+ );+ if (values.apply)+ await database.query(+ `INSERT INTO loops_sync_jobs (userId,nextAttemptAt) SELECT u.id,UTC_TIMESTAMP() FROM users u WHERE ${eligibility} ON DUPLICATE KEY UPDATE revision=revision+1,nextAttemptAt=UTC_TIMESTAMP()`,+ params,);- }} finally {- await db.end();+ await database.end();}diff --git a/scripts/loops/sync-policy.ts b/scripts/loops/sync-policy.tsindex 346d8d8f2..fd08f22b7 100644--- a/scripts/loops/sync-policy.ts+++ b/scripts/loops/sync-policy.ts@@ -1,93 +1 @@-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);-}+export * from "../../packages/database/loops/sync-policy";diff --git a/scripts/loops/sync.ts b/scripts/loops/sync.tsindex fab58dde2..16ffe7f2d 100644--- a/scripts/loops/sync.ts+++ b/scripts/loops/sync.ts@@ -1,189 +1,12 @@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";+import { customerCopy } from "../../emails/customer-copy";+import { runLoopsSync } from "../../packages/database/loops/worker";-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" },- },+ options: { apply: { type: "boolean", default: false } },});-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)+if (!values.apply)throw new Error(- "DATABASE_URL and read-only LOOPS_LICENSE_DATABASE_URL are required",+ "Pass --apply to process queued updates. Defaults to the owned-email allowlist; see README.md.",);-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();-}+console.log(JSON.stringify(await runLoopsSync(customerCopy)));