@open-workspace/email 0.2.0 → 0.4.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.
Files changed (223) hide show
  1. package/README.md +23 -20
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/0000_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +78 -26
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +84 -52
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +283 -171
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +153 -91
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +597 -227
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -1,3 +1,4 @@
1
+ import { defaultSystemFolderOrder } from "./folder-model";
1
2
  /**
2
3
  * JMAP views over a mailbox's SQLite store (RFC 8621). A JMAP Mailbox is a
3
4
  * system folder or a custom folder; an email sits in exactly one, derived
@@ -15,11 +16,11 @@ export const EMAIL_MAILBOX_SQL = `case
15
16
  end`;
16
17
 
17
18
  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 },
19
+ { id: "inbox", name: "Inbox", role: "inbox" },
20
+ { id: "sent", name: "Sent", role: "sent" },
21
+ { id: "archive", name: "Archive", role: "archive" },
22
+ { id: "spam", name: "Spam", role: "junk" },
23
+ { id: "trash", name: "Trash", role: "trash" },
23
24
  ] as const;
24
25
 
25
26
  export type JmapMailboxRow = {
@@ -65,8 +66,17 @@ const unread = (userId: string) => ({
65
66
 
66
67
  export function mailboxes(sql: SqlStorage, userId: string): JmapMailboxRow[] {
67
68
  const isUnread = unread(userId);
69
+
68
70
  const counts = new Map(
69
- sql.exec<{ mailbox: string; total: number; unread: number; threads: number; unread_threads: number }>(`
71
+ sql
72
+ .exec<{
73
+ mailbox: string;
74
+ total: number;
75
+ unread: number;
76
+ threads: number;
77
+ unread_threads: number;
78
+ }>(
79
+ `
70
80
  select mailbox,
71
81
  count(*) as total,
72
82
  sum(is_unread) as unread,
@@ -76,17 +86,49 @@ export function mailboxes(sql: SqlStorage, userId: string): JmapMailboxRow[] {
76
86
  select ${EMAIL_MAILBOX_SQL} as mailbox, e.conversation_id, ${isUnread.sql} as is_unread
77
87
  from emails e join conversations c on c.id = e.conversation_id
78
88
  )
79
- group by mailbox`, ...isUnread.params).toArray().map((row) => [row.mailbox, row]),
89
+ group by mailbox`,
90
+ ...isUnread.params
91
+ )
92
+ .toArray()
93
+ .map((row) => [row.mailbox, row])
80
94
  );
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();
95
+
96
+ const custom = sql
97
+ .exec<{ id: string; name: string; sort_order: number }>(
98
+ "select id, name, sort_order from folders order by sort_order, name"
99
+ )
100
+ .toArray();
101
+
102
+ // Mailbox order is the mail app's folder order, system folders where they were moved.
103
+ const systemOrder = new Map(
104
+ sql
105
+ .exec<{ folder_id: string; sort_order: number }>(
106
+ "select folder_id, sort_order from system_folder_order"
107
+ )
108
+ .toArray()
109
+ .map((row) => [row.folder_id, row.sort_order])
110
+ );
111
+
84
112
  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 })),
113
+ ...SYSTEM_MAILBOXES.map((mailbox) => ({
114
+ ...mailbox,
115
+ sortOrder:
116
+ mailbox.id === "inbox"
117
+ ? 0
118
+ : (systemOrder.get(mailbox.id) ??
119
+ defaultSystemFolderOrder(mailbox.id)),
120
+ })),
121
+ ...custom.map((folder) => ({
122
+ id: folder.id,
123
+ name: folder.name,
124
+ role: null,
125
+ sortOrder: folder.sort_order,
126
+ })),
87
127
  ];
128
+
88
129
  return rows.map((mailbox) => {
89
130
  const count = counts.get(mailbox.id);
131
+
90
132
  return {
91
133
  ...mailbox,
92
134
  totalEmails: count?.total ?? 0,
@@ -115,98 +157,150 @@ export function queryEmails(
115
157
  position: number;
116
158
  limit: number;
117
159
  collapseThreads: boolean;
118
- },
160
+ }
119
161
  ) {
120
162
  const where: string[] = [];
121
163
  const params: unknown[] = [];
122
164
  const { filter } = input;
165
+
123
166
  if (filter.inMailbox) {
124
167
  where.push(`${EMAIL_MAILBOX_SQL} = ?`);
125
168
  params.push(filter.inMailbox);
126
169
  }
170
+
127
171
  if (filter.inMailboxOtherThan?.length) {
128
- where.push(`${EMAIL_MAILBOX_SQL} not in (${filter.inMailboxOtherThan.map(() => "?").join(", ")})`);
172
+ where.push(
173
+ `${EMAIL_MAILBOX_SQL} not in (${filter.inMailboxOtherThan.map(() => "?").join(", ")})`
174
+ );
129
175
  params.push(...filter.inMailboxOtherThan);
130
176
  }
177
+
131
178
  if (filter.before !== undefined) {
132
179
  where.push("e.timeline_at < ?");
133
180
  params.push(filter.before);
134
181
  }
182
+
135
183
  if (filter.after !== undefined) {
136
184
  where.push("e.timeline_at >= ?");
137
185
  params.push(filter.after);
138
186
  }
187
+
139
188
  if (filter.text?.trim()) {
140
- where.push("e.id in (select email_id from email_search where email_search match ?)");
189
+ where.push(
190
+ "e.id in (select email_id from email_search where email_search match ?)"
191
+ );
141
192
  params.push(ftsQuery(filter.text));
142
193
  }
143
- for (const [field, column] of [["from", "e.from_json"], ["subject", "e.subject"]] as const) {
194
+
195
+ for (const [field, column] of [
196
+ ["from", "e.from_json"],
197
+ ["subject", "e.subject"],
198
+ ] as const) {
144
199
  const value = filter[field];
200
+
145
201
  if (value) {
146
202
  where.push(`lower(${column}) like ?`);
147
203
  params.push(`%${value.toLowerCase()}%`);
148
204
  }
149
205
  }
206
+
150
207
  if (filter.to) {
151
208
  where.push("(lower(e.to_json) like ? or lower(e.cc_json) like ?)");
152
209
  params.push(`%${filter.to.toLowerCase()}%`, `%${filter.to.toLowerCase()}%`);
153
210
  }
211
+
154
212
  const isUnread = unread(input.userId);
213
+
155
214
  if (filter.hasKeyword === "$seen") {
156
215
  where.push(`not ${isUnread.sql}`);
157
216
  params.push(...isUnread.params);
158
217
  }
218
+
159
219
  if (filter.notKeyword === "$seen") {
160
220
  where.push(isUnread.sql);
161
221
  params.push(...isUnread.params);
162
222
  }
223
+
163
224
  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");
225
+ where.push(
226
+ filter.hasAttachment
227
+ ? "json_array_length(e.attachments_json) > 0"
228
+ : "json_array_length(e.attachments_json) = 0"
229
+ );
167
230
  }
231
+
168
232
  const direction = input.ascending ? "asc" : "desc";
233
+
169
234
  const filtered = `
170
235
  select e.id, e.conversation_id, e.timeline_at,
171
236
  row_number() over (partition by e.conversation_id order by e.timeline_at desc, e.id desc) as thread_rank
172
237
  from emails e join conversations c on c.id = e.conversation_id
173
238
  ${where.length ? `where ${where.join(" and ")}` : ""}`;
174
- const rows = sql.exec<{ id: string; total: number }>(`
239
+
240
+ const rows = sql
241
+ .exec<{ id: string; total: number }>(
242
+ `
175
243
  select id, count(*) over () as total from (${filtered})
176
244
  ${input.collapseThreads ? "where thread_rank = 1" : ""}
177
245
  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;
246
+ limit ? offset ?`,
247
+ ...params,
248
+ input.limit,
249
+ input.position
250
+ )
251
+ .toArray();
252
+
253
+ const total =
254
+ rows[0]?.total ??
255
+ sql
256
+ .exec<{ total: number }>(
257
+ `select count(*) as total from (${filtered}) ${input.collapseThreads ? "where thread_rank = 1" : ""}`,
258
+ ...params
259
+ )
260
+ .one().total;
261
+
183
262
  return { ids: rows.map((row) => row.id), total };
184
263
  }
185
264
 
186
265
  /** For each email: its JMAP Mailbox, and whether this user has read it. */
187
266
  export function emailPlacement(sql: SqlStorage, userId: string, ids: string[]) {
188
- if (!ids.length) return new Map<string, { mailboxId: string; seen: boolean }>();
267
+ if (!ids.length) {
268
+ return new Map<string, { mailboxId: string; seen: boolean }>();
269
+ }
270
+
189
271
  const isUnread = unread(userId);
272
+
190
273
  return new Map(
191
- sql.exec<{ id: string; mailbox: string; is_unread: number }>(`
274
+ sql
275
+ .exec<{ id: string; mailbox: string; is_unread: number }>(
276
+ `
192
277
  select e.id, ${EMAIL_MAILBOX_SQL} as mailbox, ${isUnread.sql} as is_unread
193
278
  from emails e join conversations c on c.id = e.conversation_id
194
- where e.id in (${ids.map(() => "?").join(", ")})`, ...isUnread.params, ...ids)
279
+ where e.id in (${ids.map(() => "?").join(", ")})`,
280
+ ...isUnread.params,
281
+ ...ids
282
+ )
195
283
  .toArray()
196
- .map((row) => [row.id, { mailboxId: row.mailbox, seen: !row.is_unread }]),
284
+ .map((row) => [row.id, { mailboxId: row.mailbox, seen: !row.is_unread }])
197
285
  );
198
286
  }
199
287
 
200
288
  export function threadEmails(sql: SqlStorage, threadIds: string[]) {
201
289
  const threads = new Map<string, string[]>();
290
+
202
291
  if (!threadIds.length) return threads;
292
+
203
293
  for (const row of sql.exec<{ id: string; conversation_id: string }>(
204
294
  `select id, conversation_id from emails where conversation_id in (${threadIds.map(() => "?").join(", ")})
205
295
  order by timeline_at, id`,
206
- ...threadIds,
296
+ ...threadIds
207
297
  )) {
208
- threads.set(row.conversation_id, [...(threads.get(row.conversation_id) ?? []), row.id]);
298
+ threads.set(row.conversation_id, [
299
+ ...(threads.get(row.conversation_id) ?? []),
300
+ row.id,
301
+ ]);
209
302
  }
303
+
210
304
  return threads;
211
305
  }
212
306
 
@@ -215,24 +309,34 @@ export function threadEmails(sql: SqlStorage, threadIds: string[]) {
215
309
  * move as a whole, as they do in the app. Returns false for an unknown or
216
310
  * read-only target.
217
311
  */
218
- export function moveEmails(sql: SqlStorage, emailIds: string[], target: string) {
312
+ export function moveEmails(
313
+ sql: SqlStorage,
314
+ emailIds: string[],
315
+ target: string
316
+ ) {
219
317
  if (!emailIds.length) return true;
220
318
  let state: string;
221
319
  let folderId: string | null = null;
320
+
222
321
  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) {
322
+ else if (target === "archive" || target === "spam" || target === "trash") {
323
+ state = target;
324
+ } else if (
325
+ sql.exec("select 1 from folders where id = ?", target).toArray().length
326
+ ) {
225
327
  state = "active";
226
328
  folderId = target;
227
329
  } else {
228
330
  return false;
229
331
  }
332
+
230
333
  sql.exec(
231
334
  `update conversations set mailbox_state = ?, folder_id = ?
232
335
  where id in (select conversation_id from emails where id in (${emailIds.map(() => "?").join(", ")}))`,
233
336
  state,
234
337
  folderId,
235
- ...emailIds,
338
+ ...emailIds
236
339
  );
340
+
237
341
  return true;
238
342
  }
@@ -13,17 +13,14 @@ export type {
13
13
  InboundAuthentication,
14
14
  ListUnsubscribe,
15
15
  } from "../../shared/mail-authentication";
16
- export type { DeliveryFacts, SenderIntel } from "../../shared/mail-sender-intel";
17
16
 
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" };
17
+ export type {
18
+ DeliveryFacts,
19
+ SenderIntel,
20
+ } from "../../shared/mail-sender-intel";
23
21
 
24
22
  export type StoredEmailAuthentication =
25
- | import("../../shared/mail-authentication").InboundAuthentication
26
- | LegacyEmailAuthentication;
23
+ import("../../shared/mail-authentication").InboundAuthentication;
27
24
 
28
25
  export type MailboxAiConfiguration = {
29
26
  instructions: string;
@@ -31,8 +28,7 @@ export type MailboxAiConfiguration = {
31
28
  };
32
29
 
33
30
  export type EmailAiClassification = {
34
- /** "workers-ai" on results stored before models became configurable. */
35
- source: "ai" | "workers-ai";
31
+ source: "ai";
36
32
  model: string;
37
33
  processedAt: number;
38
34
  spam: boolean;
@@ -42,12 +38,9 @@ export type EmailAiClassification = {
42
38
  reason: string;
43
39
  };
44
40
 
45
- /** What blocks and rules decided for an incoming message at ingestion. */
41
+ /** What sender blocks decided for an incoming message at ingestion. */
46
42
  export type EmailScreening = {
47
43
  blocked: "mailbox" | "workspace" | null;
48
- ruleIds: string[];
49
- /** Matching rules chose the destination, so AI sorting was skipped. */
50
- ruleDestination: boolean;
51
44
  };
52
45
 
53
46
  export type StoredAttachment = {
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  MAX_OFFICE_PREVIEW_BYTES,
3
3
  officePreviewExtension,
4
- type OfficePreviewJob,
5
4
  } from "../../shared/office-preview";
5
+ import type { OfficePreviewJob } from "../../shared/office-preview";
6
6
  import type { NewEmail } from "./schema";
7
7
 
8
8
  export function prepareOfficePreviews(email: NewEmail): NewEmail {
@@ -11,14 +11,20 @@ export function prepareOfficePreviews(email: NewEmail): NewEmail {
11
11
  attachmentsJson: email.attachmentsJson?.map((file) => ({
12
12
  ...file,
13
13
  pdfPreviewStatus: officePreviewExtension(file.filename)
14
- ? file.size <= MAX_OFFICE_PREVIEW_BYTES ? "pending" : "failed"
14
+ ? file.size <= MAX_OFFICE_PREVIEW_BYTES
15
+ ? "pending"
16
+ : "failed"
15
17
  : undefined,
16
18
  })),
17
19
  };
18
20
  }
19
21
 
20
22
  export function hasPendingOfficePreviews(email: NewEmail) {
21
- return email.attachmentsJson?.some((file) => file.pdfPreviewStatus === "pending") ?? false;
23
+ return (
24
+ email.attachmentsJson?.some(
25
+ (file) => file.pdfPreviewStatus === "pending"
26
+ ) ?? false
27
+ );
22
28
  }
23
29
 
24
30
  export function insertOfficePreviewJobs(sql: SqlStorage, email: NewEmail) {
@@ -29,45 +35,70 @@ export function insertOfficePreviewJobs(sql: SqlStorage, email: NewEmail) {
29
35
  `insert into pending_office_previews
30
36
  (source_key, email_id, attachment_id, attempts, next_attempt_at)
31
37
  values (?, ?, ?, 0, ?) on conflict do nothing`,
32
- file.r2Key, email.id, file.id, Date.now(),
38
+ file.r2Key,
39
+ email.id,
40
+ file.id,
41
+ Date.now()
33
42
  );
34
43
  }
35
44
  }
36
45
 
37
- export async function dispatchOfficePreviewJobs(sql: SqlStorage, env: Env, mailboxId: string) {
38
- const jobs = sql.exec<{
39
- source_key: string; email_id: string; attachment_id: string; attempts: number;
40
- }>(
41
- "select * from pending_office_previews where next_attempt_at <= ? order by next_attempt_at limit 10",
42
- Date.now(),
43
- ).toArray();
46
+ export async function dispatchOfficePreviewJobs(
47
+ sql: SqlStorage,
48
+ env: Env,
49
+ mailboxId: string
50
+ ) {
51
+ const jobs = sql
52
+ .exec<{
53
+ source_key: string;
54
+ email_id: string;
55
+ attachment_id: string;
56
+ attempts: number;
57
+ }>(
58
+ "select * from pending_office_previews where next_attempt_at <= ? order by next_attempt_at limit 10",
59
+ Date.now()
60
+ )
61
+ .toArray();
62
+
44
63
  if (!jobs.length) return;
64
+
45
65
  try {
46
- await env.OFFICE_PREVIEWS.sendBatch(jobs.map((job) => ({
47
- body: {
48
- mailboxId,
49
- messageId: job.email_id,
50
- attachmentId: job.attachment_id,
51
- sourceKey: job.source_key,
52
- } satisfies OfficePreviewJob,
53
- })));
66
+ await env.OFFICE_PREVIEWS.sendBatch(
67
+ jobs.map((job) => ({
68
+ body: {
69
+ mailboxId,
70
+ messageId: job.email_id,
71
+ attachmentId: job.attachment_id,
72
+ sourceKey: job.source_key,
73
+ } satisfies OfficePreviewJob,
74
+ }))
75
+ );
76
+
54
77
  for (const job of jobs) {
55
- sql.exec("delete from pending_office_previews where source_key = ?", job.source_key);
78
+ sql.exec(
79
+ "delete from pending_office_previews where source_key = ?",
80
+ job.source_key
81
+ );
56
82
  }
57
83
  } catch (error) {
58
84
  for (const job of jobs) {
59
- const delay = Math.min(3_600_000, 5_000 * 2 ** Math.min(job.attempts, 10));
85
+ const delay = Math.min(3_600_000, 5000 * 2 ** Math.min(job.attempts, 10));
86
+
60
87
  sql.exec(
61
88
  "update pending_office_previews set attempts = attempts + 1, next_attempt_at = ? where source_key = ?",
62
- Date.now() + delay, job.source_key,
89
+ Date.now() + delay,
90
+ job.source_key
63
91
  );
64
92
  }
93
+
65
94
  console.error("Could not queue Office previews", error);
66
95
  }
67
96
  }
68
97
 
69
98
  export function nextOfficePreviewAttempt(sql: SqlStorage) {
70
- return sql.exec<{ next_attempt_at: number }>(
71
- "select next_attempt_at from pending_office_previews order by next_attempt_at limit 1",
72
- ).toArray()[0]?.next_attempt_at;
99
+ return sql
100
+ .exec<{ next_attempt_at: number }>(
101
+ "select next_attempt_at from pending_office_previews order by next_attempt_at limit 1"
102
+ )
103
+ .toArray()[0]?.next_attempt_at;
73
104
  }