@open-workspace/email 0.4.2 → 0.5.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 (268) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -1,9 +1,12 @@
1
- import { z } from "zod";
1
+ import { waitUntil } from "cloudflare:workers";
2
2
 
3
3
  import { mailboxStub } from "../mailbox";
4
- import type { JmapAccount } from "./methods";
5
- import { stateChange } from "./push";
6
- import { wantsMailChanges } from "./push-types";
4
+ import type { JmapAccount } from "./method-core";
5
+ import {
6
+ jmapStateSocketMessage,
7
+ stateChange,
8
+ wantsMailChanges,
9
+ } from "./push-types";
7
10
  import type { StateChange } from "./push-types";
8
11
 
9
12
  /** How often a stream re-checks its token and accounts when the client asked for no pings. */
@@ -11,7 +14,6 @@ const AUTHORIZATION_CHECK_SECONDS = 300;
11
14
  const MIN_PING_SECONDS = 30;
12
15
 
13
16
  /** A mailbox sends its new JMAP state, a counter, as a text message. */
14
- const mailboxStateMessage = z.string();
15
17
 
16
18
  /** RFC 8620 §7.3: the ping a stream sends at the interval the client asked for. */
17
19
  type Ping = { "@type": "Ping"; interval: number };
@@ -36,7 +38,6 @@ export async function jmapEventStream(input: {
36
38
  * taken away) it closes and the client reconnects with the new set.
37
39
  */
38
40
  currentAccounts: () => Promise<JmapAccount[]>;
39
- defer: (task: Promise<unknown>) => void;
40
41
  /** How often to re-check; tests shorten it. Defaults to the ping interval, or five minutes. */
41
42
  checkEveryMs?: number;
42
43
  }) {
@@ -60,7 +61,7 @@ export async function jmapEventStream(input: {
60
61
  let timer: ReturnType<typeof setInterval> | undefined;
61
62
  let closed = false;
62
63
  let finished!: () => void;
63
- input.defer(
64
+ waitUntil(
64
65
  new Promise<void>((resolve) => {
65
66
  finished = resolve;
66
67
  })
@@ -111,7 +112,7 @@ export async function jmapEventStream(input: {
111
112
  socket.accept();
112
113
  sockets.push(socket);
113
114
  socket.addEventListener("message", (message) => {
114
- const state = mailboxStateMessage.safeParse(message.data);
115
+ const state = jmapStateSocketMessage.safeParse(message.data);
115
116
 
116
117
  if (!state.success) return;
117
118
  event("state", stateChange({ [account.id]: state.data }));
@@ -0,0 +1,205 @@
1
+ /** Email/import: uploaded messages stored as history. */
2
+ import { z } from "zod";
3
+
4
+ import { MAX_IMPORT_MESSAGE_BYTES } from "../../shared/mail-import";
5
+ import { importRawMessage } from "../mail/import";
6
+ import { loadComposerUpload, UploadValidationError } from "../mail/uploads";
7
+ import { mailboxStub } from "../mailbox";
8
+ import { placementForImport } from "../mailbox/jmap-placement";
9
+ import { trueSet } from "./email-methods";
10
+ import type { JmapAccount, JsonObject, RequestState } from "./method-core";
11
+ import {
12
+ MAX_OBJECTS,
13
+ MethodError,
14
+ UPLOAD_BLOB,
15
+ account,
16
+ accountId,
17
+ invalidProperties,
18
+ methodIssue,
19
+ setResult,
20
+ utcDate,
21
+ } from "./method-core";
22
+
23
+ // ------------------------------------------------------------------ import
24
+
25
+ /** An Email/import object (RFC 8621 §4.8): an uploaded message, its one mailbox and $seen. */
26
+ const emailImportObject = z.object({
27
+ blobId: z.string(),
28
+ mailboxIds: trueSet
29
+ .transform((ids) => Object.keys(ids))
30
+ .refine((ids) => ids.length > 0, "An email is in at least one mailbox"),
31
+ keywords: trueSet
32
+ .nullish()
33
+ .refine(
34
+ (keywords) =>
35
+ Object.keys(keywords ?? {}).every((name) => name === "$seen"),
36
+ "Only the $seen keyword is stored"
37
+ ),
38
+ receivedAt: utcDate.nullish(),
39
+ });
40
+
41
+ export const emailImportArguments = z.object({
42
+ accountId,
43
+ ifInState: z.string().nullish(),
44
+ emails: z.record(z.string(), z.json()).superRefine((emails, context) => {
45
+ if (Object.keys(emails).length > MAX_OBJECTS) {
46
+ methodIssue(context, "requestTooLarge", `At most ${MAX_OBJECTS} emails`);
47
+ }
48
+ }),
49
+ });
50
+
51
+ type EmailImportArguments = z.output<typeof emailImportArguments>;
52
+
53
+ /** The bytes of a blob uploaded to this account, or null when there is none. */
54
+ async function uploadedBlob(
55
+ state: RequestState,
56
+ owner: JmapAccount,
57
+ blobId: string
58
+ ) {
59
+ const upload = UPLOAD_BLOB.exec(blobId);
60
+
61
+ if (!upload) return null;
62
+
63
+ try {
64
+ return await loadComposerUpload({
65
+ env: state.context.env,
66
+ mailboxId: owner.id,
67
+ userId: state.context.user.id,
68
+ uploadId: upload[1],
69
+ });
70
+ } catch (error) {
71
+ if (error instanceof UploadValidationError) return null;
72
+ throw error;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Stores uploaded messages as the import CLI does: their date, mailbox and
78
+ * read state kept, threaded, no AI, webhooks or push. A message imported
79
+ * before (the same bytes or Message-ID) is alreadyExists.
80
+ */
81
+ export async function emailImport(
82
+ state: RequestState,
83
+ args: EmailImportArguments
84
+ ) {
85
+ const owner = account(state, args.accountId);
86
+ const { env, user } = state.context;
87
+
88
+ // Imported mail shows as received, so only its owner may add to a mailbox (as with the CLI).
89
+ if (!owner.isPersonal) {
90
+ throw new MethodError(
91
+ "forbidden",
92
+ "Mail can be imported only into your own mailboxes"
93
+ );
94
+ }
95
+
96
+ const stub = mailboxStub(env, owner.id);
97
+ const oldState = await stub.jmapState();
98
+
99
+ if (args.ifInState != null && args.ifInState !== oldState) {
100
+ throw new MethodError("stateMismatch");
101
+ }
102
+
103
+ const { mailboxes } = await stub.jmapMailboxes(user.id, false);
104
+
105
+ const folders = new Map(
106
+ mailboxes
107
+ .filter((row) => row.role === null)
108
+ .map((row) => [row.id, row.name])
109
+ );
110
+
111
+ const created = new Map<string, JsonObject>();
112
+ const notCreated = new Map<string, JsonObject>();
113
+
114
+ for (const [creationId, input] of Object.entries(args.emails)) {
115
+ const parsed = emailImportObject.safeParse(input);
116
+
117
+ if (!parsed.success) {
118
+ notCreated.set(creationId, invalidProperties(parsed.error.issues));
119
+ continue;
120
+ }
121
+
122
+ const { blobId, mailboxIds, keywords, receivedAt } = parsed.data;
123
+ const target = placementForImport((id) => folders.has(id), mailboxIds);
124
+
125
+ if (!target) {
126
+ notCreated.set(creationId, {
127
+ type: "invalidProperties",
128
+ properties: ["mailboxIds"],
129
+ description: mailboxIds.includes("drafts")
130
+ ? "Save drafts with Email/set, not Email/import"
131
+ : "The email can't be in those Mailboxes",
132
+ });
133
+ continue;
134
+ }
135
+
136
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one at a time, so a message given twice is stored once
137
+ const upload = await uploadedBlob(state, owner, blobId);
138
+
139
+ if (upload && upload.size > MAX_IMPORT_MESSAGE_BYTES) {
140
+ notCreated.set(creationId, {
141
+ type: "tooLarge",
142
+ description: `Messages are limited to ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB`,
143
+ });
144
+ continue;
145
+ }
146
+
147
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
148
+ const object = upload ? await env.MAIL_STORAGE.get(upload.r2Key) : null;
149
+
150
+ if (!object) {
151
+ notCreated.set(creationId, { type: "blobNotFound", notFound: [blobId] });
152
+ continue;
153
+ }
154
+
155
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
156
+ const raw = new Uint8Array(await object.arrayBuffer());
157
+
158
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
159
+ const result = await importRawMessage({
160
+ env,
161
+ mailbox: owner,
162
+ raw,
163
+ importKey: raw,
164
+ receivedAt: receivedAt ? Date.parse(receivedAt) : null,
165
+ placement: target.placement,
166
+ folderName: target.folderId
167
+ ? (folders.get(target.folderId) ?? null)
168
+ : null,
169
+ seen: Object.hasOwn(keywords ?? {}, "$seen"),
170
+ thread: null,
171
+ direction: target.direction,
172
+ });
173
+
174
+ if (result.status === "unprocessable") {
175
+ notCreated.set(creationId, {
176
+ type: "invalidEmail",
177
+ description: result.reason,
178
+ });
179
+ } else if (result.status === "duplicate") {
180
+ notCreated.set(creationId, {
181
+ type: "alreadyExists",
182
+ existingId: result.id,
183
+ });
184
+ } else {
185
+ state.createdIds.set(creationId, result.id);
186
+ created.set(creationId, {
187
+ id: result.id,
188
+ blobId: `raw~${result.id}`,
189
+ threadId: result.conversationId,
190
+ size: raw.byteLength,
191
+ });
192
+ }
193
+ }
194
+
195
+ // Announces the imports now (counts, open apps, JMAP state), not with the alarm.
196
+ if (created.size) await stub.finishImport();
197
+
198
+ return {
199
+ accountId: owner.id,
200
+ oldState,
201
+ newState: await stub.jmapState(),
202
+ created: setResult(created),
203
+ notCreated: setResult(notCreated),
204
+ };
205
+ }
@@ -0,0 +1,187 @@
1
+ /** Mailbox/get and Mailbox/query. */
2
+ import { z } from "zod";
3
+
4
+ import { sortFolders } from "../../shared/folder-order";
5
+ import { mailboxStub } from "../mailbox";
6
+ import type { JmapMailboxRow } from "../mailbox/jmap-mailboxes";
7
+ import type { RequestState } from "./method-core";
8
+ import {
9
+ account,
10
+ accountId,
11
+ accountRights,
12
+ idList,
13
+ methodIssue,
14
+ pick,
15
+ properties,
16
+ } from "./method-core";
17
+
18
+ // ------------------------------------------------------------------ mailbox
19
+
20
+ function mailboxObject(
21
+ row: JmapMailboxRow,
22
+ rights: ReturnType<typeof accountRights>
23
+ ) {
24
+ return {
25
+ ...row,
26
+ parentId: null,
27
+ myRights: {
28
+ mayReadItems: true,
29
+ mayAddItems:
30
+ row.role === "drafts"
31
+ ? rights.submit
32
+ : rights.organize && row.role !== "sent",
33
+ mayRemoveItems: rights.organize,
34
+ maySetSeen: rights.organize && row.role !== "drafts",
35
+ maySetKeywords: false,
36
+ mayCreateChild: false,
37
+ mayRename: false,
38
+ mayDelete: false,
39
+ maySubmit: rights.submit,
40
+ },
41
+ isSubscribed: true,
42
+ };
43
+ }
44
+
45
+ export const mailboxGetArguments = z.object({
46
+ accountId,
47
+ ids: idList.nullish(),
48
+ properties,
49
+ });
50
+
51
+ export async function mailboxGet(
52
+ state: RequestState,
53
+ args: z.output<typeof mailboxGetArguments>
54
+ ) {
55
+ const owner = account(state, args.accountId);
56
+
57
+ const rights = accountRights(owner, state.context.scopes);
58
+
59
+ const withCounts =
60
+ !args.properties ||
61
+ ["totalEmails", "unreadEmails", "totalThreads", "unreadThreads"].some(
62
+ (property) => args.properties?.includes(property)
63
+ );
64
+
65
+ const { state: mailboxState, mailboxes } = await mailboxStub(
66
+ state.context.env,
67
+ owner.id
68
+ ).jmapMailboxes(state.context.user.id, withCounts);
69
+
70
+ const ids = args.ids ?? mailboxes.map((row) => row.id);
71
+ const byId = new Map(mailboxes.map((row) => [row.id, row]));
72
+
73
+ return {
74
+ accountId: owner.id,
75
+ state: mailboxState,
76
+ list: ids.flatMap((id) => {
77
+ const row = byId.get(id);
78
+
79
+ return row ? [pick(mailboxObject(row, rights), args.properties)] : [];
80
+ }),
81
+ notFound: ids.filter((id) => !byId.has(id)),
82
+ };
83
+ }
84
+
85
+ const mailboxComparator = z
86
+ .object({
87
+ property: z.string(),
88
+ isAscending: z.boolean().default(true),
89
+ collation: z.string().nullish(),
90
+ })
91
+ .superRefine(({ property, collation }, context) => {
92
+ if (
93
+ (property !== "sortOrder" && property !== "name") ||
94
+ (property === "name" && collation != null)
95
+ ) {
96
+ methodIssue(
97
+ context,
98
+ "unsupportedSort",
99
+ "Mailboxes sort by sortOrder or name with the default collation"
100
+ );
101
+ }
102
+ });
103
+
104
+ export const mailboxQueryArguments = z.object({
105
+ accountId,
106
+ filter: z
107
+ .object({
108
+ /** null matches the mailboxes without a role. */
109
+ role: z.string().nullable().optional(),
110
+ hasAnyRole: z.boolean().optional(),
111
+ isSubscribed: z.boolean().optional(),
112
+ name: z.string().optional(),
113
+ parentId: z.string().nullish(),
114
+ })
115
+ .catchall(
116
+ z.unknown().superRefine((_, context) => {
117
+ methodIssue(context, "unsupportedFilter", "Unsupported Mailbox filter");
118
+ })
119
+ )
120
+ .nullish(),
121
+ sort: z.array(mailboxComparator).nullish(),
122
+ position: z.number().int().nullish(),
123
+ limit: z.number().int().nonnegative().nullish(),
124
+ });
125
+
126
+ export async function mailboxQuery(
127
+ state: RequestState,
128
+ args: z.output<typeof mailboxQueryArguments>
129
+ ) {
130
+ const owner = account(state, args.accountId);
131
+
132
+ const { state: mailboxState, mailboxes } = await mailboxStub(
133
+ state.context.env,
134
+ owner.id
135
+ ).jmapMailboxes(state.context.user.id, false);
136
+
137
+ const role = args.filter?.role;
138
+ const name = args.filter?.name?.toLowerCase();
139
+
140
+ const matching = mailboxes.filter(
141
+ (row) =>
142
+ args.filter?.parentId == null &&
143
+ args.filter?.isSubscribed !== false &&
144
+ (args.filter?.hasAnyRole === undefined ||
145
+ args.filter.hasAnyRole === (row.role !== null)) &&
146
+ (role === undefined || row.role === role) &&
147
+ (name === undefined || row.name.toLowerCase().includes(name))
148
+ );
149
+
150
+ const sort = args.sort ?? [];
151
+
152
+ const ordered = sort.length
153
+ ? matching.sort((left, right) => {
154
+ for (const { property, isAscending } of sort) {
155
+ const difference =
156
+ property === "sortOrder"
157
+ ? left.sortOrder - right.sortOrder
158
+ : left.name.localeCompare(right.name, undefined, {
159
+ sensitivity: "accent",
160
+ });
161
+
162
+ if (difference) return isAscending ? difference : -difference;
163
+ }
164
+
165
+ return left.id.localeCompare(right.id);
166
+ })
167
+ : sortFolders(matching);
168
+
169
+ const ids = ordered.map((row) => row.id);
170
+
171
+ const requested = args.position ?? 0;
172
+
173
+ const position =
174
+ requested < 0 ? Math.max(0, ids.length + requested) : requested;
175
+
176
+ return {
177
+ accountId: owner.id,
178
+ queryState: mailboxState,
179
+ canCalculateChanges: false,
180
+ position,
181
+ ids: ids.slice(
182
+ position,
183
+ args.limit == null ? undefined : position + args.limit
184
+ ),
185
+ total: ids.length,
186
+ };
187
+ }