@theokit/gateway-email 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter } from '@theokit/gateway';
1
+ import { channelConfigReaders, BasePlatformAdapter } from '@theokit/gateway';
2
2
  import { ImapFlow } from 'imapflow';
3
3
  import { simpleParser } from 'mailparser';
4
4
  import { createTransport } from 'nodemailer';
@@ -93,16 +93,23 @@ var ImapClient = class {
93
93
  await this.client.connect();
94
94
  await this.client.mailboxOpen("INBOX");
95
95
  }
96
+ // eslint-disable-next-line @typescript-eslint/require-await
97
+ async mailboxStatus() {
98
+ const box = this.client?.mailbox;
99
+ if (box === void 0 || box === false) throw new Error("no mailbox open");
100
+ return { uidValidity: Number(box.uidValidity), uidNext: box.uidNext };
101
+ }
96
102
  supportsIdle() {
97
103
  if (this.client === void 0) return false;
98
104
  const caps = this.client.capabilities;
99
105
  return caps?.has?.("IDLE") ?? false;
100
106
  }
101
107
  // 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.
102
- async fetchUnseen() {
108
+ async fetchUnseen(sinceUid) {
103
109
  if (this.client === void 0) return [];
104
110
  const out = [];
105
- for await (const raw of this.client.fetch({ seen: false }, {
111
+ const query = sinceUid === void 0 ? { seen: false } : { seen: false, uid: `${sinceUid}:*` };
112
+ for await (const raw of this.client.fetch(query, {
106
113
  uid: true,
107
114
  source: true,
108
115
  headers: true
@@ -374,6 +381,8 @@ var EmailAdapter = class extends BasePlatformAdapter {
374
381
  // EC-4: serialize concurrent _dispatchInbound calls.
375
382
  dispatchQueue = Promise.resolve();
376
383
  pollTimer;
384
+ /** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
385
+ cursor;
377
386
  constructor(opts) {
378
387
  super();
379
388
  for (const k of ["address", "password", "imapHost", "smtpHost"]) {
@@ -414,13 +423,13 @@ var EmailAdapter = class extends BasePlatformAdapter {
414
423
  });
415
424
  await this.smtp.verify();
416
425
  await this.imap.connect();
426
+ await this._establishCursor(this.imap);
417
427
  if (this.imap.supportsIdle()) {
418
428
  await this.imap.startIdle(() => {
419
429
  void this._drainUnseen().catch(reportDrainFailure);
420
430
  });
421
- await this._drainUnseen();
431
+ void this._drainUnseen().catch(reportDrainFailure);
422
432
  } else {
423
- await this._drainUnseen();
424
433
  const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
425
434
  this.pollTimer = setInterval(() => {
426
435
  void this._drainUnseen().catch(reportDrainFailure);
@@ -495,21 +504,50 @@ var EmailAdapter = class extends BasePlatformAdapter {
495
504
  if (this.handler === handler) this.handler = void 0;
496
505
  };
497
506
  }
498
- /** @internal — drain UNSEEN once and dispatch each. */
507
+ /**
508
+ * Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
509
+ * UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
510
+ */
511
+ async _establishCursor(imap) {
512
+ const store = this.options.cursorStore;
513
+ const status = await imap.mailboxStatus();
514
+ const known = this.cursor ?? await store?.load();
515
+ if (known !== void 0 && known.uidValidity === status.uidValidity) {
516
+ this.cursor = known;
517
+ return;
518
+ }
519
+ this.cursor = { uidValidity: status.uidValidity, uid: status.uidNext };
520
+ await store?.save(this.cursor);
521
+ }
522
+ /** @internal — drain UNSEEN past the cursor once and dispatch each. */
499
523
  async _drainUnseen() {
500
- if (this.imap === void 0) return;
524
+ if (this.imap === void 0 || this.cursor === void 0) return;
525
+ const since = this.cursor.uid;
501
526
  let messages = [];
502
527
  try {
503
- messages = await this.imap.fetchUnseen();
528
+ messages = await this.imap.fetchUnseen(since);
504
529
  } catch (err) {
505
530
  console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
506
531
  return;
507
532
  }
533
+ messages = messages.filter((m) => m.uid >= since);
508
534
  for (const msg of messages) {
509
535
  this._dispatchInbound(msg.uid, msg.source, msg.headers);
510
536
  }
537
+ await this._advanceCursor(messages);
511
538
  this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
512
539
  }
540
+ async _advanceCursor(messages) {
541
+ if (this.cursor === void 0 || messages.length === 0) return;
542
+ const next = Math.max(...messages.map((m) => m.uid)) + 1;
543
+ if (next <= this.cursor.uid) return;
544
+ this.cursor = { uidValidity: this.cursor.uidValidity, uid: next };
545
+ try {
546
+ await this.options.cursorStore?.save(this.cursor);
547
+ } catch (err) {
548
+ console.error("[email] could not save cursor:", err instanceof Error ? err.message : err);
549
+ }
550
+ }
513
551
  /**
514
552
  * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
515
553
  * Fire-and-forget: never throws; errors logged.
@@ -615,6 +653,137 @@ async function sendWithTextFallback(smtp, base, html) {
615
653
  }
616
654
  }
617
655
 
618
- export { EmailAdapter, SeenUidSet, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
656
+ // ../../shared/channel-config-field.ts
657
+ var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
658
+
659
+ // ../../shared/env-value-readers.ts
660
+ function readEnvNumber(invalid2, config, key) {
661
+ const value = config[key];
662
+ if (value === void 0) return void 0;
663
+ if (typeof value === "number" && Number.isFinite(value)) return value;
664
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
665
+ const parsed = Number(value.trim());
666
+ if (Number.isFinite(parsed)) return parsed;
667
+ }
668
+ throw invalid2(key, "a number or a digit string");
669
+ }
670
+ function readEnvBoolean(invalid2, config, key) {
671
+ const value = config[key];
672
+ if (value === void 0) return void 0;
673
+ if (value === true || value === "true") return true;
674
+ if (value === false || value === "false") return false;
675
+ throw invalid2(key, 'a boolean or the string "true" or "false"');
676
+ }
677
+ function envValueReaders(invalid2) {
678
+ return {
679
+ number: (config, key) => readEnvNumber(invalid2, config, key),
680
+ boolean: (config, key) => readEnvBoolean(invalid2, config, key)
681
+ };
682
+ }
683
+
684
+ // src/channel.ts
685
+ var readers = channelConfigReaders("gateway-email");
686
+ var { invalid } = readers;
687
+ var isAbsent = (value) => value === void 0;
688
+ var read = {
689
+ ...envValueReaders(invalid),
690
+ string: readers.requiredString,
691
+ optionalString: (config, key) => config[key] === void 0 ? void 0 : readers.requiredString(config, key),
692
+ list(config, key) {
693
+ const value = config[key];
694
+ if (value === void 0) return void 0;
695
+ if (typeof value === "string") {
696
+ return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
697
+ }
698
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
699
+ throw invalid(key, "an array of strings or a comma-separated string");
700
+ }
701
+ };
702
+ function readCursorStore(config) {
703
+ const value = config.cursorStore;
704
+ if (isAbsent(value)) return void 0;
705
+ const store = value;
706
+ if (typeof value !== "object" || typeof store?.load !== "function" || typeof store.save !== "function") {
707
+ throw invalid("cursorStore", "an object with load and save functions");
708
+ }
709
+ return value;
710
+ }
711
+ var CONFIG = [
712
+ field(
713
+ "address",
714
+ "EMAIL_ADDRESS",
715
+ "Email address the bot listens on; also the From address of outbound mail."
716
+ ),
717
+ field("password", "EMAIL_PASSWORD", "Password or app password for the IMAP and SMTP login.", {
718
+ secret: true
719
+ }),
720
+ field("imapHost", "EMAIL_IMAP_HOST", "IMAP server host name."),
721
+ field("imapPort", "EMAIL_IMAP_PORT", "IMAP server port.", { required: false }),
722
+ field("smtpHost", "EMAIL_SMTP_HOST", "SMTP server host name."),
723
+ field("smtpPort", "EMAIL_SMTP_PORT", "SMTP server port.", { required: false }),
724
+ field("fromName", "EMAIL_FROM_NAME", "Display name for outbound mail.", { required: false }),
725
+ field(
726
+ "allowedSenders",
727
+ "EMAIL_ALLOWED_SENDERS",
728
+ "Sender addresses allowed through, as a list or comma-separated string.",
729
+ { required: false }
730
+ ),
731
+ field(
732
+ "allowAutomated",
733
+ "EMAIL_ALLOW_AUTOMATED",
734
+ "When true, automated senders (no-reply, bulk mail) are not filtered out.",
735
+ { required: false }
736
+ ),
737
+ field("pollIntervalMs", "EMAIL_POLL_INTERVAL_MS", "Milliseconds between mailbox polls.", {
738
+ required: false
739
+ }),
740
+ field("maxBodyChars", "EMAIL_MAX_BODY_CHARS", "Longest inbound body kept, in characters.", {
741
+ required: false
742
+ }),
743
+ {
744
+ key: "cursorStore",
745
+ required: false,
746
+ secret: false,
747
+ description: "Programmatic store that persists the IMAP cursor; no env binding."
748
+ }
749
+ ];
750
+ var emailChannel = {
751
+ platform: "email",
752
+ transport: "socket",
753
+ senderIdentity: {
754
+ unauthenticated: "an email From header is written by the sender and can be forged"
755
+ },
756
+ config: CONFIG,
757
+ create(config) {
758
+ const address = read.string(config, "address");
759
+ const password = read.string(config, "password");
760
+ const imapHost = read.string(config, "imapHost");
761
+ const smtpHost = read.string(config, "smtpHost");
762
+ const imapPort = read.number(config, "imapPort");
763
+ const smtpPort = read.number(config, "smtpPort");
764
+ const fromName = read.optionalString(config, "fromName");
765
+ const allowedSenders = read.list(config, "allowedSenders");
766
+ const allowAutomated = read.boolean(config, "allowAutomated");
767
+ const pollIntervalMs = read.number(config, "pollIntervalMs");
768
+ const maxBodyChars = read.number(config, "maxBodyChars");
769
+ const cursorStore = readCursorStore(config);
770
+ return new EmailAdapter({
771
+ address,
772
+ password,
773
+ imapHost,
774
+ smtpHost,
775
+ ...imapPort === void 0 ? {} : { imapPort },
776
+ ...smtpPort === void 0 ? {} : { smtpPort },
777
+ ...fromName === void 0 ? {} : { fromName },
778
+ ...allowedSenders === void 0 ? {} : { allowedSenders },
779
+ ...allowAutomated === void 0 ? {} : { allowAutomated },
780
+ ...pollIntervalMs === void 0 ? {} : { pollIntervalMs },
781
+ ...maxBodyChars === void 0 ? {} : { maxBodyChars },
782
+ ...cursorStore === void 0 ? {} : { cursorStore }
783
+ });
784
+ }
785
+ };
786
+
787
+ export { EmailAdapter, SeenUidSet, ThreadStore, emailChannel, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
619
788
  //# sourceMappingURL=index.js.map
620
789
  //# sourceMappingURL=index.js.map
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/refuse-attachments.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;;;AA8BA,IAAM,cAAA,GAAiB,gEAAA;AAShB,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,OAAO,CAAA,CAAE,YAAA,KAAiB,QAAA,GAAW,EAAE,YAAA,GAAe,MAAA;AACvE,EAAA,MAAM,OAAA,GAAU,OAAO,CAAA,CAAE,OAAA,KAAY,QAAA,IAAY,CAAA,CAAE,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA;AAG9F,EAAA,IAAI,IAAA,KAAS,OAAA,IAAW,IAAA,KAAS,iBAAA,EAAmB;AAClD,IAAA,OAAO,EAAE,IAAA,EAAM,aAAA,EAAe,OAAA,EAAQ;AAAA,EACxC;AACA,EAAA,IAAI,IAAA,KAAS,WAAA,IAAe,KAAA,CAAM,IAAA,CAAK,OAAO,CAAA,EAAG;AAC/C,IAAA,OAAO,EAAE,IAAA,EAAM,iBAAA,EAAmB,OAAA,EAAQ;A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;AAAA,IAEnB,UAAA,EAAY,KAAA,CAAM,IAAA,iBAAK,IAAI,GAAA,CAAI,CAAC,GAAG,OAAA,CAAQ,UAAA,EAAY,OAAA,CAAQ,aAAa,CAAC,CAAC;AAAA,GAChF;AACF;AAUA,eAAe,oBAAA,CACb,IAAA,EACA,IAAA,EACA,IAAA,EACiB;AACjB,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,KAAS,KAAA,CAAA,GAAY,OAAO,EAAE,GAAG,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,EACtE,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI,IAAA,KAAS,QAAW,MAAM,GAAA;AAC9B,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,MACb;AAAA,KACF;AACA,IAAA,OAAO,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA,EACvB;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/**\n * Map anything thrown by SMTP or IMAP into the canonical `{ code, message }` payload.\n *\n * Total by construction: `null`, `undefined`, a string and an unrecognised object each map to an\n * `unknown`-coded payload rather than propagating.\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\n/** Options for {@link normalizeEmail}. */\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/**\n * Parse raw RFC 5322 bytes into an `EmailMessageEvent`.\n *\n * The body is capped at `maxBodyChars` (50000 by default) because an inbound mail can carry\n * megabytes of quoted history, and everything downstream — hooks, the handler, the model — pays for\n * every character of it.\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 // Trimmed, and empty means ABSENT. mailparser reports `name: \"\"` for a bare `From: a@b` — not\n // `undefined` — so testing only for undefined carried an empty display name into every event\n // without one. The convention two lines down is the same: `addr.length > 0`.\n const trimmedName = fromEntries[0]?.name?.trim();\n const fromName = trimmedName !== undefined && trimmedName.length > 0 ? trimmedName : undefined;\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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"email adapter cannot send attachments\" },\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 /**\n * The same message as HTML, sent alongside `text` as a multipart alternative.\n *\n * Present only when the caller declared a format the platform can render. A client that\n * cannot display HTML falls back to `text`, which is why both are sent rather than one\n * replacing the other — an HTML-only mail is unreadable in a plain-text reader.\n */\n readonly html?: 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.html !== undefined) {\n mail.html = opts.html;\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\n/** What a reply needs in order to land in the same mail thread as the message it answers. */\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\n/**\n * In-memory map from conversation id to the headers a threaded reply needs.\n *\n * Bounded at `MAX_SIZE` entries and evicted oldest-first: a long-running bot would otherwise retain\n * every thread it ever saw. State is per-process and deliberately not persisted — a restart loses\n * threading, which degrades a reply to a new thread rather than losing the reply.\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 { refuseAttachments } from \"./refuse-attachments.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient, type SmtpSendOptions } from \"./smtp-client.js\";\nimport { type ThreadContext, ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\n/**\n * Last-resort report for a drain that rejected.\n *\n * `_drainUnseen` is written never to reject — it contains the fetch failure, and dispatch failures\n * are contained one level down. But both launch sites discard the promise, so that property is the\n * only thing standing between a future edit and an unhandled rejection, which under Node 22's\n * default ends the process. Nothing enforced it; this does, at the site that would pay for it (#41).\n */\nfunction reportDrainFailure(err: unknown): void {\n console.error(\"[email] drain failed:\", err instanceof Error ? err.message : err);\n}\n\n/**\n * The HTML alternative for a message whose caller declared a format.\n *\n * Two paths, and they carry different trust.\n *\n * `markdown` is ESCAPED and wrapped, never rendered: a markdown-to-HTML renderer is a\n * dependency this package does not have and does not need for the field to stop being\n * discarded. What the caller declared reaches the wire; converting the syntax is the\n * presenter's job, not the transport's.\n *\n * `html` is passed THROUGH, because that is what the caller declared it to be — escaping it\n * would make the value meaningless. **This is a trust boundary and it is the caller's to\n * hold.** A consumer whose text is influenced by untrusted input must not set\n * `format: \"html\"`; `markdown` is the safe declaration and it escapes. The alternative —\n * sanitising here — would need an HTML parser in a package that has no runtime dependencies,\n * and would silently alter a payload the caller said was already HTML.\n */\nfunction htmlPartFor(text: string, format: \"markdown\" | \"html\"): string {\n if (format === \"html\") return text;\n const escaped = text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n return `<pre>${escaped}</pre>`;\n}\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().catch(reportDrainFailure);\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().catch(reportDrainFailure);\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 async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(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 const { subject, inReplyTo, references } = replyHeaders(context);\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 base = {\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n };\n // Sent ALONGSIDE `text`, never instead of it: a plain-text reader shows the text part, so\n // a client that cannot render HTML still gets the message.\n const html =\n out.format === \"markdown\" || out.format === \"html\"\n ? htmlPartFor(out.text, out.format)\n : undefined;\n\n const messageId = await sendWithTextFallback(this.smtp, base, html);\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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * The subject and threading headers of a send: a reply's when the topic has a thread, a fresh\n * subject otherwise. Extracted from `sendText` unchanged (B-674) to keep it under the complexity\n * limit once it was renamed from `sendMessage`.\n */\nfunction replyHeaders(context: ThreadContext | undefined): {\n subject: string;\n inReplyTo?: string;\n references?: readonly string[];\n} {\n if (context === undefined) return { subject: \"Message from agent\" };\n return {\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\n/**\n * Send `base` with its html part, and once more as text alone if the server refuses the html.\n *\n * ADR-2: an undelivered message is worse than an unformatted one. A server that refuses the html\n * part still accepts the text one, and the recipient reading a plain-text client would never have\n * seen the difference. Only attempted when there WAS an html part — otherwise this would retry a\n * send that failed for some entirely other reason.\n */\nasync function sendWithTextFallback(\n smtp: ISmtpClient,\n base: SmtpSendOptions,\n html: string | undefined,\n): Promise<string> {\n try {\n return await smtp.send(html === undefined ? base : { ...base, html });\n } catch (err) {\n if (html === undefined) throw err;\n process.stderr.write(\n \"[gateway-email] the server rejected the html part; retrying with text only\\n\",\n );\n return smtp.send(base);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/filters.ts","../src/imap-client.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts","../../../shared/channel-config-field.ts","../../../shared/env-value-readers.ts","../src/channel.ts"],"names":["invalid"],"mappings":";;;;;;;;AA8BA,IAAM,cAAA,GAAiB,gEAAA;AAShB,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,OAAO,CAAA,CAAE,YAAA,KAAiB,QAAA,GAAW,EAAE,YAAA,GAAe,MAAA;AACvE,EAAA,MAAM,OAAA,GAAU,OAAO,CAAA,CAAE,OAAA,KAAY,QAAA,IAAY,CAAA,CAAE,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA;AAG9F,EAAA,IAAI,IAAA,KAAS,OAAA,IAAW,IAAA,KAAS,iBAAA,EAAmB;AAClD,IAAA,OAAO,EAAE,IAAA,EAAM,aAAA,EAAe,OAAA,EAAQ;AAAA,EACxC;AACA,EAAA,IAAI,IAAA,KAAS,WAAA,IAAe,KAAA,CAAM,IAAA,CAAK,OAAO,CAAA,EAAG;AAC/C,IAAA,OAAO,EAAE,IAAA,EAAM,iBAAA,EAAmB,OAAA,EAAQ;AAAA,EAC5C;AACA,EAAA,IAAI,IAAA,KAAS,aAA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K,MAAA,EAAQ,gBAAgB,CAAA;AACzD,IAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,OAAA,CAAQ,MAAA,EAAQ,gBAAgB,CAAA;AAC5D,IAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,gBAAgB,CAAA;AAC3D,IAAA,MAAM,YAAA,GAAe,IAAA,CAAK,MAAA,CAAO,MAAA,EAAQ,cAAc,CAAA;AACvD,IAAA,MAAM,WAAA,GAAc,gBAAgB,MAAM,CAAA;AAC1C,IAAA,OAAO,IAAI,YAAA,CAAa;AAAA,MACtB,OAAA;AAAA,MACA,QAAA;AAAA,MACA,QAAA;AAAA,MACA,QAAA;AAAA,MACA,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA,EAAS;AAAA,MAC7C,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA,EAAS;AAAA,MAC7C,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA,EAAS;AAAA,MAC7C,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA,EAAe;AAAA,MACzD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA,EAAe;AAAA,MACzD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA,EAAe;AAAA,MACzD,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAa;AAAA,MACrD,GAAI,WAAA,KAAgB,MAAA,GAAY,EAAC,GAAI,EAAE,WAAA;AAAY,KACpD,CAAA;AAAA,EACH;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/**\n * Map anything thrown by SMTP or IMAP into the canonical `{ code, message }` payload.\n *\n * Total by construction: `null`, `undefined`, a string and an unrecognised object each map to an\n * `unknown`-coded payload rather than propagating.\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 MailboxStatus {\n readonly uidValidity: number;\n readonly uidNext: number;\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 /** The open mailbox's UIDVALIDITY and UIDNEXT: the baseline a first connect records (#348). */\n mailboxStatus(): Promise<MailboxStatus>;\n /**\n * Fetch UNSEEN messages once, only those with `uid >= sinceUid` when given. Used for poll +\n * post-IDLE-event drain.\n */\n fetchUnseen(sinceUid?: number): 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 // eslint-disable-next-line @typescript-eslint/require-await\n async mailboxStatus(): Promise<MailboxStatus> {\n const box = this.client?.mailbox;\n if (box === undefined || box === false) throw new Error(\"no mailbox open\");\n return { uidValidity: Number(box.uidValidity), uidNext: box.uidNext };\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(sinceUid?: number): Promise<FetchedMessage[]> {\n if (this.client === undefined) return [];\n const out: FetchedMessage[] = [];\n const query = sinceUid === undefined ? { seen: false } : { seen: false, uid: `${sinceUid}:*` };\n for await (const raw of this.client.fetch(query, {\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\n/** Options for {@link normalizeEmail}. */\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/**\n * Parse raw RFC 5322 bytes into an `EmailMessageEvent`.\n *\n * The body is capped at `maxBodyChars` (50000 by default) because an inbound mail can carry\n * megabytes of quoted history, and everything downstream — hooks, the handler, the model — pays for\n * every character of it.\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 // Trimmed, and empty means ABSENT. mailparser reports `name: \"\"` for a bare `From: a@b` — not\n // `undefined` — so testing only for undefined carried an empty display name into every event\n // without one. The convention two lines down is the same: `addr.length > 0`.\n const trimmedName = fromEntries[0]?.name?.trim();\n const fromName = trimmedName !== undefined && trimmedName.length > 0 ? trimmedName : undefined;\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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"email adapter cannot send attachments\" },\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 /**\n * The same message as HTML, sent alongside `text` as a multipart alternative.\n *\n * Present only when the caller declared a format the platform can render. A client that\n * cannot display HTML falls back to `text`, which is why both are sent rather than one\n * replacing the other — an HTML-only mail is unreadable in a plain-text reader.\n */\n readonly html?: 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.html !== undefined) {\n mail.html = opts.html;\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\n/** What a reply needs in order to land in the same mail thread as the message it answers. */\nexport interface ThreadContext {\n readonly subject: string;\n readonly references: readonly string[];\n readonly lastMessageId: string;\n}\n\n/**\n * In-memory map from conversation id to the headers a threaded reply needs.\n *\n * Bounded at `MAX_SIZE` entries and evicted oldest-first: a long-running bot would otherwise retain\n * every thread it ever saw. State is per-process and deliberately not persisted — a restart loses\n * threading, which degrades a reply to a new thread rather than losing the reply.\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 { refuseAttachments } from \"./refuse-attachments.js\";\nimport { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient, type SmtpSendOptions } from \"./smtp-client.js\";\nimport { type ThreadContext, ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions, EmailCursor } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\n/**\n * Last-resort report for a drain that rejected.\n *\n * `_drainUnseen` is written never to reject — it contains the fetch failure, and dispatch failures\n * are contained one level down. But both launch sites discard the promise, so that property is the\n * only thing standing between a future edit and an unhandled rejection, which under Node 22's\n * default ends the process. Nothing enforced it; this does, at the site that would pay for it (#41).\n */\nfunction reportDrainFailure(err: unknown): void {\n console.error(\"[email] drain failed:\", err instanceof Error ? err.message : err);\n}\n\n/**\n * The HTML alternative for a message whose caller declared a format.\n *\n * Two paths, and they carry different trust.\n *\n * `markdown` is ESCAPED and wrapped, never rendered: a markdown-to-HTML renderer is a\n * dependency this package does not have and does not need for the field to stop being\n * discarded. What the caller declared reaches the wire; converting the syntax is the\n * presenter's job, not the transport's.\n *\n * `html` is passed THROUGH, because that is what the caller declared it to be — escaping it\n * would make the value meaningless. **This is a trust boundary and it is the caller's to\n * hold.** A consumer whose text is influenced by untrusted input must not set\n * `format: \"html\"`; `markdown` is the safe declaration and it escapes. The alternative —\n * sanitising here — would need an HTML parser in a package that has no runtime dependencies,\n * and would silently alter a payload the caller said was already HTML.\n */\nfunction htmlPartFor(text: string, format: \"markdown\" | \"html\"): string {\n if (format === \"html\") return text;\n const escaped = text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n return `<pre>${escaped}</pre>`;\n}\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 /** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */\n private cursor: EmailCursor | 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 await this._establishCursor(this.imap);\n\n // Start inbound dispatch loop — IDLE if supported, poll otherwise. `connect()` resolves\n // once the baseline is set; nothing is dispatched from inside it (#348).\n if (this.imap.supportsIdle()) {\n await this.imap.startIdle(() => {\n void this._drainUnseen().catch(reportDrainFailure);\n });\n // Mail that arrived between the baseline and IDLE starting.\n void this._drainUnseen().catch(reportDrainFailure);\n } else {\n // Polling fallback.\n const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.pollTimer = setInterval(() => {\n void this._drainUnseen().catch(reportDrainFailure);\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 async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(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 const { subject, inReplyTo, references } = replyHeaders(context);\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 base = {\n from,\n to,\n subject,\n text: out.text,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n ...(references !== undefined ? { references } : {}),\n };\n // Sent ALONGSIDE `text`, never instead of it: a plain-text reader shows the text part, so\n // a client that cannot render HTML still gets the message.\n const html =\n out.format === \"markdown\" || out.format === \"html\"\n ? htmlPartFor(out.text, out.format)\n : undefined;\n\n const messageId = await sendWithTextFallback(this.smtp, base, html);\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 /**\n * Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its\n * UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.\n */\n private async _establishCursor(imap: IImapClient): Promise<void> {\n const store = this.options.cursorStore;\n const status = await imap.mailboxStatus();\n const known = this.cursor ?? (await store?.load());\n if (known !== undefined && known.uidValidity === status.uidValidity) {\n this.cursor = known;\n return;\n }\n this.cursor = { uidValidity: status.uidValidity, uid: status.uidNext };\n await store?.save(this.cursor);\n }\n\n /** @internal — drain UNSEEN past the cursor once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined || this.cursor === undefined) return;\n const since = this.cursor.uid;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen(since);\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n // `N:*` always includes the last message even when it is below N.\n messages = messages.filter((m) => m.uid >= since);\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n await this._advanceCursor(messages);\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 private async _advanceCursor(messages: readonly FetchedMessage[]): Promise<void> {\n if (this.cursor === undefined || messages.length === 0) return;\n const next = Math.max(...messages.map((m) => m.uid)) + 1;\n if (next <= this.cursor.uid) return;\n this.cursor = { uidValidity: this.cursor.uidValidity, uid: next };\n try {\n await this.options.cursorStore?.save(this.cursor);\n } catch (err) {\n console.error(\"[email] could not save cursor:\", err instanceof Error ? err.message : err);\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 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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * The subject and threading headers of a send: a reply's when the topic has a thread, a fresh\n * subject otherwise. Extracted from `sendText` unchanged (B-674) to keep it under the complexity\n * limit once it was renamed from `sendMessage`.\n */\nfunction replyHeaders(context: ThreadContext | undefined): {\n subject: string;\n inReplyTo?: string;\n references?: readonly string[];\n} {\n if (context === undefined) return { subject: \"Message from agent\" };\n return {\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\n/**\n * Send `base` with its html part, and once more as text alone if the server refuses the html.\n *\n * ADR-2: an undelivered message is worse than an unformatted one. A server that refuses the html\n * part still accepts the text one, and the recipient reading a plain-text client would never have\n * seen the difference. Only attempted when there WAS an html part — otherwise this would retry a\n * send that failed for some entirely other reason.\n */\nasync function sendWithTextFallback(\n smtp: ISmtpClient,\n base: SmtpSendOptions,\n html: string | undefined,\n): Promise<string> {\n try {\n return await smtp.send(html === undefined ? base : { ...base, html });\n } catch (err) {\n if (html === undefined) throw err;\n process.stderr.write(\n \"[gateway-email] the server rejected the html part; retrying with text only\\n\",\n );\n return smtp.send(base);\n }\n}\n","/**\n * One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published\n * `.d.ts` never names a core type an older peer release lacks), and its constructor.\n */\nexport interface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n readonly env?: string;\n}\n\nexport const field = (\n key: string,\n env: string,\n description: string,\n { required = true, secret = false }: { required?: boolean; secret?: boolean } = {},\n): ConfigField => ({ key, required, secret, env, description });\n","/**\n * Readers for config values that may arrive as environment strings, where only `undefined` is\n * absent: `null` and `\"\"` are wrong shapes and throw. The core readers treat both as absent, so a\n * channel that must refuse them takes these instead. `invalid` is the channel's own error builder.\n */\ntype Config = Readonly<Record<string, unknown>>;\ntype Invalid = (key: string, expected: string) => Error;\n\nfunction readEnvNumber(invalid: Invalid, config: Config, key: string): number | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && /^[0-9]+$/.test(value.trim())) {\n const parsed = Number(value.trim());\n if (Number.isFinite(parsed)) return parsed;\n }\n throw invalid(key, \"a number or a digit string\");\n}\n\nfunction readEnvBoolean(invalid: Invalid, config: Config, key: string): boolean | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (value === true || value === \"true\") return true;\n if (value === false || value === \"false\") return false;\n throw invalid(key, 'a boolean or the string \"true\" or \"false\"');\n}\n\nexport function envValueReaders(invalid: Invalid) {\n return {\n number: (config: Config, key: string) => readEnvNumber(invalid, config, key),\n boolean: (config: Config, key: string) => readEnvBoolean(invalid, config, key),\n };\n}\n","/**\n * `emailChannel` — the email channel described as data.\n *\n * Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration\n * package's typecheck is where a drift between the two fails. The package has no error class of\n * its own, so a refused value throws the core `GatewayConfigurationError` tagged `gateway-email`.\n */\n\nimport { channelConfigReaders } from \"@theokit/gateway\";\n\nimport { type ConfigField, field } from \"../../../shared/channel-config-field.js\";\nimport { envValueReaders } from \"../../../shared/env-value-readers.js\";\nimport { EmailAdapter } from \"./adapter.js\";\nimport type { EmailCursorStore } from \"./types.js\";\n\nconst readers = channelConfigReaders(\"gateway-email\");\nconst { invalid } = readers;\n\n/** Only `undefined` is absent: `null` and `\"\"` are wrong shapes and throw `invalid_config`. */\nconst isAbsent = (value: unknown): boolean => value === undefined;\n\ntype Config = Readonly<Record<string, unknown>>;\n\n/** Readers for values that may arrive as env strings; only `undefined` is absent. */\nconst read = {\n ...envValueReaders(invalid),\n string: readers.requiredString,\n optionalString: (config: Config, key: string): string | undefined =>\n config[key] === undefined ? undefined : readers.requiredString(config, key),\n list(config: Config, key: string): string[] | undefined {\n const value = config[key];\n if (value === undefined) return undefined;\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value;\n throw invalid(key, \"an array of strings or a comma-separated string\");\n },\n};\n\nfunction readCursorStore(config: Readonly<Record<string, unknown>>): EmailCursorStore | undefined {\n const value = config.cursorStore;\n if (isAbsent(value)) return undefined;\n const store = value as Partial<EmailCursorStore> | null;\n if (\n typeof value !== \"object\" ||\n typeof store?.load !== \"function\" ||\n typeof store.save !== \"function\"\n ) {\n throw invalid(\"cursorStore\", \"an object with load and save functions\");\n }\n return value as EmailCursorStore;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n field(\n \"address\",\n \"EMAIL_ADDRESS\",\n \"Email address the bot listens on; also the From address of outbound mail.\",\n ),\n field(\"password\", \"EMAIL_PASSWORD\", \"Password or app password for the IMAP and SMTP login.\", {\n secret: true,\n }),\n field(\"imapHost\", \"EMAIL_IMAP_HOST\", \"IMAP server host name.\"),\n field(\"imapPort\", \"EMAIL_IMAP_PORT\", \"IMAP server port.\", { required: false }),\n field(\"smtpHost\", \"EMAIL_SMTP_HOST\", \"SMTP server host name.\"),\n field(\"smtpPort\", \"EMAIL_SMTP_PORT\", \"SMTP server port.\", { required: false }),\n field(\"fromName\", \"EMAIL_FROM_NAME\", \"Display name for outbound mail.\", { required: false }),\n field(\n \"allowedSenders\",\n \"EMAIL_ALLOWED_SENDERS\",\n \"Sender addresses allowed through, as a list or comma-separated string.\",\n { required: false },\n ),\n field(\n \"allowAutomated\",\n \"EMAIL_ALLOW_AUTOMATED\",\n \"When true, automated senders (no-reply, bulk mail) are not filtered out.\",\n { required: false },\n ),\n field(\"pollIntervalMs\", \"EMAIL_POLL_INTERVAL_MS\", \"Milliseconds between mailbox polls.\", {\n required: false,\n }),\n field(\"maxBodyChars\", \"EMAIL_MAX_BODY_CHARS\", \"Longest inbound body kept, in characters.\", {\n required: false,\n }),\n {\n key: \"cursorStore\",\n required: false,\n secret: false,\n description: \"Programmatic store that persists the IMAP cursor; no env binding.\",\n },\n];\n\n/**\n * The email channel: the adapter polls IMAP itself, so it needs no webhook route. A From header is\n * written by the sender, so `sender.id` is not authenticated.\n *\n * `create` validates each value and throws `GatewayConfigurationError` (`invalid_config`) naming\n * the key; it makes no network call.\n *\n * @public\n */\nexport const emailChannel = {\n platform: \"email\" as const,\n transport: \"socket\" as const,\n senderIdentity: {\n unauthenticated: \"an email From header is written by the sender and can be forged\",\n },\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): EmailAdapter {\n const address = read.string(config, \"address\");\n const password = read.string(config, \"password\");\n const imapHost = read.string(config, \"imapHost\");\n const smtpHost = read.string(config, \"smtpHost\");\n const imapPort = read.number(config, \"imapPort\");\n const smtpPort = read.number(config, \"smtpPort\");\n const fromName = read.optionalString(config, \"fromName\");\n const allowedSenders = read.list(config, \"allowedSenders\");\n const allowAutomated = read.boolean(config, \"allowAutomated\");\n const pollIntervalMs = read.number(config, \"pollIntervalMs\");\n const maxBodyChars = read.number(config, \"maxBodyChars\");\n const cursorStore = readCursorStore(config);\n return new EmailAdapter({\n address,\n password,\n imapHost,\n smtpHost,\n ...(imapPort === undefined ? {} : { imapPort }),\n ...(smtpPort === undefined ? {} : { smtpPort }),\n ...(fromName === undefined ? {} : { fromName }),\n ...(allowedSenders === undefined ? {} : { allowedSenders }),\n ...(allowAutomated === undefined ? {} : { allowAutomated }),\n ...(pollIntervalMs === undefined ? {} : { pollIntervalMs }),\n ...(maxBodyChars === undefined ? {} : { maxBodyChars }),\n ...(cursorStore === undefined ? {} : { cursorStore }),\n });\n },\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-email",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
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
  "repository": {
@@ -36,7 +36,7 @@
36
36
  "CHANGELOG.md"
37
37
  ],
38
38
  "peerDependencies": {
39
- "@theokit/gateway": ">=0.9.0 <1.0.0",
39
+ "@theokit/gateway": ">=0.21.0 <1.0.0",
40
40
  "imapflow": "^1.0.0",
41
41
  "mailparser": "^3.0.0",
42
42
  "nodemailer": "^10.0.6"
@@ -54,7 +54,7 @@
54
54
  "typescript": "5.9.3",
55
55
  "vitest": "^4.1.11",
56
56
  "zod": "^4.0.0",
57
- "@theokit/gateway": "0.14.0"
57
+ "@theokit/gateway": "0.24.0"
58
58
  },
59
59
  "publishConfig": {
60
60
  "access": "public",