@open-workspace/email 0.3.0 → 0.4.1

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 (221) hide show
  1. package/README.md +22 -22
  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_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  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 +77 -28
  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 +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  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 +88 -22
  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 +271 -173
  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 +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  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 +126 -93
  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 +595 -225
  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 +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  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 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -0,0 +1,279 @@
1
+ import { responseJson, useAuth } from "@open-workspace/core/ui";
2
+ import {
3
+ queryOptions,
4
+ skipToken,
5
+ useInfiniteQuery,
6
+ useMutation,
7
+ useQueries,
8
+ useQuery,
9
+ useQueryClient,
10
+ } from "@tanstack/react-query";
11
+ import type { InfiniteData } from "@tanstack/react-query";
12
+ import { useEffect } from "react";
13
+
14
+ import { mailApi } from "../lib/mail-api";
15
+ import {
16
+ conversationQuery,
17
+ conversationsQuery,
18
+ foldersQuery,
19
+ mailboxesQuery,
20
+ } from "./mail-queries";
21
+ import { applyOwnReadChange, scheduleMailboxRefresh } from "./mail-query-cache";
22
+ import type { Folder, MessageDetail } from "./types";
23
+
24
+ export function useMailboxes() {
25
+ return useQuery(mailboxesQuery());
26
+ }
27
+
28
+ export function useFolders(mailboxId: string | undefined) {
29
+ return useQuery(foldersQuery(mailboxId));
30
+ }
31
+
32
+ export function useRecipientSuggestions(
33
+ mailboxId: string | undefined,
34
+ query: string,
35
+ active: boolean
36
+ ) {
37
+ return useQuery({
38
+ queryKey: ["recipient-suggestions", mailboxId, query],
39
+ queryFn: mailboxId
40
+ ? async ({ signal }) =>
41
+ responseJson(
42
+ await mailApi.api.mail.mailboxes[":id"][
43
+ "recipient-suggestions"
44
+ ].$get(
45
+ { param: { id: mailboxId }, query: { q: query, limit: "8" } },
46
+ { init: { signal } }
47
+ )
48
+ )
49
+ : skipToken,
50
+ enabled: active,
51
+ staleTime: 30_000,
52
+ });
53
+ }
54
+
55
+ export function useConversations(
56
+ mailboxId: string | undefined,
57
+ folder: Folder,
58
+ search: string,
59
+ unreadOnly: boolean,
60
+ active = true
61
+ ) {
62
+ return useInfiniteQuery({
63
+ ...conversationsQuery(mailboxId, folder, search, unreadOnly),
64
+ enabled: Boolean(mailboxId) && active,
65
+ });
66
+ }
67
+
68
+ export function useConversation(
69
+ mailboxId: string | undefined,
70
+ conversationId: string | undefined
71
+ ) {
72
+ return useInfiniteQuery(conversationQuery(mailboxId, conversationId));
73
+ }
74
+
75
+ /**
76
+ * Starts loading a conversation the person is about to open (pointer
77
+ * resting on its row, keyboard focus, or the next and previous one), so the
78
+ * reader can show it at once.
79
+ */
80
+ export function usePrefetchConversation() {
81
+ const client = useQueryClient();
82
+
83
+ return (
84
+ mailboxId: string | undefined,
85
+ conversationId: string | undefined
86
+ ) => {
87
+ if (!mailboxId || !conversationId) return;
88
+ void client.prefetchInfiniteQuery(
89
+ conversationQuery(mailboxId, conversationId)
90
+ );
91
+ };
92
+ }
93
+
94
+ type ConversationPage = { messages: MessageDetail[] };
95
+
96
+ function senderIntelQuery(mailboxId: string, messageId: string) {
97
+ return queryOptions({
98
+ queryKey: ["sender-intel", mailboxId, messageId],
99
+ queryFn: async ({ signal }) =>
100
+ responseJson(
101
+ await mailApi.api.mail.messages[":id"]["sender-intel"].$get(
102
+ {
103
+ param: { id: messageId },
104
+ query: { mailboxId },
105
+ },
106
+ { init: { signal } }
107
+ )
108
+ ),
109
+ staleTime: 5 * 60_000,
110
+ });
111
+ }
112
+
113
+ /**
114
+ * The reader gets a conversation before the sender lookups (DNS, blocklists)
115
+ * of messages that had none finish; this fetches each one's result and puts
116
+ * it into the cached conversation, which shows a pending state meanwhile.
117
+ */
118
+ export function useSenderIntelFill(
119
+ mailboxId: string | undefined,
120
+ conversationId: string | undefined,
121
+ messages: MessageDetail[]
122
+ ) {
123
+ const client = useQueryClient();
124
+
125
+ const pending =
126
+ mailboxId && conversationId
127
+ ? messages.filter((message) => message.senderIntelPending)
128
+ : [];
129
+
130
+ const results = useQueries({
131
+ queries: mailboxId
132
+ ? pending.map((message) => senderIntelQuery(mailboxId, message.id))
133
+ : [],
134
+ });
135
+
136
+ const readyKey = pending
137
+ .flatMap((message, index) => (results[index]?.data ? [message.id] : []))
138
+ .join(",");
139
+
140
+ useEffect(() => {
141
+ if (!mailboxId || !readyKey) return;
142
+
143
+ const ready = readyKey.split(",").flatMap((id) => {
144
+ const data = client.getQueryData(
145
+ senderIntelQuery(mailboxId, id).queryKey
146
+ );
147
+
148
+ return data ? [{ id, data }] : [];
149
+ });
150
+
151
+ client.setQueryData<InfiniteData<ConversationPage>>(
152
+ ["conversation", mailboxId, conversationId],
153
+ (data) =>
154
+ data && {
155
+ ...data,
156
+ pages: data.pages.map((page) => ({
157
+ ...page,
158
+ messages: page.messages.map((message) => {
159
+ const filled = ready.find((item) => item.id === message.id);
160
+
161
+ if (!filled || !message.senderIntelPending) return message;
162
+ const { ok: _ok, ...intel } = filled.data;
163
+
164
+ return { ...message, ...intel };
165
+ }),
166
+ })),
167
+ }
168
+ );
169
+ }, [client, conversationId, mailboxId, readyKey]);
170
+ }
171
+
172
+ export function useResendMessage() {
173
+ const client = useQueryClient();
174
+
175
+ return useMutation({
176
+ mutationFn: async ({ id, mailboxId }: { id: string; mailboxId: string }) =>
177
+ responseJson(
178
+ await mailApi.api.mail.messages[":id"]["send-again"].$post({
179
+ param: { id },
180
+ query: { mailboxId },
181
+ })
182
+ ),
183
+ onSuccess: (_result, { mailboxId }) =>
184
+ scheduleMailboxRefresh(client, mailboxId),
185
+ });
186
+ }
187
+
188
+ export function useSetMessageRead() {
189
+ const client = useQueryClient();
190
+ const { user } = useAuth();
191
+
192
+ return useMutation({
193
+ mutationFn: async ({
194
+ id,
195
+ mailboxId,
196
+ isRead,
197
+ }: {
198
+ id: string;
199
+ mailboxId: string;
200
+ conversationId: string;
201
+ isRead: boolean;
202
+ }) =>
203
+ responseJson(
204
+ await mailApi.api.mail.messages[":id"].read.$patch({
205
+ param: { id },
206
+ query: { mailboxId },
207
+ json: { isRead },
208
+ })
209
+ ),
210
+ // The change is applied to the cached conversation, lists and counts;
211
+ // a refetch is needed only when the cache was not exactly one change behind.
212
+ onSuccess: ({ version }, { id, mailboxId, conversationId, isRead }) => {
213
+ const applied =
214
+ user &&
215
+ applyOwnReadChange(client, {
216
+ mailboxId,
217
+ conversationId,
218
+ messageId: id,
219
+ isRead,
220
+ version,
221
+ reader: { userId: user.id, name: user.name },
222
+ });
223
+
224
+ if (!applied) scheduleMailboxRefresh(client, mailboxId);
225
+ },
226
+ });
227
+ }
228
+
229
+ export type BulkConversationAction =
230
+ | { type: "read"; isRead: boolean }
231
+ | {
232
+ type: "update";
233
+ update: {
234
+ mailboxState?: "active" | "archive" | "spam" | "trash";
235
+ folderId?: string | null;
236
+ };
237
+ }
238
+ | { type: "delete_permanently" };
239
+
240
+ export function useBulkConversationAction() {
241
+ const client = useQueryClient();
242
+
243
+ return useMutation({
244
+ mutationFn: async ({
245
+ mailboxId,
246
+ sourceFolderId,
247
+ conversationIds,
248
+ action,
249
+ }: {
250
+ mailboxId: string;
251
+ sourceFolderId: string;
252
+ conversationIds: string[];
253
+ action: BulkConversationAction;
254
+ }) => {
255
+ if (action.type === "update") {
256
+ return responseJson(
257
+ await mailApi.api.mail.conversations.bulk.$patch({
258
+ query: { mailboxId },
259
+ json: {
260
+ type: action.type,
261
+ conversationIds,
262
+ sourceFolderId,
263
+ update: action.update,
264
+ },
265
+ })
266
+ );
267
+ }
268
+
269
+ return responseJson(
270
+ await mailApi.api.mail.conversations.bulk.$patch({
271
+ query: { mailboxId },
272
+ json: { conversationIds, ...action },
273
+ })
274
+ );
275
+ },
276
+ onSuccess: (_result, { mailboxId }) =>
277
+ scheduleMailboxRefresh(client, mailboxId),
278
+ });
279
+ }
@@ -0,0 +1,155 @@
1
+ import { responseJson } from "@open-workspace/core/ui";
2
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3
+
4
+ import { mailApi } from "../lib/mail-api";
5
+ import { scheduleMailboxRefresh } from "./mail-query-cache";
6
+
7
+ const blockedKey = (mailboxId: string) =>
8
+ ["blocked-senders", mailboxId] as const;
9
+
10
+ function useMailboxRefresh() {
11
+ const client = useQueryClient();
12
+
13
+ return (mailboxId: string) => {
14
+ scheduleMailboxRefresh(client, mailboxId);
15
+ void client.invalidateQueries({ queryKey: blockedKey(mailboxId) });
16
+ void client.invalidateQueries({
17
+ queryKey: ["recipient-suggestions", mailboxId],
18
+ });
19
+ };
20
+ }
21
+
22
+ export function useUnsubscribe() {
23
+ const refresh = useMailboxRefresh();
24
+
25
+ return useMutation({
26
+ mutationFn: async (input: {
27
+ mailboxId: string;
28
+ messageId: string;
29
+ method: "auto" | "link";
30
+ }) =>
31
+ responseJson(
32
+ await mailApi.api.mail.messages[":id"].unsubscribe.$post({
33
+ param: { id: input.messageId },
34
+ query: { mailboxId: input.mailboxId },
35
+ json: { method: input.method },
36
+ })
37
+ ),
38
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
39
+ });
40
+ }
41
+
42
+ export function useReportMessage() {
43
+ const refresh = useMailboxRefresh();
44
+
45
+ return useMutation({
46
+ mutationFn: async (input: { mailboxId: string; messageId: string }) =>
47
+ responseJson(
48
+ await mailApi.api.mail.messages[":id"].report.$post({
49
+ param: { id: input.messageId },
50
+ query: { mailboxId: input.mailboxId },
51
+ })
52
+ ),
53
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
54
+ });
55
+ }
56
+
57
+ export function useBulkReport() {
58
+ const refresh = useMailboxRefresh();
59
+
60
+ return useMutation({
61
+ mutationFn: async (input: {
62
+ mailboxId: string;
63
+ conversationIds: string[];
64
+ }) =>
65
+ responseJson(
66
+ await mailApi.api.mail.conversations.report.$post({
67
+ query: { mailboxId: input.mailboxId },
68
+ json: { conversationIds: input.conversationIds },
69
+ })
70
+ ),
71
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
72
+ });
73
+ }
74
+
75
+ export function useNotSpam() {
76
+ const refresh = useMailboxRefresh();
77
+
78
+ return useMutation({
79
+ mutationFn: async (input: { mailboxId: string; messageId: string }) =>
80
+ responseJson(
81
+ await mailApi.api.mail.messages[":id"]["not-spam"].$post({
82
+ param: { id: input.messageId },
83
+ query: { mailboxId: input.mailboxId },
84
+ })
85
+ ),
86
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
87
+ });
88
+ }
89
+
90
+ export function useBlockedSenders(mailboxId: string, enabled: boolean) {
91
+ return useQuery({
92
+ queryKey: blockedKey(mailboxId),
93
+ queryFn: async ({ signal }) =>
94
+ responseJson(
95
+ await mailApi.api.mail.mailboxes[":id"]["blocked-senders"].$get(
96
+ { param: { id: mailboxId } },
97
+ { init: { signal } }
98
+ )
99
+ ),
100
+ enabled,
101
+ });
102
+ }
103
+
104
+ export function useBlockSender() {
105
+ const refresh = useMailboxRefresh();
106
+
107
+ return useMutation({
108
+ mutationFn: async (input: {
109
+ mailboxId: string;
110
+ pattern: string;
111
+ moveExisting: boolean;
112
+ }) =>
113
+ responseJson(
114
+ await mailApi.api.mail.mailboxes[":id"]["blocked-senders"].$post({
115
+ param: { id: input.mailboxId },
116
+ json: { pattern: input.pattern, moveExisting: input.moveExisting },
117
+ })
118
+ ),
119
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
120
+ });
121
+ }
122
+
123
+ export function useUnblockSender() {
124
+ const refresh = useMailboxRefresh();
125
+
126
+ return useMutation({
127
+ mutationFn: async (input: { mailboxId: string; pattern: string }) =>
128
+ responseJson(
129
+ await mailApi.api.mail.mailboxes[":id"]["blocked-senders"].$delete({
130
+ param: { id: input.mailboxId },
131
+ query: { pattern: input.pattern },
132
+ })
133
+ ),
134
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
135
+ });
136
+ }
137
+
138
+ export function useTrustSender() {
139
+ const refresh = useMailboxRefresh();
140
+
141
+ return useMutation({
142
+ mutationFn: async (input: {
143
+ mailboxId: string;
144
+ address: string;
145
+ trusted: boolean;
146
+ }) =>
147
+ responseJson(
148
+ await mailApi.api.mail.mailboxes[":id"]["trusted-senders"].$put({
149
+ param: { id: input.mailboxId },
150
+ json: { address: input.address, trusted: input.trusted },
151
+ })
152
+ ),
153
+ onSuccess: (_result, { mailboxId }) => refresh(mailboxId),
154
+ });
155
+ }
@@ -0,0 +1,142 @@
1
+ import { ApiError, responseJson } from "@open-workspace/core/ui";
2
+ import type { SuccessfulResponse } from "@open-workspace/core/ui";
3
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
4
+
5
+ import type { ReplyActionMode } from "../../shared/mail";
6
+ import { mailApi } from "../lib/mail-api";
7
+ import type { SubmittedComposerUpload } from "./composer-session";
8
+ import { scheduleMailboxRefresh } from "./mail-query-cache";
9
+
10
+ export type SubmittedMessage = SuccessfulResponse<
11
+ Awaited<ReturnType<typeof mailApi.api.mail.messages.$post>>
12
+ >;
13
+
14
+ type MessageContent = {
15
+ requestId: string;
16
+ mailboxId: string;
17
+ bodyText: string;
18
+ bodyHtml?: string;
19
+ uploadedAttachments?: SubmittedComposerUpload[];
20
+ };
21
+
22
+ type MailSendInput =
23
+ | (MessageContent & {
24
+ kind: "compose";
25
+ to: string[];
26
+ cc: string[];
27
+ bcc: string[];
28
+ replyTo?: string;
29
+ subject: string;
30
+ })
31
+ | (MessageContent & {
32
+ kind: "reply";
33
+ parentEmailId: string;
34
+ mode: ReplyActionMode;
35
+ cc: string[];
36
+ bcc: string[];
37
+ })
38
+ | (MessageContent & {
39
+ kind: "forward";
40
+ sourceEmailId: string;
41
+ to: string[];
42
+ cc: string[];
43
+ bcc: string[];
44
+ replyTo?: string;
45
+ });
46
+
47
+ type WithoutRequestId<Input> = Input extends MailSendInput
48
+ ? Omit<Input, "requestId">
49
+ : never;
50
+
51
+ export type MailSendDraft = WithoutRequestId<MailSendInput>;
52
+
53
+ export function withMailSendRequestId(
54
+ draft: MailSendDraft,
55
+ requestId: string
56
+ ): MailSendInput {
57
+ switch (draft.kind) {
58
+ case "compose": {
59
+ return { ...draft, requestId };
60
+ }
61
+
62
+ case "reply": {
63
+ return { ...draft, requestId };
64
+ }
65
+
66
+ case "forward": {
67
+ return { ...draft, requestId };
68
+ }
69
+
70
+ default: {
71
+ const unexpected: never = draft;
72
+ throw new Error(`Unknown send kind: ${JSON.stringify(unexpected)}`);
73
+ }
74
+ }
75
+ }
76
+
77
+ export function useMailSend() {
78
+ const client = useQueryClient();
79
+
80
+ const send = useMutation({
81
+ mutationFn: async (input: MailSendInput) => {
82
+ const request = {
83
+ requestId: input.requestId,
84
+ mailboxId: input.mailboxId,
85
+ bodyText: input.bodyText,
86
+ bodyHtml: input.bodyHtml,
87
+ attachments: input.uploadedAttachments ?? [],
88
+ };
89
+
90
+ if (input.kind === "reply") {
91
+ return responseJson(
92
+ await mailApi.api.mail.messages[":id"].replies.$post({
93
+ param: { id: input.parentEmailId },
94
+ json: {
95
+ ...request,
96
+ mode: input.mode,
97
+ cc: input.cc,
98
+ bcc: input.bcc,
99
+ },
100
+ })
101
+ );
102
+ }
103
+
104
+ if (input.kind === "forward") {
105
+ return responseJson(
106
+ await mailApi.api.mail.messages[":id"].forward.$post({
107
+ param: { id: input.sourceEmailId },
108
+ json: {
109
+ ...request,
110
+ to: input.to,
111
+ cc: input.cc,
112
+ bcc: input.bcc,
113
+ replyTo: input.replyTo,
114
+ },
115
+ })
116
+ );
117
+ }
118
+
119
+ return responseJson(
120
+ await mailApi.api.mail.messages.$post({
121
+ json: {
122
+ ...request,
123
+ to: input.to,
124
+ cc: input.cc,
125
+ bcc: input.bcc,
126
+ replyTo: input.replyTo,
127
+ subject: input.subject,
128
+ },
129
+ })
130
+ );
131
+ },
132
+ // A retry reuses the caller-owned requestId. The Worker derives the
133
+ // message id from it, so a lost response cannot create a second message.
134
+ retry: (failureCount, error) =>
135
+ failureCount < 1 && (!(error instanceof ApiError) || error.status >= 500),
136
+ onSuccess: (_result, input) => {
137
+ scheduleMailboxRefresh(client, input.mailboxId);
138
+ },
139
+ });
140
+
141
+ return { send };
142
+ }