commit
Fixes
diff --git a/scripts/migrate-v1/README.md b/scripts/migrate-v1/README.md
new file mode 100644
index 0000000..164eec9
--- /dev/null
+++ b/scripts/migrate-v1/README.md
@@ -0,0 +1,25 @@
+# Copy mail from the old inbox
+
+One-off: copies the old inbox's mail (`email-db`) into the new schema
+(`email-db-v2` + R2). It runs locally through `wrangler dev`, talking to the
+real databases and bucket. Nothing is deployed.
+
+```sh
+# Optional but recommended: lets attachments the old inbox never stored be
+# fetched again from Resend (only works while Resend still has the emails).
+echo 'RESEND_API_KEY=re_...' > scripts/migrate-v1/.dev.vars
+
+npx wrangler dev -c scripts/migrate-v1/wrangler.jsonc --port 8799
+curl localhost:8799 # dry run: reports what it would copy
+curl 'localhost:8799/?apply=1' # copies it
+
+rm scripts/migrate-v1/.dev.vars
+```
+
+- Only mail for users who've signed in to the new inbox is copied (mailboxes
+ belong to SSO accounts now). Anyone listed under `waitingForSignIn` signs in,
+ then run `?apply=1` again.
+- Running again is safe: ids come from the old rows, so copied mail is skipped.
+ That includes its attachments, so add the Resend key *before* the first
+ `?apply=1` if you want them.
+- Old threads stay together; read/unread is kept.
diff --git a/scripts/migrate-v1/migrate.ts b/scripts/migrate-v1/migrate.ts
new file mode 100644
index 0000000..733d95f
--- /dev/null
+++ b/scripts/migrate-v1/migrate.ts
@@ -0,0 +1,194 @@
+// One-off copy of the old inbox's mail (the `emails` table of email-db) into
+// the new schema. Run through worker.ts; see README.md in this folder.
+//
+// Safe to run more than once: messages, threads and attachments keep ids
+// derived from the old rows, so anything already copied is skipped.
+
+import { Resend } from "resend";
+import { bareAddress, baseSubject } from "../../src/worker/lib/address";
+import { snippetOf } from "../../src/worker/services/messages";
+
+export interface MigrateEnv {
+ OLD_DB: D1Database;
+ DB: D1Database;
+ BUCKET: R2Bucket;
+ /** Optional: lets inbound attachments the old inbox never stored be fetched again from Resend. */
+ RESEND_API_KEY?: string;
+}
+
+type OldEmail = {
+ seq: number;
+ id: string;
+ owner: string;
+ folder: "inbox" | "sent" | "drafts";
+ from_addr: string;
+ to_addrs: string;
+ subject: string;
+ html: string | null;
+ text: string | null;
+ received_at: string;
+ attachments: string;
+ direction: "inbound" | "outbound";
+ status: "sent" | "draft";
+ message_id: string | null;
+ in_reply_to: string | null;
+ refs: string | null;
+ thread_key: string;
+ read: number;
+};
+
+type OldAttachment = { id?: string; filename?: string; contentType?: string; size?: number; contentId?: string | null };
+
+export interface Report {
+ dryRun: boolean;
+ oldEmails: number;
+ copied: number;
+ alreadyCopied: number;
+ /** Mail for users who haven't signed in to the new inbox yet. They sign in, you run this again. */
+ waitingForSignIn: Record<string, number>;
+ attachments: { fromOldDb: number; fromResend: number; unavailable: string[] };
+}
+
+async function threadIdFor(owner: string, threadKey: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${owner}\n${threadKey}`));
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ return `v1-${hex.slice(0, 32)}`;
+}
+
+async function oldBytes(env: MigrateEnv, attachmentId: string): Promise<Uint8Array | null> {
+ const { results } = await env.OLD_DB.prepare(
+ "SELECT data FROM attachment_chunks WHERE attachment_id = ? ORDER BY idx",
+ )
+ .bind(attachmentId)
+ .all<{ data: ArrayBuffer | number[] }>();
+ if (!results.length) return null;
+ const parts = results.map((r) => new Uint8Array(r.data));
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let off = 0;
+ for (const p of parts) {
+ out.set(p, off);
+ off += p.length;
+ }
+ return out;
+}
+
+/** What Resend still has for a received email, if anything. */
+async function resendAttachments(env: MigrateEnv, emailId: string) {
+ if (!env.RESEND_API_KEY) return [];
+ const { data } = await new Resend(env.RESEND_API_KEY).emails.receiving.attachments.list({ emailId, limit: 100 });
+ return data?.data ?? [];
+}
+
+export async function migrate(env: MigrateEnv, { apply }: { apply: boolean }): Promise<Report> {
+ const report: Report = {
+ dryRun: !apply,
+ oldEmails: 0,
+ copied: 0,
+ alreadyCopied: 0,
+ waitingForSignIn: {},
+ attachments: { fromOldDb: 0, fromResend: 0, unavailable: [] },
+ };
+
+ const { results: users } = await env.DB.prepare("SELECT username FROM users").all<{ username: string }>();
+ const signedIn = new Set(users.map((u) => u.username.toLowerCase()));
+
+ let after = 0;
+ for (;;) {
+ const { results: page } = await env.OLD_DB.prepare("SELECT * FROM emails WHERE seq > ? ORDER BY seq LIMIT 25")
+ .bind(after)
+ .all<OldEmail>();
+ if (!page.length) break;
+ after = page[page.length - 1]!.seq;
+
+ for (const e of page) {
+ report.oldEmails++;
+ const owner = e.owner.toLowerCase();
+ if (!signedIn.has(owner)) {
+ report.waitingForSignIn[owner] = (report.waitingForSignIn[owner] ?? 0) + 1;
+ continue;
+ }
+ if (await env.DB.prepare("SELECT 1 FROM messages WHERE id = ?").bind(e.id).first()) {
+ report.alreadyCopied++;
+ continue;
+ }
+
+ const to = JSON.parse(e.to_addrs) as string[];
+ const sentAt = Date.parse(e.received_at) || 0;
+ const threadId = await threadIdFor(owner, e.thread_key);
+ const counterpart = e.thread_key.split("::")[1] || bareAddress(e.direction === "inbound" ? e.from_addr : to[0]);
+ const mailbox = bareAddress(e.direction === "inbound" ? to[0] : e.from_addr);
+ const writes: D1PreparedStatement[] = [
+ env.DB.prepare(
+ "INSERT INTO threads (id, owner, subject, counterpart, last_at) VALUES (?, ?, ?, ?, ?) " +
+ "ON CONFLICT (id) DO UPDATE SET last_at = MAX(last_at, excluded.last_at)",
+ ).bind(threadId, owner, baseSubject(e.subject), counterpart, sentAt),
+ env.DB.prepare(
+ "INSERT OR IGNORE INTO messages (id, owner, thread_id, folder, mailbox, resend_id, message_id, in_reply_to, " +
+ "refs, from_addr, to_addrs, cc_addrs, subject, snippet, html, text, sent_at, read) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, ?, ?)",
+ ).bind(
+ e.id,
+ owner,
+ threadId,
+ e.folder,
+ mailbox,
+ e.status === "draft" ? null : e.id,
+ e.message_id,
+ e.in_reply_to,
+ e.refs,
+ e.from_addr,
+ e.to_addrs,
+ e.subject,
+ snippetOf(e.text, e.html),
+ e.html,
+ e.text,
+ sentAt,
+ e.read,
+ ),
+ ];
+
+ // The old inbox listed attachments it often never stored the bytes of.
+ // Take them from the old DB when they're there, else ask Resend again.
+ const listed = (JSON.parse(e.attachments) as OldAttachment[]).filter((a) => a.id);
+ const fromResend = listed.length && e.direction === "inbound" ? await resendAttachments(env, e.id) : [];
+ for (const [i, a] of listed.entries()) {
+ const id = a.id!;
+ const key = `inbox/v1/${id}`;
+ const filename = a.filename || "attachment";
+ const contentType = a.contentType || "application/octet-stream";
+
+ let body = await oldBytes(env, id);
+ let source: "fromOldDb" | "fromResend" = "fromOldDb";
+ if (!body) {
+ const match =
+ fromResend.find((r) => a.contentId && r.content_id?.replace(/^<|>$/g, "") === a.contentId) ??
+ fromResend.find((r) => r.filename === a.filename) ??
+ fromResend[i];
+ const res = match ? await fetch(match.download_url) : null;
+ body = res?.ok ? await res.arrayBuffer().then((b) => new Uint8Array(b)) : null;
+ source = "fromResend";
+ }
+ if (!body) {
+ report.attachments.unavailable.push(`${filename} (in "${e.subject}")`);
+ continue;
+ }
+ report.attachments[source]++;
+
+ if (apply && !(await env.BUCKET.head(key))) {
+ await env.BUCKET.put(key, body, { httpMetadata: { contentType } });
+ }
+ writes.push(
+ env.DB.prepare(
+ "INSERT OR IGNORE INTO attachments (id, owner, message_id, r2_key, filename, content_type, size, " +
+ "content_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ ).bind(id, owner, e.id, key, filename, contentType, body.byteLength, a.contentId ?? null, sentAt),
+ );
+ }
+
+ // Thread, message and its attachments land together or not at all.
+ if (apply) await env.DB.batch(writes);
+ report.copied++;
+ }
+ }
+ return report;
+}
diff --git a/scripts/migrate-v1/worker.ts b/scripts/migrate-v1/worker.ts
new file mode 100644
index 0000000..6235fbd
--- /dev/null
+++ b/scripts/migrate-v1/worker.ts
@@ -0,0 +1,10 @@
+import { migrate, type MigrateEnv } from "./migrate";
+
+// GET / dry run: reports what would be copied, writes nothing
+// GET /?apply=1 copies it
+export default {
+ async fetch(request: Request, env: MigrateEnv): Promise<Response> {
+ const apply = new URL(request.url).searchParams.get("apply") === "1";
+ return Response.json(await migrate(env, { apply }), { headers: { "Cache-Control": "no-store" } });
+ },
+};
diff --git a/scripts/migrate-v1/wrangler.jsonc b/scripts/migrate-v1/wrangler.jsonc
new file mode 100644
index 0000000..ba15a7c
--- /dev/null
+++ b/scripts/migrate-v1/wrangler.jsonc
@@ -0,0 +1,31 @@
+// Never deployed: run with `wrangler dev`, which runs the code locally but
+// talks to the real databases and bucket ("remote": true). See README.md.
+{
+ "$schema": "../../node_modules/wrangler/config-schema.json",
+ "name": "email-migrate-v1",
+ "main": "worker.ts",
+ "account_id": "f87ee4b9600f437b8da1104d077418c3",
+ "compatibility_date": "2026-10-01",
+ "compatibility_flags": ["nodejs_compat"],
+ "d1_databases": [
+ {
+ "binding": "OLD_DB",
+ "database_name": "email-db",
+ "database_id": "5dbd0d25-8c8a-49c8-83c6-768bda4e9c19",
+ "remote": true
+ },
+ {
+ "binding": "DB",
+ "database_name": "email-db-v2",
+ "database_id": "c6a27bce-97c3-4b10-ad2a-df4a308f494f",
+ "remote": true
+ }
+ ],
+ "r2_buckets": [
+ {
+ "binding": "BUCKET",
+ "bucket_name": "email-attachments",
+ "remote": true
+ }
+ ]
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f081cb5..97aec47 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -48,6 +48,8 @@ export interface Message {
to: string[];
cc: string[];
subject: string;
+ /** Plain-text preview, shown while the message is collapsed. */
+ snippet: string;
/** Email HTML. Only ever render it inside the sandboxed EmailFrame. */
html: string | null;
text: string | null;
diff --git a/src/web/components/ThreadView.svelte b/src/web/components/ThreadView.svelte
index dad042c..e98257c 100644
--- a/src/web/components/ThreadView.svelte
+++ b/src/web/components/ThreadView.svelte
@@ -4,6 +4,7 @@
See LICENCE.md in the project root for full licence information. -->
<script lang="ts">
import ArrowLeft from "@lucide/svelte/icons/arrow-left";
+ import ChevronDown from "@lucide/svelte/icons/chevron-down";
import Forward from "@lucide/svelte/icons/forward";
import MailOpen from "@lucide/svelte/icons/mail-open";
import Paperclip from "@lucide/svelte/icons/paperclip";
@@ -11,8 +12,9 @@
import Reply from "@lucide/svelte/icons/reply";
import Trash from "@lucide/svelte/icons/trash";
import type { Message, Thread } from "../../shared/types";
+ import { SvelteSet } from "svelte/reactivity";
import { api } from "../lib/api";
- import { fmtSize } from "../lib/format";
+ import { fmtSize, fmtTime } from "../lib/format";
import { router } from "../lib/router.svelte";
import { changed, composeDraft, composeForward, composeReply } from "../lib/state.svelte";
import EmailFrame from "./EmailFrame.svelte";
@@ -30,6 +32,7 @@
thread = null;
error = "";
confirming = null;
+ opened.clear();
api
.thread(threadId)
.then((t) => {
@@ -50,6 +53,19 @@
const last = $derived(thread?.messages.filter((m) => m.folder !== "drafts").at(-1) ?? thread?.messages.at(-1));
const hasInbound = $derived(thread?.messages.some((m) => m.folder === "inbox") ?? false);
+ /** Newest first. The API sends them oldest first. */
+ const newestFirst = $derived(thread ? [...thread.messages].sort((a, b) => b.sentAt - a.sentAt) : []);
+ const newestId = $derived(newestFirst[0]?.id);
+ /** Older messages the user has opened; the newest is always open. */
+ const opened = new SvelteSet<string>();
+ const isOpen = (m: Message) => m.id === newestId || opened.has(m.id);
+
+ function toggle(m: Message) {
+ if (m.id === newestId) return;
+ if (opened.has(m.id)) opened.delete(m.id);
+ else opened.add(m.id);
+ }
+
async function markUnread() {
changed((await api.markThread(id, false)).unread);
router.thread(null);
@@ -85,30 +101,63 @@
{:else}
<h2>{thread.subject || "(no subject)"}</h2>
- {#each thread.messages as m (m.id)}
- <section class="message" class:draft={m.folder === "drafts"}>
+ {#if last}
+ <div class="actions">
+ <button class="btn accent" onclick={() => composeReply(last)}><Reply size={14} /> Reply</button>
+ <button class="btn" onclick={() => composeForward(last)}><Forward size={14} /> Forward</button>
+ {#if hasInbound}
+ <button class="btn" onclick={markUnread}><MailOpen size={14} /> Mark unread</button>
+ {/if}
+ <button class="btn danger" onclick={removeThread}>
+ <Trash size={14} />
+ {confirming === "thread" ? "Click again to delete" : "Delete conversation"}
+ </button>
+ </div>
+ {/if}
+
+ {#each newestFirst as m (m.id)}
+ {@const open = isOpen(m)}
+ <section class="message" class:draft={m.folder === "drafts"} class:collapsed={!open}>
<header>
- <div>
+ <button
+ class="summary"
+ onclick={() => toggle(m)}
+ disabled={m.id === newestId}
+ aria-expanded={open}
+ title={m.id === newestId ? undefined : open ? "Collapse" : "Expand"}
+ >
<span class="badge {m.folder}">{m.folder === "inbox" ? "received" : m.folder === "sent" ? "sent" : "draft"}</span>
<strong>{m.from}</strong>
- <span class="muted">to {m.to.join(", ")}{m.cc.length ? `, cc ${m.cc.join(", ")}` : ""}</span>
- </div>
+ {#if open}
+ <span class="muted">to {m.to.join(", ")}{m.cc.length ? `, cc ${m.cc.join(", ")}` : ""}</span>
+ {:else}
+ <span class="muted snippet">{m.snippet}</span>
+ {/if}
+ </button>
<div class="right">
- <time class="muted">{new Date(m.sentAt).toLocaleString()}</time>
- {#if m.folder === "drafts"}
- <button class="btn icon" title="Edit draft" onclick={() => composeDraft(m)}><Pencil size={14} /></button>
+ <time class="muted">{open ? new Date(m.sentAt).toLocaleString() : fmtTime(m.sentAt)}</time>
+ {#if open}
+ {#if m.folder === "drafts"}
+ <button class="btn icon" title="Edit draft" onclick={() => composeDraft(m)}><Pencil size={14} /></button>
+ {/if}
+ <button
+ class="btn icon"
+ class:danger={confirming === m.id}
+ title={confirming === m.id ? "Click again to delete" : "Delete this message"}
+ onclick={() => removeMessage(m)}
+ >
+ <Trash size={14} />
+ </button>
+ {/if}
+ {#if m.id !== newestId}
+ <button class="btn icon chevron" class:open title={open ? "Collapse" : "Expand"} onclick={() => toggle(m)}>
+ <ChevronDown size={14} />
+ </button>
{/if}
- <button
- class="btn icon"
- class:danger={confirming === m.id}
- title={confirming === m.id ? "Click again to delete" : "Delete this message"}
- onclick={() => removeMessage(m)}
- >
- <Trash size={14} />
- </button>
</div>
</header>
+ {#if open}
{#if m.html}
<EmailFrame html={m.html} attachments={m.attachments} />
{:else}
@@ -130,22 +179,9 @@
{/each}
</ul>
{/if}
+ {/if}
</section>
{/each}
-
- {#if last}
- <footer>
- <button class="btn accent" onclick={() => composeReply(last)}><Reply size={14} /> Reply</button>
- <button class="btn" onclick={() => composeForward(last)}><Forward size={14} /> Forward</button>
- {#if hasInbound}
- <button class="btn" onclick={markUnread}><MailOpen size={14} /> Mark unread</button>
- {/if}
- <button class="btn danger" onclick={removeThread}>
- <Trash size={14} />
- {confirming === "thread" ? "Click again to delete" : "Delete conversation"}
- </button>
- </footer>
- {/if}
{/if}
</article>
@@ -255,11 +291,72 @@
outline-color: var(--accent);
}
- footer {
+ .actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
- padding-bottom: 0.75rem;
+ margin-bottom: 1rem;
+ }
+
+ /* Collapsed: one line (sender, preview, time); click to open. */
+ .message.collapsed {
+ padding-block: 0.6rem;
+ transition: border-color 0.15s ease;
+ }
+
+ .message.collapsed:hover {
+ border-color: var(--accent-line);
+ }
+
+ .message.collapsed header {
+ flex-wrap: nowrap;
+ margin-bottom: 0;
+ }
+
+ .summary {
+ display: flex;
+ flex: 1;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 0.35rem;
+ min-width: 0;
+ padding: 0;
+ border: none;
+ background: none;
+ color: inherit;
+ font-size: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+
+ .summary:disabled {
+ cursor: default;
+ }
+
+ .collapsed .summary {
+ flex-wrap: nowrap;
+ }
+
+ .collapsed .summary strong {
+ flex-shrink: 0;
+ }
+
+ .snippet {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .right time {
+ white-space: nowrap;
+ }
+
+ .chevron :global(svg) {
+ transition: transform 0.15s ease;
+ }
+
+ .chevron.open :global(svg) {
+ transform: rotate(180deg);
}
@media (max-width: 800px) {
diff --git a/src/worker/services/messages.ts b/src/worker/services/messages.ts
index 847ac8c..a3589f8 100644
--- a/src/worker/services/messages.ts
+++ b/src/worker/services/messages.ts
@@ -56,6 +56,7 @@ function toMessage(row: MessageRow, attachments: AttachmentInfo[]): Message {
to: JSON.parse(row.to_addrs) as string[],
cc: JSON.parse(row.cc_addrs) as string[],
subject: row.subject,
+ snippet: row.snippet,
html: row.html,
text: row.text,
sentAt: row.sent_at,
diff --git a/test/migrate-v1.test.ts b/test/migrate-v1.test.ts
new file mode 100644
index 0000000..2d0c2de
--- /dev/null
+++ b/test/migrate-v1.test.ts
@@ -0,0 +1,134 @@
+import { env } from "cloudflare:workers";
+import { beforeAll, describe, expect, it } from "vitest";
+import { migrate, type MigrateEnv } from "../scripts/migrate-v1/migrate";
+import { getThread } from "../src/worker/services/messages";
+
+// The old tables don't clash with the new ones, so the test DB plays both.
+const both: MigrateEnv = { OLD_DB: env.DB, DB: env.DB, BUCKET: env.BUCKET };
+
+const oldEmail = (o: {
+ id: string;
+ owner: string;
+ folder: "inbox" | "sent";
+ from: string;
+ to: string;
+ subject: string;
+ at: string;
+ threadKey: string;
+ attachments?: unknown[];
+ read?: number;
+}) =>
+ env.DB.prepare(
+ "INSERT INTO emails (id, owner, folder, from_addr, to_addrs, subject, html, text, received_at, attachments, " +
+ "direction, status, message_id, in_reply_to, refs, thread_key, read) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'sent', NULL, NULL, NULL, ?, ?)",
+ ).bind(
+ o.id,
+ o.owner,
+ o.folder,
+ o.from,
+ JSON.stringify([o.to]),
+ o.subject,
+ `<p>${o.subject}</p>`,
+ o.subject,
+ o.at,
+ JSON.stringify(o.attachments ?? []),
+ o.folder === "inbox" ? "inbound" : "outbound",
+ o.threadKey,
+ o.read ?? 1,
+ );
+
+beforeAll(async () => {
+ await env.DB.batch([
+ env.DB.prepare(
+ "CREATE TABLE emails (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, owner TEXT NOT NULL, " +
+ "folder TEXT NOT NULL, from_addr TEXT NOT NULL, to_addrs TEXT NOT NULL, subject TEXT NOT NULL, html TEXT, " +
+ "text TEXT, received_at TEXT NOT NULL, attachments TEXT NOT NULL, direction TEXT NOT NULL, status TEXT NOT NULL, " +
+ "message_id TEXT, in_reply_to TEXT, refs TEXT, thread_key TEXT NOT NULL, read INTEGER NOT NULL DEFAULT 0)",
+ ),
+ env.DB.prepare(
+ "CREATE TABLE attachment_chunks (attachment_id TEXT NOT NULL, idx INTEGER NOT NULL, data BLOB NOT NULL, " +
+ "PRIMARY KEY (attachment_id, idx))",
+ ),
+ env.DB.prepare(
+ "INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES ('clove', 'sub-clove', 1, 0, 0)",
+ ),
+ oldEmail({
+ id: "11111111-1111-4111-8111-111111111111",
+ owner: "clove",
+ folder: "inbox",
+ from: "Ari <[email protected]>",
+ to: "[email protected]",
+ subject: "Plans",
+ at: "2026-09-01T10:00:00.000Z",
+ threadKey: "plans::[email protected]",
+ read: 0,
+ attachments: [
+ { id: "aaaaaaaa-0000-4000-8000-000000000001", filename: "map.txt", contentType: "text/plain", size: 5, contentId: null },
+ { id: "aaaaaaaa-0000-4000-8000-000000000002", filename: "lost.pdf", contentType: "application/pdf", size: 0 },
+ ],
+ }),
+ oldEmail({
+ id: "22222222-2222-4222-8222-222222222222",
+ owner: "clove",
+ folder: "sent",
+ from: "[email protected]",
+ to: "[email protected]",
+ subject: "Re: Plans",
+ at: "2026-09-01T11:00:00.000Z",
+ threadKey: "plans::[email protected]",
+ }),
+ oldEmail({
+ id: "33333333-3333-4333-8333-333333333333",
+ owner: "ari",
+ folder: "inbox",
+ from: "[email protected]",
+ to: "[email protected]",
+ subject: "For Ari",
+ at: "2026-09-02T10:00:00.000Z",
+ threadKey: "for ari::[email protected]",
+ }),
+ // Only the first attachment's bytes were ever stored, as with the real data.
+ env.DB.prepare("INSERT INTO attachment_chunks (attachment_id, idx, data) VALUES (?, 0, ?)").bind(
+ "aaaaaaaa-0000-4000-8000-000000000001",
+ new TextEncoder().encode("hello"),
+ ),
+ ]);
+});
+
+describe("migrate v1", () => {
+ it("writes nothing on a dry run", async () => {
+ const report = await migrate(both, { apply: false });
+ expect(report).toMatchObject({ dryRun: true, oldEmails: 3, copied: 2, waitingForSignIn: { ari: 1 } });
+ expect(await env.DB.prepare("SELECT COUNT(*) AS n FROM messages").first("n")).toBe(0);
+ });
+
+ it("copies signed-in users' mail into threads, with attachments in R2", async () => {
+ const report = await migrate(both, { apply: true });
+ expect(report).toMatchObject({ copied: 2, alreadyCopied: 0, waitingForSignIn: { ari: 1 } });
+ expect(report.attachments).toEqual({ fromOldDb: 1, fromResend: 0, unavailable: ['lost.pdf (in "Plans")'] });
+
+ const { thread_id } = (await env.DB.prepare("SELECT thread_id FROM messages WHERE id = ?")
+ .bind("11111111-1111-4111-8111-111111111111")
+ .first<{ thread_id: string }>())!;
+ const thread = (await getThread(env, "clove", thread_id))!;
+ expect(thread.messages.map((m) => [m.folder, m.subject, m.read])).toEqual([
+ ["inbox", "Plans", false],
+ ["sent", "Re: Plans", true],
+ ]);
+ expect(thread.messages[0]!.mailbox).toBe("[email protected]");
+ expect(thread.messages[0]!.attachments.map((a) => a.filename)).toEqual(["map.txt"]);
+
+ const obj = await env.BUCKET.get("inbox/v1/aaaaaaaa-0000-4000-8000-000000000001");
+ expect(await obj?.text()).toBe("hello");
+ });
+
+ it("is safe to run again, and picks up users who've since signed in", async () => {
+ await env.DB.prepare(
+ "INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES ('ari', 'sub-ari', 0, 0, 0)",
+ ).run();
+ const report = await migrate(both, { apply: true });
+ expect(report).toMatchObject({ copied: 1, alreadyCopied: 2, waitingForSignIn: {} });
+ expect(await env.DB.prepare("SELECT COUNT(*) AS n FROM messages").first("n")).toBe(3);
+ });
+});
diff --git a/test/tsconfig.json b/test/tsconfig.json
index 8eca979..8d81a0c 100644
--- a/test/tsconfig.json
+++ b/test/tsconfig.json
@@ -3,6 +3,6 @@
"compilerOptions": {
"types": ["../src/worker/worker-configuration.d.ts", "node", "@cloudflare/vitest-plugin/types"]
},
- "include": ["./**/*.ts", "../src/**/*.ts"],
+ "include": ["./**/*.ts", "../src/**/*.ts", "../scripts/**/*.ts"],
"exclude": ["../src/web/**"]
}