@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
|
@@ -1,1284 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A mailbox in memory, and the JMAP that answers questions about it.
|
|
3
|
-
*
|
|
4
|
-
* **A fake transport, not a fake API.** The obvious shortcut is to stub the
|
|
5
|
-
* exported functions -- `mailboxes()` returns three objects, `listThreads()`
|
|
6
|
-
* returns five rows -- and it is the wrong one: every story then exercises the
|
|
7
|
-
* stub, and the four-call chain, the result references, the body-value
|
|
8
|
-
* resolution and the null-handling that make up most of this package are
|
|
9
|
-
* never run. This answers JMAP instead, so a component drawn against the fake
|
|
10
|
-
* is drawn through exactly the code that will face a real server.
|
|
11
|
-
*
|
|
12
|
-
* It implements only the methods this package sends. Anything else answers
|
|
13
|
-
* `unknownMethod`, which is what a real server does and what the error path
|
|
14
|
-
* expects.
|
|
15
|
-
*/
|
|
16
|
-
/** The fake models a single account, so its own `myRights` on its own
|
|
17
|
-
* mailboxes are always every right, granted -- there is no second login
|
|
18
|
-
* here for `shareWith` to matter *to*. What `shareMailbox`/`unshareMailbox`
|
|
19
|
-
* exercise is what this account grants to OTHER accounts, which is
|
|
20
|
-
* `shareWith`, not `myRights`. */
|
|
21
|
-
const OWNER_RIGHTS = {
|
|
22
|
-
mayReadItems: true,
|
|
23
|
-
mayAddItems: true,
|
|
24
|
-
mayRemoveItems: true,
|
|
25
|
-
maySetSeen: true,
|
|
26
|
-
maySetKeywords: true,
|
|
27
|
-
mayCreateChild: true,
|
|
28
|
-
mayRename: true,
|
|
29
|
-
maySubmit: true,
|
|
30
|
-
mayDelete: true,
|
|
31
|
-
mayShare: true,
|
|
32
|
-
};
|
|
33
|
-
const ACCOUNT = 'fake-account';
|
|
34
|
-
/** Stalwart's five, with its names and Stalwart's uniform sortOrder of 0 --
|
|
35
|
-
* which is what makes a real tree come out alphabetical. Copied fresh into
|
|
36
|
-
* each instance's `#boxes`, never held here: a rename must not leak from
|
|
37
|
-
* one test's fake into the next. */
|
|
38
|
-
const MAILBOXES = [
|
|
39
|
-
{ id: 'mb-inbox', name: 'Inbox', role: 'inbox' },
|
|
40
|
-
{ id: 'mb-drafts', name: 'Drafts', role: 'drafts' },
|
|
41
|
-
{ id: 'mb-sent', name: 'Sent Items', role: 'sent' },
|
|
42
|
-
{ id: 'mb-junk', name: 'Junk Mail', role: 'junk' },
|
|
43
|
-
{ id: 'mb-trash', name: 'Deleted Items', role: 'trash' },
|
|
44
|
-
];
|
|
45
|
-
/** Stalwart's default for both limits, as `fixtures/instance-one.json` has it. */
|
|
46
|
-
const STALWART_MAX_SIZE = 50_000_000;
|
|
47
|
-
/** A UTC instant the way a JMAP server writes one. RFC 8620 §1.4 requires the
|
|
48
|
-
* fractional part to be **omitted when it is zero**, which
|
|
49
|
-
* `Date.prototype.toISOString()` never does -- it always pads three digits.
|
|
50
|
-
* A fake that only ever emits `.000` hides every bug that depends on a real
|
|
51
|
-
* server's mixed precision, so it emits the spec's shape instead. */
|
|
52
|
-
function jmapDate(at) {
|
|
53
|
-
return at.toISOString().replace(/\.000Z$/, 'Z');
|
|
54
|
-
}
|
|
55
|
-
export class FakeMailbox {
|
|
56
|
-
me;
|
|
57
|
-
/** The fake's clock. Fixed at construction and moved only by `advance()`
|
|
58
|
-
* -- never a wall-clock read, so a cancel-window test stays
|
|
59
|
-
* deterministic. */
|
|
60
|
-
#now;
|
|
61
|
-
#latency;
|
|
62
|
-
#maxSizeUpload;
|
|
63
|
-
#emails = [];
|
|
64
|
-
/** Every mailbox: Stalwart's fixed five, then whatever `Mailbox/set` made.
|
|
65
|
-
* A fresh copy per instance -- see `MAILBOXES`'s note on why. */
|
|
66
|
-
#boxes;
|
|
67
|
-
#threads = new Map();
|
|
68
|
-
#counter = 0;
|
|
69
|
-
/** Everything `EmailSubmission/set` accepted, for a test that asserts a
|
|
70
|
-
* message was actually sent rather than only composed. */
|
|
71
|
-
submissions = [];
|
|
72
|
-
/** Each submission's send-hold state, keyed by its id -- what the update
|
|
73
|
-
* (cancel) path needs to know that the flat `submissions` list above,
|
|
74
|
-
* kept only for the tests above, does not carry. */
|
|
75
|
-
#submissionState = new Map();
|
|
76
|
-
/** Every blob uploaded, for a test that asserts the bytes reached the
|
|
77
|
-
* server rather than only the composer. */
|
|
78
|
-
uploads = [];
|
|
79
|
-
/** RFC 8621 §8's singleton, `id: 'singleton'` always -- there is no create
|
|
80
|
-
* or destroy for it, only the one object every account starts with, off
|
|
81
|
-
* and empty. */
|
|
82
|
-
#vacation = {
|
|
83
|
-
isEnabled: false,
|
|
84
|
-
fromDate: null,
|
|
85
|
-
toDate: null,
|
|
86
|
-
subject: null,
|
|
87
|
-
textBody: null,
|
|
88
|
-
htmlBody: null,
|
|
89
|
-
};
|
|
90
|
-
/** An uploaded blob's actual bytes, as text, keyed by the id `uploads`
|
|
91
|
-
* also records. Nothing else in this fake stores content -- an
|
|
92
|
-
* attachment's synthetic blobId (`add()`, above) is never a key here, so
|
|
93
|
-
* `/jmap/download/` falls back to its fixed stub for those, unchanged.
|
|
94
|
-
* Sieve scripts read back what was uploaded, and a body part derived
|
|
95
|
-
* from a `bodyStructure` create (`#deriveBodyParts`) stores its bytes
|
|
96
|
-
* here too, so an iMIP part downloads as what was sent. */
|
|
97
|
-
#blobContents = new Map();
|
|
98
|
-
/** `SieveScript` objects: `{id, name, blobId}` triples, `isActive` derived
|
|
99
|
-
* from `#activeSieveScriptId` -- the same shape `SieveProperty` has on the
|
|
100
|
-
* real server (`jmap-proto/src/object/sieve.rs:19-24`). */
|
|
101
|
-
#principals;
|
|
102
|
-
#sieveScripts = [];
|
|
103
|
-
#activeSieveScriptId = null;
|
|
104
|
-
constructor(options = {}) {
|
|
105
|
-
this.me = options.me ?? { name: 'Ada Lovelace', email: 'ada@example.com' };
|
|
106
|
-
this.#now = options.now ?? new Date('2026-09-07T12:00:00Z');
|
|
107
|
-
this.#latency = options.latency ?? 0;
|
|
108
|
-
this.#maxSizeUpload = options.maxSizeUpload ?? STALWART_MAX_SIZE;
|
|
109
|
-
this.#principals = options.principals ?? [];
|
|
110
|
-
this.#boxes = MAILBOXES.map((box) => ({
|
|
111
|
-
id: box.id,
|
|
112
|
-
name: box.name,
|
|
113
|
-
parentId: null,
|
|
114
|
-
role: box.role,
|
|
115
|
-
sortOrder: 0,
|
|
116
|
-
isSubscribed: true,
|
|
117
|
-
shareWith: {},
|
|
118
|
-
}));
|
|
119
|
-
for (const seed of options.threads ?? [])
|
|
120
|
-
this.add(seed);
|
|
121
|
-
}
|
|
122
|
-
/** Move the fake's clock forward by `ms` milliseconds. The only way `#now`
|
|
123
|
-
* changes after construction, so a test can hold a submission, advance
|
|
124
|
-
* past its `sendAt`, and see the cancel window close -- deterministically,
|
|
125
|
-
* with no real wait and no wall-clock read. */
|
|
126
|
-
advance(ms) {
|
|
127
|
-
this.#now = new Date(this.#now.getTime() + ms);
|
|
128
|
-
}
|
|
129
|
-
/** Put a thread in the mailbox. Returns its id. */
|
|
130
|
-
add(seed) {
|
|
131
|
-
const threadId = `t${++this.#counter}`;
|
|
132
|
-
const ids = [];
|
|
133
|
-
for (const message of seed.messages) {
|
|
134
|
-
const id = `e${++this.#counter}`;
|
|
135
|
-
const at = new Date(this.#now.getTime() - seed.messages.indexOf(message) * 0);
|
|
136
|
-
const receivedAt = new Date(this.#now.getTime() - message.agoMinutes * 60_000).toISOString();
|
|
137
|
-
const attachments = (message.attachments ?? []).map((file, index) => ({
|
|
138
|
-
partId: `a${index}`,
|
|
139
|
-
blobId: `blob-${id}-${index}`,
|
|
140
|
-
size: file.size,
|
|
141
|
-
name: file.name,
|
|
142
|
-
type: file.type,
|
|
143
|
-
disposition: 'attachment',
|
|
144
|
-
cid: null,
|
|
145
|
-
}));
|
|
146
|
-
const textPart = {
|
|
147
|
-
partId: 't',
|
|
148
|
-
blobId: `blob-${id}-t`,
|
|
149
|
-
size: message.text.length,
|
|
150
|
-
name: null,
|
|
151
|
-
type: 'text/plain',
|
|
152
|
-
charset: 'UTF-8',
|
|
153
|
-
disposition: null,
|
|
154
|
-
cid: null,
|
|
155
|
-
};
|
|
156
|
-
const htmlPart = {
|
|
157
|
-
partId: 'h',
|
|
158
|
-
blobId: `blob-${id}-h`,
|
|
159
|
-
size: message.html?.length ?? 0,
|
|
160
|
-
name: null,
|
|
161
|
-
type: 'text/html',
|
|
162
|
-
charset: 'UTF-8',
|
|
163
|
-
disposition: null,
|
|
164
|
-
cid: null,
|
|
165
|
-
};
|
|
166
|
-
this.#emails.push({
|
|
167
|
-
id,
|
|
168
|
-
blobId: `blob-${id}`,
|
|
169
|
-
threadId,
|
|
170
|
-
mailboxIds: { [seed.mailbox]: true },
|
|
171
|
-
keywords: {
|
|
172
|
-
...(message.seen ? { $seen: true } : {}),
|
|
173
|
-
...(message.flagged ? { $flagged: true } : {}),
|
|
174
|
-
},
|
|
175
|
-
size: message.text.length + 400,
|
|
176
|
-
receivedAt,
|
|
177
|
-
sentAt: receivedAt,
|
|
178
|
-
messageId: [`${id}@example.com`],
|
|
179
|
-
inReplyTo: null,
|
|
180
|
-
references: null,
|
|
181
|
-
from: [message.from],
|
|
182
|
-
to: message.to ?? [this.me],
|
|
183
|
-
cc: null,
|
|
184
|
-
bcc: null,
|
|
185
|
-
replyTo: null,
|
|
186
|
-
subject: message.subject,
|
|
187
|
-
preview: message.text.slice(0, 80),
|
|
188
|
-
hasAttachment: attachments.length > 0,
|
|
189
|
-
/* Each list falls back to the other's part, as RFC 8621 §4.1.4 has a
|
|
190
|
-
server do: an HTML-only message lists its HTML in `textBody` too,
|
|
191
|
-
and a plain one its text in `htmlBody`. A fake that kept them apart
|
|
192
|
-
would let a client that confuses the two pass every test. */
|
|
193
|
-
textBody: [message.text || !message.html ? textPart : htmlPart],
|
|
194
|
-
htmlBody: [message.html ? htmlPart : textPart],
|
|
195
|
-
attachments,
|
|
196
|
-
bodyValues: {
|
|
197
|
-
t: { value: message.text, isEncodingProblem: false, isTruncated: false },
|
|
198
|
-
...(message.html
|
|
199
|
-
? { h: { value: message.html, isEncodingProblem: false, isTruncated: false } }
|
|
200
|
-
: {}),
|
|
201
|
-
},
|
|
202
|
-
_at: at,
|
|
203
|
-
});
|
|
204
|
-
ids.push(id);
|
|
205
|
-
}
|
|
206
|
-
this.#threads.set(threadId, ids);
|
|
207
|
-
return threadId;
|
|
208
|
-
}
|
|
209
|
-
/** RFC 8621 §2 on `name`: "There MUST NOT be two sibling Mailboxes with
|
|
210
|
-
* both the same parent and the same name." `excludeId` leaves a
|
|
211
|
-
* mailbox's own current record out, so renaming it to the name it
|
|
212
|
-
* already has is never a collision with itself. */
|
|
213
|
-
#nameCollides(parentId, name, excludeId) {
|
|
214
|
-
return this.#boxes.some((existing) => existing.id !== excludeId && existing.parentId === parentId && existing.name === name);
|
|
215
|
-
}
|
|
216
|
-
#mailboxes() {
|
|
217
|
-
return this.#boxes.map((box) => {
|
|
218
|
-
const inBox = this.#emails.filter((email) => email.mailboxIds[box.id]);
|
|
219
|
-
const unread = inBox.filter((email) => !email.keywords.$seen);
|
|
220
|
-
const threads = new Set(inBox.map((email) => email.threadId));
|
|
221
|
-
const unreadThreads = new Set(unread.map((email) => email.threadId));
|
|
222
|
-
return {
|
|
223
|
-
id: box.id,
|
|
224
|
-
name: box.name,
|
|
225
|
-
parentId: box.parentId,
|
|
226
|
-
role: box.role,
|
|
227
|
-
sortOrder: box.sortOrder,
|
|
228
|
-
totalEmails: inBox.length,
|
|
229
|
-
unreadEmails: unread.length,
|
|
230
|
-
totalThreads: threads.size,
|
|
231
|
-
unreadThreads: unreadThreads.size,
|
|
232
|
-
isSubscribed: box.isSubscribed,
|
|
233
|
-
myRights: OWNER_RIGHTS,
|
|
234
|
-
shareWith: box.shareWith,
|
|
235
|
-
};
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
/** The session document, as Stalwart writes it. */
|
|
239
|
-
session(origin = 'https://email.example.com') {
|
|
240
|
-
return {
|
|
241
|
-
capabilities: {
|
|
242
|
-
'urn:ietf:params:jmap:core': { maxSizeUpload: this.#maxSizeUpload },
|
|
243
|
-
'urn:ietf:params:jmap:mail': {},
|
|
244
|
-
'urn:ietf:params:jmap:submission': {},
|
|
245
|
-
'urn:ietf:params:jmap:vacationresponse': {},
|
|
246
|
-
'urn:ietf:params:jmap:sieve': {},
|
|
247
|
-
'urn:ietf:params:jmap:principals': {},
|
|
248
|
-
},
|
|
249
|
-
accounts: {
|
|
250
|
-
[ACCOUNT]: {
|
|
251
|
-
name: this.me.email,
|
|
252
|
-
isPersonal: true,
|
|
253
|
-
isReadOnly: false,
|
|
254
|
-
accountCapabilities: {
|
|
255
|
-
'urn:ietf:params:jmap:mail': { maxSizeAttachmentsPerEmail: STALWART_MAX_SIZE },
|
|
256
|
-
'urn:ietf:params:jmap:submission': {},
|
|
257
|
-
'urn:ietf:params:jmap:vacationresponse': {},
|
|
258
|
-
'urn:ietf:params:jmap:sieve': {},
|
|
259
|
-
},
|
|
260
|
-
},
|
|
261
|
-
},
|
|
262
|
-
primaryAccounts: {
|
|
263
|
-
'urn:ietf:params:jmap:mail': ACCOUNT,
|
|
264
|
-
'urn:ietf:params:jmap:submission': ACCOUNT,
|
|
265
|
-
},
|
|
266
|
-
username: this.me.email,
|
|
267
|
-
apiUrl: `${origin}/jmap/`,
|
|
268
|
-
downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?accept={type}`,
|
|
269
|
-
uploadUrl: `${origin}/jmap/upload/{accountId}/`,
|
|
270
|
-
eventSourceUrl: `${origin}/jmap/eventsource/?types={types}&closeafter={closeafter}&ping={ping}`,
|
|
271
|
-
state: 'fake-session',
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
/** Answer one method call. Exported for the transport, and for a test that
|
|
275
|
-
* wants to assert on a single call's arguments. */
|
|
276
|
-
call(method, args) {
|
|
277
|
-
switch (method) {
|
|
278
|
-
case 'Mailbox/get':
|
|
279
|
-
return { accountId: ACCOUNT, state: 'm1', list: this.#mailboxes(), notFound: [] };
|
|
280
|
-
case 'Mailbox/set': {
|
|
281
|
-
const create = (args.create ?? {});
|
|
282
|
-
const created = {};
|
|
283
|
-
const notCreated = {};
|
|
284
|
-
for (const [key, box] of Object.entries(create)) {
|
|
285
|
-
if (typeof box.name !== 'string' || box.name.length === 0) {
|
|
286
|
-
notCreated[key] = {
|
|
287
|
-
type: 'invalidProperties',
|
|
288
|
-
properties: ['name'],
|
|
289
|
-
description: 'a mailbox needs a name',
|
|
290
|
-
};
|
|
291
|
-
continue;
|
|
292
|
-
}
|
|
293
|
-
const parentId = box.parentId ?? null;
|
|
294
|
-
if (parentId !== null && !this.#boxes.some((existing) => existing.id === parentId)) {
|
|
295
|
-
notCreated[key] = {
|
|
296
|
-
type: 'invalidProperties',
|
|
297
|
-
properties: ['parentId'],
|
|
298
|
-
description: `no mailbox ${parentId} to nest under`,
|
|
299
|
-
};
|
|
300
|
-
continue;
|
|
301
|
-
}
|
|
302
|
-
if (this.#nameCollides(parentId, box.name)) {
|
|
303
|
-
notCreated[key] = {
|
|
304
|
-
type: 'invalidProperties',
|
|
305
|
-
properties: ['name'],
|
|
306
|
-
description: `a mailbox named "${box.name}" already exists at that level`,
|
|
307
|
-
};
|
|
308
|
-
continue;
|
|
309
|
-
}
|
|
310
|
-
const id = `mb${++this.#counter}`;
|
|
311
|
-
this.#boxes.push({
|
|
312
|
-
id,
|
|
313
|
-
name: box.name,
|
|
314
|
-
parentId,
|
|
315
|
-
role: box.role ?? null,
|
|
316
|
-
sortOrder: 0,
|
|
317
|
-
isSubscribed: true,
|
|
318
|
-
shareWith: {},
|
|
319
|
-
});
|
|
320
|
-
created[key] = { id };
|
|
321
|
-
}
|
|
322
|
-
// Rename, for `renameMailbox`, and a `shareWith/<accountId>` grant
|
|
323
|
-
// or revoke, for `shareMailbox`/`unshareMailbox` -- the same patch
|
|
324
|
-
// key shape `Email/set` already handles for `mailboxIds/<id>` and
|
|
325
|
-
// `keywords/<name>` below, applied to one account's rights instead:
|
|
326
|
-
// a plain object replaces that one account's whole grant, and
|
|
327
|
-
// `null` deletes it, leaving every other account's grant alone.
|
|
328
|
-
const update = (args.update ?? {});
|
|
329
|
-
const updated = {};
|
|
330
|
-
const notUpdated = {};
|
|
331
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
332
|
-
const box = this.#boxes.find((existing) => existing.id === id);
|
|
333
|
-
if (!box) {
|
|
334
|
-
notUpdated[id] = { type: 'notFound' };
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
let refused;
|
|
338
|
-
for (const [path, value] of Object.entries(patch)) {
|
|
339
|
-
if (path === 'name') {
|
|
340
|
-
if (typeof value !== 'string' || value.length === 0) {
|
|
341
|
-
refused = { type: 'invalidProperties', description: 'a mailbox needs a name' };
|
|
342
|
-
break;
|
|
343
|
-
}
|
|
344
|
-
if (this.#nameCollides(box.parentId, value, box.id)) {
|
|
345
|
-
refused = {
|
|
346
|
-
type: 'invalidProperties',
|
|
347
|
-
description: `a mailbox named "${value}" already exists at that level`,
|
|
348
|
-
};
|
|
349
|
-
break;
|
|
350
|
-
}
|
|
351
|
-
box.name = value;
|
|
352
|
-
}
|
|
353
|
-
else if (path.startsWith('shareWith/')) {
|
|
354
|
-
const accountId = unpointer(path.slice('shareWith/'.length));
|
|
355
|
-
if (value === null) {
|
|
356
|
-
delete box.shareWith[accountId];
|
|
357
|
-
}
|
|
358
|
-
else {
|
|
359
|
-
box.shareWith[accountId] = { ...value };
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
else {
|
|
363
|
-
refused = { type: 'invalidPatch', description: `cannot patch ${path}` };
|
|
364
|
-
break;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
if (refused) {
|
|
368
|
-
notUpdated[id] = refused;
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
updated[id] = null;
|
|
372
|
-
}
|
|
373
|
-
// Destroy, for `deleteMailbox`. RFC 8621 §2's own refusals: a
|
|
374
|
-
// mailbox still holding children or mail is not silently emptied.
|
|
375
|
-
// The role guard that matters -- refusing to delete an Inbox, a
|
|
376
|
-
// Drafts, ... -- is `deleteMailbox`'s job, not this fake's; a real
|
|
377
|
-
// server's stance on that varies, and this only mirrors the two
|
|
378
|
-
// refusals RFC 8621 actually names.
|
|
379
|
-
const destroy = (args.destroy ?? []);
|
|
380
|
-
const destroyed = [];
|
|
381
|
-
const notDestroyed = {};
|
|
382
|
-
for (const id of destroy) {
|
|
383
|
-
const box = this.#boxes.find((existing) => existing.id === id);
|
|
384
|
-
if (!box) {
|
|
385
|
-
notDestroyed[id] = { type: 'notFound' };
|
|
386
|
-
continue;
|
|
387
|
-
}
|
|
388
|
-
if (this.#boxes.some((existing) => existing.parentId === id)) {
|
|
389
|
-
notDestroyed[id] = {
|
|
390
|
-
type: 'mailboxHasChild',
|
|
391
|
-
description: 'the mailbox still has child mailboxes',
|
|
392
|
-
};
|
|
393
|
-
continue;
|
|
394
|
-
}
|
|
395
|
-
const hasEmail = this.#emails.some((email) => email.mailboxIds[id]);
|
|
396
|
-
if (hasEmail) {
|
|
397
|
-
notDestroyed[id] = {
|
|
398
|
-
type: 'mailboxHasEmail',
|
|
399
|
-
description: 'the mailbox still has mail in it',
|
|
400
|
-
};
|
|
401
|
-
continue;
|
|
402
|
-
}
|
|
403
|
-
this.#boxes = this.#boxes.filter((existing) => existing.id !== id);
|
|
404
|
-
destroyed.push(id);
|
|
405
|
-
}
|
|
406
|
-
return {
|
|
407
|
-
accountId: ACCOUNT,
|
|
408
|
-
oldState: 'm1',
|
|
409
|
-
newState: 'm2',
|
|
410
|
-
created,
|
|
411
|
-
notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
|
|
412
|
-
updated,
|
|
413
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
414
|
-
destroyed,
|
|
415
|
-
notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
case 'Identity/get':
|
|
419
|
-
return {
|
|
420
|
-
accountId: ACCOUNT,
|
|
421
|
-
state: 'i1',
|
|
422
|
-
list: [
|
|
423
|
-
{
|
|
424
|
-
id: 'identity-1',
|
|
425
|
-
name: this.me.name ?? '',
|
|
426
|
-
email: this.me.email,
|
|
427
|
-
replyTo: null,
|
|
428
|
-
bcc: null,
|
|
429
|
-
textSignature: '',
|
|
430
|
-
htmlSignature: '',
|
|
431
|
-
mayDelete: false,
|
|
432
|
-
},
|
|
433
|
-
],
|
|
434
|
-
notFound: [],
|
|
435
|
-
};
|
|
436
|
-
case 'VacationResponse/get':
|
|
437
|
-
return {
|
|
438
|
-
accountId: ACCOUNT,
|
|
439
|
-
state: 'vr1',
|
|
440
|
-
list: [{ id: 'singleton', ...this.#vacation }],
|
|
441
|
-
notFound: [],
|
|
442
|
-
};
|
|
443
|
-
case 'VacationResponse/set': {
|
|
444
|
-
// Neither created nor destroyed: RFC 8621 §8.1 fixes the object's id
|
|
445
|
-
// at `singleton` from the start, so the only legal write is an
|
|
446
|
-
// update of that one id.
|
|
447
|
-
const create = (args.create ?? {});
|
|
448
|
-
const notCreated = {};
|
|
449
|
-
for (const key of Object.keys(create)) {
|
|
450
|
-
notCreated[key] = {
|
|
451
|
-
type: 'forbidden',
|
|
452
|
-
description: 'the vacation response is a singleton; update "singleton" instead',
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
const destroy = (args.destroy ?? []);
|
|
456
|
-
const notDestroyed = {};
|
|
457
|
-
for (const id of destroy) {
|
|
458
|
-
notDestroyed[id] = {
|
|
459
|
-
type: 'forbidden',
|
|
460
|
-
description: 'the vacation response cannot be destroyed',
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
const update = (args.update ?? {});
|
|
464
|
-
const updated = {};
|
|
465
|
-
const notUpdated = {};
|
|
466
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
467
|
-
if (id !== 'singleton') {
|
|
468
|
-
notUpdated[id] = {
|
|
469
|
-
type: 'notFound',
|
|
470
|
-
description: 'the vacation response id is "singleton"',
|
|
471
|
-
};
|
|
472
|
-
continue;
|
|
473
|
-
}
|
|
474
|
-
let refused;
|
|
475
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
476
|
-
if (!(key in this.#vacation)) {
|
|
477
|
-
refused = { type: 'invalidPatch', description: `cannot patch ${key}` };
|
|
478
|
-
break;
|
|
479
|
-
}
|
|
480
|
-
this.#vacation[key] = value;
|
|
481
|
-
}
|
|
482
|
-
if (refused) {
|
|
483
|
-
notUpdated[id] = refused;
|
|
484
|
-
continue;
|
|
485
|
-
}
|
|
486
|
-
updated[id] = null;
|
|
487
|
-
}
|
|
488
|
-
return {
|
|
489
|
-
accountId: ACCOUNT,
|
|
490
|
-
oldState: 'vr1',
|
|
491
|
-
newState: 'vr2',
|
|
492
|
-
created: null,
|
|
493
|
-
notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
|
|
494
|
-
updated: Object.keys(updated).length > 0 ? updated : null,
|
|
495
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
496
|
-
destroyed: null,
|
|
497
|
-
notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
case 'Email/query': {
|
|
501
|
-
const filter = (args.filter ?? {});
|
|
502
|
-
let matching = this.#emails.filter((email) => this.#matches(email, filter));
|
|
503
|
-
matching.sort((a, b) => (a.receivedAt < b.receivedAt ? 1 : -1));
|
|
504
|
-
if (args.collapseThreads) {
|
|
505
|
-
const seen = new Set();
|
|
506
|
-
const collapsed = [];
|
|
507
|
-
for (const email of matching) {
|
|
508
|
-
if (seen.has(email.threadId))
|
|
509
|
-
continue;
|
|
510
|
-
seen.add(email.threadId);
|
|
511
|
-
collapsed.push(email);
|
|
512
|
-
}
|
|
513
|
-
matching = collapsed;
|
|
514
|
-
}
|
|
515
|
-
const position = Number(args.position ?? 0);
|
|
516
|
-
const limit = args.limit === undefined ? matching.length : Number(args.limit);
|
|
517
|
-
return {
|
|
518
|
-
accountId: ACCOUNT,
|
|
519
|
-
queryState: 'q1',
|
|
520
|
-
canCalculateChanges: false,
|
|
521
|
-
position,
|
|
522
|
-
ids: matching.slice(position, position + limit).map((email) => email.id),
|
|
523
|
-
...(args.calculateTotal ? { total: matching.length } : {}),
|
|
524
|
-
};
|
|
525
|
-
}
|
|
526
|
-
case 'Email/get': {
|
|
527
|
-
const ids = (args.ids ?? []);
|
|
528
|
-
const properties = args.properties;
|
|
529
|
-
const list = ids
|
|
530
|
-
.map((id) => this.#emails.find((email) => email.id === id))
|
|
531
|
-
.filter((email) => email !== undefined)
|
|
532
|
-
.map((email) => this.#project(email, properties, Boolean(args.fetchTextBodyValues)));
|
|
533
|
-
return {
|
|
534
|
-
accountId: ACCOUNT,
|
|
535
|
-
state: 'e1',
|
|
536
|
-
list,
|
|
537
|
-
notFound: ids.filter((id) => !this.#emails.some((email) => email.id === id)),
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
|
-
case 'Thread/get': {
|
|
541
|
-
const ids = (args.ids ?? []);
|
|
542
|
-
return {
|
|
543
|
-
accountId: ACCOUNT,
|
|
544
|
-
state: 'th1',
|
|
545
|
-
list: ids
|
|
546
|
-
.filter((id) => this.#threads.has(id))
|
|
547
|
-
.map((id) => ({ id, emailIds: this.#threads.get(id) ?? [] })),
|
|
548
|
-
notFound: ids.filter((id) => !this.#threads.has(id)),
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
case 'Email/set': {
|
|
552
|
-
const create = (args.create ?? {});
|
|
553
|
-
const created = {};
|
|
554
|
-
for (const [key, draft] of Object.entries(create)) {
|
|
555
|
-
const id = `e${++this.#counter}`;
|
|
556
|
-
const threadId = `t${++this.#counter}`;
|
|
557
|
-
// `textBody`/`htmlBody`/`attachments` are always server-derived
|
|
558
|
-
// from `bodyStructure` (RFC 8621 §4.1.4), never echoed from what
|
|
559
|
-
// the client sent -- and `thread()` asks for exactly those, never
|
|
560
|
-
// `bodyStructure` itself. A create that used the flat
|
|
561
|
-
// `textBody`/`htmlBody`/`attachments` form instead (everything
|
|
562
|
-
// but a calendar-bearing draft) already has them, so there is
|
|
563
|
-
// nothing to derive.
|
|
564
|
-
const bodyStructure = draft.bodyStructure;
|
|
565
|
-
const derived = bodyStructure
|
|
566
|
-
? this.#deriveBodyParts(id, bodyStructure, (draft.bodyValues ?? {}))
|
|
567
|
-
: {};
|
|
568
|
-
this.#emails.push({
|
|
569
|
-
...draft,
|
|
570
|
-
...derived,
|
|
571
|
-
id,
|
|
572
|
-
blobId: `blob-${id}`,
|
|
573
|
-
threadId,
|
|
574
|
-
receivedAt: this.#now.toISOString(),
|
|
575
|
-
});
|
|
576
|
-
this.#threads.set(threadId, [id]);
|
|
577
|
-
created[key] = { id, blobId: `blob-${id}`, threadId, size: 512 };
|
|
578
|
-
}
|
|
579
|
-
/* The patch language, enough of it for what `mutate.ts` sends:
|
|
580
|
-
`keywords/$seen`, a whole `mailboxIds` replacement, and
|
|
581
|
-
`mailboxIds/<id>` removal. A `null` value deletes rather than sets
|
|
582
|
-
false, which is RFC 8620 §5.3's rule and the one a fake gets wrong
|
|
583
|
-
by treating the patch as a merge -- `keywords: { $seen: false }`
|
|
584
|
-
reads as unread everywhere in this package, so a fake that stores
|
|
585
|
-
the false would pass a test the real server fails. */
|
|
586
|
-
const update = (args.update ?? {});
|
|
587
|
-
const updated = {};
|
|
588
|
-
const notUpdated = {};
|
|
589
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
590
|
-
const email = this.#emails.find((one) => one.id === id);
|
|
591
|
-
if (!email) {
|
|
592
|
-
notUpdated[id] = { type: 'notFound' };
|
|
593
|
-
continue;
|
|
594
|
-
}
|
|
595
|
-
for (const [path, value] of Object.entries(patch)) {
|
|
596
|
-
if (path === 'mailboxIds') {
|
|
597
|
-
email.mailboxIds = { ...value };
|
|
598
|
-
}
|
|
599
|
-
else if (path.startsWith('mailboxIds/')) {
|
|
600
|
-
const boxId = unpointer(path.slice('mailboxIds/'.length));
|
|
601
|
-
const next = { ...email.mailboxIds };
|
|
602
|
-
if (value === null)
|
|
603
|
-
delete next[boxId];
|
|
604
|
-
else
|
|
605
|
-
next[boxId] = true;
|
|
606
|
-
email.mailboxIds = next;
|
|
607
|
-
}
|
|
608
|
-
else if (path.startsWith('keywords/')) {
|
|
609
|
-
const keyword = unpointer(path.slice('keywords/'.length));
|
|
610
|
-
const next = { ...email.keywords };
|
|
611
|
-
if (value === null)
|
|
612
|
-
delete next[keyword];
|
|
613
|
-
else
|
|
614
|
-
next[keyword] = true;
|
|
615
|
-
email.keywords = next;
|
|
616
|
-
}
|
|
617
|
-
else if (path === 'keywords') {
|
|
618
|
-
email.keywords = { ...value };
|
|
619
|
-
}
|
|
620
|
-
else {
|
|
621
|
-
notUpdated[id] = { type: 'invalidPatch', description: `cannot patch ${path}` };
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
updated[id] = null;
|
|
625
|
-
}
|
|
626
|
-
// Destroy, for `saveDraft` replacing an earlier draft and `send`
|
|
627
|
-
// consuming one. Gone from its thread too, and an emptied thread is
|
|
628
|
-
// gone, as a server's derived threads are.
|
|
629
|
-
const destroy = (args.destroy ?? []);
|
|
630
|
-
const destroyed = [];
|
|
631
|
-
const notDestroyed = {};
|
|
632
|
-
for (const id of destroy) {
|
|
633
|
-
const email = this.#emails.find((one) => one.id === id);
|
|
634
|
-
if (!email) {
|
|
635
|
-
notDestroyed[id] = { type: 'notFound' };
|
|
636
|
-
continue;
|
|
637
|
-
}
|
|
638
|
-
this.#emails = this.#emails.filter((one) => one.id !== id);
|
|
639
|
-
const members = (this.#threads.get(email.threadId) ?? []).filter((one) => one !== id);
|
|
640
|
-
if (members.length > 0)
|
|
641
|
-
this.#threads.set(email.threadId, members);
|
|
642
|
-
else
|
|
643
|
-
this.#threads.delete(email.threadId);
|
|
644
|
-
destroyed.push(id);
|
|
645
|
-
}
|
|
646
|
-
return {
|
|
647
|
-
accountId: ACCOUNT,
|
|
648
|
-
oldState: '1',
|
|
649
|
-
newState: '2',
|
|
650
|
-
created,
|
|
651
|
-
notCreated: null,
|
|
652
|
-
updated,
|
|
653
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
654
|
-
destroyed,
|
|
655
|
-
notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
case 'EmailSubmission/set': {
|
|
659
|
-
const create = (args.create ?? {});
|
|
660
|
-
const created = {};
|
|
661
|
-
const notCreated = {};
|
|
662
|
-
for (const [key, submission] of Object.entries(create)) {
|
|
663
|
-
// RFC 4865's send-delay parameter rides in the envelope, not a
|
|
664
|
-
// `sendAt` property, and Stalwart validates it as 1..=999999999.
|
|
665
|
-
const holdFor = this.#holdForSeconds(submission.envelope);
|
|
666
|
-
if (holdFor === 'invalid') {
|
|
667
|
-
notCreated[key] = {
|
|
668
|
-
type: 'invalidProperties',
|
|
669
|
-
properties: ['envelope'],
|
|
670
|
-
description: 'Failed to parse mailFrom parameters: HOLDFOR.',
|
|
671
|
-
};
|
|
672
|
-
continue;
|
|
673
|
-
}
|
|
674
|
-
this.submissions.push({ emailId: submission.emailId, identityId: submission.identityId });
|
|
675
|
-
const id = `sub-${this.submissions.length}`;
|
|
676
|
-
const sendAt = new Date(this.#now.getTime() + (holdFor ?? 0) * 1000);
|
|
677
|
-
const undoStatus = holdFor ? 'pending' : 'final';
|
|
678
|
-
this.#submissionState.set(id, { emailId: submission.emailId, sendAt, undoStatus });
|
|
679
|
-
created[key] = { id, sendAt: jmapDate(sendAt), undoStatus };
|
|
680
|
-
// The move to Sent that `onSuccessUpdateEmail` asks for. It runs
|
|
681
|
-
// immediately even on a held message: holding delays delivery,
|
|
682
|
-
// not filing.
|
|
683
|
-
const email = this.#emails.find((one) => one.id === submission.emailId);
|
|
684
|
-
if (email) {
|
|
685
|
-
email.mailboxIds = { 'mb-sent': true };
|
|
686
|
-
email.keywords = { $seen: true };
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
// `undoStatus: 'canceled'` is the only update this server accepts,
|
|
690
|
-
// and it is the unsend: valid only while the submission is still
|
|
691
|
-
// `pending` and its `sendAt` has not arrived. Destroy is handled
|
|
692
|
-
// separately below, and is not a cancel.
|
|
693
|
-
const update = (args.update ?? {});
|
|
694
|
-
const updated = {};
|
|
695
|
-
const notUpdated = {};
|
|
696
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
697
|
-
if (patch.undoStatus !== 'canceled') {
|
|
698
|
-
notUpdated[id] = {
|
|
699
|
-
type: 'invalidProperties',
|
|
700
|
-
properties: ['undoStatus'],
|
|
701
|
-
description: 'Email submissions can only be cancelled.',
|
|
702
|
-
};
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
const record = this.#submissionState.get(id);
|
|
706
|
-
if (!record ||
|
|
707
|
-
record.undoStatus !== 'pending' ||
|
|
708
|
-
record.sendAt.getTime() <= this.#now.getTime()) {
|
|
709
|
-
notUpdated[id] = {
|
|
710
|
-
type: 'cannotUnsend',
|
|
711
|
-
description: 'The requested message is no longer in the queue.',
|
|
712
|
-
};
|
|
713
|
-
continue;
|
|
714
|
-
}
|
|
715
|
-
record.undoStatus = 'canceled';
|
|
716
|
-
updated[id] = null;
|
|
717
|
-
// The move back to Drafts that `onSuccessUpdateEmail` asks for on
|
|
718
|
-
// an unsend, the mirror of the create path's move to Sent above.
|
|
719
|
-
const email = this.#emails.find((one) => one.id === record.emailId);
|
|
720
|
-
if (email) {
|
|
721
|
-
email.mailboxIds = { 'mb-drafts': true };
|
|
722
|
-
email.keywords = { $draft: true, $seen: true };
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
// Destroy is not a cancel: Stalwart forgets the submission record
|
|
726
|
-
// but still sends the mail, so this only drops it from
|
|
727
|
-
// `#submissionState`. It must not touch a submission's status or
|
|
728
|
-
// move its email, or a destroy would silently double as an unsend --
|
|
729
|
-
// the asymmetry that makes destroy a trap rather than a shortcut.
|
|
730
|
-
const destroy = (args.destroy ?? []);
|
|
731
|
-
const destroyed = [];
|
|
732
|
-
const notDestroyed = {};
|
|
733
|
-
for (const id of destroy) {
|
|
734
|
-
if (this.#submissionState.has(id)) {
|
|
735
|
-
this.#submissionState.delete(id);
|
|
736
|
-
destroyed.push(id);
|
|
737
|
-
}
|
|
738
|
-
else {
|
|
739
|
-
notDestroyed[id] = { type: 'notFound' };
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
return {
|
|
743
|
-
accountId: ACCOUNT,
|
|
744
|
-
oldState: '2',
|
|
745
|
-
newState: '3',
|
|
746
|
-
created,
|
|
747
|
-
notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
|
|
748
|
-
updated: Object.keys(updated).length > 0 ? updated : null,
|
|
749
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
750
|
-
destroyed: destroyed.length > 0 ? destroyed : null,
|
|
751
|
-
notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
case 'EmailSubmission/query': {
|
|
755
|
-
const filter = (args.filter ?? {});
|
|
756
|
-
// Mirrors Stalwart's own rule (crates/jmap/src/submission/query.rs
|
|
757
|
-
// 106-127): a submission is only rechecked against the clock, and
|
|
758
|
-
// demoted from `pending` to `final` once its `sendAt` has passed,
|
|
759
|
-
// when the query itself filters on `undoStatus`. Do this
|
|
760
|
-
// unconditionally instead and every query -- not just the ones
|
|
761
|
-
// `queued()` sends -- would tell a caller a message had already
|
|
762
|
-
// gone, which is not what the real server does.
|
|
763
|
-
if (filter.undoStatus !== undefined) {
|
|
764
|
-
for (const record of this.#submissionState.values()) {
|
|
765
|
-
if (record.undoStatus === 'pending' && record.sendAt.getTime() <= this.#now.getTime()) {
|
|
766
|
-
record.undoStatus = 'final';
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
const ids = [...this.#submissionState.entries()]
|
|
771
|
-
.filter(([, record]) => filter.undoStatus === undefined || record.undoStatus === filter.undoStatus)
|
|
772
|
-
.map(([id]) => id);
|
|
773
|
-
return {
|
|
774
|
-
accountId: ACCOUNT,
|
|
775
|
-
queryState: 'sub-q1',
|
|
776
|
-
canCalculateChanges: false,
|
|
777
|
-
position: 0,
|
|
778
|
-
ids,
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
case 'EmailSubmission/get': {
|
|
782
|
-
const ids = (args.ids ?? []);
|
|
783
|
-
const list = ids.flatMap((id) => {
|
|
784
|
-
const record = this.#submissionState.get(id);
|
|
785
|
-
if (!record)
|
|
786
|
-
return [];
|
|
787
|
-
const email = this.#emails.find((one) => one.id === record.emailId);
|
|
788
|
-
return [
|
|
789
|
-
{
|
|
790
|
-
id,
|
|
791
|
-
emailId: record.emailId,
|
|
792
|
-
threadId: email?.threadId ?? '',
|
|
793
|
-
sendAt: jmapDate(record.sendAt),
|
|
794
|
-
undoStatus: record.undoStatus,
|
|
795
|
-
},
|
|
796
|
-
];
|
|
797
|
-
});
|
|
798
|
-
return {
|
|
799
|
-
accountId: ACCOUNT,
|
|
800
|
-
state: 'sub-g1',
|
|
801
|
-
list,
|
|
802
|
-
notFound: ids.filter((id) => !this.#submissionState.has(id)),
|
|
803
|
-
};
|
|
804
|
-
}
|
|
805
|
-
case 'Principal/query': {
|
|
806
|
-
const filter = (args.filter ?? {});
|
|
807
|
-
const email = filter.email?.toLowerCase();
|
|
808
|
-
const text = filter.text?.toLowerCase();
|
|
809
|
-
const ids = this.#principals
|
|
810
|
-
.filter((one) => email !== undefined
|
|
811
|
-
? one.email.toLowerCase().includes(email)
|
|
812
|
-
: text === undefined ||
|
|
813
|
-
one.name.toLowerCase().includes(text) ||
|
|
814
|
-
one.email.toLowerCase().includes(text))
|
|
815
|
-
.map((one) => one.id);
|
|
816
|
-
return {
|
|
817
|
-
accountId: ACCOUNT,
|
|
818
|
-
queryState: 'principal1',
|
|
819
|
-
canCalculateChanges: false,
|
|
820
|
-
position: 0,
|
|
821
|
-
ids: ids.slice(0, typeof args.limit === 'number' ? args.limit : ids.length),
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
case 'Principal/get': {
|
|
825
|
-
const ids = (args.ids ?? null);
|
|
826
|
-
const list = this.#principals
|
|
827
|
-
.filter((one) => ids === null || ids.includes(one.id))
|
|
828
|
-
.map((one) => ({
|
|
829
|
-
id: one.id,
|
|
830
|
-
type: one.type ?? 'individual',
|
|
831
|
-
name: one.name,
|
|
832
|
-
email: one.email,
|
|
833
|
-
accounts: one.accountId
|
|
834
|
-
? {
|
|
835
|
-
[one.accountId]: {
|
|
836
|
-
name: one.email,
|
|
837
|
-
isPersonal: true,
|
|
838
|
-
isReadOnly: false,
|
|
839
|
-
accountCapabilities: { 'urn:ietf:params:jmap:mail': {} },
|
|
840
|
-
},
|
|
841
|
-
}
|
|
842
|
-
: {},
|
|
843
|
-
}));
|
|
844
|
-
return {
|
|
845
|
-
accountId: ACCOUNT,
|
|
846
|
-
state: 'principal1',
|
|
847
|
-
list,
|
|
848
|
-
notFound: (ids ?? []).filter((id) => !this.#principals.some((one) => one.id === id)),
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
case 'SieveScript/get': {
|
|
852
|
-
const ids = (args.ids ?? null);
|
|
853
|
-
const found = ids
|
|
854
|
-
? this.#sieveScripts.filter((script) => ids.includes(script.id))
|
|
855
|
-
: this.#sieveScripts;
|
|
856
|
-
return {
|
|
857
|
-
accountId: ACCOUNT,
|
|
858
|
-
state: 'sieve1',
|
|
859
|
-
list: found.map((script) => ({
|
|
860
|
-
id: script.id,
|
|
861
|
-
name: script.name,
|
|
862
|
-
blobId: script.blobId,
|
|
863
|
-
isActive: script.id === this.#activeSieveScriptId,
|
|
864
|
-
})),
|
|
865
|
-
notFound: (ids ?? []).filter((id) => !this.#sieveScripts.some((script) => script.id === id)),
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
case 'SieveScript/validate': {
|
|
869
|
-
const blobId = args.blobId;
|
|
870
|
-
const text = blobId === undefined ? undefined : this.#blobContents.get(blobId);
|
|
871
|
-
if (text === undefined) {
|
|
872
|
-
return {
|
|
873
|
-
accountId: ACCOUNT,
|
|
874
|
-
error: { type: 'blobNotFound', description: 'Blob does not exist.' },
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
if (!this.#compilesAsSieve(text)) {
|
|
878
|
-
return {
|
|
879
|
-
accountId: ACCOUNT,
|
|
880
|
-
error: { type: 'invalidScript', description: 'unbalanced braces' },
|
|
881
|
-
};
|
|
882
|
-
}
|
|
883
|
-
return { accountId: ACCOUNT, error: null };
|
|
884
|
-
}
|
|
885
|
-
case 'SieveScript/set': {
|
|
886
|
-
const create = (args.create ?? {});
|
|
887
|
-
const created = {};
|
|
888
|
-
const notCreated = {};
|
|
889
|
-
for (const [key, item] of Object.entries(create)) {
|
|
890
|
-
if (!item.blobId) {
|
|
891
|
-
notCreated[key] = {
|
|
892
|
-
type: 'invalidProperties',
|
|
893
|
-
properties: ['blobId'],
|
|
894
|
-
description: 'Missing blobId.',
|
|
895
|
-
};
|
|
896
|
-
continue;
|
|
897
|
-
}
|
|
898
|
-
const text = this.#blobContents.get(item.blobId);
|
|
899
|
-
if (text === undefined) {
|
|
900
|
-
notCreated[key] = { type: 'blobNotFound', description: 'Blob does not exist.' };
|
|
901
|
-
continue;
|
|
902
|
-
}
|
|
903
|
-
if (!this.#compilesAsSieve(text)) {
|
|
904
|
-
notCreated[key] = { type: 'invalidScript', description: 'unbalanced braces' };
|
|
905
|
-
continue;
|
|
906
|
-
}
|
|
907
|
-
const name = item.name?.trim();
|
|
908
|
-
if (!name) {
|
|
909
|
-
notCreated[key] = {
|
|
910
|
-
type: 'invalidProperties',
|
|
911
|
-
properties: ['name'],
|
|
912
|
-
description: 'a sieve script needs a name',
|
|
913
|
-
};
|
|
914
|
-
continue;
|
|
915
|
-
}
|
|
916
|
-
if (this.#sieveScripts.some((script) => script.name === name)) {
|
|
917
|
-
notCreated[key] = {
|
|
918
|
-
type: 'alreadyExists',
|
|
919
|
-
description: `A sieve script with name '${name}' already exists.`,
|
|
920
|
-
};
|
|
921
|
-
continue;
|
|
922
|
-
}
|
|
923
|
-
const id = `sieve${++this.#counter}`;
|
|
924
|
-
this.#sieveScripts.push({ id, name, blobId: item.blobId });
|
|
925
|
-
created[key] = { id, blobId: item.blobId };
|
|
926
|
-
}
|
|
927
|
-
const update = (args.update ?? {});
|
|
928
|
-
const updated = {};
|
|
929
|
-
const notUpdated = {};
|
|
930
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
931
|
-
const script = this.#sieveScripts.find((existing) => existing.id === id);
|
|
932
|
-
if (!script) {
|
|
933
|
-
notUpdated[id] = { type: 'notFound' };
|
|
934
|
-
continue;
|
|
935
|
-
}
|
|
936
|
-
if (patch.blobId !== undefined) {
|
|
937
|
-
const text = this.#blobContents.get(patch.blobId);
|
|
938
|
-
if (text === undefined) {
|
|
939
|
-
notUpdated[id] = { type: 'blobNotFound', description: 'Blob does not exist.' };
|
|
940
|
-
continue;
|
|
941
|
-
}
|
|
942
|
-
if (!this.#compilesAsSieve(text)) {
|
|
943
|
-
notUpdated[id] = { type: 'invalidScript', description: 'unbalanced braces' };
|
|
944
|
-
continue;
|
|
945
|
-
}
|
|
946
|
-
script.blobId = patch.blobId;
|
|
947
|
-
}
|
|
948
|
-
if (patch.name !== undefined) {
|
|
949
|
-
const name = patch.name.trim();
|
|
950
|
-
if (!name) {
|
|
951
|
-
notUpdated[id] = {
|
|
952
|
-
type: 'invalidProperties',
|
|
953
|
-
properties: ['name'],
|
|
954
|
-
description: 'a sieve script needs a name',
|
|
955
|
-
};
|
|
956
|
-
continue;
|
|
957
|
-
}
|
|
958
|
-
if (this.#sieveScripts.some((existing) => existing.id !== id && existing.name === name)) {
|
|
959
|
-
notUpdated[id] = {
|
|
960
|
-
type: 'alreadyExists',
|
|
961
|
-
description: `A sieve script with name '${name}' already exists.`,
|
|
962
|
-
};
|
|
963
|
-
continue;
|
|
964
|
-
}
|
|
965
|
-
script.name = name;
|
|
966
|
-
}
|
|
967
|
-
updated[id] = null;
|
|
968
|
-
}
|
|
969
|
-
// RFC 8621 §2's own refusal for a mailbox with a role, restated here
|
|
970
|
-
// for the one script that is active: Stalwart requires it deactivated
|
|
971
|
-
// first (`crates/jmap/src/sieve/set.rs:341-346`).
|
|
972
|
-
const destroy = (args.destroy ?? []);
|
|
973
|
-
const destroyed = [];
|
|
974
|
-
const notDestroyed = {};
|
|
975
|
-
for (const id of destroy) {
|
|
976
|
-
if (!this.#sieveScripts.some((script) => script.id === id)) {
|
|
977
|
-
notDestroyed[id] = { type: 'notFound' };
|
|
978
|
-
continue;
|
|
979
|
-
}
|
|
980
|
-
if (id === this.#activeSieveScriptId) {
|
|
981
|
-
notDestroyed[id] = {
|
|
982
|
-
type: 'scriptIsActive',
|
|
983
|
-
description: 'Deactivate Sieve script before deletion.',
|
|
984
|
-
};
|
|
985
|
-
continue;
|
|
986
|
-
}
|
|
987
|
-
this.#sieveScripts = this.#sieveScripts.filter((script) => script.id !== id);
|
|
988
|
-
destroyed.push(id);
|
|
989
|
-
}
|
|
990
|
-
// Activation/deactivation, RFC 9661's non-standard set arguments.
|
|
991
|
-
// Only applied when nothing above failed, mirroring Stalwart
|
|
992
|
-
// (`set.rs:371-376`); a bad id in `onSuccessActivateScript` is
|
|
993
|
-
// silently ignored here too (`set.rs:96-101`), which is exactly why
|
|
994
|
-
// `activateSieveScript` never sends one without a same-id `update`
|
|
995
|
-
// whose own `notFound` can be seen above.
|
|
996
|
-
const noFailures = Object.keys(notCreated).length === 0 &&
|
|
997
|
-
Object.keys(notUpdated).length === 0 &&
|
|
998
|
-
Object.keys(notDestroyed).length === 0;
|
|
999
|
-
if (noFailures) {
|
|
1000
|
-
const activate = args.onSuccessActivateScript;
|
|
1001
|
-
if (activate !== undefined &&
|
|
1002
|
-
this.#sieveScripts.some((script) => script.id === activate)) {
|
|
1003
|
-
this.#activeSieveScriptId = activate;
|
|
1004
|
-
}
|
|
1005
|
-
else if (args.onSuccessDeactivateScript === true) {
|
|
1006
|
-
this.#activeSieveScriptId = null;
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
return {
|
|
1010
|
-
accountId: ACCOUNT,
|
|
1011
|
-
oldState: 'sieve1',
|
|
1012
|
-
newState: 'sieve2',
|
|
1013
|
-
created,
|
|
1014
|
-
notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
|
|
1015
|
-
updated,
|
|
1016
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
1017
|
-
destroyed,
|
|
1018
|
-
notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
|
|
1019
|
-
};
|
|
1020
|
-
}
|
|
1021
|
-
default:
|
|
1022
|
-
return {
|
|
1023
|
-
type: 'unknownMethod',
|
|
1024
|
-
description: `the fake mailbox does not implement ${method}`,
|
|
1025
|
-
};
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
/**
|
|
1029
|
-
* What a real server computes from a `bodyStructure` create: `textBody`,
|
|
1030
|
-
* `htmlBody` and `attachments`, RFC 8621 §4.1.4's derived properties.
|
|
1031
|
-
* Handles only the shape `draftToEmail` sends for a calendar part -- one
|
|
1032
|
-
* `multipart/alternative` with flat leaf subParts, never nested further --
|
|
1033
|
-
* since that is the only caller that reaches for `bodyStructure` at all.
|
|
1034
|
-
*
|
|
1035
|
-
* Also records each leaf's bytes under its synthetic blob id, so the
|
|
1036
|
-
* download route below can answer with what was actually sent rather than
|
|
1037
|
-
* the fixed placeholder every other attachment gets.
|
|
1038
|
-
*/
|
|
1039
|
-
#deriveBodyParts(id, bodyStructure, bodyValues) {
|
|
1040
|
-
const parts = (bodyStructure.subParts ?? []).map((leaf) => {
|
|
1041
|
-
const partId = leaf.partId ?? '';
|
|
1042
|
-
// The bare media type: a real server strips `method=` (and every
|
|
1043
|
-
// other parameter) from what `Email/get`'s `type` reports, the same
|
|
1044
|
-
// way it already strips `charset` -- see the PR's citation of
|
|
1045
|
-
// `crates/email/src/message/body.rs:77-82`.
|
|
1046
|
-
const type = (leaf.type ?? 'text/plain').split(';')[0]?.trim().toLowerCase() || 'text/plain';
|
|
1047
|
-
const blobId = `blob-${id}-${partId}`;
|
|
1048
|
-
this.#blobContents.set(blobId, bodyValues[partId]?.value ?? '');
|
|
1049
|
-
return {
|
|
1050
|
-
partId,
|
|
1051
|
-
blobId,
|
|
1052
|
-
size: bodyValues[partId]?.value.length ?? 0,
|
|
1053
|
-
name: null,
|
|
1054
|
-
type,
|
|
1055
|
-
charset: type.startsWith('text/') ? 'UTF-8' : null,
|
|
1056
|
-
disposition: null,
|
|
1057
|
-
cid: null,
|
|
1058
|
-
};
|
|
1059
|
-
});
|
|
1060
|
-
const textBody = parts.filter((part) => part.type === 'text/plain');
|
|
1061
|
-
const htmlBody = parts.filter((part) => part.type === 'text/html');
|
|
1062
|
-
const inBody = new Set([...textBody, ...htmlBody].map((part) => part.partId));
|
|
1063
|
-
const attachments = parts.filter((part) => !inBody.has(part.partId));
|
|
1064
|
-
return { textBody, htmlBody, attachments, hasAttachment: attachments.length > 0 };
|
|
1065
|
-
}
|
|
1066
|
-
/** RFC 4865's send-delay SMTP parameter, read the way Stalwart reads it:
|
|
1067
|
-
* case-insensitively, since the server uppercases every `mailFrom`
|
|
1068
|
-
* parameter key before matching. `undefined` means no `holdFor` was
|
|
1069
|
-
* sent; `'invalid'` means one was sent but failed the 1..=999999999
|
|
1070
|
-
* range. `holdUntil` is not supported yet, so it is ignored. */
|
|
1071
|
-
#holdForSeconds(envelope) {
|
|
1072
|
-
const parameters = envelope?.mailFrom?.parameters;
|
|
1073
|
-
if (!parameters)
|
|
1074
|
-
return undefined;
|
|
1075
|
-
const key = Object.keys(parameters).find((name) => name.toUpperCase() === 'HOLDFOR');
|
|
1076
|
-
if (key === undefined)
|
|
1077
|
-
return undefined;
|
|
1078
|
-
const seconds = Number(parameters[key]);
|
|
1079
|
-
if (!Number.isInteger(seconds) || seconds < 1 || seconds > 999_999_999)
|
|
1080
|
-
return 'invalid';
|
|
1081
|
-
return seconds;
|
|
1082
|
-
}
|
|
1083
|
-
#matches(email, filter) {
|
|
1084
|
-
const mailboxIds = email.mailboxIds;
|
|
1085
|
-
if (typeof filter.inMailbox === 'string' && !mailboxIds[filter.inMailbox])
|
|
1086
|
-
return false;
|
|
1087
|
-
if (Array.isArray(filter.inMailboxOtherThan)) {
|
|
1088
|
-
const excluded = filter.inMailboxOtherThan;
|
|
1089
|
-
if (Object.keys(mailboxIds).every((id) => excluded.includes(id)))
|
|
1090
|
-
return false;
|
|
1091
|
-
}
|
|
1092
|
-
if (typeof filter.text === 'string') {
|
|
1093
|
-
const haystack = [
|
|
1094
|
-
email.subject,
|
|
1095
|
-
email.bodyValues?.t?.value,
|
|
1096
|
-
...(email.from ?? []).map((a) => `${a.name ?? ''} ${a.email}`),
|
|
1097
|
-
]
|
|
1098
|
-
.join(' ')
|
|
1099
|
-
.toLowerCase();
|
|
1100
|
-
if (!haystack.includes(filter.text.toLowerCase()))
|
|
1101
|
-
return false;
|
|
1102
|
-
}
|
|
1103
|
-
if (typeof filter.from === 'string') {
|
|
1104
|
-
const from = (email.from ?? []).map((a) => a.email).join(' ');
|
|
1105
|
-
if (!from.toLowerCase().includes(filter.from.toLowerCase()))
|
|
1106
|
-
return false;
|
|
1107
|
-
}
|
|
1108
|
-
if (filter.hasAttachment === true && !email.hasAttachment)
|
|
1109
|
-
return false;
|
|
1110
|
-
return true;
|
|
1111
|
-
}
|
|
1112
|
-
/** A stand-in for the real compiler `SieveScript/set` and `/validate` both
|
|
1113
|
-
* run server-side (`crates/jmap/src/sieve/set.rs:541`) -- not a Sieve
|
|
1114
|
-
* parser, just enough to make a genuine syntax error (unbalanced `{}`, or
|
|
1115
|
-
* nothing at all) refused deterministically, the way `#holdForSeconds`
|
|
1116
|
-
* above stands in for Stalwart's own delay validation without being one. */
|
|
1117
|
-
#compilesAsSieve(text) {
|
|
1118
|
-
if (text.trim().length === 0)
|
|
1119
|
-
return false;
|
|
1120
|
-
let depth = 0;
|
|
1121
|
-
for (const char of text) {
|
|
1122
|
-
if (char === '{')
|
|
1123
|
-
depth += 1;
|
|
1124
|
-
else if (char === '}') {
|
|
1125
|
-
depth -= 1;
|
|
1126
|
-
if (depth < 0)
|
|
1127
|
-
return false;
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
return depth === 0;
|
|
1131
|
-
}
|
|
1132
|
-
/** Return only what was asked for, the way a server does -- so a component
|
|
1133
|
-
* reading a property the query never requested fails here as it would
|
|
1134
|
-
* there. */
|
|
1135
|
-
#project(email, properties, bodies) {
|
|
1136
|
-
const { _at, bodyValues, ...rest } = email;
|
|
1137
|
-
const base = { ...rest, ...(bodies ? { bodyValues } : {}) };
|
|
1138
|
-
if (!properties)
|
|
1139
|
-
return base;
|
|
1140
|
-
const out = { id: email.id };
|
|
1141
|
-
for (const key of properties)
|
|
1142
|
-
if (key in base)
|
|
1143
|
-
out[key] = base[key];
|
|
1144
|
-
if (bodies)
|
|
1145
|
-
out.bodyValues = base.bodyValues;
|
|
1146
|
-
return out;
|
|
1147
|
-
}
|
|
1148
|
-
/** A `fetch` that answers this mailbox. Hand it to `MailClient`. */
|
|
1149
|
-
fetch = async (input, init) => {
|
|
1150
|
-
if (this.#latency > 0)
|
|
1151
|
-
await new Promise((resolve) => setTimeout(resolve, this.#latency));
|
|
1152
|
-
const url = String(input);
|
|
1153
|
-
const json = (body) => new Response(JSON.stringify(body), {
|
|
1154
|
-
status: 200,
|
|
1155
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1156
|
-
});
|
|
1157
|
-
if (!init || (init.method ?? 'GET') === 'GET') {
|
|
1158
|
-
if (url.includes('/jmap/download/')) {
|
|
1159
|
-
// `{accountId}/{blobId}/{name}` -- only a blob this fake actually
|
|
1160
|
-
// stored content for (an upload, never an attachment's synthetic
|
|
1161
|
-
// blobId from `add()`) reads back as anything but the fixed stub.
|
|
1162
|
-
const blobId = url.split('/jmap/download/')[1]?.split('/')[1];
|
|
1163
|
-
const stored = blobId ? this.#blobContents.get(decodeURIComponent(blobId)) : undefined;
|
|
1164
|
-
return new Response(stored ?? 'fake attachment bytes');
|
|
1165
|
-
}
|
|
1166
|
-
if (url.includes('/eventsource')) {
|
|
1167
|
-
// An open stream that never sends: `push` stays connected and quiet.
|
|
1168
|
-
return new Response(new ReadableStream(), {
|
|
1169
|
-
headers: { 'Content-Type': 'text/event-stream' },
|
|
1170
|
-
});
|
|
1171
|
-
}
|
|
1172
|
-
return json(this.session(new URL(url).origin));
|
|
1173
|
-
}
|
|
1174
|
-
/* An upload is the one POST that is not a JMAP request: raw bytes in,
|
|
1175
|
-
RFC 8620 §6.1's `{accountId, blobId, type, size}` out. The size is
|
|
1176
|
-
measured, not taken from a header, which is what a server does. An
|
|
1177
|
-
aborted request never gets here in a browser; here it has to be
|
|
1178
|
-
checked, or a test that cancels an upload would see it land. */
|
|
1179
|
-
if (url.includes('/jmap/upload/')) {
|
|
1180
|
-
init.signal?.throwIfAborted();
|
|
1181
|
-
const size = await measure(init.body);
|
|
1182
|
-
if (size > this.#maxSizeUpload) {
|
|
1183
|
-
return new Response(JSON.stringify({
|
|
1184
|
-
type: 'urn:ietf:params:jmap:error:limit',
|
|
1185
|
-
limit: 'maxSizeUpload',
|
|
1186
|
-
status: 413,
|
|
1187
|
-
}), { status: 413, headers: { 'Content-Type': 'application/problem+json' } });
|
|
1188
|
-
}
|
|
1189
|
-
const type = new Headers(init.headers).get('Content-Type') ?? 'application/octet-stream';
|
|
1190
|
-
const blob = { blobId: `upload-${this.uploads.length + 1}`, type, size };
|
|
1191
|
-
this.uploads.push(blob);
|
|
1192
|
-
this.#blobContents.set(blob.blobId, await bodyText(init.body));
|
|
1193
|
-
return json({ accountId: ACCOUNT, ...blob });
|
|
1194
|
-
}
|
|
1195
|
-
const body = JSON.parse(String(init.body));
|
|
1196
|
-
const responses = [];
|
|
1197
|
-
for (const [method, args, id] of body.methodCalls) {
|
|
1198
|
-
const resolved = this.#resolveRefs(args, responses);
|
|
1199
|
-
const result = this.call(method, resolved);
|
|
1200
|
-
responses.push([result.type === 'unknownMethod' ? 'error' : method, result, id]);
|
|
1201
|
-
}
|
|
1202
|
-
return json({ methodResponses: responses, sessionState: 'fake-session' });
|
|
1203
|
-
};
|
|
1204
|
-
/** Replace `#ids` result references with the values they point at, which is
|
|
1205
|
-
* the whole reason a page of threads is one round trip. */
|
|
1206
|
-
#resolveRefs(args, done) {
|
|
1207
|
-
const out = {};
|
|
1208
|
-
for (const [key, value] of Object.entries(args)) {
|
|
1209
|
-
if (!key.startsWith('#')) {
|
|
1210
|
-
out[key] = value;
|
|
1211
|
-
continue;
|
|
1212
|
-
}
|
|
1213
|
-
const reference = value;
|
|
1214
|
-
const source = done.find(([, , id]) => id === reference.resultOf)?.[1];
|
|
1215
|
-
out[key.slice(1)] = source ? pointer(source, reference.path) : [];
|
|
1216
|
-
}
|
|
1217
|
-
return out;
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
/** How many bytes an upload body carries, whatever shape `fetch` was given it
|
|
1221
|
-
* in. A `File` from a test's DOM is recognised by its `size`, since it is
|
|
1222
|
-
* not this realm's `Blob`. */
|
|
1223
|
-
async function measure(body) {
|
|
1224
|
-
if (body === null || body === undefined)
|
|
1225
|
-
return 0;
|
|
1226
|
-
if (typeof body === 'string')
|
|
1227
|
-
return new TextEncoder().encode(body).byteLength;
|
|
1228
|
-
if (typeof body === 'object' && 'size' in body && typeof body.size === 'number') {
|
|
1229
|
-
return body.size;
|
|
1230
|
-
}
|
|
1231
|
-
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
1232
|
-
return body.byteLength;
|
|
1233
|
-
return (await new Response(body).arrayBuffer()).byteLength;
|
|
1234
|
-
}
|
|
1235
|
-
/** An upload body's bytes, as text -- what `SieveScript/set` and
|
|
1236
|
-
* `/validate` need back to answer honestly, unlike an attachment whose
|
|
1237
|
-
* content nothing here ever reads again. Mirrors `measure`'s type handling
|
|
1238
|
-
* above so a `Blob` is read by its own `.text()` rather than by `instanceof`
|
|
1239
|
-
* (a page can hold more than one realm's `Blob`), and neither call consumes
|
|
1240
|
-
* the other's read: everything `client.upload` actually sends -- a string,
|
|
1241
|
-
* an `ArrayBuffer`/typed array, or a `Blob` -- supports being read twice. */
|
|
1242
|
-
async function bodyText(body) {
|
|
1243
|
-
if (body === null || body === undefined)
|
|
1244
|
-
return '';
|
|
1245
|
-
if (typeof body === 'string')
|
|
1246
|
-
return body;
|
|
1247
|
-
if (body instanceof ArrayBuffer)
|
|
1248
|
-
return new TextDecoder().decode(body);
|
|
1249
|
-
if (ArrayBuffer.isView(body))
|
|
1250
|
-
return new TextDecoder().decode(body);
|
|
1251
|
-
if (typeof body === 'object' && 'text' in body && typeof body.text === 'function') {
|
|
1252
|
-
return body.text();
|
|
1253
|
-
}
|
|
1254
|
-
return new Response(body).text();
|
|
1255
|
-
}
|
|
1256
|
-
/** RFC 6901 §3 in reverse: one patch-key segment, unescaped. A mailbox id is
|
|
1257
|
-
* the server's to choose, so a key built from one may carry `~0` or `~1`. */
|
|
1258
|
-
function unpointer(segment) {
|
|
1259
|
-
return segment.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
1260
|
-
}
|
|
1261
|
-
/** RFC 8620 §3.7's pointer, with the `*` that maps over a list. */
|
|
1262
|
-
function pointer(value, path) {
|
|
1263
|
-
let current = value;
|
|
1264
|
-
for (const rawSegment of path.split('/').filter(Boolean)) {
|
|
1265
|
-
const segment = rawSegment.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
1266
|
-
if (segment === '*') {
|
|
1267
|
-
if (!Array.isArray(current))
|
|
1268
|
-
return [];
|
|
1269
|
-
// The rest of the path applies to every item, and a list of lists is
|
|
1270
|
-
// flattened -- which is what turns `/list/*/emailIds` into every id.
|
|
1271
|
-
const rest = path.slice(path.indexOf('*') + 1);
|
|
1272
|
-
const mapped = current.map((item) => pointer(item, rest));
|
|
1273
|
-
return mapped.flat();
|
|
1274
|
-
}
|
|
1275
|
-
if (Array.isArray(current))
|
|
1276
|
-
current = current[Number(segment)];
|
|
1277
|
-
else if (current && typeof current === 'object') {
|
|
1278
|
-
current = current[segment];
|
|
1279
|
-
}
|
|
1280
|
-
else
|
|
1281
|
-
return undefined;
|
|
1282
|
-
}
|
|
1283
|
-
return current;
|
|
1284
|
-
}
|