@wtfalch/email 0.10.0 → 0.12.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.
package/README.md CHANGED
@@ -47,7 +47,10 @@ by JMAP result reference in a single request.
47
47
  compute the recipients, the subject prefix, the `In-Reply-To` and `References`
48
48
  chain and the quoted body, with no client and no network, so a composer can
49
49
  call them on every keystroke. `send` creates the draft, submits it, and files
50
- it in Sent. `attach` uploads a file and gives back what a draft carries; the
50
+ it in Sent; a `delay` in seconds holds it there first, and `cancel` unsends
51
+ it while `undoStatus` is still `'pending'` — the only honest sign the window
52
+ is still open, since a server not set up for held delivery answers `'final'`
53
+ regardless. `attach` uploads a file and gives back what a draft carries; the
51
54
  upload is refused before any of it is sent when the file is over the
52
55
  session's `maxSizeUpload`, which `client.session()` reports alongside
53
56
  `maxSizeAttachmentsPerEmail`.
@@ -62,6 +62,11 @@ export declare class FakeMailbox {
62
62
  size: number;
63
63
  }[];
64
64
  constructor(options?: FakeOptions);
65
+ /** Move the fake's clock forward by `ms` milliseconds. The only way `#now`
66
+ * changes after construction, so a test can hold a submission, advance
67
+ * past its `sendAt`, and see the cancel window close -- deterministically,
68
+ * with no real wait and no wall-clock read. */
69
+ advance(ms: number): void;
65
70
  /** Put a thread in the mailbox. Returns its id. */
66
71
  add(seed: SeedThread): string;
67
72
  /** The session document, as Stalwart writes it. */
@@ -27,6 +27,9 @@ const MAILBOXES = [
27
27
  const STALWART_MAX_SIZE = 50_000_000;
28
28
  export class FakeMailbox {
29
29
  me;
30
+ /** The fake's clock. Fixed at construction and moved only by `advance()`
31
+ * -- never a wall-clock read, so a cancel-window test stays
32
+ * deterministic. */
30
33
  #now;
31
34
  #latency;
32
35
  #maxSizeUpload;
@@ -36,6 +39,10 @@ export class FakeMailbox {
36
39
  /** Everything `EmailSubmission/set` accepted, for a test that asserts a
37
40
  * message was actually sent rather than only composed. */
38
41
  submissions = [];
42
+ /** Each submission's send-hold state, keyed by its id -- what the update
43
+ * (cancel) path needs to know that the flat `submissions` list above,
44
+ * kept only for the tests above, does not carry. */
45
+ #submissionState = new Map();
39
46
  /** Every blob uploaded, for a test that asserts the bytes reached the
40
47
  * server rather than only the composer. */
41
48
  uploads = [];
@@ -47,6 +54,13 @@ export class FakeMailbox {
47
54
  for (const seed of options.threads ?? [])
48
55
  this.add(seed);
49
56
  }
57
+ /** Move the fake's clock forward by `ms` milliseconds. The only way `#now`
58
+ * changes after construction, so a test can hold a submission, advance
59
+ * past its `sendAt`, and see the cancel window close -- deterministically,
60
+ * with no real wait and no wall-clock read. */
61
+ advance(ms) {
62
+ this.#now = new Date(this.#now.getTime() + ms);
63
+ }
50
64
  /** Put a thread in the mailbox. Returns its id. */
51
65
  add(seed) {
52
66
  const threadId = `t${++this.#counter}`;
@@ -329,17 +343,98 @@ export class FakeMailbox {
329
343
  case 'EmailSubmission/set': {
330
344
  const create = (args.create ?? {});
331
345
  const created = {};
346
+ const notCreated = {};
332
347
  for (const [key, submission] of Object.entries(create)) {
333
- this.submissions.push(submission);
334
- created[key] = { id: `sub-${this.submissions.length}`, undoStatus: 'final' };
335
- // The move to Sent that `onSuccessUpdateEmail` asks for.
348
+ // RFC 4865's send-delay parameter rides in the envelope, not a
349
+ // `sendAt` property, and Stalwart validates it as 1..=999999999.
350
+ const holdFor = this.#holdForSeconds(submission.envelope);
351
+ if (holdFor === 'invalid') {
352
+ notCreated[key] = {
353
+ type: 'invalidProperties',
354
+ properties: ['envelope'],
355
+ description: 'Failed to parse mailFrom parameters: HOLDFOR.',
356
+ };
357
+ continue;
358
+ }
359
+ this.submissions.push({ emailId: submission.emailId, identityId: submission.identityId });
360
+ const id = `sub-${this.submissions.length}`;
361
+ const sendAt = new Date(this.#now.getTime() + (holdFor ?? 0) * 1000);
362
+ const undoStatus = holdFor ? 'pending' : 'final';
363
+ this.#submissionState.set(id, { emailId: submission.emailId, sendAt, undoStatus });
364
+ created[key] = { id, sendAt: sendAt.toISOString(), undoStatus };
365
+ // The move to Sent that `onSuccessUpdateEmail` asks for. It runs
366
+ // immediately even on a held message: holding delays delivery,
367
+ // not filing.
336
368
  const email = this.#emails.find((one) => one.id === submission.emailId);
337
369
  if (email) {
338
370
  email.mailboxIds = { 'mb-sent': true };
339
371
  email.keywords = { $seen: true };
340
372
  }
341
373
  }
342
- return { accountId: ACCOUNT, oldState: '2', newState: '3', created, notCreated: null };
374
+ // `undoStatus: 'canceled'` is the only update this server accepts,
375
+ // and it is the unsend: valid only while the submission is still
376
+ // `pending` and its `sendAt` has not arrived. Destroy is handled
377
+ // separately below, and is not a cancel.
378
+ const update = (args.update ?? {});
379
+ const updated = {};
380
+ const notUpdated = {};
381
+ for (const [id, patch] of Object.entries(update)) {
382
+ if (patch.undoStatus !== 'canceled') {
383
+ notUpdated[id] = {
384
+ type: 'invalidProperties',
385
+ properties: ['undoStatus'],
386
+ description: 'Email submissions can only be cancelled.',
387
+ };
388
+ continue;
389
+ }
390
+ const record = this.#submissionState.get(id);
391
+ if (!record ||
392
+ record.undoStatus !== 'pending' ||
393
+ record.sendAt.getTime() <= this.#now.getTime()) {
394
+ notUpdated[id] = {
395
+ type: 'cannotUnsend',
396
+ description: 'The requested message is no longer in the queue.',
397
+ };
398
+ continue;
399
+ }
400
+ record.undoStatus = 'canceled';
401
+ updated[id] = null;
402
+ // The move back to Drafts that `onSuccessUpdateEmail` asks for on
403
+ // an unsend, the mirror of the create path's move to Sent above.
404
+ const email = this.#emails.find((one) => one.id === record.emailId);
405
+ if (email) {
406
+ email.mailboxIds = { 'mb-drafts': true };
407
+ email.keywords = { $draft: true, $seen: true };
408
+ }
409
+ }
410
+ // Destroy is not a cancel: Stalwart forgets the submission record
411
+ // but still sends the mail, so this only drops it from
412
+ // `#submissionState`. It must not touch a submission's status or
413
+ // move its email, or a destroy would silently double as an unsend --
414
+ // the asymmetry that makes destroy a trap rather than a shortcut.
415
+ const destroy = (args.destroy ?? []);
416
+ const destroyed = [];
417
+ const notDestroyed = {};
418
+ for (const id of destroy) {
419
+ if (this.#submissionState.has(id)) {
420
+ this.#submissionState.delete(id);
421
+ destroyed.push(id);
422
+ }
423
+ else {
424
+ notDestroyed[id] = { type: 'notFound' };
425
+ }
426
+ }
427
+ return {
428
+ accountId: ACCOUNT,
429
+ oldState: '2',
430
+ newState: '3',
431
+ created,
432
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
433
+ updated: Object.keys(updated).length > 0 ? updated : null,
434
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
435
+ destroyed: destroyed.length > 0 ? destroyed : null,
436
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
437
+ };
343
438
  }
344
439
  default:
345
440
  return {
@@ -348,6 +443,23 @@ export class FakeMailbox {
348
443
  };
349
444
  }
350
445
  }
446
+ /** RFC 4865's send-delay SMTP parameter, read the way Stalwart reads it:
447
+ * case-insensitively, since the server uppercases every `mailFrom`
448
+ * parameter key before matching. `undefined` means no `holdFor` was
449
+ * sent; `'invalid'` means one was sent but failed the 1..=999999999
450
+ * range. `holdUntil` is not supported yet, so it is ignored. */
451
+ #holdForSeconds(envelope) {
452
+ const parameters = envelope?.mailFrom?.parameters;
453
+ if (!parameters)
454
+ return undefined;
455
+ const key = Object.keys(parameters).find((name) => name.toUpperCase() === 'HOLDFOR');
456
+ if (key === undefined)
457
+ return undefined;
458
+ const seconds = Number(parameters[key]);
459
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 999_999_999)
460
+ return 'invalid';
461
+ return seconds;
462
+ }
351
463
  #matches(email, filter) {
352
464
  const mailboxIds = email.mailboxIds;
353
465
  if (typeof filter.inMailbox === 'string' && !mailboxIds[filter.inMailbox])
@@ -19,8 +19,8 @@ export type { SearchOptions } from './search.ts';
19
19
  export { identities } from './identities.ts';
20
20
  export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardSubject, quoteText, replyDraft, replySubject, } from './drafts.ts';
21
21
  export type { ForwardOptions, ReplyOptions } from './drafts.ts';
22
- export { draftToEmail, send, sentPatch } from './submit.ts';
23
- export type { SendOptions } from './submit.ts';
22
+ export { cancel, draftPatch, draftToEmail, send, sentPatch } from './submit.ts';
23
+ export type { CancelOptions, SendOptions } from './submit.ts';
24
24
  export { attach } from './attach.ts';
25
25
  export { moveThread, moveToRole, removeFromMailbox, setFlagged, setRead, } from './mutate.ts';
26
26
  export type { MoveOptions } from './mutate.ts';
@@ -12,7 +12,7 @@ export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from "./thread.js";
12
12
  export { search } from "./search.js";
13
13
  export { identities } from "./identities.js";
14
14
  export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardSubject, quoteText, replyDraft, replySubject, } from "./drafts.js";
15
- export { draftToEmail, send, sentPatch } from "./submit.js";
15
+ export { cancel, draftPatch, draftToEmail, send, sentPatch } from "./submit.js";
16
16
  export { attach } from "./attach.js";
17
17
  export { moveThread, moveToRole, removeFromMailbox, setFlagged, setRead, } from "./mutate.js";
18
18
  export { DEFAULT_MAX_DOWNLOAD_BYTES, downloadAttachment } from "./download.js";
@@ -150,6 +150,25 @@
150
150
  white-space: nowrap;
151
151
  }
152
152
 
153
+ /* Said when the push stream is not connected. Quiet on purpose: nothing is
154
+ broken for the reader, and a list that has stopped growing is the only
155
+ symptom, so this is the one thing on screen that explains it. It borrows
156
+ the warning colour rather than the danger one -- mail is still arriving,
157
+ it is just not being announced. */
158
+ .mail-offline {
159
+ display: flex;
160
+ align-items: center;
161
+ gap: var(--space-1);
162
+ color: var(--warn);
163
+ font-size: var(--text-sm);
164
+ white-space: nowrap;
165
+ min-width: 0;
166
+ }
167
+
168
+ .mail-offline-word {
169
+ white-space: nowrap;
170
+ }
171
+
153
172
  .mail-panes {
154
173
  display: flex;
155
174
  flex: 1 1 auto;
@@ -1124,6 +1143,14 @@
1124
1143
  display: none;
1125
1144
  }
1126
1145
 
1146
+ /* The same bargain the compose word makes: at narrow widths the glyph carries
1147
+ it, and the wording survives in the tooltip and in the refresh button's
1148
+ accessible name. */
1149
+ .mail.is-narrow .mail-offline-word,
1150
+ .mail.is-medium .mail-offline-word {
1151
+ display: none;
1152
+ }
1153
+
1127
1154
  .mail.is-narrow .mail-compose-word {
1128
1155
  /* The pen alone. The button keeps its name from the `aria-label` the icon
1129
1156
  is given, so this is a visual change and not a semantic one. */
@@ -45,6 +45,13 @@ import { saveBlob } from "./save.js";
45
45
  * focus, or `c` could never be typed into a subject.
46
46
  */
47
47
  const PAGE = 50;
48
+ /** Said in the control's label and in the marker's tooltip, so the two cannot
49
+ * drift apart and describe the same state differently. */
50
+ const OFFLINE_TITLE = 'Not receiving new mail automatically. Refresh to check.';
51
+ /** How long the stream may be down before the reader is told. Long enough that
52
+ * a reconnect nobody needed to know about stays invisible, short enough that
53
+ * a reader who is about to wonder why nothing is arriving is told first. */
54
+ const OFFLINE_GRACE_MS = 10_000;
48
55
  /** A logo or a signature is kilobytes; five megabytes is a photograph, and
49
56
  * past that it is an attachment wearing a `cid:`. */
50
57
  const INLINE_MAX_BYTES = 5 * 1024 * 1024;
@@ -135,7 +142,27 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
135
142
  boxes.reload();
136
143
  threads.reload();
137
144
  }, [boxes.reload, threads.reload]);
138
- usePush(refresh, client);
145
+ /* `usePush` reconnects on its own, with backoff, and resends `Last-Event-ID`
146
+ so nothing is missed across a drop. What it cannot do is get through a
147
+ proxy that buffers a long-lived response -- and a reader whose stream is
148
+ dead sees a list that simply stops growing, which reads as "no new mail"
149
+ rather than "not listening". So the state is drawn, and a refresh is
150
+ always within reach. */
151
+ const { connected } = usePush(refresh, client);
152
+ /* `connected` is false for the moment before the stream comes up, so drawing
153
+ the marker straight from it would flash a warning on every load. It is
154
+ also false forever when a proxy swallows the stream entirely, which is the
155
+ case that started all this -- so a grace period rather than "has it ever
156
+ connected", which would stay silent in exactly that case. */
157
+ const [live, setLive] = useState(true);
158
+ useEffect(() => {
159
+ if (connected) {
160
+ setLive(true);
161
+ return;
162
+ }
163
+ const timer = setTimeout(() => setLive(false), OFFLINE_GRACE_MS);
164
+ return () => clearTimeout(timer);
165
+ }, [connected]);
139
166
  /* Errors reach the application, but only when they change: these hooks hold
140
167
  their last error while a retry is in flight, so forwarding on every
141
168
  render would call `onError` sixty times for one dead token. */
@@ -398,6 +425,10 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
398
425
  startForward(newest);
399
426
  break;
400
427
  }
428
+ case '.':
429
+ event.preventDefault();
430
+ refresh();
431
+ break;
401
432
  case 'Escape':
402
433
  if (threadId && panes === 'narrow')
403
434
  setThreadId(null);
@@ -423,6 +454,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
423
454
  setThreadId,
424
455
  archiveBox,
425
456
  trashBox,
457
+ refresh,
426
458
  ]);
427
459
  const paletteGroups = useMemo(() => [
428
460
  {
@@ -447,7 +479,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
447
479
  ...(threadId
448
480
  ? [{ id: 'unread', label: 'Mark unread', shortcut: 'U', onRun: markUnread }]
449
481
  : []),
450
- { id: 'refresh', label: 'Refresh', shortcut: 'R', onRun: refresh },
482
+ { id: 'refresh', label: 'Refresh', shortcut: '.', onRun: refresh },
451
483
  {
452
484
  id: 'help',
453
485
  label: 'Keyboard shortcuts',
@@ -483,7 +515,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
483
515
  }, "aria-label": "Clear the search", children: _jsx(Icon, { name: "close", size: 13 }) })) : (_jsx("span", { className: "mail-search-key", "aria-hidden": "true", children: "/" }))] }));
484
516
  const list = (_jsx(ThreadList, { page: threads.data, selectedId: threadId, onSelect: openThread, onPage: (threads.data?.total ?? 0) > PAGE ? setPosition : undefined, limit: PAGE, loading: threads.loading, now: now, title: query ? `Results for “${query}”` : current?.name, empty: query ? _jsxs("p", { className: "threads-quiet", children: ["Nothing matches \u201C", query, "\u201D."] }) : undefined }));
485
517
  const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, fetchInline: fetchInline, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined }));
486
- return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [_jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
518
+ return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [!live && (_jsxs("span", { className: "mail-offline", title: OFFLINE_TITLE, children: [_jsx(Icon, { name: "wifi-off", size: 15 }), _jsx("span", { className: "mail-offline-word", children: "Not live" })] })), _jsx(Button, { kind: "ghost", iconOnly: true, onClick: refresh, "aria-label": live ? 'Refresh' : OFFLINE_TITLE, children: _jsx(Icon, { name: "refresh", size: 15 }) }), _jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
487
519
  }
488
520
  /**
489
521
  * What just happened, said once and then gone.
@@ -524,6 +556,7 @@ function Shortcuts() {
524
556
  ['#', 'Delete'],
525
557
  ['U', 'Mark unread'],
526
558
  ['S', 'Flag'],
559
+ ['.', 'Refresh'],
527
560
  ['?', 'This list'],
528
561
  ];
529
562
  return (_jsx("dl", { className: "keys", children: rows.map(([key, what]) => (_jsxs("div", { className: "keys-row", children: [_jsx("dt", { children: _jsx("kbd", { children: key }) }), _jsx("dd", { children: what })] }, key))) }));
@@ -12,12 +12,19 @@
12
12
  * - `wide` — mailboxes, list and message side by side. Selecting a
13
13
  * conversation reveals it; there is nothing to navigate to.
14
14
  * - `medium` — the mailboxes collapse to a rail of icons, and the list and
15
- * the message share what is left. Below about 1150px a 3-column layout puts
16
- * the reading measure under 45 characters, which is where prose stops being
17
- * readable, and the mailbox names are the least valuable of the three.
15
+ * the message share what is left. Below `@wtfalch/design`'s `wide` breakpoint
16
+ * (1150px) a 3-column layout puts the reading measure under 45 characters,
17
+ * which is where prose stops being readable, and the mailbox names are the
18
+ * least valuable of the three.
18
19
  * - `narrow` — one at a time, with the mailboxes in a drawer. Measured at
19
- * 860px, where the list's two-line row can no longer hold a sender, a time
20
- * and a subject without the subject truncating to nothing.
20
+ * `@wtfalch/design`'s `medium` breakpoint (860px), where the list's
21
+ * two-line row can no longer hold a sender, a time and a subject without
22
+ * the subject truncating to nothing.
23
+ *
24
+ * The widths themselves live in `@wtfalch/design`'s `MEDIA_QUERIES` (and
25
+ * `BREAKPOINTS`), not here: one source, shared with the stylesheet-facing
26
+ * side of the design system, rather than a second copy that can drift from
27
+ * it.
21
28
  */
22
29
  export type Panes = 'wide' | 'medium' | 'narrow';
23
30
  /**
@@ -1,15 +1,14 @@
1
+ import { MEDIA_QUERIES } from '@wtfalch/design';
1
2
  import { useEffect, useState } from 'react';
2
- const WIDE = '(min-width: 1150px)';
3
- const MEDIUM = '(min-width: 860px)';
4
3
  function read() {
5
4
  /* Server rendering, and jsdom without the shim, both land here. `wide` is
6
5
  the right default for both: it is the layout with no hidden state, so a
7
6
  render that never gets a second chance still shows everything. */
8
7
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
9
8
  return 'wide';
10
- if (window.matchMedia(WIDE).matches)
9
+ if (window.matchMedia(MEDIA_QUERIES.wide).matches)
11
10
  return 'wide';
12
- if (window.matchMedia(MEDIUM).matches)
11
+ if (window.matchMedia(MEDIA_QUERIES.medium).matches)
13
12
  return 'medium';
14
13
  return 'narrow';
15
14
  }
@@ -26,7 +25,10 @@ export function usePanes() {
26
25
  useEffect(() => {
27
26
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
28
27
  return;
29
- const queries = [window.matchMedia(WIDE), window.matchMedia(MEDIUM)];
28
+ const queries = [
29
+ window.matchMedia(MEDIA_QUERIES.wide),
30
+ window.matchMedia(MEDIA_QUERIES.medium),
31
+ ];
30
32
  const update = () => setPanes(read());
31
33
  for (const query of queries)
32
34
  query.addEventListener('change', update);
@@ -10,6 +10,13 @@ export declare function sentPatch(draftsMailboxId: string, sentMailboxId: string
10
10
  'keywords/$draft': null;
11
11
  'keywords/$seen': boolean;
12
12
  };
13
+ /** The patch that unsends a message: out of Sent, into Drafts, a draft
14
+ * again -- the exact reverse of `sentPatch`. */
15
+ export declare function draftPatch(sentMailboxId: string, draftsMailboxId: string): {
16
+ [x: string]: boolean | null;
17
+ 'keywords/$draft': boolean;
18
+ 'keywords/$seen': null;
19
+ };
13
20
  export type SendOptions = {
14
21
  /** The identity to send as, when the caller already has it. Saves an
15
22
  * `Identity/get`. */
@@ -17,6 +24,16 @@ export type SendOptions = {
17
24
  /** The mailbox tree, when the caller already has it. Saves a
18
25
  * `Mailbox/get`. */
19
26
  mailboxes?: readonly MailboxNode[];
27
+ /** Whole seconds to hold the message before it goes out, giving the
28
+ * sender a window to `cancel()` it. `0` or omitted sends immediately,
29
+ * byte-identical to a plain send. Travels as RFC 4865's `holdFor` SMTP
30
+ * parameter, which the server validates as 1..=999999999. */
31
+ delay?: number;
32
+ };
33
+ export type CancelOptions = {
34
+ /** The mailbox tree, when the caller already has it. Saves a
35
+ * `Mailbox/get`. */
36
+ mailboxes?: readonly MailboxNode[];
20
37
  };
21
38
  /**
22
39
  * Send a draft.
@@ -33,3 +50,15 @@ export type SendOptions = {
33
50
  * submission leaves the message in Drafts rather than losing it.
34
51
  */
35
52
  export declare function send(client: MailClient, draft: Draft, options?: SendOptions): Promise<Sent>;
53
+ /**
54
+ * Unsend a message inside its hold window.
55
+ *
56
+ * `undoStatus: 'canceled'` is an update, not a destroy: `EmailSubmission/
57
+ * destroy` deletes the submission record but still sends the mail, so it is
58
+ * never used here. This is the same single-call path `send()` uses, and for
59
+ * the same reason -- RFC 8621 §7.5's `onSuccessUpdateEmail` runs an implicit
60
+ * `Email/set` and returns it under the update's own method call id, which a
61
+ * multi-call reader that maps responses by id would lose. See the docblock
62
+ * above `send()`.
63
+ */
64
+ export declare function cancel(client: MailClient, sent: Sent, options?: CancelOptions): Promise<void>;
@@ -14,6 +14,50 @@ function failed(operation, notCreated) {
14
14
  operation,
15
15
  });
16
16
  }
17
+ /** A `notUpdated` entry of type `cannotUnsend` means the window closed
18
+ * before the request arrived; everything else keeps the server's own type
19
+ * and description, the way `failed()` does for a create. */
20
+ function unsendFailed(notUpdated) {
21
+ const first = notUpdated ? Object.values(notUpdated)[0] : undefined;
22
+ if (first?.type === 'cannotUnsend') {
23
+ throw new MailError('the message has already gone; it can no longer be unsent', {
24
+ type: 'cannotUnsend',
25
+ operation: 'cancel',
26
+ });
27
+ }
28
+ throw new MailError(first?.description ?? 'the server refused to cancel the submission', {
29
+ type: first?.type ?? 'unknown',
30
+ operation: 'cancel',
31
+ });
32
+ }
33
+ /** RFC 4865's send-delay SMTP parameter travels as a string of seconds and
34
+ * Stalwart validates it as 1..=999999999 -- `holdFor: "0"` is refused
35
+ * outright, which is why a delay of zero omits the parameter entirely
36
+ * rather than sending a zero. Checked here so a bad `delay` fails with a
37
+ * clear message before anything goes to the wire, not as an opaque server
38
+ * refusal. */
39
+ function checkDelay(delay) {
40
+ if (delay === undefined)
41
+ return;
42
+ if (!Number.isInteger(delay) || delay < 0 || delay > 999_999_999) {
43
+ throw new MailError(`delay must be a whole number of seconds from 0 to 999999999, got ${delay}`, { type: 'invalidProperties', operation: 'send' });
44
+ }
45
+ }
46
+ /** `to`, `cc` and `bcc` combined for the envelope's `rcptTo`, deduplicated.
47
+ * Without an envelope the server derives recipients from the headers, but
48
+ * it strips the Bcc header before delivery, so a delayed send has to list
49
+ * every recipient explicitly here or the blind ones are silently dropped. */
50
+ function uniqueAddresses(addresses) {
51
+ const seen = new Set();
52
+ const result = [];
53
+ for (const address of addresses) {
54
+ if (seen.has(address.email))
55
+ continue;
56
+ seen.add(address.email);
57
+ result.push({ email: address.email });
58
+ }
59
+ return result;
60
+ }
17
61
  /** The JMAP `Email` object a draft becomes. Exported so the shape can be
18
62
  * asserted without a server. */
19
63
  export function draftToEmail(draft, from, draftsMailboxId) {
@@ -71,6 +115,16 @@ export function sentPatch(draftsMailboxId, sentMailboxId) {
71
115
  'keywords/$seen': true,
72
116
  };
73
117
  }
118
+ /** The patch that unsends a message: out of Sent, into Drafts, a draft
119
+ * again -- the exact reverse of `sentPatch`. */
120
+ export function draftPatch(sentMailboxId, draftsMailboxId) {
121
+ return {
122
+ [`mailboxIds/${pointer(sentMailboxId)}`]: null,
123
+ [`mailboxIds/${pointer(draftsMailboxId)}`]: true,
124
+ 'keywords/$draft': true,
125
+ 'keywords/$seen': null,
126
+ };
127
+ }
74
128
  /**
75
129
  * Send a draft.
76
130
  *
@@ -86,6 +140,7 @@ export function sentPatch(draftsMailboxId, sentMailboxId) {
86
140
  * submission leaves the message in Drafts rather than losing it.
87
141
  */
88
142
  export async function send(client, draft, options = {}) {
143
+ checkDelay(options.delay);
89
144
  const { jam, accountId } = await client.connect();
90
145
  const tree = options.mailboxes ?? (await mailboxes(client));
91
146
  const drafts = findRole(tree, 'drafts');
@@ -103,19 +158,35 @@ export async function send(client, draft, options = {}) {
103
158
  });
104
159
  }
105
160
  let from = draft.from;
106
- if (!from || from.length === 0) {
107
- const identity = options.identity ?? (await identities(client)).find((one) => one.id === draft.identityId);
161
+ let identity;
162
+ // A delay needs the identity's own address for the envelope's `mailFrom`
163
+ // even when `from` was already supplied, so it is resolved whenever
164
+ // either is missing.
165
+ if (!from || from.length === 0 || options.delay) {
166
+ identity =
167
+ options.identity ?? (await identities(client)).find((one) => one.id === draft.identityId);
108
168
  if (!identity) {
109
169
  throw new MailError(`no identity ${draft.identityId} on this account`, {
110
170
  type: 'notFound',
111
171
  operation: 'send',
112
172
  });
113
173
  }
114
- // RFC 8621 §7.1: a server may refuse a submission whose From header does
115
- // not match the identity, so the header is filled from the identity
116
- // rather than left to the server to guess.
117
- from = [{ name: identity.name, email: identity.email }];
174
+ if (!from || from.length === 0) {
175
+ // RFC 8621 §7.1: a server may refuse a submission whose From header
176
+ // does not match the identity, so the header is filled from the
177
+ // identity rather than left to the server to guess.
178
+ from = [{ name: identity.name, email: identity.email }];
179
+ }
118
180
  }
181
+ // Without a delay, no envelope is built at all: the server derives
182
+ // recipients from the headers, and this stays byte-identical to a plain
183
+ // send, which is the path in production today.
184
+ const envelope = options.delay && identity
185
+ ? {
186
+ mailFrom: { email: identity.email, parameters: { holdFor: String(options.delay) } },
187
+ rcptTo: uniqueAddresses([...draft.to, ...(draft.cc ?? []), ...(draft.bcc ?? [])]),
188
+ }
189
+ : undefined;
119
190
  return guard('send', async () => {
120
191
  const [created] = await jam.api.Email.set({
121
192
  accountId,
@@ -130,6 +201,7 @@ export async function send(client, draft, options = {}) {
130
201
  submission: {
131
202
  identityId: draft.identityId,
132
203
  emailId: email.id,
204
+ ...(envelope ? { envelope } : {}),
133
205
  },
134
206
  },
135
207
  onSuccessUpdateEmail: { '#submission': sentPatch(drafts.id, sent.id) },
@@ -146,6 +218,52 @@ export async function send(client, draft, options = {}) {
146
218
  submissionId: submission.id,
147
219
  emailId: email.id,
148
220
  threadId: email.threadId,
221
+ undoStatus: submission.undoStatus,
222
+ sendAt: submission.sendAt,
149
223
  };
150
224
  });
151
225
  }
226
+ /**
227
+ * Unsend a message inside its hold window.
228
+ *
229
+ * `undoStatus: 'canceled'` is an update, not a destroy: `EmailSubmission/
230
+ * destroy` deletes the submission record but still sends the mail, so it is
231
+ * never used here. This is the same single-call path `send()` uses, and for
232
+ * the same reason -- RFC 8621 §7.5's `onSuccessUpdateEmail` runs an implicit
233
+ * `Email/set` and returns it under the update's own method call id, which a
234
+ * multi-call reader that maps responses by id would lose. See the docblock
235
+ * above `send()`.
236
+ */
237
+ export async function cancel(client, sent, options = {}) {
238
+ const { jam, accountId } = await client.connect();
239
+ const tree = options.mailboxes ?? (await mailboxes(client));
240
+ const sentBox = findRole(tree, 'sent');
241
+ const drafts = findRole(tree, 'drafts');
242
+ if (!sentBox) {
243
+ throw new MailError('the account has no Sent mailbox the message is filed in', {
244
+ type: 'notFound',
245
+ operation: 'cancel',
246
+ });
247
+ }
248
+ if (!drafts) {
249
+ throw new MailError('the account has no Drafts mailbox to move the message back to', {
250
+ type: 'notFound',
251
+ operation: 'cancel',
252
+ });
253
+ }
254
+ return guard('cancel', async () => {
255
+ const [result] = await jam.api.EmailSubmission.set({
256
+ accountId,
257
+ update: { [sent.submissionId]: { undoStatus: 'canceled' } },
258
+ onSuccessUpdateEmail: { [sent.submissionId]: draftPatch(sentBox.id, drafts.id) },
259
+ },
260
+ // Same reason as `send()`: `onSuccessUpdateEmail` runs an Email/set,
261
+ // so the request needs the mail capability declared alongside
262
+ // submission.
263
+ { using: ['urn:ietf:params:jmap:mail'], ...JAM_FETCH });
264
+ const updated = result.updated;
265
+ if (updated && sent.submissionId in updated)
266
+ return;
267
+ unsendFailed(result.notUpdated);
268
+ });
269
+ }
@@ -201,6 +201,15 @@ export type Sent = {
201
201
  /** The id the message has once it is in Sent. */
202
202
  emailId: string;
203
203
  threadId: string;
204
+ /** Whether the message can still be `cancel()`ed. `'pending'` is the ONLY
205
+ * honest signal that a regret window exists: a server not configured for
206
+ * held delivery accepts the submission, ignores the hold, and answers
207
+ * `'final'` anyway, with no error anywhere. `'canceled'` is what `send`
208
+ * never returns -- it only ever comes back from a successful `cancel()`. */
209
+ undoStatus: 'pending' | 'final' | 'canceled';
210
+ /** The ISO 8601 UTC instant the server will (or did) release the message
211
+ * for delivery. */
212
+ sendAt: string;
204
213
  };
205
214
  /** The per-type state strings a push event carries. A value that differs
206
215
  * from the one a previous call returned means that type changed. */
@@ -49,7 +49,7 @@ export declare const API_KEY_PREFIX = "API_";
49
49
  * are Stalwart's management vocabulary (`enums.Permission`), which is why the
50
50
  * earlier guessed names all failed.
51
51
  */
52
- export declare const DASHBOARD_PERMISSIONS: readonly ["authenticate", "sysAccountQuery", "sysAccountGet", "sysAccountCreate", "sysAccountUpdate", "sysDomainQuery", "sysDomainGet", "sysSystemSettingsGet"];
52
+ export declare const DASHBOARD_PERMISSIONS: readonly ["authenticate", "sysAccountQuery", "sysAccountGet", "sysAccountCreate", "sysAccountUpdate", "sysDomainQuery", "sysDomainGet", "sysSystemSettingsGet", "sysMtaExtensionsGet"];
53
53
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
54
54
  export declare function authFor(secret: string, user?: string): StalwartAuth;
55
55
  export declare class StalwartError extends Error {
@@ -48,6 +48,15 @@ export const DASHBOARD_PERMISSIONS = [
48
48
  'sysDomainQuery',
49
49
  'sysDomainGet',
50
50
  'sysSystemSettingsGet',
51
+ // Read-only, and the one permission here that is not about the `/email`
52
+ // pages: `MtaExtensions` holds `futureRelease`, the setting that decides
53
+ // whether a held message is really held. Without it a held send cannot even
54
+ // be confirmed — the key is `forbidden` on `x:MtaExtensions/get`, and a
55
+ // server that has the setting off accepts the submission, drops the hold and
56
+ // reports success. The matching `sysMtaExtensionsUpdate` is deliberately not
57
+ // here: provisioning writes that object with an administrative credential,
58
+ // so the dashboard never needs to rewrite the MTA's extension config.
59
+ 'sysMtaExtensionsGet',
51
60
  ];
52
61
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
53
62
  export function authFor(secret, user) {
@@ -111,6 +111,19 @@ export function mailObjects(i) {
111
111
  },
112
112
  ]
113
113
  : []),
114
+ {
115
+ key: 'extensions',
116
+ object: 'MtaExtensions',
117
+ match: { id: 'singleton' },
118
+ // futureRelease gates the SMTP FUTURERELEASE extension. Empty by
119
+ // default, and empty means Stalwart's MAIL FROM handler skips the hold
120
+ // block entirely: a held submission is sent immediately, silently, and
121
+ // the client is told it succeeded. 30d matches the `maxDelayedSend` the
122
+ // server advertises to clients unconditionally, so nothing smaller
123
+ // would make that advertised capability a lie for a submission in
124
+ // between.
125
+ value: { futureRelease: { else: "'30d'" } },
126
+ },
114
127
  {
115
128
  key: 'reload',
116
129
  object: 'Action',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, and administering the Stalwart server it lives on. Two entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -42,7 +42,7 @@
42
42
  "record-fixtures": "node scripts/record-fixtures.mjs"
43
43
  },
44
44
  "peerDependencies": {
45
- "@wtfalch/design": ">=0.5.0",
45
+ "@wtfalch/design": ">=0.16.0",
46
46
  "react": "^19.0.0",
47
47
  "react-dom": "^19.0.0"
48
48
  },
@@ -61,7 +61,7 @@
61
61
  "@types/node": "^22",
62
62
  "@types/react": "^19",
63
63
  "@types/react-dom": "^19",
64
- "@wtfalch/design": "^0.7.0",
64
+ "@wtfalch/design": "^0.16.0",
65
65
  "jsdom": "^30.0.1",
66
66
  "react": "^19",
67
67
  "react-dom": "^19",