@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
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Finding the line where a received HTML message's own markup ends and the
3
+ * quoted history it carries begins.
4
+ *
5
+ * This is the HTML half of `splitQuoted` (`../quoted.ts`), which does the
6
+ * same job for a plain-text body and explains, in its own doc comment, why
7
+ * the two live apart: HTML quote detection wants the inert `DOMParser` walk
8
+ * that `./sanitise.ts` already has, and `sanitise.ts` is browser-only, while
9
+ * `../quoted.ts` is exported from the JMAP core and has to run with no DOM
10
+ * at all. So this module sits beside `sanitise.ts`, under `mailbox/react/`,
11
+ * and is exported from the react entry, not the core.
12
+ *
13
+ * **The result is a boundary, not a summary**, mirroring `QuoteBoundary`'s
14
+ * field names on purpose: a caller collapsing the thread view renders `body`
15
+ * and offers `quoted` behind a disclosure, same as the text half. A message
16
+ * with no quoted history returns the whole thing as `body` and `''` as
17
+ * `quoted`; a bare forward that is nothing but quoted history returns `''`
18
+ * (or, depending on incidental whitespace around the marker, whitespace
19
+ * that renders as nothing) as `body` and the rest as `quoted`.
20
+ *
21
+ * **Unlike the text half, `body + quoted` is not guaranteed to equal the
22
+ * original string.** When no marker is found, `body` is the input `html`
23
+ * untouched — that case is a byte-exact round trip. When a marker is found,
24
+ * both halves are serialised back out of the parsed document
25
+ * (`Element.innerHTML` / `outerHTML`), and a parser-serialiser cycle does
26
+ * not promise to reproduce the source byte for byte: attribute quoting and
27
+ * order, self-closing spelling, and incidental whitespace can all change.
28
+ * What holds instead is structural: every node from the parsed body ends up
29
+ * in exactly one of the two halves, nothing is dropped, and rendering each
30
+ * half (through `mailDocument`, same as the original `html` — neither half
31
+ * is sanitised here) reproduces what the reader would see.
32
+ *
33
+ * **What counts as a quote marker, and why a bare `<blockquote>` does not.**
34
+ * Three shapes, each a real client's own convention rather than a guess:
35
+ * - `<blockquote type="cite">` — the attribute mail composers (Apple Mail,
36
+ * Thunderbird, and others going back to Netscape Communicator) set
37
+ * specifically to mean "this is quoted history", not a styling choice. A
38
+ * `<blockquote>` with no `type` — the shape a pull-quote in the body of a
39
+ * message would actually use — is left alone and stays in `body`. That is
40
+ * the false positive that matters, and it is the same safe direction the
41
+ * text half takes when unsure: nothing is hidden, it is just not
42
+ * collapsed.
43
+ * - Gmail's `gmail_quote` class, on whichever element carries it (the
44
+ * wrapping `<div class="gmail_quote gmail_quote_container">` in current
45
+ * Gmail, or a bare `<blockquote class="gmail_quote">` in older markup).
46
+ * - Outlook's plain-text-era divider, translated to HTML: a `<div>` whose
47
+ * inline `style` sets `border-top` to something other than `none`. Real
48
+ * Outlook markup leaves this `<div>` empty and puts the actual
49
+ * `From:`/`Sent:`/`To:`/`Subject:` header block and the quoted body in
50
+ * its *following siblings*, not inside it — unlike the other two shapes,
51
+ * which wrap the quoted content. Marker detection and extraction are
52
+ * unified over this by treating every marker as "itself and everything
53
+ * that follows it, at its own level": the marker's later siblings (and
54
+ * only its own siblings — an ancestor's later siblings are not swept in)
55
+ * join it in `quoted`. For Gmail and `blockquote[type=cite]` that set is
56
+ * almost always just the marker itself, since nothing meaningful trails
57
+ * them in practice.
58
+ *
59
+ * **Not covered, deliberately**, for the same reason the text half draws
60
+ * its own line: a localised divider or attribution; Outlook's Web/desktop
61
+ * markup when it skips the `border-top` divider entirely (`id` values such
62
+ * as `divRplyFwdMsg` are not matched, since they are less stable across
63
+ * versions than the inline style); a marker nested inside a `<template>`
64
+ * (its content lives outside `.children` and is never walked); a second,
65
+ * unrelated quote block once the first marker has been found — only the
66
+ * first marker's *own* later siblings join it in `quoted` (as above), so a
67
+ * second block that is itself one of those siblings is swept in too, but
68
+ * one that instead sits at an outer level — a root-level sibling of a
69
+ * wrapper the first marker is nested inside, as Gmail's `gmail_quote` div
70
+ * often is — is left exactly where it was, inside `body`, not collapsed;
71
+ * and a quote marker a sender's own composer emits without following any
72
+ * of the three conventions above.
73
+ */
74
+ import type { Message } from '../types.ts';
75
+ /** The boundary between an HTML message's own markup and the quoted history
76
+ * under it. Field names match `QuoteBoundary` (`../quoted.ts`) so the two
77
+ * read as one feature; the type is its own because the guarantee is
78
+ * different — see this module's doc comment on round-tripping. */
79
+ export type HtmlQuoteBoundary = {
80
+ /** The reader's own markup, serialised from the document with the quote
81
+ * marker (and its later siblings) removed. Unsanitised, like the input. */
82
+ body: string;
83
+ /** The quoted history: the first quote marker found, and everything that
84
+ * follows it among its own siblings, serialised back out. `''` when no
85
+ * marker was found. Unsanitised, like the input. */
86
+ quoted: string;
87
+ };
88
+ /**
89
+ * Where a received HTML body's own markup ends and its quoted history
90
+ * begins. See the module doc comment for the three marker shapes covered,
91
+ * what is deliberately not, and what the returned halves do and do not
92
+ * guarantee about reconstructing the original string.
93
+ *
94
+ * A nullish `html` is treated the same as an empty one rather than thrown
95
+ * at `.trim()`: the parameter type says `string`, but `Message.html` is
96
+ * `string | null`, and a caller that reaches this function directly
97
+ * instead of through `htmlQuoteBoundary` should not crash a mail client
98
+ * over one message it cannot collapse a quote in.
99
+ */
100
+ export declare function splitQuotedHtml(html: string): HtmlQuoteBoundary;
101
+ /** `splitQuotedHtml` against a received message's own HTML body. A message
102
+ * with no HTML body (text-only) has nothing to split: the whole boundary
103
+ * is empty, not a guess — the same answer `quoteBoundary` (`../quoted.ts`)
104
+ * gives a text-only message with no text body, mirrored the other way. */
105
+ export declare function htmlQuoteBoundary(message: Pick<Message, 'html'>): HtmlQuoteBoundary;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Finding the line where a received HTML message's own markup ends and the
3
+ * quoted history it carries begins.
4
+ *
5
+ * This is the HTML half of `splitQuoted` (`../quoted.ts`), which does the
6
+ * same job for a plain-text body and explains, in its own doc comment, why
7
+ * the two live apart: HTML quote detection wants the inert `DOMParser` walk
8
+ * that `./sanitise.ts` already has, and `sanitise.ts` is browser-only, while
9
+ * `../quoted.ts` is exported from the JMAP core and has to run with no DOM
10
+ * at all. So this module sits beside `sanitise.ts`, under `mailbox/react/`,
11
+ * and is exported from the react entry, not the core.
12
+ *
13
+ * **The result is a boundary, not a summary**, mirroring `QuoteBoundary`'s
14
+ * field names on purpose: a caller collapsing the thread view renders `body`
15
+ * and offers `quoted` behind a disclosure, same as the text half. A message
16
+ * with no quoted history returns the whole thing as `body` and `''` as
17
+ * `quoted`; a bare forward that is nothing but quoted history returns `''`
18
+ * (or, depending on incidental whitespace around the marker, whitespace
19
+ * that renders as nothing) as `body` and the rest as `quoted`.
20
+ *
21
+ * **Unlike the text half, `body + quoted` is not guaranteed to equal the
22
+ * original string.** When no marker is found, `body` is the input `html`
23
+ * untouched — that case is a byte-exact round trip. When a marker is found,
24
+ * both halves are serialised back out of the parsed document
25
+ * (`Element.innerHTML` / `outerHTML`), and a parser-serialiser cycle does
26
+ * not promise to reproduce the source byte for byte: attribute quoting and
27
+ * order, self-closing spelling, and incidental whitespace can all change.
28
+ * What holds instead is structural: every node from the parsed body ends up
29
+ * in exactly one of the two halves, nothing is dropped, and rendering each
30
+ * half (through `mailDocument`, same as the original `html` — neither half
31
+ * is sanitised here) reproduces what the reader would see.
32
+ *
33
+ * **What counts as a quote marker, and why a bare `<blockquote>` does not.**
34
+ * Three shapes, each a real client's own convention rather than a guess:
35
+ * - `<blockquote type="cite">` — the attribute mail composers (Apple Mail,
36
+ * Thunderbird, and others going back to Netscape Communicator) set
37
+ * specifically to mean "this is quoted history", not a styling choice. A
38
+ * `<blockquote>` with no `type` — the shape a pull-quote in the body of a
39
+ * message would actually use — is left alone and stays in `body`. That is
40
+ * the false positive that matters, and it is the same safe direction the
41
+ * text half takes when unsure: nothing is hidden, it is just not
42
+ * collapsed.
43
+ * - Gmail's `gmail_quote` class, on whichever element carries it (the
44
+ * wrapping `<div class="gmail_quote gmail_quote_container">` in current
45
+ * Gmail, or a bare `<blockquote class="gmail_quote">` in older markup).
46
+ * - Outlook's plain-text-era divider, translated to HTML: a `<div>` whose
47
+ * inline `style` sets `border-top` to something other than `none`. Real
48
+ * Outlook markup leaves this `<div>` empty and puts the actual
49
+ * `From:`/`Sent:`/`To:`/`Subject:` header block and the quoted body in
50
+ * its *following siblings*, not inside it — unlike the other two shapes,
51
+ * which wrap the quoted content. Marker detection and extraction are
52
+ * unified over this by treating every marker as "itself and everything
53
+ * that follows it, at its own level": the marker's later siblings (and
54
+ * only its own siblings — an ancestor's later siblings are not swept in)
55
+ * join it in `quoted`. For Gmail and `blockquote[type=cite]` that set is
56
+ * almost always just the marker itself, since nothing meaningful trails
57
+ * them in practice.
58
+ *
59
+ * **Not covered, deliberately**, for the same reason the text half draws
60
+ * its own line: a localised divider or attribution; Outlook's Web/desktop
61
+ * markup when it skips the `border-top` divider entirely (`id` values such
62
+ * as `divRplyFwdMsg` are not matched, since they are less stable across
63
+ * versions than the inline style); a marker nested inside a `<template>`
64
+ * (its content lives outside `.children` and is never walked); a second,
65
+ * unrelated quote block once the first marker has been found — only the
66
+ * first marker's *own* later siblings join it in `quoted` (as above), so a
67
+ * second block that is itself one of those siblings is swept in too, but
68
+ * one that instead sits at an outer level — a root-level sibling of a
69
+ * wrapper the first marker is nested inside, as Gmail's `gmail_quote` div
70
+ * often is — is left exactly where it was, inside `body`, not collapsed;
71
+ * and a quote marker a sender's own composer emits without following any
72
+ * of the three conventions above.
73
+ */
74
+ /** A `<div>` is Outlook's divider when its inline style sets a `border-top`
75
+ * that is not `none` — a regex over one attribute's value, the same grain
76
+ * `sanitise.ts` itself reads CSS at (`HOSTILE_VALUE`, `FETCHES`), not over
77
+ * the markup this module is meant to parse rather than pattern-match. */
78
+ const OUTLOOK_DIVIDER = /(?:^|;)\s*border-top\s*:\s*(?!none\b)\S/i;
79
+ function isOutlookDivider(element) {
80
+ return element.localName === 'div' && OUTLOOK_DIVIDER.test(element.getAttribute('style') ?? '');
81
+ }
82
+ /** Whether `element` opens a quoted block, by one of the three conventions
83
+ * this module covers. See the module doc comment for what each means and
84
+ * why a bare `<blockquote>` does not qualify. */
85
+ function isQuoteMarker(element) {
86
+ const type = (element.getAttribute('type') ?? '').toLowerCase();
87
+ if (element.localName === 'blockquote' && type === 'cite')
88
+ return true;
89
+ if (element.classList.contains('gmail_quote'))
90
+ return true;
91
+ return isOutlookDivider(element);
92
+ }
93
+ /**
94
+ * The first element in document order that opens a quoted block, or `null`.
95
+ *
96
+ * Iterative, not recursive, for the same reason `sanitise.ts`'s `sweep` is:
97
+ * a message is a stranger's choice of nesting depth, and the stack is not.
98
+ * A matched element is never descended into, so an inner `<blockquote
99
+ * type="cite">` nested inside an outer `gmail_quote` div never overrides
100
+ * the outer match — the outermost marker wins, since it is the one that
101
+ * actually bounds the quoted content.
102
+ */
103
+ function findMarker(root) {
104
+ const stack = [];
105
+ for (let i = root.children.length - 1; i >= 0; i--)
106
+ stack.push(root.children[i]);
107
+ while (stack.length > 0) {
108
+ const element = stack.pop();
109
+ if (isQuoteMarker(element))
110
+ return element;
111
+ for (let i = element.children.length - 1; i >= 0; i--) {
112
+ stack.push(element.children[i]);
113
+ }
114
+ }
115
+ return null;
116
+ }
117
+ /**
118
+ * Moves `marker` and every node after it among its own siblings — elements,
119
+ * text, comments alike, nothing skipped — into a detached wrapper, and
120
+ * returns that wrapper's serialised contents. The move itself is what
121
+ * prunes those nodes out of `root`, so the caller reads `root.innerHTML`
122
+ * afterwards for `body`.
123
+ */
124
+ function extractQuoted(marker, doc) {
125
+ const wrapper = doc.createElement('div');
126
+ let node = marker;
127
+ while (node) {
128
+ const next = node.nextSibling;
129
+ wrapper.append(node);
130
+ node = next;
131
+ }
132
+ return wrapper.innerHTML;
133
+ }
134
+ /**
135
+ * Where a received HTML body's own markup ends and its quoted history
136
+ * begins. See the module doc comment for the three marker shapes covered,
137
+ * what is deliberately not, and what the returned halves do and do not
138
+ * guarantee about reconstructing the original string.
139
+ *
140
+ * A nullish `html` is treated the same as an empty one rather than thrown
141
+ * at `.trim()`: the parameter type says `string`, but `Message.html` is
142
+ * `string | null`, and a caller that reaches this function directly
143
+ * instead of through `htmlQuoteBoundary` should not crash a mail client
144
+ * over one message it cannot collapse a quote in.
145
+ */
146
+ export function splitQuotedHtml(html) {
147
+ if (!html?.trim())
148
+ return { body: html ?? '', quoted: '' };
149
+ const doc = new DOMParser().parseFromString(html, 'text/html');
150
+ const root = doc.body ?? doc.createElement('body');
151
+ const marker = findMarker(root);
152
+ if (!marker)
153
+ return { body: html, quoted: '' };
154
+ const quoted = extractQuoted(marker, doc);
155
+ return { body: root.innerHTML, quoted };
156
+ }
157
+ /** `splitQuotedHtml` against a received message's own HTML body. A message
158
+ * with no HTML body (text-only) has nothing to split: the whole boundary
159
+ * is empty, not a guess — the same answer `quoteBoundary` (`../quoted.ts`)
160
+ * gives a text-only message with no text body, mirrored the other way. */
161
+ export function htmlQuoteBoundary(message) {
162
+ return splitQuotedHtml(message.html ?? '');
163
+ }
@@ -0,0 +1,76 @@
1
+ import { type MailClient } from './client.ts';
2
+ export type SieveScriptSummary = {
3
+ id: string;
4
+ name: string;
5
+ isActive: boolean;
6
+ blobId: string;
7
+ };
8
+ /** Every Sieve script on the account, active one included. */
9
+ export declare function sieveScripts(client: MailClient): Promise<readonly SieveScriptSummary[]>;
10
+ /**
11
+ * One script's Sieve source.
12
+ *
13
+ * The blob carries no credential of its own (RFC 8620 §6.2), so its bytes
14
+ * are fetched with the same `Authorization` header the API uses — the same
15
+ * reason `downloadAttachment` cannot be a bare `<a href>`.
16
+ */
17
+ export declare function sieveScriptText(client: MailClient, scriptId: string): Promise<string>;
18
+ /**
19
+ * Compile `text` on the server without saving it.
20
+ *
21
+ * `SieveScript/validate` runs the same compiler `SieveScript/set` does
22
+ * (`set.rs:541`), so a script that fails here would also fail a save — this
23
+ * is a sanity check before committing, per RFC 9661.
24
+ */
25
+ export declare function validateSieveScript(client: MailClient, text: string): Promise<void>;
26
+ export type SavedSieveScript = {
27
+ id: string;
28
+ name: string;
29
+ blobId: string;
30
+ };
31
+ export type SaveSieveScriptOptions = {
32
+ /** Replace this script's content and name, instead of creating a new one. */
33
+ scriptId?: string;
34
+ };
35
+ /**
36
+ * Create a script from `text`, or replace one's content when `scriptId` is
37
+ * given. Never activated by this call — see {@link activateSieveScript}.
38
+ *
39
+ * **Not a `SieveScriptSummary`.** A replace's response only carries what
40
+ * changed (`set.rs:290-297`), and `isActive` is never one of those things
41
+ * this call touches, so reporting it here would cost a second
42
+ * `SieveScript/get` nobody asked for — the same reasoning `createMailbox`
43
+ * gives for returning a `NewMailbox` rather than a full `MailboxNode`.
44
+ */
45
+ export declare function saveSieveScript(client: MailClient, name: string, text: string, options?: SaveSieveScriptOptions): Promise<SavedSieveScript>;
46
+ /**
47
+ * Make one script the account's active filter.
48
+ *
49
+ * **`onSuccessActivateScript` alone would fail silently for an id the
50
+ * account does not have.** Stalwart clears it rather than refusing when the
51
+ * id is not the caller's own (`set.rs:96-101`), and with no `create` or
52
+ * `update` in the same call there is nothing left in the response to notice
53
+ * a no-op by. Pairing it with an empty `update` on that same id turns a bad
54
+ * id into an ordinary, checkable `notUpdated` (`set.rs:322-324`'s
55
+ * `notFound` when the id does not resolve to a real script), which is what
56
+ * this checks; a good id updates nothing (the patch is empty) and the pair
57
+ * still activates it.
58
+ */
59
+ export declare function activateSieveScript(client: MailClient, scriptId: string): Promise<void>;
60
+ /**
61
+ * Turn Sieve filtering off for the account: whichever script was active
62
+ * stops running, and nothing replaces it until something is activated
63
+ * again. RFC 9661's `onSuccessDeactivateScript`, one round trip, no id to
64
+ * get wrong — unlike {@link activateSieveScript} there is nothing here for
65
+ * a bad id to silently do nothing to.
66
+ */
67
+ export declare function deactivateSieveScripts(client: MailClient): Promise<void>;
68
+ /**
69
+ * Delete a script.
70
+ *
71
+ * Refused by the server while it is the active one
72
+ * (`type: "scriptIsActive"`, `set.rs:341-346`) — {@link deactivateSieveScripts}
73
+ * first, then delete. This surfaces that refusal rather than guessing at it,
74
+ * the same stance `deleteMailbox` takes on a mailbox with a role.
75
+ */
76
+ export declare function deleteSieveScript(client: MailClient, scriptId: string): Promise<void>;
@@ -0,0 +1,241 @@
1
+ import { JAM_FETCH, SIEVE_CAPABILITY } from "./client.js";
2
+ import { MailError, guard } from "./errors.js";
3
+ /**
4
+ * Per-account Sieve scripts — RFC 9661, "JMAP for Sieve Scripts".
5
+ *
6
+ * **`jmap-jam` has no typed `SieveScript` methods.** Its `Methods` union
7
+ * (`contracts.ts`) only covers RFC 8621/8620/8621's own objects, and its
8
+ * capability table (`capabilities.ts`) does not know
9
+ * `urn:ietf:params:jmap:sieve` either, so `jam.api.SieveScript` does not
10
+ * exist and the automatic `using` it derives from a method name would miss
11
+ * this capability. Every call here goes through `jam.request` directly, with
12
+ * the capability supplied by hand through `using` — the same thing
13
+ * `submit.ts`'s `send()` does to add the mail capability alongside
14
+ * `EmailSubmission/set`.
15
+ *
16
+ * Confirmed against `stalwartlabs/stalwart` at `main`,
17
+ * `02503015580abd6706923d34e9d8e501e76f8634`:
18
+ * - the four methods and the capability string:
19
+ * `crates/jmap-proto/src/request/method.rs:146-149,284-287`,
20
+ * `crates/jmap-proto/src/request/capability.rs:76-77,326,470`;
21
+ * - the object is exactly `{id, name, blobId, isActive}` — no structured
22
+ * condition/action shape to build on:
23
+ * `crates/jmap-proto/src/object/sieve.rs:19-24`;
24
+ * - a create requires an uploaded blob first ("Missing blobId."):
25
+ * `crates/jmap/src/sieve/set.rs:566-569`;
26
+ * - activation is the non-standard `onSuccessActivateScript` /
27
+ * `onSuccessDeactivateScript` set arguments, one round trip, no separate
28
+ * activate call: `crates/jmap-proto/src/object/sieve.rs:93-96`,
29
+ * `crates/jmap/src/sieve/set.rs:371-391`;
30
+ * - deleting the active script is refused
31
+ * (`type: "scriptIsActive"`): `crates/jmap/src/sieve/set.rs:341-346`.
32
+ *
33
+ * **`SieveScript/query` is never called.** RFC 8620 §5.1: an absent `ids`
34
+ * on `Foo/get` returns every object the account has, the same shortcut
35
+ * `identities()` takes for `Identity/get` — a plain `get` lists every script
36
+ * in one call, so the extra `query` round trip buys nothing here.
37
+ */
38
+ const SIEVE_OPTIONS = { using: [SIEVE_CAPABILITY], ...JAM_FETCH };
39
+ /** The one raw call every function below goes through: see the module
40
+ * docblock for why `jam.api` cannot reach `SieveScript/*`. */
41
+ async function sieveCall(jam, method, args) {
42
+ const [result] = await jam.request([method, args], SIEVE_OPTIONS);
43
+ return result;
44
+ }
45
+ /** Every Sieve script on the account, active one included. */
46
+ export async function sieveScripts(client) {
47
+ const { jam, accountId } = await client.connect();
48
+ return guard('sieve scripts', async () => {
49
+ const result = await sieveCall(jam, 'SieveScript/get', { accountId });
50
+ const list = result.list;
51
+ return list.map((script) => ({
52
+ id: script.id,
53
+ name: script.name,
54
+ isActive: script.isActive ?? false,
55
+ blobId: script.blobId,
56
+ }));
57
+ });
58
+ }
59
+ /**
60
+ * One script's Sieve source.
61
+ *
62
+ * The blob carries no credential of its own (RFC 8620 §6.2), so its bytes
63
+ * are fetched with the same `Authorization` header the API uses — the same
64
+ * reason `downloadAttachment` cannot be a bare `<a href>`.
65
+ */
66
+ export async function sieveScriptText(client, scriptId) {
67
+ const { jam, accountId } = await client.connect();
68
+ return guard('sieve script text', async () => {
69
+ const result = await sieveCall(jam, 'SieveScript/get', { accountId, ids: [scriptId] });
70
+ const script = result.list[0];
71
+ if (!script) {
72
+ throw new MailError(`no sieve script ${scriptId} on this account`, {
73
+ type: 'notFound',
74
+ operation: 'sieve script text',
75
+ });
76
+ }
77
+ const url = await client.downloadUrl({
78
+ blobId: script.blobId,
79
+ name: `${script.name}.sieve`,
80
+ type: 'application/sieve',
81
+ });
82
+ const response = await fetch(url, {
83
+ headers: { Authorization: client.authorization },
84
+ credentials: 'omit',
85
+ });
86
+ if (!response.ok) {
87
+ throw new MailError(`the server refused to send the script text (${response.status})`, {
88
+ status: response.status,
89
+ operation: 'sieve script text',
90
+ });
91
+ }
92
+ return response.text();
93
+ });
94
+ }
95
+ /**
96
+ * Compile `text` on the server without saving it.
97
+ *
98
+ * `SieveScript/validate` runs the same compiler `SieveScript/set` does
99
+ * (`set.rs:541`), so a script that fails here would also fail a save — this
100
+ * is a sanity check before committing, per RFC 9661.
101
+ */
102
+ export async function validateSieveScript(client, text) {
103
+ const { jam, accountId } = await client.connect();
104
+ const uploaded = await client.upload(text, 'application/sieve');
105
+ return guard('validate sieve script', async () => {
106
+ const result = await sieveCall(jam, 'SieveScript/validate', {
107
+ accountId,
108
+ blobId: uploaded.blobId,
109
+ });
110
+ const error = result.error;
111
+ if (error) {
112
+ throw new MailError(error.description ?? 'the script did not compile', {
113
+ type: error.type ?? 'invalidScript',
114
+ operation: 'validate sieve script',
115
+ });
116
+ }
117
+ });
118
+ }
119
+ /**
120
+ * Create a script from `text`, or replace one's content when `scriptId` is
121
+ * given. Never activated by this call — see {@link activateSieveScript}.
122
+ *
123
+ * **Not a `SieveScriptSummary`.** A replace's response only carries what
124
+ * changed (`set.rs:290-297`), and `isActive` is never one of those things
125
+ * this call touches, so reporting it here would cost a second
126
+ * `SieveScript/get` nobody asked for — the same reasoning `createMailbox`
127
+ * gives for returning a `NewMailbox` rather than a full `MailboxNode`.
128
+ */
129
+ export async function saveSieveScript(client, name, text, options = {}) {
130
+ const trimmed = name.trim();
131
+ if (!trimmed) {
132
+ throw new MailError('a sieve script needs a name', {
133
+ type: 'invalidArguments',
134
+ operation: 'save sieve script',
135
+ });
136
+ }
137
+ const { jam, accountId } = await client.connect();
138
+ const uploaded = await client.upload(text, 'application/sieve');
139
+ return guard('save sieve script', async () => {
140
+ if (options.scriptId) {
141
+ const scriptId = options.scriptId;
142
+ const result = await sieveCall(jam, 'SieveScript/set', {
143
+ accountId,
144
+ update: { [scriptId]: { name: trimmed, blobId: uploaded.blobId } },
145
+ });
146
+ const notUpdated = result.notUpdated;
147
+ const failure = notUpdated?.[scriptId];
148
+ if (failure) {
149
+ throw new MailError(failure.description ?? 'the server refused to replace the script', {
150
+ type: failure.type ?? 'unknown',
151
+ operation: 'save sieve script',
152
+ });
153
+ }
154
+ return { id: scriptId, name: trimmed, blobId: uploaded.blobId };
155
+ }
156
+ const result = await sieveCall(jam, 'SieveScript/set', {
157
+ accountId,
158
+ create: { script: { name: trimmed, blobId: uploaded.blobId } },
159
+ });
160
+ const created = result.created
161
+ ?.script;
162
+ if (!created) {
163
+ const notCreated = result.notCreated;
164
+ const failure = notCreated?.script;
165
+ throw new MailError(failure?.description ?? 'the server would not create the script', {
166
+ type: failure?.type ?? 'unknown',
167
+ operation: 'save sieve script',
168
+ });
169
+ }
170
+ return { id: created.id, name: trimmed, blobId: created.blobId ?? uploaded.blobId };
171
+ });
172
+ }
173
+ /**
174
+ * Make one script the account's active filter.
175
+ *
176
+ * **`onSuccessActivateScript` alone would fail silently for an id the
177
+ * account does not have.** Stalwart clears it rather than refusing when the
178
+ * id is not the caller's own (`set.rs:96-101`), and with no `create` or
179
+ * `update` in the same call there is nothing left in the response to notice
180
+ * a no-op by. Pairing it with an empty `update` on that same id turns a bad
181
+ * id into an ordinary, checkable `notUpdated` (`set.rs:322-324`'s
182
+ * `notFound` when the id does not resolve to a real script), which is what
183
+ * this checks; a good id updates nothing (the patch is empty) and the pair
184
+ * still activates it.
185
+ */
186
+ export async function activateSieveScript(client, scriptId) {
187
+ const { jam, accountId } = await client.connect();
188
+ return guard('activate sieve script', async () => {
189
+ const result = await sieveCall(jam, 'SieveScript/set', {
190
+ accountId,
191
+ update: { [scriptId]: {} },
192
+ onSuccessActivateScript: scriptId,
193
+ });
194
+ const notUpdated = result.notUpdated;
195
+ const failure = notUpdated?.[scriptId];
196
+ if (failure) {
197
+ throw new MailError(failure.description ?? 'the server refused to activate the script', {
198
+ type: failure.type ?? 'unknown',
199
+ operation: 'activate sieve script',
200
+ });
201
+ }
202
+ });
203
+ }
204
+ /**
205
+ * Turn Sieve filtering off for the account: whichever script was active
206
+ * stops running, and nothing replaces it until something is activated
207
+ * again. RFC 9661's `onSuccessDeactivateScript`, one round trip, no id to
208
+ * get wrong — unlike {@link activateSieveScript} there is nothing here for
209
+ * a bad id to silently do nothing to.
210
+ */
211
+ export async function deactivateSieveScripts(client) {
212
+ const { jam, accountId } = await client.connect();
213
+ return guard('deactivate sieve scripts', async () => {
214
+ await sieveCall(jam, 'SieveScript/set', { accountId, onSuccessDeactivateScript: true });
215
+ });
216
+ }
217
+ /**
218
+ * Delete a script.
219
+ *
220
+ * Refused by the server while it is the active one
221
+ * (`type: "scriptIsActive"`, `set.rs:341-346`) — {@link deactivateSieveScripts}
222
+ * first, then delete. This surfaces that refusal rather than guessing at it,
223
+ * the same stance `deleteMailbox` takes on a mailbox with a role.
224
+ */
225
+ export async function deleteSieveScript(client, scriptId) {
226
+ const { jam, accountId } = await client.connect();
227
+ return guard('delete sieve script', async () => {
228
+ const result = await sieveCall(jam, 'SieveScript/set', {
229
+ accountId,
230
+ destroy: [scriptId],
231
+ });
232
+ const notDestroyed = result.notDestroyed;
233
+ const failure = notDestroyed?.[scriptId];
234
+ if (failure) {
235
+ throw new MailError(failure.description ?? 'the server refused to delete the script', {
236
+ type: failure.type ?? 'unknown',
237
+ operation: 'delete sieve script',
238
+ });
239
+ }
240
+ });
241
+ }
@@ -0,0 +1,48 @@
1
+ import { type MailClient } from './client.ts';
2
+ import type { MailboxNode } from './types.ts';
3
+ /**
4
+ * Snooze: take a thread out of the Inbox until a time, then put it back.
5
+ *
6
+ * **JMAP has no snooze, so this is two halves.** `snoozeThread` moves the
7
+ * thread into a top-level mailbox named Snoozed (made on first use) and
8
+ * stamps each message with a keyword holding the wake time.
9
+ * `wakeSnoozed` moves every thread whose time has come back to the Inbox,
10
+ * unread. Nothing in a mail server calls `wakeSnoozed`; the host runs it on
11
+ * a timer. That is the part of snooze that is server work, and a library
12
+ * cannot own a clock.
13
+ *
14
+ * **The wake time is a keyword, `$snoozed:<unix seconds>`.** A message has
15
+ * no free-form property to hold a date, and a keyword is stored, searchable
16
+ * and survives every client. RFC 8621 keywords may contain `:` and digits.
17
+ */
18
+ /** The name the Snoozed mailbox is found and made by. */
19
+ export declare const SNOOZED_MAILBOX = "Snoozed";
20
+ export type SnoozeOptions = {
21
+ /** The mailbox tree, when the caller already has it. Saves a `Mailbox/get`. */
22
+ mailboxes?: readonly MailboxNode[];
23
+ };
24
+ /**
25
+ * Snooze a thread until `until`: out of every mailbox, into Snoozed.
26
+ *
27
+ * Messages in Sent or Drafts stay where they are. They are my own copies,
28
+ * not mail waiting for me, and waking files into the Inbox: a sent reply
29
+ * moved into Snoozed would come back as if it had been received.
30
+ *
31
+ * Snoozing a thread that is already snoozed moves its wake time; the old
32
+ * one is removed rather than left beside it. A time in the past is allowed
33
+ * and simply wakes on the next `wakeSnoozed`, since what "now" is belongs
34
+ * to the host's clock, not this call's.
35
+ *
36
+ * Returns the ids of the messages that moved.
37
+ */
38
+ export declare function snoozeThread(client: MailClient, threadId: string, until: Date, options?: SnoozeOptions): Promise<readonly string[]>;
39
+ /**
40
+ * Wake every snoozed thread whose time is at or before `now`: back to the
41
+ * Inbox, unread, wake time removed.
42
+ *
43
+ * Meant for a timer the host runs, every minute or so. `now` is a
44
+ * parameter so the host's clock decides, and a test can pass its own.
45
+ * Returns the ids of the threads that woke; an account that has never
46
+ * snoozed anything returns none without making a mailbox.
47
+ */
48
+ export declare function wakeSnoozed(client: MailClient, now?: Date, options?: SnoozeOptions): Promise<readonly string[]>;