@open-workspace/email 0.4.1 → 0.5.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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -1,342 +1,210 @@
1
- import { defaultSystemFolderOrder } from "./folder-model";
1
+ import { inJsonList } from "@open-workspace/core/module";
2
+ import { and, eq, sql as query } from "drizzle-orm";
3
+ import { alias } from "drizzle-orm/sqlite-core";
4
+ import { z } from "zod";
5
+
6
+ import { EMAIL_MAILBOXES_SQL, IDS, filteredEmails } from "./jmap-query-filter";
7
+ import type { EmailQueryInput } from "./jmap-query-filter";
8
+ import { drafts, conversations, emails, emailReadStates } from "./schema";
9
+ import type { MailboxContext, MailboxDatabase } from "./support";
10
+
2
11
  /**
3
12
  * JMAP views over a mailbox's SQLite store (RFC 8621). A JMAP Mailbox is a
4
- * system folder or a custom folder; an email sits in exactly one, derived
5
- * from its conversation's state and its own direction.
13
+ * system folder or a custom folder. An email is in each the app shows it
14
+ * in: a custom folder is a label inside the Inbox, as in the app, so
15
+ * received mail in one is in Inbox and that folder; sent mail is in Sent
16
+ * and, archived or in Spam, there too.
6
17
  */
7
18
 
8
- /** Which JMAP Mailbox an email (alias e) of conversation (alias c) is in. */
9
- export const EMAIL_MAILBOX_SQL = `case
10
- when c.mailbox_state = 'trash' then 'trash'
11
- when c.mailbox_state = 'spam' then 'spam'
12
- when c.mailbox_state = 'archive' then 'archive'
13
- when e.direction = 'outgoing' then 'sent'
14
- when c.folder_id is not null then c.folder_id
15
- else 'inbox'
16
- end`;
17
-
18
- const SYSTEM_MAILBOXES = [
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" },
24
- ] as const;
25
-
26
- export type JmapMailboxRow = {
27
- id: string;
28
- name: string;
29
- role: string | null;
30
- sortOrder: number;
31
- totalEmails: number;
32
- unreadEmails: number;
33
- totalThreads: number;
34
- unreadThreads: number;
35
- };
36
-
37
- export type JmapEmailFilter = {
38
- inMailbox?: string;
39
- inMailboxOtherThan?: string[];
40
- before?: number;
41
- after?: number;
42
- text?: string;
43
- from?: string;
44
- to?: string;
45
- subject?: string;
46
- hasKeyword?: string;
47
- notKeyword?: string;
48
- hasAttachment?: boolean;
49
- };
50
-
51
- const STATE_KEY = "jmap:state";
52
-
53
- /** A counter bumped on every change; JMAP clients compare it to resync. */
54
- export function jmapState(storage: DurableObjectStorage) {
55
- return String(storage.kv.get<number>(STATE_KEY) ?? 0);
56
- }
57
-
58
- export function bumpJmapState(storage: DurableObjectStorage) {
59
- storage.kv.put(STATE_KEY, (storage.kv.get<number>(STATE_KEY) ?? 0) + 1);
60
- }
19
+ export { EMAIL_MAILBOXES_SQL };
61
20
 
62
- const unread = (userId: string) => ({
63
- sql: "not exists (select 1 from email_read_states r where r.email_id = e.id and r.user_id = ?)",
64
- params: [userId],
65
- });
66
-
67
- export function mailboxes(sql: SqlStorage, userId: string): JmapMailboxRow[] {
68
- const isUnread = unread(userId);
69
-
70
- const counts = new Map(
71
- sql
72
- .exec<{
73
- mailbox: string;
74
- total: number;
75
- unread: number;
76
- threads: number;
77
- unread_threads: number;
78
- }>(
79
- `
80
- select mailbox,
81
- count(*) as total,
82
- sum(is_unread) as unread,
83
- count(distinct conversation_id) as threads,
84
- count(distinct case when is_unread then conversation_id end) as unread_threads
85
- from (
86
- select ${EMAIL_MAILBOX_SQL} as mailbox, e.conversation_id, ${isUnread.sql} as is_unread
87
- from emails e join conversations c on c.id = e.conversation_id
88
- )
89
- group by mailbox`,
90
- ...isUnread.params
91
- )
92
- .toArray()
93
- .map((row) => [row.mailbox, row])
94
- );
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
-
112
- const rows = [
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
- })),
127
- ];
128
-
129
- return rows.map((mailbox) => {
130
- const count = counts.get(mailbox.id);
131
-
132
- return {
133
- ...mailbox,
134
- totalEmails: count?.total ?? 0,
135
- unreadEmails: count?.unread ?? 0,
136
- totalThreads: count?.threads ?? 0,
137
- unreadThreads: count?.unread_threads ?? 0,
138
- };
139
- });
140
- }
141
-
142
- function ftsQuery(text: string) {
143
- // Each word must appear; quoting keeps FTS syntax out of user input.
144
- return text
145
- .split(/\s+/u)
146
- .filter(Boolean)
147
- .map((word) => `"${word.replaceAll('"', '""')}"`)
148
- .join(" ");
149
- }
21
+ export type { JmapEmailFilter } from "./jmap-query-filter";
150
22
 
151
23
  export function queryEmails(
152
- sql: SqlStorage,
153
- input: {
154
- userId: string;
155
- filter: JmapEmailFilter;
156
- ascending: boolean;
24
+ m: MailboxContext,
25
+ input: EmailQueryInput & {
26
+ calculateTotal: boolean;
157
27
  position: number;
158
28
  limit: number;
159
- collapseThreads: boolean;
29
+ anchor: string | null;
30
+ anchorOffset: number;
160
31
  }
161
32
  ) {
162
- const where: string[] = [];
163
- const params: unknown[] = [];
164
- const { filter } = input;
165
-
166
- if (filter.inMailbox) {
167
- where.push(`${EMAIL_MAILBOX_SQL} = ?`);
168
- params.push(filter.inMailbox);
169
- }
170
-
171
- if (filter.inMailboxOtherThan?.length) {
172
- where.push(
173
- `${EMAIL_MAILBOX_SQL} not in (${filter.inMailboxOtherThan.map(() => "?").join(", ")})`
174
- );
175
- params.push(...filter.inMailboxOtherThan);
176
- }
177
-
178
- if (filter.before !== undefined) {
179
- where.push("e.timeline_at < ?");
180
- params.push(filter.before);
181
- }
182
-
183
- if (filter.after !== undefined) {
184
- where.push("e.timeline_at >= ?");
185
- params.push(filter.after);
186
- }
33
+ const { matches, order, params } = filteredEmails(m.db, input);
34
+ const { sql } = m.state.storage;
187
35
 
188
- if (filter.text?.trim()) {
189
- where.push(
190
- "e.id in (select email_id from email_search where email_search match ?)"
191
- );
192
- params.push(ftsQuery(filter.text));
193
- }
36
+ const count = () =>
37
+ sql
38
+ .exec<{ total: number }>(`select count(*) as total ${matches}`, ...params)
39
+ .one().total;
194
40
 
195
- for (const [field, column] of [
196
- ["from", "e.from_json"],
197
- ["subject", "e.subject"],
198
- ] as const) {
199
- const value = filter[field];
41
+ let { position } = input;
42
+ let total: number | undefined;
200
43
 
201
- if (value) {
202
- where.push(`lower(${column}) like ?`);
203
- params.push(`%${value.toLowerCase()}%`);
204
- }
205
- }
44
+ if (input.anchor !== null) {
45
+ // Rank after filtering and collapsing, in the same order used to return the page.
46
+ const anchor = sql
47
+ .exec<{ idx: number }>(
48
+ `select idx from (select id, row_number() over (${order}) - 1 as idx ${matches}) where id = ?`,
49
+ ...params,
50
+ input.anchor
51
+ )
52
+ .toArray()[0];
206
53
 
207
- if (filter.to) {
208
- where.push("(lower(e.to_json) like ? or lower(e.cc_json) like ?)");
209
- params.push(`%${filter.to.toLowerCase()}%`, `%${filter.to.toLowerCase()}%`);
54
+ if (!anchor) return null;
55
+ position = Math.max(0, anchor.idx + input.anchorOffset);
56
+ } else if (position < 0) {
57
+ total = count();
58
+ position = Math.max(0, total + position);
210
59
  }
211
60
 
212
- const isUnread = unread(input.userId);
61
+ const includeCount = input.calculateTotal && total === undefined;
62
+
63
+ const rows = input.limit
64
+ ? sql
65
+ .exec<{ id: string; total?: number }>(
66
+ `select id${includeCount ? ", count(*) over () as total" : ""} ${matches} ${order} limit ? offset ?`,
67
+ ...params,
68
+ input.limit,
69
+ position
70
+ )
71
+ .toArray()
72
+ : [];
73
+
74
+ return {
75
+ position,
76
+ ids: rows.map((row) => row.id),
77
+ total: input.calculateTotal ? (total ?? rows[0]?.total ?? count()) : null,
78
+ };
79
+ }
213
80
 
214
- if (filter.hasKeyword === "$seen") {
215
- where.push(`not ${isUnread.sql}`);
216
- params.push(...isUnread.params);
217
- }
81
+ /** Count the filtered list, including any thread collapse, without loading its rows. */
82
+ export function countQueryEmails(m: MailboxContext, input: EmailQueryInput) {
83
+ const { matches, params } = filteredEmails(m.db, input);
84
+ const { sql } = m.state.storage;
218
85
 
219
- if (filter.notKeyword === "$seen") {
220
- where.push(isUnread.sql);
221
- params.push(...isUnread.params);
222
- }
223
-
224
- if (filter.hasAttachment !== undefined) {
225
- where.push(
226
- filter.hasAttachment
227
- ? "json_array_length(e.attachments_json) > 0"
228
- : "json_array_length(e.attachments_json) = 0"
229
- );
230
- }
231
-
232
- const direction = input.ascending ? "asc" : "desc";
86
+ return sql
87
+ .exec<{ total: number }>(`select count(*) as total ${matches}`, ...params)
88
+ .one().total;
89
+ }
233
90
 
234
- const filtered = `
235
- select e.id, e.conversation_id, e.timeline_at,
236
- row_number() over (partition by e.conversation_id order by e.timeline_at desc, e.id desc) as thread_rank
237
- from emails e join conversations c on c.id = e.conversation_id
238
- ${where.length ? `where ${where.join(" and ")}` : ""}`;
91
+ /** Rank the full query first, then return only changed entries at their current positions. */
92
+ export function queryChangedEmails(
93
+ m: MailboxContext,
94
+ input: EmailQueryInput & { calculateTotal: boolean },
95
+ changed: ReadonlySet<string>,
96
+ threads: ReadonlySet<string>
97
+ ) {
98
+ const { matches, order, params } = filteredEmails(m.db, input);
99
+ const { sql } = m.state.storage;
239
100
 
240
101
  const rows = sql
241
- .exec<{ id: string; total: number }>(
242
- `
243
- select id, count(*) over () as total from (${filtered})
244
- ${input.collapseThreads ? "where thread_rank = 1" : ""}
245
- order by timeline_at ${direction}, id ${direction}
246
- limit ? offset ?`,
102
+ .exec<{ id: string; idx: number; total?: number }>(
103
+ `select * from (
104
+ select id, conversation_id, row_number() over (${order}) - 1 as idx
105
+ ${input.calculateTotal ? ", count(*) over () as total" : ""}
106
+ ${matches}
107
+ ) where id in ${IDS} ${threads.size ? `or conversation_id in ${IDS}` : ""}
108
+ order by idx`,
247
109
  ...params,
248
- input.limit,
249
- input.position
110
+ JSON.stringify([...changed]),
111
+ ...(threads.size ? [JSON.stringify([...threads])] : [])
250
112
  )
251
113
  .toArray();
252
114
 
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
-
262
- return { ids: rows.map((row) => row.id), total };
115
+ return {
116
+ added: rows.map(({ id, idx }) => ({ id, index: idx })),
117
+ // When all changes left the list, no ranked row carries its total.
118
+ total: input.calculateTotal
119
+ ? (rows[0]?.total ??
120
+ sql
121
+ .exec<{ total: number }>(
122
+ `select count(*) as total ${matches}`,
123
+ ...params
124
+ )
125
+ .one().total)
126
+ : null,
127
+ };
263
128
  }
264
129
 
265
- /** For each email: its JMAP Mailbox, and whether this user has read it. */
266
- export function emailPlacement(sql: SqlStorage, userId: string, ids: string[]) {
267
- if (!ids.length) {
268
- return new Map<string, { mailboxId: string; seen: boolean }>();
269
- }
270
-
271
- const isUnread = unread(userId);
130
+ /** For each email: its JMAP Mailboxes, whether it was sent here, and whether this user has read it. */
131
+ export function emailPlacement(
132
+ db: MailboxDatabase,
133
+ userId: string,
134
+ ids: string[]
135
+ ) {
136
+ const e = alias(emails, "e");
137
+ const c = alias(conversations, "c");
138
+
139
+ const rows = ids.length
140
+ ? db
141
+ .select({
142
+ id: e.id,
143
+ conversationId: e.conversationId,
144
+ direction: e.direction,
145
+ mailboxes: query<string>`${query.raw(EMAIL_MAILBOXES_SQL)}`,
146
+ readId: emailReadStates.emailId,
147
+ })
148
+ .from(e)
149
+ .innerJoin(c, eq(c.id, e.conversationId))
150
+ .leftJoin(
151
+ emailReadStates,
152
+ and(
153
+ eq(emailReadStates.emailId, e.id),
154
+ eq(emailReadStates.userId, userId)
155
+ )
156
+ )
157
+ .where(inJsonList(e.id, ids))
158
+ .all()
159
+ : [];
272
160
 
273
161
  return new Map(
274
- sql
275
- .exec<{ id: string; mailbox: string; is_unread: number }>(
276
- `
277
- select e.id, ${EMAIL_MAILBOX_SQL} as mailbox, ${isUnread.sql} as is_unread
278
- from emails e join conversations c on c.id = e.conversation_id
279
- where e.id in (${ids.map(() => "?").join(", ")})`,
280
- ...isUnread.params,
281
- ...ids
282
- )
283
- .toArray()
284
- .map((row) => [row.id, { mailboxId: row.mailbox, seen: !row.is_unread }])
162
+ rows.map((row) => [
163
+ row.id,
164
+ {
165
+ conversationId: row.conversationId,
166
+ mailboxIds: mailboxIdList.parse(JSON.parse(row.mailboxes)),
167
+ sent: row.direction === "outgoing",
168
+ seen: row.direction === "outgoing" || row.readId !== null,
169
+ },
170
+ ])
285
171
  );
286
172
  }
287
173
 
288
- export function threadEmails(sql: SqlStorage, threadIds: string[]) {
174
+ const mailboxIdList = z.array(z.string());
175
+
176
+ /**
177
+ * The emails of each thread, oldest first. A draft of `userId` is a thread
178
+ * of its own, as its `threadId` says.
179
+ */
180
+ export function threadEmails(
181
+ m: MailboxContext,
182
+ threadIds: string[],
183
+ userId: string
184
+ ) {
289
185
  const threads = new Map<string, string[]>();
290
186
 
291
187
  if (!threadIds.length) return threads;
292
188
 
293
- for (const row of sql.exec<{ id: string; conversation_id: string }>(
294
- `select id, conversation_id from emails where conversation_id in (${threadIds.map(() => "?").join(", ")})
295
- order by timeline_at, id`,
296
- ...threadIds
297
- )) {
298
- threads.set(row.conversation_id, [
299
- ...(threads.get(row.conversation_id) ?? []),
300
- row.id,
301
- ]);
189
+ for (const row of m.db
190
+ .select({ id: drafts.id })
191
+ .from(drafts)
192
+ .where(and(eq(drafts.userId, userId), inJsonList(drafts.id, threadIds)))
193
+ .all()) {
194
+ threads.set(row.id, [row.id]);
302
195
  }
303
196
 
304
- return threads;
305
- }
197
+ for (const row of m.db
198
+ .select({ id: emails.id, conversationId: emails.conversationId })
199
+ .from(emails)
200
+ .where(inJsonList(emails.conversationId, threadIds))
201
+ .orderBy(emails.timelineAt, emails.id)
202
+ .all()) {
203
+ const messages = threads.get(row.conversationId);
306
204
 
307
- /**
308
- * Moves the conversations of `emailIds` into a JMAP Mailbox. Conversations
309
- * move as a whole, as they do in the app. Returns false for an unknown or
310
- * read-only target.
311
- */
312
- export function moveEmails(
313
- sql: SqlStorage,
314
- emailIds: string[],
315
- target: string
316
- ) {
317
- if (!emailIds.length) return true;
318
- let state: string;
319
- let folderId: string | null = null;
320
-
321
- if (target === "inbox") state = "active";
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
- ) {
327
- state = "active";
328
- folderId = target;
329
- } else {
330
- return false;
205
+ if (messages) messages.push(row.id);
206
+ else threads.set(row.conversationId, [row.id]);
331
207
  }
332
208
 
333
- sql.exec(
334
- `update conversations set mailbox_state = ?, folder_id = ?
335
- where id in (select conversation_id from emails where id in (${emailIds.map(() => "?").join(", ")}))`,
336
- state,
337
- folderId,
338
- ...emailIds
339
- );
340
-
341
- return true;
209
+ return threads;
342
210
  }