imapflow 2.0.7 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/cjs/commands/append.js +12 -12
  3. package/dist/cjs/commands/authenticate.d.ts +3 -8
  4. package/dist/cjs/commands/close.js +2 -1
  5. package/dist/cjs/commands/copy.js +4 -4
  6. package/dist/cjs/commands/create.js +2 -3
  7. package/dist/cjs/commands/delete.js +4 -4
  8. package/dist/cjs/commands/expunge.js +8 -5
  9. package/dist/cjs/commands/fetch.js +12 -10
  10. package/dist/cjs/commands/idle.js +6 -2
  11. package/dist/cjs/commands/list.js +22 -18
  12. package/dist/cjs/commands/move.js +11 -6
  13. package/dist/cjs/commands/namespace.js +1 -1
  14. package/dist/cjs/commands/quota.js +10 -9
  15. package/dist/cjs/commands/rename.js +4 -4
  16. package/dist/cjs/commands/search.js +7 -8
  17. package/dist/cjs/commands/select.js +12 -9
  18. package/dist/cjs/commands/status.js +11 -11
  19. package/dist/cjs/commands/store.js +5 -5
  20. package/dist/cjs/commands/subscribe.js +2 -17
  21. package/dist/cjs/commands/subscription.d.ts +10 -0
  22. package/dist/cjs/commands/subscription.js +29 -0
  23. package/dist/cjs/commands/unsubscribe.js +2 -17
  24. package/dist/cjs/download.d.ts +22 -0
  25. package/dist/cjs/download.js +588 -0
  26. package/dist/cjs/errors.d.ts +50 -1
  27. package/dist/cjs/errors.js +53 -1
  28. package/dist/cjs/handler/imap-compiler.js +1 -1
  29. package/dist/cjs/handler/imap-stream.d.ts +13 -2
  30. package/dist/cjs/handler/imap-stream.js +51 -30
  31. package/dist/cjs/handler/parser-instance.js +2 -2
  32. package/dist/cjs/handler/token-parser.js +15 -9
  33. package/dist/cjs/imap-flow.d.ts +30 -84
  34. package/dist/cjs/imap-flow.js +282 -734
  35. package/dist/cjs/jp-decoder.js +1 -1
  36. package/dist/cjs/package-info.d.ts +1 -1
  37. package/dist/cjs/package-info.js +3 -3
  38. package/dist/cjs/search-compiler.js +5 -12
  39. package/dist/cjs/tools.d.ts +52 -11
  40. package/dist/cjs/tools.js +86 -23
  41. package/dist/cjs/types.d.ts +30 -16
  42. package/dist/esm/commands/append.js +13 -13
  43. package/dist/esm/commands/authenticate.d.ts +3 -8
  44. package/dist/esm/commands/close.js +2 -1
  45. package/dist/esm/commands/copy.js +5 -5
  46. package/dist/esm/commands/create.js +3 -4
  47. package/dist/esm/commands/delete.js +5 -5
  48. package/dist/esm/commands/expunge.js +9 -6
  49. package/dist/esm/commands/fetch.js +13 -11
  50. package/dist/esm/commands/idle.js +7 -3
  51. package/dist/esm/commands/list.js +22 -18
  52. package/dist/esm/commands/move.js +12 -7
  53. package/dist/esm/commands/namespace.js +2 -2
  54. package/dist/esm/commands/quota.js +11 -10
  55. package/dist/esm/commands/rename.js +5 -5
  56. package/dist/esm/commands/search.js +8 -9
  57. package/dist/esm/commands/select.js +13 -10
  58. package/dist/esm/commands/status.js +12 -12
  59. package/dist/esm/commands/store.js +6 -6
  60. package/dist/esm/commands/subscribe.js +2 -17
  61. package/dist/esm/commands/subscription.d.ts +10 -0
  62. package/dist/esm/commands/subscription.js +26 -0
  63. package/dist/esm/commands/unsubscribe.js +2 -17
  64. package/dist/esm/download.d.ts +22 -0
  65. package/dist/esm/download.js +581 -0
  66. package/dist/esm/errors.d.ts +50 -1
  67. package/dist/esm/errors.js +52 -0
  68. package/dist/esm/handler/imap-compiler.js +1 -1
  69. package/dist/esm/handler/imap-stream.d.ts +13 -2
  70. package/dist/esm/handler/imap-stream.js +51 -30
  71. package/dist/esm/handler/parser-instance.js +2 -2
  72. package/dist/esm/handler/token-parser.js +15 -9
  73. package/dist/esm/imap-flow.d.ts +30 -84
  74. package/dist/esm/imap-flow.js +282 -735
  75. package/dist/esm/jp-decoder.js +1 -1
  76. package/dist/esm/package-info.d.ts +1 -1
  77. package/dist/esm/package-info.js +3 -3
  78. package/dist/esm/search-compiler.js +5 -12
  79. package/dist/esm/tools.d.ts +52 -11
  80. package/dist/esm/tools.js +79 -21
  81. package/dist/esm/types.d.ts +30 -16
  82. package/package.json +4 -4
@@ -0,0 +1,26 @@
1
+ import { encodePath, normalizePath, isAuthenticatedState, reportCommandError } from '../tools.js';
2
+ /**
3
+ * Runs SUBSCRIBE or UNSUBSCRIBE for a mailbox, the shared body of the two commands.
4
+ *
5
+ * @param connection - IMAP connection instance
6
+ * @param command - SUBSCRIBE or UNSUBSCRIBE
7
+ * @param path - Mailbox path
8
+ * @returns True on success, false on failure, or undefined if preconditions not met
9
+ */
10
+ export async function setSubscription(connection, command, path) {
11
+ if (!isAuthenticatedState(connection)) {
12
+ // nothing to do here
13
+ return;
14
+ }
15
+ path = normalizePath(connection, path);
16
+ let response;
17
+ try {
18
+ response = await connection.exec(command, [{ type: 'ATOM', value: encodePath(connection, path) }]);
19
+ response.next();
20
+ return true;
21
+ }
22
+ catch (err) {
23
+ await reportCommandError(connection, err);
24
+ return false;
25
+ }
26
+ }
@@ -1,4 +1,4 @@
1
- import { encodePath, normalizePath, enhanceCommandError } from '../tools.js';
1
+ import { setSubscription } from './subscription.js';
2
2
  /**
3
3
  * Unsubscribes from a mailbox.
4
4
  *
@@ -7,20 +7,5 @@ import { encodePath, normalizePath, enhanceCommandError } from '../tools.js';
7
7
  * @returns True on success, false on failure, or undefined if preconditions not met
8
8
  */
9
9
  export default async function unsubscribe(connection, path) {
10
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
11
- // nothing to do here
12
- return;
13
- }
14
- path = normalizePath(connection, path);
15
- let response;
16
- try {
17
- response = await connection.exec('UNSUBSCRIBE', [{ type: 'ATOM', value: encodePath(connection, path) }]);
18
- response.next();
19
- return true;
20
- }
21
- catch (err) {
22
- await enhanceCommandError(err);
23
- connection.log.warn({ err, cid: connection.id });
24
- return false;
25
- }
10
+ return await setSubscription(connection, 'UNSUBSCRIBE', path);
26
11
  }
@@ -0,0 +1,22 @@
1
+ import type { ImapFlow } from './imap-flow.js';
2
+ import type { DownloadManyOptions, DownloadManyResult, DownloadNotFound, DownloadObject, DownloadOptions, SequenceString } from './types.js';
3
+ /**
4
+ * Implements ImapFlow.download(), see its documentation
5
+ *
6
+ * @param client - Connection to download from
7
+ * @param range - UID or sequence number of the message
8
+ * @param part - Body part to download, the whole message when not set
9
+ * @param options - Download options
10
+ * @returns The download, or an empty object when there is nothing to download
11
+ */
12
+ export declare function downloadMessage(client: ImapFlow, range: SequenceString, part?: string | undefined, options?: DownloadOptions | undefined): Promise<DownloadObject | DownloadNotFound>;
13
+ /**
14
+ * Implements ImapFlow.downloadMany(), see its documentation
15
+ *
16
+ * @param client - Connection to download from
17
+ * @param range - UID or sequence number of the message
18
+ * @param parts - Body parts to download
19
+ * @param options - Download options
20
+ * @returns Downloaded parts keyed by part number
21
+ */
22
+ export declare function downloadMessageParts(client: ImapFlow, range: SequenceString, parts: string[], options?: DownloadManyOptions | undefined): Promise<DownloadManyResult>;
@@ -0,0 +1,581 @@
1
+ // The download() and downloadMany() implementations of ImapFlow. Both are built on the public
2
+ // fetchOne(): download() streams a message or one body part through the decoding pipeline,
3
+ // fetching it in chunks, and downloadMany() buffers several body parts from one FETCH.
4
+ import { PassThrough } from 'node:stream';
5
+ import libmime from 'libmime';
6
+ import libqp from 'libqp';
7
+ import libbase64 from 'libbase64';
8
+ import { Headers } from '@zone-eu/mailsplit';
9
+ import FlowedDecoder from '@zone-eu/mailsplit/lib/flowed-decoder.js';
10
+ import { LimitedPassthrough, normalizeByteLimit } from './limited-passthrough.js';
11
+ import { getDecoder, isUnsafeKey } from './tools.js';
12
+ /**
13
+ * Implements ImapFlow.download(), see its documentation
14
+ *
15
+ * @param client - Connection to download from
16
+ * @param range - UID or sequence number of the message
17
+ * @param part - Body part to download, the whole message when not set
18
+ * @param options - Download options
19
+ * @returns The download, or an empty object when there is nothing to download
20
+ */
21
+ export async function downloadMessage(client, range, part, options) {
22
+ if (!client.mailbox) {
23
+ // no mailbox selected, nothing to do
24
+ return {};
25
+ }
26
+ let downloadOptions = Object.assign({
27
+ chunkSize: 64 * 1024,
28
+ maxBytes: Infinity
29
+ }, options || {});
30
+ let hasMore = true;
31
+ let processed = 0;
32
+ let chunkSize = Number(downloadOptions.chunkSize) || 64 * 1024;
33
+ // Normalized once here so every bounded stage of the pipeline below agrees on the budget
34
+ let maxBytes = normalizeByteLimit(downloadOptions.maxBytes);
35
+ let uid = false;
36
+ if (part === '1') {
37
+ // Special handling for part "1": in single-node emails (no childNodes),
38
+ // the body is accessed via "TEXT" rather than "1", and headers via
39
+ // "HEADER" instead of "1.MIME". Check bodyStructure to detect this.
40
+ let response = await client.fetchOne(range, { uid: true, bodyStructure: true }, downloadOptions);
41
+ if (!response) {
42
+ return {};
43
+ }
44
+ if (!uid && response.uid) {
45
+ uid = response.uid;
46
+ // force UID from now on even if first range was a sequence number
47
+ range = uid;
48
+ downloadOptions.uid = true;
49
+ }
50
+ if (!response.bodyStructure.childNodes) {
51
+ // single text message
52
+ part = 'TEXT';
53
+ }
54
+ }
55
+ let getNextPart = async (query) => {
56
+ query = query || {};
57
+ let mimeKey;
58
+ if (!part) {
59
+ query.source = {
60
+ start: processed,
61
+ maxLength: chunkSize
62
+ };
63
+ }
64
+ else {
65
+ part = part.toString().toLowerCase().trim();
66
+ if (!query.bodyParts) {
67
+ query.bodyParts = [];
68
+ }
69
+ if (query.size) {
70
+ if (/^[\d.]+$/.test(part)) {
71
+ // fetch meta as well
72
+ mimeKey = part + '.mime';
73
+ query.bodyParts.push(mimeKey);
74
+ }
75
+ else if (part === 'text') {
76
+ mimeKey = 'header';
77
+ query.bodyParts.push(mimeKey);
78
+ }
79
+ }
80
+ query.bodyParts.push({
81
+ key: part,
82
+ start: processed,
83
+ maxLength: chunkSize
84
+ });
85
+ }
86
+ let response = await client.fetchOne(range, query, downloadOptions);
87
+ if (!response) {
88
+ return { response: false, chunk: false };
89
+ }
90
+ if (!uid && response.uid) {
91
+ uid = response.uid;
92
+ // force UID from now on even if first range was a sequence number
93
+ range = uid;
94
+ downloadOptions.uid = true;
95
+ }
96
+ let chunk = !part ? response.source : response.bodyParts && response.bodyParts.get(part);
97
+ if (!chunk) {
98
+ return {};
99
+ }
100
+ processed += chunk.length;
101
+ // A compliant server returns at most `chunkSize` bytes for a partial
102
+ // request. Some servers (Tencent Exmail among them) ignore the partial
103
+ // spec and answer every request with the complete part. That chunk is
104
+ // then larger than requested, so treating it as "full, keep going"
105
+ // would advance the offset past the end forever and never see a short
106
+ // chunk. An oversized answer already contains the whole part - stop.
107
+ hasMore = chunk.length === chunkSize;
108
+ if (chunk.length > chunkSize) {
109
+ client.log.warn({
110
+ msg: 'Server returned more than the requested window, treating the part as complete',
111
+ chunkSize,
112
+ received: chunk.length,
113
+ processed,
114
+ cid: client.id
115
+ });
116
+ }
117
+ let result = { chunk };
118
+ if (query.size) {
119
+ result.response = response;
120
+ }
121
+ if (query.bodyParts) {
122
+ if (mimeKey === 'header') {
123
+ result.mime = response.headers;
124
+ }
125
+ else {
126
+ result.mime = response.bodyParts && mimeKey ? response.bodyParts.get(mimeKey) : undefined;
127
+ }
128
+ }
129
+ return result;
130
+ };
131
+ let { response, chunk, mime } = await getNextPart({
132
+ size: true,
133
+ uid: true
134
+ });
135
+ if (!response || !chunk) {
136
+ // the message or the part does not exist
137
+ return {};
138
+ }
139
+ let meta = {
140
+ expectedSize: response.size
141
+ };
142
+ if (!part) {
143
+ meta.contentType = 'message/rfc822';
144
+ }
145
+ else if (mime) {
146
+ let headers = new Headers(mime);
147
+ let contentType = libmime.parseHeaderValue(headers.getFirst('Content-Type'));
148
+ let transferEncoding = libmime.parseHeaderValue(headers.getFirst('Content-Transfer-Encoding'));
149
+ let disposition = libmime.parseHeaderValue(headers.getFirst('Content-Disposition'));
150
+ if (contentType.value.toLowerCase().trim()) {
151
+ meta.contentType = contentType.value.toLowerCase().trim();
152
+ }
153
+ if (contentType.params.charset) {
154
+ meta.charset = contentType.params.charset.toLowerCase().trim();
155
+ }
156
+ if (transferEncoding.value) {
157
+ meta.encoding = transferEncoding.value
158
+ .replace(/\(.*\)/g, '')
159
+ .toLowerCase()
160
+ .trim();
161
+ }
162
+ if (disposition.value) {
163
+ /* c8 ignore next */ // a parsed disposition value is never all-whitespace, so the `false` fallback is unreachable
164
+ meta.disposition = disposition.value.toLowerCase().trim() || false;
165
+ try {
166
+ meta.disposition = libmime.decodeWords(meta.disposition);
167
+ }
168
+ catch {
169
+ // failed to parse disposition, keep as is (most probably an unknown charset is used)
170
+ }
171
+ }
172
+ if (contentType.params.format && contentType.params.format.toLowerCase().trim() === 'flowed') {
173
+ meta.flowed = true;
174
+ if (contentType.params.delsp && contentType.params.delsp.toLowerCase().trim() === 'yes') {
175
+ meta.delSp = true;
176
+ }
177
+ }
178
+ let filename = disposition.params.filename || contentType.params.name || false;
179
+ if (filename) {
180
+ try {
181
+ filename = libmime.decodeWords(filename);
182
+ }
183
+ catch {
184
+ // failed to parse filename, keep as is (most probably an unknown charset is used)
185
+ }
186
+ meta.filename = filename;
187
+ }
188
+ }
189
+ let stream;
190
+ let output;
191
+ let fetchAborted = false;
192
+ // Build a decoder pipeline that progressively transforms the raw FETCH data:
193
+ // 1. Transfer-encoding decoder (base64 or quoted-printable -> binary)
194
+ // 2. Format decoder (format=flowed -> plain text, if applicable)
195
+ // 3. Charset decoder (non-UTF-8 -> UTF-8, for text parts only)
196
+ // 4. Byte limiter (enforces maxBytes cap)
197
+ // `stream` is the head of the pipeline (where raw chunks are written),
198
+ // `output` is the tail (what the caller reads from).
199
+ // Parts that arrived via FETCH BINARY (response.binaryParts) are already
200
+ // decoded by the server - decoding again would corrupt the data, so stage 1
201
+ // is skipped for them.
202
+ let clientEncoding = response.binaryParts && part && response.binaryParts.has(part) ? false : meta.encoding;
203
+ switch (clientEncoding) {
204
+ case 'base64':
205
+ output = stream = new libbase64.Decoder();
206
+ break;
207
+ case 'quoted-printable':
208
+ output = stream = new libqp.Decoder();
209
+ break;
210
+ default:
211
+ output = stream = new PassThrough();
212
+ }
213
+ // Every byte-bounded stage of the pipeline. The fetch loop below stops as soon as any of
214
+ // them has taken all it will accept. The limiter at the tail is not enough on its own: a
215
+ // transform in the middle that buffers its whole input before emitting anything (the
216
+ // format=flowed decoder, the Japanese charset decoder) leaves the tail limiter reporting
217
+ // `limited === false` however much the server sends, so a download with a small maxBytes
218
+ // would still pull the entire part off the wire.
219
+ let limiters = [];
220
+ let isLimited = () => limiters.some(entry => entry.limited);
221
+ // Appending a stage means forwarding the current tail's errors to it before piping, so a
222
+ // failure anywhere reaches the stream the caller is reading
223
+ let pipeStage = (stage) => {
224
+ output.on('error', err => {
225
+ stage.emit('error', err);
226
+ });
227
+ output = output.pipe(stage);
228
+ return stage;
229
+ };
230
+ let isTextNode = ['text/html', 'text/plain', 'text/x-amp-html'].includes(meta.contentType) || (part === '1' && !meta.contentType);
231
+ if ((!meta.disposition || meta.disposition === 'inline') && isTextNode) {
232
+ // RFC 3676 format=flowed text: unwrap soft line breaks
233
+ if (meta.flowed) {
234
+ // FlowedDecoder buffers its whole input before emitting, and being third party it
235
+ // carries no bound of its own, so bound what it can ever be handed. Unwrapping only
236
+ // removes bytes, so capping its input at maxBytes cannot push the delivered output
237
+ // above the cap either.
238
+ limiters.push(pipeStage(new LimitedPassthrough({ maxBytes })));
239
+ pipeStage(new FlowedDecoder(meta.delSp ? { delSp: true } : {}));
240
+ }
241
+ // Convert non-UTF-8 charsets to UTF-8 via a streaming decoder.
242
+ // ASCII and UTF-8 need no conversion. Unknown charsets are left as-is.
243
+ if (meta.charset && !['ascii', 'usascii', 'utf8'].includes(meta.charset.toLowerCase().replace(/[^a-z0-9]+/g, ''))) {
244
+ try {
245
+ let decoder = getDecoder(meta.charset, maxBytes);
246
+ // Safety listener attached first so the decoder always has at least
247
+ // one 'error' listener. Prevents Node.js from throwing
248
+ // ERR_UNHANDLED_ERROR if a later pipe setup step throws and leaves
249
+ // the source-forwarding closure attached without a downstream
250
+ // listener wired up. Any real listener the caller attaches still
251
+ // fires in addition to this one.
252
+ decoder.on('error', err => {
253
+ client.log.warn({ err, charset: meta.charset, cid: client.id });
254
+ });
255
+ // The Japanese decoder buffers its whole input as well, and reports the same
256
+ // `limited` flag the limiters do so the fetch loop can stop once it is full.
257
+ // A streaming decoder has no such flag, which reads as false and is correct.
258
+ limiters.push(pipeStage(decoder));
259
+ // force to utf-8 for output
260
+ meta.charset = 'utf-8';
261
+ }
262
+ catch {
263
+ // do not decode charset
264
+ }
265
+ }
266
+ }
267
+ let limiter = pipeStage(new LimitedPassthrough({ maxBytes }));
268
+ limiters.push(limiter);
269
+ // Cleanup function
270
+ const cleanup = () => {
271
+ fetchAborted = true;
272
+ if (stream && !stream.destroyed) {
273
+ stream.destroy();
274
+ }
275
+ };
276
+ // Listen for stream destruction
277
+ output.once('error', cleanup);
278
+ output.once('close', cleanup);
279
+ let writeChunk = (chunk) => {
280
+ if (isLimited() || fetchAborted || stream.destroyed) {
281
+ return true;
282
+ }
283
+ return stream.write(chunk);
284
+ };
285
+ // Ceiling on how many bytes one download may pull off the wire, as the backstop for the
286
+ // partial-ignoring servers above: a part whose size happens to equal chunkSize exactly
287
+ // comes back looking like a full window every time, so no test over chunk lengths can end
288
+ // that loop. RFC822.SIZE bounds any part of the message; doubled for servers that count
289
+ // line endings differently than they deliver, plus one window so a download sitting right
290
+ // at the bound still gets its terminating chunk. Infinity when the server reported no
291
+ // size, which leaves the loop bounded by maxBytes alone.
292
+ let maxTotalBytes = normalizeByteLimit(meta.expectedSize ? meta.expectedSize * 2 + chunkSize : 0);
293
+ // Fetch remaining chunks in a loop, writing each to the decoder stream.
294
+ // Stops when the server returns a short chunk (< chunkSize), answers with more than the
295
+ // requested window, the byte limiter is satisfied, or the consumer destroys the output
296
+ // stream. Throws when the ceiling above is crossed.
297
+ let fetchAllParts = async () => {
298
+ while (hasMore && !isLimited() && !fetchAborted) {
299
+ if (processed >= maxTotalBytes) {
300
+ // Loud on purpose. Everything written downstream by this point holds
301
+ // duplicated content, and a quiet stop is indistinguishable from a clean EOF,
302
+ // so the consumer would store a corrupt body believing it intact.
303
+ let err = new Error('Download exceeded the expected message size');
304
+ err.code = 'DownloadOverflow';
305
+ err.maxSize = maxTotalBytes;
306
+ err.cid = client.id;
307
+ throw err;
308
+ }
309
+ let { response, chunk } = await getNextPart();
310
+ if (fetchAborted) {
311
+ break;
312
+ }
313
+ if (response === false) {
314
+ // The message is gone mid-download (expunged by another client, or the
315
+ // mailbox was closed). Ending the stream here would pass the truncated body
316
+ // off as complete, so the consumer is told the same way as for an overflow.
317
+ let err = new Error('Message disappeared before the download completed');
318
+ err.code = 'DownloadIncomplete';
319
+ err.cid = client.id;
320
+ throw err;
321
+ }
322
+ if (!chunk) {
323
+ break;
324
+ }
325
+ // Handle backpressure
326
+ if (writeChunk(chunk) === false) {
327
+ // Wait for drain event before continuing
328
+ try {
329
+ await new Promise((resolve, reject) => {
330
+ // finish() is the listener itself, as settle() is for the TLS upgrade:
331
+ // 'drain' and 'close' emit no arguments, 'error' emits the error, and
332
+ // removal needs no separate handler references. It removes only the
333
+ // three listeners this wait installed - removeAllListeners('error')
334
+ // also took off the forwarder pipeStage() attached to the head stream
335
+ // when the pipeline was built, and the head must keep that forwarder
336
+ // for the life of the download or a chunk failure has nowhere to go.
337
+ const finish = (err) => {
338
+ for (let event of ['drain', 'error', 'close']) {
339
+ stream.removeListener(event, finish);
340
+ }
341
+ /* c8 ignore next 2 */ // stream error during a backpressure drain wait is timing-dependent
342
+ if (err) {
343
+ reject(err);
344
+ }
345
+ else {
346
+ resolve();
347
+ }
348
+ };
349
+ stream.once('drain', finish);
350
+ stream.once('error', finish);
351
+ stream.once('close', finish);
352
+ });
353
+ /* c8 ignore start */ // re-throw path only triggers on a stream error mid-drain, which is timing-dependent
354
+ }
355
+ catch (err) {
356
+ // Re-throw only if not aborted
357
+ if (!fetchAborted) {
358
+ throw err;
359
+ }
360
+ }
361
+ /* c8 ignore stop */
362
+ // Check if we should abort after waiting
363
+ if (fetchAborted) {
364
+ break;
365
+ }
366
+ }
367
+ }
368
+ };
369
+ // A download is a sequence of chunk FETCHes with a backpressure wait in between. Those
370
+ // gaps look exactly like an inactive connection, so without this auto-IDLE would start
371
+ // between chunks and the next chunk would have to break it again - two extra round
372
+ // trips per chunk, for as long as the consumer is slow. Counted before control returns
373
+ // to the event loop: the head chunk's own FETCH already armed the auto-IDLE timer, and
374
+ // with a very short autoIdleDelay that timer could otherwise fire before the deferred
375
+ // chunk loop below has marked the download open.
376
+ client._openDownloads++;
377
+ let downloadDone = false;
378
+ let finishDownload = () => {
379
+ if (!downloadDone) {
380
+ downloadDone = true;
381
+ client._openDownloads--;
382
+ client.autoidle();
383
+ }
384
+ };
385
+ // Kick off the download pipeline asynchronously. The first chunk was
386
+ // already fetched above (to get metadata); write it to the decoder
387
+ // stream and then fetch remaining chunks via fetchAllParts().
388
+ // setImmediate ensures the caller gets the {meta, content} return
389
+ // value before streaming begins.
390
+ let runFetchAllParts = () => {
391
+ fetchAllParts()
392
+ .catch(err => {
393
+ if (!fetchAborted && stream && !stream.destroyed) {
394
+ stream.emit('error', err);
395
+ /* c8 ignore start */ // the else logs when a fetch error arrives after the stream was already torn down (timing-dependent)
396
+ }
397
+ else {
398
+ // Log when error cannot be emitted to stream
399
+ client.log.warn({
400
+ msg: 'Download error after stream closed',
401
+ err,
402
+ fetchAborted,
403
+ streamDestroyed: stream?.destroyed,
404
+ cid: client.id
405
+ });
406
+ }
407
+ /* c8 ignore stop */
408
+ })
409
+ .finally(() => {
410
+ finishDownload();
411
+ if (!fetchAborted && stream && !stream.destroyed) {
412
+ stream.end();
413
+ }
414
+ })
415
+ // Terminal guard: nothing consumes this chain, so a throw from either handler
416
+ // above rejects a promise nobody holds and takes the process down on
417
+ // unhandledRejection. Reaching it always means an invariant broke - the head
418
+ // stream kept pipeStage()'s error forwarder for the life of the download, so
419
+ // emit('error') above has somewhere to go - which is why it logs at error even
420
+ // for a routine-looking connection code.
421
+ .catch(err => client.log.error({ msg: 'Failed to fail the download stream', err, cid: client.id }));
422
+ };
423
+ setImmediate(() => {
424
+ let writeResult;
425
+ try {
426
+ writeResult = writeChunk(chunk);
427
+ }
428
+ catch (err) {
429
+ stream.emit('error', err);
430
+ finishDownload();
431
+ /* c8 ignore next 3 */ // emitting the error above triggers cleanup (fetchAborted=true), so this end() guard is already false here
432
+ if (!fetchAborted && stream && !stream.destroyed) {
433
+ stream.end();
434
+ }
435
+ return;
436
+ }
437
+ /* c8 ignore next 9 */ // `stream` is piped to the limiter before this runs, so the head write drains synchronously and always returns true (verified for chunkSize up to 8MB); the drain-wait branch is unreachable
438
+ if (!writeResult) {
439
+ // Initial chunk filled the buffer, wait for drain
440
+ stream.once('drain', () => {
441
+ if (!fetchAborted) {
442
+ runFetchAllParts();
443
+ }
444
+ else {
445
+ finishDownload();
446
+ }
447
+ });
448
+ }
449
+ else {
450
+ runFetchAllParts();
451
+ }
452
+ });
453
+ return {
454
+ meta,
455
+ content: output
456
+ };
457
+ }
458
+ /**
459
+ * Implements ImapFlow.downloadMany(), see its documentation
460
+ *
461
+ * @param client - Connection to download from
462
+ * @param range - UID or sequence number of the message
463
+ * @param parts - Body parts to download
464
+ * @param options - Download options
465
+ * @returns Downloaded parts keyed by part number
466
+ */
467
+ export async function downloadMessageParts(client, range, parts, options) {
468
+ if (!client.mailbox) {
469
+ // no mailbox selected, nothing to do
470
+ return {};
471
+ }
472
+ let downloadOptions = Object.assign({
473
+ chunkSize: 64 * 1024,
474
+ maxBytes: Infinity
475
+ }, options || {});
476
+ let query = { bodyParts: [] };
477
+ for (let part of parts) {
478
+ query.bodyParts.push(part + '.mime');
479
+ query.bodyParts.push(part);
480
+ }
481
+ let response = await client.fetchOne(range, query, downloadOptions);
482
+ if (!response || !response.bodyParts) {
483
+ return {};
484
+ }
485
+ let data = {};
486
+ for (let [part, content] of response.bodyParts) {
487
+ let keyParts = part.split('.mime');
488
+ // The server chooses the BODY[...] keys it answers with: never let one be a
489
+ // prototype-chain name, or the assignments below write onto Object.prototype
490
+ // (process-wide pollution) instead of the result object.
491
+ if (isUnsafeKey(keyParts[0])) {
492
+ continue;
493
+ }
494
+ if (keyParts.length === 1) {
495
+ // content
496
+ let key = keyParts[0];
497
+ if (!data[key]) {
498
+ data[key] = { content };
499
+ }
500
+ else {
501
+ data[key].content = content;
502
+ }
503
+ }
504
+ else if (keyParts.length === 2) {
505
+ // header
506
+ let key = keyParts[0];
507
+ if (!data[key]) {
508
+ data[key] = {};
509
+ }
510
+ let entry = data[key];
511
+ if (!entry.meta) {
512
+ entry.meta = {};
513
+ }
514
+ let meta = entry.meta;
515
+ let headers = new Headers(content);
516
+ let contentType = libmime.parseHeaderValue(headers.getFirst('Content-Type'));
517
+ let transferEncoding = libmime.parseHeaderValue(headers.getFirst('Content-Transfer-Encoding'));
518
+ let disposition = libmime.parseHeaderValue(headers.getFirst('Content-Disposition'));
519
+ if (contentType.value.toLowerCase().trim()) {
520
+ meta.contentType = contentType.value.toLowerCase().trim();
521
+ }
522
+ if (contentType.params.charset) {
523
+ meta.charset = contentType.params.charset.toLowerCase().trim();
524
+ }
525
+ if (transferEncoding.value) {
526
+ meta.encoding = transferEncoding.value
527
+ .replace(/\(.*\)/g, '')
528
+ .toLowerCase()
529
+ .trim();
530
+ }
531
+ if (disposition.value) {
532
+ /* c8 ignore next */ // a parsed disposition value is never all-whitespace, so the `false` fallback is unreachable
533
+ meta.disposition = disposition.value.toLowerCase().trim() || false;
534
+ try {
535
+ meta.disposition = libmime.decodeWords(meta.disposition);
536
+ }
537
+ catch {
538
+ // failed to parse disposition, keep as is (most probably an unknown charset is used)
539
+ }
540
+ }
541
+ if (contentType.params.format && contentType.params.format.toLowerCase().trim() === 'flowed') {
542
+ meta.flowed = true;
543
+ if (contentType.params.delsp && contentType.params.delsp.toLowerCase().trim() === 'yes') {
544
+ meta.delSp = true;
545
+ }
546
+ }
547
+ let filename = disposition.params.filename || contentType.params.name || false;
548
+ if (filename) {
549
+ try {
550
+ filename = libmime.decodeWords(filename);
551
+ }
552
+ catch {
553
+ // failed to parse filename, keep as is (most probably an unknown charset is used)
554
+ }
555
+ meta.filename = filename;
556
+ }
557
+ }
558
+ }
559
+ for (let part of Object.keys(data)) {
560
+ let entry = data[part];
561
+ // `meta` is only built from the companion BODY[<part>.MIME] item. A server may
562
+ // legally answer with fewer items than were requested, and one part arriving
563
+ // without its MIME headers must not cost the caller the whole download.
564
+ let meta = entry.meta || {};
565
+ entry.meta = meta;
566
+ // parts that arrived via FETCH BINARY (response.binaryParts) are already
567
+ // decoded by the server - decoding again would corrupt the data
568
+ let clientEncoding = response.binaryParts && response.binaryParts.has(part) ? false : meta.encoding;
569
+ switch (clientEncoding) {
570
+ case 'base64':
571
+ entry.content = entry.content ? libbase64.decode(entry.content.toString()) : null;
572
+ break;
573
+ case 'quoted-printable':
574
+ entry.content = entry.content ? libqp.decode(entry.content.toString()) : null;
575
+ break;
576
+ default:
577
+ // keep as is, already a buffer
578
+ }
579
+ }
580
+ return data;
581
+ }