Email for professionals and teams
update migration flow
Hieu Nguyen (Jack)c5c756a77583
diff --git a/.github/workflows/deploy-update.yml b/.github/workflows/deploy-update.ymlindex 9a458c8..31f6592 100644--- a/.github/workflows/deploy-update.yml+++ b/.github/workflows/deploy-update.yml@@ -10,8 +10,6 @@ jobs:update:runs-on: ubuntu-latestenv:- CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}- CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}UPDATE_SOURCE_REPOSITORY: ${{ vars.UPDATE_SOURCE_REPOSITORY || 'hieunc229/mailflare' }}steps:@@ -49,17 +47,6 @@ jobs:exit 1fi- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: "22"-- - name: Install dependencies- run: npm install --no-package-lock-- - name: Apply database migrations- run: npx wrangler d1 migrations apply DB --remote-- name: Push updaterun: |set -euo pipefaildiff --git a/.gitignore b/.gitignoreindex 1d2a939..d126ef0 100644--- a/.gitignore+++ b/.gitignore@@ -46,6 +46,7 @@ next-env.d.ts# OpenNext/.open-next+/src/lib/migrations/bundle.json# wrangler files.wranglerdiff --git a/CLAUDE.md b/CLAUDE.mdindex 2006a99..902f3eb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,7 +15,7 @@ npm run db:migrate:remote # --remote (needs a concrete database_id in wrangnpm run db:seed # POST /api/seed against localhost:3000npm run deploy # opennextjs-cloudflare build + wrangler deploy-npm run deploy:with-migrations # remote migrations, then deploy+npm run deploy # build and deploy; migrate later from Admin settingsnpm run preview # local OpenNext previewnpm run cf-typegen # regenerate cloudflare-env.d.ts from wrangler.jsonc```@@ -75,7 +75,7 @@ Auth is `CF_TOKEN` (preferred) or the legacy `CF_EMAIL` + `CF_API_KEY` pair.Schema lives in one file: `src/db/schema/index.ts` (21 tables). Migrations are generated into `drizzle/migrations/`. Note that `drizzle-kit generate` currently prompts interactively about a snapshot rename conflict, so recent migrations were hand-written to match the generated style.-**`src/lib/setup/migration.ts` duplicates the entire schema as inline SQL.** `/api/setup/prepare` uses it to bootstrap an empty D1 database in one batch, then inserts every migration name into `d1_migrations` so Wrangler treats them as applied. When you add a migration you must update both places: run `db:generate`, then add the new DDL to `INITIAL_SCHEMA_SQL` and the filename to `MIGRATION_NAMES`. Omitting a name from `MIGRATION_NAMES` leaves that migration pending for a later Wrangler apply (this is how `0013_add_license_settings.sql` is currently handled).+`npm run db:bundle` packages the SQL files for the Worker. `/api/setup/prepare` and the admin migration endpoint use the shared runner in `src/lib/migrations/service.ts`; migration files remain the only schema history to maintain. Build, deploy, preview, and development scripts generate the bundle before loading application code.The setup path only ever initializes an empty database — it refuses to touch one that already has tables.@@ -118,7 +118,7 @@ Pro/Team keys are validated against Paymug (`src/lib/licenses/`); only a one-way### Self-update-The admin overview dispatches `deploy-update.yml` (constant in `src/app/api/admin/update/utils.ts`) in the installation repo, which merges the upstream default branch and applies D1 migrations. It does not build or deploy. The README refers to this workflow as `update.yml`; the code is authoritative.+The admin overview dispatches `deploy-update.yml` (constant in `src/app/api/admin/update/utils.ts`) in the installation repo, which merges the upstream default branch and pushes it. It does not migrate, build, or deploy; the connected Cloudflare Git integration deploys the push. The admin update card separately reports and applies pending D1 migrations through the Worker binding.## Conventionsdiff --git a/docs/deployment.md b/docs/deployment.mdindex f288bc5..02aa027 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -37,7 +37,7 @@ Paste only the token secret into `CF_TOKEN`. Do not include the word `Bearer` an3. Let Mailflare check the required Cloudflare configuration and initialize the empty D1 database.4. Create the first admin account when prompted.-The setup page initializes only a new, empty database. It never applies later migrations to an existing database.+Setup applies the committed migrations through the Worker's D1 binding before creating the first admin account.## Step 3: Connect your primary domain and create an account@@ -61,9 +61,9 @@ npm installnpm run deploy:local```-The local deploy command builds the OpenNext application, applies pending D1 migrations, and uploads the complete Worker with Wrangler. The complete Worker is required because `worker.ts` also handles inbound email, queues, scheduled backups, and the real-time Durable Object.+The local deploy command builds and uploads the complete Worker with Wrangler. It does not modify D1. The complete Worker is required because `worker.ts` also handles inbound email, queues, scheduled backups, and the real-time Durable Object.-To migrate an existing remote D1 database before deploying, use:+For manual recovery, pending migrations can still be applied with:```bashnpm run db:migrate:remote@@ -81,7 +81,15 @@ After upgrading an existing installation and confirming the cron trigger is acti## Updating Mailflare-The **Update Mailflare** button in the admin dashboard dispatches `.github/workflows/update.yml` in the installation repository. The workflow merges the latest upstream source, applies pending D1 migrations, and pushes the updated source. A connected Cloudflare Git integration can then build and deploy the change.+The **Update Mailflare** button in the admin dashboard dispatches `.github/workflows/deploy-update.yml` in the installation repository. The workflow merges the latest upstream source and pushes the updated source. A connected Cloudflare Git integration then builds and deploys the change.++Deployment and database migration are separate. After Cloudflare deploys a repository push or an admin-triggered update, open or refresh **Admin settings**. The application update card shows any pending database migrations. Select **Update database** to apply them through the Worker's D1 binding. The same runner initializes a new database during setup.++If the Cloudflare dashboard has a custom deploy command containing `wrangler d1 migrations apply DB --remote`, remove that part and use `npm run deploy`.++Each migration and its `d1_migrations` history entry run in one D1 batch. If a migration fails, its changes are rolled back, the failed filename is shown, and it can be retried after the problem is corrected. Wrangler remains available as a manual recovery tool.++New application releases must remain compatible with the previous schema until an administrator applies their migrations. Prefer additive changes, keep old columns during the transition, and avoid making authentication or the admin settings page depend immediately on a newly added column. Plan a maintenance window for an incompatible schema change.Configure these Worker values:@@ -89,18 +97,13 @@ Configure these Worker values:- `GITHUB_UPDATE_REPO` — the installation repository in `owner/repository` format.- `GITHUB_UPDATE_REF` — an optional update branch. The repository's default branch is used when omitted.-Configure these GitHub Actions repository secrets:--- `CLOUDFLARE_API_TOKEN` — a Cloudflare token allowed to read and migrate D1.-- `CLOUDFLARE_ACCOUNT_ID` — the Cloudflare account ID.-- `MAILFLARE_UPSTREAM_TOKEN` — required only when the upstream repository is private.-Optional repository variables:-- `MAILFLARE_UPSTREAM_REPOSITORY` — the upstream repository. Defaults to `hieunc229/mailflare`.-- `MAILFLARE_UPSTREAM_BRANCH` — the upstream branch. Defaults to `main`.+- `UPDATE_SOURCE_REPOSITORY` — the upstream repository. Defaults to `hieunc229/mailflare`.++If an older installation still runs migrations in its updater, copy the latest `.github/workflows/deploy-update.yml` into that installation once. A workflow already running cannot update itself before executing its old migration step.-If an older installation contains a failing updater, copy the latest `.github/workflows/update.yml` into that installation once. An updater that cannot read upstream cannot update its own workflow.+When adding a schema change, create a new uniquely named SQL file in `drizzle/migrations` and do not edit an applied migration. Build and development commands generate the Worker migration bundle from those files. `npm run db:bundle` can generate it explicitly.## Branding licensediff --git a/package.json b/package.jsonindex 146e3c4..bb940a3 100644--- a/package.json+++ b/package.json@@ -3,26 +3,26 @@"version": "0.2.0","private": true,"scripts": {- "dev": "next dev",- "build": "next build",- "build:next": "next build",+ "dev": "npm run db:bundle && next dev",+ "build": "npm run db:bundle && next build",+ "build:next": "npm run db:bundle && next build","start": "next start","lint": "eslint .",- "deploy": "opennextjs-cloudflare build && npm run db:migrate:remote && npm run deploy:worker",+ "deploy": "npm run db:bundle && opennextjs-cloudflare build && npm run deploy:worker","deploy:worker": "OPEN_NEXT_DEPLOY=true wrangler deploy",- "deploy:local": "npm run build && npm run deploy",- "deploy:with-migrations": "npm run deploy:local",- "upload": "opennextjs-cloudflare build && OPEN_NEXT_DEPLOY=true wrangler versions upload",- "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",+ "deploy:local": "npm run deploy",+ "upload": "npm run db:bundle && opennextjs-cloudflare build && OPEN_NEXT_DEPLOY=true wrangler versions upload",+ "preview": "npm run db:bundle && opennextjs-cloudflare build && opennextjs-cloudflare preview","cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",+ "db:bundle": "node scripts/generate-migration-bundle.mjs","db:generate": "drizzle-kit generate","db:migrate:local": "wrangler d1 migrations apply DB --local","db:migrate:remote": "wrangler d1 migrations apply DB --remote","migrate": "wrangler d1 migrations apply DB","db:seed": "curl -X POST http://localhost:3000/api/seed",- "build:node": "MAILFLARE_RUNTIME=node next build && node scripts/build-server.mjs",+ "build:node": "npm run db:bundle && MAILFLARE_RUNTIME=node next build && node scripts/build-server.mjs","start:node": "MAILFLARE_RUNTIME=node NODE_ENV=production node dist/server.mjs",- "dev:node": "MAILFLARE_RUNTIME=node node --import tsx server/index.ts"+ "dev:node": "npm run db:bundle && MAILFLARE_RUNTIME=node node --import tsx server/index.ts"},"cloudflare": {"bindings": {@@ -39,7 +39,7 @@"description": "Worker name used when creating Cloudflare Email Routing rules. Set this to the deployed Worker name; if you rename the Worker, update this value too."},"GITHUB_UPDATE_TOKEN": {- "description": "Fine-grained GitHub token for the installation repository with Actions: write permission, Contents: write read permission. Used only by the admin update endpoint to dispatch update.yml."+ "description": "Fine-grained GitHub token for the installation repository with Actions: write permission, Contents: write read permission. Used only by the admin update endpoint to dispatch deploy-update.yml."},"GITHUB_UPDATE_REF": {"description": "Optional branch used to dispatch updates. Leave blank to use the repository default branch."diff --git a/scripts/generate-migration-bundle.mjs b/scripts/generate-migration-bundle.mjsnew file mode 100644index 0000000..e4fbfaf--- /dev/null+++ b/scripts/generate-migration-bundle.mjs@@ -0,0 +1,45 @@+import { readFileSync, readdirSync, writeFileSync } from "node:fs";++const root = new URL("../", import.meta.url);+const migrationsDirectory = new URL("drizzle/migrations/", root);+const output = new URL("src/lib/migrations/bundle.json", root);++function splitSql(sql) {+ const tokens = sql.match(/--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|[A-Za-z_]+|;|[^\S\n]+|\n|./g) ?? [];+ const statements = [];+ let current = "";+ let triggerDepth = 0;+ let insideTrigger = false;++ for (const token of tokens) {+ if (token.startsWith("--") || token.startsWith("/*")) {+ current += " ";+ continue;+ }++ const word = token.toUpperCase();+ if (word === "TRIGGER") insideTrigger = true;+ if (insideTrigger && (word === "BEGIN" || word === "CASE")) triggerDepth += 1;+ if (insideTrigger && word === "END") triggerDepth -= 1;+ current += token;++ if (token === ";" && triggerDepth === 0) {+ if (current.trim()) statements.push(current.trim());+ current = "";+ insideTrigger = false;+ }+ }++ if (current.trim()) statements.push(current.trim());+ return statements;+}++const migrations = readdirSync(migrationsDirectory)+ .filter((name) => name.endsWith(".sql"))+ .sort()+ .map((name) => ({+ name,+ statements: splitSql(readFileSync(new URL(name, migrationsDirectory), "utf8")),+ }));++writeFileSync(output, `${JSON.stringify({ migrations }, null, 2)}\n`);diff --git a/src/app/api/admin/migrations/GET.ts b/src/app/api/admin/migrations/GET.tsnew file mode 100644index 0000000..82c6b4e--- /dev/null+++ b/src/app/api/admin/migrations/GET.ts@@ -0,0 +1,17 @@+import { NextResponse } from "next/server";+import { getMigrationStatus } from "@/lib/migrations/service";+import { authorizeMigrationRequest } from "./utils";++export async function GET(request: Request) {+ const authorization = await authorizeMigrationRequest(request);+ if ("error" in authorization) return authorization.error;++ try {+ return NextResponse.json(await getMigrationStatus(authorization.env.DB));+ } catch (error) {+ return NextResponse.json(+ { error: error instanceof Error ? error.message : "Could not check database migrations" },+ { status: 500 },+ );+ }+}diff --git a/src/app/api/admin/migrations/POST.ts b/src/app/api/admin/migrations/POST.tsnew file mode 100644index 0000000..06774be--- /dev/null+++ b/src/app/api/admin/migrations/POST.ts@@ -0,0 +1,17 @@+import { NextResponse } from "next/server";+import { applyPendingMigrations } from "@/lib/migrations/service";+import { authorizeMigrationRequest } from "./utils";++export async function POST(request: Request) {+ const authorization = await authorizeMigrationRequest(request);+ if ("error" in authorization) return authorization.error;++ try {+ return NextResponse.json(await applyPendingMigrations(authorization.env.DB));+ } catch (error) {+ return NextResponse.json(+ { error: error instanceof Error ? error.message : "Could not apply database migrations" },+ { status: 500 },+ );+ }+}diff --git a/src/app/api/admin/migrations/route.ts b/src/app/api/admin/migrations/route.tsnew file mode 100644index 0000000..9687bbb--- /dev/null+++ b/src/app/api/admin/migrations/route.ts@@ -0,0 +1,2 @@+export { GET } from "./GET";+export { POST } from "./POST";diff --git a/src/app/api/admin/migrations/types.d.ts b/src/app/api/admin/migrations/types.d.tsnew file mode 100644index 0000000..f2cbaf3--- /dev/null+++ b/src/app/api/admin/migrations/types.d.ts@@ -0,0 +1,9 @@+import type { MigrationResult, MigrationStatus } from "@/lib/migrations/types";++export interface MigrationStatusResponse extends MigrationStatus {+ error?: string;+}++export interface MigrationApplyResponse extends MigrationResult {+ error?: string;+}diff --git a/src/app/api/admin/migrations/utils.ts b/src/app/api/admin/migrations/utils.tsnew file mode 100644index 0000000..ede01e3--- /dev/null+++ b/src/app/api/admin/migrations/utils.ts@@ -0,0 +1,11 @@+import { NextResponse } from "next/server";+import { authorizeAdminRequest } from "@/app/api/admin/update/utils";++export async function authorizeMigrationRequest(request: Request) {+ const authorization = await authorizeAdminRequest(request);+ if ("error" in authorization) return authorization;+ if (request.method !== "GET" && request.headers.get("Origin") !== new URL(request.url).origin) {+ return { error: NextResponse.json({ error: "Invalid request origin" }, { status: 403 }) };+ }+ return authorization;+}diff --git a/src/components/admin-update-card-types.d.ts b/src/components/admin-update-card-types.d.tsindex a9cbbcf..64a2720 100644--- a/src/components/admin-update-card-types.d.ts+++ b/src/components/admin-update-card-types.d.ts@@ -14,3 +14,11 @@ export interface UpdateWorkflowResponse {runUrl?: string;workflowRunId?: number;}++export interface MigrationStatusResponse {+ applied?: string[];+ error?: string;+ pending: string[];+ ready: boolean;+ unknown: string[];+}diff --git a/src/components/admin-update-card-utils.ts b/src/components/admin-update-card-utils.tsindex a35b361..810f92c 100644--- a/src/components/admin-update-card-utils.ts+++ b/src/components/admin-update-card-utils.ts@@ -1,4 +1,4 @@-import type { UpdateStatusResponse, UpdateWorkflowResponse } from "./admin-update-card-types";+import type { MigrationStatusResponse, UpdateStatusResponse, UpdateWorkflowResponse } from "./admin-update-card-types";export async function getApplicationUpdateStatus(): Promise<UpdateStatusResponse> {const response = await fetch("/api/admin/update", { cache: "no-store" });@@ -21,3 +21,17 @@ export async function triggerApplicationUpdate(): Promise<UpdateWorkflowResponsereturn data;}++export async function getMigrationStatus(): Promise<MigrationStatusResponse> {+ const response = await fetch("/api/admin/migrations", { cache: "no-store" });+ const data = (await response.json()) as MigrationStatusResponse;+ if (!response.ok) throw new Error(data.error ?? "Could not check database migrations");+ return data;+}++export async function applyDatabaseMigrations(): Promise<MigrationStatusResponse> {+ const response = await fetch("/api/admin/migrations", { method: "POST" });+ const data = (await response.json()) as MigrationStatusResponse;+ if (!response.ok) throw new Error(data.error ?? "Could not apply database migrations");+ return data;+}diff --git a/src/components/admin-update-card.tsx b/src/components/admin-update-card.tsxindex 92c4182..3081a10 100644--- a/src/components/admin-update-card.tsx+++ b/src/components/admin-update-card.tsx@@ -5,15 +5,24 @@ import { RefreshCw } from "lucide-react";import { Button } from "@/components/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";-import { getApplicationUpdateStatus, triggerApplicationUpdate } from "./admin-update-card-utils";-import type { UpdateStatusResponse, UpdateWorkflowResponse } from "./admin-update-card-types";+import {+ applyDatabaseMigrations,+ getApplicationUpdateStatus,+ getMigrationStatus,+ triggerApplicationUpdate,+} from "./admin-update-card-utils";+import type { MigrationStatusResponse, UpdateStatusResponse, UpdateWorkflowResponse } from "./admin-update-card-types";export function AdminUpdateCard() {const [status, setStatus] = useState<UpdateStatusResponse>();const [result, setResult] = useState<UpdateWorkflowResponse>();const [error, setError] = useState("");+ const [migrationError, setMigrationError] = useState("");+ const [migrationStatus, setMigrationStatus] = useState<MigrationStatusResponse>();const [isChecking, setIsChecking] = useState(true);+ const [isCheckingMigrations, setIsCheckingMigrations] = useState(true);const [isPending, setIsPending] = useState(false);+ const [isMigrating, setIsMigrating] = useState(false);useEffect(() => {let isActive = true;@@ -31,6 +40,19 @@ export function AdminUpdateCard() {if (isActive) setIsChecking(false);});+ getMigrationStatus()+ .then((databaseStatus) => {+ if (isActive) setMigrationStatus(databaseStatus);+ })+ .catch((statusError) => {+ if (isActive) {+ setMigrationError(statusError instanceof Error ? statusError.message : "Could not check database migrations");+ }+ })+ .finally(() => {+ if (isActive) setIsCheckingMigrations(false);+ });+return () => {isActive = false;};@@ -50,6 +72,20 @@ export function AdminUpdateCard() {}}+ async function handleMigrate() {+ setMigrationError("");+ setIsMigrating(true);+ try {+ setMigrationStatus(await applyDatabaseMigrations());+ } catch (migrationFailure) {+ setMigrationError(+ migrationFailure instanceof Error ? migrationFailure.message : "Could not apply database migrations",+ );+ } finally {+ setIsMigrating(false);+ }+ }+return (<Card className="rounded-3xl border-0 bg-white p-6"><CardHeader className="flex-row items-center gap-4 space-y-0 py-0">@@ -59,35 +95,59 @@ export function AdminUpdateCard() {<div><CardTitle className="text-base">Application update</CardTitle><p className="mt-1 text-sm text-neutral-500">- Sync the latest Mailflare release, apply D1 migrations, and deploy the Worker.+ Sync the latest Mailflare release and keep its database schema up to date.</p></div></CardHeader>- <CardContent className="flex items-center gap-4 pt-5">- <Button type="button" onClick={handleUpdate} disabled={isChecking || isPending || !status?.available}>- <RefreshCw className={isPending ? "h-4 w-4 animate-spin" : "h-4 w-4"} />- {isPending ? "Starting update..." : "Update Mailflare"}- </Button>- {isChecking && <Skeleton className="h-4 w-44" />}- {!isChecking && status?.available && (- <p className="text-sm text-amber-700">- Update available: v{status.currentVersion} → v{status.targetVersion}- </p>- )}- {!isChecking && status && !status.available && (- <p className="text-sm text-green-700">Mailflare v{status.currentVersion} is up to date.</p>- )}- {result?.ok && (- <p className="text-sm text-green-700">- Update started for {result.repository}@{result.ref}.{" "}- {result.runUrl && (- <a className="font-medium underline" href={result.runUrl} target="_blank" rel="noreferrer">- View workflow- </a>- )}- </p>- )}- {error && <p className="text-sm text-red-600">{error}</p>}+ <CardContent className="space-y-5 pt-5">+ <div className="flex items-center gap-4">+ <Button type="button" onClick={handleUpdate} disabled={isChecking || isPending || !status?.available}>+ <RefreshCw className={isPending ? "h-4 w-4 animate-spin" : "h-4 w-4"} />+ {isPending ? "Starting update..." : "Update Mailflare"}+ </Button>+ {isChecking && <Skeleton className="h-4 w-44" />}+ {!isChecking && status?.available && (+ <p className="text-sm text-amber-700">+ Update available: v{status.currentVersion} → v{status.targetVersion}+ </p>+ )}+ {!isChecking && status && !status.available && (+ <p className="text-sm text-green-700">Mailflare v{status.currentVersion} is up to date.</p>+ )}+ {result?.ok && (+ <p className="text-sm text-green-700">+ Update started for {result.repository}@{result.ref}. Refresh this page after Cloudflare deploys it. {" "}+ {result.runUrl && (+ <a className="font-medium underline" href={result.runUrl} target="_blank" rel="noreferrer">+ View workflow+ </a>+ )}+ </p>+ )}+ {error && <p className="text-sm text-red-600">{error}</p>}+ </div>+ <div className="flex items-center gap-4 border-t border-neutral-100 pt-5">+ <Button+ type="button"+ onClick={handleMigrate}+ disabled={isCheckingMigrations || isMigrating || !migrationStatus?.pending.length || !!migrationStatus.unknown.length}+ >+ <RefreshCw className={isMigrating ? "h-4 w-4 animate-spin" : "h-4 w-4"} />+ {isMigrating ? "Updating database..." : "Update database"}+ </Button>+ {isCheckingMigrations && <Skeleton className="h-4 w-44" />}+ {migrationStatus?.pending.length ? (+ <p className="text-sm text-amber-700">+ {migrationStatus.pending.length} database {migrationStatus.pending.length === 1 ? "migration" : "migrations"} pending.+ </p>+ ) : migrationStatus?.ready ? (+ <p className="text-sm text-green-700">Database schema is up to date.</p>+ ) : null}+ {!!migrationStatus?.unknown.length && (+ <p className="text-sm text-red-600">Deploy the matching Mailflare release before changing this database.</p>+ )}+ {migrationError && <p className="text-sm text-red-600">{migrationError}</p>}+ </div></CardContent></Card>);diff --git a/src/components/new-message-popup.tsx b/src/components/new-message-popup.tsxindex d798084..6ed72ab 100644--- a/src/components/new-message-popup.tsx+++ b/src/components/new-message-popup.tsx@@ -10,7 +10,7 @@ export function NewMessagePopup({onDismiss,}: NewMessagePopupProps) {return (- <div className="fixed right-5 top-5 z-[100] w-[min(380px,calc(100vw-40px))] rounded-xl border border-blue-200 bg-white p-4 shadow-xl">+ <div className="fixed right-5 top-5 z-[100] w-[min(380px,calc(100vw-40px))] rounded-xl bg-white p-4 shadow-xl"><div className="flex items-start gap-3"><div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-blue-100 text-blue-700"><Mail className="h-5 w-5" />diff --git a/src/lib/migrations/service.ts b/src/lib/migrations/service.tsnew file mode 100644index 0000000..7588a17--- /dev/null+++ b/src/lib/migrations/service.ts@@ -0,0 +1,60 @@+import bundle from "./bundle.json";+import type { BundledMigration, MigrationNameRow, MigrationResult, MigrationStatus } from "./types";++const MIGRATION_TABLE_SQL =+ "CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)";++const migrations = bundle.migrations as BundledMigration[];++async function getAppliedMigrationNames(db: D1Database): Promise<string[]> {+ const table = await db+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'd1_migrations'")+ .first<MigrationNameRow>();+ if (!table) return [];++ const result = await db.prepare("SELECT name FROM d1_migrations").all<MigrationNameRow>();+ return result.results.map((row) => row.name);+}++export async function getMigrationStatus(db: D1Database): Promise<MigrationStatus> {+ const applied = new Set(await getAppliedMigrationNames(db));+ const committed = new Set(migrations.map((migration) => migration.name));+ const pending = migrations.filter((migration) => !applied.has(migration.name)).map((migration) => migration.name);+ const unknown = [...applied].filter((name) => !committed.has(name)).sort();++ return { ready: pending.length === 0 && unknown.length === 0, pending, unknown };+}++export async function applyPendingMigrations(db: D1Database): Promise<MigrationResult> {+ const initial = await getMigrationStatus(db);+ if (initial.unknown.length > 0) {+ throw new Error("The database contains migrations that are not part of this Mailflare release.");+ }++ await db.prepare(MIGRATION_TABLE_SQL).run();+ const applied: string[] = [];++ for (const name of initial.pending) {+ const migration = migrations.find((candidate) => candidate.name === name);+ if (!migration) continue;++ try {+ await db.batch([+ db.prepare("INSERT INTO d1_migrations (name) VALUES (?)").bind(name),+ ...migration.statements.map((statement) => db.prepare(statement)),+ ]);+ applied.push(name);+ } catch (error) {+ const completed = await db+ .prepare("SELECT name FROM d1_migrations WHERE name = ?")+ .bind(name)+ .first<MigrationNameRow>();+ if (completed) continue;+ throw new Error(+ `Migration ${name} failed: ${error instanceof Error ? error.message : "Database error"}`,+ );+ }+ }++ return { ...(await getMigrationStatus(db)), applied };+}diff --git a/src/lib/migrations/types.d.ts b/src/lib/migrations/types.d.tsnew file mode 100644index 0000000..d24a995--- /dev/null+++ b/src/lib/migrations/types.d.ts@@ -0,0 +1,18 @@+export interface BundledMigration {+ name: string;+ statements: string[];+}++export interface MigrationStatus {+ ready: boolean;+ pending: string[];+ unknown: string[];+}++export interface MigrationResult extends MigrationStatus {+ applied: string[];+}++export interface MigrationNameRow {+ name: string;+}diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.tsindex b300111..112ee37 100644--- a/src/lib/setup/migration.ts+++ b/src/lib/setup/migration.ts@@ -1,158 +1,6 @@-const MIGRATION_NAMES = [- "0000_flowery_smasher.sql",- "0001_add_reset_email.sql",- "0002_add_message_read.sql",- "0003_add_contacts.sql",- "0004_add_accounts.sql",- "0005_add_folders.sql",- "0006_add_rule_conditions.sql",- "0007_add_shared_mailboxes.sql",- "0008_add_message_attachments.sql",- "0009_add_backups.sql",- "0010_hard_squirrel_girl.sql",- "0011_add_folder_colors.sql",- "0012_add_app_settings.sql",- "0013_add_license_settings.sql",- "0014_add_account_permissions.sql",- "0015_add_forwarding_email.sql",- "0016_add_message_snooze.sql",- "0017_add_message_star.sql",- "0018_add_mailbox_domain_aliases.sql",- "0019_merge_message_bodies.sql",- "0020_add_calendar_templates_schedule.sql",- "0021_add_mailbox_signature.sql",- "0022_add_mailbox_auto_reply.sql",- "0023_add_mailbox_aliases.sql",- "0024_add_advanced_routing_and_webhook_retries.sql",- "0025_add_threading_and_cc_bcc.sql",- "0026_add_contact_avatars.sql",- "0027_add_domain_sending_intent.sql",- "0028_add_keyboard_shortcuts_setting.sql",- "0029_add_spam_protection.sql",- "0030_add_message_search_index.sql",- "0031_add_password_reset_and_mfa.sql",-];--const INITIAL_SCHEMA_SQL = `-CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, forwarding_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, can_manage_mailboxes integer DEFAULT false NOT NULL, keyboard_shortcuts_enabled integer DEFAULT true NOT NULL, spam_protection_enabled integer DEFAULT true NOT NULL, totp_secret text, totp_enabled integer DEFAULT false NOT NULL, totp_confirmed_at integer, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS users_created_by_idx ON users(created_by_user_id);-CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_requested integer DEFAULT false NOT NULL, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS domains_hostname_idx ON domains(hostname);-CREATE INDEX IF NOT EXISTS domains_user_idx ON domains(user_id);-CREATE TABLE IF NOT EXISTS mailboxes (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, local_part text NOT NULL, display_name text, signature text, auto_reply_enabled integer DEFAULT false NOT NULL, auto_reply_subject text DEFAULT 'Out of office' NOT NULL, auto_reply_body text DEFAULT '' NOT NULL, avatar_key text, type text DEFAULT 'personal' NOT NULL, use_all_domains integer DEFAULT true NOT NULL, disabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS mailboxes_address_idx ON mailboxes(domain_id, local_part);-CREATE TABLE IF NOT EXISTS mailbox_aliases (id text PRIMARY KEY NOT NULL, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, local_part text NOT NULL, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS mailbox_aliases_address_idx ON mailbox_aliases(domain_id, local_part);-CREATE INDEX IF NOT EXISTS mailbox_aliases_mailbox_idx ON mailbox_aliases(mailbox_id);-CREATE TABLE IF NOT EXISTS auto_reply_deliveries (id text PRIMARY KEY NOT NULL, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, recipient text NOT NULL, sent_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS auto_reply_deliveries_mailbox_recipient_idx ON auto_reply_deliveries(mailbox_id, recipient);-CREATE INDEX IF NOT EXISTS auto_reply_deliveries_sent_idx ON auto_reply_deliveries(sent_at);-CREATE TABLE IF NOT EXISTS mailbox_access (id text PRIMARY KEY NOT NULL, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, permission text DEFAULT 'read_only' NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS mailbox_access_mailbox_user_idx ON mailbox_access(mailbox_id, user_id);-CREATE INDEX IF NOT EXISTS mailbox_access_user_idx ON mailbox_access(user_id);-CREATE INDEX IF NOT EXISTS mailbox_access_mailbox_idx ON mailbox_access(mailbox_id);-CREATE TABLE IF NOT EXISTS contacts (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, email text NOT NULL, display_name text, avatar_key text, source text DEFAULT 'inbound' NOT NULL, blocked integer DEFAULT false NOT NULL, last_seen_at integer, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS contacts_user_email_idx ON contacts(user_id, email);-CREATE INDEX IF NOT EXISTS contacts_user_idx ON contacts(user_id);-CREATE TABLE IF NOT EXISTS folders (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, name text NOT NULL, color text DEFAULT '#2563eb' NOT NULL, created_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS folders_mailbox_name_idx ON folders(mailbox_id, name);-CREATE INDEX IF NOT EXISTS folders_user_idx ON folders(user_id);-CREATE INDEX IF NOT EXISTS folders_mailbox_idx ON folders(mailbox_id);-CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, name text NOT NULL, prefix text NOT NULL, key_hash text NOT NULL, scopes text NOT NULL, created_at integer NOT NULL, last_used_at integer);-CREATE TABLE IF NOT EXISTS messages (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, direction text NOT NULL, provider_message_id text, folder_id text REFERENCES folders(id) ON DELETE set null, from_addr text NOT NULL, to_addr text NOT NULL, cc_addr text, bcc_addr text, subject text, snippet text, text_body text, html_body text, raw_r2_key text, status text DEFAULT 'received' NOT NULL, read integer DEFAULT false NOT NULL, starred integer DEFAULT false NOT NULL, snoozed_until integer, thread_id text, in_reply_to text, references_header text, spam_score integer, spam_verdict text, spam_signals text, spam_analyzed_at integer, spam_analysis_error text, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS messages_user_created_idx ON messages(user_id, created_at);-CREATE INDEX IF NOT EXISTS messages_mailbox_idx ON messages(mailbox_id);-CREATE INDEX IF NOT EXISTS messages_folder_idx ON messages(folder_id);-CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(subject, from_addr, to_addr, cc_addr, text_body, html_body, content='messages', content_rowid='rowid', tokenize='unicode61 remove_diacritics 2');-CREATE TRIGGER IF NOT EXISTS messages_fts_ai AFTER INSERT ON messages BEGIN INSERT INTO messages_fts(rowid, subject, from_addr, to_addr, cc_addr, text_body, html_body) VALUES (new.rowid, new.subject, new.from_addr, new.to_addr, new.cc_addr, new.text_body, new.html_body); END;-CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, subject, from_addr, to_addr, cc_addr, text_body, html_body) VALUES ('delete', old.rowid, old.subject, old.from_addr, old.to_addr, old.cc_addr, old.text_body, old.html_body); END;-CREATE TRIGGER IF NOT EXISTS messages_fts_au AFTER UPDATE OF subject, from_addr, to_addr, cc_addr, text_body, html_body ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, subject, from_addr, to_addr, cc_addr, text_body, html_body) VALUES ('delete', old.rowid, old.subject, old.from_addr, old.to_addr, old.cc_addr, old.text_body, old.html_body); INSERT INTO messages_fts(rowid, subject, from_addr, to_addr, cc_addr, text_body, html_body) VALUES (new.rowid, new.subject, new.from_addr, new.to_addr, new.cc_addr, new.text_body, new.html_body); END;-CREATE INDEX IF NOT EXISTS messages_thread_idx ON messages(mailbox_id, thread_id);-CREATE INDEX IF NOT EXISTS messages_provider_message_idx ON messages(mailbox_id, provider_message_id);-CREATE INDEX IF NOT EXISTS messages_raw_r2_key_idx ON messages(raw_r2_key);-CREATE TABLE IF NOT EXISTS spam_token_stats (mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, token text NOT NULL, spam_count integer DEFAULT 0 NOT NULL, ham_count integer DEFAULT 0 NOT NULL, updated_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS spam_token_stats_mailbox_token_idx ON spam_token_stats(mailbox_id, token);-CREATE INDEX IF NOT EXISTS spam_token_stats_mailbox_idx ON spam_token_stats(mailbox_id);-CREATE TABLE IF NOT EXISTS spam_reputation (mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, type text NOT NULL, key text NOT NULL, messages_seen integer DEFAULT 0 NOT NULL, spam_count integer DEFAULT 0 NOT NULL, ham_count integer DEFAULT 0 NOT NULL, first_seen_at integer NOT NULL, last_seen_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS spam_reputation_mailbox_type_key_idx ON spam_reputation(mailbox_id, type, key);-CREATE INDEX IF NOT EXISTS spam_reputation_mailbox_idx ON spam_reputation(mailbox_id);-CREATE TABLE IF NOT EXISTS spam_feedback (message_id text PRIMARY KEY NOT NULL REFERENCES messages(id) ON DELETE cascade, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, actor_user_id text REFERENCES users(id) ON DELETE set null, classification text NOT NULL, training_tokens text NOT NULL, reputation_keys text NOT NULL, tokenizer_version integer DEFAULT 1 NOT NULL, created_at integer NOT NULL, updated_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS spam_feedback_mailbox_idx ON spam_feedback(mailbox_id);-CREATE TABLE IF NOT EXISTS message_attachments (id text PRIMARY KEY NOT NULL, message_id text NOT NULL REFERENCES messages(id) ON DELETE cascade, filename text NOT NULL, content_type text NOT NULL, size integer NOT NULL, disposition text DEFAULT 'attachment' NOT NULL, content_id text, r2_key text NOT NULL UNIQUE, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS message_attachments_message_idx ON message_attachments(message_id);-CREATE TABLE IF NOT EXISTS outbound_jobs (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, message_id text REFERENCES messages(id) ON DELETE set null, status text DEFAULT 'queued' NOT NULL, payload text NOT NULL, error text, scheduled_at integer, created_at integer NOT NULL, updated_at integer NOT NULL);-CREATE TABLE IF NOT EXISTS email_templates (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, name text NOT NULL, subject text DEFAULT '' NOT NULL, text_body text DEFAULT '' NOT NULL, created_at integer NOT NULL, updated_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS email_templates_user_idx ON email_templates(user_id);-CREATE TABLE IF NOT EXISTS calendar_events (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, title text NOT NULL, description text DEFAULT '' NOT NULL, location text DEFAULT '' NOT NULL, attendees text DEFAULT '[]' NOT NULL, starts_at integer NOT NULL, ends_at integer NOT NULL, created_at integer NOT NULL, updated_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS calendar_events_user_starts_idx ON calendar_events(user_id, starts_at);-CREATE TABLE IF NOT EXISTS routing_rules (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, scope text DEFAULT 'mailbox' NOT NULL, name text, enabled integer DEFAULT true NOT NULL, pattern text NOT NULL, match_field text DEFAULT 'email' NOT NULL, match_operator text DEFAULT 'contains' NOT NULL, match_value text DEFAULT '' NOT NULL, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, folder_id text REFERENCES folders(id) ON DELETE set null, action text DEFAULT 'store' NOT NULL, forward_to text, keep_copy integer DEFAULT false NOT NULL, reject_reason text, priority integer DEFAULT 0 NOT NULL, last_matched_at integer, match_count integer DEFAULT 0 NOT NULL, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS routing_rules_domain_scope_idx ON routing_rules(domain_id, scope, enabled);-CREATE INDEX IF NOT EXISTS routing_rules_mailbox_idx ON routing_rules(mailbox_id);-CREATE INDEX IF NOT EXISTS routing_rules_priority_idx ON routing_rules(priority);-CREATE TABLE IF NOT EXISTS webhooks (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, description text, url text NOT NULL, secret text NOT NULL, events text NOT NULL, enabled integer DEFAULT true NOT NULL, max_attempts integer DEFAULT 5 NOT NULL, created_at integer NOT NULL);-CREATE TABLE IF NOT EXISTS webhook_deliveries (id text PRIMARY KEY NOT NULL, webhook_id text NOT NULL REFERENCES webhooks(id) ON DELETE cascade, event_type text NOT NULL, payload text NOT NULL, status text DEFAULT 'pending' NOT NULL, attempts integer DEFAULT 0 NOT NULL, response_status integer, error text, duration_ms integer, last_attempt_at integer, next_retry_at integer, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS webhook_deliveries_webhook_idx ON webhook_deliveries(webhook_id, created_at);-CREATE INDEX IF NOT EXISTS webhook_deliveries_status_idx ON webhook_deliveries(status);-CREATE TABLE IF NOT EXISTS password_reset_tokens (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, used_at integer, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS password_reset_tokens_user_idx ON password_reset_tokens(user_id);-CREATE TABLE IF NOT EXISTS mfa_recovery_codes (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, code_hash text NOT NULL UNIQUE, used_at integer, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS mfa_recovery_codes_user_idx ON mfa_recovery_codes(user_id);-CREATE TABLE IF NOT EXISTS login_challenges (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, created_at integer NOT NULL);-CREATE TABLE IF NOT EXISTS sessions (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, created_at integer NOT NULL);-CREATE TABLE IF NOT EXISTS audit_logs (id text PRIMARY KEY NOT NULL, actor_user_id text REFERENCES users(id) ON DELETE set null, target_user_id text REFERENCES users(id) ON DELETE set null, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, message_id text REFERENCES messages(id) ON DELETE set null, action text NOT NULL, metadata text, created_at integer NOT NULL);-CREATE INDEX IF NOT EXISTS audit_logs_actor_idx ON audit_logs(actor_user_id);-CREATE INDEX IF NOT EXISTS audit_logs_mailbox_idx ON audit_logs(mailbox_id);-CREATE INDEX IF NOT EXISTS audit_logs_created_idx ON audit_logs(created_at);-CREATE TABLE IF NOT EXISTS backup_settings (id text PRIMARY KEY NOT NULL, enabled integer DEFAULT false NOT NULL, schedule_type text DEFAULT 'daily' NOT NULL, schedule_value integer, retention_enabled integer DEFAULT false NOT NULL, retention_days integer DEFAULT 30 NOT NULL, updated_at integer NOT NULL);-INSERT OR IGNORE INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at) VALUES ('default', false, 'daily', false, 30, unixepoch());-CREATE TABLE IF NOT EXISTS backups (id text PRIMARY KEY NOT NULL, status text DEFAULT 'queued' NOT NULL, trigger text NOT NULL, r2_key text, filename text, size integer, error text, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL, started_at integer, completed_at integer);-CREATE INDEX IF NOT EXISTS backups_created_idx ON backups(created_at);-CREATE INDEX IF NOT EXISTS backups_status_idx ON backups(status);-CREATE TABLE IF NOT EXISTS app_settings (id text PRIMARY KEY NOT NULL, app_name text DEFAULT 'Mailflare' NOT NULL, icon_key text, updated_at integer NOT NULL);-INSERT OR IGNORE INTO app_settings (id, app_name, updated_at) VALUES ('default', 'Mailflare', unixepoch());-CREATE TABLE IF NOT EXISTS license_settings (id text PRIMARY KEY NOT NULL, instance_id text NOT NULL, instance_url text, license_key_hash text, plan text DEFAULT 'community' NOT NULL, state text DEFAULT 'inactive' NOT NULL, features text DEFAULT '[]' NOT NULL, activated_at integer, validated_at integer, updated_at integer NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS license_settings_instance_id_unique ON license_settings(instance_id);-CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);-`;+import { applyPendingMigrations } from "@/lib/migrations/service";export async function migrateCleanDatabase(db: D1Database): Promise<boolean> {- const existing = await db- .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%' AND name NOT IN ('d1_migrations', 'd1_kv')")- .all<{ name: string }>();- if (existing.results.length > 0) {- const tableNames = new Set(existing.results.map((table) => table.name));- if (tableNames.has("users") && tableNames.has("domains")) return false;- throw new Error(- "The D1 database is not empty, but the Mailflare schema is incomplete. Apply the committed D1 migrations before continuing setup.",- );- }-- const schemaStatements = splitSqlStatements(INITIAL_SCHEMA_SQL).map((statement) => db.prepare(statement));- const migrationStatements = MIGRATION_NAMES.map((name) =>- db.prepare("INSERT OR IGNORE INTO d1_migrations (name) VALUES (?)").bind(name),- );- await db.batch([...schemaStatements, ...migrationStatements]);- return true;-}--/**- * Split the bootstrap SQL into statements. A plain split on ";" would cut a- * trigger body apart, so pieces are joined back together until every BEGIN- * has its END.- */-export function splitSqlStatements(sqlText: string): string[] {- const statements: string[] = [];- let current = "";- for (const piece of sqlText.split(";")) {- current = current ? `${current};${piece}` : piece;- const opened = (current.match(/\bBEGIN\b/gi) ?? []).length;- const closed = (current.match(/\bEND\b/gi) ?? []).length;- if (opened > closed) continue;- const statement = current.trim();- if (statement) statements.push(statement);- current = "";- }- const rest = current.trim();- if (rest) statements.push(rest);- return statements;+ const result = await applyPendingMigrations(db);+ return result.applied.length > 0;}