@theokit/gateway-email 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
8
+
9
+ The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
10
+
11
+ **The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
12
+
13
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
14
+
15
+ **LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
16
+
17
+ **Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
18
+
19
+ **Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
20
+
21
+ **SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
22
+
23
+ **Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
24
+
25
+ **Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
26
+
27
+ Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
28
+
29
+ WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
30
+
31
+ - 7ccb21b: Two defects that only a real server could show, both found by the live suites.
32
+
33
+ **Email — the bot re-answered its whole unread inbox after every restart.** Nothing ever flagged a message as read on the server, and the only record of what had already been handled lived in memory and was thrown away on disconnect. So each reconnect fetched the entire unread backlog again and delivered all of it a second time: on the test mailbox, 166 messages meant 166 duplicate replies to the people who had written in. It got worse over time, because the backlog only ever grew. Messages are now flagged on the server once handled, in a single command per batch, so a restart picks up where it left off.
34
+
35
+ **Matrix — `disconnect()` could kill your process.** Shutting the client down cancels the requests it has open, and one of those cancellations surfaced as an unhandled rejection, which Node treats as fatal. An application that reconnects — the well-behaved kind, with retry on connection loss — could be terminated by its own clean shutdown. Measured against a real homeserver before the fix: 7 occurrences in 8 connect/disconnect cycles. Cancellations during shutdown are now contained, while any cancellation you request yourself through `getClient()` still reaches you unchanged.
36
+
3
37
  ## 0.1.1
4
38
 
5
39
  ### Patch Changes
package/LICENSE CHANGED
@@ -137,8 +137,8 @@
137
137
 
138
138
  6. Trademarks. This License does not grant permission to use the trade
139
139
  names, trademarks, service marks, or product names of the Licensor,
140
- except as required for describing the origin of the Work and
141
- reproducing the content of the NOTICE file.
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
142
 
143
143
  7. Disclaimer of Warranty. Unless required by applicable law or
144
144
  agreed to in writing, Licensor provides the Work (and each
package/README.md CHANGED
@@ -4,4 +4,3 @@ Email platform adapter for `@theokit/gateway`. Built on the community-standard 2
4
4
 
5
5
  Status: **v0.1.0 pre-release**. Pre-1.0 contract per ADR D338 — breaking changes allowed within 0.x.
6
6
 
7
- See `examples/email-bot/` for a full Gmail App Password walkthrough.
package/dist/index.cjs CHANGED
@@ -133,6 +133,10 @@ var ImapClient = class {
133
133
  }
134
134
  return out;
135
135
  }
136
+ async markSeen(uids) {
137
+ if (this.client === void 0 || uids.length === 0) return;
138
+ await this.client.messageFlagsAdd({ uid: uids.join(",") }, ["\\Seen"], { uid: true });
139
+ }
136
140
  async startIdle(onExists) {
137
141
  if (this.client === void 0) return;
138
142
  this.idleAbort = new AbortController();
@@ -341,6 +345,8 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
341
345
  platform = "email";
342
346
  options;
343
347
  seenUids = new SeenUidSet();
348
+ /** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
349
+ pendingSeen = /* @__PURE__ */ new Set();
344
350
  threadStore = new ThreadStore();
345
351
  imap;
346
352
  smtp;
@@ -470,7 +476,7 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
470
476
  onInbound(handler) {
471
477
  this.handler = handler;
472
478
  return () => {
473
- this.handler = void 0;
479
+ if (this.handler === handler) this.handler = void 0;
474
480
  };
475
481
  }
476
482
  /** @internal — drain UNSEEN once and dispatch each. */
@@ -486,6 +492,7 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
486
492
  for (const msg of messages) {
487
493
  this._dispatchInbound(msg.uid, msg.source, msg.headers);
488
494
  }
495
+ this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
489
496
  }
490
497
  /**
491
498
  * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
@@ -502,6 +509,30 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
502
509
  async _dispatchInboundInner(uid, rawBuffer, headers) {
503
510
  if (this.seenUids.has(uid)) return;
504
511
  this.seenUids.add(uid);
512
+ try {
513
+ await this._dispatchOrDrop(uid, rawBuffer, headers);
514
+ } finally {
515
+ this.pendingSeen.add(uid);
516
+ }
517
+ }
518
+ /**
519
+ * Flush the batch to the server. Never throws — a mailbox we cannot flag is
520
+ * not worth dropping mail over; those UIDs simply come back on the next drain.
521
+ */
522
+ async _flushSeen() {
523
+ if (this.imap === void 0 || this.pendingSeen.size === 0) return;
524
+ const uids = [...this.pendingSeen];
525
+ this.pendingSeen.clear();
526
+ try {
527
+ await this.imap.markSeen(uids);
528
+ } catch (err) {
529
+ console.error(
530
+ `[email] could not flag ${uids.length} message(s) \\Seen (they will be re-delivered):`,
531
+ err instanceof Error ? err.message : err
532
+ );
533
+ }
534
+ }
535
+ async _dispatchOrDrop(uid, rawBuffer, headers) {
505
536
  const event = await normalizeEmail(rawBuffer, {
506
537
  botAddress: this.options.address,
507
538
  ...this.options.maxBodyChars !== void 0 ? { maxBodyChars: this.options.maxBodyChars } : {}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/filters.ts","../src/imap-client.ts","../src/normalize.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts"],"names":["ImapFlow","simpleParser","createTransport","BasePlatformAdapter"],"mappings":";;;;;;;;;;AA8BA,IAAM,cAAA,GAAiB,gEAAA;AAGhB,SAAS,cAAc,GAAA,EAA4B;AACxD,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,EAAW;AACrC,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,OAAA,EAAS,eAAA,EAAgB;AAAA,EACrD;AACA,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,OAAA,EAAS,GAAA,EAAI;AAAA,EACzC;AACA,EAAA,MAAM,CAAA,GAAI,GAAA;AAOV,EAAA,MAAM,IAAA,GAAO,EAAE,IAAA,IAAQ,EAAA;AACvB,EAAA,MAAM,WAAW,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AY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AACF","file":"index.cjs","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder is exhaustive — each branch maps one nodemailer/imapflow/SMTP-response class to one typed canonical code; splitting hurts traceability.\nexport function mapEmailError(err: unknown): ErrorPayload {\n if (err === null || err === undefined) {\n return { code: \"unknown\", message: \"Unknown error\" };\n }\n if (typeof err === \"string\") {\n return { code: \"unknown\", message: err };\n }\n const e = err as {\n code?: string;\n responseCode?: number;\n response?: string;\n message?: string;\n name?: string;\n };\n const code = e.code ?? \"\";\n const respCode = typeof e.responseCode === \"number\" ? e.responseCode : undefined;\n const message = typeof e.message === \"string\" && e.message.length > 0 ? e.message : String(err);\n\n // nodemailer error codes\n if (code === \"EAUTH\" || code === \"EAUTHENTICATION\") {\n return { code: \"auth_failed\", message };\n }\n if (code === \"EENVELOPE\" && /550/.test(message)) {\n return { code: \"invalid_request\", message };\n }\n if (code === \"ECONNECTION\" || code === \"ESOCKET\" || code === \"ETLS\") {\n return { code: \"server_error\", message };\n }\n if (code === \"ETIMEDOUT\") {\n return { code: \"timeout\", message };\n }\n // SMTP response codes\n if (respCode !== undefined) {\n if (respCode === 535 || respCode === 530) return { code: \"auth_failed\", message };\n if (respCode === 421 || respCode === 451 || respCode === 452)\n return { code: \"rate_limit\", message };\n if (respCode === 550 || respCode === 551 || respCode === 553)\n return { code: \"invalid_request\", message };\n if (respCode >= 500) return { code: \"server_error\", message };\n if (respCode >= 400) return { code: \"rate_limit\", message };\n }\n // imapflow throws Error with .authenticationFailed flag in some versions\n if (e.name === \"IMAP_AUTH_FAILED\" || /auth/i.test(message)) {\n return { code: \"auth_failed\", message };\n }\n // EC-7: plain Error fallback\n if (NETWORK_ERR_RE.test(message)) return { code: \"server_error\", message };\n return { code: \"unknown\", message };\n}\n","/**\n * Inbound filters: automated-sender (D332) + allowed-sender allowlist (D333 + EC-3).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __filtersMarker: unique symbol = Symbol(\"email-filters\");\n\nconst NOREPLY_RE =\n /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;\n\n/**\n * EC-3: extract pure email address from a string that may include display\n * name + brackets (`\"Alice\" <alice@example.com>`). Normalizes to lowercase.\n */\nexport function extractAddr(s: string): string {\n const m = s.match(/<([^>]+)>/);\n return (m?.[1] ?? s).toLowerCase().trim();\n}\n\n/**\n * D332: automated-sender filter. Returns `true` if the message should be\n * DROPPED (sender is automated / bot-loop risk).\n */\nexport function isAutomatedSender(fromAddress: string, headers: Map<string, string>): boolean {\n if (NOREPLY_RE.test(fromAddress)) return true;\n // Normalize header keys to lowercase for lookup.\n const lowered = new Map<string, string>();\n for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);\n // RFC 3834: Auto-Submitted\n const autoSubmitted = lowered.get(\"auto-submitted\");\n if (typeof autoSubmitted === \"string\" && /auto-generated|auto-replied/i.test(autoSubmitted)) {\n return true;\n }\n // Legacy Precedence header\n const precedence = lowered.get(\"precedence\");\n if (typeof precedence === \"string\" && /bulk|list/i.test(precedence)) {\n return true;\n }\n // Microsoft X-Auto-Response-Suppress\n const xAuto = lowered.get(\"x-auto-response-suppress\");\n if (typeof xAuto === \"string\" && /all/i.test(xAuto)) {\n return true;\n }\n return false;\n}\n\n/**\n * D333 + EC-3: allowed-sender allowlist.\n *\n * - `undefined` allowlist → OPEN (all allowed).\n * - Empty array → CLOSED (none allowed). Intentional distinction from undefined.\n * - Both sides normalized via `extractAddr` so `\"Alice <alice@x>\"` matches `alice@x`.\n */\nexport function isAllowedSender(fromAddress: string, allowedSenders?: readonly string[]): boolean {\n if (allowedSenders === undefined) return true;\n const norm = extractAddr(fromAddress);\n return allowedSenders.some((s) => extractAddr(s) === norm);\n}\n","/**\n * IMAP client wrapper around `imapflow`. Supports IDLE + polling fallback.\n *\n * @internal\n */\n\nimport { type FetchMessageObject, ImapFlow } from \"imapflow\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __imapMarker: unique symbol = Symbol(\"imap\");\n\ninterface ImapClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface FetchedMessage {\n readonly uid: number;\n readonly source: Buffer;\n readonly headers: Map<string, string>;\n}\n\nexport interface IImapClient {\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n /** Capability check — does the server advertise IDLE? */\n supportsIdle(): boolean;\n /** Fetch all UNSEEN messages once. Used for poll + post-IDLE-event drain. */\n fetchUnseen(): Promise<FetchedMessage[]>;\n /** Start IDLE; invoke `onExists` whenever the server pushes a new-message notification. */\n startIdle(onExists: () => void): Promise<void>;\n /** Stop IDLE if running. */\n stopIdle(): Promise<void>;\n}\n\nexport class ImapClient implements IImapClient {\n private client: ImapFlow | undefined;\n private idleAbort: AbortController | undefined;\n\n constructor(private readonly config: ImapClientConfig) {}\n\n async connect(): Promise<void> {\n this.client = new ImapFlow({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n logger: false,\n });\n await this.client.connect();\n await this.client.mailboxOpen(\"INBOX\");\n }\n\n supportsIdle(): boolean {\n if (this.client === undefined) return false;\n const caps = (this.client as unknown as { capabilities?: { has?: (s: string) => boolean } })\n .capabilities;\n return caps?.has?.(\"IDLE\") ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.\n async fetchUnseen(): Promise<FetchedMessage[]> {\n if (this.client === undefined) return [];\n const out: FetchedMessage[] = [];\n for await (const raw of this.client.fetch({ seen: false }, {\n uid: true,\n source: true,\n headers: true,\n } as Parameters<ImapFlow[\"fetch\"]>[1])) {\n const msg = raw as FetchMessageObject;\n const headers = new Map<string, string>();\n // headers is a Buffer/Map in imapflow; handle both shapes safely.\n const h = (msg as unknown as { headers?: unknown }).headers;\n if (h instanceof Map) {\n for (const [k, v] of h as Map<string, string | string[]>) {\n headers.set(String(k), Array.isArray(v) ? (v[0] ?? \"\") : v);\n }\n } else if (h instanceof Buffer) {\n for (const line of h.toString(\"utf8\").split(/\\r?\\n/)) {\n const idx = line.indexOf(\":\");\n if (idx > 0)\n headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());\n }\n }\n if (msg.uid !== undefined && msg.source !== undefined) {\n out.push({\n uid: msg.uid,\n source: msg.source as Buffer,\n headers,\n });\n }\n }\n return out;\n }\n\n async startIdle(onExists: () => void): Promise<void> {\n if (this.client === undefined) return;\n this.idleAbort = new AbortController();\n const c = this.client;\n // imapflow's `c.idle()` resolves when IDLE ends. The `mailbox.on(\"exists\")`\n // event fires inside IDLE. We register the listener once and let imapflow\n // refresh IDLE internally per RFC 2177.\n c.on(\"exists\", () => {\n onExists();\n });\n void c.idle().catch(() => {\n /* idle aborted */\n });\n }\n\n async stopIdle(): Promise<void> {\n if (this.idleAbort !== undefined) {\n this.idleAbort.abort();\n this.idleAbort = undefined;\n }\n }\n\n async disconnect(): Promise<void> {\n await this.stopIdle();\n if (this.client !== undefined) {\n try {\n await this.client.logout();\n } catch {\n /* ignore */\n }\n this.client = undefined;\n }\n }\n}\n","/**\n * Inbound `raw RFC 5322 bytes` → `EmailMessageEvent`.\n *\n * EC-2 absorbed: body capped at `maxBodyChars` (default 50000).\n * EC-5 absorbed: subject fallback to `\"(no subject)\"`.\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\nimport { simpleParser } from \"mailparser\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __normalizeMarker: unique symbol = Symbol(\"email-normalize\");\n\nexport interface NormalizeOptions {\n readonly botAddress: string;\n /** EC-2: cap body length. Default 50000. */\n readonly maxBodyChars?: number;\n}\n\nconst DEFAULT_MAX_BODY = 50_000;\n\nfunction stripBraces(id: string | undefined): string | undefined {\n if (id === undefined || id.length === 0) return undefined;\n return id.replace(/^<|>$/g, \"\");\n}\n\nfunction normalizeRefs(refs: string | string[] | undefined): readonly string[] | undefined {\n if (refs === undefined) return undefined;\n const arr = Array.isArray(refs) ? refs : refs.split(/\\s+/).filter((s) => s.length > 0);\n const cleaned = arr.map((r) => stripBraces(r)).filter((r): r is string => r !== undefined);\n return cleaned.length > 0 ? cleaned : undefined;\n}\n\ninterface AddressEntry {\n readonly address?: string;\n readonly name?: string;\n}\n\ninterface AddressObject {\n readonly value?: ReadonlyArray<AddressEntry>;\n}\n\nfunction addressesFrom(\n obj: AddressObject | ReadonlyArray<AddressObject> | undefined,\n): AddressEntry[] {\n if (obj === undefined) return [];\n if (Array.isArray(obj)) {\n const out: AddressEntry[] = [];\n for (const o of obj) out.push(...(o.value ?? []));\n return out;\n }\n return Array.from((obj as AddressObject).value ?? []);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional RFC 5322 field; splitting hurts the \"one event normalization here\" locality.\nexport async function normalizeEmail(\n rawBuffer: Buffer | string,\n opts: NormalizeOptions,\n): Promise<EmailMessageEvent> {\n const parsed = await simpleParser(rawBuffer);\n\n const messageId = stripBraces(parsed.messageId) ?? \"unknown\";\n const inReplyTo = stripBraces(parsed.inReplyTo);\n const references = normalizeRefs(parsed.references as string | string[] | undefined);\n\n const fromEntries = addressesFrom(parsed.from as AddressObject | undefined);\n const fromAddress = (fromEntries[0]?.address ?? \"anonymous\").toLowerCase().trim();\n const fromName = fromEntries[0]?.name;\n\n const botAddrLc = opts.botAddress.toLowerCase().trim();\n const recipients: string[] = [];\n for (const entry of [\n ...addressesFrom(parsed.to as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ...addressesFrom(parsed.cc as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ]) {\n const addr = entry.address?.toLowerCase().trim();\n if (addr !== undefined && addr.length > 0 && addr !== botAddrLc) {\n recipients.push(addr);\n }\n }\n\n // EC-5: subject fallback.\n const subject = parsed.subject ?? \"(no subject)\";\n\n // EC-2: cap body.\n const rawText = parsed.text ?? \"\";\n const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;\n const text =\n rawText.length > maxChars\n ? `${rawText.slice(0, maxChars)}\\n\\n[truncated — full body in event.email.raw]`\n : rawText;\n\n const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();\n const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;\n\n const emailMeta: EmailMessageEvent[\"email\"] = {\n messageId,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n subject,\n fromAddress,\n ...(fromName !== undefined ? { fromName } : {}),\n recipients,\n attachmentCount,\n raw: parsed,\n };\n\n return {\n id: messageId,\n platform: \"email\",\n sender: {\n id: fromAddress,\n ...(fromName !== undefined ? { displayName: fromName } : {}),\n },\n channel: { id: fromAddress, type: \"dm\", topicId: messageId },\n text,\n receivedAt,\n email: emailMeta,\n };\n}\n","/**\n * Bounded `Set<number>` of dispatched IMAP UIDs (ADR D331).\n *\n * Caps at 5000 entries; trims to 4000 (drops oldest 1000) on overflow.\n * Same pattern as the Teams ConversationReferenceStore / WhatsApp Web bridge\n * — bounded memory in long-running bots.\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __seenUidsMarker: unique symbol = Symbol(\"seen-uids\");\n\nexport class SeenUidSet {\n private set = new Set<number>();\n static readonly MAX_SIZE = 5000;\n static readonly TRIM_TO = 4000;\n\n has(uid: number): boolean {\n return this.set.has(uid);\n }\n\n add(uid: number): void {\n if (this.set.size >= SeenUidSet.MAX_SIZE) this.trim();\n this.set.add(uid);\n }\n\n private trim(): void {\n // Set iteration is insertion-ordered in JS. Drop oldest until at TRIM_TO.\n const target = SeenUidSet.TRIM_TO;\n const toDrop = this.set.size - target;\n if (toDrop <= 0) return;\n let i = 0;\n for (const key of this.set) {\n if (i >= toDrop) break;\n this.set.delete(key);\n i++;\n }\n }\n\n get size(): number {\n return this.set.size;\n }\n\n clear(): void {\n this.set.clear();\n }\n}\n","/**\n * SMTP client wrapper around `nodemailer`. Thin shim; tests inject a fake.\n *\n * @internal\n */\n\nimport { createTransport, type SendMailOptions, type Transporter } from \"nodemailer\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __smtpMarker: unique symbol = Symbol(\"smtp\");\n\ninterface SmtpClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface SmtpSendOptions {\n readonly from: string | { name: string; address: string };\n readonly to: string;\n readonly subject: string;\n readonly text: string;\n /** Message-ID (without `<>`) we're replying to. */\n readonly inReplyTo?: string;\n /** References chain (without `<>`). Will be serialized with braces. */\n readonly references?: readonly string[];\n}\n\nexport interface ISmtpClient {\n verify(): Promise<true>;\n send(opts: SmtpSendOptions): Promise<string>;\n close(): Promise<void>;\n}\n\nexport class SmtpClient implements ISmtpClient {\n private transporter: Transporter | undefined;\n\n constructor(private readonly config: SmtpClientConfig) {}\n\n private getTransporter(): Transporter {\n if (this.transporter === undefined) {\n this.transporter = createTransport({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n });\n }\n return this.transporter;\n }\n\n async verify(): Promise<true> {\n return this.getTransporter().verify();\n }\n\n async send(opts: SmtpSendOptions): Promise<string> {\n const mail: SendMailOptions = {\n from: opts.from,\n to: opts.to,\n subject: opts.subject,\n text: opts.text,\n };\n if (opts.inReplyTo !== undefined) {\n mail.inReplyTo = `<${opts.inReplyTo}>`;\n }\n if (opts.references !== undefined && opts.references.length > 0) {\n mail.references = opts.references.map((r) => `<${r}>`);\n }\n const info = await this.getTransporter().sendMail(mail);\n // Strip `<>` from new Message-ID for consistency with inbound.\n const raw = (info.messageId ?? \"\").replace(/^<|>$/g, \"\");\n return raw;\n }\n\n async close(): Promise<void> {\n if (this.transporter !== undefined) {\n this.transporter.close();\n this.transporter = undefined;\n }\n }\n}\n","/**\n * Thread context store (ADR D337). Records `{subject, references, lastMessageId}`\n * per inbound `Message-ID`; consumed on outbound to reconstruct threading headers.\n *\n * Capped at 1000 entries with FIFO eviction (matches WhatsApp / Teams pattern).\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __threadStoreMarker: unique symbol = Symbol(\"thread-store\");\n\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\nexport class ThreadStore {\n private readonly map = new Map<string, ThreadContext>();\n static readonly MAX_SIZE = 1000;\n\n recordFromInbound(event: EmailMessageEvent): void {\n const ctx: ThreadContext = {\n subject: event.email.subject,\n references: event.email.references ?? [],\n lastMessageId: event.email.messageId,\n };\n // FIFO eviction.\n if (this.map.size >= ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n this.map.delete(event.email.messageId);\n this.map.set(event.email.messageId, ctx);\n }\n\n lookup(topicId: string): ThreadContext | undefined {\n return this.map.get(topicId);\n }\n\n get size(): number {\n return this.map.size;\n }\n\n clear(): void {\n this.map.clear();\n }\n}\n","/**\n * `EmailAdapter` — Email platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #4; ADRs D327-D339).\n *\n * Stack: nodemailer (SMTP) + imapflow (IMAP IDLE) + mailparser (RFC 5322).\n * Inbound: IMAP IDLE preferred (D328), 15s poll fallback.\n * Outbound: SMTP via nodemailer + threading reciprocity (D337).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { mapEmailError } from \"./errors.js\";\nimport { isAllowedSender, isAutomatedSender } from \"./filters.js\";\nimport { type FetchedMessage, type IImapClient, ImapClient } from \"./imap-client.js\";\nimport { normalizeEmail } from \"./normalize.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\nexport class EmailAdapter extends BasePlatformAdapter {\n readonly platform = \"email\" as const;\n private readonly options: EmailAdapterOptions;\n private readonly seenUids = new SeenUidSet();\n private readonly threadStore = new ThreadStore();\n private imap: IImapClient | undefined;\n private smtp: ISmtpClient | undefined;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n // EC-4: serialize concurrent _dispatchInbound calls.\n private dispatchQueue: Promise<void> = Promise.resolve();\n private pollTimer: NodeJS.Timeout | undefined;\n\n constructor(opts: EmailAdapterOptions) {\n super();\n // EC-1 pattern (from Teams): validate non-empty at construction (fail fast).\n for (const k of [\"address\", \"password\", \"imapHost\", \"smtpHost\"] as const) {\n const v = opts[k];\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);\n }\n }\n this.options = opts;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n // Construct clients (test seams allow injection).\n const imapFactory = this.options.__imapFactory as ((cfg: unknown) => IImapClient) | undefined;\n const smtpFactory = this.options.__smtpFactory as ((cfg: unknown) => ISmtpClient) | undefined;\n this.imap =\n imapFactory !== undefined\n ? imapFactory({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new ImapClient({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n });\n this.smtp =\n smtpFactory !== undefined\n ? smtpFactory({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new SmtpClient({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n });\n await this.smtp.verify();\n await this.imap.connect();\n\n // Start inbound dispatch loop — IDLE if supported, poll otherwise.\n if (this.imap.supportsIdle()) {\n await this.imap.startIdle(() => {\n void this._drainUnseen();\n });\n // Drain anything already UNSEEN before IDLE started.\n await this._drainUnseen();\n } else {\n // Polling fallback.\n await this._drainUnseen();\n const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.pollTimer = setInterval(() => {\n void this._drainUnseen();\n }, intervalMs);\n }\n\n this.connected = true;\n return true;\n } catch (err) {\n console.error(\"[email] connect failed:\", err instanceof Error ? err.message : err);\n await this.disconnect().catch(() => {});\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pollTimer !== undefined) {\n clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n }\n if (this.imap !== undefined) {\n await this.imap.disconnect().catch(() => {});\n this.imap = undefined;\n }\n if (this.smtp !== undefined) {\n await this.smtp.close().catch(() => {});\n this.smtp = undefined;\n }\n this.connected = false;\n this.handler = undefined;\n this.seenUids.clear();\n this.threadStore.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const messageId = await this.smtp.send({\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n });\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n return () => {\n this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/filters.ts","../src/imap-client.ts","../src/normalize.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts"],"names":["ImapFlow","simpleParser","createTransport","BasePlatformAdapter"],"mappings":";;;;;;;;;;AA8BA,IAAM,cAAA,GAAiB,gEAAA;AAGhB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AAa,IAAA,CAAK,OAAA,CAAQ,cAAc,CAAA,EAAG;AAC1E,MAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,iCAAA,EAAoC,KAAA,CAAM,KAAA,CAAM,WAAW,CAAA,CAAE,CAAA;AAC1E,MAAA;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,WAAA,CAAY,kBAAkB,KAAK,CAAA;AAExC,IAAA,IAAI,KAAK,OAAA,KAAY,MAAA,EAAW,MAAM,IAAA,CAAK,QAAQ,KAAK,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,IAAI,aAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA,EACA,IAAI,gBAAA,GAA2B;AAC7B,IAAA,OAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AACF","file":"index.cjs","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder is exhaustive — each branch maps one nodemailer/imapflow/SMTP-response class to one typed canonical code; splitting hurts traceability.\nexport function mapEmailError(err: unknown): ErrorPayload {\n if (err === null || err === undefined) {\n return { code: \"unknown\", message: \"Unknown error\" };\n }\n if (typeof err === \"string\") {\n return { code: \"unknown\", message: err };\n }\n const e = err as {\n code?: string;\n responseCode?: number;\n response?: string;\n message?: string;\n name?: string;\n };\n const code = e.code ?? \"\";\n const respCode = typeof e.responseCode === \"number\" ? e.responseCode : undefined;\n const message = typeof e.message === \"string\" && e.message.length > 0 ? e.message : String(err);\n\n // nodemailer error codes\n if (code === \"EAUTH\" || code === \"EAUTHENTICATION\") {\n return { code: \"auth_failed\", message };\n }\n if (code === \"EENVELOPE\" && /550/.test(message)) {\n return { code: \"invalid_request\", message };\n }\n if (code === \"ECONNECTION\" || code === \"ESOCKET\" || code === \"ETLS\") {\n return { code: \"server_error\", message };\n }\n if (code === \"ETIMEDOUT\") {\n return { code: \"timeout\", message };\n }\n // SMTP response codes\n if (respCode !== undefined) {\n if (respCode === 535 || respCode === 530) return { code: \"auth_failed\", message };\n if (respCode === 421 || respCode === 451 || respCode === 452)\n return { code: \"rate_limit\", message };\n if (respCode === 550 || respCode === 551 || respCode === 553)\n return { code: \"invalid_request\", message };\n if (respCode >= 500) return { code: \"server_error\", message };\n if (respCode >= 400) return { code: \"rate_limit\", message };\n }\n // imapflow throws Error with .authenticationFailed flag in some versions\n if (e.name === \"IMAP_AUTH_FAILED\" || /auth/i.test(message)) {\n return { code: \"auth_failed\", message };\n }\n // EC-7: plain Error fallback\n if (NETWORK_ERR_RE.test(message)) return { code: \"server_error\", message };\n return { code: \"unknown\", message };\n}\n","/**\n * Inbound filters: automated-sender (D332) + allowed-sender allowlist (D333 + EC-3).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __filtersMarker: unique symbol = Symbol(\"email-filters\");\n\nconst NOREPLY_RE =\n /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;\n\n/**\n * EC-3: extract pure email address from a string that may include display\n * name + brackets (`\"Alice\" <alice@example.com>`). Normalizes to lowercase.\n */\nexport function extractAddr(s: string): string {\n const m = s.match(/<([^>]+)>/);\n return (m?.[1] ?? s).toLowerCase().trim();\n}\n\n/**\n * D332: automated-sender filter. Returns `true` if the message should be\n * DROPPED (sender is automated / bot-loop risk).\n */\nexport function isAutomatedSender(fromAddress: string, headers: Map<string, string>): boolean {\n if (NOREPLY_RE.test(fromAddress)) return true;\n // Normalize header keys to lowercase for lookup.\n const lowered = new Map<string, string>();\n for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);\n // RFC 3834: Auto-Submitted\n const autoSubmitted = lowered.get(\"auto-submitted\");\n if (typeof autoSubmitted === \"string\" && /auto-generated|auto-replied/i.test(autoSubmitted)) {\n return true;\n }\n // Legacy Precedence header\n const precedence = lowered.get(\"precedence\");\n if (typeof precedence === \"string\" && /bulk|list/i.test(precedence)) {\n return true;\n }\n // Microsoft X-Auto-Response-Suppress\n const xAuto = lowered.get(\"x-auto-response-suppress\");\n if (typeof xAuto === \"string\" && /all/i.test(xAuto)) {\n return true;\n }\n return false;\n}\n\n/**\n * D333 + EC-3: allowed-sender allowlist.\n *\n * - `undefined` allowlist → OPEN (all allowed).\n * - Empty array → CLOSED (none allowed). Intentional distinction from undefined.\n * - Both sides normalized via `extractAddr` so `\"Alice <alice@x>\"` matches `alice@x`.\n */\nexport function isAllowedSender(fromAddress: string, allowedSenders?: readonly string[]): boolean {\n if (allowedSenders === undefined) return true;\n const norm = extractAddr(fromAddress);\n return allowedSenders.some((s) => extractAddr(s) === norm);\n}\n","/**\n * IMAP client wrapper around `imapflow`. Supports IDLE + polling fallback.\n *\n * @internal\n */\n\nimport { type FetchMessageObject, ImapFlow } from \"imapflow\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __imapMarker: unique symbol = Symbol(\"imap\");\n\ninterface ImapClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface FetchedMessage {\n readonly uid: number;\n readonly source: Buffer;\n readonly headers: Map<string, string>;\n}\n\nexport interface IImapClient {\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n /** Capability check — does the server advertise IDLE? */\n supportsIdle(): boolean;\n /** Fetch all UNSEEN messages once. Used for poll + post-IDLE-event drain. */\n fetchUnseen(): Promise<FetchedMessage[]>;\n /**\n * Set `\\Seen` on the server for a whole batch, so `fetchUnseen()` stops\n * returning them.\n *\n * The server flag is the only delivery state that survives a restart, which\n * is what issue #11 turned on: the in-memory UID set is cleared by\n * `disconnect()`, so without this a reconnect re-delivers the whole unread\n * backlog to the handler.\n *\n * Batched, not per-message, and the reason is measured rather than stylistic.\n * The first version flagged each message individually from inside the\n * serialized dispatch queue; against a 166-message backlog on a real mailbox\n * that put 166 sequential round trips ahead of every newly-arrived message,\n * and an inbound probe waited past 120s to be delivered. One command per\n * drain removes that queue entirely.\n */\n markSeen(uids: readonly number[]): Promise<void>;\n /** Start IDLE; invoke `onExists` whenever the server pushes a new-message notification. */\n startIdle(onExists: () => void): Promise<void>;\n /** Stop IDLE if running. */\n stopIdle(): Promise<void>;\n}\n\nexport class ImapClient implements IImapClient {\n private client: ImapFlow | undefined;\n private idleAbort: AbortController | undefined;\n\n constructor(private readonly config: ImapClientConfig) {}\n\n async connect(): Promise<void> {\n this.client = new ImapFlow({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n logger: false,\n });\n await this.client.connect();\n await this.client.mailboxOpen(\"INBOX\");\n }\n\n supportsIdle(): boolean {\n if (this.client === undefined) return false;\n const caps = (this.client as unknown as { capabilities?: { has?: (s: string) => boolean } })\n .capabilities;\n return caps?.has?.(\"IDLE\") ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.\n async fetchUnseen(): Promise<FetchedMessage[]> {\n if (this.client === undefined) return [];\n const out: FetchedMessage[] = [];\n for await (const raw of this.client.fetch({ seen: false }, {\n uid: true,\n source: true,\n headers: true,\n } as Parameters<ImapFlow[\"fetch\"]>[1])) {\n const msg = raw as FetchMessageObject;\n const headers = new Map<string, string>();\n // headers is a Buffer/Map in imapflow; handle both shapes safely.\n const h = (msg as unknown as { headers?: unknown }).headers;\n if (h instanceof Map) {\n for (const [k, v] of h as Map<string, string | string[]>) {\n headers.set(String(k), Array.isArray(v) ? (v[0] ?? \"\") : v);\n }\n } else if (h instanceof Buffer) {\n for (const line of h.toString(\"utf8\").split(/\\r?\\n/)) {\n const idx = line.indexOf(\":\");\n if (idx > 0)\n headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());\n }\n }\n if (msg.uid !== undefined && msg.source !== undefined) {\n out.push({\n uid: msg.uid,\n source: msg.source as Buffer,\n headers,\n });\n }\n }\n return out;\n }\n\n async markSeen(uids: readonly number[]): Promise<void> {\n if (this.client === undefined || uids.length === 0) return;\n // `uid: true` is load-bearing — without it imapflow reads these numbers as\n // sequence numbers, which are positional and shift as the mailbox changes,\n // so the flags would land on whatever messages happen to sit at those slots.\n await this.client.messageFlagsAdd({ uid: uids.join(\",\") }, [\"\\\\Seen\"], { uid: true });\n }\n\n async startIdle(onExists: () => void): Promise<void> {\n if (this.client === undefined) return;\n this.idleAbort = new AbortController();\n const c = this.client;\n // imapflow's `c.idle()` resolves when IDLE ends. The `mailbox.on(\"exists\")`\n // event fires inside IDLE. We register the listener once and let imapflow\n // refresh IDLE internally per RFC 2177.\n c.on(\"exists\", () => {\n onExists();\n });\n void c.idle().catch(() => {\n /* idle aborted */\n });\n }\n\n async stopIdle(): Promise<void> {\n if (this.idleAbort !== undefined) {\n this.idleAbort.abort();\n this.idleAbort = undefined;\n }\n }\n\n async disconnect(): Promise<void> {\n await this.stopIdle();\n if (this.client !== undefined) {\n try {\n await this.client.logout();\n } catch {\n /* ignore */\n }\n this.client = undefined;\n }\n }\n}\n","/**\n * Inbound `raw RFC 5322 bytes` → `EmailMessageEvent`.\n *\n * EC-2 absorbed: body capped at `maxBodyChars` (default 50000).\n * EC-5 absorbed: subject fallback to `\"(no subject)\"`.\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\nimport { simpleParser } from \"mailparser\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __normalizeMarker: unique symbol = Symbol(\"email-normalize\");\n\nexport interface NormalizeOptions {\n readonly botAddress: string;\n /** EC-2: cap body length. Default 50000. */\n readonly maxBodyChars?: number;\n}\n\nconst DEFAULT_MAX_BODY = 50_000;\n\nfunction stripBraces(id: string | undefined): string | undefined {\n if (id === undefined || id.length === 0) return undefined;\n return id.replace(/^<|>$/g, \"\");\n}\n\nfunction normalizeRefs(refs: string | string[] | undefined): readonly string[] | undefined {\n if (refs === undefined) return undefined;\n const arr = Array.isArray(refs) ? refs : refs.split(/\\s+/).filter((s) => s.length > 0);\n const cleaned = arr.map((r) => stripBraces(r)).filter((r): r is string => r !== undefined);\n return cleaned.length > 0 ? cleaned : undefined;\n}\n\ninterface AddressEntry {\n readonly address?: string;\n readonly name?: string;\n}\n\ninterface AddressObject {\n readonly value?: ReadonlyArray<AddressEntry>;\n}\n\nfunction addressesFrom(\n obj: AddressObject | ReadonlyArray<AddressObject> | undefined,\n): AddressEntry[] {\n if (obj === undefined) return [];\n if (Array.isArray(obj)) {\n const out: AddressEntry[] = [];\n for (const o of obj) out.push(...(o.value ?? []));\n return out;\n }\n return Array.from((obj as AddressObject).value ?? []);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional RFC 5322 field; splitting hurts the \"one event normalization here\" locality.\nexport async function normalizeEmail(\n rawBuffer: Buffer | string,\n opts: NormalizeOptions,\n): Promise<EmailMessageEvent> {\n const parsed = await simpleParser(rawBuffer);\n\n const messageId = stripBraces(parsed.messageId) ?? \"unknown\";\n const inReplyTo = stripBraces(parsed.inReplyTo);\n const references = normalizeRefs(parsed.references as string | string[] | undefined);\n\n const fromEntries = addressesFrom(parsed.from as AddressObject | undefined);\n const fromAddress = (fromEntries[0]?.address ?? \"anonymous\").toLowerCase().trim();\n const fromName = fromEntries[0]?.name;\n\n const botAddrLc = opts.botAddress.toLowerCase().trim();\n const recipients: string[] = [];\n for (const entry of [\n ...addressesFrom(parsed.to as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ...addressesFrom(parsed.cc as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ]) {\n const addr = entry.address?.toLowerCase().trim();\n if (addr !== undefined && addr.length > 0 && addr !== botAddrLc) {\n recipients.push(addr);\n }\n }\n\n // EC-5: subject fallback.\n const subject = parsed.subject ?? \"(no subject)\";\n\n // EC-2: cap body.\n const rawText = parsed.text ?? \"\";\n const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;\n const text =\n rawText.length > maxChars\n ? `${rawText.slice(0, maxChars)}\\n\\n[truncated — full body in event.email.raw]`\n : rawText;\n\n const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();\n const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;\n\n const emailMeta: EmailMessageEvent[\"email\"] = {\n messageId,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n subject,\n fromAddress,\n ...(fromName !== undefined ? { fromName } : {}),\n recipients,\n attachmentCount,\n raw: parsed,\n };\n\n return {\n id: messageId,\n platform: \"email\",\n sender: {\n id: fromAddress,\n ...(fromName !== undefined ? { displayName: fromName } : {}),\n },\n channel: { id: fromAddress, type: \"dm\", topicId: messageId },\n text,\n receivedAt,\n email: emailMeta,\n };\n}\n","/**\n * Bounded `Set<number>` of dispatched IMAP UIDs (ADR D331).\n *\n * Caps at 5000 entries; trims to 4000 (drops oldest 1000) on overflow.\n * Same pattern as the Teams ConversationReferenceStore / WhatsApp Web bridge\n * — bounded memory in long-running bots.\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __seenUidsMarker: unique symbol = Symbol(\"seen-uids\");\n\nexport class SeenUidSet {\n private set = new Set<number>();\n static readonly MAX_SIZE = 5000;\n static readonly TRIM_TO = 4000;\n\n has(uid: number): boolean {\n return this.set.has(uid);\n }\n\n add(uid: number): void {\n if (this.set.size >= SeenUidSet.MAX_SIZE) this.trim();\n this.set.add(uid);\n }\n\n private trim(): void {\n // Set iteration is insertion-ordered in JS. Drop oldest until at TRIM_TO.\n const target = SeenUidSet.TRIM_TO;\n const toDrop = this.set.size - target;\n if (toDrop <= 0) return;\n let i = 0;\n for (const key of this.set) {\n if (i >= toDrop) break;\n this.set.delete(key);\n i++;\n }\n }\n\n get size(): number {\n return this.set.size;\n }\n\n clear(): void {\n this.set.clear();\n }\n}\n","/**\n * SMTP client wrapper around `nodemailer`. Thin shim; tests inject a fake.\n *\n * @internal\n */\n\nimport { createTransport, type SendMailOptions, type Transporter } from \"nodemailer\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __smtpMarker: unique symbol = Symbol(\"smtp\");\n\ninterface SmtpClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface SmtpSendOptions {\n readonly from: string | { name: string; address: string };\n readonly to: string;\n readonly subject: string;\n readonly text: string;\n /** Message-ID (without `<>`) we're replying to. */\n readonly inReplyTo?: string;\n /** References chain (without `<>`). Will be serialized with braces. */\n readonly references?: readonly string[];\n}\n\nexport interface ISmtpClient {\n verify(): Promise<true>;\n send(opts: SmtpSendOptions): Promise<string>;\n close(): Promise<void>;\n}\n\nexport class SmtpClient implements ISmtpClient {\n private transporter: Transporter | undefined;\n\n constructor(private readonly config: SmtpClientConfig) {}\n\n private getTransporter(): Transporter {\n if (this.transporter === undefined) {\n this.transporter = createTransport({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n });\n }\n return this.transporter;\n }\n\n async verify(): Promise<true> {\n return this.getTransporter().verify();\n }\n\n async send(opts: SmtpSendOptions): Promise<string> {\n const mail: SendMailOptions = {\n from: opts.from,\n to: opts.to,\n subject: opts.subject,\n text: opts.text,\n };\n if (opts.inReplyTo !== undefined) {\n mail.inReplyTo = `<${opts.inReplyTo}>`;\n }\n if (opts.references !== undefined && opts.references.length > 0) {\n mail.references = opts.references.map((r) => `<${r}>`);\n }\n const info = await this.getTransporter().sendMail(mail);\n // Strip `<>` from new Message-ID for consistency with inbound.\n const raw = (info.messageId ?? \"\").replace(/^<|>$/g, \"\");\n return raw;\n }\n\n async close(): Promise<void> {\n if (this.transporter !== undefined) {\n this.transporter.close();\n this.transporter = undefined;\n }\n }\n}\n","/**\n * Thread context store (ADR D337). Records `{subject, references, lastMessageId}`\n * per inbound `Message-ID`; consumed on outbound to reconstruct threading headers.\n *\n * Capped at 1000 entries with FIFO eviction (matches WhatsApp / Teams pattern).\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __threadStoreMarker: unique symbol = Symbol(\"thread-store\");\n\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\nexport class ThreadStore {\n private readonly map = new Map<string, ThreadContext>();\n static readonly MAX_SIZE = 1000;\n\n recordFromInbound(event: EmailMessageEvent): void {\n const ctx: ThreadContext = {\n subject: event.email.subject,\n references: event.email.references ?? [],\n lastMessageId: event.email.messageId,\n };\n // FIFO eviction.\n if (this.map.size >= ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n this.map.delete(event.email.messageId);\n this.map.set(event.email.messageId, ctx);\n }\n\n lookup(topicId: string): ThreadContext | undefined {\n return this.map.get(topicId);\n }\n\n get size(): number {\n return this.map.size;\n }\n\n clear(): void {\n this.map.clear();\n }\n}\n","/**\n * `EmailAdapter` — Email platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #4; ADRs D327-D339).\n *\n * Stack: nodemailer (SMTP) + imapflow (IMAP IDLE) + mailparser (RFC 5322).\n * Inbound: IMAP IDLE preferred (D328), 15s poll fallback.\n * Outbound: SMTP via nodemailer + threading reciprocity (D337).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { mapEmailError } from \"./errors.js\";\nimport { isAllowedSender, isAutomatedSender } from \"./filters.js\";\nimport { type FetchedMessage, type IImapClient, ImapClient } from \"./imap-client.js\";\nimport { normalizeEmail } from \"./normalize.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\nexport class EmailAdapter extends BasePlatformAdapter {\n readonly platform = \"email\" as const;\n private readonly options: EmailAdapterOptions;\n private readonly seenUids = new SeenUidSet();\n /** UIDs finished with in this batch, awaiting one `\\Seen` command (#11). */\n private readonly pendingSeen = new Set<number>();\n private readonly threadStore = new ThreadStore();\n private imap: IImapClient | undefined;\n private smtp: ISmtpClient | undefined;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n // EC-4: serialize concurrent _dispatchInbound calls.\n private dispatchQueue: Promise<void> = Promise.resolve();\n private pollTimer: NodeJS.Timeout | undefined;\n\n constructor(opts: EmailAdapterOptions) {\n super();\n // EC-1 pattern (from Teams): validate non-empty at construction (fail fast).\n for (const k of [\"address\", \"password\", \"imapHost\", \"smtpHost\"] as const) {\n const v = opts[k];\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);\n }\n }\n this.options = opts;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n // Construct clients (test seams allow injection).\n const imapFactory = this.options.__imapFactory as ((cfg: unknown) => IImapClient) | undefined;\n const smtpFactory = this.options.__smtpFactory as ((cfg: unknown) => ISmtpClient) | undefined;\n this.imap =\n imapFactory !== undefined\n ? imapFactory({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new ImapClient({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n });\n this.smtp =\n smtpFactory !== undefined\n ? smtpFactory({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new SmtpClient({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n });\n await this.smtp.verify();\n await this.imap.connect();\n\n // Start inbound dispatch loop — IDLE if supported, poll otherwise.\n if (this.imap.supportsIdle()) {\n await this.imap.startIdle(() => {\n void this._drainUnseen();\n });\n // Drain anything already UNSEEN before IDLE started.\n await this._drainUnseen();\n } else {\n // Polling fallback.\n await this._drainUnseen();\n const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.pollTimer = setInterval(() => {\n void this._drainUnseen();\n }, intervalMs);\n }\n\n this.connected = true;\n return true;\n } catch (err) {\n console.error(\"[email] connect failed:\", err instanceof Error ? err.message : err);\n await this.disconnect().catch(() => {});\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pollTimer !== undefined) {\n clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n }\n if (this.imap !== undefined) {\n await this.imap.disconnect().catch(() => {});\n this.imap = undefined;\n }\n if (this.smtp !== undefined) {\n await this.smtp.close().catch(() => {});\n this.smtp = undefined;\n }\n this.connected = false;\n this.handler = undefined;\n this.seenUids.clear();\n this.threadStore.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const messageId = await this.smtp.send({\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n });\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n // The guard is not decoration. Without it, onInbound(A) -> onInbound(B) ->\n // A's stale unsubscribe clears B, and inbound delivery stops permanently\n // with nothing logged. Email and Teams were the only two adapters of ten\n // missing it, and no test anywhere exercised the A->B->unsubA sequence.\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n // Chain the flush behind this batch's dispatches rather than awaiting them\n // here: `connect()` calls this, and blocking it on a large backlog is the\n // slow-connect problem, not something to make worse.\n this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n try {\n await this._dispatchOrDrop(uid, rawBuffer, headers);\n } finally {\n // Every exit records, including the drops. A discarded message is finished\n // with, and leaving it UNSEEN means downloading and re-parsing it on\n // every drain forever — most of the 166-message backlog measured on the\n // live mailbox was old own-address probes being re-read and re-thrown-away.\n //\n // Recorded AFTER the attempt, not before: a crash in the window between\n // the two costs at most a duplicate of the single in-flight message,\n // where flagging first would lose it silently. Duplicates are visible and\n // apologisable; a support email nobody ever answers is neither.\n this.pendingSeen.add(uid);\n }\n }\n\n /**\n * Flush the batch to the server. Never throws — a mailbox we cannot flag is\n * not worth dropping mail over; those UIDs simply come back on the next drain.\n */\n private async _flushSeen(): Promise<void> {\n if (this.imap === undefined || this.pendingSeen.size === 0) return;\n const uids = [...this.pendingSeen];\n this.pendingSeen.clear();\n try {\n await this.imap.markSeen(uids);\n } catch (err) {\n console.error(\n `[email] could not flag ${uids.length} message(s) \\\\Seen (they will be re-delivered):`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n private async _dispatchOrDrop(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -42,6 +42,8 @@ declare class EmailAdapter extends BasePlatformAdapter {
42
42
  readonly platform: "email";
43
43
  private readonly options;
44
44
  private readonly seenUids;
45
+ /** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
46
+ private readonly pendingSeen;
45
47
  private readonly threadStore;
46
48
  private imap;
47
49
  private smtp;
@@ -60,6 +62,12 @@ declare class EmailAdapter extends BasePlatformAdapter {
60
62
  */
61
63
  private _dispatchInbound;
62
64
  private _dispatchInboundInner;
65
+ /**
66
+ * Flush the batch to the server. Never throws — a mailbox we cannot flag is
67
+ * not worth dropping mail over; those UIDs simply come back on the next drain.
68
+ */
69
+ private _flushSeen;
70
+ private _dispatchOrDrop;
63
71
  get _threadStoreSize(): number;
64
72
  }
65
73
 
package/dist/index.d.ts CHANGED
@@ -42,6 +42,8 @@ declare class EmailAdapter extends BasePlatformAdapter {
42
42
  readonly platform: "email";
43
43
  private readonly options;
44
44
  private readonly seenUids;
45
+ /** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
46
+ private readonly pendingSeen;
45
47
  private readonly threadStore;
46
48
  private imap;
47
49
  private smtp;
@@ -60,6 +62,12 @@ declare class EmailAdapter extends BasePlatformAdapter {
60
62
  */
61
63
  private _dispatchInbound;
62
64
  private _dispatchInboundInner;
65
+ /**
66
+ * Flush the batch to the server. Never throws — a mailbox we cannot flag is
67
+ * not worth dropping mail over; those UIDs simply come back on the next drain.
68
+ */
69
+ private _flushSeen;
70
+ private _dispatchOrDrop;
63
71
  get _threadStoreSize(): number;
64
72
  }
65
73
 
package/dist/index.js CHANGED
@@ -131,6 +131,10 @@ var ImapClient = class {
131
131
  }
132
132
  return out;
133
133
  }
134
+ async markSeen(uids) {
135
+ if (this.client === void 0 || uids.length === 0) return;
136
+ await this.client.messageFlagsAdd({ uid: uids.join(",") }, ["\\Seen"], { uid: true });
137
+ }
134
138
  async startIdle(onExists) {
135
139
  if (this.client === void 0) return;
136
140
  this.idleAbort = new AbortController();
@@ -339,6 +343,8 @@ var EmailAdapter = class extends BasePlatformAdapter {
339
343
  platform = "email";
340
344
  options;
341
345
  seenUids = new SeenUidSet();
346
+ /** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
347
+ pendingSeen = /* @__PURE__ */ new Set();
342
348
  threadStore = new ThreadStore();
343
349
  imap;
344
350
  smtp;
@@ -468,7 +474,7 @@ var EmailAdapter = class extends BasePlatformAdapter {
468
474
  onInbound(handler) {
469
475
  this.handler = handler;
470
476
  return () => {
471
- this.handler = void 0;
477
+ if (this.handler === handler) this.handler = void 0;
472
478
  };
473
479
  }
474
480
  /** @internal — drain UNSEEN once and dispatch each. */
@@ -484,6 +490,7 @@ var EmailAdapter = class extends BasePlatformAdapter {
484
490
  for (const msg of messages) {
485
491
  this._dispatchInbound(msg.uid, msg.source, msg.headers);
486
492
  }
493
+ this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
487
494
  }
488
495
  /**
489
496
  * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
@@ -500,6 +507,30 @@ var EmailAdapter = class extends BasePlatformAdapter {
500
507
  async _dispatchInboundInner(uid, rawBuffer, headers) {
501
508
  if (this.seenUids.has(uid)) return;
502
509
  this.seenUids.add(uid);
510
+ try {
511
+ await this._dispatchOrDrop(uid, rawBuffer, headers);
512
+ } finally {
513
+ this.pendingSeen.add(uid);
514
+ }
515
+ }
516
+ /**
517
+ * Flush the batch to the server. Never throws — a mailbox we cannot flag is
518
+ * not worth dropping mail over; those UIDs simply come back on the next drain.
519
+ */
520
+ async _flushSeen() {
521
+ if (this.imap === void 0 || this.pendingSeen.size === 0) return;
522
+ const uids = [...this.pendingSeen];
523
+ this.pendingSeen.clear();
524
+ try {
525
+ await this.imap.markSeen(uids);
526
+ } catch (err) {
527
+ console.error(
528
+ `[email] could not flag ${uids.length} message(s) \\Seen (they will be re-delivered):`,
529
+ err instanceof Error ? err.message : err
530
+ );
531
+ }
532
+ }
533
+ async _dispatchOrDrop(uid, rawBuffer, headers) {
503
534
  const event = await normalizeEmail(rawBuffer, {
504
535
  botAddress: this.options.address,
505
536
  ...this.options.maxBodyChars !== void 0 ? { maxBodyChars: this.options.maxBodyChars } : {}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/filters.ts","../src/imap-client.ts","../src/normalize.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;;;AA8BA,IAAM,cAAA,GAAiB,gEAAA;AAGhB,SAAS,cAAc,GAAA,EAA4B;AACxD,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,EAAW;AACrC,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,OAAA,EAAS,eAAA,EAAgB;AAAA,EACrD;AACA,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3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Q,KAAK,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,IAAI,aAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA,EACA,IAAI,gBAAA,GAA2B;AAC7B,IAAA,OAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AACF","file":"index.js","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder is exhaustive — each branch maps one nodemailer/imapflow/SMTP-response class to one typed canonical code; splitting hurts traceability.\nexport function mapEmailError(err: unknown): ErrorPayload {\n if (err === null || err === undefined) {\n return { code: \"unknown\", message: \"Unknown error\" };\n }\n if (typeof err === \"string\") {\n return { code: \"unknown\", message: err };\n }\n const e = err as {\n code?: string;\n responseCode?: number;\n response?: string;\n message?: string;\n name?: string;\n };\n const code = e.code ?? \"\";\n const respCode = typeof e.responseCode === \"number\" ? e.responseCode : undefined;\n const message = typeof e.message === \"string\" && e.message.length > 0 ? e.message : String(err);\n\n // nodemailer error codes\n if (code === \"EAUTH\" || code === \"EAUTHENTICATION\") {\n return { code: \"auth_failed\", message };\n }\n if (code === \"EENVELOPE\" && /550/.test(message)) {\n return { code: \"invalid_request\", message };\n }\n if (code === \"ECONNECTION\" || code === \"ESOCKET\" || code === \"ETLS\") {\n return { code: \"server_error\", message };\n }\n if (code === \"ETIMEDOUT\") {\n return { code: \"timeout\", message };\n }\n // SMTP response codes\n if (respCode !== undefined) {\n if (respCode === 535 || respCode === 530) return { code: \"auth_failed\", message };\n if (respCode === 421 || respCode === 451 || respCode === 452)\n return { code: \"rate_limit\", message };\n if (respCode === 550 || respCode === 551 || respCode === 553)\n return { code: \"invalid_request\", message };\n if (respCode >= 500) return { code: \"server_error\", message };\n if (respCode >= 400) return { code: \"rate_limit\", message };\n }\n // imapflow throws Error with .authenticationFailed flag in some versions\n if (e.name === \"IMAP_AUTH_FAILED\" || /auth/i.test(message)) {\n return { code: \"auth_failed\", message };\n }\n // EC-7: plain Error fallback\n if (NETWORK_ERR_RE.test(message)) return { code: \"server_error\", message };\n return { code: \"unknown\", message };\n}\n","/**\n * Inbound filters: automated-sender (D332) + allowed-sender allowlist (D333 + EC-3).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __filtersMarker: unique symbol = Symbol(\"email-filters\");\n\nconst NOREPLY_RE =\n /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;\n\n/**\n * EC-3: extract pure email address from a string that may include display\n * name + brackets (`\"Alice\" <alice@example.com>`). Normalizes to lowercase.\n */\nexport function extractAddr(s: string): string {\n const m = s.match(/<([^>]+)>/);\n return (m?.[1] ?? s).toLowerCase().trim();\n}\n\n/**\n * D332: automated-sender filter. Returns `true` if the message should be\n * DROPPED (sender is automated / bot-loop risk).\n */\nexport function isAutomatedSender(fromAddress: string, headers: Map<string, string>): boolean {\n if (NOREPLY_RE.test(fromAddress)) return true;\n // Normalize header keys to lowercase for lookup.\n const lowered = new Map<string, string>();\n for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);\n // RFC 3834: Auto-Submitted\n const autoSubmitted = lowered.get(\"auto-submitted\");\n if (typeof autoSubmitted === \"string\" && /auto-generated|auto-replied/i.test(autoSubmitted)) {\n return true;\n }\n // Legacy Precedence header\n const precedence = lowered.get(\"precedence\");\n if (typeof precedence === \"string\" && /bulk|list/i.test(precedence)) {\n return true;\n }\n // Microsoft X-Auto-Response-Suppress\n const xAuto = lowered.get(\"x-auto-response-suppress\");\n if (typeof xAuto === \"string\" && /all/i.test(xAuto)) {\n return true;\n }\n return false;\n}\n\n/**\n * D333 + EC-3: allowed-sender allowlist.\n *\n * - `undefined` allowlist → OPEN (all allowed).\n * - Empty array → CLOSED (none allowed). Intentional distinction from undefined.\n * - Both sides normalized via `extractAddr` so `\"Alice <alice@x>\"` matches `alice@x`.\n */\nexport function isAllowedSender(fromAddress: string, allowedSenders?: readonly string[]): boolean {\n if (allowedSenders === undefined) return true;\n const norm = extractAddr(fromAddress);\n return allowedSenders.some((s) => extractAddr(s) === norm);\n}\n","/**\n * IMAP client wrapper around `imapflow`. Supports IDLE + polling fallback.\n *\n * @internal\n */\n\nimport { type FetchMessageObject, ImapFlow } from \"imapflow\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __imapMarker: unique symbol = Symbol(\"imap\");\n\ninterface ImapClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface FetchedMessage {\n readonly uid: number;\n readonly source: Buffer;\n readonly headers: Map<string, string>;\n}\n\nexport interface IImapClient {\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n /** Capability check — does the server advertise IDLE? */\n supportsIdle(): boolean;\n /** Fetch all UNSEEN messages once. Used for poll + post-IDLE-event drain. */\n fetchUnseen(): Promise<FetchedMessage[]>;\n /** Start IDLE; invoke `onExists` whenever the server pushes a new-message notification. */\n startIdle(onExists: () => void): Promise<void>;\n /** Stop IDLE if running. */\n stopIdle(): Promise<void>;\n}\n\nexport class ImapClient implements IImapClient {\n private client: ImapFlow | undefined;\n private idleAbort: AbortController | undefined;\n\n constructor(private readonly config: ImapClientConfig) {}\n\n async connect(): Promise<void> {\n this.client = new ImapFlow({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n logger: false,\n });\n await this.client.connect();\n await this.client.mailboxOpen(\"INBOX\");\n }\n\n supportsIdle(): boolean {\n if (this.client === undefined) return false;\n const caps = (this.client as unknown as { capabilities?: { has?: (s: string) => boolean } })\n .capabilities;\n return caps?.has?.(\"IDLE\") ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.\n async fetchUnseen(): Promise<FetchedMessage[]> {\n if (this.client === undefined) return [];\n const out: FetchedMessage[] = [];\n for await (const raw of this.client.fetch({ seen: false }, {\n uid: true,\n source: true,\n headers: true,\n } as Parameters<ImapFlow[\"fetch\"]>[1])) {\n const msg = raw as FetchMessageObject;\n const headers = new Map<string, string>();\n // headers is a Buffer/Map in imapflow; handle both shapes safely.\n const h = (msg as unknown as { headers?: unknown }).headers;\n if (h instanceof Map) {\n for (const [k, v] of h as Map<string, string | string[]>) {\n headers.set(String(k), Array.isArray(v) ? (v[0] ?? \"\") : v);\n }\n } else if (h instanceof Buffer) {\n for (const line of h.toString(\"utf8\").split(/\\r?\\n/)) {\n const idx = line.indexOf(\":\");\n if (idx > 0)\n headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());\n }\n }\n if (msg.uid !== undefined && msg.source !== undefined) {\n out.push({\n uid: msg.uid,\n source: msg.source as Buffer,\n headers,\n });\n }\n }\n return out;\n }\n\n async startIdle(onExists: () => void): Promise<void> {\n if (this.client === undefined) return;\n this.idleAbort = new AbortController();\n const c = this.client;\n // imapflow's `c.idle()` resolves when IDLE ends. The `mailbox.on(\"exists\")`\n // event fires inside IDLE. We register the listener once and let imapflow\n // refresh IDLE internally per RFC 2177.\n c.on(\"exists\", () => {\n onExists();\n });\n void c.idle().catch(() => {\n /* idle aborted */\n });\n }\n\n async stopIdle(): Promise<void> {\n if (this.idleAbort !== undefined) {\n this.idleAbort.abort();\n this.idleAbort = undefined;\n }\n }\n\n async disconnect(): Promise<void> {\n await this.stopIdle();\n if (this.client !== undefined) {\n try {\n await this.client.logout();\n } catch {\n /* ignore */\n }\n this.client = undefined;\n }\n }\n}\n","/**\n * Inbound `raw RFC 5322 bytes` → `EmailMessageEvent`.\n *\n * EC-2 absorbed: body capped at `maxBodyChars` (default 50000).\n * EC-5 absorbed: subject fallback to `\"(no subject)\"`.\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\nimport { simpleParser } from \"mailparser\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __normalizeMarker: unique symbol = Symbol(\"email-normalize\");\n\nexport interface NormalizeOptions {\n readonly botAddress: string;\n /** EC-2: cap body length. Default 50000. */\n readonly maxBodyChars?: number;\n}\n\nconst DEFAULT_MAX_BODY = 50_000;\n\nfunction stripBraces(id: string | undefined): string | undefined {\n if (id === undefined || id.length === 0) return undefined;\n return id.replace(/^<|>$/g, \"\");\n}\n\nfunction normalizeRefs(refs: string | string[] | undefined): readonly string[] | undefined {\n if (refs === undefined) return undefined;\n const arr = Array.isArray(refs) ? refs : refs.split(/\\s+/).filter((s) => s.length > 0);\n const cleaned = arr.map((r) => stripBraces(r)).filter((r): r is string => r !== undefined);\n return cleaned.length > 0 ? cleaned : undefined;\n}\n\ninterface AddressEntry {\n readonly address?: string;\n readonly name?: string;\n}\n\ninterface AddressObject {\n readonly value?: ReadonlyArray<AddressEntry>;\n}\n\nfunction addressesFrom(\n obj: AddressObject | ReadonlyArray<AddressObject> | undefined,\n): AddressEntry[] {\n if (obj === undefined) return [];\n if (Array.isArray(obj)) {\n const out: AddressEntry[] = [];\n for (const o of obj) out.push(...(o.value ?? []));\n return out;\n }\n return Array.from((obj as AddressObject).value ?? []);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional RFC 5322 field; splitting hurts the \"one event normalization here\" locality.\nexport async function normalizeEmail(\n rawBuffer: Buffer | string,\n opts: NormalizeOptions,\n): Promise<EmailMessageEvent> {\n const parsed = await simpleParser(rawBuffer);\n\n const messageId = stripBraces(parsed.messageId) ?? \"unknown\";\n const inReplyTo = stripBraces(parsed.inReplyTo);\n const references = normalizeRefs(parsed.references as string | string[] | undefined);\n\n const fromEntries = addressesFrom(parsed.from as AddressObject | undefined);\n const fromAddress = (fromEntries[0]?.address ?? \"anonymous\").toLowerCase().trim();\n const fromName = fromEntries[0]?.name;\n\n const botAddrLc = opts.botAddress.toLowerCase().trim();\n const recipients: string[] = [];\n for (const entry of [\n ...addressesFrom(parsed.to as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ...addressesFrom(parsed.cc as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ]) {\n const addr = entry.address?.toLowerCase().trim();\n if (addr !== undefined && addr.length > 0 && addr !== botAddrLc) {\n recipients.push(addr);\n }\n }\n\n // EC-5: subject fallback.\n const subject = parsed.subject ?? \"(no subject)\";\n\n // EC-2: cap body.\n const rawText = parsed.text ?? \"\";\n const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;\n const text =\n rawText.length > maxChars\n ? `${rawText.slice(0, maxChars)}\\n\\n[truncated — full body in event.email.raw]`\n : rawText;\n\n const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();\n const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;\n\n const emailMeta: EmailMessageEvent[\"email\"] = {\n messageId,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n subject,\n fromAddress,\n ...(fromName !== undefined ? { fromName } : {}),\n recipients,\n attachmentCount,\n raw: parsed,\n };\n\n return {\n id: messageId,\n platform: \"email\",\n sender: {\n id: fromAddress,\n ...(fromName !== undefined ? { displayName: fromName } : {}),\n },\n channel: { id: fromAddress, type: \"dm\", topicId: messageId },\n text,\n receivedAt,\n email: emailMeta,\n };\n}\n","/**\n * Bounded `Set<number>` of dispatched IMAP UIDs (ADR D331).\n *\n * Caps at 5000 entries; trims to 4000 (drops oldest 1000) on overflow.\n * Same pattern as the Teams ConversationReferenceStore / WhatsApp Web bridge\n * — bounded memory in long-running bots.\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __seenUidsMarker: unique symbol = Symbol(\"seen-uids\");\n\nexport class SeenUidSet {\n private set = new Set<number>();\n static readonly MAX_SIZE = 5000;\n static readonly TRIM_TO = 4000;\n\n has(uid: number): boolean {\n return this.set.has(uid);\n }\n\n add(uid: number): void {\n if (this.set.size >= SeenUidSet.MAX_SIZE) this.trim();\n this.set.add(uid);\n }\n\n private trim(): void {\n // Set iteration is insertion-ordered in JS. Drop oldest until at TRIM_TO.\n const target = SeenUidSet.TRIM_TO;\n const toDrop = this.set.size - target;\n if (toDrop <= 0) return;\n let i = 0;\n for (const key of this.set) {\n if (i >= toDrop) break;\n this.set.delete(key);\n i++;\n }\n }\n\n get size(): number {\n return this.set.size;\n }\n\n clear(): void {\n this.set.clear();\n }\n}\n","/**\n * SMTP client wrapper around `nodemailer`. Thin shim; tests inject a fake.\n *\n * @internal\n */\n\nimport { createTransport, type SendMailOptions, type Transporter } from \"nodemailer\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __smtpMarker: unique symbol = Symbol(\"smtp\");\n\ninterface SmtpClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface SmtpSendOptions {\n readonly from: string | { name: string; address: string };\n readonly to: string;\n readonly subject: string;\n readonly text: string;\n /** Message-ID (without `<>`) we're replying to. */\n readonly inReplyTo?: string;\n /** References chain (without `<>`). Will be serialized with braces. */\n readonly references?: readonly string[];\n}\n\nexport interface ISmtpClient {\n verify(): Promise<true>;\n send(opts: SmtpSendOptions): Promise<string>;\n close(): Promise<void>;\n}\n\nexport class SmtpClient implements ISmtpClient {\n private transporter: Transporter | undefined;\n\n constructor(private readonly config: SmtpClientConfig) {}\n\n private getTransporter(): Transporter {\n if (this.transporter === undefined) {\n this.transporter = createTransport({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n });\n }\n return this.transporter;\n }\n\n async verify(): Promise<true> {\n return this.getTransporter().verify();\n }\n\n async send(opts: SmtpSendOptions): Promise<string> {\n const mail: SendMailOptions = {\n from: opts.from,\n to: opts.to,\n subject: opts.subject,\n text: opts.text,\n };\n if (opts.inReplyTo !== undefined) {\n mail.inReplyTo = `<${opts.inReplyTo}>`;\n }\n if (opts.references !== undefined && opts.references.length > 0) {\n mail.references = opts.references.map((r) => `<${r}>`);\n }\n const info = await this.getTransporter().sendMail(mail);\n // Strip `<>` from new Message-ID for consistency with inbound.\n const raw = (info.messageId ?? \"\").replace(/^<|>$/g, \"\");\n return raw;\n }\n\n async close(): Promise<void> {\n if (this.transporter !== undefined) {\n this.transporter.close();\n this.transporter = undefined;\n }\n }\n}\n","/**\n * Thread context store (ADR D337). Records `{subject, references, lastMessageId}`\n * per inbound `Message-ID`; consumed on outbound to reconstruct threading headers.\n *\n * Capped at 1000 entries with FIFO eviction (matches WhatsApp / Teams pattern).\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __threadStoreMarker: unique symbol = Symbol(\"thread-store\");\n\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\nexport class ThreadStore {\n private readonly map = new Map<string, ThreadContext>();\n static readonly MAX_SIZE = 1000;\n\n recordFromInbound(event: EmailMessageEvent): void {\n const ctx: ThreadContext = {\n subject: event.email.subject,\n references: event.email.references ?? [],\n lastMessageId: event.email.messageId,\n };\n // FIFO eviction.\n if (this.map.size >= ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n this.map.delete(event.email.messageId);\n this.map.set(event.email.messageId, ctx);\n }\n\n lookup(topicId: string): ThreadContext | undefined {\n return this.map.get(topicId);\n }\n\n get size(): number {\n return this.map.size;\n }\n\n clear(): void {\n this.map.clear();\n }\n}\n","/**\n * `EmailAdapter` — Email platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #4; ADRs D327-D339).\n *\n * Stack: nodemailer (SMTP) + imapflow (IMAP IDLE) + mailparser (RFC 5322).\n * Inbound: IMAP IDLE preferred (D328), 15s poll fallback.\n * Outbound: SMTP via nodemailer + threading reciprocity (D337).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { mapEmailError } from \"./errors.js\";\nimport { isAllowedSender, isAutomatedSender } from \"./filters.js\";\nimport { type FetchedMessage, type IImapClient, ImapClient } from \"./imap-client.js\";\nimport { normalizeEmail } from \"./normalize.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\nexport class EmailAdapter extends BasePlatformAdapter {\n readonly platform = \"email\" as const;\n private readonly options: EmailAdapterOptions;\n private readonly seenUids = new SeenUidSet();\n private readonly threadStore = new ThreadStore();\n private imap: IImapClient | undefined;\n private smtp: ISmtpClient | undefined;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n // EC-4: serialize concurrent _dispatchInbound calls.\n private dispatchQueue: Promise<void> = Promise.resolve();\n private pollTimer: NodeJS.Timeout | undefined;\n\n constructor(opts: EmailAdapterOptions) {\n super();\n // EC-1 pattern (from Teams): validate non-empty at construction (fail fast).\n for (const k of [\"address\", \"password\", \"imapHost\", \"smtpHost\"] as const) {\n const v = opts[k];\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);\n }\n }\n this.options = opts;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n // Construct clients (test seams allow injection).\n const imapFactory = this.options.__imapFactory as ((cfg: unknown) => IImapClient) | undefined;\n const smtpFactory = this.options.__smtpFactory as ((cfg: unknown) => ISmtpClient) | undefined;\n this.imap =\n imapFactory !== undefined\n ? imapFactory({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new ImapClient({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n });\n this.smtp =\n smtpFactory !== undefined\n ? smtpFactory({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new SmtpClient({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n });\n await this.smtp.verify();\n await this.imap.connect();\n\n // Start inbound dispatch loop — IDLE if supported, poll otherwise.\n if (this.imap.supportsIdle()) {\n await this.imap.startIdle(() => {\n void this._drainUnseen();\n });\n // Drain anything already UNSEEN before IDLE started.\n await this._drainUnseen();\n } else {\n // Polling fallback.\n await this._drainUnseen();\n const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.pollTimer = setInterval(() => {\n void this._drainUnseen();\n }, intervalMs);\n }\n\n this.connected = true;\n return true;\n } catch (err) {\n console.error(\"[email] connect failed:\", err instanceof Error ? err.message : err);\n await this.disconnect().catch(() => {});\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pollTimer !== undefined) {\n clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n }\n if (this.imap !== undefined) {\n await this.imap.disconnect().catch(() => {});\n this.imap = undefined;\n }\n if (this.smtp !== undefined) {\n await this.smtp.close().catch(() => {});\n this.smtp = undefined;\n }\n this.connected = false;\n this.handler = undefined;\n this.seenUids.clear();\n this.threadStore.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const messageId = await this.smtp.send({\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n });\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n return () => {\n this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/filters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,EAAqC,KAAA,CAAM,KAAA,CAAM,WAAW,CAAA,CAAE,CAAA;AAC3E,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,CAAC,gBAAgB,KAAA,CAAM,KAAA,CAAM,aAAa,IAAA,CAAK,OAAA,CAAQ,cAAc,CAAA,EAAG;AAC1E,MAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,iCAAA,EAAoC,KAAA,CAAM,KAAA,CAAM,WAAW,CAAA,CAAE,CAAA;AAC1E,MAAA;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,WAAA,CAAY,kBAAkB,KAAK,CAAA;AAExC,IAAA,IAAI,KAAK,OAAA,KAAY,MAAA,EAAW,MAAM,IAAA,CAAK,QAAQ,KAAK,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,IAAI,aAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA,EACA,IAAI,gBAAA,GAA2B;AAC7B,IAAA,OAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AACF","file":"index.js","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder is exhaustive — each branch maps one nodemailer/imapflow/SMTP-response class to one typed canonical code; splitting hurts traceability.\nexport function mapEmailError(err: unknown): ErrorPayload {\n if (err === null || err === undefined) {\n return { code: \"unknown\", message: \"Unknown error\" };\n }\n if (typeof err === \"string\") {\n return { code: \"unknown\", message: err };\n }\n const e = err as {\n code?: string;\n responseCode?: number;\n response?: string;\n message?: string;\n name?: string;\n };\n const code = e.code ?? \"\";\n const respCode = typeof e.responseCode === \"number\" ? e.responseCode : undefined;\n const message = typeof e.message === \"string\" && e.message.length > 0 ? e.message : String(err);\n\n // nodemailer error codes\n if (code === \"EAUTH\" || code === \"EAUTHENTICATION\") {\n return { code: \"auth_failed\", message };\n }\n if (code === \"EENVELOPE\" && /550/.test(message)) {\n return { code: \"invalid_request\", message };\n }\n if (code === \"ECONNECTION\" || code === \"ESOCKET\" || code === \"ETLS\") {\n return { code: \"server_error\", message };\n }\n if (code === \"ETIMEDOUT\") {\n return { code: \"timeout\", message };\n }\n // SMTP response codes\n if (respCode !== undefined) {\n if (respCode === 535 || respCode === 530) return { code: \"auth_failed\", message };\n if (respCode === 421 || respCode === 451 || respCode === 452)\n return { code: \"rate_limit\", message };\n if (respCode === 550 || respCode === 551 || respCode === 553)\n return { code: \"invalid_request\", message };\n if (respCode >= 500) return { code: \"server_error\", message };\n if (respCode >= 400) return { code: \"rate_limit\", message };\n }\n // imapflow throws Error with .authenticationFailed flag in some versions\n if (e.name === \"IMAP_AUTH_FAILED\" || /auth/i.test(message)) {\n return { code: \"auth_failed\", message };\n }\n // EC-7: plain Error fallback\n if (NETWORK_ERR_RE.test(message)) return { code: \"server_error\", message };\n return { code: \"unknown\", message };\n}\n","/**\n * Inbound filters: automated-sender (D332) + allowed-sender allowlist (D333 + EC-3).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __filtersMarker: unique symbol = Symbol(\"email-filters\");\n\nconst NOREPLY_RE =\n /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;\n\n/**\n * EC-3: extract pure email address from a string that may include display\n * name + brackets (`\"Alice\" <alice@example.com>`). Normalizes to lowercase.\n */\nexport function extractAddr(s: string): string {\n const m = s.match(/<([^>]+)>/);\n return (m?.[1] ?? s).toLowerCase().trim();\n}\n\n/**\n * D332: automated-sender filter. Returns `true` if the message should be\n * DROPPED (sender is automated / bot-loop risk).\n */\nexport function isAutomatedSender(fromAddress: string, headers: Map<string, string>): boolean {\n if (NOREPLY_RE.test(fromAddress)) return true;\n // Normalize header keys to lowercase for lookup.\n const lowered = new Map<string, string>();\n for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);\n // RFC 3834: Auto-Submitted\n const autoSubmitted = lowered.get(\"auto-submitted\");\n if (typeof autoSubmitted === \"string\" && /auto-generated|auto-replied/i.test(autoSubmitted)) {\n return true;\n }\n // Legacy Precedence header\n const precedence = lowered.get(\"precedence\");\n if (typeof precedence === \"string\" && /bulk|list/i.test(precedence)) {\n return true;\n }\n // Microsoft X-Auto-Response-Suppress\n const xAuto = lowered.get(\"x-auto-response-suppress\");\n if (typeof xAuto === \"string\" && /all/i.test(xAuto)) {\n return true;\n }\n return false;\n}\n\n/**\n * D333 + EC-3: allowed-sender allowlist.\n *\n * - `undefined` allowlist → OPEN (all allowed).\n * - Empty array → CLOSED (none allowed). Intentional distinction from undefined.\n * - Both sides normalized via `extractAddr` so `\"Alice <alice@x>\"` matches `alice@x`.\n */\nexport function isAllowedSender(fromAddress: string, allowedSenders?: readonly string[]): boolean {\n if (allowedSenders === undefined) return true;\n const norm = extractAddr(fromAddress);\n return allowedSenders.some((s) => extractAddr(s) === norm);\n}\n","/**\n * IMAP client wrapper around `imapflow`. Supports IDLE + polling fallback.\n *\n * @internal\n */\n\nimport { type FetchMessageObject, ImapFlow } from \"imapflow\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __imapMarker: unique symbol = Symbol(\"imap\");\n\ninterface ImapClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface FetchedMessage {\n readonly uid: number;\n readonly source: Buffer;\n readonly headers: Map<string, string>;\n}\n\nexport interface IImapClient {\n connect(): Promise<void>;\n disconnect(): Promise<void>;\n /** Capability check — does the server advertise IDLE? */\n supportsIdle(): boolean;\n /** Fetch all UNSEEN messages once. Used for poll + post-IDLE-event drain. */\n fetchUnseen(): Promise<FetchedMessage[]>;\n /**\n * Set `\\Seen` on the server for a whole batch, so `fetchUnseen()` stops\n * returning them.\n *\n * The server flag is the only delivery state that survives a restart, which\n * is what issue #11 turned on: the in-memory UID set is cleared by\n * `disconnect()`, so without this a reconnect re-delivers the whole unread\n * backlog to the handler.\n *\n * Batched, not per-message, and the reason is measured rather than stylistic.\n * The first version flagged each message individually from inside the\n * serialized dispatch queue; against a 166-message backlog on a real mailbox\n * that put 166 sequential round trips ahead of every newly-arrived message,\n * and an inbound probe waited past 120s to be delivered. One command per\n * drain removes that queue entirely.\n */\n markSeen(uids: readonly number[]): Promise<void>;\n /** Start IDLE; invoke `onExists` whenever the server pushes a new-message notification. */\n startIdle(onExists: () => void): Promise<void>;\n /** Stop IDLE if running. */\n stopIdle(): Promise<void>;\n}\n\nexport class ImapClient implements IImapClient {\n private client: ImapFlow | undefined;\n private idleAbort: AbortController | undefined;\n\n constructor(private readonly config: ImapClientConfig) {}\n\n async connect(): Promise<void> {\n this.client = new ImapFlow({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n logger: false,\n });\n await this.client.connect();\n await this.client.mailboxOpen(\"INBOX\");\n }\n\n supportsIdle(): boolean {\n if (this.client === undefined) return false;\n const caps = (this.client as unknown as { capabilities?: { has?: (s: string) => boolean } })\n .capabilities;\n return caps?.has?.(\"IDLE\") ?? false;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.\n async fetchUnseen(): Promise<FetchedMessage[]> {\n if (this.client === undefined) return [];\n const out: FetchedMessage[] = [];\n for await (const raw of this.client.fetch({ seen: false }, {\n uid: true,\n source: true,\n headers: true,\n } as Parameters<ImapFlow[\"fetch\"]>[1])) {\n const msg = raw as FetchMessageObject;\n const headers = new Map<string, string>();\n // headers is a Buffer/Map in imapflow; handle both shapes safely.\n const h = (msg as unknown as { headers?: unknown }).headers;\n if (h instanceof Map) {\n for (const [k, v] of h as Map<string, string | string[]>) {\n headers.set(String(k), Array.isArray(v) ? (v[0] ?? \"\") : v);\n }\n } else if (h instanceof Buffer) {\n for (const line of h.toString(\"utf8\").split(/\\r?\\n/)) {\n const idx = line.indexOf(\":\");\n if (idx > 0)\n headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());\n }\n }\n if (msg.uid !== undefined && msg.source !== undefined) {\n out.push({\n uid: msg.uid,\n source: msg.source as Buffer,\n headers,\n });\n }\n }\n return out;\n }\n\n async markSeen(uids: readonly number[]): Promise<void> {\n if (this.client === undefined || uids.length === 0) return;\n // `uid: true` is load-bearing — without it imapflow reads these numbers as\n // sequence numbers, which are positional and shift as the mailbox changes,\n // so the flags would land on whatever messages happen to sit at those slots.\n await this.client.messageFlagsAdd({ uid: uids.join(\",\") }, [\"\\\\Seen\"], { uid: true });\n }\n\n async startIdle(onExists: () => void): Promise<void> {\n if (this.client === undefined) return;\n this.idleAbort = new AbortController();\n const c = this.client;\n // imapflow's `c.idle()` resolves when IDLE ends. The `mailbox.on(\"exists\")`\n // event fires inside IDLE. We register the listener once and let imapflow\n // refresh IDLE internally per RFC 2177.\n c.on(\"exists\", () => {\n onExists();\n });\n void c.idle().catch(() => {\n /* idle aborted */\n });\n }\n\n async stopIdle(): Promise<void> {\n if (this.idleAbort !== undefined) {\n this.idleAbort.abort();\n this.idleAbort = undefined;\n }\n }\n\n async disconnect(): Promise<void> {\n await this.stopIdle();\n if (this.client !== undefined) {\n try {\n await this.client.logout();\n } catch {\n /* ignore */\n }\n this.client = undefined;\n }\n }\n}\n","/**\n * Inbound `raw RFC 5322 bytes` → `EmailMessageEvent`.\n *\n * EC-2 absorbed: body capped at `maxBodyChars` (default 50000).\n * EC-5 absorbed: subject fallback to `\"(no subject)\"`.\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\nimport { simpleParser } from \"mailparser\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __normalizeMarker: unique symbol = Symbol(\"email-normalize\");\n\nexport interface NormalizeOptions {\n readonly botAddress: string;\n /** EC-2: cap body length. Default 50000. */\n readonly maxBodyChars?: number;\n}\n\nconst DEFAULT_MAX_BODY = 50_000;\n\nfunction stripBraces(id: string | undefined): string | undefined {\n if (id === undefined || id.length === 0) return undefined;\n return id.replace(/^<|>$/g, \"\");\n}\n\nfunction normalizeRefs(refs: string | string[] | undefined): readonly string[] | undefined {\n if (refs === undefined) return undefined;\n const arr = Array.isArray(refs) ? refs : refs.split(/\\s+/).filter((s) => s.length > 0);\n const cleaned = arr.map((r) => stripBraces(r)).filter((r): r is string => r !== undefined);\n return cleaned.length > 0 ? cleaned : undefined;\n}\n\ninterface AddressEntry {\n readonly address?: string;\n readonly name?: string;\n}\n\ninterface AddressObject {\n readonly value?: ReadonlyArray<AddressEntry>;\n}\n\nfunction addressesFrom(\n obj: AddressObject | ReadonlyArray<AddressObject> | undefined,\n): AddressEntry[] {\n if (obj === undefined) return [];\n if (Array.isArray(obj)) {\n const out: AddressEntry[] = [];\n for (const o of obj) out.push(...(o.value ?? []));\n return out;\n }\n return Array.from((obj as AddressObject).value ?? []);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional RFC 5322 field; splitting hurts the \"one event normalization here\" locality.\nexport async function normalizeEmail(\n rawBuffer: Buffer | string,\n opts: NormalizeOptions,\n): Promise<EmailMessageEvent> {\n const parsed = await simpleParser(rawBuffer);\n\n const messageId = stripBraces(parsed.messageId) ?? \"unknown\";\n const inReplyTo = stripBraces(parsed.inReplyTo);\n const references = normalizeRefs(parsed.references as string | string[] | undefined);\n\n const fromEntries = addressesFrom(parsed.from as AddressObject | undefined);\n const fromAddress = (fromEntries[0]?.address ?? \"anonymous\").toLowerCase().trim();\n const fromName = fromEntries[0]?.name;\n\n const botAddrLc = opts.botAddress.toLowerCase().trim();\n const recipients: string[] = [];\n for (const entry of [\n ...addressesFrom(parsed.to as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ...addressesFrom(parsed.cc as AddressObject | ReadonlyArray<AddressObject> | undefined),\n ]) {\n const addr = entry.address?.toLowerCase().trim();\n if (addr !== undefined && addr.length > 0 && addr !== botAddrLc) {\n recipients.push(addr);\n }\n }\n\n // EC-5: subject fallback.\n const subject = parsed.subject ?? \"(no subject)\";\n\n // EC-2: cap body.\n const rawText = parsed.text ?? \"\";\n const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;\n const text =\n rawText.length > maxChars\n ? `${rawText.slice(0, maxChars)}\\n\\n[truncated — full body in event.email.raw]`\n : rawText;\n\n const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();\n const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;\n\n const emailMeta: EmailMessageEvent[\"email\"] = {\n messageId,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n subject,\n fromAddress,\n ...(fromName !== undefined ? { fromName } : {}),\n recipients,\n attachmentCount,\n raw: parsed,\n };\n\n return {\n id: messageId,\n platform: \"email\",\n sender: {\n id: fromAddress,\n ...(fromName !== undefined ? { displayName: fromName } : {}),\n },\n channel: { id: fromAddress, type: \"dm\", topicId: messageId },\n text,\n receivedAt,\n email: emailMeta,\n };\n}\n","/**\n * Bounded `Set<number>` of dispatched IMAP UIDs (ADR D331).\n *\n * Caps at 5000 entries; trims to 4000 (drops oldest 1000) on overflow.\n * Same pattern as the Teams ConversationReferenceStore / WhatsApp Web bridge\n * — bounded memory in long-running bots.\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __seenUidsMarker: unique symbol = Symbol(\"seen-uids\");\n\nexport class SeenUidSet {\n private set = new Set<number>();\n static readonly MAX_SIZE = 5000;\n static readonly TRIM_TO = 4000;\n\n has(uid: number): boolean {\n return this.set.has(uid);\n }\n\n add(uid: number): void {\n if (this.set.size >= SeenUidSet.MAX_SIZE) this.trim();\n this.set.add(uid);\n }\n\n private trim(): void {\n // Set iteration is insertion-ordered in JS. Drop oldest until at TRIM_TO.\n const target = SeenUidSet.TRIM_TO;\n const toDrop = this.set.size - target;\n if (toDrop <= 0) return;\n let i = 0;\n for (const key of this.set) {\n if (i >= toDrop) break;\n this.set.delete(key);\n i++;\n }\n }\n\n get size(): number {\n return this.set.size;\n }\n\n clear(): void {\n this.set.clear();\n }\n}\n","/**\n * SMTP client wrapper around `nodemailer`. Thin shim; tests inject a fake.\n *\n * @internal\n */\n\nimport { createTransport, type SendMailOptions, type Transporter } from \"nodemailer\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __smtpMarker: unique symbol = Symbol(\"smtp\");\n\ninterface SmtpClientConfig {\n readonly host: string;\n readonly port: number;\n readonly secure: boolean;\n readonly auth: { user: string; pass: string };\n}\n\nexport interface SmtpSendOptions {\n readonly from: string | { name: string; address: string };\n readonly to: string;\n readonly subject: string;\n readonly text: string;\n /** Message-ID (without `<>`) we're replying to. */\n readonly inReplyTo?: string;\n /** References chain (without `<>`). Will be serialized with braces. */\n readonly references?: readonly string[];\n}\n\nexport interface ISmtpClient {\n verify(): Promise<true>;\n send(opts: SmtpSendOptions): Promise<string>;\n close(): Promise<void>;\n}\n\nexport class SmtpClient implements ISmtpClient {\n private transporter: Transporter | undefined;\n\n constructor(private readonly config: SmtpClientConfig) {}\n\n private getTransporter(): Transporter {\n if (this.transporter === undefined) {\n this.transporter = createTransport({\n host: this.config.host,\n port: this.config.port,\n secure: this.config.secure,\n auth: this.config.auth,\n });\n }\n return this.transporter;\n }\n\n async verify(): Promise<true> {\n return this.getTransporter().verify();\n }\n\n async send(opts: SmtpSendOptions): Promise<string> {\n const mail: SendMailOptions = {\n from: opts.from,\n to: opts.to,\n subject: opts.subject,\n text: opts.text,\n };\n if (opts.inReplyTo !== undefined) {\n mail.inReplyTo = `<${opts.inReplyTo}>`;\n }\n if (opts.references !== undefined && opts.references.length > 0) {\n mail.references = opts.references.map((r) => `<${r}>`);\n }\n const info = await this.getTransporter().sendMail(mail);\n // Strip `<>` from new Message-ID for consistency with inbound.\n const raw = (info.messageId ?? \"\").replace(/^<|>$/g, \"\");\n return raw;\n }\n\n async close(): Promise<void> {\n if (this.transporter !== undefined) {\n this.transporter.close();\n this.transporter = undefined;\n }\n }\n}\n","/**\n * Thread context store (ADR D337). Records `{subject, references, lastMessageId}`\n * per inbound `Message-ID`; consumed on outbound to reconstruct threading headers.\n *\n * Capped at 1000 entries with FIFO eviction (matches WhatsApp / Teams pattern).\n *\n * @internal\n */\n\nimport type { EmailMessageEvent } from \"@theokit/gateway\";\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __threadStoreMarker: unique symbol = Symbol(\"thread-store\");\n\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\nexport class ThreadStore {\n private readonly map = new Map<string, ThreadContext>();\n static readonly MAX_SIZE = 1000;\n\n recordFromInbound(event: EmailMessageEvent): void {\n const ctx: ThreadContext = {\n subject: event.email.subject,\n references: event.email.references ?? [],\n lastMessageId: event.email.messageId,\n };\n // FIFO eviction.\n if (this.map.size >= ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n this.map.delete(event.email.messageId);\n this.map.set(event.email.messageId, ctx);\n }\n\n lookup(topicId: string): ThreadContext | undefined {\n return this.map.get(topicId);\n }\n\n get size(): number {\n return this.map.size;\n }\n\n clear(): void {\n this.map.clear();\n }\n}\n","/**\n * `EmailAdapter` — Email platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #4; ADRs D327-D339).\n *\n * Stack: nodemailer (SMTP) + imapflow (IMAP IDLE) + mailparser (RFC 5322).\n * Inbound: IMAP IDLE preferred (D328), 15s poll fallback.\n * Outbound: SMTP via nodemailer + threading reciprocity (D337).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { mapEmailError } from \"./errors.js\";\nimport { isAllowedSender, isAutomatedSender } from \"./filters.js\";\nimport { type FetchedMessage, type IImapClient, ImapClient } from \"./imap-client.js\";\nimport { normalizeEmail } from \"./normalize.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\nexport class EmailAdapter extends BasePlatformAdapter {\n readonly platform = \"email\" as const;\n private readonly options: EmailAdapterOptions;\n private readonly seenUids = new SeenUidSet();\n /** UIDs finished with in this batch, awaiting one `\\Seen` command (#11). */\n private readonly pendingSeen = new Set<number>();\n private readonly threadStore = new ThreadStore();\n private imap: IImapClient | undefined;\n private smtp: ISmtpClient | undefined;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n // EC-4: serialize concurrent _dispatchInbound calls.\n private dispatchQueue: Promise<void> = Promise.resolve();\n private pollTimer: NodeJS.Timeout | undefined;\n\n constructor(opts: EmailAdapterOptions) {\n super();\n // EC-1 pattern (from Teams): validate non-empty at construction (fail fast).\n for (const k of [\"address\", \"password\", \"imapHost\", \"smtpHost\"] as const) {\n const v = opts[k];\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);\n }\n }\n this.options = opts;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n // Construct clients (test seams allow injection).\n const imapFactory = this.options.__imapFactory as ((cfg: unknown) => IImapClient) | undefined;\n const smtpFactory = this.options.__smtpFactory as ((cfg: unknown) => ISmtpClient) | undefined;\n this.imap =\n imapFactory !== undefined\n ? imapFactory({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new ImapClient({\n host: this.options.imapHost,\n port: this.options.imapPort ?? 993,\n secure: true,\n auth: { user: this.options.address, pass: this.options.password },\n });\n this.smtp =\n smtpFactory !== undefined\n ? smtpFactory({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n })\n : new SmtpClient({\n host: this.options.smtpHost,\n port: this.options.smtpPort ?? 587,\n secure: (this.options.smtpPort ?? 587) === 465,\n auth: { user: this.options.address, pass: this.options.password },\n });\n await this.smtp.verify();\n await this.imap.connect();\n\n // Start inbound dispatch loop — IDLE if supported, poll otherwise.\n if (this.imap.supportsIdle()) {\n await this.imap.startIdle(() => {\n void this._drainUnseen();\n });\n // Drain anything already UNSEEN before IDLE started.\n await this._drainUnseen();\n } else {\n // Polling fallback.\n await this._drainUnseen();\n const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.pollTimer = setInterval(() => {\n void this._drainUnseen();\n }, intervalMs);\n }\n\n this.connected = true;\n return true;\n } catch (err) {\n console.error(\"[email] connect failed:\", err instanceof Error ? err.message : err);\n await this.disconnect().catch(() => {});\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pollTimer !== undefined) {\n clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n }\n if (this.imap !== undefined) {\n await this.imap.disconnect().catch(() => {});\n this.imap = undefined;\n }\n if (this.smtp !== undefined) {\n await this.smtp.close().catch(() => {});\n this.smtp = undefined;\n }\n this.connected = false;\n this.handler = undefined;\n this.seenUids.clear();\n this.threadStore.clear();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const messageId = await this.smtp.send({\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n });\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n // The guard is not decoration. Without it, onInbound(A) -> onInbound(B) ->\n // A's stale unsubscribe clears B, and inbound delivery stops permanently\n // with nothing logged. Email and Teams were the only two adapters of ten\n // missing it, and no test anywhere exercised the A->B->unsubA sequence.\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n // Chain the flush behind this batch's dispatches rather than awaiting them\n // here: `connect()` calls this, and blocking it on a large backlog is the\n // slow-connect problem, not something to make worse.\n this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n try {\n await this._dispatchOrDrop(uid, rawBuffer, headers);\n } finally {\n // Every exit records, including the drops. A discarded message is finished\n // with, and leaving it UNSEEN means downloading and re-parsing it on\n // every drain forever — most of the 166-message backlog measured on the\n // live mailbox was old own-address probes being re-read and re-thrown-away.\n //\n // Recorded AFTER the attempt, not before: a crash in the window between\n // the two costs at most a duplicate of the single in-flight message,\n // where flagging first would lose it silently. Duplicates are visible and\n // apologisable; a support email nobody ever answers is neither.\n this.pendingSeen.add(uid);\n }\n }\n\n /**\n * Flush the batch to the server. Never throws — a mailbox we cannot flag is\n * not worth dropping mail over; those UIDs simply come back on the next drain.\n */\n private async _flushSeen(): Promise<void> {\n if (this.imap === undefined || this.pendingSeen.size === 0) return;\n const uids = [...this.pendingSeen];\n this.pendingSeen.clear();\n try {\n await this.imap.markSeen(uids);\n } catch (err) {\n console.error(\n `[email] could not flag ${uids.length} message(s) \\\\Seen (they will be re-delivered):`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n private async _dispatchOrDrop(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-email",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Email platform adapter for @theokit/gateway. Community-standard 2026 stack: nodemailer + imapflow + mailparser. ADRs D327-D339.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -34,7 +34,7 @@
34
34
  "imapflow": "^1.0.0",
35
35
  "mailparser": "^3.0.0",
36
36
  "nodemailer": "^8.0.0",
37
- "@theokit/gateway": "^0.4.1"
37
+ "@theokit/gateway": "^0.5.1"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@theokit/sdk": "^2.18.0",
@@ -47,7 +47,7 @@
47
47
  "typescript": "^5.8.0",
48
48
  "vitest": "^4.1.8",
49
49
  "zod": "^4.0.0",
50
- "@theokit/gateway": "0.4.1"
50
+ "@theokit/gateway": "0.5.1"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",