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
@@ -37,7 +37,7 @@ class JPDecoder extends node_stream_1.Transform {
37
37
  chunk = Buffer.from(chunk, encoding);
38
38
  }
39
39
  if (this.chunklen + chunk.length > this.maxBytes) {
40
- chunk = chunk.slice(0, Math.max(0, this.maxBytes - this.chunklen));
40
+ chunk = chunk.subarray(0, Math.max(0, this.maxBytes - this.chunklen));
41
41
  }
42
42
  if (chunk.length) {
43
43
  this.chunks.push(chunk);
@@ -1,3 +1,3 @@
1
1
  export declare const name = "imapflow";
2
- export declare const version = "2.0.7";
2
+ export declare const version = "2.1.0";
3
3
  export declare const homepage = "https://imapflow.com/";
@@ -2,6 +2,6 @@
2
2
  // Generated by scripts/build.js from package.json. Do not edit by hand.
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.homepage = exports.version = exports.name = void 0;
5
- exports.name = 'imapflow';
6
- exports.version = '2.0.7';
7
- exports.homepage = 'https://imapflow.com/';
5
+ exports.name = "imapflow";
6
+ exports.version = "2.1.0";
7
+ exports.homepage = "https://imapflow.com/";
@@ -406,21 +406,14 @@ const searchCompiler = (connection, query) => {
406
406
  * @returns Binary tree structure
407
407
  */
408
408
  let genOrTree = (list) => {
409
- let group = false;
410
409
  let groups = [];
411
410
  // Group items in pairs
412
- list.forEach((entry, i) => {
413
- if (i % 2 === 0) {
414
- group = [entry];
415
- }
416
- else {
417
- group.push(entry);
418
- groups.push(group);
419
- group = false;
420
- }
421
- });
411
+ for (let i = 0; i + 1 < list.length; i += 2) {
412
+ groups.push([list[i], list[i + 1]]);
413
+ }
422
414
  // Handle odd number of items
423
- if (group && group.length) {
415
+ if (list.length % 2) {
416
+ let group = [list[list.length - 1]];
424
417
  while (group.length === 1 && Array.isArray(group[0])) {
425
418
  group = group[0];
426
419
  }
@@ -1,8 +1,8 @@
1
1
  import type { Transform } from 'node:stream';
2
2
  import type { ImapFlow } from './imap-flow.js';
3
- import type { ConnectionErrorSite, ImapFlowError } from './errors.js';
3
+ import { type ConnectionErrorSite, type ImapFlowError } from './errors.js';
4
4
  import type { ImapAttributeList, ImapAttributeNode, ImapResponse } from './handler/types.js';
5
- import type { FetchMessageObject, ListResponse, ListTreeResponse, MailboxObject, MessageEnvelopeObject, MessageStructureObject, StatusQuery } from './types.js';
5
+ import type { FetchMessageObject, ListResponse, ListTreeResponse, MailboxObject, MessageEnvelopeObject, MessageStructureObject, ImapFlowEvents, StatusQuery } from './types.js';
6
6
  export { AuthenticationFailure } from './errors.js';
7
7
  export declare const EXPANDED_RANGE_LIMIT = 16777216;
8
8
  export declare const MAX_UINT32_DIGITS = 10;
@@ -80,6 +80,13 @@ export declare function guardedPromise<T>(executor: (resolve: (value: T | Promis
80
80
  * @returns Rejected promise, with its rejection already observed
81
81
  */
82
82
  export declare function guardedReject(error: Error): Promise<never>;
83
+ /**
84
+ * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
85
+ * null, and the connection nulls its timer fields once cleared, so every site clears through here.
86
+ *
87
+ * @param timer - Timer handle returned by setTimeout, or null/undefined when none is armed
88
+ */
89
+ export declare function clearTimer(timer: NodeJS.Timeout | null | undefined): void;
83
90
  /**
84
91
  * Detaches a background timer from the event loop, so it cannot keep the process alive on its
85
92
  * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
@@ -89,13 +96,6 @@ export declare function guardedReject(error: Error): Promise<never>;
89
96
  * @param timer - Timer handle returned by setTimeout
90
97
  * @returns The same timer handle
91
98
  */
92
- /**
93
- * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
94
- * null, and the connection nulls its timer fields once cleared, so every site clears through here.
95
- *
96
- * @param timer - Timer handle returned by setTimeout, or null/undefined when none is armed
97
- */
98
- export declare function clearTimer(timer: NodeJS.Timeout | null | undefined): void;
99
99
  export declare function unrefTimer<T extends NodeJS.Timeout | null | undefined>(timer: T): T;
100
100
  /**
101
101
  * Logs a failure from background connection work at the level its cause deserves.
@@ -200,6 +200,25 @@ export declare function updateCapabilities(list: ImapAttributeList | null | unde
200
200
  * @returns Uppercase status code string, or false if not found
201
201
  */
202
202
  export declare function getStatusCode(response: ImapResponse | string | false | undefined): string | false;
203
+ /**
204
+ * Emits a state-change event from inside the command pipeline. A listener that throws must not
205
+ * abort the code that emitted it: select() emits before it releases the response, so the throw
206
+ * would leave the reader loop waiting forever, and close() would never get to emit 'close'. The
207
+ * error is logged instead, the same contract untagged handlers and the 'response' event get.
208
+ *
209
+ * @param connection - IMAP connection instance
210
+ * @param event - Event name
211
+ * @param args - Event arguments
212
+ */
213
+ export declare function emitSafe<K extends keyof ImapFlowEvents>(connection: ImapFlow, event: K, ...args: ImapFlowEvents[K]): void;
214
+ /**
215
+ * Collects the values of the TEXT tokens of a parsed response (the human-readable
216
+ * part of a status response, a greeting or a BYE).
217
+ *
218
+ * @param attributes - Attributes of a parsed IMAP response
219
+ * @returns Values of the TEXT tokens, in order
220
+ */
221
+ export declare function getTextValues(attributes: ImapAttributeList | undefined): string[];
203
222
  /**
204
223
  * Compiles an IMAP response object back into a human-readable string.
205
224
  *
@@ -214,6 +233,28 @@ export declare function getErrorText(response: ImapResponse | string | false | u
214
233
  * @returns The enhanced error with `serverResponseCode` and string `response`
215
234
  */
216
235
  export declare function enhanceCommandError(err: ImapFlowError): Promise<ImapFlowError>;
236
+ /**
237
+ * Enhances a failed command's error (see enhanceCommandError()) and logs it, the shared first
238
+ * step of every command's failure path. The caller decides whether to throw or return.
239
+ *
240
+ * @param connection - IMAP connection instance
241
+ * @param err - The command error
242
+ */
243
+ export declare function reportCommandError(connection: ImapFlow, err: ImapFlowError): Promise<void>;
244
+ /**
245
+ * Whether the session is authenticated, that is in the AUTHENTICATED or SELECTED state, which
246
+ * every mailbox-level command requires.
247
+ *
248
+ * @param connection - IMAP connection instance
249
+ */
250
+ export declare function isAuthenticatedState(connection: ImapFlow): boolean;
251
+ /**
252
+ * Returns the selected mailbox, or false when the connection is not in the SELECTED state.
253
+ * Message-level commands use it as their precondition, which also narrows the mailbox type.
254
+ *
255
+ * @param connection - IMAP connection instance
256
+ */
257
+ export declare function getSelectedMailbox(connection: ImapFlow): MailboxObject | false;
217
258
  /**
218
259
  * Converts a flat list of mailbox folders into a tree structure.
219
260
  *
@@ -305,14 +346,14 @@ export declare function toValidDate(value: unknown): Date | null;
305
346
  * @param value - Date to format
306
347
  * @returns Formatted date string, or undefined if invalid
307
348
  */
308
- export declare function formatDate(value: Date | string | null | undefined): string | undefined;
349
+ export declare function formatDate(value: unknown): string | undefined;
309
350
  /**
310
351
  * Formats a date value into IMAP date-time format (DD-Mon-YYYY HH:MM:SS +0000).
311
352
  *
312
353
  * @param value - Date to format
313
354
  * @returns Formatted date-time string, or undefined if invalid
314
355
  */
315
- export declare function formatDateTime(value: Date | string | null | undefined): string | undefined;
356
+ export declare function formatDateTime(value: unknown): string | undefined;
316
357
  /**
317
358
  * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent),
318
359
  * and capitalizes system flags properly.
package/dist/cjs/tools.js CHANGED
@@ -21,8 +21,13 @@ exports.normalizePath = normalizePath;
21
21
  exports.comparePaths = comparePaths;
22
22
  exports.updateCapabilities = updateCapabilities;
23
23
  exports.getStatusCode = getStatusCode;
24
+ exports.emitSafe = emitSafe;
25
+ exports.getTextValues = getTextValues;
24
26
  exports.getErrorText = getErrorText;
25
27
  exports.enhanceCommandError = enhanceCommandError;
28
+ exports.reportCommandError = reportCommandError;
29
+ exports.isAuthenticatedState = isAuthenticatedState;
30
+ exports.getSelectedMailbox = getSelectedMailbox;
26
31
  exports.getFolderTree = getFolderTree;
27
32
  exports.getFlagColor = getFlagColor;
28
33
  exports.getColorFlags = getColorFlags;
@@ -53,11 +58,12 @@ const imap_handler_js_1 = require("./handler/imap-handler.js");
53
58
  const node_crypto_1 = require("node:crypto");
54
59
  const jp_decoder_js_1 = require("./jp-decoder.js");
55
60
  const iconv_lite_1 = __importDefault(require("iconv-lite"));
56
- var errors_js_1 = require("./errors.js");
57
- Object.defineProperty(exports, "AuthenticationFailure", { enumerable: true, get: function () { return errors_js_1.AuthenticationFailure; } });
61
+ const errors_js_1 = require("./errors.js");
62
+ var errors_js_2 = require("./errors.js");
63
+ Object.defineProperty(exports, "AuthenticationFailure", { enumerable: true, get: function () { return errors_js_2.AuthenticationFailure; } });
58
64
  const FLAG_COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'grey'];
59
65
  // Error codes that only mean the connection is no longer usable. See logConnectionError().
60
- const CONNECTION_GONE_CODES = new Set(['NoConnection', 'EConnectionClosed', 'StateLogout']);
66
+ const CONNECTION_GONE_CODES = new Set([errors_js_1.ImapFlowErrorCode.NoConnection, errors_js_1.ImapFlowErrorCode.EConnectionClosed, errors_js_1.ImapFlowErrorCode.StateLogout]);
61
67
  // Upper bound for expanding server-supplied sequence ranges (see expandRange). 2^24
62
68
  // entries in total is far beyond any legitimate mailbox while keeping the worst-case
63
69
  // expansion of a hostile range set bounded.
@@ -208,15 +214,6 @@ function guardedReject(error) {
208
214
  promise.catch(exports.noop);
209
215
  return promise;
210
216
  }
211
- /**
212
- * Detaches a background timer from the event loop, so it cannot keep the process alive on its
213
- * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
214
- * back-off, held-lock diagnostics); connection and greeting deadlines are deliberately left
215
- * attached, because a caller is waiting for connect() to settle.
216
- *
217
- * @param timer - Timer handle returned by setTimeout
218
- * @returns The same timer handle
219
- */
220
217
  /**
221
218
  * Clears a timer that may already have been dropped. `clearTimeout()` accepts undefined but not
222
219
  * null, and the connection nulls its timer fields once cleared, so every site clears through here.
@@ -228,6 +225,15 @@ function clearTimer(timer) {
228
225
  clearTimeout(timer);
229
226
  }
230
227
  }
228
+ /**
229
+ * Detaches a background timer from the event loop, so it cannot keep the process alive on its
230
+ * own. Applied to every background timer (auto-IDLE, IDLE restart, fallback polling, throttle
231
+ * back-off, held-lock diagnostics); connection and greeting deadlines are deliberately left
232
+ * attached, because a caller is waiting for connect() to settle.
233
+ *
234
+ * @param timer - Timer handle returned by setTimeout
235
+ * @returns The same timer handle
236
+ */
231
237
  function unrefTimer(timer) {
232
238
  /* c8 ignore next 3 */ // node timers always expose unref(); the guard covers replaced globals in tests
233
239
  if (timer && typeof timer.unref === 'function') {
@@ -443,7 +449,7 @@ function updateCapabilities(list) {
443
449
  }
444
450
  if (capability.startsWith('APPENDLIMIT=')) {
445
451
  let splitPos = capability.indexOf('=');
446
- map.set('APPENDLIMIT', parseUintValue(capability.substr(splitPos + 1)) || 0);
452
+ map.set('APPENDLIMIT', parseUintValue(capability.slice(splitPos + 1)) || 0);
447
453
  return;
448
454
  }
449
455
  map.set(capability, true);
@@ -469,6 +475,34 @@ function getStatusCode(response) {
469
475
  ? response.attributes[0].section[0].value.toUpperCase().trim()
470
476
  : false;
471
477
  }
478
+ /**
479
+ * Emits a state-change event from inside the command pipeline. A listener that throws must not
480
+ * abort the code that emitted it: select() emits before it releases the response, so the throw
481
+ * would leave the reader loop waiting forever, and close() would never get to emit 'close'. The
482
+ * error is logged instead, the same contract untagged handlers and the 'response' event get.
483
+ *
484
+ * @param connection - IMAP connection instance
485
+ * @param event - Event name
486
+ * @param args - Event arguments
487
+ */
488
+ function emitSafe(connection, event, ...args) {
489
+ try {
490
+ connection.emit(event, ...args);
491
+ }
492
+ catch (err) {
493
+ connection.log.warn({ msg: 'Event listener failed', event, err, cid: connection.id });
494
+ }
495
+ }
496
+ /**
497
+ * Collects the values of the TEXT tokens of a parsed response (the human-readable
498
+ * part of a status response, a greeting or a BYE).
499
+ *
500
+ * @param attributes - Attributes of a parsed IMAP response
501
+ * @returns Values of the TEXT tokens, in order
502
+ */
503
+ function getTextValues(attributes) {
504
+ return (attributes || []).filter(attr => attr?.type === 'TEXT').map(attr => String(attr?.value ?? ''));
505
+ }
472
506
  /**
473
507
  * Compiles an IMAP response object back into a human-readable string.
474
508
  *
@@ -506,6 +540,35 @@ async function enhanceCommandError(err) {
506
540
  err.response = await getErrorText(err.response);
507
541
  return err;
508
542
  }
543
+ /**
544
+ * Enhances a failed command's error (see enhanceCommandError()) and logs it, the shared first
545
+ * step of every command's failure path. The caller decides whether to throw or return.
546
+ *
547
+ * @param connection - IMAP connection instance
548
+ * @param err - The command error
549
+ */
550
+ async function reportCommandError(connection, err) {
551
+ await enhanceCommandError(err);
552
+ connection.log.warn({ err, cid: connection.id });
553
+ }
554
+ /**
555
+ * Whether the session is authenticated, that is in the AUTHENTICATED or SELECTED state, which
556
+ * every mailbox-level command requires.
557
+ *
558
+ * @param connection - IMAP connection instance
559
+ */
560
+ function isAuthenticatedState(connection) {
561
+ return connection.state === connection.states.AUTHENTICATED || connection.state === connection.states.SELECTED;
562
+ }
563
+ /**
564
+ * Returns the selected mailbox, or false when the connection is not in the SELECTED state.
565
+ * Message-level commands use it as their precondition, which also narrows the mailbox type.
566
+ *
567
+ * @param connection - IMAP connection instance
568
+ */
569
+ function getSelectedMailbox(connection) {
570
+ return connection.state === connection.states.SELECTED && connection.mailbox ? connection.mailbox : false;
571
+ }
509
572
  /**
510
573
  * Converts a flat list of mailbox folders into a tree structure.
511
574
  *
@@ -993,7 +1056,7 @@ function getStructuredParams(arr) {
993
1056
  // nothing to do here, does not seem like a continuation param
994
1057
  return;
995
1058
  }
996
- actualKey = key.substr(0, match.index).toLowerCase();
1059
+ actualKey = key.substring(0, match.index).toLowerCase();
997
1060
  nr = Number(match[2]) || 0;
998
1061
  if (isUnsafeKey(actualKey)) {
999
1062
  // A continuation key like "__proto__*0*" would group under "__proto__":
@@ -1085,7 +1148,7 @@ function parseBodystructure(entry) {
1085
1148
  curNode.type = 'multipart/' + ((node[i++] || {}).value || '').toString().toLowerCase();
1086
1149
  // extension data (not available for BODY requests)
1087
1150
  // body parameter parenthesized list
1088
- if (i < node.length - 1) {
1151
+ if (i < node.length) {
1089
1152
  if (node[i]) {
1090
1153
  curNode.parameters = getStructuredParams(node[i]);
1091
1154
  }
@@ -1167,7 +1230,7 @@ function parseBodystructure(entry) {
1167
1230
  }
1168
1231
  // extension data (not available for BODY requests)
1169
1232
  // md5
1170
- if (i < node.length - 1) {
1233
+ if (i < node.length) {
1171
1234
  if (node[i]) {
1172
1235
  curNode.md5 = (node[i].value || '').toString().toLowerCase();
1173
1236
  }
@@ -1177,7 +1240,7 @@ function parseBodystructure(entry) {
1177
1240
  // the following are shared extension values (for both multipart and non-multipart parts)
1178
1241
  // not available for BODY requests
1179
1242
  // body disposition
1180
- if (i < node.length - 1) {
1243
+ if (i < node.length) {
1181
1244
  let disposition = node[i];
1182
1245
  if (Array.isArray(disposition) && disposition.length) {
1183
1246
  curNode.disposition = ((disposition[0] && disposition[0].value) || '').toString().toLowerCase();
@@ -1188,7 +1251,7 @@ function parseBodystructure(entry) {
1188
1251
  i++;
1189
1252
  }
1190
1253
  // body language
1191
- if (i < node.length - 1) {
1254
+ if (i < node.length) {
1192
1255
  if (node[i]) {
1193
1256
  /* c8 ignore next */ // node[i] is truthy inside this guard, so the [] fallback is unreachable
1194
1257
  curNode.language = [].concat(node[i] || []).map(val => ((val && val.value) || '').toString().toLowerCase());
@@ -1198,7 +1261,7 @@ function parseBodystructure(entry) {
1198
1261
  // body location
1199
1262
  // NB! defined as a "string list" in RFC3501 but replaced in errata document with "string"
1200
1263
  // Errata: http://www.rfc-editor.org/errata_search.php?rfc=3501
1201
- if (i < node.length - 1) {
1264
+ if (i < node.length) {
1202
1265
  if (node[i]) {
1203
1266
  curNode.location = (node[i].value || '').toString();
1204
1267
  }
@@ -1245,7 +1308,7 @@ function formatDate(value) {
1245
1308
  if (!date) {
1246
1309
  return;
1247
1310
  }
1248
- let dateParts = date.toISOString().substr(0, 10).split('-');
1311
+ let dateParts = date.toISOString().substring(0, 10).split('-');
1249
1312
  dateParts.reverse();
1250
1313
  let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1251
1314
  dateParts[1] = months[Number(dateParts[1]) - 1];
@@ -1263,7 +1326,7 @@ function formatDateTime(value) {
1263
1326
  return;
1264
1327
  }
1265
1328
  let dateStr = formatDate(date).replace(/^0/, ' '); //starts with date-day-fixed with leading 0 replaced by SP
1266
- let timeStr = date.toISOString().substr(11, 8);
1329
+ let timeStr = date.toISOString().substring(11, 19);
1267
1330
  return `${dateStr} ${timeStr} +0000`;
1268
1331
  }
1269
1332
  /**
@@ -1417,8 +1480,8 @@ function expandRange(range) {
1417
1480
  }
1418
1481
  continue;
1419
1482
  }
1420
- let first = Number(entry.substr(0, colon));
1421
- let second = Number(entry.substr(colon + 1));
1483
+ let first = Number(entry.substring(0, colon));
1484
+ let second = Number(entry.slice(colon + 1));
1422
1485
  if (!isValidSequenceValue(first) || !isValidSequenceValue(second)) {
1423
1486
  continue;
1424
1487
  }
@@ -207,26 +207,32 @@ export interface IdInfoObject {
207
207
  'support-url'?: string | false | undefined;
208
208
  /** Date program was released */
209
209
  date?: Date | string | false | undefined;
210
- [key: string]: any;
210
+ /** Any other field, sent as its string form */
211
+ [key: string]: unknown;
212
+ }
213
+ /**
214
+ * Usage and limit of one quota resource. The `storage` values are bytes (the wire format is
215
+ * kilobytes), the other resources are counts
216
+ */
217
+ export interface QuotaResource {
218
+ /** Current usage, missing when the server did not send a usable number */
219
+ usage?: number | undefined;
220
+ /** The limit, missing when the server did not send a usable number */
221
+ limit?: number | undefined;
222
+ /** Usage as a percentage of the limit, e.g. "50%", set once a limit above zero is known */
223
+ status?: string | undefined;
211
224
  }
212
225
  export interface QuotaResponse {
213
226
  /** Mailbox path this quota applies to */
214
227
  path: string;
215
- /** Storage quota if provided by server */
216
- storage?: {
217
- /** Used storage in bytes */
218
- used: number;
219
- /** Total storage available */
220
- limit: number;
221
- } | undefined;
222
- /** Message count quota if provided by server */
223
- messages?: {
224
- /** Stored messages */
225
- used: number;
226
- /** Maximum messages allowed */
227
- limit: number;
228
- } | undefined;
229
- [resource: string]: any;
228
+ /** The quota root the server reported for the mailbox, if any */
229
+ quotaRoot?: string | undefined;
230
+ /** The STORAGE resource, if the server reports one */
231
+ storage?: QuotaResource | undefined;
232
+ /** The MESSAGE resource, if the server reports one */
233
+ message?: QuotaResource | undefined;
234
+ /** Any other resource the server reports, under its lowercased name (e.g. "mailbox") */
235
+ [resource: string]: QuotaResource | string | undefined;
230
236
  }
231
237
  /**
232
238
  * Status data items to request with `status()` or the `statusQuery` listing option
@@ -616,6 +622,14 @@ export interface DownloadObject {
616
622
  /** Streamed content */
617
623
  content: Readable;
618
624
  }
625
+ /**
626
+ * What `download()` resolves with when there is nothing to download: no mailbox is selected, or
627
+ * the message or part was not found. Check `content` before using the result.
628
+ */
629
+ export interface DownloadNotFound {
630
+ meta?: undefined;
631
+ content?: undefined;
632
+ }
619
633
  export interface DownloadOptions {
620
634
  /** If true then uses UID number instead of sequence number for `range` */
621
635
  uid?: boolean | undefined;
@@ -1,4 +1,4 @@
1
- import { formatFlag, canUseFlag, formatDateTime, normalizePath, encodePath, comparePaths, enhanceCommandError, parseBigIntValue, parseUintValue, MAX_UINT32_DIGITS } from '../tools.js';
1
+ import { formatFlag, canUseFlag, formatDateTime, normalizePath, encodePath, comparePaths, parseBigIntValue, parseUintValue, MAX_UINT32_DIGITS, getSelectedMailbox, emitSafe, isAuthenticatedState, reportCommandError } from '../tools.js';
2
2
  /**
3
3
  * Appends a message to a mailbox.
4
4
  *
@@ -11,7 +11,7 @@ import { formatFlag, canUseFlag, formatDateTime, normalizePath, encodePath, comp
11
11
  * @throws {Error} If the APPEND command fails or message exceeds APPENDLIMIT
12
12
  */
13
13
  export default async function append(connection, destination, content, flags, idate) {
14
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !destination) {
14
+ if (!isAuthenticatedState(connection) || !destination) {
15
15
  // nothing to do here
16
16
  return;
17
17
  }
@@ -31,7 +31,9 @@ export default async function append(connection, destination, content, flags, id
31
31
  destination = normalizePath(connection, destination);
32
32
  // If appending to the currently selected mailbox, we can listen for the
33
33
  // untagged EXISTS response to capture the new message's sequence number.
34
- let expectExists = comparePaths(connection, connection.mailbox.path, destination);
34
+ let selected = getSelectedMailbox(connection);
35
+ // The selected mailbox when appending to it, false otherwise
36
+ const targetMailbox = selected && comparePaths(connection, selected.path, destination) ? selected : false;
35
37
  // Validate and format flags. Only flags allowed by the mailbox's permanentFlags are included.
36
38
  flags = (Array.isArray(flags) ? flags : [].concat(flags || []))
37
39
  .map(flag => flag && formatFlag(flag.toString()))
@@ -74,13 +76,12 @@ export default async function append(connection, destination, content, flags, id
74
76
  map.seq = seq;
75
77
  // Update the connection's mailbox state and emit 'exists' event if the
76
78
  // count changed (notifies listeners about the new message).
77
- if (expectExists) {
78
- let mailbox = connection.mailbox;
79
- let prevCount = mailbox.exists;
79
+ if (targetMailbox) {
80
+ let prevCount = targetMailbox.exists;
80
81
  if (map.seq !== prevCount) {
81
- mailbox.exists = map.seq;
82
- connection.emit('exists', {
83
- path: mailbox.path,
82
+ targetMailbox.exists = map.seq;
83
+ emitSafe(connection, 'exists', {
84
+ path: targetMailbox.path,
84
85
  count: map.seq,
85
86
  prevCount
86
87
  });
@@ -91,7 +92,7 @@ export default async function append(connection, destination, content, flags, id
91
92
  try {
92
93
  response = await connection.exec('APPEND', attributes, {
93
94
  // Only listen for EXISTS if we're appending to the currently selected mailbox
94
- untagged: expectExists ? { EXISTS: handleExistsUpdate } : false
95
+ untagged: targetMailbox ? { EXISTS: handleExistsUpdate } : false
95
96
  });
96
97
  // UIDPLUS (RFC 4315): the server may include APPENDUID response code in
97
98
  // the tagged OK. Format: [APPENDUID <uidValidity> <uid>]
@@ -116,7 +117,7 @@ export default async function append(connection, destination, content, flags, id
116
117
  response.next();
117
118
  // If we didn't get an EXISTS during APPEND (some servers don't send it
118
119
  // until the next command), issue a NOOP to flush pending notifications.
119
- if (expectExists && !map.seq) {
120
+ if (targetMailbox && !map.seq) {
120
121
  try {
121
122
  response = await connection.exec('NOOP', false, {
122
123
  untagged: { EXISTS: handleExistsUpdate },
@@ -139,8 +140,7 @@ export default async function append(connection, destination, content, flags, id
139
140
  return map;
140
141
  }
141
142
  catch (err) {
142
- await enhanceCommandError(err);
143
- connection.log.warn({ err, cid: connection.id });
143
+ await reportCommandError(connection, err);
144
144
  throw err;
145
145
  }
146
146
  }
@@ -1,16 +1,11 @@
1
1
  import type { ImapFlow } from '../imap-flow.js';
2
+ import type { AuthOptions } from '../types.js';
2
3
  /**
3
- * Credentials for the AUTHENTICATE command
4
+ * Credentials for the AUTHENTICATE command: the auth options, with the password passed as `password`
4
5
  */
5
- export interface AuthenticateCredentials {
6
- /** OAuth2 access token for OAUTHBEARER/XOAUTH2 authentication */
7
- accessToken?: string | undefined;
6
+ export interface AuthenticateCredentials extends Omit<AuthOptions, 'user' | 'pass'> {
8
7
  /** Password for PLAIN or LOGIN authentication */
9
8
  password?: string | undefined;
10
- /** Force a specific login method (e.g., 'AUTH=PLAIN', 'AUTH=LOGIN') */
11
- loginMethod?: string | undefined;
12
- /** Authorization identity for PLAIN authentication */
13
- authzid?: string | undefined;
14
9
  }
15
10
  /**
16
11
  * Authenticates user using the best available method.
@@ -1,3 +1,4 @@
1
+ import { emitSafe } from '../tools.js';
1
2
  /**
2
3
  * Closes the currently selected mailbox.
3
4
  *
@@ -23,7 +24,7 @@ export default async function close(connection) {
23
24
  connection.currentSelectCommand = false;
24
25
  connection.state = connection.states.AUTHENTICATED;
25
26
  if (currentMailbox) {
26
- connection.emit('mailboxClose', currentMailbox);
27
+ emitSafe(connection, 'mailboxClose', currentMailbox);
27
28
  }
28
29
  return true;
29
30
  }
@@ -1,4 +1,4 @@
1
- import { normalizePath, encodePath, enhanceCommandError } from '../tools.js';
1
+ import { normalizePath, encodePath, reportCommandError, getSelectedMailbox } from '../tools.js';
2
2
  import { parseCopyUid } from './copyuid-parser.js';
3
3
  /**
4
4
  * Copies messages from the current mailbox to another mailbox.
@@ -11,7 +11,8 @@ import { parseCopyUid } from './copyuid-parser.js';
11
11
  * @returns Copy result with UID mapping if available, false on failure, or undefined if preconditions not met
12
12
  */
13
13
  export default async function copy(connection, range, destination, options) {
14
- if (connection.state !== connection.states.SELECTED || !range || !destination) {
14
+ let mailbox = getSelectedMailbox(connection);
15
+ if (!mailbox || !range || !destination) {
15
16
  // nothing to do here
16
17
  return;
17
18
  }
@@ -25,15 +26,14 @@ export default async function copy(connection, range, destination, options) {
25
26
  try {
26
27
  response = await connection.exec(options.uid ? 'UID COPY' : 'COPY', attributes);
27
28
  response.next();
28
- let map = { path: connection.mailbox.path, destination };
29
+ let map = { path: mailbox.path, destination };
29
30
  // UIDPLUS (RFC 4315): the server may include a COPYUID response code in the
30
31
  // tagged OK response, providing a mapping from source UIDs to destination UIDs.
31
32
  parseCopyUid(response.response, map);
32
33
  return map;
33
34
  }
34
35
  catch (err) {
35
- await enhanceCommandError(err);
36
- connection.log.warn({ err, cid: connection.id });
36
+ await reportCommandError(connection, err);
37
37
  return false;
38
38
  }
39
39
  }
@@ -1,4 +1,4 @@
1
- import { encodePath, normalizePath, getStatusCode, enhanceCommandError } from '../tools.js';
1
+ import { encodePath, normalizePath, getStatusCode, isAuthenticatedState, reportCommandError } from '../tools.js';
2
2
  /**
3
3
  * Creates a new mailbox and subscribes to it.
4
4
  *
@@ -8,7 +8,7 @@ import { encodePath, normalizePath, getStatusCode, enhanceCommandError } from '.
8
8
  * @throws If the CREATE command fails (except when mailbox already exists)
9
9
  */
10
10
  export default async function create(connection, path) {
11
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
11
+ if (!isAuthenticatedState(connection)) {
12
12
  // nothing to do here
13
13
  return;
14
14
  }
@@ -68,8 +68,7 @@ export default async function create(connection, path) {
68
68
  created: false
69
69
  };
70
70
  }
71
- await enhanceCommandError(err);
72
- connection.log.warn({ err, cid: connection.id });
71
+ await reportCommandError(connection, err);
73
72
  throw err;
74
73
  }
75
74
  }
@@ -1,4 +1,4 @@
1
- import { encodePath, normalizePath, enhanceCommandError } from '../tools.js';
1
+ import { encodePath, normalizePath, isAuthenticatedState, reportCommandError, getSelectedMailbox } from '../tools.js';
2
2
  /**
3
3
  * Deletes an existing mailbox.
4
4
  *
@@ -8,14 +8,15 @@ import { encodePath, normalizePath, enhanceCommandError } from '../tools.js';
8
8
  * @throws If the DELETE command fails
9
9
  */
10
10
  export default async function deleteMailbox(connection, path) {
11
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
11
+ if (!isAuthenticatedState(connection)) {
12
12
  // nothing to do here
13
13
  return;
14
14
  }
15
15
  path = normalizePath(connection, path);
16
16
  // If the mailbox to delete is currently selected, we must close/deselect it first.
17
17
  // IMAP servers reject DELETE on the currently selected mailbox (RFC 3501 6.3.4).
18
- if (connection.state === connection.states.SELECTED && connection.mailbox.path === path) {
18
+ let selected = getSelectedMailbox(connection);
19
+ if (selected && selected.path === path) {
19
20
  await connection.run('CLOSE');
20
21
  }
21
22
  let response;
@@ -28,8 +29,7 @@ export default async function deleteMailbox(connection, path) {
28
29
  return map;
29
30
  }
30
31
  catch (err) {
31
- await enhanceCommandError(err);
32
- connection.log.warn({ err, cid: connection.id });
32
+ await reportCommandError(connection, err);
33
33
  throw err;
34
34
  }
35
35
  }