@open-workspace/email 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,15 @@ import { and, asc, desc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-o
3
3
  import { drizzle, type DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
4
4
  import { migrate } from "drizzle-orm/durable-sqlite/migrator";
5
5
  import migrations from "./migrations";
6
- import { upgradeLegacyMailbox } from "./legacy-migrations";
6
+ import {
7
+ bumpJmapState,
8
+ emailPlacement as jmapEmailPlacement,
9
+ jmapState,
10
+ mailboxes as jmapMailboxRows,
11
+ moveEmails as jmapMoveEmails,
12
+ queryEmails as queryJmapEmails,
13
+ threadEmails as jmapThreadEmails,
14
+ } from "./jmap-store";
7
15
  import { officePreviewExtension, officePreviewKey } from "../../shared/office-preview";
8
16
  import {
9
17
  dispatchOfficePreviewJobs,
@@ -142,6 +150,11 @@ const ALARM_WAKE_DELAY_MS = 1_000;
142
150
  const PRESENCE_TTL_MS = 60_000;
143
151
  const AI_CONFIGURATION_ID = "default";
144
152
 
153
+ /** Browser sessions, authorized against their session on every update. */
154
+ const SESSION_SOCKET_TAG = "session";
155
+ /** JMAP EventSource streams held by the Worker; they receive the new state. */
156
+ const JMAP_SOCKET_TAG = "jmap";
157
+
145
158
  type MailboxSocketAttachment = {
146
159
  userId: string;
147
160
  sessionId: string;
@@ -335,8 +348,6 @@ export class MailboxDO extends DurableObject<Env> {
335
348
  this.bindings = env;
336
349
  this.db = drizzle(ctx.storage, { schema });
337
350
  ctx.blockConcurrencyWhile(async () => {
338
- ctx.storage.transactionSync(() =>
339
- upgradeLegacyMailbox(ctx.storage.sql, migrations.journal.entries[0]!.when));
340
351
  await migrate(this.db, migrations);
341
352
  });
342
353
  }
@@ -345,6 +356,12 @@ export class MailboxDO extends DurableObject<Env> {
345
356
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
346
357
  return new Response("WebSocket upgrade required", { status: 426 });
347
358
  }
359
+ // JMAP EventSource streams; the Worker holding one checks its token.
360
+ if (request.headers.get("x-openworkspace-jmap") === "1") {
361
+ const pair = new WebSocketPair();
362
+ this.state.acceptWebSocket(pair[1], [JMAP_SOCKET_TAG]);
363
+ return new Response(null, { status: 101, webSocket: pair[0] });
364
+ }
348
365
  const userId = request.headers.get("x-openworkspace-user-id");
349
366
  const sessionId = request.headers.get("x-openworkspace-session-id");
350
367
  const sessionTokenHash = request.headers.get("x-openworkspace-session-token-hash");
@@ -363,7 +380,7 @@ export class MailboxDO extends DurableObject<Env> {
363
380
  visibility,
364
381
  presenceUpdatedAt: Date.now(),
365
382
  } satisfies MailboxSocketAttachment);
366
- this.state.acceptWebSocket(server);
383
+ this.state.acceptWebSocket(server, [SESSION_SOCKET_TAG]);
367
384
  return new Response(null, { status: 101, webSocket: client });
368
385
  }
369
386
 
@@ -421,7 +438,7 @@ export class MailboxDO extends DurableObject<Env> {
421
438
  userId: string;
422
439
  visibleAfter: number;
423
440
  }) {
424
- const sockets = this.state.getWebSockets().flatMap((socket) => {
441
+ const sockets = this.state.getWebSockets(SESSION_SOCKET_TAG).flatMap((socket) => {
425
442
  const attachment = socketAttachment(socket);
426
443
  if (attachment) {
427
444
  if (
@@ -481,7 +498,7 @@ export class MailboxDO extends DurableObject<Env> {
481
498
  } catch (error) {
482
499
  // Closing forces clients to reconnect and refresh instead of silently
483
500
  // losing the only invalidation now that there is no polling fallback.
484
- for (const socket of this.state.getWebSockets()) {
501
+ for (const socket of this.state.getWebSockets(SESSION_SOCKET_TAG)) {
485
502
  socket.close(1011, "Realtime authorization is temporarily unavailable");
486
503
  }
487
504
  throw error;
@@ -497,9 +514,29 @@ export class MailboxDO extends DurableObject<Env> {
497
514
  }
498
515
 
499
516
  private publishUpdate() {
517
+ bumpJmapState(this.state.storage);
500
518
  this.state.waitUntil(this.broadcastUpdate().catch((error) => {
501
519
  console.error("Could not authorize realtime delivery", error);
502
520
  }));
521
+ this.announceJmapState();
522
+ }
523
+
524
+ /** Tells JMAP EventSource streams and push subscribers the new state. */
525
+ private announceJmapState() {
526
+ const mailboxId = this.state.id.name;
527
+ if (!mailboxId) return;
528
+ const state = jmapState(this.state.storage);
529
+ for (const socket of this.state.getWebSockets(JMAP_SOCKET_TAG)) {
530
+ try {
531
+ socket.send(state);
532
+ } catch {
533
+ socket.close(1011, "Could not deliver realtime event");
534
+ }
535
+ }
536
+ const job: MailboxPushJob = { type: "jmap-state", mailboxId, state, occurredAt: Date.now() };
537
+ this.state.waitUntil(this.bindings.PUSH_NOTIFICATIONS.send(job).catch((error) => {
538
+ console.error("Could not queue JMAP push", error);
539
+ }));
503
540
  }
504
541
 
505
542
  private queueIncomingNotification(email: Email) {
@@ -852,6 +889,41 @@ export class MailboxDO extends DurableObject<Env> {
852
889
  return this.getMailboxAiSettings();
853
890
  }
854
891
 
892
+ jmapState() {
893
+ return jmapState(this.state.storage);
894
+ }
895
+
896
+ jmapMailboxes(userId: string) {
897
+ return { state: jmapState(this.state.storage), mailboxes: jmapMailboxRows(this.state.storage.sql, userId) };
898
+ }
899
+
900
+ jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
901
+ return { state: jmapState(this.state.storage), ...queryJmapEmails(this.state.storage.sql, input) };
902
+ }
903
+
904
+ /** Emails with their JMAP Mailbox and this user's $seen keyword; unknown ids are left out. */
905
+ jmapEmails(userId: string, ids: string[]) {
906
+ const placement = jmapEmailPlacement(this.state.storage.sql, userId, ids);
907
+ return {
908
+ state: jmapState(this.state.storage),
909
+ emails: ids.flatMap((id) => {
910
+ const email = this.getEmail(id);
911
+ const place = placement.get(id);
912
+ return email && place ? [{ email, ...place }] : [];
913
+ }),
914
+ };
915
+ }
916
+
917
+ jmapThreads(ids: string[]) {
918
+ return { state: jmapState(this.state.storage), threads: [...jmapThreadEmails(this.state.storage.sql, ids)] };
919
+ }
920
+
921
+ jmapMoveEmails(emailIds: string[], target: string) {
922
+ const moved = jmapMoveEmails(this.state.storage.sql, emailIds, target);
923
+ if (moved) this.publishUpdate();
924
+ return moved;
925
+ }
926
+
855
927
  getEmail(id: string) {
856
928
  return this.db.select().from(emails).where(eq(emails.id, id)).all()[0] ?? null;
857
929
  }
@@ -1304,7 +1376,7 @@ export class MailboxDO extends DurableObject<Env> {
1304
1376
  console.error("Could not read workspace identity for sender checks", error);
1305
1377
  }
1306
1378
  const stored = email.authenticationResultsJson;
1307
- const authentication = stored?.source === "headers" ? stored : null;
1379
+ const authentication = stored ?? null;
1308
1380
  const from = email.fromJson[0] ?? { address: "", name: null };
1309
1381
  const sql = this.state.storage.sql;
1310
1382
  const status = from.address ? senderStatuses(sql, [from.address]).get(from.address.toLocaleLowerCase()) : undefined;
@@ -1534,22 +1606,6 @@ export class MailboxDO extends DurableObject<Env> {
1534
1606
  return Object.fromEntries(senderHistory(this.state.storage.sql, addresses));
1535
1607
  }
1536
1608
 
1537
- /** Lazy backfill for messages stored before header parsing existed. */
1538
- setEmailHeaderMetadata(
1539
- emailId: string,
1540
- metadata: {
1541
- authenticationResultsJson: InboundAuthentication;
1542
- listUnsubscribeJson: ListUnsubscribe | null;
1543
- },
1544
- ) {
1545
- return this.db
1546
- .update(emails)
1547
- .set(metadata)
1548
- .where(and(eq(emails.id, emailId), eq(emails.direction, "incoming")))
1549
- .returning({ id: emails.id })
1550
- .all().length > 0;
1551
- }
1552
-
1553
1609
  /** Block, trust and report state for senders, and unsubscribe records for lists. */
1554
1610
  getMessageSafetyContext(addresses: string[], listKeys: string[]) {
1555
1611
  const keys = [...new Set(listKeys)].slice(0, 100);
@@ -0,0 +1,238 @@
1
+ /**
2
+ * JMAP views over a mailbox's SQLite store (RFC 8621). A JMAP Mailbox is a
3
+ * system folder or a custom folder; an email sits in exactly one, derived
4
+ * from its conversation's state and its own direction.
5
+ */
6
+
7
+ /** Which JMAP Mailbox an email (alias e) of conversation (alias c) is in. */
8
+ export const EMAIL_MAILBOX_SQL = `case
9
+ when c.mailbox_state = 'trash' then 'trash'
10
+ when c.mailbox_state = 'spam' then 'spam'
11
+ when c.mailbox_state = 'archive' then 'archive'
12
+ when e.direction = 'outgoing' then 'sent'
13
+ when c.folder_id is not null then c.folder_id
14
+ else 'inbox'
15
+ end`;
16
+
17
+ const SYSTEM_MAILBOXES = [
18
+ { id: "inbox", name: "Inbox", role: "inbox", sortOrder: 0 },
19
+ { id: "sent", name: "Sent", role: "sent", sortOrder: 1_000 },
20
+ { id: "archive", name: "Archive", role: "archive", sortOrder: 1_010 },
21
+ { id: "spam", name: "Spam", role: "junk", sortOrder: 1_020 },
22
+ { id: "trash", name: "Trash", role: "trash", sortOrder: 1_030 },
23
+ ] as const;
24
+
25
+ export type JmapMailboxRow = {
26
+ id: string;
27
+ name: string;
28
+ role: string | null;
29
+ sortOrder: number;
30
+ totalEmails: number;
31
+ unreadEmails: number;
32
+ totalThreads: number;
33
+ unreadThreads: number;
34
+ };
35
+
36
+ export type JmapEmailFilter = {
37
+ inMailbox?: string;
38
+ inMailboxOtherThan?: string[];
39
+ before?: number;
40
+ after?: number;
41
+ text?: string;
42
+ from?: string;
43
+ to?: string;
44
+ subject?: string;
45
+ hasKeyword?: string;
46
+ notKeyword?: string;
47
+ hasAttachment?: boolean;
48
+ };
49
+
50
+ const STATE_KEY = "jmap:state";
51
+
52
+ /** A counter bumped on every change; JMAP clients compare it to resync. */
53
+ export function jmapState(storage: DurableObjectStorage) {
54
+ return String(storage.kv.get<number>(STATE_KEY) ?? 0);
55
+ }
56
+
57
+ export function bumpJmapState(storage: DurableObjectStorage) {
58
+ storage.kv.put(STATE_KEY, (storage.kv.get<number>(STATE_KEY) ?? 0) + 1);
59
+ }
60
+
61
+ const unread = (userId: string) => ({
62
+ sql: "not exists (select 1 from email_read_states r where r.email_id = e.id and r.user_id = ?)",
63
+ params: [userId],
64
+ });
65
+
66
+ export function mailboxes(sql: SqlStorage, userId: string): JmapMailboxRow[] {
67
+ const isUnread = unread(userId);
68
+ const counts = new Map(
69
+ sql.exec<{ mailbox: string; total: number; unread: number; threads: number; unread_threads: number }>(`
70
+ select mailbox,
71
+ count(*) as total,
72
+ sum(is_unread) as unread,
73
+ count(distinct conversation_id) as threads,
74
+ count(distinct case when is_unread then conversation_id end) as unread_threads
75
+ from (
76
+ select ${EMAIL_MAILBOX_SQL} as mailbox, e.conversation_id, ${isUnread.sql} as is_unread
77
+ from emails e join conversations c on c.id = e.conversation_id
78
+ )
79
+ group by mailbox`, ...isUnread.params).toArray().map((row) => [row.mailbox, row]),
80
+ );
81
+ const custom = sql.exec<{ id: string; name: string; sort_order: number }>(
82
+ "select id, name, sort_order from folders order by sort_order, name",
83
+ ).toArray();
84
+ const rows = [
85
+ ...SYSTEM_MAILBOXES.map((mailbox) => ({ ...mailbox })),
86
+ ...custom.map((folder) => ({ id: folder.id, name: folder.name, role: null, sortOrder: 10 + folder.sort_order })),
87
+ ];
88
+ return rows.map((mailbox) => {
89
+ const count = counts.get(mailbox.id);
90
+ return {
91
+ ...mailbox,
92
+ totalEmails: count?.total ?? 0,
93
+ unreadEmails: count?.unread ?? 0,
94
+ totalThreads: count?.threads ?? 0,
95
+ unreadThreads: count?.unread_threads ?? 0,
96
+ };
97
+ });
98
+ }
99
+
100
+ function ftsQuery(text: string) {
101
+ // Each word must appear; quoting keeps FTS syntax out of user input.
102
+ return text
103
+ .split(/\s+/u)
104
+ .filter(Boolean)
105
+ .map((word) => `"${word.replaceAll('"', '""')}"`)
106
+ .join(" ");
107
+ }
108
+
109
+ export function queryEmails(
110
+ sql: SqlStorage,
111
+ input: {
112
+ userId: string;
113
+ filter: JmapEmailFilter;
114
+ ascending: boolean;
115
+ position: number;
116
+ limit: number;
117
+ collapseThreads: boolean;
118
+ },
119
+ ) {
120
+ const where: string[] = [];
121
+ const params: unknown[] = [];
122
+ const { filter } = input;
123
+ if (filter.inMailbox) {
124
+ where.push(`${EMAIL_MAILBOX_SQL} = ?`);
125
+ params.push(filter.inMailbox);
126
+ }
127
+ if (filter.inMailboxOtherThan?.length) {
128
+ where.push(`${EMAIL_MAILBOX_SQL} not in (${filter.inMailboxOtherThan.map(() => "?").join(", ")})`);
129
+ params.push(...filter.inMailboxOtherThan);
130
+ }
131
+ if (filter.before !== undefined) {
132
+ where.push("e.timeline_at < ?");
133
+ params.push(filter.before);
134
+ }
135
+ if (filter.after !== undefined) {
136
+ where.push("e.timeline_at >= ?");
137
+ params.push(filter.after);
138
+ }
139
+ if (filter.text?.trim()) {
140
+ where.push("e.id in (select email_id from email_search where email_search match ?)");
141
+ params.push(ftsQuery(filter.text));
142
+ }
143
+ for (const [field, column] of [["from", "e.from_json"], ["subject", "e.subject"]] as const) {
144
+ const value = filter[field];
145
+ if (value) {
146
+ where.push(`lower(${column}) like ?`);
147
+ params.push(`%${value.toLowerCase()}%`);
148
+ }
149
+ }
150
+ if (filter.to) {
151
+ where.push("(lower(e.to_json) like ? or lower(e.cc_json) like ?)");
152
+ params.push(`%${filter.to.toLowerCase()}%`, `%${filter.to.toLowerCase()}%`);
153
+ }
154
+ const isUnread = unread(input.userId);
155
+ if (filter.hasKeyword === "$seen") {
156
+ where.push(`not ${isUnread.sql}`);
157
+ params.push(...isUnread.params);
158
+ }
159
+ if (filter.notKeyword === "$seen") {
160
+ where.push(isUnread.sql);
161
+ params.push(...isUnread.params);
162
+ }
163
+ if (filter.hasAttachment !== undefined) {
164
+ where.push(filter.hasAttachment
165
+ ? "json_array_length(e.attachments_json) > 0"
166
+ : "json_array_length(e.attachments_json) = 0");
167
+ }
168
+ const direction = input.ascending ? "asc" : "desc";
169
+ const filtered = `
170
+ select e.id, e.conversation_id, e.timeline_at,
171
+ row_number() over (partition by e.conversation_id order by e.timeline_at desc, e.id desc) as thread_rank
172
+ from emails e join conversations c on c.id = e.conversation_id
173
+ ${where.length ? `where ${where.join(" and ")}` : ""}`;
174
+ const rows = sql.exec<{ id: string; total: number }>(`
175
+ select id, count(*) over () as total from (${filtered})
176
+ ${input.collapseThreads ? "where thread_rank = 1" : ""}
177
+ order by timeline_at ${direction}, id ${direction}
178
+ limit ? offset ?`, ...params, input.limit, input.position).toArray();
179
+ const total = rows[0]?.total ?? sql.exec<{ total: number }>(
180
+ `select count(*) as total from (${filtered}) ${input.collapseThreads ? "where thread_rank = 1" : ""}`,
181
+ ...params,
182
+ ).one().total;
183
+ return { ids: rows.map((row) => row.id), total };
184
+ }
185
+
186
+ /** For each email: its JMAP Mailbox, and whether this user has read it. */
187
+ export function emailPlacement(sql: SqlStorage, userId: string, ids: string[]) {
188
+ if (!ids.length) return new Map<string, { mailboxId: string; seen: boolean }>();
189
+ const isUnread = unread(userId);
190
+ return new Map(
191
+ sql.exec<{ id: string; mailbox: string; is_unread: number }>(`
192
+ select e.id, ${EMAIL_MAILBOX_SQL} as mailbox, ${isUnread.sql} as is_unread
193
+ from emails e join conversations c on c.id = e.conversation_id
194
+ where e.id in (${ids.map(() => "?").join(", ")})`, ...isUnread.params, ...ids)
195
+ .toArray()
196
+ .map((row) => [row.id, { mailboxId: row.mailbox, seen: !row.is_unread }]),
197
+ );
198
+ }
199
+
200
+ export function threadEmails(sql: SqlStorage, threadIds: string[]) {
201
+ const threads = new Map<string, string[]>();
202
+ if (!threadIds.length) return threads;
203
+ for (const row of sql.exec<{ id: string; conversation_id: string }>(
204
+ `select id, conversation_id from emails where conversation_id in (${threadIds.map(() => "?").join(", ")})
205
+ order by timeline_at, id`,
206
+ ...threadIds,
207
+ )) {
208
+ threads.set(row.conversation_id, [...(threads.get(row.conversation_id) ?? []), row.id]);
209
+ }
210
+ return threads;
211
+ }
212
+
213
+ /**
214
+ * Moves the conversations of `emailIds` into a JMAP Mailbox. Conversations
215
+ * move as a whole, as they do in the app. Returns false for an unknown or
216
+ * read-only target.
217
+ */
218
+ export function moveEmails(sql: SqlStorage, emailIds: string[], target: string) {
219
+ if (!emailIds.length) return true;
220
+ let state: string;
221
+ let folderId: string | null = null;
222
+ if (target === "inbox") state = "active";
223
+ else if (target === "archive" || target === "spam" || target === "trash") state = target;
224
+ else if (sql.exec("select 1 from folders where id = ?", target).toArray().length) {
225
+ state = "active";
226
+ folderId = target;
227
+ } else {
228
+ return false;
229
+ }
230
+ sql.exec(
231
+ `update conversations set mailbox_state = ?, folder_id = ?
232
+ where id in (select conversation_id from emails where id in (${emailIds.map(() => "?").join(", ")}))`,
233
+ state,
234
+ folderId,
235
+ ...emailIds,
236
+ );
237
+ return true;
238
+ }
@@ -15,15 +15,7 @@ export type {
15
15
  } from "../../shared/mail-authentication";
16
16
  export type { DeliveryFacts, SenderIntel } from "../../shared/mail-sender-intel";
17
17
 
18
- /**
19
- * Rows written before header parsing carried Cloudflare GraphQL analytics.
20
- * They are re-derived from the stored original on first view.
21
- */
22
- export type LegacyEmailAuthentication = { source: "cloudflare" };
23
-
24
- export type StoredEmailAuthentication =
25
- | import("../../shared/mail-authentication").InboundAuthentication
26
- | LegacyEmailAuthentication;
18
+ export type StoredEmailAuthentication = import("../../shared/mail-authentication").InboundAuthentication;
27
19
 
28
20
  export type MailboxAiConfiguration = {
29
21
  instructions: string;
@@ -31,8 +23,7 @@ export type MailboxAiConfiguration = {
31
23
  };
32
24
 
33
25
  export type EmailAiClassification = {
34
- /** "workers-ai" on results stored before models became configurable. */
35
- source: "ai" | "workers-ai";
26
+ source: "ai";
36
27
  model: string;
37
28
  processedAt: number;
38
29
  spam: boolean;
package/worker/module.ts CHANGED
@@ -16,6 +16,7 @@ import { mailRoutes } from "./mail/routes";
16
16
  import { emailWebhookData } from "./mail/webhook-source";
17
17
  import { seedEmailDemo } from "./mailbox/demo-seed";
18
18
  import { registerMailTools } from "./mcp/tools";
19
+ import { jmapRoutes } from "./jmap/routes";
19
20
 
20
21
  /** Routes the browser and MCP use under /api. */
21
22
  export const mailAccountApi = new Hono<AppEnv>()
@@ -23,6 +24,7 @@ export const mailAccountApi = new Hono<AppEnv>()
23
24
  .route("/admin", reportAdminRoutes);
24
25
 
25
26
  const mailPublicRoutes = new Hono<AppEnv>()
27
+ .route("/", jmapRoutes as unknown as Hono<AppEnv>)
26
28
  .route("/api/downloads", mailDownloadRoutes)
27
29
  .route("/api/demo", demoRoutes)
28
30
  .route("/api/notifications", pushNotificationRoutes);
@@ -1,41 +0,0 @@
1
- /**
2
- * Mailbox migrations from before the 0.1.0 baseline, for Durable Objects
3
- * created by earlier deployments. Applied only to a mailbox whose drizzle
4
- * journal predates the baseline; new mailboxes never run them.
5
- */
6
- export const legacyMailboxMigrations: ReadonlyArray<{ when: number; sql: string }> = [
7
- { when: 1784825133044, sql: "CREATE TABLE `conversations` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`latest_email_id` text NOT NULL,\n\t`timeline_at` integer NOT NULL,\n\t`mailbox_state` text DEFAULT 'active' NOT NULL,\n\t`folder_id` text,\n\t`has_incoming` integer DEFAULT false NOT NULL,\n\t`has_outgoing` integer DEFAULT false NOT NULL,\n\tFOREIGN KEY (`latest_email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `conversations_timeline_idx` ON `conversations` (`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_inbox_timeline_idx` ON `conversations` (`mailbox_state`,`has_incoming`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_sent_timeline_idx` ON `conversations` (`mailbox_state`,`has_outgoing`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_folder_timeline_idx` ON `conversations` (`folder_id`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE TABLE `emails` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`request_fingerprint` text,\n\t`conversation_id` text NOT NULL,\n\t`direction` text NOT NULL,\n\t`message_id_header` text,\n\t`in_reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`references_json` text DEFAULT '[]' NOT NULL,\n\t`from_json` text NOT NULL,\n\t`reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`to_json` text DEFAULT '[]' NOT NULL,\n\t`cc_json` text DEFAULT '[]' NOT NULL,\n\t`bcc_json` text DEFAULT '[]' NOT NULL,\n\t`subject` text DEFAULT '(no subject)' NOT NULL,\n\t`preview` text DEFAULT '' NOT NULL,\n\t`body_text` text,\n\t`quoted_text` text,\n\t`body_html_r2_key` text,\n\t`raw_mime_r2_key` text,\n\t`attachments_json` text DEFAULT '[]' NOT NULL,\n\t`list_id` text,\n\t`list_post_address` text,\n\t`timeline_at` integer NOT NULL,\n\t`transport_state` text NOT NULL,\n\t`transport_error` text,\n\t`delivery_status_json` text DEFAULT '[]' NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `emails_conversation_timeline_idx` ON `emails` (`conversation_id`,`timeline_at`,`id`);--> statement-breakpoint\nCREATE INDEX `emails_message_id_header_idx` ON `emails` (`message_id_header`);--> statement-breakpoint\nCREATE TABLE `folders` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `folders_name_unique` ON `folders` (`name`);--> statement-breakpoint\nCREATE INDEX `folders_order_idx` ON `folders` (`sort_order`,`name`);--> statement-breakpoint\nCREATE TABLE `pending_inbound` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`raw_object_key` text NOT NULL,\n\t`envelope_from` text NOT NULL,\n\t`envelope_to` text NOT NULL,\n\t`received_at` integer NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_inbound_next_attempt_idx` ON `pending_inbound` (`next_attempt_at`,`received_at`);--> statement-breakpoint\n-- Runtime-only search/projection objects: Drizzle snapshots do not model them.\nCREATE VIRTUAL TABLE `email_search` USING fts5(\n\t`email_id` UNINDEXED,\n\t`conversation_id` UNINDEXED,\n\t`subject`,\n\t`addresses`,\n\t`body`,\n\ttokenize = 'unicode61 remove_diacritics 2'\n);--> statement-breakpoint\nCREATE TRIGGER `emails_after_insert`\nAFTER INSERT ON `emails`\nBEGIN\n\tINSERT INTO `conversations` (\n\t\t`id`,\n\t\t`latest_email_id`,\n\t\t`timeline_at`,\n\t\t`mailbox_state`,\n\t\t`folder_id`,\n\t\t`has_incoming`,\n\t\t`has_outgoing`\n\t)\n\tVALUES (\n\t\tNEW.`conversation_id`,\n\t\tNEW.`id`,\n\t\tNEW.`timeline_at`,\n\t\t'active',\n\t\tNULL,\n\t\tNEW.`direction` = 'incoming',\n\t\tNEW.`direction` = 'outgoing'\n\t)\n\tON CONFLICT(`id`) DO UPDATE SET\n\t\t`latest_email_id` = CASE\n\t\t\tWHEN NEW.`timeline_at` > `conversations`.`timeline_at`\n\t\t\t\tOR (\n\t\t\t\t\tNEW.`timeline_at` = `conversations`.`timeline_at`\n\t\t\t\t\tAND NEW.`id` > `conversations`.`latest_email_id`\n\t\t\t\t)\n\t\t\tTHEN NEW.`id`\n\t\t\tELSE `conversations`.`latest_email_id`\n\t\tEND,\n\t\t`timeline_at` = MAX(`conversations`.`timeline_at`, NEW.`timeline_at`),\n\t\t`mailbox_state` = CASE\n\t\t\tWHEN `conversations`.`mailbox_state` IN ('archive', 'trash')\n\t\t\t\tOR (\n\t\t\t\t\t`conversations`.`mailbox_state` = 'spam'\n\t\t\t\t\tAND NEW.`direction` = 'outgoing'\n\t\t\t\t)\n\t\t\tTHEN 'active'\n\t\t\tELSE `conversations`.`mailbox_state`\n\t\tEND,\n\t\t`has_incoming` = `conversations`.`has_incoming`\n\t\t\tOR NEW.`direction` = 'incoming',\n\t\t`has_outgoing` = `conversations`.`has_outgoing`\n\t\t\tOR NEW.`direction` = 'outgoing';\n\n\tINSERT INTO `email_search` (\n\t\t`email_id`,\n\t\t`conversation_id`,\n\t\t`subject`,\n\t\t`addresses`,\n\t\t`body`\n\t)\n\tVALUES (\n\t\tNEW.`id`,\n\t\tNEW.`conversation_id`,\n\t\tNEW.`subject`,\n\t\tCOALESCE(NEW.`from_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`reply_to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`cc_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`bcc_json`, ''),\n\t\tCOALESCE(NEW.`body_text`, '') || ' ' || COALESCE(NEW.`preview`, '')\n\t);\nEND;\n" },
8
- { when: 1787348208125, sql: "CREATE TABLE `email_read_states` (\n\t`user_id` text NOT NULL,\n\t`email_id` text NOT NULL,\n\t`read_at` integer NOT NULL,\n\tPRIMARY KEY(`user_id`, `email_id`),\n\tFOREIGN KEY (`email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE cascade\n);\n--> statement-breakpoint\nCREATE INDEX `email_read_states_email_idx` ON `email_read_states` (`email_id`);" },
9
- { when: 1787422760085, sql: "CREATE TABLE `pending_object_deletions` (\n\t`object_key` text PRIMARY KEY NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_object_deletions_next_attempt_idx` ON `pending_object_deletions` (`next_attempt_at`);" },
10
- { when: 1787514819958, sql: "ALTER TABLE `emails` ADD `authentication_results_json` text;" },
11
- { when: 1787522950002, sql: "CREATE TABLE `mailbox_ai_configuration` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`instructions` text DEFAULT '' NOT NULL,\n\t`confidence_threshold` integer DEFAULT 75 NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE `emails` ADD `ai_classification_json` text;--> statement-breakpoint\nALTER TABLE `pending_inbound` ADD `ai_attempts` integer DEFAULT 0 NOT NULL;\n" },
12
- { when: 1791081433051, sql: "CREATE TABLE `pending_office_previews` (\n\t`source_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text NOT NULL,\n\t`attachment_id` text NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_office_previews_next_attempt_idx` ON `pending_office_previews` (`next_attempt_at`);" },
13
- { when: 1793417083777, sql: "ALTER TABLE `emails` ADD `envelope_from` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `envelope_to` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `list_unsubscribe_json` text;" },
14
- { when: 1793418627171, sql: "CREATE TABLE `senders` (\n\t`address` text PRIMARY KEY NOT NULL,\n\t`domain` text NOT NULL,\n\t`first_seen_at` integer,\n\t`last_seen_at` integer,\n\t`message_count` integer DEFAULT 0 NOT NULL,\n\t`outbound_count` integer DEFAULT 0 NOT NULL,\n\t`last_outbound_at` integer,\n\t`blocked_at` integer,\n\t`trusted_at` integer,\n\t`reported_at` integer\n);\n--> statement-breakpoint\nCREATE INDEX `senders_domain_idx` ON `senders` (`domain`);--> statement-breakpoint\nALTER TABLE `emails` ADD `sender_intel_json` text;--> statement-breakpoint\nINSERT INTO `senders` (`address`, `domain`, `first_seen_at`, `last_seen_at`, `message_count`)\nSELECT `address`, substr(`address`, instr(`address`, '@') + 1), min(`timeline_at`), max(`timeline_at`), count(*)\nFROM (\n\tSELECT lower(json_extract(`from_json`, '$[0].address')) AS `address`, `timeline_at`\n\tFROM `emails`\n\tWHERE `direction` = 'incoming'\n)\nWHERE `address` LIKE '%_@_%'\nGROUP BY `address`;--> statement-breakpoint\nINSERT INTO `senders` (`address`, `domain`, `outbound_count`, `last_outbound_at`)\nSELECT `address`, substr(`address`, instr(`address`, '@') + 1), count(*), max(`timeline_at`)\nFROM (\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')) AS `address`, `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`to_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n\tUNION ALL\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')), `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`cc_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n\tUNION ALL\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')), `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`bcc_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n)\nWHERE `address` LIKE '%_@_%'\nGROUP BY `address`\nON CONFLICT (`address`) DO UPDATE SET\n\t`outbound_count` = excluded.`outbound_count`,\n\t`last_outbound_at` = excluded.`last_outbound_at`;\n" },
15
- { when: 1793439647535, sql: "CREATE TABLE `mail_rules` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL,\n\t`enabled` integer DEFAULT true NOT NULL,\n\t`conditions_json` text NOT NULL,\n\t`actions_json` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `mail_rules_order_idx` ON `mail_rules` (`sort_order`,`created_at`);--> statement-breakpoint\nCREATE TABLE `sender_feedback` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`address` text NOT NULL,\n\t`domain` text NOT NULL,\n\t`email_id` text,\n\t`label` text NOT NULL,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `sender_feedback_address_idx` ON `sender_feedback` (`address`,`created_at`);--> statement-breakpoint\nCREATE INDEX `sender_feedback_domain_idx` ON `sender_feedback` (`domain`);--> statement-breakpoint\nCREATE TABLE `unsubscriptions` (\n\t`list_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text,\n\t`method` text NOT NULL,\n\t`status` text NOT NULL,\n\t`target` text,\n\t`detail` text,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE `emails` ADD `delivery_json` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `screening_json` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `report_label` text;" },
16
- { when: 1793467839387, sql: "ALTER TABLE `pending_inbound` ADD `list_address` text;" },
17
- ];
18
-
19
- /**
20
- * Brings a mailbox created before the baseline up to it: applies the legacy
21
- * migrations it has not run, then records the baseline as applied so drizzle
22
- * does not create its tables a second time. A no-op for new mailboxes.
23
- */
24
- export function upgradeLegacyMailbox(sql: SqlStorage, baselineWhen: number) {
25
- const hasJournal = sql
26
- .exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'")
27
- .toArray().length > 0;
28
- if (!hasJournal) return;
29
- const [{ last }] = sql
30
- .exec<{ last: number | null }>("SELECT max(created_at) AS last FROM __drizzle_migrations")
31
- .toArray();
32
- if (last === null || Number(last) >= baselineWhen) return;
33
- for (const migration of legacyMailboxMigrations) {
34
- if (migration.when <= Number(last)) continue;
35
- for (const statement of migration.sql.split("--> statement-breakpoint")) {
36
- if (statement.trim()) sql.exec(statement);
37
- }
38
- sql.exec("INSERT INTO __drizzle_migrations (hash, created_at) VALUES ('', ?)", migration.when);
39
- }
40
- sql.exec("INSERT INTO __drizzle_migrations (hash, created_at) VALUES ('', ?)", baselineWhen);
41
- }