@wtfalch/email 0.21.0 → 0.24.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 +54 -25
- package/dist/mailbox/index.d.ts +4 -4
- package/dist/mailbox/index.js +2 -2
- package/dist/mailbox/rules.d.ts +36 -0
- package/dist/mailbox/rules.js +144 -17
- package/dist/mailbox/submit.d.ts +20 -1
- package/dist/mailbox/submit.js +125 -0
- package/dist/mailbox/types.d.ts +19 -0
- package/dist/mailbox/vacation.d.ts +4 -0
- package/dist/mailbox/vacation.js +118 -10
- package/dist/postmaster/apply.d.ts +20 -0
- package/dist/postmaster/apply.js +48 -1
- package/dist/postmaster/audit.d.ts +3 -0
- package/dist/postmaster/audit.js +1 -0
- package/dist/postmaster/index.d.ts +3 -2
- package/dist/postmaster/index.js +3 -2
- package/dist/postmaster/mail-copy.d.ts +12 -1
- package/dist/postmaster/mail-copy.js +2 -2
- package/dist/postmaster/mail-takeout.d.ts +31 -0
- package/dist/postmaster/mail-takeout.js +113 -0
- package/dist/postmaster/org-mail-export.d.ts +2 -2
- package/dist/postmaster/writes.d.ts +14 -1
- package/dist/postmaster/writes.js +17 -1
- package/package.json +1 -5
- package/dist/mailbox/fake/index.d.ts +0 -34
- package/dist/mailbox/fake/index.js +0 -85
- package/dist/mailbox/fake/mailbox.d.ts +0 -90
- package/dist/mailbox/fake/mailbox.js +0 -1284
- package/dist/mailbox/fake/sample.d.ts +0 -2
- package/dist/mailbox/fake/sample.js +0 -322
package/README.md
CHANGED
|
@@ -106,7 +106,13 @@ regardless. `queued` lists everything still held, soonest first, for a
|
|
|
106
106
|
rather than reading the field off an unfiltered one, since that filter is
|
|
107
107
|
what makes the server recheck each submission against the mail queue and
|
|
108
108
|
demote one that already went, instead of answering a stale `'pending'`. Every
|
|
109
|
-
row it returns is safe to hand straight to `cancel`. `
|
|
109
|
+
row it returns is safe to hand straight to `cancel`. `submissions` lists the
|
|
110
|
+
account's sent mail newest first, each with a `state` (`scheduled`, `sending`,
|
|
111
|
+
`delivered`, `failed`, `canceled`) read from `undoStatus` and the server's
|
|
112
|
+
`deliveryStatus`, plus the email's `subject` and `to`; `options.states` and
|
|
113
|
+
`options.limit` (default 100) narrow it, and a `failed` row carries the
|
|
114
|
+
recipient's `smtpReply` as `failure`. `resend` sends a message that is already
|
|
115
|
+
in Sent again, with the identity matching its From, and files nothing. `saveDraft` stores a
|
|
110
116
|
draft in Drafts so it outlives the compose sheet, and given the id it returned
|
|
111
117
|
last time, replaces that draft instead of adding one (messages are immutable,
|
|
112
118
|
so the id changes each save). `send(…, { draftId })` sends and removes the
|
|
@@ -151,6 +157,15 @@ it. `clearVacationResponse` is the shorthand for turning it off — `isEnabled:
|
|
|
151
157
|
false` — without touching the dates or the message, so switching it back on
|
|
152
158
|
does not need them resupplied.
|
|
153
159
|
|
|
160
|
+
The reply has an `audience`: `'anyone'` (default), `'company'` (senders in the
|
|
161
|
+
account's own domain, taken from the first identity) or `'nobody'` (dates and
|
|
162
|
+
text kept, no reply). With the sieve capability the away reply is the vacation
|
|
163
|
+
section of the account's one active script, next to the mail rules, and the
|
|
164
|
+
server's own `VacationResponse` is kept `isEnabled: false` so it never replies
|
|
165
|
+
twice; a hand-written active script refuses an enabling write (`conflict`) but
|
|
166
|
+
can still be turned off. Without the capability only `'anyone'` works and the
|
|
167
|
+
JMAP object is used as before.
|
|
168
|
+
|
|
154
169
|
```ts
|
|
155
170
|
await setVacationResponse(client, {
|
|
156
171
|
isEnabled: true,
|
|
@@ -275,23 +290,6 @@ without pictures.
|
|
|
275
290
|
five `sortOrder: 0`, so the tie-break by name puts Deleted Items first and
|
|
276
291
|
Inbox third. `mailboxes()` still reports what the server said.
|
|
277
292
|
|
|
278
|
-
### A mailbox with no server
|
|
279
|
-
|
|
280
|
-
`@wtfalch/email/mailbox/fake` is an inbox in memory, for stories, for a
|
|
281
|
-
development build and for tests.
|
|
282
|
-
|
|
283
|
-
```ts
|
|
284
|
-
const { client, mailbox, dispose } = fakeMail();
|
|
285
|
-
const tree = await mailboxes(client); // the real function, over the real wire code
|
|
286
|
-
```
|
|
287
|
-
|
|
288
|
-
**It fakes the transport, not the API.** Stubbing the exported functions would
|
|
289
|
-
mean every story exercises the stub while the four-call chain, the result
|
|
290
|
-
references, the body resolution and the null-handling never run. It answers
|
|
291
|
-
JMAP instead. It replaces the global `fetch`, because `jmap-jam` calls the
|
|
292
|
-
bare global and takes no way to pass another one; the replacement delegates
|
|
293
|
-
anything not addressed to it, and `dispose()` puts it back.
|
|
294
|
-
|
|
295
293
|
## What it knows that the RFCs do not
|
|
296
294
|
|
|
297
295
|
**RFC 8621 §7.5's `onSuccessUpdateEmail` collides.** The server returns the
|
|
@@ -555,8 +553,18 @@ directly". Provision the replacement before revoking the one in use.
|
|
|
555
553
|
**A `List<T>` write replaces the whole list.** Adding one alias means sending
|
|
556
554
|
back every alias that survives. A read-modify-write that drops an entry does
|
|
557
555
|
not fail; it deletes somebody's alias, or every app password on their phone.
|
|
558
|
-
`withAlias`, `withoutAlias` and `
|
|
559
|
-
is decided by a unit test rather than at the end of
|
|
556
|
+
`withAlias`, `withoutAlias`, `withoutAppPassword` and `withoutAllAppPasswords`
|
|
557
|
+
exist so that arithmetic is decided by a unit test rather than at the end of
|
|
558
|
+
a request.
|
|
559
|
+
|
|
560
|
+
**Disabling a person's sign-in does not stop their mail by itself.** IMAP and
|
|
561
|
+
SMTP authenticate against the account's own credentials and never consult the
|
|
562
|
+
issuer, so an app password minted before a person is disabled keeps working
|
|
563
|
+
after. `revokeAllAppPasswords` drops every `AppPassword` credential on an
|
|
564
|
+
account at once — the `Password` and any `ApiKey` entries survive untouched —
|
|
565
|
+
for the moment a person must be shut out of mail immediately, alongside
|
|
566
|
+
whatever disables their sign-in. Same self-protection as `revokeAppPassword`:
|
|
567
|
+
refused on the account this app itself signs in as.
|
|
560
568
|
|
|
561
569
|
**A shared mailbox is a `Group` account.** `hr@` that a team reads together is
|
|
562
570
|
an ordinary account whose `@type` is `Group`: same delivery, same aliases, no
|
|
@@ -600,7 +608,8 @@ instead.
|
|
|
600
608
|
## The audit
|
|
601
609
|
|
|
602
610
|
`createMailbox`, `createGroupMailbox`, `addToGroup`, `removeFromGroup`, `addAlias`, `removeAlias`,
|
|
603
|
-
`revokeAppPassword`, `enableHolding`, `retryQueuedMessage` and
|
|
611
|
+
`revokeAppPassword`, `revokeAllAppPasswords`, `enableHolding`, `retryQueuedMessage` and
|
|
612
|
+
`purgeQueuedMessage` take an
|
|
604
613
|
optional last argument, a `PostmasterAudit`: a `write` the host bound to its
|
|
605
614
|
own ledger, the principal it resolved for this request, and the request id
|
|
606
615
|
its log uses. Without one, nothing changes.
|
|
@@ -726,6 +735,26 @@ one shared instance regardless of level; Agora's own org scoping is the
|
|
|
726
735
|
boundary between them, not a Stalwart tenant. Moving an org's old mail in
|
|
727
736
|
from Google or Microsoft — [`wtfalch/email#108`](https://github.com/wtfalch/email/issues/108) — is `mailCopyPlan`, below.
|
|
728
737
|
|
|
738
|
+
## Importing an uploaded Google Takeout archive
|
|
739
|
+
|
|
740
|
+
For a person whose mailbox is over Google's daily download cap, `mailTakeoutPlan`
|
|
741
|
+
decides the Vandelay commands that import an uploaded Takeout `.mbox` into one Stalwart
|
|
742
|
+
account (`import takeout`, then the same `export` step as `mailCopyPlan`; the export
|
|
743
|
+
credential is only named in `exportEnv`, never in argv). It refuses, with
|
|
744
|
+
`MailCopyPlanRefused`, a path that is not an absolute `.mbox` under `uploadDir` in its own
|
|
745
|
+
directory, a size over `TAKEOUT_MAX_BYTES` (50 GiB), and a target naming both id and name or
|
|
746
|
+
neither. Vandelay scans the mbox's whole *directory*, so keep one upload per directory.
|
|
747
|
+
|
|
748
|
+
How it differs from the IMAP route (`mailCopyPlan`):
|
|
749
|
+
|
|
750
|
+
- **Labels differ.** IMAP folders become mailboxes. Takeout carries Gmail labels in
|
|
751
|
+
`X-Gmail-Labels`: each label becomes a mailbox of that name (`Archived` → `Archive`),
|
|
752
|
+
`Inbox`/`Sent`/`Drafts`/`Trash`/`Spam`/`Archive` get the matching Stalwart roles,
|
|
753
|
+
`Starred`/`Important`/`Opened` become the `$flagged`/`$important`/`$seen` keywords, and
|
|
754
|
+
`Category …` labels are dropped. A message with several labels sits in several mailboxes.
|
|
755
|
+
- **The final pass is still IMAP.** A Takeout is a snapshot at export time; mail that arrived
|
|
756
|
+
since is picked up by running the `mailCopyPlan` import afterwards.
|
|
757
|
+
|
|
729
758
|
## Copying an org's old mail with Vandelay
|
|
730
759
|
|
|
731
760
|
Stalwart ships its own migration tool, [`stalwartlabs/vandelay`](https://github.com/stalwartlabs/vandelay):
|
|
@@ -741,13 +770,13 @@ import { mailCopyPlan } from '@wtfalch/email/postmaster';
|
|
|
741
770
|
const plan = mailCopyPlan({
|
|
742
771
|
provider: 'google', // or 'microsoft'
|
|
743
772
|
accounts: [{ source: 'alice@acme.com', targetAccountId: 'a1' }],
|
|
744
|
-
stalwartUrl: 'https://mail.
|
|
773
|
+
stalwartUrl: 'https://mail.companyincluded.com',
|
|
745
774
|
archiveDir: '/var/lib/mail-copy/acme',
|
|
746
775
|
});
|
|
747
776
|
|
|
748
777
|
// plan.accounts[0].importArgv: ['import', 'imap', '--url', 'imaps://imap.gmail.com',
|
|
749
778
|
// '--auth-bearer', '--auth-user=alice@acme.com', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
|
|
750
|
-
// plan.accounts[0].exportArgv: ['export', '--url', 'https://mail.
|
|
779
|
+
// plan.accounts[0].exportArgv: ['export', '--url', 'https://mail.companyincluded.com',
|
|
751
780
|
// '--auth-bearer', '--account-id=a1', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
|
|
752
781
|
// plan.accounts[0].importEnv / .exportEnv: [{ name: 'VANDELAY_TOKEN', purpose: '…' }] — a
|
|
753
782
|
// variable NAME, never a value.
|
|
@@ -850,7 +879,7 @@ const accounts = await accountsOnDomain(client, 'acme.com');
|
|
|
850
879
|
// 2. The Vandelay commands that pull each one's mail into a local archive.
|
|
851
880
|
const backup = orgMailBackupPlan({
|
|
852
881
|
accounts,
|
|
853
|
-
stalwartUrl: 'https://mail.
|
|
882
|
+
stalwartUrl: 'https://mail.companyincluded.com',
|
|
854
883
|
archiveDir: '/var/lib/mail-backup/acme',
|
|
855
884
|
});
|
|
856
885
|
|
|
@@ -860,7 +889,7 @@ const backup = orgMailBackupPlan({
|
|
|
860
889
|
// archives back in.
|
|
861
890
|
const restore = orgMailRestorePlan({
|
|
862
891
|
accounts: [{ address: 'alice@acme.com', targetAccountId: 'b1' }],
|
|
863
|
-
stalwartUrl: 'https://mail.
|
|
892
|
+
stalwartUrl: 'https://mail.companyincluded.com',
|
|
864
893
|
archiveDir: '/var/lib/mail-backup/acme',
|
|
865
894
|
});
|
|
866
895
|
```
|
package/dist/mailbox/index.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardS
|
|
|
23
23
|
export type { ForwardOptions, ReplyOptions } from './drafts.ts';
|
|
24
24
|
export { quoteBoundary, splitQuoted } from './quoted.ts';
|
|
25
25
|
export type { QuoteBoundary } from './quoted.ts';
|
|
26
|
-
export { cancel, draftPatch, draftToEmail, queued, saveDraft, send, sentPatch } from './submit.ts';
|
|
26
|
+
export { cancel, draftPatch, draftToEmail, queued, resend, saveDraft, send, sentPatch, submissions, } from './submit.ts';
|
|
27
27
|
export type { CancelOptions, SaveDraftOptions, SendOptions } from './submit.ts';
|
|
28
28
|
export { SNOOZED_MAILBOX, snoozeThread, wakeSnoozed } from './snooze.ts';
|
|
29
29
|
export type { SnoozeOptions } from './snooze.ts';
|
|
@@ -40,7 +40,7 @@ export { activateSieveScript, deactivateSieveScripts, deleteSieveScript, saveSie
|
|
|
40
40
|
export type { SavedSieveScript, SaveSieveScriptOptions, SieveScriptSummary } from './sieve.ts';
|
|
41
41
|
export { findPrincipals, lookupPrincipal } from './principals.ts';
|
|
42
42
|
export type { PrincipalMatch } from './principals.ts';
|
|
43
|
-
export { rulesToSieve, sieveToRules } from './rules.ts';
|
|
44
|
-
export type { MailRule, MailRuleAction, MailRuleCondition } from './rules.ts';
|
|
43
|
+
export { combineScript, isOurScript, rulesToSieve, sieveToRules, splitScript } from './rules.ts';
|
|
44
|
+
export type { MailRule, MailRuleAction, MailRuleCondition, VacationSection, } from './rules.ts';
|
|
45
45
|
export { expandTemplate } from './uri.ts';
|
|
46
|
-
export type { Attachment, ChangedState, Draft, DraftAttachment, EmailAddress, MailAccount, MailFilter, MailIdentity, MailSession, MailSort, MailboxNode, MailboxRight, MailboxRights, MailboxRole, Message, Queued, Sent, ThreadDetail, ThreadPage, ThreadSummary, VacationResponse, } from './types.ts';
|
|
46
|
+
export type { Attachment, ChangedState, Draft, DraftAttachment, EmailAddress, MailAccount, MailFilter, MailIdentity, MailSession, MailSort, MailboxNode, MailboxRight, MailboxRights, MailboxRole, Message, Queued, Sent, Submission, SubmissionState, ThreadDetail, ThreadPage, ThreadSummary, VacationResponse, } from './types.ts';
|
package/dist/mailbox/index.js
CHANGED
|
@@ -14,7 +14,7 @@ export { search } from "./search.js";
|
|
|
14
14
|
export { identities } from "./identities.js";
|
|
15
15
|
export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardSubject, quoteText, replyDraft, replySubject, } from "./drafts.js";
|
|
16
16
|
export { quoteBoundary, splitQuoted } from "./quoted.js";
|
|
17
|
-
export { cancel, draftPatch, draftToEmail, queued, saveDraft, send, sentPatch } from "./submit.js";
|
|
17
|
+
export { cancel, draftPatch, draftToEmail, queued, resend, saveDraft, send, sentPatch, submissions, } from "./submit.js";
|
|
18
18
|
export { SNOOZED_MAILBOX, snoozeThread, wakeSnoozed } from "./snooze.js";
|
|
19
19
|
export { clearVacationResponse, setVacationResponse, vacationResponse } from "./vacation.js";
|
|
20
20
|
export { attach } from "./attach.js";
|
|
@@ -23,5 +23,5 @@ export { DEFAULT_MAX_DOWNLOAD_BYTES, downloadAttachment } from "./download.js";
|
|
|
23
23
|
export { push } from "./push.js";
|
|
24
24
|
export { activateSieveScript, deactivateSieveScripts, deleteSieveScript, saveSieveScript, sieveScriptText, sieveScripts, validateSieveScript, } from "./sieve.js";
|
|
25
25
|
export { findPrincipals, lookupPrincipal } from "./principals.js";
|
|
26
|
-
export { rulesToSieve, sieveToRules } from "./rules.js";
|
|
26
|
+
export { combineScript, isOurScript, rulesToSieve, sieveToRules, splitScript } from "./rules.js";
|
|
27
27
|
export { expandTemplate } from "./uri.js";
|
package/dist/mailbox/rules.d.ts
CHANGED
|
@@ -57,6 +57,42 @@ export type MailRule = {
|
|
|
57
57
|
* escaped, so no value can end the string early.
|
|
58
58
|
*/
|
|
59
59
|
export declare function rulesToSieve(rules: readonly MailRule[]): string;
|
|
60
|
+
/** The away reply kept in the same script as the rules. */
|
|
61
|
+
export type VacationSection = {
|
|
62
|
+
isEnabled: boolean;
|
|
63
|
+
audience: 'anyone' | 'company' | 'nobody';
|
|
64
|
+
/** The company domain, set by the caller; needed for `company`. */
|
|
65
|
+
domain: string | null;
|
|
66
|
+
fromDate: string | null;
|
|
67
|
+
toDate: string | null;
|
|
68
|
+
subject: string | null;
|
|
69
|
+
textBody: string | null;
|
|
70
|
+
htmlBody: string | null;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* One Sieve script holding the rules section and a marked vacation section.
|
|
74
|
+
* `rules` null leaves the rules section out; `vacation` null leaves the
|
|
75
|
+
* vacation section out; `combineScript(rules, null)` is `rulesToSieve(rules)`
|
|
76
|
+
* byte for byte, and `combineScript(null, null)` is `''`.
|
|
77
|
+
*
|
|
78
|
+
* Throws `invalidArguments` for a bad rule or a bad vacation value: a subject
|
|
79
|
+
* with a control character, or a text with one other than line breaks (which
|
|
80
|
+
* are written as CRLF).
|
|
81
|
+
*/
|
|
82
|
+
export declare function combineScript(rules: readonly MailRule[] | null, vacation: VacationSection | null): string;
|
|
83
|
+
/**
|
|
84
|
+
* The rules and vacation a script was combined from. Each part is rebuilt
|
|
85
|
+
* from its marker JSON alone and the whole script must equal the result;
|
|
86
|
+
* `null` for a hand-written or edited script. An empty string is
|
|
87
|
+
* `{ rules: null, vacation: null }`.
|
|
88
|
+
*/
|
|
89
|
+
export declare function splitScript(script: string): {
|
|
90
|
+
rules: MailRule[] | null;
|
|
91
|
+
vacation: VacationSection | null;
|
|
92
|
+
} | null;
|
|
93
|
+
/** True for an empty script and for one this module wrote unchanged; a caller
|
|
94
|
+
* refuses to write over a script for which this is false. */
|
|
95
|
+
export declare function isOurScript(text: string): boolean;
|
|
60
96
|
/**
|
|
61
97
|
* The rules a script was generated from, or `null` when `script` is not one
|
|
62
98
|
* {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
|
package/dist/mailbox/rules.js
CHANGED
|
@@ -146,7 +146,9 @@ const REQUIRE_ORDER = ['fileinto', 'mailbox', 'imap4flags', 'copy'];
|
|
|
146
146
|
* escaped, so no value can end the string early.
|
|
147
147
|
*/
|
|
148
148
|
export function rulesToSieve(rules) {
|
|
149
|
-
|
|
149
|
+
return combineScript(rules, null);
|
|
150
|
+
}
|
|
151
|
+
function compile(checked) {
|
|
150
152
|
const blocks = [];
|
|
151
153
|
const needs = new Set();
|
|
152
154
|
for (const rule of checked) {
|
|
@@ -161,31 +163,156 @@ export function rulesToSieve(rules) {
|
|
|
161
163
|
: `if ${rule.match === 'all' ? 'allof' : 'anyof'}(${tests.join(', ')}) {`;
|
|
162
164
|
blocks.push([head, ...lines.map((line) => ` ${line}`), '}'].join('\n'));
|
|
163
165
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
+
return { blocks, needs };
|
|
167
|
+
}
|
|
168
|
+
const VACATION_MARKER = '# wtfalch-vacation v1 ';
|
|
169
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}(?:$|[T ])/;
|
|
170
|
+
function nullableText(value, what, lineBreaks) {
|
|
171
|
+
if (value === null)
|
|
172
|
+
return null;
|
|
173
|
+
if (typeof value !== 'string')
|
|
174
|
+
return invalid(`${what} must be a string or null`);
|
|
175
|
+
const probe = lineBreaks ? value.replace(/[\r\n]/g, '') : value;
|
|
176
|
+
if (CONTROL.test(probe))
|
|
177
|
+
invalid(`${what} must not contain control characters`);
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
180
|
+
function checkDate(value, what) {
|
|
181
|
+
if (value === null)
|
|
182
|
+
return null;
|
|
183
|
+
if (typeof value !== 'string' || !ISO_DAY.test(value)) {
|
|
184
|
+
return invalid(`${what} must be an ISO date string or null`);
|
|
185
|
+
}
|
|
186
|
+
return value;
|
|
187
|
+
}
|
|
188
|
+
function checkVacation(value) {
|
|
189
|
+
const item = value;
|
|
190
|
+
if (typeof item !== 'object' || item === null)
|
|
191
|
+
invalid('the vacation must be an object');
|
|
192
|
+
if (typeof item.isEnabled !== 'boolean')
|
|
193
|
+
invalid('the vacation needs isEnabled to be true or false');
|
|
194
|
+
const audience = item.audience;
|
|
195
|
+
if (audience !== 'anyone' && audience !== 'company' && audience !== 'nobody') {
|
|
196
|
+
invalid('audience must be "anyone", "company" or "nobody"');
|
|
197
|
+
}
|
|
198
|
+
const domain = nullableText(item.domain, 'the domain', false);
|
|
199
|
+
if (audience === 'company' && item.isEnabled && (domain === null || domain.length === 0)) {
|
|
200
|
+
invalid('a company reply needs a domain');
|
|
201
|
+
}
|
|
202
|
+
return {
|
|
203
|
+
isEnabled: item.isEnabled,
|
|
204
|
+
audience,
|
|
205
|
+
domain,
|
|
206
|
+
fromDate: checkDate(item.fromDate, 'fromDate'),
|
|
207
|
+
toDate: checkDate(item.toDate, 'toDate'),
|
|
208
|
+
subject: nullableText(item.subject, 'the subject', false),
|
|
209
|
+
textBody: nullableText(item.textBody, 'the text', true),
|
|
210
|
+
htmlBody: nullableText(item.htmlBody, 'the html', true),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function vacationBlock(vacation) {
|
|
214
|
+
if (!vacation.isEnabled || vacation.audience === 'nobody')
|
|
215
|
+
return null;
|
|
216
|
+
const body = (vacation.textBody ?? '').replace(/\r\n|\r|\n/g, '\r\n');
|
|
217
|
+
const subject = vacation.subject === null ? '' : ` :subject ${quote(vacation.subject)}`;
|
|
218
|
+
const command = `vacation :days 1${subject} ${quote(body)};`;
|
|
219
|
+
const tests = [];
|
|
220
|
+
if (vacation.fromDate !== null) {
|
|
221
|
+
tests.push(`currentdate :value "ge" "date" ${quote(vacation.fromDate.slice(0, 10))}`);
|
|
222
|
+
}
|
|
223
|
+
if (vacation.toDate !== null) {
|
|
224
|
+
tests.push(`currentdate :value "le" "date" ${quote(vacation.toDate.slice(0, 10))}`);
|
|
225
|
+
}
|
|
226
|
+
if (vacation.audience === 'company') {
|
|
227
|
+
tests.push(`address :domain :is "from" ${quote(vacation.domain ?? '')}`);
|
|
228
|
+
}
|
|
229
|
+
if (tests.length === 0)
|
|
230
|
+
return command;
|
|
231
|
+
const head = tests.length === 1 ? `if ${tests[0]} {` : `if allof(${tests.join(', ')}) {`;
|
|
232
|
+
return `${head}\n ${command}\n}`;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* One Sieve script holding the rules section and a marked vacation section.
|
|
236
|
+
* `rules` null leaves the rules section out; `vacation` null leaves the
|
|
237
|
+
* vacation section out; `combineScript(rules, null)` is `rulesToSieve(rules)`
|
|
238
|
+
* byte for byte, and `combineScript(null, null)` is `''`.
|
|
239
|
+
*
|
|
240
|
+
* Throws `invalidArguments` for a bad rule or a bad vacation value: a subject
|
|
241
|
+
* with a control character, or a text with one other than line breaks (which
|
|
242
|
+
* are written as CRLF).
|
|
243
|
+
*/
|
|
244
|
+
export function combineScript(rules, vacation) {
|
|
245
|
+
const checked = rules === null ? null : checkRules(rules);
|
|
246
|
+
const section = vacation === null ? null : checkVacation(vacation);
|
|
247
|
+
const { blocks, needs } = compile(checked ?? []);
|
|
248
|
+
const block = section === null ? null : vacationBlock(section);
|
|
249
|
+
if (block !== null)
|
|
250
|
+
needs.add('vacation');
|
|
251
|
+
if (section !== null && (section.fromDate !== null || section.toDate !== null)) {
|
|
252
|
+
needs.add('date').add('relational');
|
|
253
|
+
}
|
|
254
|
+
const required = [...REQUIRE_ORDER, 'vacation', 'date', 'relational'].filter((name) => needs.has(name));
|
|
255
|
+
const parts = [];
|
|
256
|
+
if (checked !== null)
|
|
257
|
+
parts.push(`${MARKER}${JSON.stringify(checked)}`);
|
|
166
258
|
if (required.length > 0)
|
|
167
259
|
parts.push(`require [${required.map(quote).join(', ')}];`);
|
|
168
260
|
parts.push(...blocks);
|
|
169
|
-
|
|
261
|
+
if (section !== null) {
|
|
262
|
+
parts.push(`${VACATION_MARKER}${JSON.stringify(section)}`);
|
|
263
|
+
if (block !== null)
|
|
264
|
+
parts.push(block);
|
|
265
|
+
}
|
|
266
|
+
return parts.length === 0 ? '' : `${parts.join('\n')}\n`;
|
|
170
267
|
}
|
|
171
|
-
|
|
172
|
-
* The rules a script was generated from, or `null` when `script` is not one
|
|
173
|
-
* {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
|
|
174
|
-
* parse as rules, or a body that differs from what the generator writes for
|
|
175
|
-
* them.
|
|
176
|
-
*/
|
|
177
|
-
export function sieveToRules(script) {
|
|
178
|
-
const first = script.split('\n', 1)[0] ?? '';
|
|
179
|
-
if (!first.startsWith(MARKER))
|
|
180
|
-
return null;
|
|
181
|
-
let rules;
|
|
268
|
+
function parseMarker(line, marker, check) {
|
|
182
269
|
try {
|
|
183
|
-
|
|
270
|
+
return check(JSON.parse(line.slice(marker.length)));
|
|
184
271
|
}
|
|
185
272
|
catch (error) {
|
|
186
273
|
if (error instanceof MailError || error instanceof SyntaxError)
|
|
187
274
|
return null;
|
|
188
275
|
throw error;
|
|
189
276
|
}
|
|
190
|
-
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* The rules and vacation a script was combined from. Each part is rebuilt
|
|
280
|
+
* from its marker JSON alone and the whole script must equal the result;
|
|
281
|
+
* `null` for a hand-written or edited script. An empty string is
|
|
282
|
+
* `{ rules: null, vacation: null }`.
|
|
283
|
+
*/
|
|
284
|
+
export function splitScript(script) {
|
|
285
|
+
if (script === '')
|
|
286
|
+
return { rules: null, vacation: null };
|
|
287
|
+
const lines = script.split('\n');
|
|
288
|
+
let rules = null;
|
|
289
|
+
if (lines[0]?.startsWith(MARKER)) {
|
|
290
|
+
rules = parseMarker(lines[0], MARKER, checkRules);
|
|
291
|
+
if (rules === null)
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
if (combineScript(rules, null) === script)
|
|
295
|
+
return rules === null ? null : { rules, vacation: null };
|
|
296
|
+
for (const line of lines) {
|
|
297
|
+
if (!line.startsWith(VACATION_MARKER))
|
|
298
|
+
continue;
|
|
299
|
+
const vacation = parseMarker(line, VACATION_MARKER, checkVacation);
|
|
300
|
+
if (vacation !== null && combineScript(rules, vacation) === script)
|
|
301
|
+
return { rules, vacation };
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
/** True for an empty script and for one this module wrote unchanged; a caller
|
|
306
|
+
* refuses to write over a script for which this is false. */
|
|
307
|
+
export function isOurScript(text) {
|
|
308
|
+
return splitScript(text) !== null;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The rules a script was generated from, or `null` when `script` is not one
|
|
312
|
+
* {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
|
|
313
|
+
* parse as rules, or a body that differs from what the generator writes for
|
|
314
|
+
* them.
|
|
315
|
+
*/
|
|
316
|
+
export function sieveToRules(script) {
|
|
317
|
+
return splitScript(script)?.rules ?? null;
|
|
191
318
|
}
|
package/dist/mailbox/submit.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type MailClient } from './client.ts';
|
|
2
|
-
import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent } from './types.ts';
|
|
2
|
+
import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent, Submission, SubmissionState } from './types.ts';
|
|
3
3
|
/**
|
|
4
4
|
* The JMAP `Email` object a draft becomes. Exported so the shape can be
|
|
5
5
|
* asserted without a server.
|
|
@@ -147,3 +147,22 @@ export declare function cancel(client: MailClient, sent: Pick<Sent, 'submissionI
|
|
|
147
147
|
* `12:00:00Z`.
|
|
148
148
|
*/
|
|
149
149
|
export declare function queued(client: MailClient): Promise<Queued[]>;
|
|
150
|
+
/**
|
|
151
|
+
* Sent mail with its delivery state, newest `sendAt` first.
|
|
152
|
+
*
|
|
153
|
+
* JMAP's `EmailSubmission` carries no subject, recipients, sent time or
|
|
154
|
+
* failure text: `subject` and `to` come from one `Email/get`, `failure` from
|
|
155
|
+
* the recipient's `deliveryStatus.smtpReply`, and `sentAt` is `sendAt` once
|
|
156
|
+
* the hold has passed. One query per needed `undoStatus`, each filtered on it
|
|
157
|
+
* for the reason given above `queued()`.
|
|
158
|
+
*/
|
|
159
|
+
export declare function submissions(client: MailClient, options?: {
|
|
160
|
+
states?: SubmissionState[];
|
|
161
|
+
limit?: number;
|
|
162
|
+
}): Promise<Submission[]>;
|
|
163
|
+
/**
|
|
164
|
+
* Send a message that is already in Sent again, as a new submission with the
|
|
165
|
+
* identity whose address matches the message's From. Nothing is filed: no
|
|
166
|
+
* `onSuccessUpdateEmail`, so the message keeps its mailbox and keywords.
|
|
167
|
+
*/
|
|
168
|
+
export declare function resend(client: MailClient, submission: Pick<Submission, 'emailId'>): Promise<Sent>;
|
package/dist/mailbox/submit.js
CHANGED
|
@@ -461,3 +461,128 @@ export async function queued(client) {
|
|
|
461
461
|
.sort((a, b) => Date.parse(a.sendAt) - Date.parse(b.sendAt));
|
|
462
462
|
});
|
|
463
463
|
}
|
|
464
|
+
const SUBMISSION_LIMIT = 100;
|
|
465
|
+
const UNDO_FOR_STATE = {
|
|
466
|
+
scheduled: 'pending',
|
|
467
|
+
sending: 'final',
|
|
468
|
+
delivered: 'final',
|
|
469
|
+
failed: 'final',
|
|
470
|
+
canceled: 'canceled',
|
|
471
|
+
};
|
|
472
|
+
function submissionState(record) {
|
|
473
|
+
if (record.undoStatus === 'canceled')
|
|
474
|
+
return { state: 'canceled', failure: null };
|
|
475
|
+
if (record.undoStatus === 'pending')
|
|
476
|
+
return { state: 'scheduled', failure: null };
|
|
477
|
+
const entries = Object.values(record.deliveryStatus ?? {});
|
|
478
|
+
const refused = entries.find((entry) => entry.delivered === 'no');
|
|
479
|
+
if (refused) {
|
|
480
|
+
return { state: 'failed', failure: refused.smtpReply || 'the server refused delivery' };
|
|
481
|
+
}
|
|
482
|
+
if (entries.length === 0 || entries.some((entry) => entry.delivered !== 'yes')) {
|
|
483
|
+
return { state: 'sending', failure: null };
|
|
484
|
+
}
|
|
485
|
+
return { state: 'delivered', failure: null };
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Sent mail with its delivery state, newest `sendAt` first.
|
|
489
|
+
*
|
|
490
|
+
* JMAP's `EmailSubmission` carries no subject, recipients, sent time or
|
|
491
|
+
* failure text: `subject` and `to` come from one `Email/get`, `failure` from
|
|
492
|
+
* the recipient's `deliveryStatus.smtpReply`, and `sentAt` is `sendAt` once
|
|
493
|
+
* the hold has passed. One query per needed `undoStatus`, each filtered on it
|
|
494
|
+
* for the reason given above `queued()`.
|
|
495
|
+
*/
|
|
496
|
+
export async function submissions(client, options = {}) {
|
|
497
|
+
const limit = options.limit ?? SUBMISSION_LIMIT;
|
|
498
|
+
if (!Number.isInteger(limit) || limit < 0) {
|
|
499
|
+
throw new MailError('limit must be a non-negative integer', {
|
|
500
|
+
type: 'invalidArguments',
|
|
501
|
+
operation: 'submissions',
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
const wanted = options.states ? new Set(options.states) : null;
|
|
505
|
+
const undoStatuses = [
|
|
506
|
+
...new Set((wanted ? [...wanted] : Object.keys(UNDO_FOR_STATE)).map((state) => UNDO_FOR_STATE[state])),
|
|
507
|
+
];
|
|
508
|
+
const { jam, accountId } = await client.connect();
|
|
509
|
+
return guard('submissions', async () => {
|
|
510
|
+
const lists = await Promise.all(undoStatuses.map(async (undoStatus) => {
|
|
511
|
+
const [results] = await jam.requestMany((t) => {
|
|
512
|
+
const query = t.EmailSubmission.query({
|
|
513
|
+
accountId,
|
|
514
|
+
filter: { undoStatus },
|
|
515
|
+
});
|
|
516
|
+
const got = t.EmailSubmission.get({ accountId, ids: query.$ref('/ids') });
|
|
517
|
+
return { query, got };
|
|
518
|
+
}, JAM_FETCH);
|
|
519
|
+
return results.got.list;
|
|
520
|
+
}));
|
|
521
|
+
const rows = lists
|
|
522
|
+
.flat()
|
|
523
|
+
.map((record) => ({ record, ...submissionState(record) }))
|
|
524
|
+
.filter((row) => !wanted || wanted.has(row.state))
|
|
525
|
+
.sort((a, b) => Date.parse(b.record.sendAt) - Date.parse(a.record.sendAt))
|
|
526
|
+
.slice(0, limit);
|
|
527
|
+
if (rows.length === 0)
|
|
528
|
+
return [];
|
|
529
|
+
const emailIds = [...new Set(rows.map((row) => row.record.emailId))];
|
|
530
|
+
const [fetched] = await jam.api.Email.get({ accountId, ids: emailIds, properties: ['subject', 'to', 'from'] }, JAM_FETCH);
|
|
531
|
+
const emails = new Map(fetched.list.map((email) => [email.id, email]));
|
|
532
|
+
return rows.map(({ record, state, failure }) => {
|
|
533
|
+
const email = emails.get(record.emailId);
|
|
534
|
+
return {
|
|
535
|
+
submissionId: record.id,
|
|
536
|
+
emailId: record.emailId,
|
|
537
|
+
threadId: record.threadId,
|
|
538
|
+
sendAt: record.sendAt,
|
|
539
|
+
sentAt: state === 'scheduled' || state === 'canceled' ? null : record.sendAt,
|
|
540
|
+
to: email?.to ?? [],
|
|
541
|
+
subject: email?.subject ?? '',
|
|
542
|
+
state,
|
|
543
|
+
failure,
|
|
544
|
+
};
|
|
545
|
+
});
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Send a message that is already in Sent again, as a new submission with the
|
|
550
|
+
* identity whose address matches the message's From. Nothing is filed: no
|
|
551
|
+
* `onSuccessUpdateEmail`, so the message keeps its mailbox and keywords.
|
|
552
|
+
*/
|
|
553
|
+
export async function resend(client, submission) {
|
|
554
|
+
const { jam, accountId } = await client.connect();
|
|
555
|
+
const { emailId } = submission;
|
|
556
|
+
return guard('resend', async () => {
|
|
557
|
+
const [got] = await jam.api.Email.get({ accountId, ids: [emailId], properties: ['from', 'threadId'] }, JAM_FETCH);
|
|
558
|
+
const email = got.list[0];
|
|
559
|
+
if (!email) {
|
|
560
|
+
throw new MailError(`no message ${emailId} to send again`, {
|
|
561
|
+
type: 'notFound',
|
|
562
|
+
operation: 'resend',
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
const address = email.from?.[0]?.email.toLowerCase();
|
|
566
|
+
const identity = (await identities(client)).find((one) => one.email.toLowerCase() === address);
|
|
567
|
+
if (!identity) {
|
|
568
|
+
throw new MailError(`no identity matches the From address of message ${emailId}`, {
|
|
569
|
+
type: 'notFound',
|
|
570
|
+
operation: 'resend',
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
const [submitted] = await jam.api.EmailSubmission.set({
|
|
574
|
+
accountId,
|
|
575
|
+
create: { submission: { identityId: identity.id, emailId } },
|
|
576
|
+
}, { using: ['urn:ietf:params:jmap:mail'], ...JAM_FETCH });
|
|
577
|
+
const created = submitted.created?.submission;
|
|
578
|
+
if (!created)
|
|
579
|
+
failed('submission', submitted.notCreated);
|
|
580
|
+
return {
|
|
581
|
+
submissionId: created.id,
|
|
582
|
+
emailId,
|
|
583
|
+
threadId: email.threadId,
|
|
584
|
+
undoStatus: created.undoStatus,
|
|
585
|
+
sendAt: created.sendAt,
|
|
586
|
+
};
|
|
587
|
+
});
|
|
588
|
+
}
|
package/dist/mailbox/types.d.ts
CHANGED
|
@@ -289,6 +289,9 @@ export type Queued = {
|
|
|
289
289
|
* fields left to the server's own defaults. */
|
|
290
290
|
export type VacationResponse = {
|
|
291
291
|
isEnabled: boolean;
|
|
292
|
+
/** Who gets the reply: anyone, senders in the account's own domain, or
|
|
293
|
+
* nobody (the dates and text are kept, no reply is sent). */
|
|
294
|
+
audience: 'anyone' | 'company' | 'nobody';
|
|
292
295
|
/** The response starts here, or immediately when `null`. ISO 8601 UTC. */
|
|
293
296
|
fromDate: string | null;
|
|
294
297
|
/** The response ends here, or never when `null`. ISO 8601 UTC. */
|
|
@@ -338,3 +341,19 @@ export type MailSort = {
|
|
|
338
341
|
property: 'receivedAt' | 'sentAt' | 'size' | 'subject' | 'from' | 'to';
|
|
339
342
|
isAscending?: boolean;
|
|
340
343
|
};
|
|
344
|
+
export type SubmissionState = 'scheduled' | 'sending' | 'delivered' | 'failed' | 'canceled';
|
|
345
|
+
/** One row of `submissions()`: a sent message and where its delivery stands. */
|
|
346
|
+
export type Submission = {
|
|
347
|
+
submissionId: string;
|
|
348
|
+
emailId: string;
|
|
349
|
+
threadId: string;
|
|
350
|
+
sendAt: string;
|
|
351
|
+
/** `sendAt` once the hold has passed (JMAP has no separate sent time);
|
|
352
|
+
* `null` while `scheduled` or once `canceled`. */
|
|
353
|
+
sentAt: string | null;
|
|
354
|
+
to: readonly EmailAddress[];
|
|
355
|
+
subject: string;
|
|
356
|
+
state: SubmissionState;
|
|
357
|
+
/** The first refusing recipient's `smtpReply`, only when `failed`. */
|
|
358
|
+
failure: string | null;
|
|
359
|
+
};
|
|
@@ -15,6 +15,10 @@ export type VacationResponseOptions = {
|
|
|
15
15
|
subject?: string | null;
|
|
16
16
|
textBody?: string | null;
|
|
17
17
|
htmlBody?: string | null;
|
|
18
|
+
/** Who gets the reply: `anyone`, `company` (senders in the account's own
|
|
19
|
+
* domain) or `nobody` (dates and text kept, no reply). `undefined` leaves
|
|
20
|
+
* it as stored; a new away reply starts at `anyone`. */
|
|
21
|
+
audience?: 'anyone' | 'company' | 'nobody';
|
|
18
22
|
};
|
|
19
23
|
/**
|
|
20
24
|
* Set the vacation response: whether it is on, its window, and its message.
|