imapflow 2.2.7 → 2.2.9

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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.2.9](https://github.com/postalsys/imapflow/compare/v2.2.8...v2.2.9) (2026-10-07)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * declare DownloadOptions.binary, the QRESYNC mailboxOpen options and FetchQueryObject.emailId ([2ae26e6](https://github.com/postalsys/imapflow/commit/2ae26e64c39c83ac3e04a67e9d4d808a1258c55b))
9
+
10
+ ## [2.2.8](https://github.com/postalsys/imapflow/compare/v2.2.7...v2.2.8) (2026-10-07)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * decrement mailbox.exists on untagged VANISHED (RFC 7162 section 3.2.10) ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
16
+ * do not send sequence sets to an empty mailbox ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
17
+ * drop flags and keywords that are not atoms instead of sending them quoted ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
18
+ * encode and decode non-ASCII Gmail labels as modified UTF-7 like mailbox names ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
19
+ * expand the FETCH ALL, FAST and FULL macros instead of sending them in a list ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
20
+ * leave servername out of tls.connect() for IP literal hosts, which Bun rejects ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
21
+ * refetch body sections Apache James drops, check FETCH answers belong to the download, enable CONDSTORE with QRESYNC ([6973263](https://github.com/postalsys/imapflow/commit/697326393a4a66e743822d7fb0ac045454458492))
22
+ * send the OAuth token after the continuation request when SASL-IR is not advertised ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
23
+ * send the STORE UNCHANGEDSINCE modifier before the flags (RFC 7162 section 3.1.3) ([b40cea2](https://github.com/postalsys/imapflow/commit/b40cea22d19edd10428fe1cda98115c2f8b6cd7a))
24
+
3
25
  ## [2.2.7](https://github.com/postalsys/imapflow/compare/v2.2.6...v2.2.7) (2026-10-07)
4
26
 
5
27
 
@@ -66,15 +66,26 @@ async function authOauth(connection, username, accessToken) {
66
66
  // Empty breaker: XOAUTH2 expects an empty response to abort the SASL exchange
67
67
  breaker = '';
68
68
  }
69
+ let encoded = Buffer.from(oauthbearer).toString('base64');
70
+ // Without SASL-IR the payload may not ride on the command line (RFC 4959 section 3): it is
71
+ // sent as the answer to the first, empty continuation request instead
72
+ let payloadPending = !connection.capabilities.has('SASL-IR');
69
73
  let errorResponse = false;
70
74
  try {
71
- let response = await connection.exec('AUTHENTICATE', [
72
- { type: 'ATOM', value: command },
73
- { type: 'ATOM', value: Buffer.from(oauthbearer).toString('base64'), sensitive: true }
74
- ], {
75
+ let attributes = [{ type: 'ATOM', value: command }];
76
+ if (!payloadPending) {
77
+ attributes.push({ type: 'ATOM', value: encoded, sensitive: true });
78
+ }
79
+ let response = await connection.exec('AUTHENTICATE', attributes, {
75
80
  // Server sends a "+" continuation if auth fails, with a base64 JSON error payload.
76
81
  // We decode it for diagnostics, then send the breaker to terminate the exchange.
77
82
  onPlusTag: async (resp) => {
83
+ if (payloadPending) {
84
+ payloadPending = false;
85
+ connection.log.debug({ src: 'c', msg: '(* value hidden *)', comment: `Encoded response for AUTH=${command}`, cid: connection.id });
86
+ connection.write(encoded);
87
+ return;
88
+ }
78
89
  if (resp.attributes && resp.attributes[0] && resp.attributes[0].type === 'TEXT') {
79
90
  try {
80
91
  errorResponse = JSON.parse(Buffer.from(resp.attributes[0].value, 'base64').toString());
@@ -49,6 +49,12 @@ async function enable(connection, extensionList) {
49
49
  // extensions enabled by this command (RFC 5161), so a replace would drop
50
50
  // grants from an earlier ENABLE call
51
51
  connection.enabled = new Set([...connection.enabled, ...enabled]);
52
+ if (connection.enabled.has('QRESYNC')) {
53
+ // ENABLE QRESYNC is a CONDSTORE enabling command (RFC 7162 3.2.3), whether or not the
54
+ // server lists CONDSTORE in its ENABLED answer. Apache James advertises only QRESYNC
55
+ // and leaves a lone ENABLE CONDSTORE unanswered, which the RFC allows.
56
+ connection.enabled.add('CONDSTORE');
57
+ }
52
58
  response.next();
53
59
  return connection.enabled;
54
60
  }
@@ -65,13 +65,30 @@ async function fetch(connection, range, query, options) {
65
65
  };
66
66
  queryStructure.push(bodyPeek);
67
67
  };
68
- // IMAP fetch macros (ALL, FAST, FULL) and standard data items map directly to IMAP atoms
69
- ['all', 'fast', 'full', 'uid', 'flags', 'bodyStructure', 'envelope', 'internalDate'].forEach(key => {
70
- if (query[key]) {
68
+ // The ALL, FAST and FULL macros may only be sent on their own, never in a list with other
69
+ // items (RFC 3501 section 9), and UID is always in the list, so they are expanded into
70
+ // the items they stand for. FULL is expanded to BODYSTRUCTURE rather than the
71
+ // non-extensible BODY, as documented for the full option.
72
+ let full = !!query.full;
73
+ let all = !!query.all || full;
74
+ let fast = !!query.fast || all;
75
+ let items = {
76
+ flags: query.flags || fast,
77
+ internalDate: query.internalDate || fast,
78
+ size: query.size || fast,
79
+ envelope: query.envelope || all,
80
+ bodyStructure: query.bodyStructure || full
81
+ };
82
+ // standard data items map directly to IMAP atoms
83
+ if (query.uid) {
84
+ queryStructure.push({ type: 'ATOM', value: 'UID' });
85
+ }
86
+ ['flags', 'bodyStructure', 'envelope', 'internalDate'].forEach(key => {
87
+ if (items[key]) {
71
88
  queryStructure.push({ type: 'ATOM', value: key.toUpperCase() });
72
89
  }
73
90
  });
74
- if (query.size) {
91
+ if (items.size) {
75
92
  queryStructure.push({ type: 'ATOM', value: 'RFC822.SIZE' });
76
93
  }
77
94
  // Fetch full message source, optionally with byte range (start/maxLength)
@@ -194,7 +211,7 @@ async function fetch(connection, range, query, options) {
194
211
  if (consumerError) {
195
212
  return;
196
213
  }
197
- let formatted = await (0, tools_js_1.formatMessageResponse)(untagged, mailbox, connection.idHashAlgorithm);
214
+ let formatted = await (0, tools_js_1.formatMessageResponse)(untagged, mailbox, connection.idHashAlgorithm, connection);
198
215
  if (typeof options.onUntaggedFetch === 'function') {
199
216
  /* c8 ignore next */ // a UID FETCH row without its UID is a non-compliant server, so the seq fallback is not exercised
200
217
  let key = options.uid ? formatted.uid || formatted.seq : formatted.seq;
@@ -1,24 +1,13 @@
1
1
  import type { ImapFlow } from '../imap-flow.js';
2
2
  import type { MailboxObject, MailboxOpenOptions } from '../types.js';
3
- /**
4
- * Options for SELECT/EXAMINE: the public open options plus the QRESYNC resynchronization
5
- * parameters, which are only honored when the QRESYNC extension has been enabled
6
- */
7
- export interface SelectOptions extends MailboxOpenOptions {
8
- /** QRESYNC modseq value to fetch changes since */
9
- changedSince?: bigint | number | string | undefined;
10
- /** QRESYNC UID validity value */
11
- uidValidity?: bigint | number | string | undefined;
12
- }
3
+ /** SELECT/EXAMINE options, the QRESYNC parameters are part of the public mailboxOpen() options */
4
+ export type SelectOptions = MailboxOpenOptions;
13
5
  /**
14
6
  * Selects or examines a mailbox, making it the current mailbox for subsequent operations.
15
7
  *
16
8
  * @param connection - IMAP connection instance
17
9
  * @param path - Mailbox path to select
18
- * @param options - Select options
19
- * @param options.readOnly - If true, use EXAMINE instead of SELECT (read-only access)
20
- * @param options.changedSince - QRESYNC modseq value to fetch changes since
21
- * @param options.uidValidity - QRESYNC UID validity value
10
+ * @param options - Select options, see MailboxOpenOptions
22
11
  * @returns Mailbox info object with path, flags, exists, uidNext, uidValidity, highestModseq, etc., or undefined if preconditions not met
23
12
  * @throws If the SELECT/EXAMINE command fails
24
13
  */
@@ -51,10 +51,7 @@ const VALUED_RESPONSE_CODES = Object.assign(Object.create(null), {
51
51
  *
52
52
  * @param connection - IMAP connection instance
53
53
  * @param path - Mailbox path to select
54
- * @param options - Select options
55
- * @param options.readOnly - If true, use EXAMINE instead of SELECT (read-only access)
56
- * @param options.changedSince - QRESYNC modseq value to fetch changes since
57
- * @param options.uidValidity - QRESYNC UID validity value
54
+ * @param options - Select options, see MailboxOpenOptions
58
55
  * @returns Mailbox info object with path, flags, exists, uidNext, uidValidity, highestModseq, etc., or undefined if preconditions not met
59
56
  * @throws If the SELECT/EXAMINE command fails
60
57
  */
@@ -61,7 +61,10 @@ async function store(connection, range, flags, options) {
61
61
  const dropped = [];
62
62
  flags = (Array.isArray(flags) ? flags : [].concat(flags || []))
63
63
  .map(flag => {
64
- let formatted = (0, tools_js_1.formatFlag)(flag);
64
+ // Gmail labels other than the \-prefixed system labels are mailbox names: astrings in
65
+ // the form mailbox names take on the session (modified UTF-7 unless UTF-8 is enabled),
66
+ // not atoms like IMAP keywords
67
+ let formatted = options.useLabels && flag && flag.charAt(0) !== '\\' ? (0, tools_js_1.encodePath)(connection, flag) : (0, tools_js_1.formatFlag)(flag);
65
68
  if (!formatted || (!(0, tools_js_1.canUseFlag)(flagSource, formatted) && operationName !== 'remove')) {
66
69
  dropped.push(flag);
67
70
  return false;
@@ -83,13 +86,10 @@ async function store(connection, range, flags, options) {
83
86
  if (!flags.length && !clearAll) {
84
87
  return false;
85
88
  }
86
- let attributes = [
87
- { type: 'SEQUENCE', value: range },
88
- { type: 'ATOM', value: operation },
89
- flags.map(flag => ({ type: 'ATOM', value: flag }))
90
- ];
89
+ let attributes = [{ type: 'SEQUENCE', value: range }];
91
90
  // CONDSTORE (RFC 7162): UNCHANGEDSINCE modifier prevents updating messages whose
92
91
  // mod-sequence is higher than the specified value, avoiding overwriting concurrent changes.
92
+ // The store-modifiers list goes between the sequence set and the item name (section 3.1.3).
93
93
  if (options.unchangedSince && connection.enabled.has('CONDSTORE') && !mailbox.noModseq) {
94
94
  attributes.push([
95
95
  {
@@ -102,6 +102,7 @@ async function store(connection, range, flags, options) {
102
102
  }
103
103
  ]);
104
104
  }
105
+ attributes.push({ type: 'ATOM', value: operation }, flags.map(flag => ({ type: 'ATOM', value: flag })));
105
106
  let response;
106
107
  try {
107
108
  response = await connection.exec(options.uid ? 'UID STORE' : 'STORE', attributes);
@@ -19,6 +19,113 @@ const limited_passthrough_js_1 = require("./limited-passthrough.js");
19
19
  // away (a consumer destroying it closes it without a 'drain')
20
20
  const DRAIN_WAIT_EVENTS = ['drain', 'error', 'close'];
21
21
  const tools_js_1 = require("./tools.js");
22
+ const isEmptySection = (value) => !value?.length;
23
+ /**
24
+ * The section to ask again when exactly one of a part's MIME headers and content came back
25
+ * empty (see refetchDroppedSections()), undefined when both or neither did
26
+ */
27
+ const droppedSection = (mime, content, mimeRequest, contentRequest) => {
28
+ if (isEmptySection(mime) === isEmptySection(content)) {
29
+ return undefined;
30
+ }
31
+ return isEmptySection(content) ? contentRequest : mimeRequest;
32
+ };
33
+ /** Start offset of every partial section among the requests, keyed by section */
34
+ const partialStarts = (requests) => {
35
+ let starts = new Map();
36
+ for (let request of requests) {
37
+ if (typeof request !== 'string') {
38
+ starts.set(request.key, Number(request.start) || 0);
39
+ }
40
+ }
41
+ return starts;
42
+ };
43
+ // How many times a request is repeated after answers that belong to another request
44
+ const MAX_FOREIGN_ANSWERS = 3;
45
+ const requestedUid = (range, options) => options.uid && /^\d+$/.test(String(range)) ? Number(range) : undefined;
46
+ const isForeignAnswer = (response, expected) => {
47
+ if (expected.uid && response.uid && response.uid !== expected.uid) {
48
+ return true;
49
+ }
50
+ for (let [key, start] of expected.origins) {
51
+ let origin = response.partialOrigins && response.partialOrigins.get(key);
52
+ // An answer without the origin is taken as is: some servers leave it out, and some
53
+ // ignore the partial specifier altogether
54
+ if (typeof origin === 'number' && origin !== start) {
55
+ return true;
56
+ }
57
+ }
58
+ return false;
59
+ };
60
+ /**
61
+ * fetchOne() that takes only an answer belonging to the request. Apache James now and then
62
+ * writes the head of a FETCH answer after its tagged OK, so the data of one request shows up
63
+ * within the answer to the next one. Taken at face value it would be the data of that next
64
+ * request, and a download would end without an error but with misplaced bytes. An answer for
65
+ * another UID, or with a partial section that starts at another offset than asked, is dropped
66
+ * and the request repeated.
67
+ */
68
+ async function fetchExpected(client, range, query, options, expected) {
69
+ for (let attempt = 1;; attempt++) {
70
+ let response = await client.fetchOne(range, query, options);
71
+ if (!response || !isForeignAnswer(response, expected)) {
72
+ return response;
73
+ }
74
+ client.log.warn({
75
+ msg: 'Server answered with data of another request, asking again',
76
+ uid: response.uid,
77
+ origins: response.partialOrigins && Object.fromEntries(response.partialOrigins),
78
+ attempt,
79
+ cid: client.id
80
+ });
81
+ if (attempt >= MAX_FOREIGN_ANSWERS) {
82
+ let err = new Error('Server kept answering with data of another request');
83
+ err.code = 'DownloadIncomplete';
84
+ err.cid = client.id;
85
+ throw err;
86
+ }
87
+ }
88
+ }
89
+ /**
90
+ * Apache James (and the servers built on it, Twake Mail among them) answers only the first
91
+ * section it is asked for each MIME part of one FETCH and returns the other one empty:
92
+ * BODY[2.MIME] with BODY[2] yields the headers and a zero-length body, the reverse order loses
93
+ * the headers (FetchGroup.addPartContent() keeps the first descriptor for a part path). Asks the
94
+ * sections that came back empty again, in a FETCH of their own, and merges the answer into
95
+ * `response`. Callers only list a section whose companion did arrive, so a compliant server
96
+ * pays the extra round trip only for a part that really is empty.
97
+ */
98
+ async function refetchDroppedSections(client, response, range, options, sections) {
99
+ if (!sections.length) {
100
+ return;
101
+ }
102
+ client.log.debug({
103
+ msg: 'Server answered a body section empty while its companion section was not, asking it again separately',
104
+ sections: sections.map(section => (typeof section === 'string' ? section : section.key)),
105
+ cid: client.id
106
+ });
107
+ // the UID pins the message even when the first command addressed it by sequence number
108
+ let uid = response.uid;
109
+ let retry = await fetchExpected(client, uid || range, { uid: true, bodyParts: sections }, uid ? { ...options, uid: true } : options, {
110
+ uid,
111
+ origins: partialStarts(sections)
112
+ });
113
+ if (!retry) {
114
+ return;
115
+ }
116
+ if (retry.headers) {
117
+ response.headers = retry.headers;
118
+ }
119
+ for (let [key, value] of retry.bodyParts || []) {
120
+ (response.bodyParts ??= new Map()).set(key, value);
121
+ if (retry.binaryParts && retry.binaryParts.has(key)) {
122
+ (response.binaryParts ??= new Set()).add(key);
123
+ }
124
+ else if (response.binaryParts) {
125
+ response.binaryParts.delete(key);
126
+ }
127
+ }
128
+ }
22
129
  /**
23
130
  * Implements ImapFlow.download(), see its documentation
24
131
  *
@@ -66,6 +173,7 @@ async function downloadMessage(client, range, part, options) {
66
173
  let getNextPart = async (query) => {
67
174
  query = query || {};
68
175
  let mimeKey;
176
+ let contentRequest;
69
177
  if (!part) {
70
178
  query.source = {
71
179
  start: processed,
@@ -88,13 +196,18 @@ async function downloadMessage(client, range, part, options) {
88
196
  query.bodyParts.push(mimeKey);
89
197
  }
90
198
  }
91
- query.bodyParts.push({
199
+ contentRequest = {
92
200
  key: part,
93
201
  start: processed,
94
202
  maxLength: chunkSize
95
- });
203
+ };
204
+ query.bodyParts.push(contentRequest);
96
205
  }
97
- let response = await client.fetchOne(range, query, downloadOptions);
206
+ let expected = {
207
+ uid: uid || requestedUid(range, downloadOptions),
208
+ origins: new Map([[part || '', processed]])
209
+ };
210
+ let response = await fetchExpected(client, range, query, downloadOptions, expected);
98
211
  if (!response) {
99
212
  return { response: false, chunk: false };
100
213
  }
@@ -104,6 +217,12 @@ async function downloadMessage(client, range, part, options) {
104
217
  range = uid;
105
218
  downloadOptions.uid = true;
106
219
  }
220
+ if (mimeKey && contentRequest) {
221
+ let dropped = droppedSection(mimeKey === 'header' ? response.headers : response.bodyParts?.get(mimeKey), response.bodyParts?.get(part), mimeKey, contentRequest);
222
+ if (dropped) {
223
+ await refetchDroppedSections(client, response, range, downloadOptions, [dropped]);
224
+ }
225
+ }
107
226
  let chunk = !part ? response.source : response.bodyParts && response.bodyParts.get(part);
108
227
  if (!chunk) {
109
228
  return {};
@@ -458,16 +577,31 @@ async function downloadMessageParts(client, range, parts, options) {
458
577
  // again on the answer for servers that ignore the partial specifier
459
578
  let maxBytes = (0, limited_passthrough_js_1.normalizeByteLimit)(downloadOptions.maxBytes);
460
579
  let query = { bodyParts: [] };
580
+ let contentRequests = new Map();
461
581
  for (let part of parts) {
462
582
  query.bodyParts.push(part + '.mime');
463
583
  // The partial specifier carries a 32-bit length (RFC 9051 "number"), so a cap beyond
464
584
  // that is applied on the answer alone
465
- query.bodyParts.push(maxBytes > 0xffffffff ? part : { key: part, start: 0, maxLength: maxBytes });
585
+ let contentRequest = maxBytes > 0xffffffff ? part : { key: part, start: 0, maxLength: maxBytes };
586
+ contentRequests.set(part, contentRequest);
587
+ query.bodyParts.push(contentRequest);
466
588
  }
467
- let response = await client.fetchOne(range, query, downloadOptions);
589
+ let response = await fetchExpected(client, range, query, downloadOptions, {
590
+ uid: requestedUid(range, downloadOptions),
591
+ origins: partialStarts(query.bodyParts)
592
+ });
468
593
  if (!response || !response.bodyParts) {
469
594
  return {};
470
595
  }
596
+ let dropped = [];
597
+ for (let [part, contentRequest] of contentRequests) {
598
+ let section = droppedSection(response.bodyParts.get(part + '.mime'), response.bodyParts.get(part), part + '.mime', contentRequest);
599
+ if (section) {
600
+ dropped.push(section);
601
+ }
602
+ }
603
+ // Sections of different parts do not collide, so every dropped one fits in one FETCH
604
+ await refetchDroppedSections(client, response, range, downloadOptions, dropped);
471
605
  let data = {};
472
606
  for (let [part, content] of response.bodyParts) {
473
607
  let keyParts = part.split('.mime');
@@ -122,8 +122,8 @@ export declare class ImapFlow extends EventEmitter {
122
122
  */
123
123
  usable: boolean;
124
124
  /**
125
- * Currently authenticated user or `false` if mailbox is not open
126
- * or `true` if connection was authenticated by PREAUTH
125
+ * `true` once the connection is authenticated (by LOGIN, AUTHENTICATE or a PREAUTH greeting),
126
+ * `false` before that. The user name is in `options.auth.user`
127
127
  */
128
128
  authenticated: string | boolean;
129
129
  /**
@@ -1500,9 +1500,8 @@ class ImapFlow extends node_events_1.EventEmitter {
1500
1500
  // of the IP - accepting any "localhost" certificate for any IP-hosted
1501
1501
  // server, and rejecting legitimate IP-SAN certificates.
1502
1502
  host: this.host,
1503
- servername: this.servername,
1504
1503
  port: this.port
1505
- }, this.options.tls || {});
1504
+ }, this.tlsServername(), this.options.tls || {});
1506
1505
  this.clearSocketHandlers();
1507
1506
  let settled = false;
1508
1507
  // Single settlement path for the upgrade. Every terminal outcome - handshake
@@ -1892,12 +1891,18 @@ class ImapFlow extends node_events_1.EventEmitter {
1892
1891
  uids = untagged.attributes[0].value;
1893
1892
  }
1894
1893
  let uidList = (0, tools_js_1.expandRange)(uids);
1894
+ let earlier = tags.includes('EARLIER');
1895
+ // RFC 7162 section 3.2.10: unlike VANISHED (EARLIER), a plain VANISHED reports messages the
1896
+ // client knows about and decrements the message count like the same number of EXPUNGEs would
1897
+ if (!earlier) {
1898
+ mailbox.exists = Math.max(0, mailbox.exists - uidList.length);
1899
+ }
1895
1900
  for (let uid of uidList) {
1896
1901
  let payload = {
1897
1902
  path: mailbox.path,
1898
1903
  uid,
1899
1904
  vanished: true,
1900
- earlier: tags.includes('EARLIER')
1905
+ earlier
1901
1906
  };
1902
1907
  await this.notifyExpunge(payload);
1903
1908
  }
@@ -1909,7 +1914,7 @@ class ImapFlow extends node_events_1.EventEmitter {
1909
1914
  // mailbox closed, ignore
1910
1915
  return;
1911
1916
  }
1912
- let message = await (0, tools_js_1.formatMessageResponse)(untagged, mailbox, this.idHashAlgorithm);
1917
+ let message = await (0, tools_js_1.formatMessageResponse)(untagged, mailbox, this.idHashAlgorithm, this);
1913
1918
  if (message.flags) {
1914
1919
  let updateEvent = {
1915
1920
  path: mailbox.path,
@@ -1938,6 +1943,12 @@ class ImapFlow extends node_events_1.EventEmitter {
1938
1943
  }
1939
1944
  return true;
1940
1945
  }
1946
+ // servername for tls.connect(), left out for an IP literal host (this.servername is false then):
1947
+ // Node treats a false value like a missing one, but Bun throws a TypeError for it
1948
+ /** @internal */
1949
+ tlsServername() {
1950
+ return this.servername ? { servername: this.servername } : {};
1951
+ }
1941
1952
  // Normalizes a message range from various input formats into an IMAP-compatible
1942
1953
  // sequence string (e.g., "1:5,7,10:*"). Handles: numbers, "*", {all:true},
1943
1954
  // {uid:value}, search query objects (resolved via SEARCH), and arrays of numbers.
@@ -1980,6 +1991,11 @@ class ImapFlow extends node_events_1.EventEmitter {
1980
1991
  if (!value) {
1981
1992
  return false;
1982
1993
  }
1994
+ // An empty mailbox has no message numbers: every sequence set, "1:*" included, would get a
1995
+ // BAD (RFC 9051 section 9, seq-number). UID sets may point past the end, so they are sent.
1996
+ if (!options.uid && this.mailbox && !this.mailbox.exists) {
1997
+ return false;
1998
+ }
1983
1999
  return value;
1984
2000
  }
1985
2001
  // The single definition of "the connection is not free". A held or queued mailbox lock, a
@@ -2049,9 +2065,8 @@ class ImapFlow extends node_events_1.EventEmitter {
2049
2065
  let connector = this.secureConnection ? node_tls_1.default : node_net_1.default;
2050
2066
  let opts = Object.assign({
2051
2067
  host: this.host,
2052
- servername: this.servername,
2053
2068
  port: this.port
2054
- }, this.options.tls || {});
2069
+ }, this.tlsServername(), this.options.tls || {});
2055
2070
  this.untaggedHandlers.OK = (...args) => this.initialOK(...args);
2056
2071
  this.untaggedHandlers.BYE = (...args) => this.serverBye(...args);
2057
2072
  this.untaggedHandlers.PREAUTH = () => this.initialPREAUTH();
@@ -1,3 +1,3 @@
1
1
  export declare const name = "imapflow";
2
- export declare const version = "2.2.7";
2
+ export declare const version = "2.2.9";
3
3
  export declare const homepage = "https://imapflow.com/";
@@ -3,5 +3,5 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.homepage = exports.version = exports.name = void 0;
5
5
  exports.name = "imapflow";
6
- exports.version = "2.2.7";
6
+ exports.version = "2.2.9";
7
7
  exports.homepage = "https://imapflow.com/";
@@ -371,10 +371,13 @@ const searchCompiler = (connection, query) => {
371
371
  fail('InvalidSearchQuery', `Search value for ${term.toLowerCase()} must be a string`);
372
372
  }
373
373
  let flag = (0, tools_js_1.formatFlag)(params[term]);
374
- // formatFlag() refuses \Recent, which is not a keyword. Dropping the
375
- // criterion would widen the search, so the query is refused instead
374
+ // formatFlag() refuses \Recent, which is not a keyword, and values that are
375
+ // not atoms. Dropping the criterion would widen the search, so the query is
376
+ // refused instead
376
377
  if (flag === false) {
377
- fail('InvalidSearchQuery', `${params[term]} can not be searched as a keyword, use the "recent" search key instead`);
378
+ fail('InvalidSearchQuery', /^\\recent$/i.test(params[term])
379
+ ? `${params[term]} can not be searched as a keyword, use the "recent" search key instead`
380
+ : `${params[term]} is not a valid keyword`);
378
381
  }
379
382
  // Compiled even when the mailbox does not allow the keyword: the
380
383
  // correct answer is then the empty set, which dropping the
@@ -293,9 +293,10 @@ export declare function getColorFlags(color: string | null | undefined): {
293
293
  * @param untagged - Parsed untagged IMAP response
294
294
  * @param mailbox - Current mailbox state object
295
295
  * @param idHashAlgorithm - Hash for the fallback message id, `md5` unless the client was told otherwise
296
+ * @param connection - Connection the response arrived on, decodes Gmail labels like mailbox names
296
297
  * @returns Formatted message object with properties like seq, uid, flags, envelope, etc.
297
298
  */
298
- export declare function formatMessageResponse(untagged: ImapResponse, mailbox: MailboxObject, idHashAlgorithm?: string): Promise<FetchMessageObject>;
299
+ export declare function formatMessageResponse(untagged: ImapResponse, mailbox: MailboxObject, idHashAlgorithm?: string, connection?: ImapFlow): Promise<FetchMessageObject>;
299
300
  /**
300
301
  * Strips surrounding double quotes from a name string.
301
302
  *
@@ -364,8 +365,8 @@ export declare function formatDate(value: unknown): string | undefined;
364
365
  */
365
366
  export declare function formatDateTime(value: unknown): string | undefined;
366
367
  /**
367
- * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent),
368
- * and capitalizes system flags properly.
368
+ * Normalizes a flag string. Returns false for non-settable flags (e.g. \Recent) and for
369
+ * values that are not valid flags (keywords must be atoms), and capitalizes system flags properly.
369
370
  *
370
371
  * @param flag - Flag string to normalize
371
372
  * @returns Normalized flag string, or false if the flag cannot be set