@remit/mailbox-service 0.0.111 → 0.0.112

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 (123) hide show
  1. package/package.json +21 -6
  2. package/src/body-part-mapper.ts +51 -1
  3. package/src/body-sync-queue.test.ts +39 -99
  4. package/src/body-sync-terminal.test.ts +115 -277
  5. package/src/body-sync-terminal.ts +10 -12
  6. package/src/body-sync.test.ts +925 -0
  7. package/src/body-sync.ts +156 -235
  8. package/src/classification-backfill.test.ts +197 -527
  9. package/src/classify-message.test.ts +11 -74
  10. package/src/external-move.test.ts +102 -209
  11. package/src/external-move.ts +13 -0
  12. package/src/filter-operations.test.ts +319 -0
  13. package/src/filter-operations.ts +377 -0
  14. package/src/filter-update.test.ts +313 -0
  15. package/src/filters/filter-config.test.ts +55 -197
  16. package/src/filters/filter-config.ts +4 -39
  17. package/src/filters/match.test.ts +1 -38
  18. package/src/filters/match.ts +3 -52
  19. package/src/filters/pipeline.test.ts +158 -289
  20. package/src/filters/pipeline.ts +56 -170
  21. package/src/flag-push-terminal.ts +9 -11
  22. package/src/flag-push.test.ts +76 -372
  23. package/src/flag-queue.test.ts +197 -0
  24. package/src/folder-operations.test.ts +273 -0
  25. package/src/folder-operations.ts +217 -0
  26. package/src/forwarded-message.test.ts +122 -0
  27. package/src/imapflow-connect-retry.test.ts +76 -113
  28. package/src/imapflow-connection.test.ts +34 -0
  29. package/src/imapflow-connection.ts +5 -4
  30. package/src/index.ts +59 -12
  31. package/src/list-id-backfill.test.ts +133 -499
  32. package/src/mailbox-cursor.test.ts +81 -189
  33. package/src/mailbox-delete-intent.test.ts +78 -205
  34. package/src/mailbox-intent.ts +5 -3
  35. package/src/mailbox-management.test.ts +107 -220
  36. package/src/mailbox-management.ts +1 -2
  37. package/src/mailbox-presence.test.ts +36 -34
  38. package/src/mailbox-queue.ts +2 -20
  39. package/src/mailbox-rename-intent.test.ts +156 -325
  40. package/src/mailbox-rename-subtree.test.ts +205 -582
  41. package/src/mailbox-sync.test.ts +182 -744
  42. package/src/message-move.test.ts +726 -0
  43. package/src/message-move.ts +227 -57
  44. package/src/message-read.ts +87 -0
  45. package/src/message-save-retry.test.ts +90 -0
  46. package/src/message-sync-flags.test.ts +10 -1
  47. package/src/message-sync.test.ts +762 -0
  48. package/src/message-sync.ts +409 -239
  49. package/src/mime-walker.ts +16 -15
  50. package/src/organize-job.ts +93 -0
  51. package/src/outbox-attachment.test.ts +97 -209
  52. package/src/outbox-failed-recovery.test.ts +198 -269
  53. package/src/outbox-queue.test.ts +24 -0
  54. package/src/outbox-queue.ts +25 -8
  55. package/src/ownership.ts +140 -0
  56. package/src/placement-move-terminal.ts +9 -12
  57. package/src/placement-move.ts +33 -6
  58. package/src/placement-settled.ts +28 -4
  59. package/src/placement.test.ts +404 -0
  60. package/src/quarantine.test.ts +90 -148
  61. package/src/quarantine.ts +3 -2
  62. package/src/refusal.ts +29 -0
  63. package/src/restore-source-placement.ts +0 -4
  64. package/src/spam-report.test.ts +238 -710
  65. package/src/sync-warning.test.ts +213 -0
  66. package/src/sync-warning.ts +56 -0
  67. package/src/test-helpers/fake-imap.ts +690 -0
  68. package/src/test-helpers/test-queue.ts +56 -0
  69. package/src/test-helpers/test-store.ts +299 -0
  70. package/src/thread-root.test.ts +29 -0
  71. package/src/thread-root.ts +51 -0
  72. package/src/types/mailparser-augment.d.ts +8 -0
  73. package/src/adversarial-mime.e2e.test.ts +0 -307
  74. package/src/body-sync-auto-read-writeonce.test.ts +0 -219
  75. package/src/body-sync-calendar-suggestion.test.ts +0 -433
  76. package/src/body-sync-category-denormalize.test.ts +0 -352
  77. package/src/body-sync-category-override.test.ts +0 -501
  78. package/src/body-sync-category-writeonce.test.ts +0 -234
  79. package/src/body-sync-filter.test.ts +0 -237
  80. package/src/body-sync-message-gone.test.ts +0 -139
  81. package/src/body-sync-placement-flags.test.ts +0 -347
  82. package/src/body-sync-placement-writeonce.test.ts +0 -337
  83. package/src/body-sync-quarantine.test.ts +0 -276
  84. package/src/body-sync-resync.test.ts +0 -605
  85. package/src/body-sync-unclassifiable-once.test.ts +0 -260
  86. package/src/body-sync-unsubscribed-auto-read.test.ts +0 -176
  87. package/src/filters/anchor-drift.ts +0 -55
  88. package/src/filters/message-embedder.test.ts +0 -39
  89. package/src/filters/message-embedder.ts +0 -33
  90. package/src/flag-push-terminal.test.ts +0 -209
  91. package/src/flag-queue-stars.test.ts +0 -171
  92. package/src/imapflow-connection.e2e.test.ts +0 -335
  93. package/src/imapflow-connection.integ.test.ts +0 -316
  94. package/src/message-delete-junk-reconcile.test.ts +0 -117
  95. package/src/message-delete-no-trash.test.ts +0 -245
  96. package/src/message-delete-unsettled-placement.test.ts +0 -396
  97. package/src/message-move-copy.test.ts +0 -562
  98. package/src/message-move-empty-trash.test.ts +0 -326
  99. package/src/message-move-same-mailbox.test.ts +0 -139
  100. package/src/message-move-unsettled-placement.test.ts +0 -378
  101. package/src/message-sync-address-spoof.test.ts +0 -293
  102. package/src/message-sync-category.test.ts +0 -142
  103. package/src/message-sync-changedsince.test.ts +0 -840
  104. package/src/message-sync-junk-harvest.test.ts +0 -244
  105. package/src/message-sync-quarantine.test.ts +0 -416
  106. package/src/message-sync-repoint.test.ts +0 -419
  107. package/src/outbox-queue-settled-row.test.ts +0 -140
  108. package/src/pass-through-unit-of-work.ts +0 -17
  109. package/src/placement-move-terminal.test.ts +0 -300
  110. package/src/placement-move-unsettled.test.ts +0 -275
  111. package/src/placement-transition-race.test.ts +0 -482
  112. package/src/stale-message-reconcile.test.ts +0 -82
  113. package/src/stale-message-reconcile.ts +0 -55
  114. package/src/test-helpers/isolated-mailbox.ts +0 -44
  115. package/src/test-helpers/mailfuzz-connection.ts +0 -27
  116. package/test/fixtures/mime-adversarial-e2e/01-octet-stream-pdf.eml +0 -21
  117. package/test/fixtures/mime-adversarial-e2e/02-nested-related-cid-image.eml +0 -31
  118. package/test/fixtures/mime-adversarial-e2e/03-calendar-invite.eml +0 -33
  119. package/test/fixtures/mime-adversarial-e2e/04-forwarded-rfc822-with-attachments.eml +0 -42
  120. package/test/fixtures/mime-adversarial-e2e/05-tnef-winmail.eml +0 -25
  121. package/test/fixtures/mime-adversarial-e2e/06-8bit-non-ascii.eml +0 -15
  122. package/test/fixtures/mime-adversarial-e2e/07-quoted-printable-soft-breaks.eml +0 -17
  123. package/test/fixtures/mime-adversarial-e2e/08-alternative-empty-text.eml +0 -18
@@ -0,0 +1,726 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, beforeEach, describe, it } from "node:test";
3
+ import type {
4
+ AccountItem,
5
+ CreateMessageInput,
6
+ MailboxItem,
7
+ } from "@remit/data-ports";
8
+ import { MessagePlacementUnsettledError } from "@remit/data-ports/errors";
9
+ import { composeFolderRoleAppointmentName } from "@remit/data-ports/folder-role";
10
+ import { deriveAddressId, deriveCopyMessageId } from "@remit/data-ports/id";
11
+ import {
12
+ CanonicalMailboxRole,
13
+ MessageClassificationState,
14
+ } from "@remit/domain-enums";
15
+ import { BodySyncService } from "./body-sync.js";
16
+ import {
17
+ MessageMoveService,
18
+ NoTrashMailboxError,
19
+ StaleTrashAppointmentError,
20
+ UnconfirmedTrashMailboxError,
21
+ } from "./message-move.js";
22
+ import { restoreSourcePlacement } from "./restore-source-placement.js";
23
+ import { SyncWarningService } from "./sync-warning.js";
24
+ import { eml, FakeImapServer } from "./test-helpers/fake-imap.js";
25
+ import {
26
+ arriveAt,
27
+ captureQueue,
28
+ openStore,
29
+ type QueueCapture,
30
+ type QueuedEvent,
31
+ type Store,
32
+ seedAccount,
33
+ seedMailbox,
34
+ seedMessage,
35
+ silentLog,
36
+ syncFolder,
37
+ } from "./test-helpers/test-store.js";
38
+
39
+ type TrashSetup = "flagged" | "named" | "none" | "appointed" | "stale";
40
+
41
+ let store: Store;
42
+ let capture: QueueCapture;
43
+ let queue: QueuedEvent[];
44
+ let imap: FakeImapServer;
45
+ let account: AccountItem;
46
+ let inbox: MailboxItem;
47
+ let archive: MailboxItem;
48
+ let junk: MailboxItem;
49
+ let trash: MailboxItem | undefined;
50
+
51
+ beforeEach(async () => {
52
+ capture = captureQueue();
53
+ queue = capture.sent;
54
+ store = await openStore();
55
+ imap = new FakeImapServer();
56
+ });
57
+
58
+ afterEach(async () => {
59
+ capture.restore();
60
+ await store.close();
61
+ });
62
+
63
+ const appoint = (mailboxId: string) =>
64
+ store.accountSetting.upsert({
65
+ accountConfigId: account.accountConfigId,
66
+ name: composeFolderRoleAppointmentName(
67
+ account.accountId,
68
+ CanonicalMailboxRole.Trash,
69
+ ),
70
+ value: { kind: "String", value: mailboxId },
71
+ });
72
+
73
+ const world = async (setup: TrashSetup = "flagged") => {
74
+ account = await seedAccount(store);
75
+ inbox = await seedMailbox(store, account, "INBOX");
76
+ archive = await seedMailbox(store, account, "Archive");
77
+ junk = await seedMailbox(store, account, "Junk", { specialUse: "Junk" });
78
+ trash = undefined;
79
+ if (setup === "flagged" || setup === "stale") {
80
+ trash = await seedMailbox(store, account, "INBOX/Trash", {
81
+ specialUse: "Trash",
82
+ });
83
+ }
84
+ if (setup === "named") {
85
+ trash = await seedMailbox(store, account, "Trash");
86
+ }
87
+ if (setup === "appointed") {
88
+ await seedMailbox(store, account, "Deleted");
89
+ trash = await seedMailbox(store, account, "Bin");
90
+ await appoint(trash.mailboxId);
91
+ }
92
+ if (setup === "stale") {
93
+ await appoint("mbx-appointed-and-gone");
94
+ }
95
+ for (const mailbox of await store.mailbox.listAllByAccount(
96
+ account.accountId,
97
+ )) {
98
+ imap.addFolder(mailbox.fullPath);
99
+ }
100
+ };
101
+
102
+ const service = () =>
103
+ new MessageMoveService({
104
+ messageService: store.message,
105
+ mailboxService: store.mailbox,
106
+ mailboxSpecialUseService: store.mailboxSpecialUse,
107
+ threadMessageService: store.threadMessage,
108
+ addressService: store.address,
109
+ sqsQueueUrl: "http://localhost:9324/000000000000/remit-messages.fifo",
110
+ moveSettleTimeoutMs: 200,
111
+ moveSettlePollMs: 10,
112
+ });
113
+
114
+ const rowIn = async (
115
+ mailbox: MailboxItem,
116
+ uid: number,
117
+ message: Partial<CreateMessageInput> = {},
118
+ ) =>
119
+ (await seedMessage(store, account, mailbox, uid, { message })).message
120
+ .messageId;
121
+
122
+ const midMove = async (uid = 42) => {
123
+ const messageId = await rowIn(inbox, uid);
124
+ await service().moveMessage(
125
+ account.accountConfigId,
126
+ messageId,
127
+ archive.mailboxId,
128
+ account.accountId,
129
+ );
130
+ queue.length = 0;
131
+ return messageId;
132
+ };
133
+
134
+ const midDelete = async (uid = 42) => {
135
+ const messageId = await rowIn(inbox, uid);
136
+ await service().deleteMessages(
137
+ account.accountConfigId,
138
+ [messageId],
139
+ account.accountId,
140
+ );
141
+ queue.length = 0;
142
+ return messageId;
143
+ };
144
+
145
+ const settleLater = (messageId: string, uid = 907) =>
146
+ setTimeout(() => {
147
+ void store.message.updateUid(messageId, uid, archive.mailboxId);
148
+ }, 30);
149
+
150
+ const row = (messageId: string) => store.message.get(messageId);
151
+
152
+ describe("moving a message", () => {
153
+ it("moves locally first and enqueues the IMAP move from the folder it is in", async () => {
154
+ await world();
155
+ const messageId = await rowIn(inbox, 337);
156
+
157
+ await service().moveMessages(
158
+ account.accountConfigId,
159
+ [messageId],
160
+ archive.mailboxId,
161
+ account.accountId,
162
+ );
163
+
164
+ const moved = await row(messageId);
165
+ assert.equal(moved.mailboxId, archive.mailboxId);
166
+ assert.equal(moved.syncStatus, "pending");
167
+ assert.deepEqual(
168
+ queue.map((event) => [
169
+ event.body.type,
170
+ event.body.sourceMailboxPath,
171
+ event.body.uid,
172
+ ]),
173
+ [["MESSAGE_MOVE", "INBOX", 337]],
174
+ );
175
+ });
176
+
177
+ it("does nothing for a move into the folder the message is already in", async () => {
178
+ await world();
179
+ const messageId = await rowIn(inbox, 337);
180
+ const before = await row(messageId);
181
+
182
+ await service().moveMessages(
183
+ account.accountConfigId,
184
+ [messageId],
185
+ inbox.mailboxId,
186
+ account.accountId,
187
+ );
188
+
189
+ assert.equal(queue.length, 0);
190
+ assert.deepEqual(await row(messageId), before);
191
+ });
192
+
193
+ it("binds the confirmed folder and uid once an in-flight move settles", async () => {
194
+ await world();
195
+ const messageId = await midMove();
196
+
197
+ settleLater(messageId);
198
+ await service().moveMessage(
199
+ account.accountConfigId,
200
+ messageId,
201
+ inbox.mailboxId,
202
+ account.accountId,
203
+ );
204
+
205
+ assert.deepEqual(
206
+ queue.map((event) => [event.body.sourceMailboxPath, event.body.uid]),
207
+ [["Archive", 907]],
208
+ );
209
+ });
210
+
211
+ it("refuses and writes nothing while the earlier move never settles", async () => {
212
+ await world();
213
+ const messageId = await midMove();
214
+ const before = await row(messageId);
215
+
216
+ await assert.rejects(
217
+ service().moveMessage(
218
+ account.accountConfigId,
219
+ messageId,
220
+ inbox.mailboxId,
221
+ account.accountId,
222
+ ),
223
+ (error: unknown) =>
224
+ error instanceof MessagePlacementUnsettledError &&
225
+ error.statusCode === 409 &&
226
+ error.publicApiError?.details?.reason === "in_flight",
227
+ );
228
+
229
+ assert.equal(queue.length, 0);
230
+ assert.deepEqual(await row(messageId), before);
231
+ });
232
+
233
+ it("never answers the same-folder skip from a folder the message has not reached", async () => {
234
+ await world();
235
+ const messageId = await midMove();
236
+
237
+ await assert.rejects(
238
+ service().moveMessage(
239
+ account.accountConfigId,
240
+ messageId,
241
+ archive.mailboxId,
242
+ account.accountId,
243
+ ),
244
+ MessagePlacementUnsettledError,
245
+ );
246
+ assert.equal(queue.length, 0);
247
+ });
248
+
249
+ it("moves no part of a batch while one row is in flight", async () => {
250
+ await world();
251
+ const settled = await rowIn(inbox, 11);
252
+ const moving = await midMove();
253
+
254
+ await assert.rejects(
255
+ service().moveMessages(
256
+ account.accountConfigId,
257
+ [settled, moving],
258
+ archive.mailboxId,
259
+ account.accountId,
260
+ ),
261
+ MessagePlacementUnsettledError,
262
+ );
263
+
264
+ assert.equal(queue.length, 0);
265
+ assert.equal((await row(settled)).mailboxId, inbox.mailboxId);
266
+ });
267
+
268
+ it("waits out a delete into Trash in flight rather than binding its borrowed uid", async () => {
269
+ await world();
270
+ const messageId = await midDelete();
271
+ assert.equal((await row(messageId)).mailboxId, trash?.mailboxId);
272
+
273
+ await assert.rejects(
274
+ service().moveMessage(
275
+ account.accountConfigId,
276
+ messageId,
277
+ inbox.mailboxId,
278
+ account.accountId,
279
+ ),
280
+ MessagePlacementUnsettledError,
281
+ );
282
+ assert.equal(queue.length, 0);
283
+ });
284
+
285
+ it("moves a row a move gave up on without waiting", async () => {
286
+ await world();
287
+ const stranded = await midMove();
288
+ await restoreSourcePlacement(
289
+ {
290
+ messageService: store.message,
291
+ threadMessageService: store.threadMessage,
292
+ },
293
+ {
294
+ accountConfigId: account.accountConfigId,
295
+ messageId: stranded,
296
+ sourceMailboxId: inbox.mailboxId,
297
+ uid: 42,
298
+ syncStatus: "abandoned",
299
+ abandonedMutation: "move",
300
+ },
301
+ );
302
+ assert.equal((await row(stranded)).syncStatus, "abandoned");
303
+
304
+ const startedAt = Date.now();
305
+ await service().moveMessage(
306
+ account.accountConfigId,
307
+ stranded,
308
+ archive.mailboxId,
309
+ account.accountId,
310
+ );
311
+
312
+ assert.ok(Date.now() - startedAt < 150);
313
+ assert.equal((await row(stranded)).mailboxId, archive.mailboxId);
314
+ });
315
+
316
+ for (const action of ["move", "delete", "copy"] as const) {
317
+ it(`refuses to ${action} a copy the server never confirms, writing nothing`, async () => {
318
+ await world();
319
+ const original = await rowIn(inbox, 5);
320
+ await service().copyMessage(
321
+ account.accountConfigId,
322
+ original,
323
+ archive.mailboxId,
324
+ account.accountId,
325
+ );
326
+ queue.length = 0;
327
+ const copy = deriveCopyMessageId(original, archive.mailboxId);
328
+ const before = await row(copy);
329
+
330
+ await assert.rejects(
331
+ action === "delete"
332
+ ? service().deleteMessages(
333
+ account.accountConfigId,
334
+ [copy],
335
+ account.accountId,
336
+ { permanent: true },
337
+ )
338
+ : service()[`${action}Message`](
339
+ account.accountConfigId,
340
+ copy,
341
+ inbox.mailboxId,
342
+ account.accountId,
343
+ ),
344
+ (error: unknown) =>
345
+ error instanceof MessagePlacementUnsettledError &&
346
+ error.statusCode === 409 &&
347
+ error.publicApiError?.details?.reason === "in_flight",
348
+ );
349
+
350
+ assert.equal(queue.length, 0);
351
+ assert.deepEqual(await row(copy), before);
352
+ });
353
+ }
354
+ });
355
+
356
+ describe("deleting a message", () => {
357
+ const remove = (messageIds: string[], permanent = false) =>
358
+ service().deleteMessages(
359
+ account.accountConfigId,
360
+ messageIds,
361
+ account.accountId,
362
+ permanent ? { permanent } : undefined,
363
+ );
364
+
365
+ it("moves it into a Trash the server flagged under a nested path", async () => {
366
+ await world("flagged");
367
+ const messageId = await rowIn(inbox, 5);
368
+
369
+ await remove([messageId]);
370
+
371
+ assert.equal((await row(messageId)).mailboxId, trash?.mailboxId);
372
+ assert.deepEqual(
373
+ queue.map((event) => [
374
+ event.body.operation,
375
+ event.body.destinationMailboxPath,
376
+ ]),
377
+ [["move_to_trash", "INBOX/Trash"]],
378
+ );
379
+ });
380
+
381
+ it("files into a Trash that resolves by name alone", async () => {
382
+ await world("named");
383
+ const messageId = await rowIn(inbox, 5);
384
+
385
+ await remove([messageId]);
386
+
387
+ assert.equal((await row(messageId)).mailboxId, trash?.mailboxId);
388
+ });
389
+
390
+ for (const [setup, error, reason] of [
391
+ ["none", NoTrashMailboxError, "none"],
392
+ ["stale", StaleTrashAppointmentError, "stale"],
393
+ ] as const) {
394
+ it(`refuses and touches nothing when the Trash is ${reason}`, async () => {
395
+ await world(setup);
396
+ const messageId = await rowIn(inbox, 5);
397
+ const before = await row(messageId);
398
+
399
+ await assert.rejects(
400
+ remove([messageId]),
401
+ (thrown: unknown) =>
402
+ thrown instanceof error &&
403
+ thrown.statusCode === 409 &&
404
+ thrown.publicApiError?.details?.reason === reason,
405
+ );
406
+
407
+ assert.equal(queue.length, 0);
408
+ assert.deepEqual(await row(messageId), before);
409
+ });
410
+ }
411
+
412
+ it("expunges only when asked for a permanent delete", async () => {
413
+ await world("none");
414
+ const messageId = await rowIn(inbox, 5);
415
+
416
+ await remove([messageId], true);
417
+
418
+ assert.deepEqual(
419
+ queue.map((event) => event.body.operation),
420
+ ["permanent_delete"],
421
+ );
422
+ });
423
+
424
+ it("expunges a message already in a confirmed Trash", async () => {
425
+ await world("flagged");
426
+ const messageId = await rowIn(trash as MailboxItem, 5);
427
+
428
+ await remove([messageId]);
429
+
430
+ assert.deepEqual(
431
+ queue.map((event) => event.body.operation),
432
+ ["permanent_delete"],
433
+ );
434
+ });
435
+
436
+ it("refuses to expunge from a Trash that only resolves by name", async () => {
437
+ await world("named");
438
+ const messageId = await rowIn(trash as MailboxItem, 5);
439
+
440
+ await assert.rejects(
441
+ remove([messageId]),
442
+ (thrown: unknown) =>
443
+ thrown instanceof UnconfirmedTrashMailboxError &&
444
+ thrown.publicApiError?.details?.reason === "unconfirmed",
445
+ );
446
+ assert.equal(queue.length, 0);
447
+ });
448
+
449
+ it("withholds a sender whose only other mail is in Junk once this one is in Trash", async () => {
450
+ await world("flagged");
451
+ const raw = eml({ From: "Spam <spam@example.com>" });
452
+ await arriveAt(store, imap, account, junk, raw);
453
+ const kept = await arriveAt(
454
+ store,
455
+ imap,
456
+ account,
457
+ inbox,
458
+ eml({ From: "Spam <spam@example.com>", "Message-ID": "<b@x>" }),
459
+ );
460
+ const sender = () =>
461
+ store.address.getAddress(
462
+ account.accountConfigId,
463
+ deriveAddressId(account.accountConfigId, "spam@example.com"),
464
+ );
465
+ assert.equal((await sender()).flags.junkOnly, undefined);
466
+
467
+ await remove([kept]);
468
+
469
+ assert.equal((await sender()).flags.junkOnly?.value, true);
470
+ });
471
+
472
+ it("binds the confirmed pair once an in-flight move settles", async () => {
473
+ await world("flagged");
474
+ const messageId = await midMove();
475
+
476
+ settleLater(messageId);
477
+ await remove([messageId]);
478
+
479
+ assert.deepEqual(
480
+ queue.map((event) => [event.body.mailboxPath, event.body.uid]),
481
+ [["Archive", 907]],
482
+ );
483
+ });
484
+
485
+ it("expunges no part of a batch while one row is in flight, and all of it once it settles", async () => {
486
+ await world("flagged");
487
+ const settled = await rowIn(inbox, 11);
488
+ const moving = await midMove();
489
+
490
+ await assert.rejects(
491
+ remove([settled, moving], true),
492
+ MessagePlacementUnsettledError,
493
+ );
494
+ assert.equal(queue.length, 0);
495
+
496
+ settleLater(moving);
497
+ await remove([settled, moving], true);
498
+
499
+ assert.deepEqual(
500
+ queue.map((event) => [event.body.messageId, event.body.uid]).sort(),
501
+ [
502
+ [moving, 907],
503
+ [settled, 11],
504
+ ].sort(),
505
+ );
506
+ });
507
+ });
508
+
509
+ describe("copying a message", () => {
510
+ const copy = (messageIds: string[], destination: MailboxItem) =>
511
+ service().copyMessages(
512
+ account.accountConfigId,
513
+ messageIds,
514
+ destination.mailboxId,
515
+ account.accountId,
516
+ );
517
+
518
+ const COPIED = eml({
519
+ "Message-ID": "<copied@example.com>",
520
+ "List-Id": "LinkedIn Invitations <invitations.linkedin.com>",
521
+ });
522
+
523
+ const source = async () => {
524
+ const messageId = await arriveAt(store, imap, account, inbox, COPIED);
525
+ await new BodySyncService(
526
+ store.message,
527
+ store.storage(),
528
+ store.threadMessage,
529
+ store.address,
530
+ store.envelope,
531
+ new SyncWarningService(store.syncWarning),
532
+ silentLog,
533
+ ).syncBodies(
534
+ [messageId],
535
+ account.accountId,
536
+ account.accountConfigId,
537
+ {
538
+ mailboxId: inbox.mailboxId,
539
+ fullPath: inbox.fullPath,
540
+ placement: "inbox",
541
+ uidValidity: inbox.uidValidity,
542
+ },
543
+ async () => imap.connection(),
544
+ );
545
+ return messageId;
546
+ };
547
+
548
+ const threads = async (messageId: string) =>
549
+ store.threadMessage.findAllByMessageId(account.accountConfigId, messageId);
550
+
551
+ it("derives the copy's id from source and destination and carries its derived fields", async () => {
552
+ await world();
553
+ const original = await source();
554
+
555
+ await copy([original], archive);
556
+
557
+ const copyId = deriveCopyMessageId(original, archive.mailboxId);
558
+ const copied = await row(copyId);
559
+ assert.equal(copied.mailboxId, archive.mailboxId);
560
+ assert.equal(
561
+ copied.classificationState,
562
+ MessageClassificationState.Examined,
563
+ );
564
+ assert.equal((await threads(copyId))[0].listId, "invitations.linkedin.com");
565
+ assert.deepEqual(
566
+ queue.map((event) => event.body.type),
567
+ ["MESSAGE_COPY"],
568
+ );
569
+ });
570
+
571
+ it("converges a replayed copy on one row", async () => {
572
+ await world();
573
+ const original = await source();
574
+
575
+ await copy([original], archive);
576
+ await copy([original], archive);
577
+
578
+ const copyId = deriveCopyMessageId(original, archive.mailboxId);
579
+ assert.equal((await threads(copyId)).length, 1);
580
+ assert.equal(
581
+ (await store.message.listAllByMailbox(archive.mailboxId)).length,
582
+ 1,
583
+ );
584
+ });
585
+
586
+ it("adds no third row when the destination folder syncs the copy", async () => {
587
+ await world();
588
+ const original = await source();
589
+ await copy([original], archive);
590
+ const copyId = deriveCopyMessageId(original, archive.mailboxId);
591
+ const uid = imap.deliver("Archive", COPIED);
592
+ await store.message.updateUid(copyId, uid, archive.mailboxId);
593
+
594
+ await syncFolder(store, account, archive, imap);
595
+
596
+ assert.equal(
597
+ (await store.message.listAllByMailbox(archive.mailboxId)).length,
598
+ 1,
599
+ );
600
+ assert.equal((await row(original)).mailboxId, inbox.mailboxId);
601
+ assert.equal((await threads(copyId)).length, 1);
602
+ });
603
+
604
+ it("deletes the copy or the original without touching the other", async () => {
605
+ await world();
606
+ const original = await source();
607
+ await copy([original], archive);
608
+ const copyId = deriveCopyMessageId(original, archive.mailboxId);
609
+ await store.message.updateUid(copyId, 77, archive.mailboxId);
610
+
611
+ await service().deleteMessages(
612
+ account.accountConfigId,
613
+ [copyId],
614
+ account.accountId,
615
+ { permanent: true },
616
+ );
617
+
618
+ assert.deepEqual(await threads(copyId), []);
619
+ assert.equal((await threads(original)).length, 1);
620
+ });
621
+
622
+ it("binds the confirmed pair once an in-flight move settles, and refuses a batch until then", async () => {
623
+ await world();
624
+ const settled = await rowIn(inbox, 11);
625
+ const moving = await midMove();
626
+
627
+ await assert.rejects(
628
+ copy([settled, moving], junk),
629
+ MessagePlacementUnsettledError,
630
+ );
631
+ assert.equal(queue.length, 0);
632
+
633
+ settleLater(moving);
634
+ await service().copyMessage(
635
+ account.accountConfigId,
636
+ moving,
637
+ inbox.mailboxId,
638
+ account.accountId,
639
+ );
640
+
641
+ assert.deepEqual(
642
+ queue.map((event) => [event.body.sourceMailboxPath, event.body.uid]),
643
+ [["Archive", 907]],
644
+ );
645
+ });
646
+ });
647
+
648
+ describe("emptying the Trash", () => {
649
+ const empty = () =>
650
+ service().emptyTrash(account.accountConfigId, account.accountId);
651
+
652
+ it("empties the appointed Trash, never the folder called Deleted", async () => {
653
+ await world("appointed");
654
+ const binned = await rowIn(trash as MailboxItem, 1);
655
+
656
+ const { deletedCount } = await empty();
657
+
658
+ assert.equal(deletedCount, 1);
659
+ assert.equal((await row(binned)).status, "deleting");
660
+ assert.deepEqual(
661
+ queue.map((event) => [
662
+ event.body.type,
663
+ event.body.trashMailboxId,
664
+ event.body.trashUidValidity,
665
+ ]),
666
+ [["EMPTY_TRASH", trash?.mailboxId, trash?.uidValidity]],
667
+ );
668
+ });
669
+
670
+ for (const [setup, error, reason] of [
671
+ ["none", NoTrashMailboxError, "none"],
672
+ ["named", UnconfirmedTrashMailboxError, "unconfirmed"],
673
+ ["stale", StaleTrashAppointmentError, "stale"],
674
+ ] as const) {
675
+ it(`refuses when the Trash is ${reason}`, async () => {
676
+ await world(setup);
677
+ const kept = trash ? await rowIn(trash, 1) : undefined;
678
+
679
+ await assert.rejects(
680
+ empty(),
681
+ (thrown: unknown) =>
682
+ thrown instanceof error &&
683
+ thrown.publicApiError?.details?.reason === reason,
684
+ );
685
+
686
+ assert.equal(queue.length, 0);
687
+ if (kept) assert.equal((await row(kept)).status, "active");
688
+ });
689
+ }
690
+
691
+ it("marks settled and sync-pending rows but leaves a move into Trash alone", async () => {
692
+ await world("flagged");
693
+ const bin = trash as MailboxItem;
694
+ const settled = await rowIn(bin, 1);
695
+ const pending = await arriveAt(store, imap, account, bin, eml({}));
696
+ const arriving = await rowIn(inbox, 10);
697
+ await service().moveMessage(
698
+ account.accountConfigId,
699
+ arriving,
700
+ bin.mailboxId,
701
+ account.accountId,
702
+ );
703
+ queue.length = 0;
704
+
705
+ const { deletedCount } = await empty();
706
+
707
+ assert.equal(deletedCount, 2);
708
+ assert.equal((await row(settled)).status, "deleting");
709
+ assert.equal((await row(pending)).status, "deleting");
710
+ assert.equal((await row(arriving)).status, "moving");
711
+ });
712
+
713
+ it("reports the same count when pressed twice before the worker runs", async () => {
714
+ await world("flagged");
715
+ const bin = trash as MailboxItem;
716
+ await rowIn(bin, 1);
717
+ await rowIn(bin, 2);
718
+
719
+ const first = await empty();
720
+ const second = await empty();
721
+
722
+ assert.equal(first.deletedCount, 2);
723
+ assert.equal(second.deletedCount, 2);
724
+ assert.equal(queue.length, 2);
725
+ });
726
+ });