@wtfalch/email 0.13.1 → 0.15.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 (60) hide show
  1. package/README.md +390 -12
  2. package/dist/imip/compose.d.ts +5 -0
  3. package/dist/imip/compose.js +84 -0
  4. package/dist/imip/index.d.ts +15 -0
  5. package/dist/imip/index.js +14 -0
  6. package/dist/imip/lookup.d.ts +21 -0
  7. package/dist/imip/lookup.js +26 -0
  8. package/dist/imip/parse.d.ts +11 -0
  9. package/dist/imip/parse.js +116 -0
  10. package/dist/imip/types.d.ts +57 -0
  11. package/dist/imip/types.js +9 -0
  12. package/dist/mailbox/client.d.ts +28 -1
  13. package/dist/mailbox/client.js +51 -0
  14. package/dist/mailbox/fake/mailbox.js +567 -7
  15. package/dist/mailbox/index.d.ts +16 -8
  16. package/dist/mailbox/index.js +8 -4
  17. package/dist/mailbox/mail.css +13 -0
  18. package/dist/mailbox/mailboxes.d.ts +95 -1
  19. package/dist/mailbox/mailboxes.js +243 -1
  20. package/dist/mailbox/mutate.d.ts +21 -0
  21. package/dist/mailbox/mutate.js +71 -0
  22. package/dist/mailbox/quoted.d.ts +94 -0
  23. package/dist/mailbox/quoted.js +158 -0
  24. package/dist/mailbox/react/Composer.js +13 -1
  25. package/dist/mailbox/react/Mail.js +273 -33
  26. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  27. package/dist/mailbox/react/ThreadView.js +5 -4
  28. package/dist/mailbox/react/index.d.ts +3 -1
  29. package/dist/mailbox/react/index.js +2 -1
  30. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  31. package/dist/mailbox/react/quotedHtml.js +163 -0
  32. package/dist/mailbox/sieve.d.ts +76 -0
  33. package/dist/mailbox/sieve.js +241 -0
  34. package/dist/mailbox/snooze.d.ts +48 -0
  35. package/dist/mailbox/snooze.js +176 -0
  36. package/dist/mailbox/submit.d.ts +56 -2
  37. package/dist/mailbox/submit.js +145 -11
  38. package/dist/mailbox/threads.js +2 -0
  39. package/dist/mailbox/types.d.ts +60 -0
  40. package/dist/mailbox/vacation.d.ts +32 -0
  41. package/dist/mailbox/vacation.js +79 -0
  42. package/dist/postmaster/apply.d.ts +154 -1
  43. package/dist/postmaster/apply.js +336 -1
  44. package/dist/postmaster/audit.d.ts +22 -1
  45. package/dist/postmaster/audit.js +7 -0
  46. package/dist/postmaster/client.d.ts +49 -0
  47. package/dist/postmaster/client.js +43 -0
  48. package/dist/postmaster/index.d.ts +6 -3
  49. package/dist/postmaster/index.js +5 -2
  50. package/dist/postmaster/mail-copy.d.ts +169 -0
  51. package/dist/postmaster/mail-copy.js +259 -0
  52. package/dist/postmaster/objects.js +11 -0
  53. package/dist/postmaster/org-mail.d.ts +117 -0
  54. package/dist/postmaster/org-mail.js +206 -0
  55. package/dist/postmaster/overview.d.ts +4 -0
  56. package/dist/postmaster/queue.d.ts +111 -0
  57. package/dist/postmaster/queue.js +64 -0
  58. package/dist/postmaster/writes.d.ts +59 -0
  59. package/dist/postmaster/writes.js +106 -0
  60. package/package.json +8 -3
@@ -13,9 +13,28 @@
13
13
  * `unknownMethod`, which is what a real server does and what the error path
14
14
  * expects.
15
15
  */
16
+ /** The fake models a single account, so its own `myRights` on its own
17
+ * mailboxes are always every right, granted -- there is no second login
18
+ * here for `shareWith` to matter *to*. What `shareMailbox`/`unshareMailbox`
19
+ * exercise is what this account grants to OTHER accounts, which is
20
+ * `shareWith`, not `myRights`. */
21
+ const OWNER_RIGHTS = {
22
+ mayReadItems: true,
23
+ mayAddItems: true,
24
+ mayRemoveItems: true,
25
+ maySetSeen: true,
26
+ maySetKeywords: true,
27
+ mayCreateChild: true,
28
+ mayRename: true,
29
+ maySubmit: true,
30
+ mayDelete: true,
31
+ mayShare: true,
32
+ };
16
33
  const ACCOUNT = 'fake-account';
17
34
  /** Stalwart's five, with its names and Stalwart's uniform sortOrder of 0 --
18
- * which is what makes a real tree come out alphabetical. */
35
+ * which is what makes a real tree come out alphabetical. Copied fresh into
36
+ * each instance's `#boxes`, never held here: a rename must not leak from
37
+ * one test's fake into the next. */
19
38
  const MAILBOXES = [
20
39
  { id: 'mb-inbox', name: 'Inbox', role: 'inbox' },
21
40
  { id: 'mb-drafts', name: 'Drafts', role: 'drafts' },
@@ -42,6 +61,9 @@ export class FakeMailbox {
42
61
  #latency;
43
62
  #maxSizeUpload;
44
63
  #emails = [];
64
+ /** Every mailbox: Stalwart's fixed five, then whatever `Mailbox/set` made.
65
+ * A fresh copy per instance -- see `MAILBOXES`'s note on why. */
66
+ #boxes;
45
67
  #threads = new Map();
46
68
  #counter = 0;
47
69
  /** Everything `EmailSubmission/set` accepted, for a test that asserts a
@@ -54,11 +76,44 @@ export class FakeMailbox {
54
76
  /** Every blob uploaded, for a test that asserts the bytes reached the
55
77
  * server rather than only the composer. */
56
78
  uploads = [];
79
+ /** RFC 8621 §8's singleton, `id: 'singleton'` always -- there is no create
80
+ * or destroy for it, only the one object every account starts with, off
81
+ * and empty. */
82
+ #vacation = {
83
+ isEnabled: false,
84
+ fromDate: null,
85
+ toDate: null,
86
+ subject: null,
87
+ textBody: null,
88
+ htmlBody: null,
89
+ };
90
+ /** An uploaded blob's actual bytes, as text, keyed by the id `uploads`
91
+ * also records. Nothing else in this fake stores content -- an
92
+ * attachment's synthetic blobId (`add()`, above) is never a key here, so
93
+ * `/jmap/download/` falls back to its fixed stub for those, unchanged.
94
+ * Sieve scripts read back what was uploaded, and a body part derived
95
+ * from a `bodyStructure` create (`#deriveBodyParts`) stores its bytes
96
+ * here too, so an iMIP part downloads as what was sent. */
97
+ #blobContents = new Map();
98
+ /** `SieveScript` objects: `{id, name, blobId}` triples, `isActive` derived
99
+ * from `#activeSieveScriptId` -- the same shape `SieveProperty` has on the
100
+ * real server (`jmap-proto/src/object/sieve.rs:19-24`). */
101
+ #sieveScripts = [];
102
+ #activeSieveScriptId = null;
57
103
  constructor(options = {}) {
58
104
  this.me = options.me ?? { name: 'Ada Lovelace', email: 'ada@example.com' };
59
105
  this.#now = options.now ?? new Date('2026-09-07T12:00:00Z');
60
106
  this.#latency = options.latency ?? 0;
61
107
  this.#maxSizeUpload = options.maxSizeUpload ?? STALWART_MAX_SIZE;
108
+ this.#boxes = MAILBOXES.map((box) => ({
109
+ id: box.id,
110
+ name: box.name,
111
+ parentId: null,
112
+ role: box.role,
113
+ sortOrder: 0,
114
+ isSubscribed: true,
115
+ shareWith: {},
116
+ }));
62
117
  for (const seed of options.threads ?? [])
63
118
  this.add(seed);
64
119
  }
@@ -149,8 +204,15 @@ export class FakeMailbox {
149
204
  this.#threads.set(threadId, ids);
150
205
  return threadId;
151
206
  }
207
+ /** RFC 8621 §2 on `name`: "There MUST NOT be two sibling Mailboxes with
208
+ * both the same parent and the same name." `excludeId` leaves a
209
+ * mailbox's own current record out, so renaming it to the name it
210
+ * already has is never a collision with itself. */
211
+ #nameCollides(parentId, name, excludeId) {
212
+ return this.#boxes.some((existing) => existing.id !== excludeId && existing.parentId === parentId && existing.name === name);
213
+ }
152
214
  #mailboxes() {
153
- return MAILBOXES.map((box) => {
215
+ return this.#boxes.map((box) => {
154
216
  const inBox = this.#emails.filter((email) => email.mailboxIds[box.id]);
155
217
  const unread = inBox.filter((email) => !email.keywords.$seen);
156
218
  const threads = new Set(inBox.map((email) => email.threadId));
@@ -158,14 +220,16 @@ export class FakeMailbox {
158
220
  return {
159
221
  id: box.id,
160
222
  name: box.name,
161
- parentId: null,
223
+ parentId: box.parentId,
162
224
  role: box.role,
163
- sortOrder: 0,
225
+ sortOrder: box.sortOrder,
164
226
  totalEmails: inBox.length,
165
227
  unreadEmails: unread.length,
166
228
  totalThreads: threads.size,
167
229
  unreadThreads: unreadThreads.size,
168
- isSubscribed: true,
230
+ isSubscribed: box.isSubscribed,
231
+ myRights: OWNER_RIGHTS,
232
+ shareWith: box.shareWith,
169
233
  };
170
234
  });
171
235
  }
@@ -176,6 +240,8 @@ export class FakeMailbox {
176
240
  'urn:ietf:params:jmap:core': { maxSizeUpload: this.#maxSizeUpload },
177
241
  'urn:ietf:params:jmap:mail': {},
178
242
  'urn:ietf:params:jmap:submission': {},
243
+ 'urn:ietf:params:jmap:vacationresponse': {},
244
+ 'urn:ietf:params:jmap:sieve': {},
179
245
  },
180
246
  accounts: {
181
247
  [ACCOUNT]: {
@@ -185,6 +251,8 @@ export class FakeMailbox {
185
251
  accountCapabilities: {
186
252
  'urn:ietf:params:jmap:mail': { maxSizeAttachmentsPerEmail: STALWART_MAX_SIZE },
187
253
  'urn:ietf:params:jmap:submission': {},
254
+ 'urn:ietf:params:jmap:vacationresponse': {},
255
+ 'urn:ietf:params:jmap:sieve': {},
188
256
  },
189
257
  },
190
258
  },
@@ -206,6 +274,144 @@ export class FakeMailbox {
206
274
  switch (method) {
207
275
  case 'Mailbox/get':
208
276
  return { accountId: ACCOUNT, state: 'm1', list: this.#mailboxes(), notFound: [] };
277
+ case 'Mailbox/set': {
278
+ const create = (args.create ?? {});
279
+ const created = {};
280
+ const notCreated = {};
281
+ for (const [key, box] of Object.entries(create)) {
282
+ if (typeof box.name !== 'string' || box.name.length === 0) {
283
+ notCreated[key] = {
284
+ type: 'invalidProperties',
285
+ properties: ['name'],
286
+ description: 'a mailbox needs a name',
287
+ };
288
+ continue;
289
+ }
290
+ const parentId = box.parentId ?? null;
291
+ if (parentId !== null && !this.#boxes.some((existing) => existing.id === parentId)) {
292
+ notCreated[key] = {
293
+ type: 'invalidProperties',
294
+ properties: ['parentId'],
295
+ description: `no mailbox ${parentId} to nest under`,
296
+ };
297
+ continue;
298
+ }
299
+ if (this.#nameCollides(parentId, box.name)) {
300
+ notCreated[key] = {
301
+ type: 'invalidProperties',
302
+ properties: ['name'],
303
+ description: `a mailbox named "${box.name}" already exists at that level`,
304
+ };
305
+ continue;
306
+ }
307
+ const id = `mb${++this.#counter}`;
308
+ this.#boxes.push({
309
+ id,
310
+ name: box.name,
311
+ parentId,
312
+ role: box.role ?? null,
313
+ sortOrder: 0,
314
+ isSubscribed: true,
315
+ shareWith: {},
316
+ });
317
+ created[key] = { id };
318
+ }
319
+ // Rename, for `renameMailbox`, and a `shareWith/<accountId>` grant
320
+ // or revoke, for `shareMailbox`/`unshareMailbox` -- the same patch
321
+ // key shape `Email/set` already handles for `mailboxIds/<id>` and
322
+ // `keywords/<name>` below, applied to one account's rights instead:
323
+ // a plain object replaces that one account's whole grant, and
324
+ // `null` deletes it, leaving every other account's grant alone.
325
+ const update = (args.update ?? {});
326
+ const updated = {};
327
+ const notUpdated = {};
328
+ for (const [id, patch] of Object.entries(update)) {
329
+ const box = this.#boxes.find((existing) => existing.id === id);
330
+ if (!box) {
331
+ notUpdated[id] = { type: 'notFound' };
332
+ continue;
333
+ }
334
+ let refused;
335
+ for (const [path, value] of Object.entries(patch)) {
336
+ if (path === 'name') {
337
+ if (typeof value !== 'string' || value.length === 0) {
338
+ refused = { type: 'invalidProperties', description: 'a mailbox needs a name' };
339
+ break;
340
+ }
341
+ if (this.#nameCollides(box.parentId, value, box.id)) {
342
+ refused = {
343
+ type: 'invalidProperties',
344
+ description: `a mailbox named "${value}" already exists at that level`,
345
+ };
346
+ break;
347
+ }
348
+ box.name = value;
349
+ }
350
+ else if (path.startsWith('shareWith/')) {
351
+ const accountId = unpointer(path.slice('shareWith/'.length));
352
+ if (value === null) {
353
+ delete box.shareWith[accountId];
354
+ }
355
+ else {
356
+ box.shareWith[accountId] = { ...value };
357
+ }
358
+ }
359
+ else {
360
+ refused = { type: 'invalidPatch', description: `cannot patch ${path}` };
361
+ break;
362
+ }
363
+ }
364
+ if (refused) {
365
+ notUpdated[id] = refused;
366
+ continue;
367
+ }
368
+ updated[id] = null;
369
+ }
370
+ // Destroy, for `deleteMailbox`. RFC 8621 §2's own refusals: a
371
+ // mailbox still holding children or mail is not silently emptied.
372
+ // The role guard that matters -- refusing to delete an Inbox, a
373
+ // Drafts, ... -- is `deleteMailbox`'s job, not this fake's; a real
374
+ // server's stance on that varies, and this only mirrors the two
375
+ // refusals RFC 8621 actually names.
376
+ const destroy = (args.destroy ?? []);
377
+ const destroyed = [];
378
+ const notDestroyed = {};
379
+ for (const id of destroy) {
380
+ const box = this.#boxes.find((existing) => existing.id === id);
381
+ if (!box) {
382
+ notDestroyed[id] = { type: 'notFound' };
383
+ continue;
384
+ }
385
+ if (this.#boxes.some((existing) => existing.parentId === id)) {
386
+ notDestroyed[id] = {
387
+ type: 'mailboxHasChild',
388
+ description: 'the mailbox still has child mailboxes',
389
+ };
390
+ continue;
391
+ }
392
+ const hasEmail = this.#emails.some((email) => email.mailboxIds[id]);
393
+ if (hasEmail) {
394
+ notDestroyed[id] = {
395
+ type: 'mailboxHasEmail',
396
+ description: 'the mailbox still has mail in it',
397
+ };
398
+ continue;
399
+ }
400
+ this.#boxes = this.#boxes.filter((existing) => existing.id !== id);
401
+ destroyed.push(id);
402
+ }
403
+ return {
404
+ accountId: ACCOUNT,
405
+ oldState: 'm1',
406
+ newState: 'm2',
407
+ created,
408
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
409
+ updated,
410
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
411
+ destroyed,
412
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
413
+ };
414
+ }
209
415
  case 'Identity/get':
210
416
  return {
211
417
  accountId: ACCOUNT,
@@ -224,6 +430,70 @@ export class FakeMailbox {
224
430
  ],
225
431
  notFound: [],
226
432
  };
433
+ case 'VacationResponse/get':
434
+ return {
435
+ accountId: ACCOUNT,
436
+ state: 'vr1',
437
+ list: [{ id: 'singleton', ...this.#vacation }],
438
+ notFound: [],
439
+ };
440
+ case 'VacationResponse/set': {
441
+ // Neither created nor destroyed: RFC 8621 §8.1 fixes the object's id
442
+ // at `singleton` from the start, so the only legal write is an
443
+ // update of that one id.
444
+ const create = (args.create ?? {});
445
+ const notCreated = {};
446
+ for (const key of Object.keys(create)) {
447
+ notCreated[key] = {
448
+ type: 'forbidden',
449
+ description: 'the vacation response is a singleton; update "singleton" instead',
450
+ };
451
+ }
452
+ const destroy = (args.destroy ?? []);
453
+ const notDestroyed = {};
454
+ for (const id of destroy) {
455
+ notDestroyed[id] = {
456
+ type: 'forbidden',
457
+ description: 'the vacation response cannot be destroyed',
458
+ };
459
+ }
460
+ const update = (args.update ?? {});
461
+ const updated = {};
462
+ const notUpdated = {};
463
+ for (const [id, patch] of Object.entries(update)) {
464
+ if (id !== 'singleton') {
465
+ notUpdated[id] = {
466
+ type: 'notFound',
467
+ description: 'the vacation response id is "singleton"',
468
+ };
469
+ continue;
470
+ }
471
+ let refused;
472
+ for (const [key, value] of Object.entries(patch)) {
473
+ if (!(key in this.#vacation)) {
474
+ refused = { type: 'invalidPatch', description: `cannot patch ${key}` };
475
+ break;
476
+ }
477
+ this.#vacation[key] = value;
478
+ }
479
+ if (refused) {
480
+ notUpdated[id] = refused;
481
+ continue;
482
+ }
483
+ updated[id] = null;
484
+ }
485
+ return {
486
+ accountId: ACCOUNT,
487
+ oldState: 'vr1',
488
+ newState: 'vr2',
489
+ created: null,
490
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
491
+ updated: Object.keys(updated).length > 0 ? updated : null,
492
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
493
+ destroyed: null,
494
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
495
+ };
496
+ }
227
497
  case 'Email/query': {
228
498
  const filter = (args.filter ?? {});
229
499
  let matching = this.#emails.filter((email) => this.#matches(email, filter));
@@ -281,8 +551,20 @@ export class FakeMailbox {
281
551
  for (const [key, draft] of Object.entries(create)) {
282
552
  const id = `e${++this.#counter}`;
283
553
  const threadId = `t${++this.#counter}`;
554
+ // `textBody`/`htmlBody`/`attachments` are always server-derived
555
+ // from `bodyStructure` (RFC 8621 §4.1.4), never echoed from what
556
+ // the client sent -- and `thread()` asks for exactly those, never
557
+ // `bodyStructure` itself. A create that used the flat
558
+ // `textBody`/`htmlBody`/`attachments` form instead (everything
559
+ // but a calendar-bearing draft) already has them, so there is
560
+ // nothing to derive.
561
+ const bodyStructure = draft.bodyStructure;
562
+ const derived = bodyStructure
563
+ ? this.#deriveBodyParts(id, bodyStructure, (draft.bodyValues ?? {}))
564
+ : {};
284
565
  this.#emails.push({
285
566
  ...draft,
567
+ ...derived,
286
568
  id,
287
569
  blobId: `blob-${id}`,
288
570
  threadId,
@@ -338,6 +620,26 @@ export class FakeMailbox {
338
620
  }
339
621
  updated[id] = null;
340
622
  }
623
+ // Destroy, for `saveDraft` replacing an earlier draft and `send`
624
+ // consuming one. Gone from its thread too, and an emptied thread is
625
+ // gone, as a server's derived threads are.
626
+ const destroy = (args.destroy ?? []);
627
+ const destroyed = [];
628
+ const notDestroyed = {};
629
+ for (const id of destroy) {
630
+ const email = this.#emails.find((one) => one.id === id);
631
+ if (!email) {
632
+ notDestroyed[id] = { type: 'notFound' };
633
+ continue;
634
+ }
635
+ this.#emails = this.#emails.filter((one) => one.id !== id);
636
+ const members = (this.#threads.get(email.threadId) ?? []).filter((one) => one !== id);
637
+ if (members.length > 0)
638
+ this.#threads.set(email.threadId, members);
639
+ else
640
+ this.#threads.delete(email.threadId);
641
+ destroyed.push(id);
642
+ }
341
643
  return {
342
644
  accountId: ACCOUNT,
343
645
  oldState: '1',
@@ -346,6 +648,8 @@ export class FakeMailbox {
346
648
  notCreated: null,
347
649
  updated,
348
650
  notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
651
+ destroyed,
652
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
349
653
  };
350
654
  }
351
655
  case 'EmailSubmission/set': {
@@ -495,6 +799,176 @@ export class FakeMailbox {
495
799
  notFound: ids.filter((id) => !this.#submissionState.has(id)),
496
800
  };
497
801
  }
802
+ case 'SieveScript/get': {
803
+ const ids = (args.ids ?? null);
804
+ const found = ids
805
+ ? this.#sieveScripts.filter((script) => ids.includes(script.id))
806
+ : this.#sieveScripts;
807
+ return {
808
+ accountId: ACCOUNT,
809
+ state: 'sieve1',
810
+ list: found.map((script) => ({
811
+ id: script.id,
812
+ name: script.name,
813
+ blobId: script.blobId,
814
+ isActive: script.id === this.#activeSieveScriptId,
815
+ })),
816
+ notFound: (ids ?? []).filter((id) => !this.#sieveScripts.some((script) => script.id === id)),
817
+ };
818
+ }
819
+ case 'SieveScript/validate': {
820
+ const blobId = args.blobId;
821
+ const text = blobId === undefined ? undefined : this.#blobContents.get(blobId);
822
+ if (text === undefined) {
823
+ return {
824
+ accountId: ACCOUNT,
825
+ error: { type: 'blobNotFound', description: 'Blob does not exist.' },
826
+ };
827
+ }
828
+ if (!this.#compilesAsSieve(text)) {
829
+ return {
830
+ accountId: ACCOUNT,
831
+ error: { type: 'invalidScript', description: 'unbalanced braces' },
832
+ };
833
+ }
834
+ return { accountId: ACCOUNT, error: null };
835
+ }
836
+ case 'SieveScript/set': {
837
+ const create = (args.create ?? {});
838
+ const created = {};
839
+ const notCreated = {};
840
+ for (const [key, item] of Object.entries(create)) {
841
+ if (!item.blobId) {
842
+ notCreated[key] = {
843
+ type: 'invalidProperties',
844
+ properties: ['blobId'],
845
+ description: 'Missing blobId.',
846
+ };
847
+ continue;
848
+ }
849
+ const text = this.#blobContents.get(item.blobId);
850
+ if (text === undefined) {
851
+ notCreated[key] = { type: 'blobNotFound', description: 'Blob does not exist.' };
852
+ continue;
853
+ }
854
+ if (!this.#compilesAsSieve(text)) {
855
+ notCreated[key] = { type: 'invalidScript', description: 'unbalanced braces' };
856
+ continue;
857
+ }
858
+ const name = item.name?.trim();
859
+ if (!name) {
860
+ notCreated[key] = {
861
+ type: 'invalidProperties',
862
+ properties: ['name'],
863
+ description: 'a sieve script needs a name',
864
+ };
865
+ continue;
866
+ }
867
+ if (this.#sieveScripts.some((script) => script.name === name)) {
868
+ notCreated[key] = {
869
+ type: 'alreadyExists',
870
+ description: `A sieve script with name '${name}' already exists.`,
871
+ };
872
+ continue;
873
+ }
874
+ const id = `sieve${++this.#counter}`;
875
+ this.#sieveScripts.push({ id, name, blobId: item.blobId });
876
+ created[key] = { id, blobId: item.blobId };
877
+ }
878
+ const update = (args.update ?? {});
879
+ const updated = {};
880
+ const notUpdated = {};
881
+ for (const [id, patch] of Object.entries(update)) {
882
+ const script = this.#sieveScripts.find((existing) => existing.id === id);
883
+ if (!script) {
884
+ notUpdated[id] = { type: 'notFound' };
885
+ continue;
886
+ }
887
+ if (patch.blobId !== undefined) {
888
+ const text = this.#blobContents.get(patch.blobId);
889
+ if (text === undefined) {
890
+ notUpdated[id] = { type: 'blobNotFound', description: 'Blob does not exist.' };
891
+ continue;
892
+ }
893
+ if (!this.#compilesAsSieve(text)) {
894
+ notUpdated[id] = { type: 'invalidScript', description: 'unbalanced braces' };
895
+ continue;
896
+ }
897
+ script.blobId = patch.blobId;
898
+ }
899
+ if (patch.name !== undefined) {
900
+ const name = patch.name.trim();
901
+ if (!name) {
902
+ notUpdated[id] = {
903
+ type: 'invalidProperties',
904
+ properties: ['name'],
905
+ description: 'a sieve script needs a name',
906
+ };
907
+ continue;
908
+ }
909
+ if (this.#sieveScripts.some((existing) => existing.id !== id && existing.name === name)) {
910
+ notUpdated[id] = {
911
+ type: 'alreadyExists',
912
+ description: `A sieve script with name '${name}' already exists.`,
913
+ };
914
+ continue;
915
+ }
916
+ script.name = name;
917
+ }
918
+ updated[id] = null;
919
+ }
920
+ // RFC 8621 §2's own refusal for a mailbox with a role, restated here
921
+ // for the one script that is active: Stalwart requires it deactivated
922
+ // first (`crates/jmap/src/sieve/set.rs:341-346`).
923
+ const destroy = (args.destroy ?? []);
924
+ const destroyed = [];
925
+ const notDestroyed = {};
926
+ for (const id of destroy) {
927
+ if (!this.#sieveScripts.some((script) => script.id === id)) {
928
+ notDestroyed[id] = { type: 'notFound' };
929
+ continue;
930
+ }
931
+ if (id === this.#activeSieveScriptId) {
932
+ notDestroyed[id] = {
933
+ type: 'scriptIsActive',
934
+ description: 'Deactivate Sieve script before deletion.',
935
+ };
936
+ continue;
937
+ }
938
+ this.#sieveScripts = this.#sieveScripts.filter((script) => script.id !== id);
939
+ destroyed.push(id);
940
+ }
941
+ // Activation/deactivation, RFC 9661's non-standard set arguments.
942
+ // Only applied when nothing above failed, mirroring Stalwart
943
+ // (`set.rs:371-376`); a bad id in `onSuccessActivateScript` is
944
+ // silently ignored here too (`set.rs:96-101`), which is exactly why
945
+ // `activateSieveScript` never sends one without a same-id `update`
946
+ // whose own `notFound` can be seen above.
947
+ const noFailures = Object.keys(notCreated).length === 0 &&
948
+ Object.keys(notUpdated).length === 0 &&
949
+ Object.keys(notDestroyed).length === 0;
950
+ if (noFailures) {
951
+ const activate = args.onSuccessActivateScript;
952
+ if (activate !== undefined &&
953
+ this.#sieveScripts.some((script) => script.id === activate)) {
954
+ this.#activeSieveScriptId = activate;
955
+ }
956
+ else if (args.onSuccessDeactivateScript === true) {
957
+ this.#activeSieveScriptId = null;
958
+ }
959
+ }
960
+ return {
961
+ accountId: ACCOUNT,
962
+ oldState: 'sieve1',
963
+ newState: 'sieve2',
964
+ created,
965
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
966
+ updated,
967
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
968
+ destroyed,
969
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
970
+ };
971
+ }
498
972
  default:
499
973
  return {
500
974
  type: 'unknownMethod',
@@ -502,6 +976,44 @@ export class FakeMailbox {
502
976
  };
503
977
  }
504
978
  }
979
+ /**
980
+ * What a real server computes from a `bodyStructure` create: `textBody`,
981
+ * `htmlBody` and `attachments`, RFC 8621 §4.1.4's derived properties.
982
+ * Handles only the shape `draftToEmail` sends for a calendar part -- one
983
+ * `multipart/alternative` with flat leaf subParts, never nested further --
984
+ * since that is the only caller that reaches for `bodyStructure` at all.
985
+ *
986
+ * Also records each leaf's bytes under its synthetic blob id, so the
987
+ * download route below can answer with what was actually sent rather than
988
+ * the fixed placeholder every other attachment gets.
989
+ */
990
+ #deriveBodyParts(id, bodyStructure, bodyValues) {
991
+ const parts = (bodyStructure.subParts ?? []).map((leaf) => {
992
+ const partId = leaf.partId ?? '';
993
+ // The bare media type: a real server strips `method=` (and every
994
+ // other parameter) from what `Email/get`'s `type` reports, the same
995
+ // way it already strips `charset` -- see the PR's citation of
996
+ // `crates/email/src/message/body.rs:77-82`.
997
+ const type = (leaf.type ?? 'text/plain').split(';')[0]?.trim().toLowerCase() || 'text/plain';
998
+ const blobId = `blob-${id}-${partId}`;
999
+ this.#blobContents.set(blobId, bodyValues[partId]?.value ?? '');
1000
+ return {
1001
+ partId,
1002
+ blobId,
1003
+ size: bodyValues[partId]?.value.length ?? 0,
1004
+ name: null,
1005
+ type,
1006
+ charset: type.startsWith('text/') ? 'UTF-8' : null,
1007
+ disposition: null,
1008
+ cid: null,
1009
+ };
1010
+ });
1011
+ const textBody = parts.filter((part) => part.type === 'text/plain');
1012
+ const htmlBody = parts.filter((part) => part.type === 'text/html');
1013
+ const inBody = new Set([...textBody, ...htmlBody].map((part) => part.partId));
1014
+ const attachments = parts.filter((part) => !inBody.has(part.partId));
1015
+ return { textBody, htmlBody, attachments, hasAttachment: attachments.length > 0 };
1016
+ }
505
1017
  /** RFC 4865's send-delay SMTP parameter, read the way Stalwart reads it:
506
1018
  * case-insensitively, since the server uppercases every `mailFrom`
507
1019
  * parameter key before matching. `undefined` means no `holdFor` was
@@ -548,6 +1060,26 @@ export class FakeMailbox {
548
1060
  return false;
549
1061
  return true;
550
1062
  }
1063
+ /** A stand-in for the real compiler `SieveScript/set` and `/validate` both
1064
+ * run server-side (`crates/jmap/src/sieve/set.rs:541`) -- not a Sieve
1065
+ * parser, just enough to make a genuine syntax error (unbalanced `{}`, or
1066
+ * nothing at all) refused deterministically, the way `#holdForSeconds`
1067
+ * above stands in for Stalwart's own delay validation without being one. */
1068
+ #compilesAsSieve(text) {
1069
+ if (text.trim().length === 0)
1070
+ return false;
1071
+ let depth = 0;
1072
+ for (const char of text) {
1073
+ if (char === '{')
1074
+ depth += 1;
1075
+ else if (char === '}') {
1076
+ depth -= 1;
1077
+ if (depth < 0)
1078
+ return false;
1079
+ }
1080
+ }
1081
+ return depth === 0;
1082
+ }
551
1083
  /** Return only what was asked for, the way a server does -- so a component
552
1084
  * reading a property the query never requested fails here as it would
553
1085
  * there. */
@@ -574,8 +1106,14 @@ export class FakeMailbox {
574
1106
  headers: { 'Content-Type': 'application/json' },
575
1107
  });
576
1108
  if (!init || (init.method ?? 'GET') === 'GET') {
577
- if (url.includes('/jmap/download/'))
578
- return new Response('fake attachment bytes');
1109
+ if (url.includes('/jmap/download/')) {
1110
+ // `{accountId}/{blobId}/{name}` -- only a blob this fake actually
1111
+ // stored content for (an upload, never an attachment's synthetic
1112
+ // blobId from `add()`) reads back as anything but the fixed stub.
1113
+ const blobId = url.split('/jmap/download/')[1]?.split('/')[1];
1114
+ const stored = blobId ? this.#blobContents.get(decodeURIComponent(blobId)) : undefined;
1115
+ return new Response(stored ?? 'fake attachment bytes');
1116
+ }
579
1117
  if (url.includes('/eventsource')) {
580
1118
  // An open stream that never sends: `push` stays connected and quiet.
581
1119
  return new Response(new ReadableStream(), {
@@ -602,6 +1140,7 @@ export class FakeMailbox {
602
1140
  const type = new Headers(init.headers).get('Content-Type') ?? 'application/octet-stream';
603
1141
  const blob = { blobId: `upload-${this.uploads.length + 1}`, type, size };
604
1142
  this.uploads.push(blob);
1143
+ this.#blobContents.set(blob.blobId, await bodyText(init.body));
605
1144
  return json({ accountId: ACCOUNT, ...blob });
606
1145
  }
607
1146
  const body = JSON.parse(String(init.body));
@@ -644,6 +1183,27 @@ async function measure(body) {
644
1183
  return body.byteLength;
645
1184
  return (await new Response(body).arrayBuffer()).byteLength;
646
1185
  }
1186
+ /** An upload body's bytes, as text -- what `SieveScript/set` and
1187
+ * `/validate` need back to answer honestly, unlike an attachment whose
1188
+ * content nothing here ever reads again. Mirrors `measure`'s type handling
1189
+ * above so a `Blob` is read by its own `.text()` rather than by `instanceof`
1190
+ * (a page can hold more than one realm's `Blob`), and neither call consumes
1191
+ * the other's read: everything `client.upload` actually sends -- a string,
1192
+ * an `ArrayBuffer`/typed array, or a `Blob` -- supports being read twice. */
1193
+ async function bodyText(body) {
1194
+ if (body === null || body === undefined)
1195
+ return '';
1196
+ if (typeof body === 'string')
1197
+ return body;
1198
+ if (body instanceof ArrayBuffer)
1199
+ return new TextDecoder().decode(body);
1200
+ if (ArrayBuffer.isView(body))
1201
+ return new TextDecoder().decode(body);
1202
+ if (typeof body === 'object' && 'text' in body && typeof body.text === 'function') {
1203
+ return body.text();
1204
+ }
1205
+ return new Response(body).text();
1206
+ }
647
1207
  /** RFC 6901 §3 in reverse: one patch-key segment, unescaped. A mailbox id is
648
1208
  * the server's to choose, so a key built from one may carry `~0` or `~1`. */
649
1209
  function unpointer(segment) {