imap-wizard 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +155 -0
- package/README.md +495 -2
- package/dist/app.d.ts +61 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +201 -0
- package/dist/app.js.map +1 -0
- package/dist/cache/body-cache.d.ts +29 -0
- package/dist/cache/body-cache.d.ts.map +1 -0
- package/dist/cache/body-cache.js +95 -0
- package/dist/cache/body-cache.js.map +1 -0
- package/dist/cache/schema.d.ts +40 -0
- package/dist/cache/schema.d.ts.map +1 -0
- package/dist/cache/schema.js +160 -0
- package/dist/cache/schema.js.map +1 -0
- package/dist/cache/store.d.ts +233 -0
- package/dist/cache/store.d.ts.map +1 -0
- package/dist/cache/store.js +556 -0
- package/dist/cache/store.js.map +1 -0
- package/dist/cache/sync-engine.d.ts +140 -0
- package/dist/cache/sync-engine.d.ts.map +1 -0
- package/dist/cache/sync-engine.js +477 -0
- package/dist/cache/sync-engine.js.map +1 -0
- package/dist/cli/account-commands.d.ts +51 -0
- package/dist/cli/account-commands.d.ts.map +1 -0
- package/dist/cli/account-commands.js +767 -0
- package/dist/cli/account-commands.js.map +1 -0
- package/dist/cli/config-commands.d.ts +9 -0
- package/dist/cli/config-commands.d.ts.map +1 -0
- package/dist/cli/config-commands.js +293 -0
- package/dist/cli/config-commands.js.map +1 -0
- package/dist/cli/email-commands.d.ts +18 -0
- package/dist/cli/email-commands.d.ts.map +1 -0
- package/dist/cli/email-commands.js +447 -0
- package/dist/cli/email-commands.js.map +1 -0
- package/dist/cli/guard.d.ts +11 -0
- package/dist/cli/guard.d.ts.map +1 -0
- package/dist/cli/guard.js +18 -0
- package/dist/cli/guard.js.map +1 -0
- package/dist/cli/http.d.ts +15 -0
- package/dist/cli/http.d.ts.map +1 -0
- package/dist/cli/http.js +263 -0
- package/dist/cli/http.js.map +1 -0
- package/dist/cli/install-commands.d.ts +18 -0
- package/dist/cli/install-commands.d.ts.map +1 -0
- package/dist/cli/install-commands.js +323 -0
- package/dist/cli/install-commands.js.map +1 -0
- package/dist/cli/keychain-commands.d.ts +9 -0
- package/dist/cli/keychain-commands.d.ts.map +1 -0
- package/dist/cli/keychain-commands.js +243 -0
- package/dist/cli/keychain-commands.js.map +1 -0
- package/dist/cli/notify.d.ts +8 -0
- package/dist/cli/notify.d.ts.map +1 -0
- package/dist/cli/notify.js +143 -0
- package/dist/cli/notify.js.map +1 -0
- package/dist/cli/providers.d.ts +13 -0
- package/dist/cli/providers.d.ts.map +1 -0
- package/dist/cli/providers.js +180 -0
- package/dist/cli/providers.js.map +1 -0
- package/dist/cli/scheduler.d.ts +8 -0
- package/dist/cli/scheduler.d.ts.map +1 -0
- package/dist/cli/scheduler.js +268 -0
- package/dist/cli/scheduler.js.map +1 -0
- package/dist/cli/setup.d.ts +12 -0
- package/dist/cli/setup.d.ts.map +1 -0
- package/dist/cli/setup.js +15 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/test.d.ts +7 -0
- package/dist/cli/test.d.ts.map +1 -0
- package/dist/cli/test.js +67 -0
- package/dist/cli/test.js.map +1 -0
- package/dist/config/loader.d.ts +45 -0
- package/dist/config/loader.d.ts.map +1 -0
- package/dist/config/loader.js +487 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/password-command.d.ts +14 -0
- package/dist/config/password-command.d.ts.map +1 -0
- package/dist/config/password-command.js +74 -0
- package/dist/config/password-command.js.map +1 -0
- package/dist/config/schema.d.ts +416 -0
- package/dist/config/schema.d.ts.map +1 -0
- package/dist/config/schema.js +260 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/config/send-limit.d.ts +18 -0
- package/dist/config/send-limit.d.ts.map +1 -0
- package/dist/config/send-limit.js +64 -0
- package/dist/config/send-limit.js.map +1 -0
- package/dist/config/validate.d.ts +30 -0
- package/dist/config/validate.d.ts.map +1 -0
- package/dist/config/validate.js +120 -0
- package/dist/config/validate.js.map +1 -0
- package/dist/config/xdg.d.ts +44 -0
- package/dist/config/xdg.d.ts.map +1 -0
- package/dist/config/xdg.js +49 -0
- package/dist/config/xdg.js.map +1 -0
- package/dist/connections/manager.d.ts +53 -0
- package/dist/connections/manager.d.ts.map +1 -0
- package/dist/connections/manager.js +376 -0
- package/dist/connections/manager.js.map +1 -0
- package/dist/connections/types.d.ts +15 -0
- package/dist/connections/types.d.ts.map +1 -0
- package/dist/connections/types.js +2 -0
- package/dist/connections/types.js.map +1 -0
- package/dist/logging.d.ts +22 -0
- package/dist/logging.d.ts.map +1 -0
- package/dist/logging.js +33 -0
- package/dist/logging.js.map +1 -0
- package/dist/main.d.ts +15 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +276 -0
- package/dist/main.js.map +1 -0
- package/dist/prompts/actions.prompt.d.ts +9 -0
- package/dist/prompts/actions.prompt.d.ts.map +1 -0
- package/dist/prompts/actions.prompt.js +70 -0
- package/dist/prompts/actions.prompt.js.map +1 -0
- package/dist/prompts/calendar.prompt.d.ts +9 -0
- package/dist/prompts/calendar.prompt.d.ts.map +1 -0
- package/dist/prompts/calendar.prompt.js +59 -0
- package/dist/prompts/calendar.prompt.js.map +1 -0
- package/dist/prompts/cleanup.prompt.d.ts +9 -0
- package/dist/prompts/cleanup.prompt.d.ts.map +1 -0
- package/dist/prompts/cleanup.prompt.js +82 -0
- package/dist/prompts/cleanup.prompt.js.map +1 -0
- package/dist/prompts/compose.prompt.d.ts +8 -0
- package/dist/prompts/compose.prompt.d.ts.map +1 -0
- package/dist/prompts/compose.prompt.js +124 -0
- package/dist/prompts/compose.prompt.js.map +1 -0
- package/dist/prompts/register.d.ts +8 -0
- package/dist/prompts/register.d.ts.map +1 -0
- package/dist/prompts/register.js +20 -0
- package/dist/prompts/register.js.map +1 -0
- package/dist/prompts/thread.prompt.d.ts +9 -0
- package/dist/prompts/thread.prompt.d.ts.map +1 -0
- package/dist/prompts/thread.prompt.js +62 -0
- package/dist/prompts/thread.prompt.js.map +1 -0
- package/dist/prompts/triage.prompt.d.ts +9 -0
- package/dist/prompts/triage.prompt.d.ts.map +1 -0
- package/dist/prompts/triage.prompt.js +71 -0
- package/dist/prompts/triage.prompt.js.map +1 -0
- package/dist/resources/accounts.resource.d.ts +9 -0
- package/dist/resources/accounts.resource.d.ts.map +1 -0
- package/dist/resources/accounts.resource.js +26 -0
- package/dist/resources/accounts.resource.js.map +1 -0
- package/dist/resources/mailboxes.resource.d.ts +10 -0
- package/dist/resources/mailboxes.resource.d.ts.map +1 -0
- package/dist/resources/mailboxes.resource.js +33 -0
- package/dist/resources/mailboxes.resource.js.map +1 -0
- package/dist/resources/register.d.ts +12 -0
- package/dist/resources/register.d.ts.map +1 -0
- package/dist/resources/register.js +20 -0
- package/dist/resources/register.js.map +1 -0
- package/dist/resources/scheduled.resource.d.ts +9 -0
- package/dist/resources/scheduled.resource.d.ts.map +1 -0
- package/dist/resources/scheduled.resource.js +31 -0
- package/dist/resources/scheduled.resource.js.map +1 -0
- package/dist/resources/stats.resource.d.ts +10 -0
- package/dist/resources/stats.resource.d.ts.map +1 -0
- package/dist/resources/stats.resource.js +50 -0
- package/dist/resources/stats.resource.js.map +1 -0
- package/dist/resources/templates.resource.d.ts +9 -0
- package/dist/resources/templates.resource.d.ts.map +1 -0
- package/dist/resources/templates.resource.js +34 -0
- package/dist/resources/templates.resource.js.map +1 -0
- package/dist/resources/unread.resource.d.ts +11 -0
- package/dist/resources/unread.resource.d.ts.map +1 -0
- package/dist/resources/unread.resource.js +53 -0
- package/dist/resources/unread.resource.js.map +1 -0
- package/dist/safety/audit.d.ts +17 -0
- package/dist/safety/audit.d.ts.map +1 -0
- package/dist/safety/audit.js +50 -0
- package/dist/safety/audit.js.map +1 -0
- package/dist/safety/rate-limiter.d.ts +22 -0
- package/dist/safety/rate-limiter.d.ts.map +1 -0
- package/dist/safety/rate-limiter.js +52 -0
- package/dist/safety/rate-limiter.js.map +1 -0
- package/dist/safety/validation.d.ts +46 -0
- package/dist/safety/validation.d.ts.map +1 -0
- package/dist/safety/validation.js +114 -0
- package/dist/safety/validation.js.map +1 -0
- package/dist/safety/webhook-guard.d.ts +33 -0
- package/dist/safety/webhook-guard.d.ts.map +1 -0
- package/dist/safety/webhook-guard.js +154 -0
- package/dist/safety/webhook-guard.js.map +1 -0
- package/dist/security/keychain.d.ts +31 -0
- package/dist/security/keychain.d.ts.map +1 -0
- package/dist/security/keychain.js +217 -0
- package/dist/security/keychain.js.map +1 -0
- package/dist/server.d.ts +13 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +35 -0
- package/dist/server.js.map +1 -0
- package/dist/services/calendar.service.d.ts +22 -0
- package/dist/services/calendar.service.d.ts.map +1 -0
- package/dist/services/calendar.service.js +115 -0
- package/dist/services/calendar.service.js.map +1 -0
- package/dist/services/clipboard.service.d.ts +16 -0
- package/dist/services/clipboard.service.d.ts.map +1 -0
- package/dist/services/clipboard.service.js +92 -0
- package/dist/services/clipboard.service.js.map +1 -0
- package/dist/services/event-bus.d.ts +62 -0
- package/dist/services/event-bus.d.ts.map +1 -0
- package/dist/services/event-bus.js +16 -0
- package/dist/services/event-bus.js.map +1 -0
- package/dist/services/hooks.service.d.ts +88 -0
- package/dist/services/hooks.service.d.ts.map +1 -0
- package/dist/services/hooks.service.js +539 -0
- package/dist/services/hooks.service.js.map +1 -0
- package/dist/services/imap.service.d.ts +301 -0
- package/dist/services/imap.service.d.ts.map +1 -0
- package/dist/services/imap.service.js +2135 -0
- package/dist/services/imap.service.js.map +1 -0
- package/dist/services/label-strategy.d.ts +20 -0
- package/dist/services/label-strategy.d.ts.map +1 -0
- package/dist/services/label-strategy.js +247 -0
- package/dist/services/label-strategy.js.map +1 -0
- package/dist/services/local-calendar.service.d.ts +127 -0
- package/dist/services/local-calendar.service.d.ts.map +1 -0
- package/dist/services/local-calendar.service.js +537 -0
- package/dist/services/local-calendar.service.js.map +1 -0
- package/dist/services/notifier.service.d.ts +91 -0
- package/dist/services/notifier.service.d.ts.map +1 -0
- package/dist/services/notifier.service.js +381 -0
- package/dist/services/notifier.service.js.map +1 -0
- package/dist/services/oauth.service.d.ts +47 -0
- package/dist/services/oauth.service.d.ts.map +1 -0
- package/dist/services/oauth.service.js +140 -0
- package/dist/services/oauth.service.js.map +1 -0
- package/dist/services/presets.d.ts +36 -0
- package/dist/services/presets.d.ts.map +1 -0
- package/dist/services/presets.js +175 -0
- package/dist/services/presets.js.map +1 -0
- package/dist/services/reminders.service.d.ts +63 -0
- package/dist/services/reminders.service.d.ts.map +1 -0
- package/dist/services/reminders.service.js +305 -0
- package/dist/services/reminders.service.js.map +1 -0
- package/dist/services/scheduler.service.d.ts +42 -0
- package/dist/services/scheduler.service.d.ts.map +1 -0
- package/dist/services/scheduler.service.js +294 -0
- package/dist/services/scheduler.service.js.map +1 -0
- package/dist/services/smtp.service.d.ts +97 -0
- package/dist/services/smtp.service.d.ts.map +1 -0
- package/dist/services/smtp.service.js +339 -0
- package/dist/services/smtp.service.js.map +1 -0
- package/dist/services/template.service.d.ts +33 -0
- package/dist/services/template.service.d.ts.map +1 -0
- package/dist/services/template.service.js +123 -0
- package/dist/services/template.service.js.map +1 -0
- package/dist/services/verification.service.d.ts +26 -0
- package/dist/services/verification.service.d.ts.map +1 -0
- package/dist/services/verification.service.js +94 -0
- package/dist/services/verification.service.js.map +1 -0
- package/dist/services/watcher.service.d.ts +36 -0
- package/dist/services/watcher.service.d.ts.map +1 -0
- package/dist/services/watcher.service.js +238 -0
- package/dist/services/watcher.service.js.map +1 -0
- package/dist/tools/accounts.tool.d.ts +7 -0
- package/dist/tools/accounts.tool.d.ts.map +1 -0
- package/dist/tools/accounts.tool.js +33 -0
- package/dist/tools/accounts.tool.js.map +1 -0
- package/dist/tools/analytics.tool.d.ts +9 -0
- package/dist/tools/analytics.tool.d.ts.map +1 -0
- package/dist/tools/analytics.tool.js +32 -0
- package/dist/tools/analytics.tool.js.map +1 -0
- package/dist/tools/attachments.tool.d.ts +7 -0
- package/dist/tools/attachments.tool.d.ts.map +1 -0
- package/dist/tools/attachments.tool.js +93 -0
- package/dist/tools/attachments.tool.js.map +1 -0
- package/dist/tools/bulk.tool.d.ts +7 -0
- package/dist/tools/bulk.tool.d.ts.map +1 -0
- package/dist/tools/bulk.tool.js +80 -0
- package/dist/tools/bulk.tool.js.map +1 -0
- package/dist/tools/calendar.tool.d.ts +19 -0
- package/dist/tools/calendar.tool.d.ts.map +1 -0
- package/dist/tools/calendar.tool.js +576 -0
- package/dist/tools/calendar.tool.js.map +1 -0
- package/dist/tools/contacts.tool.d.ts +7 -0
- package/dist/tools/contacts.tool.d.ts.map +1 -0
- package/dist/tools/contacts.tool.js +49 -0
- package/dist/tools/contacts.tool.js.map +1 -0
- package/dist/tools/drafts.tool.d.ts +8 -0
- package/dist/tools/drafts.tool.d.ts.map +1 -0
- package/dist/tools/drafts.tool.js +110 -0
- package/dist/tools/drafts.tool.js.map +1 -0
- package/dist/tools/emails.tool.d.ts +17 -0
- package/dist/tools/emails.tool.d.ts.map +1 -0
- package/dist/tools/emails.tool.js +508 -0
- package/dist/tools/emails.tool.js.map +1 -0
- package/dist/tools/folders.tool.d.ts +7 -0
- package/dist/tools/folders.tool.d.ts.map +1 -0
- package/dist/tools/folders.tool.js +129 -0
- package/dist/tools/folders.tool.js.map +1 -0
- package/dist/tools/health.tool.d.ts +10 -0
- package/dist/tools/health.tool.d.ts.map +1 -0
- package/dist/tools/health.tool.js +106 -0
- package/dist/tools/health.tool.js.map +1 -0
- package/dist/tools/label.tool.d.ts +11 -0
- package/dist/tools/label.tool.d.ts.map +1 -0
- package/dist/tools/label.tool.js +190 -0
- package/dist/tools/label.tool.js.map +1 -0
- package/dist/tools/locate.tool.d.ts +11 -0
- package/dist/tools/locate.tool.d.ts.map +1 -0
- package/dist/tools/locate.tool.js +65 -0
- package/dist/tools/locate.tool.js.map +1 -0
- package/dist/tools/mailboxes.tool.d.ts +7 -0
- package/dist/tools/mailboxes.tool.d.ts.map +1 -0
- package/dist/tools/mailboxes.tool.js +49 -0
- package/dist/tools/mailboxes.tool.js.map +1 -0
- package/dist/tools/manage.tool.d.ts +7 -0
- package/dist/tools/manage.tool.d.ts.map +1 -0
- package/dist/tools/manage.tool.js +140 -0
- package/dist/tools/manage.tool.js.map +1 -0
- package/dist/tools/register.d.ts +20 -0
- package/dist/tools/register.d.ts.map +1 -0
- package/dist/tools/register.js +60 -0
- package/dist/tools/register.js.map +1 -0
- package/dist/tools/scheduler.tool.d.ts +9 -0
- package/dist/tools/scheduler.tool.d.ts.map +1 -0
- package/dist/tools/scheduler.tool.js +130 -0
- package/dist/tools/scheduler.tool.js.map +1 -0
- package/dist/tools/schemas.d.ts +146 -0
- package/dist/tools/schemas.d.ts.map +1 -0
- package/dist/tools/schemas.js +89 -0
- package/dist/tools/schemas.js.map +1 -0
- package/dist/tools/security.tool.d.ts +11 -0
- package/dist/tools/security.tool.d.ts.map +1 -0
- package/dist/tools/security.tool.js +49 -0
- package/dist/tools/security.tool.js.map +1 -0
- package/dist/tools/send.tool.d.ts +7 -0
- package/dist/tools/send.tool.d.ts.map +1 -0
- package/dist/tools/send.tool.js +196 -0
- package/dist/tools/send.tool.js.map +1 -0
- package/dist/tools/templates.tool.d.ts +12 -0
- package/dist/tools/templates.tool.d.ts.map +1 -0
- package/dist/tools/templates.tool.js +149 -0
- package/dist/tools/templates.tool.js.map +1 -0
- package/dist/tools/thread.tool.d.ts +10 -0
- package/dist/tools/thread.tool.d.ts.map +1 -0
- package/dist/tools/thread.tool.js +140 -0
- package/dist/tools/thread.tool.js.map +1 -0
- package/dist/tools/verification.tool.d.ts +5 -0
- package/dist/tools/verification.tool.d.ts.map +1 -0
- package/dist/tools/verification.tool.js +125 -0
- package/dist/tools/verification.tool.js.map +1 -0
- package/dist/tools/watcher.tool.d.ts +19 -0
- package/dist/tools/watcher.tool.d.ts.map +1 -0
- package/dist/tools/watcher.tool.js +319 -0
- package/dist/tools/watcher.tool.js.map +1 -0
- package/dist/types/index.d.ts +329 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +5 -0
- package/dist/types/index.js.map +1 -0
- package/dist/utils/auth-results.d.ts +24 -0
- package/dist/utils/auth-results.d.ts.map +1 -0
- package/dist/utils/auth-results.js +71 -0
- package/dist/utils/auth-results.js.map +1 -0
- package/dist/utils/bulk-headers.d.ts +34 -0
- package/dist/utils/bulk-headers.d.ts.map +1 -0
- package/dist/utils/bulk-headers.js +112 -0
- package/dist/utils/bulk-headers.js.map +1 -0
- package/dist/utils/calendar-notes.d.ts +31 -0
- package/dist/utils/calendar-notes.d.ts.map +1 -0
- package/dist/utils/calendar-notes.js +83 -0
- package/dist/utils/calendar-notes.js.map +1 -0
- package/dist/utils/calendar-state.d.ts +27 -0
- package/dist/utils/calendar-state.d.ts.map +1 -0
- package/dist/utils/calendar-state.js +85 -0
- package/dist/utils/calendar-state.js.map +1 -0
- package/dist/utils/conference-details.d.ts +12 -0
- package/dist/utils/conference-details.d.ts.map +1 -0
- package/dist/utils/conference-details.js +71 -0
- package/dist/utils/conference-details.js.map +1 -0
- package/dist/utils/html.d.ts +24 -0
- package/dist/utils/html.d.ts.map +1 -0
- package/dist/utils/html.js +162 -0
- package/dist/utils/html.js.map +1 -0
- package/dist/utils/imap-client.d.ts +22 -0
- package/dist/utils/imap-client.d.ts.map +1 -0
- package/dist/utils/imap-client.js +26 -0
- package/dist/utils/imap-client.js.map +1 -0
- package/dist/utils/imap-error.d.ts +28 -0
- package/dist/utils/imap-error.d.ts.map +1 -0
- package/dist/utils/imap-error.js +82 -0
- package/dist/utils/imap-error.js.map +1 -0
- package/dist/utils/meeting-url.d.ts +10 -0
- package/dist/utils/meeting-url.d.ts.map +1 -0
- package/dist/utils/meeting-url.js +30 -0
- package/dist/utils/meeting-url.js.map +1 -0
- package/dist/utils/offline-notice.d.ts +10 -0
- package/dist/utils/offline-notice.d.ts.map +1 -0
- package/dist/utils/offline-notice.js +10 -0
- package/dist/utils/offline-notice.js.map +1 -0
- package/dist/utils/reply-chain.d.ts +6 -0
- package/dist/utils/reply-chain.d.ts.map +1 -0
- package/dist/utils/reply-chain.js +15 -0
- package/dist/utils/reply-chain.js.map +1 -0
- package/dist/utils/verification-code.d.ts +29 -0
- package/dist/utils/verification-code.d.ts.map +1 -0
- package/dist/utils/verification-code.js +305 -0
- package/dist/utils/verification-code.js.map +1 -0
- package/dist/utils/verification-link.d.ts +26 -0
- package/dist/utils/verification-link.d.ts.map +1 -0
- package/dist/utils/verification-link.js +197 -0
- package/dist/utils/verification-link.js.map +1 -0
- package/package.json +105 -4
|
@@ -0,0 +1,2135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IMAP service — pure business logic for email read operations.
|
|
3
|
+
*
|
|
4
|
+
* No MCP dependency — fully unit-testable.
|
|
5
|
+
*/
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { sanitizeMailboxName, sanitizeSearchQuery } from '../safety/validation.js';
|
|
8
|
+
import { extractAuthenticationResults, parseAuthSignals, } from '../utils/auth-results.js';
|
|
9
|
+
import { BULK_HEADER_FIELDS, classifyBulk, parseHeaderBlock } from '../utils/bulk-headers.js';
|
|
10
|
+
import { imapCommand, isConnectivityError } from '../utils/imap-error.js';
|
|
11
|
+
import eventBus from './event-bus.js';
|
|
12
|
+
import { detectLabelStrategy } from './label-strategy.js';
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
// Helpers (must be defined before ImapService)
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
function parseAddress(addr) {
|
|
17
|
+
return {
|
|
18
|
+
name: addr?.name ?? undefined,
|
|
19
|
+
address: addr?.address ?? 'unknown',
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function parseAddresses(addrs) {
|
|
23
|
+
if (!addrs)
|
|
24
|
+
return [];
|
|
25
|
+
return addrs.map(parseAddress);
|
|
26
|
+
}
|
|
27
|
+
function hasAttachments(bodyStructure) {
|
|
28
|
+
if (!bodyStructure || typeof bodyStructure !== 'object')
|
|
29
|
+
return false;
|
|
30
|
+
const bs = bodyStructure;
|
|
31
|
+
if (bs.disposition === 'attachment')
|
|
32
|
+
return true;
|
|
33
|
+
if (Array.isArray(bs.childNodes)) {
|
|
34
|
+
return bs.childNodes.some((child) => hasAttachments(child));
|
|
35
|
+
}
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Calendar parts are surfaced through the calendar tools, not as attachments.
|
|
40
|
+
*
|
|
41
|
+
* Match the exact media type rather than a substring: an `application/*` type
|
|
42
|
+
* that merely contains the word "calendar" is an ordinary attachment and must
|
|
43
|
+
* not be hidden. The filename check catches calendar parts that arrive with a
|
|
44
|
+
* generic type such as `application/octet-stream`.
|
|
45
|
+
*/
|
|
46
|
+
function isCalendarPart(mimeType, filename) {
|
|
47
|
+
const media = mimeType.toLowerCase().split(';')[0].trim();
|
|
48
|
+
return media === 'text/calendar' || filename.toLowerCase().endsWith('.ics');
|
|
49
|
+
}
|
|
50
|
+
function extractAttachments(bodyStructure) {
|
|
51
|
+
const attachments = [];
|
|
52
|
+
if (!bodyStructure || typeof bodyStructure !== 'object')
|
|
53
|
+
return attachments;
|
|
54
|
+
const bs = bodyStructure;
|
|
55
|
+
if (bs.disposition === 'attachment') {
|
|
56
|
+
const params = (bs.dispositionParameters ?? bs.parameters ?? {});
|
|
57
|
+
attachments.push({
|
|
58
|
+
filename: params.filename ?? params.name ?? 'unnamed',
|
|
59
|
+
// `bs.type` is already a complete Content-Type; there is no subtype
|
|
60
|
+
// field to append.
|
|
61
|
+
mimeType: typeof bs.type === 'string' ? bs.type.toLowerCase() : 'application/octet-stream',
|
|
62
|
+
size: bs.size ?? 0,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
if (Array.isArray(bs.childNodes)) {
|
|
66
|
+
bs.childNodes.forEach((child) => {
|
|
67
|
+
attachments.push(...extractAttachments(child));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return attachments;
|
|
71
|
+
}
|
|
72
|
+
/** Find the MIME part number for an attachment by filename. */
|
|
73
|
+
function findMimePartByFilename(bodyStructure, targetFilename, partPath = '') {
|
|
74
|
+
if (!bodyStructure || typeof bodyStructure !== 'object')
|
|
75
|
+
return undefined;
|
|
76
|
+
const bs = bodyStructure;
|
|
77
|
+
const currentPart = bs.part;
|
|
78
|
+
const effectivePath = currentPart ?? partPath;
|
|
79
|
+
if (bs.disposition === 'attachment') {
|
|
80
|
+
const params = (bs.dispositionParameters ?? bs.parameters ?? {});
|
|
81
|
+
const filename = params.filename ?? params.name ?? 'unnamed';
|
|
82
|
+
if (filename === targetFilename)
|
|
83
|
+
return effectivePath;
|
|
84
|
+
}
|
|
85
|
+
if (Array.isArray(bs.childNodes)) {
|
|
86
|
+
// eslint-disable-next-line no-plusplus
|
|
87
|
+
for (let i = 0; i < bs.childNodes.length; i++) {
|
|
88
|
+
const childPart = effectivePath ? `${effectivePath}.${i + 1}` : String(i + 1);
|
|
89
|
+
const found = findMimePartByFilename(bs.childNodes[i], targetFilename, childPart);
|
|
90
|
+
if (found)
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
/** Collect every attachment part together with its MIME part path, in one walk. */
|
|
97
|
+
function extractAttachmentParts(bodyStructure, partPath = '') {
|
|
98
|
+
const parts = [];
|
|
99
|
+
if (!bodyStructure || typeof bodyStructure !== 'object')
|
|
100
|
+
return parts;
|
|
101
|
+
const bs = bodyStructure;
|
|
102
|
+
const currentPart = bs.part;
|
|
103
|
+
const effectivePath = currentPart ?? partPath;
|
|
104
|
+
if (bs.disposition === 'attachment') {
|
|
105
|
+
const params = (bs.dispositionParameters ?? bs.parameters ?? {});
|
|
106
|
+
parts.push({
|
|
107
|
+
filename: params.filename ?? params.name ?? 'unnamed',
|
|
108
|
+
mimeType: typeof bs.type === 'string' ? bs.type.toLowerCase() : 'application/octet-stream',
|
|
109
|
+
size: bs.size ?? 0,
|
|
110
|
+
partPath: effectivePath,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
if (Array.isArray(bs.childNodes)) {
|
|
114
|
+
// eslint-disable-next-line no-plusplus
|
|
115
|
+
for (let i = 0; i < bs.childNodes.length; i++) {
|
|
116
|
+
const childPart = effectivePath ? `${effectivePath}.${i + 1}` : String(i + 1);
|
|
117
|
+
parts.push(...extractAttachmentParts(bs.childNodes[i], childPart));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return parts;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Map a raw ImapFlow fetch result to `EmailMeta`.
|
|
124
|
+
*
|
|
125
|
+
* Exported so the IDLE watcher shares one definition — a second, slightly
|
|
126
|
+
* different implementation there previously produced inconsistent records for
|
|
127
|
+
* the same message.
|
|
128
|
+
*/
|
|
129
|
+
export function messageToEmailMeta(msg) {
|
|
130
|
+
const envelope = (msg.envelope ?? {});
|
|
131
|
+
const flags = new Set((msg.flags ?? []));
|
|
132
|
+
// Extract non-system flags as labels (IMAP keywords)
|
|
133
|
+
const labels = [...flags].filter((f) => !f.startsWith('\\'));
|
|
134
|
+
// BODY.PEEK[HEADER.FIELDS (...)] comes back as a raw buffer.
|
|
135
|
+
const bulk = msg.headers && Buffer.isBuffer(msg.headers)
|
|
136
|
+
? classifyBulk(parseHeaderBlock(msg.headers.toString('utf-8')))
|
|
137
|
+
: undefined;
|
|
138
|
+
// Every fetch in this service passes `{ uid: true }`, so a missing UID means
|
|
139
|
+
// the server broke protocol. Falling back to `msg.seq` would mint an id that
|
|
140
|
+
// looks like a UID but addresses a different message on every subsequent
|
|
141
|
+
// write — fail loudly instead.
|
|
142
|
+
if (typeof msg.uid !== 'number') {
|
|
143
|
+
throw new Error(`IMAP server returned a message without a UID (seq ${String(msg.seq ?? 'unknown')})`);
|
|
144
|
+
}
|
|
145
|
+
const sanitizeUntrusted = (s) => {
|
|
146
|
+
const out = s.split('\r').join(' ').split('\n').join(' ');
|
|
147
|
+
// Strip C0 controls and DEL without a regex containing them
|
|
148
|
+
let clean = '';
|
|
149
|
+
for (const ch of out) {
|
|
150
|
+
const code = ch.charCodeAt(0);
|
|
151
|
+
if (code <= 0x1f || code === 0x7f)
|
|
152
|
+
continue;
|
|
153
|
+
clean += ch;
|
|
154
|
+
}
|
|
155
|
+
return clean.slice(0, 500);
|
|
156
|
+
};
|
|
157
|
+
return {
|
|
158
|
+
id: String(msg.uid),
|
|
159
|
+
messageId: envelope.messageId ?? '',
|
|
160
|
+
subject: sanitizeUntrusted(envelope.subject ?? '(no subject)'),
|
|
161
|
+
from: (() => {
|
|
162
|
+
const addr = parseAddress(envelope.from?.[0]);
|
|
163
|
+
return { ...addr, name: addr.name ? sanitizeUntrusted(addr.name) : addr.name };
|
|
164
|
+
})(),
|
|
165
|
+
to: parseAddresses(envelope.to),
|
|
166
|
+
date: envelope.date
|
|
167
|
+
? new Date(envelope.date).toISOString()
|
|
168
|
+
: new Date().toISOString(),
|
|
169
|
+
seen: flags.has('\\Seen'),
|
|
170
|
+
flagged: flags.has('\\Flagged'),
|
|
171
|
+
answered: flags.has('\\Answered'),
|
|
172
|
+
hasAttachments: hasAttachments(msg.bodyStructure),
|
|
173
|
+
labels,
|
|
174
|
+
bulk,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Split an ImapFlow structure node's Content-Type.
|
|
179
|
+
*
|
|
180
|
+
* ImapFlow reports `type` as the complete Content-Type ("text/html") and has
|
|
181
|
+
* no `subtype` field at all — see MessageStructureObject in imap-flow.d.ts.
|
|
182
|
+
*/
|
|
183
|
+
function splitMimeType(type) {
|
|
184
|
+
const full = typeof type === 'string' ? type.toLowerCase() : '';
|
|
185
|
+
const slash = full.indexOf('/');
|
|
186
|
+
if (slash < 0)
|
|
187
|
+
return { type: full, subtype: '' };
|
|
188
|
+
return { type: full.slice(0, slash), subtype: full.slice(slash + 1) };
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Collect every non-attachment text/* part in the MIME tree, in document order.
|
|
192
|
+
*
|
|
193
|
+
* Mirrors the traversal in `findMimePartByFilename` — part paths come from
|
|
194
|
+
* `bs.part` when the server supplies one, otherwise from the 1-based child
|
|
195
|
+
* index chain.
|
|
196
|
+
*/
|
|
197
|
+
function collectTextParts(bodyStructure, partPath = '') {
|
|
198
|
+
if (!bodyStructure || typeof bodyStructure !== 'object')
|
|
199
|
+
return [];
|
|
200
|
+
const bs = bodyStructure;
|
|
201
|
+
const effectivePath = bs.part ?? partPath;
|
|
202
|
+
const found = [];
|
|
203
|
+
if (Array.isArray(bs.childNodes)) {
|
|
204
|
+
bs.childNodes.forEach((child, i) => {
|
|
205
|
+
const childPath = effectivePath ? `${effectivePath}.${i + 1}` : String(i + 1);
|
|
206
|
+
found.push(...collectTextParts(child, childPath));
|
|
207
|
+
});
|
|
208
|
+
return found;
|
|
209
|
+
}
|
|
210
|
+
// Leaf node. Attachments are never body content, even when text/*.
|
|
211
|
+
const { type, subtype } = splitMimeType(bs.type);
|
|
212
|
+
if (type === 'text' && bs.disposition !== 'attachment') {
|
|
213
|
+
found.push({
|
|
214
|
+
// A single-part message has no `part` field at all — the body is
|
|
215
|
+
// addressable as part "1", which is what the vast majority of real mail
|
|
216
|
+
// looks like. Without this the caller falls back to raw `source`, which
|
|
217
|
+
// is still transfer-encoded.
|
|
218
|
+
path: effectivePath || '1',
|
|
219
|
+
subtype,
|
|
220
|
+
size: typeof bs.size === 'number' ? bs.size : 0,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
return found;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Choose which text part to download for an email's body, or `undefined` to
|
|
227
|
+
* skip the extra round trip and use the body already parsed from `source`.
|
|
228
|
+
*
|
|
229
|
+
* `parts` is in document order and excludes attachments.
|
|
230
|
+
*
|
|
231
|
+
* Prefers `text/plain`: it is far cheaper in agent context-window terms, which
|
|
232
|
+
* `docs/performance-roadmap.md` identifies as the real constraint.
|
|
233
|
+
*
|
|
234
|
+
* The exception is the stub plain part — a few dozen bytes of "This message
|
|
235
|
+
* requires an HTML-capable reader" shipped next to the real content in HTML.
|
|
236
|
+
* Taking it literally makes the model report the placeholder as the email, so
|
|
237
|
+
* an implausibly small plain part loses to a much larger HTML sibling.
|
|
238
|
+
*/
|
|
239
|
+
const STUB_PLAIN_MAX_BYTES = 200;
|
|
240
|
+
const STUB_PLAIN_RATIO = 5;
|
|
241
|
+
function selectBodyPart(parts) {
|
|
242
|
+
const plain = parts.find((p) => p.subtype === 'plain');
|
|
243
|
+
const html = parts.find((p) => p.subtype === 'html');
|
|
244
|
+
if (!plain)
|
|
245
|
+
return html ?? parts[0];
|
|
246
|
+
if (html && plain.size < STUB_PLAIN_MAX_BYTES && html.size > plain.size * STUB_PLAIN_RATIO) {
|
|
247
|
+
return html;
|
|
248
|
+
}
|
|
249
|
+
return plain;
|
|
250
|
+
}
|
|
251
|
+
/** Bump when body extraction or decoding changes, so cached bodies from the old logic miss. */
|
|
252
|
+
export const BODY_EXTRACTOR_VERSION = 1;
|
|
253
|
+
/** Bodies larger than this are never cached: truncating would diverge from the live answer. */
|
|
254
|
+
export const MAX_CACHED_BODY_BYTES = 256 * 1024;
|
|
255
|
+
/**
|
|
256
|
+
* The I/O half of building an `Email`: choose the text parts and download them.
|
|
257
|
+
* Everything else is derived by the pure `assembleEmail`.
|
|
258
|
+
*/
|
|
259
|
+
export async function fetchBodyBundle(msg, client, uid) {
|
|
260
|
+
let bodyText;
|
|
261
|
+
let bodyHtml;
|
|
262
|
+
let complete = true;
|
|
263
|
+
// Always download body parts; never read them out of `source`. Raw source
|
|
264
|
+
// is transfer-encoded (quoted-printable, base64) with soft line breaks, so
|
|
265
|
+
// using it directly yields "=3D" for '=' and words split mid-token.
|
|
266
|
+
// download() applies the decoding declared by Content-Transfer-Encoding.
|
|
267
|
+
//
|
|
268
|
+
// Both halves of a multipart/alternative are fetched when present. Keeping
|
|
269
|
+
// only one loses information the other carries: the plain part may be a
|
|
270
|
+
// stub, the html part may be unreadable markup, and downstream consumers
|
|
271
|
+
// cannot choose between them if they never see both.
|
|
272
|
+
const textParts = collectTextParts(msg.bodyStructure);
|
|
273
|
+
const plainPart = textParts.find((p) => p.subtype === 'plain');
|
|
274
|
+
const htmlPart = textParts.find((p) => p.subtype === 'html');
|
|
275
|
+
const chosen = selectBodyPart(textParts);
|
|
276
|
+
const downloadPart = async (target) => {
|
|
277
|
+
try {
|
|
278
|
+
const part = await client.download(String(uid), target.path, { uid: true });
|
|
279
|
+
if (!part?.content)
|
|
280
|
+
return undefined;
|
|
281
|
+
const chunks = [];
|
|
282
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
283
|
+
for await (const chunk of part.content) {
|
|
284
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
285
|
+
}
|
|
286
|
+
return Buffer.concat(chunks).toString('utf-8');
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
// Part may not exist on this server — better an empty body than a throw.
|
|
290
|
+
return undefined;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
// The selected part is fetched first so single-part messages keep exactly
|
|
294
|
+
// one round trip; its subtype decides which slot receives the bytes. When an
|
|
295
|
+
// alternative sibling exists, fetch it too.
|
|
296
|
+
if (chosen) {
|
|
297
|
+
const decoded = await downloadPart(chosen);
|
|
298
|
+
if (decoded !== undefined) {
|
|
299
|
+
if (chosen.subtype === 'html')
|
|
300
|
+
bodyHtml = decoded;
|
|
301
|
+
else
|
|
302
|
+
bodyText = decoded;
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
complete = false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const sibling = chosen === htmlPart ? plainPart : htmlPart;
|
|
309
|
+
if (sibling && sibling !== chosen) {
|
|
310
|
+
const decoded = await downloadPart(sibling);
|
|
311
|
+
if (decoded !== undefined) {
|
|
312
|
+
if (sibling.subtype === 'html')
|
|
313
|
+
bodyHtml = decoded;
|
|
314
|
+
else
|
|
315
|
+
bodyText = decoded;
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
complete = false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
envelope: msg.envelope,
|
|
323
|
+
bodyStructure: msg.bodyStructure,
|
|
324
|
+
// Headers come from a HEADER fetch. `source` would work too, but it pulls
|
|
325
|
+
// the entire message — base64 attachments and all — to read a few hundred
|
|
326
|
+
// bytes of header.
|
|
327
|
+
headersRaw: Buffer.isBuffer(msg.headers) ? msg.headers.toString('utf-8') : '',
|
|
328
|
+
bodyText,
|
|
329
|
+
bodyHtml,
|
|
330
|
+
complete,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* The pure half: build an `Email` from a bundle plus current flags. Both the
|
|
335
|
+
* live path and the cache-hit path call this, so they agree by construction.
|
|
336
|
+
*/
|
|
337
|
+
export function assembleEmail(bundle, flags, uid) {
|
|
338
|
+
const msg = {
|
|
339
|
+
uid,
|
|
340
|
+
envelope: bundle.envelope,
|
|
341
|
+
flags: new Set(flags),
|
|
342
|
+
headers: Buffer.from(bundle.headersRaw, 'utf-8'),
|
|
343
|
+
bodyStructure: bundle.bodyStructure,
|
|
344
|
+
};
|
|
345
|
+
const meta = messageToEmailMeta(msg);
|
|
346
|
+
const envelope = (bundle.envelope ?? {});
|
|
347
|
+
// parseHeaderBlock unfolds RFC 5322 continuation lines; naive line
|
|
348
|
+
// splitting truncates folded fields such as List-Unsubscribe.
|
|
349
|
+
const headers = parseHeaderBlock(bundle.headersRaw);
|
|
350
|
+
const replyToParsed = parseAddresses(envelope.replyTo ??
|
|
351
|
+
envelope['reply-to'])[0];
|
|
352
|
+
return {
|
|
353
|
+
...meta,
|
|
354
|
+
cc: parseAddresses(envelope.cc),
|
|
355
|
+
bcc: parseAddresses(envelope.bcc),
|
|
356
|
+
replyTo: replyToParsed,
|
|
357
|
+
bodyText: bundle.bodyText,
|
|
358
|
+
bodyHtml: bundle.bodyHtml,
|
|
359
|
+
messageId: envelope.messageId ?? '',
|
|
360
|
+
inReplyTo: envelope.inReplyTo ?? undefined,
|
|
361
|
+
references: headers.references?.split(/\s+/).filter(Boolean),
|
|
362
|
+
attachments: extractAttachments(bundle.bodyStructure),
|
|
363
|
+
headers,
|
|
364
|
+
// Recomputed from the full header set rather than reusing meta.bulk, which
|
|
365
|
+
// a full fetch leaves unset — the targeted HEADER.FIELDS fetch only happens
|
|
366
|
+
// on listings.
|
|
367
|
+
bulk: classifyBulk(headers),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
async function messageToEmail(msg, client, uid) {
|
|
371
|
+
const bundle = await fetchBodyBundle(msg, client, uid);
|
|
372
|
+
return assembleEmail(bundle, (msg.flags ?? []), uid);
|
|
373
|
+
}
|
|
374
|
+
// ---------------------------------------------------------------------------
|
|
375
|
+
// Service
|
|
376
|
+
// ---------------------------------------------------------------------------
|
|
377
|
+
export default class ImapService {
|
|
378
|
+
connections;
|
|
379
|
+
labelStrategies = new Map();
|
|
380
|
+
labelStrategyPending = new Map();
|
|
381
|
+
/** Label strategies are evicted after 5 minutes to prevent stale cache growth. */
|
|
382
|
+
static LABEL_STRATEGY_TTL_MS = 5 * 60 * 1000;
|
|
383
|
+
onReconnect;
|
|
384
|
+
/** Absent unless `cache.read_through` is on; absent means today's behavior exactly. */
|
|
385
|
+
bodyCache;
|
|
386
|
+
offlineReads = false;
|
|
387
|
+
constructor(connections) {
|
|
388
|
+
this.connections = connections;
|
|
389
|
+
// The label strategy is probed from server capabilities and folder layout,
|
|
390
|
+
// so it is only valid for the connection that produced it. A reconnect may
|
|
391
|
+
// reach a different server for the same account — drop the memo and
|
|
392
|
+
// re-detect on next use.
|
|
393
|
+
this.onReconnect = ({ account }) => {
|
|
394
|
+
this.labelStrategies.delete(account);
|
|
395
|
+
this.labelStrategyPending.delete(account);
|
|
396
|
+
};
|
|
397
|
+
eventBus.on('imap:reconnect', this.onReconnect);
|
|
398
|
+
}
|
|
399
|
+
/** Route `getEmail` through the local body cache. */
|
|
400
|
+
attachBodyCache(port, options) {
|
|
401
|
+
this.bodyCache = port;
|
|
402
|
+
this.offlineReads = options.offlineReads;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Answer from the cache when, and only when, the server was unreachable.
|
|
406
|
+
*
|
|
407
|
+
* Anything else (bad credentials, a missing message, a permission error) is
|
|
408
|
+
* an answer from a reachable server and is rethrown by the caller.
|
|
409
|
+
*/
|
|
410
|
+
readOffline(err, account, mailbox, uid) {
|
|
411
|
+
if (!this.bodyCache || !this.offlineReads || !isConnectivityError(err))
|
|
412
|
+
return undefined;
|
|
413
|
+
try {
|
|
414
|
+
const hit = this.bodyCache.getOffline(account, sanitizeMailboxName(mailbox), uid);
|
|
415
|
+
if (!hit)
|
|
416
|
+
return undefined;
|
|
417
|
+
return {
|
|
418
|
+
...assembleEmail(hit.bundle, hit.flags, uid),
|
|
419
|
+
offline: { cachedAt: new Date(hit.cachedAt).toISOString() },
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
return undefined;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/** Free cached bodies of messages that just left a mailbox. Hygiene only: correctness never depends on it. */
|
|
427
|
+
forgetBodies(account, mailbox, uids) {
|
|
428
|
+
if (!this.bodyCache)
|
|
429
|
+
return;
|
|
430
|
+
try {
|
|
431
|
+
this.bodyCache.forget(account, sanitizeMailboxName(mailbox), uids);
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
// Cache hygiene must not fail a move or delete that already succeeded.
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Detach from the event bus.
|
|
439
|
+
*
|
|
440
|
+
* The server holds a single long-lived instance, so this matters mainly for
|
|
441
|
+
* tests and for any future code that builds a service graph per request —
|
|
442
|
+
* without it each instance leaks a listener on the shared bus.
|
|
443
|
+
*/
|
|
444
|
+
dispose() {
|
|
445
|
+
eventBus.off('imap:reconnect', this.onReconnect);
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Fetch a whole-match UID set in bounded chunks, streamed as one sequence.
|
|
449
|
+
*
|
|
450
|
+
* Hostinger rejects a UID FETCH whose argument token is too long: joining
|
|
451
|
+
* every UID of a 25k-message mailbox makes a ~142 KB command, the server
|
|
452
|
+
* answers `BAD: Too long argument`, and the caller sees the useless
|
|
453
|
+
* "Command failed" instead of results. Chunking keeps each command far
|
|
454
|
+
* below any plausible line limit while callers consume a flat stream, so
|
|
455
|
+
* single-fetch call semantics (for-await over messages) stay unchanged.
|
|
456
|
+
*/
|
|
457
|
+
static async *fetchUidChunks(client, uids, query, options) {
|
|
458
|
+
// ~400 five-digit UIDs plus commas ≈ 2.4 KB per command — orders of
|
|
459
|
+
// magnitude under the observed 142 KB failure, and large enough that a
|
|
460
|
+
// 65k-message date sort stays ~160 round trips.
|
|
461
|
+
const CHUNK = 400;
|
|
462
|
+
for (let i = 0; i < uids.length; i += CHUNK) {
|
|
463
|
+
const range = uids.slice(i, i + CHUNK).join(',');
|
|
464
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
465
|
+
for await (const msg of client.fetch(range, query, options)) {
|
|
466
|
+
yield msg;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Lock a caller-supplied mailbox path.
|
|
472
|
+
*
|
|
473
|
+
* Trims and rejects the IMAP wildcards `*` and `%` first. Prefer this over
|
|
474
|
+
* `client.getMailboxLock()` for any path that originated outside this
|
|
475
|
+
* process — it keeps validation from drifting method by method, and
|
|
476
|
+
* normalizes the path so " INBOX " and "INBOX" address one mailbox.
|
|
477
|
+
*
|
|
478
|
+
* Paths returned by `client.list()` are server-supplied and already valid;
|
|
479
|
+
* those may be locked directly.
|
|
480
|
+
*/
|
|
481
|
+
static lockMailbox(client, mailbox) {
|
|
482
|
+
const path = sanitizeMailboxName(mailbox);
|
|
483
|
+
// Every read and write opens a mailbox first, so this is the most common
|
|
484
|
+
// place a server refusal surfaces — and the least useful one to report as
|
|
485
|
+
// a bare "Command failed".
|
|
486
|
+
return imapCommand(`Opening mailbox "${path}"`, () => client.getMailboxLock(path));
|
|
487
|
+
}
|
|
488
|
+
async getLabelStrategy(accountName) {
|
|
489
|
+
const cached = this.labelStrategies.get(accountName);
|
|
490
|
+
if (cached && Date.now() - cached.ts < ImapService.LABEL_STRATEGY_TTL_MS) {
|
|
491
|
+
return cached.strategy;
|
|
492
|
+
}
|
|
493
|
+
if (cached)
|
|
494
|
+
this.labelStrategies.delete(accountName);
|
|
495
|
+
// Deduplicate concurrent detection for the same account. A failed attempt
|
|
496
|
+
// must not stay cached: the entry is cleared when detection settles with a
|
|
497
|
+
// rejection, so the next caller retries instead of awaiting a promise that
|
|
498
|
+
// can never succeed.
|
|
499
|
+
const pending = this.labelStrategyPending.get(accountName);
|
|
500
|
+
if (pending)
|
|
501
|
+
return pending;
|
|
502
|
+
const promise = (async () => {
|
|
503
|
+
try {
|
|
504
|
+
const client = await this.connections.getImapClient(accountName);
|
|
505
|
+
const strategy = await detectLabelStrategy(client);
|
|
506
|
+
this.labelStrategies.set(accountName, { strategy, ts: Date.now() });
|
|
507
|
+
return strategy;
|
|
508
|
+
}
|
|
509
|
+
finally {
|
|
510
|
+
// Clear on settle, success or failure: a rejected detection must not
|
|
511
|
+
// stay cached, or every later caller awaits a promise that can never
|
|
512
|
+
// succeed and the account's labels are wedged until a reconnect.
|
|
513
|
+
this.labelStrategyPending.delete(accountName);
|
|
514
|
+
}
|
|
515
|
+
})();
|
|
516
|
+
this.labelStrategyPending.set(accountName, promise);
|
|
517
|
+
return promise;
|
|
518
|
+
}
|
|
519
|
+
// -------------------------------------------------------------------------
|
|
520
|
+
// Mailboxes
|
|
521
|
+
// -------------------------------------------------------------------------
|
|
522
|
+
async listMailboxes(accountName) {
|
|
523
|
+
const client = await this.connections.getImapClient(accountName);
|
|
524
|
+
const mailboxes = await client.list();
|
|
525
|
+
const statusResults = await Promise.allSettled(mailboxes.map(async (mb) => {
|
|
526
|
+
const status = await client.status(mb.path, {
|
|
527
|
+
messages: true,
|
|
528
|
+
unseen: true,
|
|
529
|
+
});
|
|
530
|
+
return {
|
|
531
|
+
name: mb.name,
|
|
532
|
+
path: mb.path,
|
|
533
|
+
specialUse: mb.specialUse ?? undefined,
|
|
534
|
+
// imapflow 2 returns false when the folder can't answer STATUS —
|
|
535
|
+
// report undefined counts, not a crash (Mailbox documents this).
|
|
536
|
+
totalMessages: status === false ? undefined : status.messages,
|
|
537
|
+
unseenMessages: status === false ? undefined : status.unseen,
|
|
538
|
+
};
|
|
539
|
+
}));
|
|
540
|
+
return statusResults.map((result, idx) => {
|
|
541
|
+
if (result.status === 'fulfilled') {
|
|
542
|
+
return result.value;
|
|
543
|
+
}
|
|
544
|
+
// STATUS failed — either the folder doesn't support it (e.g. \Noselect) or
|
|
545
|
+
// the connection is degraded. Leave the counts undefined rather than
|
|
546
|
+
// reporting 0: a caller (or the cache) must not mistake this for an empty
|
|
547
|
+
// mailbox.
|
|
548
|
+
const mb = mailboxes[idx];
|
|
549
|
+
return {
|
|
550
|
+
name: mb.name,
|
|
551
|
+
path: mb.path,
|
|
552
|
+
specialUse: mb.specialUse ?? undefined,
|
|
553
|
+
totalMessages: undefined,
|
|
554
|
+
unseenMessages: undefined,
|
|
555
|
+
};
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
// -------------------------------------------------------------------------
|
|
559
|
+
// List emails
|
|
560
|
+
// -------------------------------------------------------------------------
|
|
561
|
+
async listEmails(accountName, options = {}) {
|
|
562
|
+
const client = await this.connections.getImapClient(accountName);
|
|
563
|
+
const mailbox = sanitizeMailboxName(options.mailbox ?? 'INBOX');
|
|
564
|
+
const page = options.page ?? 1;
|
|
565
|
+
const pageSize = options.pageSize ?? 20;
|
|
566
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
567
|
+
try {
|
|
568
|
+
// Build search criteria
|
|
569
|
+
const search = {};
|
|
570
|
+
if (options.since)
|
|
571
|
+
search.since = new Date(options.since);
|
|
572
|
+
if (options.before)
|
|
573
|
+
search.before = new Date(options.before);
|
|
574
|
+
if (options.from)
|
|
575
|
+
search.from = options.from;
|
|
576
|
+
if (options.subject)
|
|
577
|
+
search.subject = options.subject;
|
|
578
|
+
if (options.seen !== undefined)
|
|
579
|
+
search.seen = options.seen;
|
|
580
|
+
if (options.flagged !== undefined)
|
|
581
|
+
search.flagged = options.flagged;
|
|
582
|
+
if (options.answered !== undefined)
|
|
583
|
+
search.answered = options.answered;
|
|
584
|
+
// Search for matching UIDs
|
|
585
|
+
const searchResult = await client.search(search, { uid: true });
|
|
586
|
+
// A server whose SEARCH is broken may answer with something other than
|
|
587
|
+
// a UID array. Treating that as 'no matches' hides real mail behind a
|
|
588
|
+
// confident-looking empty result; failing loudly names the problem.
|
|
589
|
+
if (!Array.isArray(searchResult)) {
|
|
590
|
+
throw new Error(`Mailbox search returned an unusable response from the server; its SEARCH implementation appears broken.`);
|
|
591
|
+
}
|
|
592
|
+
let uids = searchResult;
|
|
593
|
+
// Post-filter for hasAttachment (IMAP has no native attachment search)
|
|
594
|
+
if (options.hasAttachment !== undefined && uids.length > 0) {
|
|
595
|
+
const filteredUids = [];
|
|
596
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
597
|
+
for await (const msg of ImapService.fetchUidChunks(client, uids, { uid: true, bodyStructure: true }, { uid: true })) {
|
|
598
|
+
const raw = msg;
|
|
599
|
+
if (options.hasAttachment === hasAttachments(raw.bodyStructure)) {
|
|
600
|
+
filteredUids.push(raw.uid);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
uids = filteredUids;
|
|
604
|
+
}
|
|
605
|
+
if (uids.length === 0) {
|
|
606
|
+
return {
|
|
607
|
+
items: [],
|
|
608
|
+
total: 0,
|
|
609
|
+
page,
|
|
610
|
+
pageSize,
|
|
611
|
+
hasMore: false,
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
// Order the WHOLE match set before slicing a page. Slicing by UID first
|
|
615
|
+
// and date-sorting afterwards yields a per-page sort that looks right
|
|
616
|
+
// and is not: a migrated message with a low UID and a recent date lands
|
|
617
|
+
// on the wrong page and never surfaces. Date order therefore needs every
|
|
618
|
+
// message's date before the page is cut, so fetch the cheap pair for the
|
|
619
|
+
// full range; UID order keeps its original cheap path.
|
|
620
|
+
const sort = options.sort ?? 'date';
|
|
621
|
+
if (sort === 'date') {
|
|
622
|
+
const uidDates = new Map();
|
|
623
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
624
|
+
for await (const msg of ImapService.fetchUidChunks(client, uids, { uid: true, internalDate: true }, { uid: true })) {
|
|
625
|
+
const raw = msg;
|
|
626
|
+
if (typeof raw.uid === 'number') {
|
|
627
|
+
uidDates.set(raw.uid, raw.internalDate ? raw.internalDate.getTime() : 0);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Newest first; ties broken by UID so the order is stable.
|
|
631
|
+
uids.sort((a, b) => {
|
|
632
|
+
const da = uidDates.get(a) ?? 0;
|
|
633
|
+
const db = uidDates.get(b) ?? 0;
|
|
634
|
+
if (da !== db)
|
|
635
|
+
return db - da;
|
|
636
|
+
return b - a;
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
// Raw UID order, server-native ascending.
|
|
641
|
+
uids.sort((a, b) => a - b);
|
|
642
|
+
}
|
|
643
|
+
const total = uids.length;
|
|
644
|
+
const start = (page - 1) * pageSize;
|
|
645
|
+
const pageUids = uids.slice(start, start + pageSize);
|
|
646
|
+
if (pageUids.length === 0) {
|
|
647
|
+
return {
|
|
648
|
+
items: [],
|
|
649
|
+
total,
|
|
650
|
+
page,
|
|
651
|
+
pageSize,
|
|
652
|
+
hasMore: false,
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
const items = [];
|
|
656
|
+
const range = pageUids.join(',');
|
|
657
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
658
|
+
for await (const msg of client.fetch(range, {
|
|
659
|
+
uid: true,
|
|
660
|
+
envelope: true,
|
|
661
|
+
flags: true,
|
|
662
|
+
bodyStructure: true,
|
|
663
|
+
headers: BULK_HEADER_FIELDS,
|
|
664
|
+
}, { uid: true })) {
|
|
665
|
+
items.push(messageToEmailMeta(msg));
|
|
666
|
+
}
|
|
667
|
+
// Servers answer a UID range in ascending order regardless of the
|
|
668
|
+
// ordering this page was cut with, so re-apply the page's own order to
|
|
669
|
+
// the hydrated rows. This is safe precisely because the page cut already
|
|
670
|
+
// happened on the full, globally ordered set: sorting two rows is not
|
|
671
|
+
// the per-page-sort bug that motivated the change above.
|
|
672
|
+
if (sort === 'date') {
|
|
673
|
+
items.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
|
|
674
|
+
}
|
|
675
|
+
return {
|
|
676
|
+
items,
|
|
677
|
+
total,
|
|
678
|
+
page,
|
|
679
|
+
pageSize,
|
|
680
|
+
hasMore: start + pageSize < total,
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
finally {
|
|
684
|
+
lock.release();
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
// -------------------------------------------------------------------------
|
|
688
|
+
// Get single email
|
|
689
|
+
// -------------------------------------------------------------------------
|
|
690
|
+
async getEmail(accountName, emailId, mailbox = 'INBOX') {
|
|
691
|
+
const uid = parseInt(emailId, 10);
|
|
692
|
+
// Sanitized before connecting so the offline fallback looks rows up under
|
|
693
|
+
// the same key that write-back and backfill stored them with.
|
|
694
|
+
const safeMailbox = sanitizeMailboxName(mailbox);
|
|
695
|
+
let client;
|
|
696
|
+
try {
|
|
697
|
+
client = await this.connections.getImapClient(accountName);
|
|
698
|
+
}
|
|
699
|
+
catch (err) {
|
|
700
|
+
const offline = this.readOffline(err, accountName, safeMailbox, uid);
|
|
701
|
+
if (offline)
|
|
702
|
+
return offline;
|
|
703
|
+
throw err;
|
|
704
|
+
}
|
|
705
|
+
let lock;
|
|
706
|
+
try {
|
|
707
|
+
lock = await client.getMailboxLock(safeMailbox);
|
|
708
|
+
}
|
|
709
|
+
catch (err) {
|
|
710
|
+
const offline = this.readOffline(err, accountName, safeMailbox, uid);
|
|
711
|
+
if (offline)
|
|
712
|
+
return offline;
|
|
713
|
+
throw err;
|
|
714
|
+
}
|
|
715
|
+
try {
|
|
716
|
+
// A message's body, headers and structure never change for a given
|
|
717
|
+
// (UIDVALIDITY, UID), so a hit needs no freshness model: the FLAGS fetch
|
|
718
|
+
// below is what proves the message still exists and supplies live flags.
|
|
719
|
+
const selected = client.mailbox;
|
|
720
|
+
const uidValidity = this.bodyCache && selected ? selected.uidValidity?.toString() : undefined;
|
|
721
|
+
if (this.bodyCache && uidValidity) {
|
|
722
|
+
const cached = this.bodyCache.get(accountName, safeMailbox, uid, uidValidity);
|
|
723
|
+
if (cached) {
|
|
724
|
+
const current = await client.fetchOne(String(uid), { uid: true, flags: true }, { uid: true });
|
|
725
|
+
if (!current) {
|
|
726
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
727
|
+
}
|
|
728
|
+
return assembleEmail(cached, (current.flags ?? []), uid);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
const msg = await client.fetchOne(String(uid), {
|
|
732
|
+
uid: true,
|
|
733
|
+
envelope: true,
|
|
734
|
+
flags: true,
|
|
735
|
+
bodyStructure: true,
|
|
736
|
+
// Headers only. `source: true` would transfer the whole message,
|
|
737
|
+
// attachments included, to read a few hundred bytes of header —
|
|
738
|
+
// the body arrives separately as a decoded MIME part.
|
|
739
|
+
headers: true,
|
|
740
|
+
}, { uid: true });
|
|
741
|
+
if (!msg) {
|
|
742
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
743
|
+
}
|
|
744
|
+
const raw = msg;
|
|
745
|
+
const bundle = await fetchBodyBundle(raw, client, uid);
|
|
746
|
+
const email = assembleEmail(bundle, (raw.flags ?? []), uid);
|
|
747
|
+
// Written only after the answer is built, so a failure can never leave a
|
|
748
|
+
// cache row behind for a read that did not succeed.
|
|
749
|
+
if (this.bodyCache && uidValidity) {
|
|
750
|
+
this.bodyCache.put(accountName, safeMailbox, uid, uidValidity, bundle);
|
|
751
|
+
}
|
|
752
|
+
return email;
|
|
753
|
+
}
|
|
754
|
+
finally {
|
|
755
|
+
lock.release();
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// -------------------------------------------------------------------------
|
|
759
|
+
// Get email flags (lightweight — no body fetch, no \Seen change)
|
|
760
|
+
// -------------------------------------------------------------------------
|
|
761
|
+
async getEmailFlags(accountName, emailId, mailbox = 'INBOX') {
|
|
762
|
+
const client = await this.connections.getImapClient(accountName);
|
|
763
|
+
const uid = parseInt(emailId, 10);
|
|
764
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
765
|
+
try {
|
|
766
|
+
const msg = await client.fetchOne(String(uid), { uid: true, envelope: true, flags: true }, { uid: true });
|
|
767
|
+
if (!msg) {
|
|
768
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
769
|
+
}
|
|
770
|
+
const raw = msg;
|
|
771
|
+
const flags = new Set((raw.flags ?? []));
|
|
772
|
+
const labels = [...flags].filter((f) => !f.startsWith('\\'));
|
|
773
|
+
const envelope = (raw.envelope ?? {});
|
|
774
|
+
const fromEntry = envelope.from?.[0];
|
|
775
|
+
let from = '';
|
|
776
|
+
if (fromEntry) {
|
|
777
|
+
from = fromEntry.name
|
|
778
|
+
? `${fromEntry.name} <${fromEntry.address}>`
|
|
779
|
+
: (fromEntry.address ?? '');
|
|
780
|
+
}
|
|
781
|
+
return {
|
|
782
|
+
seen: flags.has('\\Seen'),
|
|
783
|
+
flagged: flags.has('\\Flagged'),
|
|
784
|
+
answered: flags.has('\\Answered'),
|
|
785
|
+
labels,
|
|
786
|
+
subject: envelope.subject ?? '(no subject)',
|
|
787
|
+
from,
|
|
788
|
+
date: envelope.date ? new Date(envelope.date).toISOString() : '',
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
finally {
|
|
792
|
+
lock.release();
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
// -------------------------------------------------------------------------
|
|
796
|
+
// Search emails
|
|
797
|
+
// -------------------------------------------------------------------------
|
|
798
|
+
async searchEmails(accountName, query, options = {}) {
|
|
799
|
+
const client = await this.connections.getImapClient(accountName);
|
|
800
|
+
const mailbox = sanitizeMailboxName(options.mailbox ?? 'INBOX');
|
|
801
|
+
const page = options.page ?? 1;
|
|
802
|
+
const pageSize = options.pageSize ?? 20;
|
|
803
|
+
const sanitizedQuery = query ? sanitizeSearchQuery(query) : '';
|
|
804
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
805
|
+
try {
|
|
806
|
+
// Build search criteria — base query OR across subject/from/body
|
|
807
|
+
const baseCriteria = sanitizedQuery
|
|
808
|
+
? { or: [{ subject: sanitizedQuery }, { from: sanitizedQuery }, { body: sanitizedQuery }] }
|
|
809
|
+
: {};
|
|
810
|
+
// Build additional filters as AND conditions
|
|
811
|
+
const andConditions = [baseCriteria];
|
|
812
|
+
if (options.to) {
|
|
813
|
+
andConditions.push({ to: options.to });
|
|
814
|
+
}
|
|
815
|
+
if (options.largerThan !== undefined) {
|
|
816
|
+
andConditions.push({ larger: options.largerThan * 1024 });
|
|
817
|
+
}
|
|
818
|
+
if (options.smallerThan !== undefined) {
|
|
819
|
+
andConditions.push({ smaller: options.smallerThan * 1024 });
|
|
820
|
+
}
|
|
821
|
+
if (options.answered === true) {
|
|
822
|
+
andConditions.push({ answered: true });
|
|
823
|
+
}
|
|
824
|
+
else if (options.answered === false) {
|
|
825
|
+
andConditions.push({ answered: false });
|
|
826
|
+
}
|
|
827
|
+
// Use the combined criteria or just the base
|
|
828
|
+
const searchCriteria = andConditions.length === 1 ? baseCriteria : Object.assign({}, ...andConditions);
|
|
829
|
+
const searchResult = await client.search(searchCriteria, { uid: true });
|
|
830
|
+
// Loud failure over silent zero - see list_emails above.
|
|
831
|
+
if (!Array.isArray(searchResult)) {
|
|
832
|
+
throw new Error(`Mailbox search returned an unusable response from the server; its SEARCH implementation appears broken.`);
|
|
833
|
+
}
|
|
834
|
+
let uids = searchResult;
|
|
835
|
+
// Post-filter for has_attachment if requested (IMAP doesn't have native support)
|
|
836
|
+
if (options.hasAttachment !== undefined && uids.length > 0) {
|
|
837
|
+
const filteredUids = [];
|
|
838
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
839
|
+
for await (const msg of ImapService.fetchUidChunks(client, uids, { uid: true, bodyStructure: true }, { uid: true })) {
|
|
840
|
+
const raw = msg;
|
|
841
|
+
const msgHasAtt = hasAttachments(raw.bodyStructure);
|
|
842
|
+
if (options.hasAttachment === msgHasAtt) {
|
|
843
|
+
filteredUids.push(raw.uid);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
uids = filteredUids;
|
|
847
|
+
}
|
|
848
|
+
if (uids.length === 0) {
|
|
849
|
+
return {
|
|
850
|
+
items: [],
|
|
851
|
+
total: 0,
|
|
852
|
+
page,
|
|
853
|
+
pageSize,
|
|
854
|
+
hasMore: false,
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
// Same ordering rule as list_emails: order the WHOLE match set before
|
|
858
|
+
// slicing, or pages restart the sort and migrated mail never surfaces.
|
|
859
|
+
if ((options.sort ?? 'date') === 'date') {
|
|
860
|
+
const uidDates = new Map();
|
|
861
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
862
|
+
for await (const msg of ImapService.fetchUidChunks(client, uids, { uid: true, internalDate: true }, { uid: true })) {
|
|
863
|
+
const raw = msg;
|
|
864
|
+
if (typeof raw.uid === 'number') {
|
|
865
|
+
uidDates.set(raw.uid, raw.internalDate ? raw.internalDate.getTime() : 0);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
uids.sort((a, b) => {
|
|
869
|
+
const da = uidDates.get(a) ?? 0;
|
|
870
|
+
const db = uidDates.get(b) ?? 0;
|
|
871
|
+
if (da !== db)
|
|
872
|
+
return db - da;
|
|
873
|
+
return b - a;
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
else {
|
|
877
|
+
// Raw UID order, server-native ascending.
|
|
878
|
+
uids.sort((a, b) => a - b);
|
|
879
|
+
}
|
|
880
|
+
const total = uids.length;
|
|
881
|
+
const start = (page - 1) * pageSize;
|
|
882
|
+
const pageUids = uids.slice(start, start + pageSize);
|
|
883
|
+
if (pageUids.length === 0) {
|
|
884
|
+
return {
|
|
885
|
+
items: [],
|
|
886
|
+
total,
|
|
887
|
+
page,
|
|
888
|
+
pageSize,
|
|
889
|
+
hasMore: false,
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
const items = [];
|
|
893
|
+
const range = pageUids.join(',');
|
|
894
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
895
|
+
for await (const msg of client.fetch(range, {
|
|
896
|
+
uid: true,
|
|
897
|
+
envelope: true,
|
|
898
|
+
flags: true,
|
|
899
|
+
bodyStructure: true,
|
|
900
|
+
headers: BULK_HEADER_FIELDS,
|
|
901
|
+
}, { uid: true })) {
|
|
902
|
+
items.push(messageToEmailMeta(msg));
|
|
903
|
+
}
|
|
904
|
+
// Same in-page re-application as list_emails: the range comes back
|
|
905
|
+
// ascending, so restore this page's own order after hydration.
|
|
906
|
+
if ((options.sort ?? 'date') === 'date') {
|
|
907
|
+
items.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
|
|
908
|
+
}
|
|
909
|
+
return {
|
|
910
|
+
items,
|
|
911
|
+
total,
|
|
912
|
+
page,
|
|
913
|
+
pageSize,
|
|
914
|
+
hasMore: start + pageSize < total,
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
finally {
|
|
918
|
+
lock.release();
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
// -------------------------------------------------------------------------
|
|
922
|
+
// Labels
|
|
923
|
+
// -------------------------------------------------------------------------
|
|
924
|
+
async listLabels(accountName) {
|
|
925
|
+
const strategy = await this.getLabelStrategy(accountName);
|
|
926
|
+
const client = await this.connections.getImapClient(accountName);
|
|
927
|
+
return strategy.listLabels(client);
|
|
928
|
+
}
|
|
929
|
+
async addLabel(accountName, emailId, mailbox, label) {
|
|
930
|
+
const strategy = await this.getLabelStrategy(accountName);
|
|
931
|
+
const client = await this.connections.getImapClient(accountName);
|
|
932
|
+
await strategy.addLabel(client, emailId, mailbox, label);
|
|
933
|
+
}
|
|
934
|
+
async removeLabel(accountName, emailId, mailbox, label) {
|
|
935
|
+
const strategy = await this.getLabelStrategy(accountName);
|
|
936
|
+
const client = await this.connections.getImapClient(accountName);
|
|
937
|
+
await strategy.removeLabel(client, emailId, mailbox, label);
|
|
938
|
+
}
|
|
939
|
+
async createLabel(accountName, name) {
|
|
940
|
+
const strategy = await this.getLabelStrategy(accountName);
|
|
941
|
+
const client = await this.connections.getImapClient(accountName);
|
|
942
|
+
await strategy.createLabel(client, name);
|
|
943
|
+
}
|
|
944
|
+
async deleteLabel(accountName, name) {
|
|
945
|
+
const strategy = await this.getLabelStrategy(accountName);
|
|
946
|
+
const client = await this.connections.getImapClient(accountName);
|
|
947
|
+
await strategy.deleteLabel(client, name);
|
|
948
|
+
}
|
|
949
|
+
// -------------------------------------------------------------------------
|
|
950
|
+
// Virtual-folder detection
|
|
951
|
+
// -------------------------------------------------------------------------
|
|
952
|
+
static VIRTUAL_SPECIAL_USE = new Set(['\\All', '\\Flagged']);
|
|
953
|
+
static async assertRealMailbox(client, mailboxPath) {
|
|
954
|
+
const mailboxes = await client.list();
|
|
955
|
+
const mb = mailboxes.find((m) => m.path === mailboxPath);
|
|
956
|
+
if (!mb)
|
|
957
|
+
return; // unknown — let the server reject if invalid
|
|
958
|
+
const virtualFlag = [...ImapService.VIRTUAL_SPECIAL_USE].find((f) => mb.specialUse === f || mb.flags?.has(f));
|
|
959
|
+
if (virtualFlag) {
|
|
960
|
+
throw new Error(`"${mailboxPath}" is a virtual folder (${virtualFlag}). ` +
|
|
961
|
+
'Use find_email_folder to locate the real folder first.');
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
// -------------------------------------------------------------------------
|
|
965
|
+
// Find real folder for an email
|
|
966
|
+
// -------------------------------------------------------------------------
|
|
967
|
+
/** Folders a message is most likely to be in, in the order worth searching. */
|
|
968
|
+
static LIKELY_SPECIAL_USE = ['\\Sent', '\\Drafts', '\\Archive'];
|
|
969
|
+
/**
|
|
970
|
+
* Order mailboxes so the first match is the one a caller would want to act
|
|
971
|
+
* on, since the search stops there.
|
|
972
|
+
*/
|
|
973
|
+
static orderByLikelihood(mailboxes) {
|
|
974
|
+
const rank = (mailbox) => {
|
|
975
|
+
if (mailbox.path === 'INBOX')
|
|
976
|
+
return 0;
|
|
977
|
+
const specialIndex = mailbox.specialUse
|
|
978
|
+
? ImapService.LIKELY_SPECIAL_USE.indexOf(mailbox.specialUse)
|
|
979
|
+
: -1;
|
|
980
|
+
return specialIndex === -1 ? ImapService.LIKELY_SPECIAL_USE.length + 1 : specialIndex + 1;
|
|
981
|
+
};
|
|
982
|
+
// Stable within a rank, so the server's own ordering is otherwise kept.
|
|
983
|
+
return [...mailboxes].sort((a, b) => rank(a) - rank(b));
|
|
984
|
+
}
|
|
985
|
+
async findEmailFolder(accountName, emailId, sourceMailbox) {
|
|
986
|
+
const client = await this.connections.getImapClient(accountName);
|
|
987
|
+
// 1. Fetch Message-ID from the source mailbox
|
|
988
|
+
let messageId;
|
|
989
|
+
const srcLock = await ImapService.lockMailbox(client, sourceMailbox);
|
|
990
|
+
try {
|
|
991
|
+
const msg = await client.fetchOne(emailId, { headers: true }, { uid: true });
|
|
992
|
+
// biome-ignore lint/complexity/useOptionalChain: optional chain breaks TS type narrowing for union with false
|
|
993
|
+
if (msg && msg.headers && Buffer.isBuffer(msg.headers)) {
|
|
994
|
+
const headerText = msg.headers.toString('utf-8');
|
|
995
|
+
const match = /^message-id:\s*(.+)$/im.exec(headerText);
|
|
996
|
+
if (match) {
|
|
997
|
+
messageId = match[1].trim();
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
finally {
|
|
1002
|
+
srcLock.release();
|
|
1003
|
+
}
|
|
1004
|
+
if (!messageId) {
|
|
1005
|
+
throw new Error('Could not retrieve Message-ID for this email.');
|
|
1006
|
+
}
|
|
1007
|
+
// 2. List all real mailboxes (exclude virtual and non-selectable)
|
|
1008
|
+
const allMailboxes = await client.list();
|
|
1009
|
+
const realMailboxes = allMailboxes.filter((mb) => {
|
|
1010
|
+
if (!mb.listed)
|
|
1011
|
+
return false;
|
|
1012
|
+
if (mb.flags?.has('\\Noselect'))
|
|
1013
|
+
return false;
|
|
1014
|
+
const isVirtual = [...ImapService.VIRTUAL_SPECIAL_USE].some((f) => mb.specialUse === f || mb.flags?.has(f));
|
|
1015
|
+
if (isVirtual)
|
|
1016
|
+
return false;
|
|
1017
|
+
return true;
|
|
1018
|
+
});
|
|
1019
|
+
// 3. Search for the Message-ID, stopping at the first hit.
|
|
1020
|
+
//
|
|
1021
|
+
// Each folder costs a SELECT and a header SEARCH, and header SEARCH is
|
|
1022
|
+
// typically an unindexed server-side scan. Continuing after a match spent
|
|
1023
|
+
// that on every remaining folder to produce a list the caller was told to
|
|
1024
|
+
// take the first entry of.
|
|
1025
|
+
//
|
|
1026
|
+
// Likely folders go first so the one hit is also the useful one: a message
|
|
1027
|
+
// is far more often in INBOX or Sent than in an archive label, and on a
|
|
1028
|
+
// label-based server it is in several folders at once.
|
|
1029
|
+
const searchOrder = ImapService.orderByLikelihood(realMailboxes);
|
|
1030
|
+
const folders = [];
|
|
1031
|
+
const findInMailbox = async (mbPath) => {
|
|
1032
|
+
try {
|
|
1033
|
+
const lock = await client.getMailboxLock(mbPath);
|
|
1034
|
+
try {
|
|
1035
|
+
const results = await client.search({ header: { 'message-id': messageId } }, { uid: true });
|
|
1036
|
+
return Array.isArray(results) && results.length > 0;
|
|
1037
|
+
}
|
|
1038
|
+
finally {
|
|
1039
|
+
lock.release();
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
catch {
|
|
1043
|
+
// Skip folders that can't be selected or searched (e.g. \Noselect, INBOX on some providers)
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1048
|
+
for (const mb of searchOrder) {
|
|
1049
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1050
|
+
if (await findInMailbox(mb.path)) {
|
|
1051
|
+
folders.push(mb.path);
|
|
1052
|
+
break;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return { folders, messageId };
|
|
1056
|
+
}
|
|
1057
|
+
// -------------------------------------------------------------------------
|
|
1058
|
+
// Move / Delete
|
|
1059
|
+
// -------------------------------------------------------------------------
|
|
1060
|
+
async moveEmail(accountName, emailId, sourceMailbox, destinationMailbox) {
|
|
1061
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1062
|
+
const safeSource = sanitizeMailboxName(sourceMailbox);
|
|
1063
|
+
const safeDest = sanitizeMailboxName(destinationMailbox);
|
|
1064
|
+
await ImapService.assertRealMailbox(client, safeSource);
|
|
1065
|
+
const lock = await client.getMailboxLock(safeSource);
|
|
1066
|
+
try {
|
|
1067
|
+
const ok = await imapCommand(`Moving message to "${safeDest}"`, () => client.messageMove(emailId, safeDest, { uid: true }));
|
|
1068
|
+
if (!ok) {
|
|
1069
|
+
throw new Error(`IMAP server rejected the move from "${safeSource}" to "${safeDest}".`);
|
|
1070
|
+
}
|
|
1071
|
+
this.forgetBodies(accountName, safeSource, [parseInt(emailId, 10)]);
|
|
1072
|
+
}
|
|
1073
|
+
finally {
|
|
1074
|
+
lock.release();
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
async deleteEmail(accountName, emailId, mailbox = 'INBOX', permanent = false) {
|
|
1078
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1079
|
+
const safeMailbox = sanitizeMailboxName(mailbox);
|
|
1080
|
+
if (permanent) {
|
|
1081
|
+
const lock = await client.getMailboxLock(safeMailbox);
|
|
1082
|
+
try {
|
|
1083
|
+
const ok = await client.messageDelete(emailId, { uid: true });
|
|
1084
|
+
if (!ok) {
|
|
1085
|
+
throw new Error('IMAP server rejected the delete operation.');
|
|
1086
|
+
}
|
|
1087
|
+
this.forgetBodies(accountName, safeMailbox, [parseInt(emailId, 10)]);
|
|
1088
|
+
}
|
|
1089
|
+
finally {
|
|
1090
|
+
lock.release();
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
else {
|
|
1094
|
+
await ImapService.assertRealMailbox(client, safeMailbox);
|
|
1095
|
+
const mailboxes = await client.list();
|
|
1096
|
+
const trash = mailboxes.find((mb) => mb.specialUse === '\\Trash');
|
|
1097
|
+
const trashPath = trash?.path ?? 'Trash';
|
|
1098
|
+
const lock = await client.getMailboxLock(safeMailbox);
|
|
1099
|
+
try {
|
|
1100
|
+
const ok = await imapCommand(`Moving message to "${trashPath}"`, () => client.messageMove(emailId, trashPath, { uid: true }));
|
|
1101
|
+
if (!ok) {
|
|
1102
|
+
throw new Error('IMAP server rejected the move to Trash.');
|
|
1103
|
+
}
|
|
1104
|
+
this.forgetBodies(accountName, safeMailbox, [parseInt(emailId, 10)]);
|
|
1105
|
+
}
|
|
1106
|
+
finally {
|
|
1107
|
+
lock.release();
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
// -------------------------------------------------------------------------
|
|
1112
|
+
// Flag management
|
|
1113
|
+
// -------------------------------------------------------------------------
|
|
1114
|
+
async setFlags(accountName, emailId, mailbox, action) {
|
|
1115
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1116
|
+
const safeMailbox = sanitizeMailboxName(mailbox);
|
|
1117
|
+
const lock = await client.getMailboxLock(safeMailbox);
|
|
1118
|
+
try {
|
|
1119
|
+
const flagMap = {
|
|
1120
|
+
read: { flags: ['\\Seen'], add: true },
|
|
1121
|
+
unread: { flags: ['\\Seen'], add: false },
|
|
1122
|
+
flag: { flags: ['\\Flagged'], add: true },
|
|
1123
|
+
unflag: { flags: ['\\Flagged'], add: false },
|
|
1124
|
+
};
|
|
1125
|
+
const { flags, add } = flagMap[action];
|
|
1126
|
+
let ok;
|
|
1127
|
+
if (add) {
|
|
1128
|
+
ok = await client.messageFlagsAdd(emailId, flags, { uid: true });
|
|
1129
|
+
}
|
|
1130
|
+
else {
|
|
1131
|
+
ok = await client.messageFlagsRemove(emailId, flags, { uid: true });
|
|
1132
|
+
}
|
|
1133
|
+
if (!ok) {
|
|
1134
|
+
throw new Error(`IMAP server rejected the ${action} flag operation.`);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
finally {
|
|
1138
|
+
lock.release();
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
// -------------------------------------------------------------------------
|
|
1142
|
+
// Bulk operations
|
|
1143
|
+
// -------------------------------------------------------------------------
|
|
1144
|
+
async bulkSetFlags(accountName, ids, mailbox, action) {
|
|
1145
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1146
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1147
|
+
const result = {
|
|
1148
|
+
total: ids.length,
|
|
1149
|
+
succeeded: 0,
|
|
1150
|
+
failed: 0,
|
|
1151
|
+
errors: [],
|
|
1152
|
+
};
|
|
1153
|
+
try {
|
|
1154
|
+
const flagMap = {
|
|
1155
|
+
mark_read: { flags: ['\\Seen'], add: true },
|
|
1156
|
+
mark_unread: { flags: ['\\Seen'], add: false },
|
|
1157
|
+
flag: { flags: ['\\Flagged'], add: true },
|
|
1158
|
+
unflag: { flags: ['\\Flagged'], add: false },
|
|
1159
|
+
};
|
|
1160
|
+
const { flags, add } = flagMap[action];
|
|
1161
|
+
const range = ids.join(',');
|
|
1162
|
+
let ok;
|
|
1163
|
+
if (add) {
|
|
1164
|
+
ok = await client.messageFlagsAdd(range, flags, { uid: true });
|
|
1165
|
+
}
|
|
1166
|
+
else {
|
|
1167
|
+
ok = await client.messageFlagsRemove(range, flags, { uid: true });
|
|
1168
|
+
}
|
|
1169
|
+
if (ok) {
|
|
1170
|
+
result.succeeded = ids.length;
|
|
1171
|
+
}
|
|
1172
|
+
else {
|
|
1173
|
+
result.failed = ids.length;
|
|
1174
|
+
result.errors = ['IMAP server rejected the flag operation.'];
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
catch (err) {
|
|
1178
|
+
result.failed = ids.length;
|
|
1179
|
+
result.errors = [err instanceof Error ? err.message : String(err)];
|
|
1180
|
+
}
|
|
1181
|
+
finally {
|
|
1182
|
+
lock.release();
|
|
1183
|
+
}
|
|
1184
|
+
if (result.errors?.length === 0)
|
|
1185
|
+
delete result.errors;
|
|
1186
|
+
return result;
|
|
1187
|
+
}
|
|
1188
|
+
async bulkMove(accountName, ids, mailbox, destination) {
|
|
1189
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1190
|
+
// The destination is never locked, so it needs validating on its own —
|
|
1191
|
+
// it goes straight to MOVE as a mailbox path.
|
|
1192
|
+
const safeDestination = sanitizeMailboxName(destination);
|
|
1193
|
+
await ImapService.assertRealMailbox(client, mailbox);
|
|
1194
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1195
|
+
const result = {
|
|
1196
|
+
total: ids.length,
|
|
1197
|
+
succeeded: 0,
|
|
1198
|
+
failed: 0,
|
|
1199
|
+
errors: [],
|
|
1200
|
+
};
|
|
1201
|
+
try {
|
|
1202
|
+
const range = ids.join(',');
|
|
1203
|
+
const ok = await imapCommand(`Moving messages to "${safeDestination}"`, () => client.messageMove(range, safeDestination, { uid: true }));
|
|
1204
|
+
if (ok) {
|
|
1205
|
+
result.succeeded = ids.length;
|
|
1206
|
+
this.forgetBodies(accountName, mailbox, ids);
|
|
1207
|
+
}
|
|
1208
|
+
else {
|
|
1209
|
+
result.failed = ids.length;
|
|
1210
|
+
result.errors = ['IMAP server rejected the move operation.'];
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
catch (err) {
|
|
1214
|
+
result.failed = ids.length;
|
|
1215
|
+
result.errors = [err instanceof Error ? err.message : String(err)];
|
|
1216
|
+
}
|
|
1217
|
+
finally {
|
|
1218
|
+
lock.release();
|
|
1219
|
+
}
|
|
1220
|
+
if (result.errors?.length === 0)
|
|
1221
|
+
delete result.errors;
|
|
1222
|
+
return result;
|
|
1223
|
+
}
|
|
1224
|
+
async bulkDelete(accountName, ids, mailbox, permanent = false) {
|
|
1225
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1226
|
+
const result = {
|
|
1227
|
+
total: ids.length,
|
|
1228
|
+
succeeded: 0,
|
|
1229
|
+
failed: 0,
|
|
1230
|
+
errors: [],
|
|
1231
|
+
};
|
|
1232
|
+
if (permanent) {
|
|
1233
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1234
|
+
try {
|
|
1235
|
+
const range = ids.join(',');
|
|
1236
|
+
const ok = await client.messageDelete(range, { uid: true });
|
|
1237
|
+
if (ok) {
|
|
1238
|
+
result.succeeded = ids.length;
|
|
1239
|
+
this.forgetBodies(accountName, mailbox, ids);
|
|
1240
|
+
}
|
|
1241
|
+
else {
|
|
1242
|
+
result.failed = ids.length;
|
|
1243
|
+
result.errors = ['IMAP server rejected the delete operation.'];
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
catch (err) {
|
|
1247
|
+
result.failed = ids.length;
|
|
1248
|
+
result.errors = [err instanceof Error ? err.message : String(err)];
|
|
1249
|
+
}
|
|
1250
|
+
finally {
|
|
1251
|
+
lock.release();
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
else {
|
|
1255
|
+
await ImapService.assertRealMailbox(client, mailbox);
|
|
1256
|
+
const mailboxes = await client.list();
|
|
1257
|
+
const trash = mailboxes.find((mb) => mb.specialUse === '\\Trash');
|
|
1258
|
+
const trashPath = trash?.path ?? 'Trash';
|
|
1259
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1260
|
+
try {
|
|
1261
|
+
const range = ids.join(',');
|
|
1262
|
+
const ok = await imapCommand(`Moving messages to "${trashPath}"`, () => client.messageMove(range, trashPath, { uid: true }));
|
|
1263
|
+
if (ok) {
|
|
1264
|
+
result.succeeded = ids.length;
|
|
1265
|
+
this.forgetBodies(accountName, mailbox, ids);
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
result.failed = ids.length;
|
|
1269
|
+
result.errors = ['IMAP server rejected the move to Trash.'];
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
catch (err) {
|
|
1273
|
+
result.failed = ids.length;
|
|
1274
|
+
result.errors = [err instanceof Error ? err.message : String(err)];
|
|
1275
|
+
}
|
|
1276
|
+
finally {
|
|
1277
|
+
lock.release();
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
if (result.errors?.length === 0)
|
|
1281
|
+
delete result.errors;
|
|
1282
|
+
return result;
|
|
1283
|
+
}
|
|
1284
|
+
// -------------------------------------------------------------------------
|
|
1285
|
+
// Draft management
|
|
1286
|
+
// -------------------------------------------------------------------------
|
|
1287
|
+
async saveDraft(accountName, options) {
|
|
1288
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1289
|
+
const account = this.connections.getAccount(accountName);
|
|
1290
|
+
// Find the Drafts folder
|
|
1291
|
+
const mailboxes = await client.list();
|
|
1292
|
+
const drafts = mailboxes.find((mb) => mb.specialUse === '\\Drafts');
|
|
1293
|
+
const draftsPath = drafts?.path ?? 'Drafts';
|
|
1294
|
+
// Build via MailComposer so headers are folded/encoded and body is transfer-encoded;
|
|
1295
|
+
// manual concat left \r\n.\r\n in body unstuffed and required ad-hoc sanitizeHeader.
|
|
1296
|
+
const { default: MailComposer } = await import('nodemailer/lib/mail-composer/index.js');
|
|
1297
|
+
const composer = new MailComposer({
|
|
1298
|
+
from: account.fullName ? { name: account.fullName, address: account.email } : account.email,
|
|
1299
|
+
to: options.to.join(', '),
|
|
1300
|
+
cc: options.cc?.join(', '),
|
|
1301
|
+
bcc: options.bcc?.join(', '),
|
|
1302
|
+
subject: options.subject,
|
|
1303
|
+
date: new Date(),
|
|
1304
|
+
...(options.inReplyTo ? { inReplyTo: options.inReplyTo } : {}),
|
|
1305
|
+
...(options.html ? { html: options.body } : { text: options.body }),
|
|
1306
|
+
});
|
|
1307
|
+
const rawMessage = await composer
|
|
1308
|
+
.compile()
|
|
1309
|
+
.build();
|
|
1310
|
+
const appendResult = await imapCommand(`Saving draft to "${draftsPath}"`, () => client.append(draftsPath, Buffer.from(rawMessage), ['\\Draft', '\\Seen']));
|
|
1311
|
+
return {
|
|
1312
|
+
id: appendResult.uid ?? 0,
|
|
1313
|
+
mailbox: draftsPath,
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Fetch a draft message for sending.
|
|
1318
|
+
* Returns the parsed draft with recipients and content.
|
|
1319
|
+
*/
|
|
1320
|
+
async fetchDraft(accountName, emailId, mailbox) {
|
|
1321
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1322
|
+
// Find drafts folder if not specified
|
|
1323
|
+
let draftsPath = mailbox;
|
|
1324
|
+
if (!draftsPath) {
|
|
1325
|
+
const mailboxes = await client.list();
|
|
1326
|
+
const draftsFolder = mailboxes.find((mb) => mb.specialUse === '\\Drafts');
|
|
1327
|
+
draftsPath = draftsFolder?.path ?? 'Drafts';
|
|
1328
|
+
}
|
|
1329
|
+
const email = await this.getEmail(accountName, String(emailId), draftsPath);
|
|
1330
|
+
return { email, mailbox: draftsPath };
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Append a sent message to the account's Sent folder.
|
|
1334
|
+
*
|
|
1335
|
+
* SMTP delivery and Sent-folder filing are separate concerns: this is best
|
|
1336
|
+
* effort by contract. Callers must treat an APPEND failure as a warning,
|
|
1337
|
+
* never as a failed send - the mail already went out.
|
|
1338
|
+
*
|
|
1339
|
+
* The folder is located per attempt from the server's own listing, so
|
|
1340
|
+
* provider differences (Gmail's "[Gmail]/Sent Mail", "Sent Items",
|
|
1341
|
+
* "INBOX.Sent", ...) resolve without configuration. Returns whether a
|
|
1342
|
+
* folder was found, so callers can log usefully when it was not.
|
|
1343
|
+
*/
|
|
1344
|
+
async appendSent(accountName, raw) {
|
|
1345
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1346
|
+
const mailboxes = await client.list();
|
|
1347
|
+
const sentFolder = (mailboxes ?? []).find((m) => m.specialUse === '\\Sent') ??
|
|
1348
|
+
(mailboxes ?? []).find((m) => {
|
|
1349
|
+
const p = String(m.path).toLowerCase();
|
|
1350
|
+
return (p === 'sent' ||
|
|
1351
|
+
p === 'sent mail' ||
|
|
1352
|
+
p.endsWith('/sent') ||
|
|
1353
|
+
p.endsWith('/sent mail') ||
|
|
1354
|
+
p.endsWith('.sent'));
|
|
1355
|
+
});
|
|
1356
|
+
if (!sentFolder)
|
|
1357
|
+
return { appended: false };
|
|
1358
|
+
const lock = await ImapService.lockMailbox(client, String(sentFolder.path));
|
|
1359
|
+
try {
|
|
1360
|
+
await client.append(String(sentFolder.path), raw, ['\\Seen']);
|
|
1361
|
+
return { appended: true, folder: String(sentFolder.path) };
|
|
1362
|
+
}
|
|
1363
|
+
finally {
|
|
1364
|
+
lock.release();
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Sender authentication signals for one message, from headers already on
|
|
1369
|
+
* the server - a single headers-only fetch, no body round trips.
|
|
1370
|
+
*/
|
|
1371
|
+
async getEmailSecurity(accountName, emailId, mailbox = 'INBOX') {
|
|
1372
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1373
|
+
const uid = parseInt(emailId, 10);
|
|
1374
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1375
|
+
try {
|
|
1376
|
+
const msg = await client.fetchOne(String(uid), { uid: true, envelope: true, headers: true }, { uid: true });
|
|
1377
|
+
if (!msg)
|
|
1378
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
1379
|
+
const headerBlock = Buffer.isBuffer(msg.headers) ? msg.headers.toString('utf-8') : '';
|
|
1380
|
+
const values = extractAuthenticationResults(headerBlock);
|
|
1381
|
+
const signals = parseAuthSignals(values);
|
|
1382
|
+
const headerValue = (key) => {
|
|
1383
|
+
const re = new RegExp(`^${key}:[ \\t]*(.*)$`, 'im');
|
|
1384
|
+
const m = re.exec(headerBlock);
|
|
1385
|
+
return m ? m[1].trim() : undefined;
|
|
1386
|
+
};
|
|
1387
|
+
return {
|
|
1388
|
+
...signals,
|
|
1389
|
+
replyTo: headerValue('reply-to'),
|
|
1390
|
+
returnPath: headerValue('return-path'),
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
finally {
|
|
1394
|
+
lock.release();
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
/** Delete a draft after it has been sent. */
|
|
1398
|
+
async deleteDraft(accountName, emailId, mailbox) {
|
|
1399
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1400
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1401
|
+
try {
|
|
1402
|
+
await client.messageDelete(String(emailId), { uid: true });
|
|
1403
|
+
}
|
|
1404
|
+
finally {
|
|
1405
|
+
lock.release();
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
// -------------------------------------------------------------------------
|
|
1409
|
+
// Mailbox (folder) CRUD
|
|
1410
|
+
// -------------------------------------------------------------------------
|
|
1411
|
+
async createMailbox(accountName, folderPath) {
|
|
1412
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1413
|
+
await imapCommand(`Creating mailbox "${folderPath}"`, () => client.mailboxCreate(folderPath));
|
|
1414
|
+
}
|
|
1415
|
+
async renameMailbox(accountName, folderPath, newPath) {
|
|
1416
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1417
|
+
await imapCommand(`Renaming mailbox "${folderPath}" to "${newPath}"`, () => client.mailboxRename(folderPath, newPath));
|
|
1418
|
+
}
|
|
1419
|
+
async deleteMailbox(accountName, folderPath) {
|
|
1420
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1421
|
+
await imapCommand(`Deleting mailbox "${folderPath}"`, () => client.mailboxDelete(folderPath));
|
|
1422
|
+
}
|
|
1423
|
+
// -------------------------------------------------------------------------
|
|
1424
|
+
// Attachment download
|
|
1425
|
+
// -------------------------------------------------------------------------
|
|
1426
|
+
async downloadAttachment(accountName, emailId, mailbox, filename, maxSizeBytes = 5 * 1024 * 1024) {
|
|
1427
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1428
|
+
const uid = parseInt(emailId, 10);
|
|
1429
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1430
|
+
try {
|
|
1431
|
+
// Fetch bodyStructure to find the MIME part
|
|
1432
|
+
const msg = await client.fetchOne(String(uid), { uid: true, bodyStructure: true }, { uid: true });
|
|
1433
|
+
if (!msg) {
|
|
1434
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
1435
|
+
}
|
|
1436
|
+
const attachments = extractAttachments(msg.bodyStructure);
|
|
1437
|
+
const attachment = attachments.find((a) => a.filename === filename);
|
|
1438
|
+
if (!attachment) {
|
|
1439
|
+
const available = attachments
|
|
1440
|
+
.map((a) => `${a.filename} (${Math.round(a.size / 1024)}KB)`)
|
|
1441
|
+
.join(', ');
|
|
1442
|
+
throw new Error(`Attachment "${filename}" not found. ` +
|
|
1443
|
+
(available ? `Available attachments: ${available}` : 'This email has no attachments.'));
|
|
1444
|
+
}
|
|
1445
|
+
if (attachment.size > maxSizeBytes) {
|
|
1446
|
+
const sizeMB = Math.round(attachment.size / 1024 / 1024);
|
|
1447
|
+
const limitMB = Math.round(maxSizeBytes / 1024 / 1024);
|
|
1448
|
+
throw new Error(`Attachment "${filename}" is ${sizeMB}MB, which exceeds the ${limitMB}MB limit. ` +
|
|
1449
|
+
`Use savePath to write it directly to disk instead of loading into context.`);
|
|
1450
|
+
}
|
|
1451
|
+
// Find the MIME part number
|
|
1452
|
+
const partNumber = findMimePartByFilename(msg.bodyStructure, filename);
|
|
1453
|
+
if (!partNumber) {
|
|
1454
|
+
throw new Error(`Could not locate MIME part for "${filename}"`);
|
|
1455
|
+
}
|
|
1456
|
+
// Download the part
|
|
1457
|
+
const downloadResult = await client.download(String(uid), partNumber, {
|
|
1458
|
+
uid: true,
|
|
1459
|
+
});
|
|
1460
|
+
if (!downloadResult?.content) {
|
|
1461
|
+
throw new Error(`Failed to download attachment "${filename}"`);
|
|
1462
|
+
}
|
|
1463
|
+
const chunks = [];
|
|
1464
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1465
|
+
for await (const chunk of downloadResult.content) {
|
|
1466
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1467
|
+
}
|
|
1468
|
+
const content = Buffer.concat(chunks);
|
|
1469
|
+
return {
|
|
1470
|
+
filename: attachment.filename,
|
|
1471
|
+
mimeType: attachment.mimeType,
|
|
1472
|
+
size: content.length,
|
|
1473
|
+
contentBase64: content.toString('base64'),
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
finally {
|
|
1477
|
+
lock.release();
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Fetch every attachment of a message as nodemailer-ready parts.
|
|
1482
|
+
*
|
|
1483
|
+
* Used by forward_email (reattaching the original's parts) and send_draft
|
|
1484
|
+
* (sending a draft's own attachments). The total byte budget is enforced
|
|
1485
|
+
* against the sizes reported by bodyStructure BEFORE any download, so an
|
|
1486
|
+
* oversized original fails at compose time with a clear message instead of
|
|
1487
|
+
* at the SMTP server mid-handshake.
|
|
1488
|
+
*/
|
|
1489
|
+
async fetchMessageAttachments(accountName, emailId, mailbox = 'INBOX', maxTotalEncodedBytes = 25 * 1024 * 1024) {
|
|
1490
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1491
|
+
const uid = parseInt(emailId, 10);
|
|
1492
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1493
|
+
try {
|
|
1494
|
+
const msg = await client.fetchOne(String(uid), { uid: true, bodyStructure: true }, { uid: true });
|
|
1495
|
+
if (!msg) {
|
|
1496
|
+
throw new Error(`Email ${emailId} not found in ${mailbox}`);
|
|
1497
|
+
}
|
|
1498
|
+
const parts = extractAttachmentParts(msg.bodyStructure);
|
|
1499
|
+
if (parts.length === 0)
|
|
1500
|
+
return [];
|
|
1501
|
+
const totalEncodedBytes = parts.reduce((sum, part) => sum + Math.ceil(part.size / 3) * 4, 0);
|
|
1502
|
+
if (totalEncodedBytes > maxTotalEncodedBytes) {
|
|
1503
|
+
const maxTotalMb = Math.floor(maxTotalEncodedBytes / (1024 * 1024));
|
|
1504
|
+
throw new Error(`Original carries about ${Math.ceil(totalEncodedBytes / 1024 / 1024)}MB of ` +
|
|
1505
|
+
`base64-encoded attachments, exceeding the ${maxTotalMb}MB outbound limit. ` +
|
|
1506
|
+
`Forward without attachments or send them another way.`);
|
|
1507
|
+
}
|
|
1508
|
+
const out = [];
|
|
1509
|
+
for (const part of parts) {
|
|
1510
|
+
if (!part.partPath)
|
|
1511
|
+
continue;
|
|
1512
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1513
|
+
const downloadResult = await client.download(String(uid), part.partPath, { uid: true });
|
|
1514
|
+
if (!downloadResult?.content) {
|
|
1515
|
+
throw new Error(`Failed to download attachment "${part.filename}"`);
|
|
1516
|
+
}
|
|
1517
|
+
const chunks = [];
|
|
1518
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1519
|
+
for await (const chunk of downloadResult.content) {
|
|
1520
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1521
|
+
}
|
|
1522
|
+
const content = Buffer.concat(chunks);
|
|
1523
|
+
out.push({
|
|
1524
|
+
filename: part.filename,
|
|
1525
|
+
content: content.toString('base64'),
|
|
1526
|
+
contentType: part.mimeType,
|
|
1527
|
+
encoding: 'base64',
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
return out;
|
|
1531
|
+
}
|
|
1532
|
+
finally {
|
|
1533
|
+
lock.release();
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
// -------------------------------------------------------------------------
|
|
1537
|
+
// Save all email attachments to a local directory
|
|
1538
|
+
// -------------------------------------------------------------------------
|
|
1539
|
+
/**
|
|
1540
|
+
* Download and save all non-ICS attachments from an email to a local directory.
|
|
1541
|
+
* Returns metadata including the saved file paths and file:// URLs.
|
|
1542
|
+
*
|
|
1543
|
+
* Attachments larger than maxSizeBytes (default 25 MB) are skipped.
|
|
1544
|
+
*/
|
|
1545
|
+
async saveEmailAttachments(accountName, emailId, mailbox, destDir, maxSizeBytes = 25 * 1024 * 1024) {
|
|
1546
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1547
|
+
const uid = parseInt(emailId, 10);
|
|
1548
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1549
|
+
let attachmentMetas = [];
|
|
1550
|
+
try {
|
|
1551
|
+
const msg = await client.fetchOne(String(uid), { uid: true, bodyStructure: true }, { uid: true });
|
|
1552
|
+
if (!msg)
|
|
1553
|
+
return [];
|
|
1554
|
+
attachmentMetas = extractAttachments(msg.bodyStructure).filter((a) => a.size <= maxSizeBytes && !isCalendarPart(a.mimeType, a.filename));
|
|
1555
|
+
}
|
|
1556
|
+
finally {
|
|
1557
|
+
lock.release();
|
|
1558
|
+
}
|
|
1559
|
+
if (attachmentMetas.length === 0)
|
|
1560
|
+
return [];
|
|
1561
|
+
const { mkdir } = await import('node:fs/promises');
|
|
1562
|
+
await mkdir(destDir, { recursive: true });
|
|
1563
|
+
// Use the attachment parts directly, not by filename, to avoid
|
|
1564
|
+
// cross-copying when two attachments share a basename.
|
|
1565
|
+
const attachmentParts = (() => {
|
|
1566
|
+
const parts = [];
|
|
1567
|
+
const _walk = (node, partPath = '') => {
|
|
1568
|
+
if (!node || typeof node !== 'object')
|
|
1569
|
+
return;
|
|
1570
|
+
const bs = node;
|
|
1571
|
+
const cur = bs.part ?? partPath;
|
|
1572
|
+
if (bs.disposition === 'attachment') {
|
|
1573
|
+
const params = (bs.dispositionParameters ?? bs.parameters ?? {});
|
|
1574
|
+
const fn = params.filename ?? params.name ?? 'unnamed';
|
|
1575
|
+
const meta = attachmentMetas.find((m) => m.filename === fn);
|
|
1576
|
+
if (meta)
|
|
1577
|
+
parts.push({ filename: fn, mimeType: meta.mimeType, size: meta.size, partPath: cur });
|
|
1578
|
+
}
|
|
1579
|
+
if (Array.isArray(bs.childNodes)) {
|
|
1580
|
+
bs.childNodes.forEach((child, i) => {
|
|
1581
|
+
const cp = cur ? `${cur}.${i + 1}` : String(i + 1);
|
|
1582
|
+
_walk(child, cp);
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
// Re-fetch structure to get part paths — reuse the earlier fetch
|
|
1587
|
+
return parts;
|
|
1588
|
+
})();
|
|
1589
|
+
// Pair each attachment meta to its part by occurrence order for that filename
|
|
1590
|
+
const occurrenceCursor = new Map();
|
|
1591
|
+
const metaToPart = new Map();
|
|
1592
|
+
attachmentMetas.forEach((meta, idx) => {
|
|
1593
|
+
const occ = occurrenceCursor.get(meta.filename) ?? 0;
|
|
1594
|
+
occurrenceCursor.set(meta.filename, occ + 1);
|
|
1595
|
+
const candidates = attachmentParts.filter((p) => p.filename === meta.filename);
|
|
1596
|
+
if (candidates[occ])
|
|
1597
|
+
metaToPart.set(idx, candidates[occ]);
|
|
1598
|
+
});
|
|
1599
|
+
const seenNames = new Map();
|
|
1600
|
+
const results = await Promise.allSettled(attachmentMetas.map(async (meta, idx) => {
|
|
1601
|
+
const part = metaToPart.get(idx);
|
|
1602
|
+
const partPath = part?.partPath;
|
|
1603
|
+
let downloaded;
|
|
1604
|
+
if (partPath) {
|
|
1605
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1606
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1607
|
+
try {
|
|
1608
|
+
const dl = await client.download(String(parseInt(emailId, 10)), partPath, {
|
|
1609
|
+
uid: true,
|
|
1610
|
+
});
|
|
1611
|
+
if (!dl.content) {
|
|
1612
|
+
throw new Error(`Failed to download mail part "${partPath}"`);
|
|
1613
|
+
}
|
|
1614
|
+
const chunks = [];
|
|
1615
|
+
for await (const c of dl.content)
|
|
1616
|
+
chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c));
|
|
1617
|
+
const buf = Buffer.concat(chunks);
|
|
1618
|
+
downloaded = { contentBase64: buf.toString('base64'), size: buf.length };
|
|
1619
|
+
}
|
|
1620
|
+
finally {
|
|
1621
|
+
lock.release();
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
else {
|
|
1625
|
+
downloaded = await this.downloadAttachment(accountName, emailId, mailbox, meta.filename, maxSizeBytes);
|
|
1626
|
+
}
|
|
1627
|
+
const resolvedDir = path.resolve(destDir);
|
|
1628
|
+
let sanitizedBase = path
|
|
1629
|
+
.basename(meta.filename)
|
|
1630
|
+
.replace(/[/\\?%*:|"<>]/g, '_')
|
|
1631
|
+
.replace(/^\.+$/, '_') || 'unnamed';
|
|
1632
|
+
// Dedup same-basename files: invoice.pdf, invoice-1.pdf, etc.
|
|
1633
|
+
const count = seenNames.get(sanitizedBase) ?? 0;
|
|
1634
|
+
seenNames.set(sanitizedBase, count + 1);
|
|
1635
|
+
if (count > 0) {
|
|
1636
|
+
const ext = path.extname(sanitizedBase);
|
|
1637
|
+
const base = path.basename(sanitizedBase, ext);
|
|
1638
|
+
sanitizedBase = `${base}-${count}${ext}`;
|
|
1639
|
+
}
|
|
1640
|
+
const localPath = path.resolve(resolvedDir, sanitizedBase);
|
|
1641
|
+
if (!localPath.startsWith(resolvedDir + path.sep)) {
|
|
1642
|
+
throw new Error(`Refusing to write outside the destination directory`);
|
|
1643
|
+
}
|
|
1644
|
+
const { writeFile } = await import('node:fs/promises');
|
|
1645
|
+
await writeFile(localPath, Buffer.from(downloaded.contentBase64, 'base64'));
|
|
1646
|
+
return {
|
|
1647
|
+
filename: meta.filename,
|
|
1648
|
+
localPath,
|
|
1649
|
+
fileUrl: `file://${localPath}`,
|
|
1650
|
+
mimeType: meta.mimeType,
|
|
1651
|
+
size: downloaded.size,
|
|
1652
|
+
};
|
|
1653
|
+
}));
|
|
1654
|
+
const rejected = results.filter((r) => r.status === 'rejected');
|
|
1655
|
+
if (rejected.length > 0) {
|
|
1656
|
+
// Surface failures — caller decides; don't silently drop attachments
|
|
1657
|
+
const msgs = rejected.map((r) => String(r.reason?.message ?? r.reason)).join('; ');
|
|
1658
|
+
throw new Error(`Failed to save ${rejected.length} attachment(s): ${msgs}`);
|
|
1659
|
+
}
|
|
1660
|
+
return results
|
|
1661
|
+
.filter((r) => r.status === 'fulfilled')
|
|
1662
|
+
.map((r) => r.value);
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Reconstruct an email thread by following References / In-Reply-To chains.
|
|
1666
|
+
* Searches by Message-ID header for each reference and returns messages in
|
|
1667
|
+
* chronological order. Caps at MAX_THREAD_MESSAGES to prevent runaway chains.
|
|
1668
|
+
*/
|
|
1669
|
+
async getThread(accountName, messageId, mailbox = 'INBOX') {
|
|
1670
|
+
const MAX_THREAD_MESSAGES = 50;
|
|
1671
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1672
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1673
|
+
try {
|
|
1674
|
+
// Collect all Message-IDs in the thread
|
|
1675
|
+
const targetMsgIds = new Set([messageId]);
|
|
1676
|
+
// First, find the root message to get its References chain
|
|
1677
|
+
const rootSearch = await client.search({ header: { 'Message-ID': messageId } }, { uid: true });
|
|
1678
|
+
const rootUids = Array.isArray(rootSearch) ? rootSearch : [];
|
|
1679
|
+
if (rootUids.length > 0) {
|
|
1680
|
+
const rootMsg = await client.fetchOne(String(rootUids[0]), { uid: true, envelope: true, source: true }, { uid: true });
|
|
1681
|
+
if (rootMsg) {
|
|
1682
|
+
const raw = rootMsg;
|
|
1683
|
+
const envelope = (raw.envelope ?? {});
|
|
1684
|
+
const inReplyTo = envelope.inReplyTo;
|
|
1685
|
+
if (inReplyTo)
|
|
1686
|
+
targetMsgIds.add(inReplyTo);
|
|
1687
|
+
// Parse References header from source
|
|
1688
|
+
if (raw.source && Buffer.isBuffer(raw.source)) {
|
|
1689
|
+
const src = raw.source.toString('utf-8');
|
|
1690
|
+
const refMatch = /^References:\s*(.+?)(?:\r?\n(?!\s))/ms.exec(src);
|
|
1691
|
+
if (refMatch) {
|
|
1692
|
+
refMatch[1]
|
|
1693
|
+
.split(/\s+/)
|
|
1694
|
+
.filter(Boolean)
|
|
1695
|
+
.forEach((ref) => {
|
|
1696
|
+
targetMsgIds.add(ref);
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
// Search for all related messages by Message-ID
|
|
1703
|
+
const foundUids = new Set();
|
|
1704
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1705
|
+
for (const msgId of targetMsgIds) {
|
|
1706
|
+
if (foundUids.size >= MAX_THREAD_MESSAGES)
|
|
1707
|
+
break;
|
|
1708
|
+
try {
|
|
1709
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1710
|
+
const searchResult = await client.search({ header: { 'Message-ID': msgId } }, { uid: true });
|
|
1711
|
+
if (Array.isArray(searchResult)) {
|
|
1712
|
+
searchResult.forEach((uid) => {
|
|
1713
|
+
foundUids.add(uid);
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
catch {
|
|
1718
|
+
// Header search may not be supported for all messages
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
// Also search for messages that reference any of our Message-IDs
|
|
1722
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1723
|
+
for (const msgId of targetMsgIds) {
|
|
1724
|
+
if (foundUids.size >= MAX_THREAD_MESSAGES)
|
|
1725
|
+
break;
|
|
1726
|
+
try {
|
|
1727
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1728
|
+
const refSearch = await client.search({ header: { References: msgId } }, { uid: true });
|
|
1729
|
+
if (Array.isArray(refSearch)) {
|
|
1730
|
+
refSearch.forEach((uid) => {
|
|
1731
|
+
foundUids.add(uid);
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1735
|
+
const replySearch = await client.search({ header: { 'In-Reply-To': msgId } }, { uid: true });
|
|
1736
|
+
if (Array.isArray(replySearch)) {
|
|
1737
|
+
replySearch.forEach((uid) => {
|
|
1738
|
+
foundUids.add(uid);
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
catch {
|
|
1743
|
+
// Header search may fail on some servers
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
if (foundUids.size === 0) {
|
|
1747
|
+
return {
|
|
1748
|
+
threadId: messageId,
|
|
1749
|
+
messages: [],
|
|
1750
|
+
participants: [],
|
|
1751
|
+
messageCount: 0,
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
// Fetch full content for all thread messages
|
|
1755
|
+
const uidList = Array.from(foundUids).slice(0, MAX_THREAD_MESSAGES);
|
|
1756
|
+
const range = uidList.join(',');
|
|
1757
|
+
const messages = [];
|
|
1758
|
+
// Collect the whole fetch before converting any of it. messageToEmail
|
|
1759
|
+
// downloads a body part, and ImapFlow runs one command at a time — so
|
|
1760
|
+
// converting inside this loop deadlocks the connection: the stream can't
|
|
1761
|
+
// finish until the download does, and the download can't start until the
|
|
1762
|
+
// stream finishes.
|
|
1763
|
+
const rawMessages = [];
|
|
1764
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1765
|
+
for await (const msg of client.fetch(range, {
|
|
1766
|
+
uid: true,
|
|
1767
|
+
envelope: true,
|
|
1768
|
+
flags: true,
|
|
1769
|
+
bodyStructure: true,
|
|
1770
|
+
// Headers, not source: a thread caps at 50 messages, and pulling
|
|
1771
|
+
// full sources means transferring 50 entire messages — attachments
|
|
1772
|
+
// included — to render what is mostly a summary.
|
|
1773
|
+
headers: true,
|
|
1774
|
+
}, { uid: true })) {
|
|
1775
|
+
rawMessages.push(msg);
|
|
1776
|
+
}
|
|
1777
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1778
|
+
for (const raw of rawMessages) {
|
|
1779
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1780
|
+
messages.push(await messageToEmail(raw, client, raw.uid));
|
|
1781
|
+
}
|
|
1782
|
+
// Sort chronologically
|
|
1783
|
+
messages.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
|
|
1784
|
+
// Extract unique participants
|
|
1785
|
+
const participantMap = new Map();
|
|
1786
|
+
messages.forEach((email) => {
|
|
1787
|
+
const addParticipant = (addr) => {
|
|
1788
|
+
const key = addr.address.toLowerCase();
|
|
1789
|
+
if (!participantMap.has(key)) {
|
|
1790
|
+
participantMap.set(key, addr);
|
|
1791
|
+
}
|
|
1792
|
+
};
|
|
1793
|
+
addParticipant(email.from);
|
|
1794
|
+
email.to.forEach(addParticipant);
|
|
1795
|
+
email.cc?.forEach(addParticipant);
|
|
1796
|
+
});
|
|
1797
|
+
return {
|
|
1798
|
+
threadId: messageId,
|
|
1799
|
+
messages,
|
|
1800
|
+
participants: Array.from(participantMap.values()),
|
|
1801
|
+
messageCount: messages.length,
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
finally {
|
|
1805
|
+
lock.release();
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
// -------------------------------------------------------------------------
|
|
1809
|
+
// Contact extraction
|
|
1810
|
+
// -------------------------------------------------------------------------
|
|
1811
|
+
async extractContacts(accountName, options = {}) {
|
|
1812
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1813
|
+
const mailbox = options.mailbox ?? 'INBOX';
|
|
1814
|
+
const limit = Math.min(options.limit ?? 100, 500);
|
|
1815
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1816
|
+
try {
|
|
1817
|
+
// Search for all messages, take the latest N
|
|
1818
|
+
const searchResult = await client.search({ all: true }, { uid: true });
|
|
1819
|
+
const uids = Array.isArray(searchResult) ? searchResult : [];
|
|
1820
|
+
if (uids.length === 0)
|
|
1821
|
+
return [];
|
|
1822
|
+
uids.sort((a, b) => b - a);
|
|
1823
|
+
const targetUids = uids.slice(0, limit);
|
|
1824
|
+
const range = targetUids.join(',');
|
|
1825
|
+
const contactMap = new Map();
|
|
1826
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1827
|
+
for await (const msg of client.fetch(range, { uid: true, envelope: true }, { uid: true })) {
|
|
1828
|
+
const envelope = (msg.envelope ?? {});
|
|
1829
|
+
const date = envelope.date ? new Date(envelope.date) : new Date();
|
|
1830
|
+
const addressLists = [
|
|
1831
|
+
envelope.from,
|
|
1832
|
+
envelope.to,
|
|
1833
|
+
envelope.cc,
|
|
1834
|
+
];
|
|
1835
|
+
addressLists.forEach((addrs) => {
|
|
1836
|
+
(addrs ?? []).forEach((addr) => {
|
|
1837
|
+
if (!addr.address)
|
|
1838
|
+
return;
|
|
1839
|
+
const key = addr.address.toLowerCase();
|
|
1840
|
+
const existing = contactMap.get(key);
|
|
1841
|
+
if (existing) {
|
|
1842
|
+
existing.frequency += 1;
|
|
1843
|
+
if (date > existing.lastSeen) {
|
|
1844
|
+
existing.lastSeen = date;
|
|
1845
|
+
if (addr.name)
|
|
1846
|
+
existing.name = addr.name;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
else {
|
|
1850
|
+
contactMap.set(key, {
|
|
1851
|
+
name: addr.name ?? undefined,
|
|
1852
|
+
email: addr.address,
|
|
1853
|
+
frequency: 1,
|
|
1854
|
+
lastSeen: date,
|
|
1855
|
+
});
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
// Sort by frequency descending
|
|
1861
|
+
const contacts = Array.from(contactMap.values())
|
|
1862
|
+
.sort((a, b) => b.frequency - a.frequency)
|
|
1863
|
+
.map((c) => ({
|
|
1864
|
+
name: c.name,
|
|
1865
|
+
email: c.email,
|
|
1866
|
+
frequency: c.frequency,
|
|
1867
|
+
lastSeen: c.lastSeen.toISOString(),
|
|
1868
|
+
}));
|
|
1869
|
+
return contacts;
|
|
1870
|
+
}
|
|
1871
|
+
finally {
|
|
1872
|
+
lock.release();
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
// -------------------------------------------------------------------------
|
|
1876
|
+
// Email analytics
|
|
1877
|
+
// -------------------------------------------------------------------------
|
|
1878
|
+
async getEmailStats(accountName, mailbox, period) {
|
|
1879
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1880
|
+
const now = new Date();
|
|
1881
|
+
const since = new Date(now);
|
|
1882
|
+
if (period === 'day')
|
|
1883
|
+
since.setDate(since.getDate() - 1);
|
|
1884
|
+
else if (period === 'week')
|
|
1885
|
+
since.setDate(since.getDate() - 7);
|
|
1886
|
+
else
|
|
1887
|
+
since.setMonth(since.getMonth() - 1);
|
|
1888
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
1889
|
+
try {
|
|
1890
|
+
// Date-range search
|
|
1891
|
+
const uids = await client
|
|
1892
|
+
.search({ since }, { uid: true })
|
|
1893
|
+
.then((r) => (Array.isArray(r) ? r : []));
|
|
1894
|
+
if (uids.length === 0) {
|
|
1895
|
+
return {
|
|
1896
|
+
period,
|
|
1897
|
+
dateRange: {
|
|
1898
|
+
from: since.toISOString().split('T')[0],
|
|
1899
|
+
to: now.toISOString().split('T')[0],
|
|
1900
|
+
},
|
|
1901
|
+
totalReceived: 0,
|
|
1902
|
+
unreadCount: 0,
|
|
1903
|
+
flaggedCount: 0,
|
|
1904
|
+
topSenders: [],
|
|
1905
|
+
dailyVolume: [],
|
|
1906
|
+
hasAttachmentsCount: 0,
|
|
1907
|
+
avgPerDay: 0,
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
const senderMap = new Map();
|
|
1911
|
+
const dailyMap = new Map();
|
|
1912
|
+
let unread = 0;
|
|
1913
|
+
let flagged = 0;
|
|
1914
|
+
let withAttachments = 0;
|
|
1915
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1916
|
+
for await (const msg of ImapService.fetchUidChunks(client, uids, {
|
|
1917
|
+
uid: true,
|
|
1918
|
+
envelope: true,
|
|
1919
|
+
flags: true,
|
|
1920
|
+
bodyStructure: true,
|
|
1921
|
+
}, { uid: true })) {
|
|
1922
|
+
const envelope = (msg.envelope ?? {});
|
|
1923
|
+
const flags = (msg.flags ??
|
|
1924
|
+
new Set());
|
|
1925
|
+
const { bodyStructure } = msg;
|
|
1926
|
+
// Count flags
|
|
1927
|
+
if (!flags.has('\\Seen'))
|
|
1928
|
+
unread += 1;
|
|
1929
|
+
if (flags.has('\\Flagged'))
|
|
1930
|
+
flagged += 1;
|
|
1931
|
+
if (hasAttachments(bodyStructure))
|
|
1932
|
+
withAttachments += 1;
|
|
1933
|
+
// Track sender
|
|
1934
|
+
const fromList = (envelope.from ?? []);
|
|
1935
|
+
if (fromList.length > 0 && fromList[0].address) {
|
|
1936
|
+
const key = fromList[0].address.toLowerCase();
|
|
1937
|
+
const existing = senderMap.get(key);
|
|
1938
|
+
if (existing) {
|
|
1939
|
+
existing.count += 1;
|
|
1940
|
+
}
|
|
1941
|
+
else {
|
|
1942
|
+
senderMap.set(key, {
|
|
1943
|
+
email: fromList[0].address,
|
|
1944
|
+
name: fromList[0].name,
|
|
1945
|
+
count: 1,
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
// Track daily volume
|
|
1950
|
+
const date = envelope.date ? new Date(envelope.date) : new Date();
|
|
1951
|
+
const dayKey = date.toISOString().split('T')[0];
|
|
1952
|
+
dailyMap.set(dayKey, (dailyMap.get(dayKey) ?? 0) + 1);
|
|
1953
|
+
}
|
|
1954
|
+
const topSenders = Array.from(senderMap.values())
|
|
1955
|
+
.sort((a, b) => b.count - a.count)
|
|
1956
|
+
.slice(0, 10);
|
|
1957
|
+
const dailyVolume = Array.from(dailyMap.entries())
|
|
1958
|
+
.map(([date, count]) => ({ date, count }))
|
|
1959
|
+
.sort((a, b) => a.date.localeCompare(b.date));
|
|
1960
|
+
const days = Math.max(1, dailyVolume.length);
|
|
1961
|
+
return {
|
|
1962
|
+
period,
|
|
1963
|
+
dateRange: {
|
|
1964
|
+
from: since.toISOString().split('T')[0],
|
|
1965
|
+
to: now.toISOString().split('T')[0],
|
|
1966
|
+
},
|
|
1967
|
+
totalReceived: uids.length,
|
|
1968
|
+
unreadCount: unread,
|
|
1969
|
+
flaggedCount: flagged,
|
|
1970
|
+
topSenders,
|
|
1971
|
+
dailyVolume,
|
|
1972
|
+
hasAttachmentsCount: withAttachments,
|
|
1973
|
+
avgPerDay: Math.round((uids.length / days) * 10) / 10,
|
|
1974
|
+
};
|
|
1975
|
+
}
|
|
1976
|
+
finally {
|
|
1977
|
+
lock.release();
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
// -------------------------------------------------------------------------
|
|
1981
|
+
// Mailbox snapshot (cheap counters)
|
|
1982
|
+
// -------------------------------------------------------------------------
|
|
1983
|
+
/**
|
|
1984
|
+
* Mailbox counters without scanning the mailbox.
|
|
1985
|
+
*
|
|
1986
|
+
* STATUS answers the totals directly, and counting today's arrivals needs
|
|
1987
|
+
* only the length of a SEARCH result — no envelopes, no body structure. Two
|
|
1988
|
+
* round trips, whatever the mailbox holds.
|
|
1989
|
+
*/
|
|
1990
|
+
async getMailboxSnapshot(accountName, mailbox = 'INBOX') {
|
|
1991
|
+
const client = await this.connections.getImapClient(accountName);
|
|
1992
|
+
const safeMailbox = sanitizeMailboxName(mailbox);
|
|
1993
|
+
const status = await client.status(safeMailbox, { messages: true, unseen: true });
|
|
1994
|
+
const startOfToday = new Date();
|
|
1995
|
+
startOfToday.setHours(0, 0, 0, 0);
|
|
1996
|
+
const lock = await client.getMailboxLock(safeMailbox);
|
|
1997
|
+
let receivedToday = 0;
|
|
1998
|
+
try {
|
|
1999
|
+
const todayUids = await client.search({ since: startOfToday }, { uid: true });
|
|
2000
|
+
receivedToday = Array.isArray(todayUids) ? todayUids.length : 0;
|
|
2001
|
+
}
|
|
2002
|
+
finally {
|
|
2003
|
+
lock.release();
|
|
2004
|
+
}
|
|
2005
|
+
return {
|
|
2006
|
+
total: status === false ? 0 : (status.messages ?? 0),
|
|
2007
|
+
unread: status === false ? 0 : (status.unseen ?? 0),
|
|
2008
|
+
receivedToday,
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
// -------------------------------------------------------------------------
|
|
2012
|
+
// Quota
|
|
2013
|
+
// -------------------------------------------------------------------------
|
|
2014
|
+
async getQuota(accountName) {
|
|
2015
|
+
const client = await this.connections.getImapClient(accountName);
|
|
2016
|
+
try {
|
|
2017
|
+
const quota = await client.getQuota('INBOX');
|
|
2018
|
+
if (!quota?.storage?.limit)
|
|
2019
|
+
return null;
|
|
2020
|
+
const usedMb = Math.round((quota.storage.used ?? 0) / 1024 / 1024);
|
|
2021
|
+
const totalMb = Math.round(quota.storage.limit / 1024 / 1024);
|
|
2022
|
+
return {
|
|
2023
|
+
usedMb,
|
|
2024
|
+
totalMb,
|
|
2025
|
+
percentage: totalMb > 0 ? Math.round((usedMb / totalMb) * 100) : 0,
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
catch {
|
|
2029
|
+
return null;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
// -------------------------------------------------------------------------
|
|
2033
|
+
// Capabilities
|
|
2034
|
+
// -------------------------------------------------------------------------
|
|
2035
|
+
async getCapabilities(accountName) {
|
|
2036
|
+
const client = await this.connections.getImapClient(accountName);
|
|
2037
|
+
try {
|
|
2038
|
+
const caps = client.capabilities;
|
|
2039
|
+
if (!caps)
|
|
2040
|
+
return [];
|
|
2041
|
+
if (caps instanceof Map)
|
|
2042
|
+
return Array.from(caps.keys());
|
|
2043
|
+
return Array.from(caps);
|
|
2044
|
+
}
|
|
2045
|
+
catch {
|
|
2046
|
+
return [];
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
// -------------------------------------------------------------------------
|
|
2050
|
+
// Calendar part extraction
|
|
2051
|
+
// -------------------------------------------------------------------------
|
|
2052
|
+
/* eslint-disable no-await-in-loop, no-restricted-syntax -- Sequential IMAP fetch required */
|
|
2053
|
+
async getCalendarParts(accountName, mailbox, emailId) {
|
|
2054
|
+
const client = await this.connections.getImapClient(accountName);
|
|
2055
|
+
const lock = await ImapService.lockMailbox(client, mailbox);
|
|
2056
|
+
try {
|
|
2057
|
+
const icsContents = [];
|
|
2058
|
+
// Drain the structure fetch completely before issuing any further
|
|
2059
|
+
// command. ImapFlow runs one command at a time, so starting the part
|
|
2060
|
+
// fetch inside this loop deadlocks: the outer stream cannot finish until
|
|
2061
|
+
// the inner one does, and the inner one cannot start until the outer
|
|
2062
|
+
// finishes.
|
|
2063
|
+
const partIds = [];
|
|
2064
|
+
for await (const msg of client.fetch(emailId, { uid: true, bodyStructure: true }, { uid: true })) {
|
|
2065
|
+
const structure = msg.bodyStructure;
|
|
2066
|
+
partIds.push(...this.findCalendarParts(structure));
|
|
2067
|
+
}
|
|
2068
|
+
// Download each part, one command at a time.
|
|
2069
|
+
//
|
|
2070
|
+
// `download()` rather than `fetch({ bodyParts })`: calendar parts are
|
|
2071
|
+
// almost always base64 or quoted-printable, and a bodyParts fetch hands
|
|
2072
|
+
// back the still-encoded bytes. download() applies the transfer decoding,
|
|
2073
|
+
// so the ICS parser gets text it can actually read.
|
|
2074
|
+
for (const partId of partIds) {
|
|
2075
|
+
const part = await client.download(emailId, partId, { uid: true });
|
|
2076
|
+
if (!part?.content)
|
|
2077
|
+
continue;
|
|
2078
|
+
const chunks = [];
|
|
2079
|
+
for await (const chunk of part.content) {
|
|
2080
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
2081
|
+
}
|
|
2082
|
+
if (chunks.length > 0) {
|
|
2083
|
+
icsContents.push(Buffer.concat(chunks).toString('utf-8'));
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
return icsContents;
|
|
2087
|
+
}
|
|
2088
|
+
finally {
|
|
2089
|
+
lock.release();
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
/* eslint-enable no-await-in-loop, no-restricted-syntax */
|
|
2093
|
+
/**
|
|
2094
|
+
* Recursively find body parts with text/calendar content type.
|
|
2095
|
+
*/
|
|
2096
|
+
findCalendarParts(structure, prefix = '') {
|
|
2097
|
+
if (!structure || typeof structure !== 'object')
|
|
2098
|
+
return [];
|
|
2099
|
+
const s = structure;
|
|
2100
|
+
const parts = [];
|
|
2101
|
+
const { type, subtype } = splitMimeType(s.type);
|
|
2102
|
+
const disposition = s.disposition?.toLowerCase() ?? '';
|
|
2103
|
+
// Check for text/calendar part
|
|
2104
|
+
if (type === 'text' && subtype === 'calendar') {
|
|
2105
|
+
const partId = s.part;
|
|
2106
|
+
if (partId)
|
|
2107
|
+
parts.push(partId);
|
|
2108
|
+
else if (prefix)
|
|
2109
|
+
parts.push(prefix);
|
|
2110
|
+
}
|
|
2111
|
+
// Locate calendar parts. Must use the same predicate as the attachment
|
|
2112
|
+
// filter: if the two disagree, a part can be excluded from attachments and
|
|
2113
|
+
// never found as calendar, disappearing from both surfaces.
|
|
2114
|
+
if (disposition === 'attachment' && typeof s.dispositionParameters === 'object') {
|
|
2115
|
+
const params = s.dispositionParameters;
|
|
2116
|
+
const filename = params.filename ?? '';
|
|
2117
|
+
if (isCalendarPart(String(s.type ?? ''), filename)) {
|
|
2118
|
+
const partId = s.part;
|
|
2119
|
+
if (partId)
|
|
2120
|
+
parts.push(partId);
|
|
2121
|
+
else if (prefix)
|
|
2122
|
+
parts.push(prefix);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
// Recurse into child nodes
|
|
2126
|
+
if (Array.isArray(s.childNodes)) {
|
|
2127
|
+
s.childNodes.forEach((child, i) => {
|
|
2128
|
+
const childPrefix = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
|
2129
|
+
parts.push(...this.findCalendarParts(child, childPrefix));
|
|
2130
|
+
});
|
|
2131
|
+
}
|
|
2132
|
+
return parts;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
//# sourceMappingURL=imap.service.js.map
|