@theokit/gateway-email 0.3.1 → 0.5.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/CHANGELOG.md +40 -0
- package/dist/index.cjs +79 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -1
- package/dist/index.d.ts +29 -1
- package/dist/index.js +79 -26
- package/dist/index.js.map +1 -1
- package/package.json +20 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5db4bf0: The first connect no longer dispatches the unread backlog. It records the mailbox's UIDNEXT (with its UIDVALIDITY) as a cursor and dispatches only mail that arrives after it; `connect()` resolves once the baseline is set. A new `cursorStore` option persists the cursor across restarts; a changed UIDVALIDITY resets it.
|
|
8
|
+
|
|
9
|
+
## 0.4.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 7aff50b: The `nodemailer` peer range is now `^10.0.6`. Every nodemailer up to 10.0.5 is inside an open advisory, and the tests already ran against 10.3.1, which the old `^9.0.1` range refused.
|
|
14
|
+
|
|
15
|
+
## 0.3.2
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 0c0328d: Tests now load against `nodemailer@9.1.1`: the vitest config inlines `mailparser`, whose ESM build imports `nodemailer/lib/addressparser` as a directory that Node's ESM resolver rejects when its nodemailer dependency is 9.x. The declared `nodemailer` range is unchanged. No runtime change.
|
|
20
|
+
- 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
|
|
21
|
+
|
|
22
|
+
`@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
|
|
23
|
+
`filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
|
|
24
|
+
carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
|
|
25
|
+
`supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
|
|
26
|
+
field. The runner and the router refuse an outbound carrying attachments as
|
|
27
|
+
`attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
|
|
28
|
+
`supportsAttachments`.
|
|
29
|
+
|
|
30
|
+
`@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
|
|
31
|
+
`sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
|
|
32
|
+
when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
|
|
33
|
+
than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
|
|
34
|
+
|
|
35
|
+
Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
|
|
36
|
+
with `attachments_unsupported` and makes no platform call, instead of sending the text and
|
|
37
|
+
dropping the image.
|
|
38
|
+
|
|
39
|
+
The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
|
|
40
|
+
throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
|
|
41
|
+
as a handler error is. Dispatch still does not throw.
|
|
42
|
+
|
|
3
43
|
## 0.3.1
|
|
4
44
|
|
|
5
45
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -95,16 +95,23 @@ var ImapClient = class {
|
|
|
95
95
|
await this.client.connect();
|
|
96
96
|
await this.client.mailboxOpen("INBOX");
|
|
97
97
|
}
|
|
98
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
99
|
+
async mailboxStatus() {
|
|
100
|
+
const box = this.client?.mailbox;
|
|
101
|
+
if (box === void 0 || box === false) throw new Error("no mailbox open");
|
|
102
|
+
return { uidValidity: Number(box.uidValidity), uidNext: box.uidNext };
|
|
103
|
+
}
|
|
98
104
|
supportsIdle() {
|
|
99
105
|
if (this.client === void 0) return false;
|
|
100
106
|
const caps = this.client.capabilities;
|
|
101
107
|
return caps?.has?.("IDLE") ?? false;
|
|
102
108
|
}
|
|
103
109
|
// 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.
|
|
104
|
-
async fetchUnseen() {
|
|
110
|
+
async fetchUnseen(sinceUid) {
|
|
105
111
|
if (this.client === void 0) return [];
|
|
106
112
|
const out = [];
|
|
107
|
-
|
|
113
|
+
const query = sinceUid === void 0 ? { seen: false } : { seen: false, uid: `${sinceUid}:*` };
|
|
114
|
+
for await (const raw of this.client.fetch(query, {
|
|
108
115
|
uid: true,
|
|
109
116
|
source: true,
|
|
110
117
|
headers: true
|
|
@@ -237,6 +244,15 @@ async function normalizeEmail(rawBuffer, opts) {
|
|
|
237
244
|
};
|
|
238
245
|
}
|
|
239
246
|
|
|
247
|
+
// src/refuse-attachments.ts
|
|
248
|
+
function refuseAttachments(out) {
|
|
249
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
250
|
+
return {
|
|
251
|
+
ok: false,
|
|
252
|
+
error: { code: "attachments_unsupported", message: "email adapter cannot send attachments" }
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
240
256
|
// src/seen-uids.ts
|
|
241
257
|
var SeenUidSet = class _SeenUidSet {
|
|
242
258
|
set = /* @__PURE__ */ new Set();
|
|
@@ -367,6 +383,8 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
367
383
|
// EC-4: serialize concurrent _dispatchInbound calls.
|
|
368
384
|
dispatchQueue = Promise.resolve();
|
|
369
385
|
pollTimer;
|
|
386
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
387
|
+
cursor;
|
|
370
388
|
constructor(opts) {
|
|
371
389
|
super();
|
|
372
390
|
for (const k of ["address", "password", "imapHost", "smtpHost"]) {
|
|
@@ -407,13 +425,13 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
407
425
|
});
|
|
408
426
|
await this.smtp.verify();
|
|
409
427
|
await this.imap.connect();
|
|
428
|
+
await this._establishCursor(this.imap);
|
|
410
429
|
if (this.imap.supportsIdle()) {
|
|
411
430
|
await this.imap.startIdle(() => {
|
|
412
431
|
void this._drainUnseen().catch(reportDrainFailure);
|
|
413
432
|
});
|
|
414
|
-
|
|
433
|
+
void this._drainUnseen().catch(reportDrainFailure);
|
|
415
434
|
} else {
|
|
416
|
-
await this._drainUnseen();
|
|
417
435
|
const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
418
436
|
this.pollTimer = setInterval(() => {
|
|
419
437
|
void this._drainUnseen().catch(reportDrainFailure);
|
|
@@ -448,8 +466,10 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
448
466
|
this.seenUids.clear();
|
|
449
467
|
this.threadStore.clear();
|
|
450
468
|
}
|
|
451
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the "one outbound transaction" locality.
|
|
452
469
|
async sendMessage(out) {
|
|
470
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
471
|
+
}
|
|
472
|
+
async sendText(out) {
|
|
453
473
|
if (out.text.length === 0) {
|
|
454
474
|
return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
|
|
455
475
|
}
|
|
@@ -462,14 +482,7 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
462
482
|
const to = out.channel.id;
|
|
463
483
|
const topicId = out.channel.topicId;
|
|
464
484
|
const context = topicId !== void 0 ? this.threadStore.lookup(topicId) : void 0;
|
|
465
|
-
|
|
466
|
-
let inReplyTo;
|
|
467
|
-
let references;
|
|
468
|
-
if (context !== void 0) {
|
|
469
|
-
subject = context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`;
|
|
470
|
-
inReplyTo = context.lastMessageId;
|
|
471
|
-
references = Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]));
|
|
472
|
-
}
|
|
485
|
+
const { subject, inReplyTo, references } = replyHeaders(context);
|
|
473
486
|
const from = this.options.fromName !== void 0 ? { name: this.options.fromName, address: this.options.address } : this.options.address;
|
|
474
487
|
try {
|
|
475
488
|
const base = {
|
|
@@ -481,16 +494,7 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
481
494
|
...references !== void 0 ? { references } : {}
|
|
482
495
|
};
|
|
483
496
|
const html = out.format === "markdown" || out.format === "html" ? htmlPartFor(out.text, out.format) : void 0;
|
|
484
|
-
|
|
485
|
-
try {
|
|
486
|
-
messageId = await this.smtp.send(html === void 0 ? base : { ...base, html });
|
|
487
|
-
} catch (err) {
|
|
488
|
-
if (html === void 0) throw err;
|
|
489
|
-
process.stderr.write(
|
|
490
|
-
"[gateway-email] the server rejected the html part; retrying with text only\n"
|
|
491
|
-
);
|
|
492
|
-
messageId = await this.smtp.send(base);
|
|
493
|
-
}
|
|
497
|
+
const messageId = await sendWithTextFallback(this.smtp, base, html);
|
|
494
498
|
return { ok: true, messageId };
|
|
495
499
|
} catch (err) {
|
|
496
500
|
return { ok: false, error: mapEmailError(err) };
|
|
@@ -502,21 +506,50 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
502
506
|
if (this.handler === handler) this.handler = void 0;
|
|
503
507
|
};
|
|
504
508
|
}
|
|
505
|
-
/**
|
|
509
|
+
/**
|
|
510
|
+
* Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
|
|
511
|
+
* UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
|
|
512
|
+
*/
|
|
513
|
+
async _establishCursor(imap) {
|
|
514
|
+
const store = this.options.cursorStore;
|
|
515
|
+
const status = await imap.mailboxStatus();
|
|
516
|
+
const known = this.cursor ?? await store?.load();
|
|
517
|
+
if (known !== void 0 && known.uidValidity === status.uidValidity) {
|
|
518
|
+
this.cursor = known;
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
this.cursor = { uidValidity: status.uidValidity, uid: status.uidNext };
|
|
522
|
+
await store?.save(this.cursor);
|
|
523
|
+
}
|
|
524
|
+
/** @internal — drain UNSEEN past the cursor once and dispatch each. */
|
|
506
525
|
async _drainUnseen() {
|
|
507
|
-
if (this.imap === void 0) return;
|
|
526
|
+
if (this.imap === void 0 || this.cursor === void 0) return;
|
|
527
|
+
const since = this.cursor.uid;
|
|
508
528
|
let messages = [];
|
|
509
529
|
try {
|
|
510
|
-
messages = await this.imap.fetchUnseen();
|
|
530
|
+
messages = await this.imap.fetchUnseen(since);
|
|
511
531
|
} catch (err) {
|
|
512
532
|
console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
|
|
513
533
|
return;
|
|
514
534
|
}
|
|
535
|
+
messages = messages.filter((m) => m.uid >= since);
|
|
515
536
|
for (const msg of messages) {
|
|
516
537
|
this._dispatchInbound(msg.uid, msg.source, msg.headers);
|
|
517
538
|
}
|
|
539
|
+
await this._advanceCursor(messages);
|
|
518
540
|
this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
|
|
519
541
|
}
|
|
542
|
+
async _advanceCursor(messages) {
|
|
543
|
+
if (this.cursor === void 0 || messages.length === 0) return;
|
|
544
|
+
const next = Math.max(...messages.map((m) => m.uid)) + 1;
|
|
545
|
+
if (next <= this.cursor.uid) return;
|
|
546
|
+
this.cursor = { uidValidity: this.cursor.uidValidity, uid: next };
|
|
547
|
+
try {
|
|
548
|
+
await this.options.cursorStore?.save(this.cursor);
|
|
549
|
+
} catch (err) {
|
|
550
|
+
console.error("[email] could not save cursor:", err instanceof Error ? err.message : err);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
520
553
|
/**
|
|
521
554
|
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
522
555
|
* Fire-and-forget: never throws; errors logged.
|
|
@@ -601,6 +634,26 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
601
634
|
return this.runHandler(this.handler, event);
|
|
602
635
|
}
|
|
603
636
|
};
|
|
637
|
+
function replyHeaders(context) {
|
|
638
|
+
if (context === void 0) return { subject: "Message from agent" };
|
|
639
|
+
return {
|
|
640
|
+
subject: context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`,
|
|
641
|
+
inReplyTo: context.lastMessageId,
|
|
642
|
+
// EC-6: dedup the chain.
|
|
643
|
+
references: Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]))
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
async function sendWithTextFallback(smtp, base, html) {
|
|
647
|
+
try {
|
|
648
|
+
return await smtp.send(html === void 0 ? base : { ...base, html });
|
|
649
|
+
} catch (err) {
|
|
650
|
+
if (html === void 0) throw err;
|
|
651
|
+
process.stderr.write(
|
|
652
|
+
"[gateway-email] the server rejected the html part; retrying with text only\n"
|
|
653
|
+
);
|
|
654
|
+
return smtp.send(base);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
604
657
|
|
|
605
658
|
exports.EmailAdapter = EmailAdapter;
|
|
606
659
|
exports.SeenUidSet = SeenUidSet;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/filters.ts","../src/imap-client.ts","../src/normalize.ts","../src/seen-uids.ts","../src/smtp-client.ts","../src/thread-store.ts","../src/adapter.ts"],"names":["ImapFlow","simpleParser","createTransport","BasePlatformAdapter"],"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,EAA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AAEA,IAAA,IAAA,CAAK,WAAA,CAAY,kBAAkB,KAAK,CAAA;AAExC,IAAA,IAAI,KAAK,OAAA,KAAY,MAAA,EAAW,MAAM,IAAA,CAAK,QAAQ,KAAK,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,IAAI,aAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA,EACA,IAAI,gBAAA,GAA2B;AAC7B,IAAA,OAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAe,QACb,KAAA,EACgD;AAChD,IAAA,OAAO,IAAA,CAAK,UAAA,CAAW,IAAA,CAAK,OAAA,EAAS,KAAK,CAAA;AAAA,EAC5C;AACF","file":"index.cjs","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n/**\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 * 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 { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\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, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\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 // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const 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 let messageId: string;\n try {\n messageId = await this.smtp.send(html === undefined ? base : { ...base, html });\n } catch (err) {\n // ADR-2: an undelivered message is worse than an unformatted one. A server that refuses\n // the html part still accepts the text one, and the recipient reading a plain-text\n // client would never have seen the difference. Only attempted when there WAS an html\n // part — otherwise this would retry a send that failed for some entirely other reason.\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 messageId = await this.smtp.send(base);\n }\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n // The guard is not decoration. Without it, onInbound(A) -> onInbound(B) ->\n // A's stale unsubscribe clears B, and inbound delivery stops permanently\n // with nothing logged. Email and Teams were the only two adapters of ten\n // missing it, and no test anywhere exercised the A->B->unsubA sequence.\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n // Chain the flush behind this batch's dispatches rather than awaiting them\n // here: `connect()` calls this, and blocking it on a large backlog is the\n // slow-connect problem, not something to make worse.\n this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n try {\n await this._dispatchOrDrop(uid, rawBuffer, headers);\n } finally {\n // Every exit records, including the drops. A discarded message is finished\n // with, and leaving it UNSEEN means downloading and re-parsing it on\n // every drain forever — most of the 166-message backlog measured on the\n // live mailbox was old own-address probes being re-read and re-thrown-away.\n //\n // Recorded AFTER the attempt, not before: a crash in the window between\n // the two costs at most a duplicate of the single in-flight message,\n // where flagging first would lose it silently. Duplicates are visible and\n // apologisable; a support email nobody ever answers is neither.\n this.pendingSeen.add(uid);\n }\n }\n\n /**\n * Flush the batch to the server. Never throws — a mailbox we cannot flag is\n * not worth dropping mail over; those UIDs simply come back on the next drain.\n */\n private async _flushSeen(): Promise<void> {\n if (this.imap === undefined || this.pendingSeen.size === 0) return;\n const uids = [...this.pendingSeen];\n this.pendingSeen.clear();\n try {\n await this.imap.markSeen(uids);\n } catch (err) {\n console.error(\n `[email] could not flag ${uids.length} message(s) \\\\Seen (they will be re-delivered):`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n private async _dispatchOrDrop(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n\n /**\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"]}
|
|
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":["ImapFlow","simpleParser","createTransport","BasePlatformAdapter"],"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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AA,CAAQ,OAAA,GAAU,CAAA,IAAA,EAAO,OAAA,CAAQ,OAAO,CAAA,CAAA;AAAA,IACrF,WAAW,OAAA,CAAQ,aAAA;AAAA;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.cjs","sourcesContent":["/**\n * Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.\n *\n * Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — workaround for rollup-plugin-dts deep type-only\n * re-export bug. The marker is INTENTIONALLY orphan: it forces rollup-plugin-dts\n * to keep the module in the bundle so re-exports from `index.ts` resolve.\n *\n * @knipignore\n */\nexport const __errorsMarker: unique symbol = Symbol(\"email-errors\");\n\ninterface ErrorPayload {\n code:\n | \"auth_failed\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"not_connected\"\n | \"empty_text\"\n | \"timeout\"\n | \"unknown\";\n message: string;\n}\n\nconst NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;\n\n/**\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, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { EmailMessageEvent, BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
2
|
export type { EmailMessageEvent };
|
|
3
3
|
|
|
4
|
+
/** Where the adapter has read up to: the next UID to dispatch, within one UIDVALIDITY. */
|
|
5
|
+
interface EmailCursor {
|
|
6
|
+
readonly uidValidity: number;
|
|
7
|
+
readonly uid: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Persistence seam for the cursor (#348). Without one the cursor lives in memory for the life of
|
|
11
|
+
* the adapter, so a process restart takes a fresh baseline and mail that arrived while it was
|
|
12
|
+
* down is not dispatched.
|
|
13
|
+
*/
|
|
14
|
+
interface EmailCursorStore {
|
|
15
|
+
load(): EmailCursor | undefined | Promise<EmailCursor | undefined>;
|
|
16
|
+
save(cursor: EmailCursor): void | Promise<void>;
|
|
17
|
+
}
|
|
4
18
|
/** Adapter options. */
|
|
5
19
|
interface EmailAdapterOptions {
|
|
6
20
|
/** Email address the bot listens on (also the From: of outbound). */
|
|
@@ -32,6 +46,11 @@ interface EmailAdapterOptions {
|
|
|
32
46
|
readonly pollIntervalMs?: number;
|
|
33
47
|
/** Max body chars before truncation (EC-2). Default 50000 (~12k tokens). */
|
|
34
48
|
readonly maxBodyChars?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Persist the `{uidValidity, uid}` cursor. A first connect with no cursor (or a changed
|
|
51
|
+
* UIDVALIDITY) baselines at the mailbox's UIDNEXT and dispatches nothing older.
|
|
52
|
+
*/
|
|
53
|
+
readonly cursorStore?: EmailCursorStore;
|
|
35
54
|
}
|
|
36
55
|
|
|
37
56
|
/**
|
|
@@ -58,11 +77,20 @@ declare class EmailAdapter extends BasePlatformAdapter {
|
|
|
58
77
|
private connected;
|
|
59
78
|
private dispatchQueue;
|
|
60
79
|
private pollTimer;
|
|
80
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
81
|
+
private cursor;
|
|
61
82
|
constructor(opts: EmailAdapterOptions);
|
|
62
83
|
connect(): Promise<boolean>;
|
|
63
84
|
disconnect(): Promise<void>;
|
|
64
85
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
86
|
+
private sendText;
|
|
65
87
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
88
|
+
/**
|
|
89
|
+
* Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
|
|
90
|
+
* UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
|
|
91
|
+
*/
|
|
92
|
+
private _establishCursor;
|
|
93
|
+
private _advanceCursor;
|
|
66
94
|
/**
|
|
67
95
|
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
68
96
|
* Fire-and-forget: never throws; errors logged.
|
|
@@ -185,4 +213,4 @@ declare class ThreadStore {
|
|
|
185
213
|
clear(): void;
|
|
186
214
|
}
|
|
187
215
|
|
|
188
|
-
export { EmailAdapter, type EmailAdapterOptions, type NormalizeOptions, SeenUidSet, type ThreadContext, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
|
216
|
+
export { EmailAdapter, type EmailAdapterOptions, type EmailCursor, type EmailCursorStore, type NormalizeOptions, SeenUidSet, type ThreadContext, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { EmailMessageEvent, BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
2
|
export type { EmailMessageEvent };
|
|
3
3
|
|
|
4
|
+
/** Where the adapter has read up to: the next UID to dispatch, within one UIDVALIDITY. */
|
|
5
|
+
interface EmailCursor {
|
|
6
|
+
readonly uidValidity: number;
|
|
7
|
+
readonly uid: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Persistence seam for the cursor (#348). Without one the cursor lives in memory for the life of
|
|
11
|
+
* the adapter, so a process restart takes a fresh baseline and mail that arrived while it was
|
|
12
|
+
* down is not dispatched.
|
|
13
|
+
*/
|
|
14
|
+
interface EmailCursorStore {
|
|
15
|
+
load(): EmailCursor | undefined | Promise<EmailCursor | undefined>;
|
|
16
|
+
save(cursor: EmailCursor): void | Promise<void>;
|
|
17
|
+
}
|
|
4
18
|
/** Adapter options. */
|
|
5
19
|
interface EmailAdapterOptions {
|
|
6
20
|
/** Email address the bot listens on (also the From: of outbound). */
|
|
@@ -32,6 +46,11 @@ interface EmailAdapterOptions {
|
|
|
32
46
|
readonly pollIntervalMs?: number;
|
|
33
47
|
/** Max body chars before truncation (EC-2). Default 50000 (~12k tokens). */
|
|
34
48
|
readonly maxBodyChars?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Persist the `{uidValidity, uid}` cursor. A first connect with no cursor (or a changed
|
|
51
|
+
* UIDVALIDITY) baselines at the mailbox's UIDNEXT and dispatches nothing older.
|
|
52
|
+
*/
|
|
53
|
+
readonly cursorStore?: EmailCursorStore;
|
|
35
54
|
}
|
|
36
55
|
|
|
37
56
|
/**
|
|
@@ -58,11 +77,20 @@ declare class EmailAdapter extends BasePlatformAdapter {
|
|
|
58
77
|
private connected;
|
|
59
78
|
private dispatchQueue;
|
|
60
79
|
private pollTimer;
|
|
80
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
81
|
+
private cursor;
|
|
61
82
|
constructor(opts: EmailAdapterOptions);
|
|
62
83
|
connect(): Promise<boolean>;
|
|
63
84
|
disconnect(): Promise<void>;
|
|
64
85
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
86
|
+
private sendText;
|
|
65
87
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
88
|
+
/**
|
|
89
|
+
* Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
|
|
90
|
+
* UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
|
|
91
|
+
*/
|
|
92
|
+
private _establishCursor;
|
|
93
|
+
private _advanceCursor;
|
|
66
94
|
/**
|
|
67
95
|
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
68
96
|
* Fire-and-forget: never throws; errors logged.
|
|
@@ -185,4 +213,4 @@ declare class ThreadStore {
|
|
|
185
213
|
clear(): void;
|
|
186
214
|
}
|
|
187
215
|
|
|
188
|
-
export { EmailAdapter, type EmailAdapterOptions, type NormalizeOptions, SeenUidSet, type ThreadContext, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
|
216
|
+
export { EmailAdapter, type EmailAdapterOptions, type EmailCursor, type EmailCursorStore, type NormalizeOptions, SeenUidSet, type ThreadContext, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
package/dist/index.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
@@ -235,6 +242,15 @@ async function normalizeEmail(rawBuffer, opts) {
|
|
|
235
242
|
};
|
|
236
243
|
}
|
|
237
244
|
|
|
245
|
+
// src/refuse-attachments.ts
|
|
246
|
+
function refuseAttachments(out) {
|
|
247
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: { code: "attachments_unsupported", message: "email adapter cannot send attachments" }
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
238
254
|
// src/seen-uids.ts
|
|
239
255
|
var SeenUidSet = class _SeenUidSet {
|
|
240
256
|
set = /* @__PURE__ */ new Set();
|
|
@@ -365,6 +381,8 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
365
381
|
// EC-4: serialize concurrent _dispatchInbound calls.
|
|
366
382
|
dispatchQueue = Promise.resolve();
|
|
367
383
|
pollTimer;
|
|
384
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
385
|
+
cursor;
|
|
368
386
|
constructor(opts) {
|
|
369
387
|
super();
|
|
370
388
|
for (const k of ["address", "password", "imapHost", "smtpHost"]) {
|
|
@@ -405,13 +423,13 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
405
423
|
});
|
|
406
424
|
await this.smtp.verify();
|
|
407
425
|
await this.imap.connect();
|
|
426
|
+
await this._establishCursor(this.imap);
|
|
408
427
|
if (this.imap.supportsIdle()) {
|
|
409
428
|
await this.imap.startIdle(() => {
|
|
410
429
|
void this._drainUnseen().catch(reportDrainFailure);
|
|
411
430
|
});
|
|
412
|
-
|
|
431
|
+
void this._drainUnseen().catch(reportDrainFailure);
|
|
413
432
|
} else {
|
|
414
|
-
await this._drainUnseen();
|
|
415
433
|
const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
416
434
|
this.pollTimer = setInterval(() => {
|
|
417
435
|
void this._drainUnseen().catch(reportDrainFailure);
|
|
@@ -446,8 +464,10 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
446
464
|
this.seenUids.clear();
|
|
447
465
|
this.threadStore.clear();
|
|
448
466
|
}
|
|
449
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the "one outbound transaction" locality.
|
|
450
467
|
async sendMessage(out) {
|
|
468
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
469
|
+
}
|
|
470
|
+
async sendText(out) {
|
|
451
471
|
if (out.text.length === 0) {
|
|
452
472
|
return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
|
|
453
473
|
}
|
|
@@ -460,14 +480,7 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
460
480
|
const to = out.channel.id;
|
|
461
481
|
const topicId = out.channel.topicId;
|
|
462
482
|
const context = topicId !== void 0 ? this.threadStore.lookup(topicId) : void 0;
|
|
463
|
-
|
|
464
|
-
let inReplyTo;
|
|
465
|
-
let references;
|
|
466
|
-
if (context !== void 0) {
|
|
467
|
-
subject = context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`;
|
|
468
|
-
inReplyTo = context.lastMessageId;
|
|
469
|
-
references = Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]));
|
|
470
|
-
}
|
|
483
|
+
const { subject, inReplyTo, references } = replyHeaders(context);
|
|
471
484
|
const from = this.options.fromName !== void 0 ? { name: this.options.fromName, address: this.options.address } : this.options.address;
|
|
472
485
|
try {
|
|
473
486
|
const base = {
|
|
@@ -479,16 +492,7 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
479
492
|
...references !== void 0 ? { references } : {}
|
|
480
493
|
};
|
|
481
494
|
const html = out.format === "markdown" || out.format === "html" ? htmlPartFor(out.text, out.format) : void 0;
|
|
482
|
-
|
|
483
|
-
try {
|
|
484
|
-
messageId = await this.smtp.send(html === void 0 ? base : { ...base, html });
|
|
485
|
-
} catch (err) {
|
|
486
|
-
if (html === void 0) throw err;
|
|
487
|
-
process.stderr.write(
|
|
488
|
-
"[gateway-email] the server rejected the html part; retrying with text only\n"
|
|
489
|
-
);
|
|
490
|
-
messageId = await this.smtp.send(base);
|
|
491
|
-
}
|
|
495
|
+
const messageId = await sendWithTextFallback(this.smtp, base, html);
|
|
492
496
|
return { ok: true, messageId };
|
|
493
497
|
} catch (err) {
|
|
494
498
|
return { ok: false, error: mapEmailError(err) };
|
|
@@ -500,21 +504,50 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
500
504
|
if (this.handler === handler) this.handler = void 0;
|
|
501
505
|
};
|
|
502
506
|
}
|
|
503
|
-
/**
|
|
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. */
|
|
504
523
|
async _drainUnseen() {
|
|
505
|
-
if (this.imap === void 0) return;
|
|
524
|
+
if (this.imap === void 0 || this.cursor === void 0) return;
|
|
525
|
+
const since = this.cursor.uid;
|
|
506
526
|
let messages = [];
|
|
507
527
|
try {
|
|
508
|
-
messages = await this.imap.fetchUnseen();
|
|
528
|
+
messages = await this.imap.fetchUnseen(since);
|
|
509
529
|
} catch (err) {
|
|
510
530
|
console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
|
|
511
531
|
return;
|
|
512
532
|
}
|
|
533
|
+
messages = messages.filter((m) => m.uid >= since);
|
|
513
534
|
for (const msg of messages) {
|
|
514
535
|
this._dispatchInbound(msg.uid, msg.source, msg.headers);
|
|
515
536
|
}
|
|
537
|
+
await this._advanceCursor(messages);
|
|
516
538
|
this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
|
|
517
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
|
+
}
|
|
518
551
|
/**
|
|
519
552
|
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
520
553
|
* Fire-and-forget: never throws; errors logged.
|
|
@@ -599,6 +632,26 @@ var EmailAdapter = class extends BasePlatformAdapter {
|
|
|
599
632
|
return this.runHandler(this.handler, event);
|
|
600
633
|
}
|
|
601
634
|
};
|
|
635
|
+
function replyHeaders(context) {
|
|
636
|
+
if (context === void 0) return { subject: "Message from agent" };
|
|
637
|
+
return {
|
|
638
|
+
subject: context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`,
|
|
639
|
+
inReplyTo: context.lastMessageId,
|
|
640
|
+
// EC-6: dedup the chain.
|
|
641
|
+
references: Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]))
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
async function sendWithTextFallback(smtp, base, html) {
|
|
645
|
+
try {
|
|
646
|
+
return await smtp.send(html === void 0 ? base : { ...base, html });
|
|
647
|
+
} catch (err) {
|
|
648
|
+
if (html === void 0) throw err;
|
|
649
|
+
process.stderr.write(
|
|
650
|
+
"[gateway-email] the server rejected the html part; retrying with text only\n"
|
|
651
|
+
);
|
|
652
|
+
return smtp.send(base);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
602
655
|
|
|
603
656
|
export { EmailAdapter, SeenUidSet, ThreadStore, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
|
604
657
|
//# 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/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,Y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CAAS,IAAA;AAAA,EACvB;AAAA,EACA,IAAI,gBAAA,GAA2B;AAC7B,IAAA,OAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC1B;AAAA;AAAA,EAEA,MAAM,mBAAA,GAAqC;AACzC,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,KAAK,YAAA,EAAa;AACxB,IAAA,MAAM,IAAA,CAAK,aAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAe,QACb,KAAA,EACgD;AAChD,IAAA,OAAO,IAAA,CAAK,UAAA,CAAW,IAAA,CAAK,OAAA,EAAS,KAAK,CAAA;AAAA,EAC5C;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 * 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 { SeenUidSet } from \"./seen-uids.js\";\nimport { type ISmtpClient, SmtpClient } from \"./smtp-client.js\";\nimport { ThreadStore } from \"./thread-store.js\";\nimport type { EmailAdapterOptions } from \"./types.js\";\n\nconst DEFAULT_POLL_INTERVAL_MS = 15_000;\n\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, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\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 // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: send orchestrates input validation + thread-context lookup + Re: prepend + EC-6 references dedup + From: formatting + SMTP-error mapping — each branch is a single-responsibility check; splitting hurts the \"one outbound transaction\" locality.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n if (!this.connected || this.smtp === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"EmailAdapter not connected.\" },\n };\n }\n const to = out.channel.id;\n const topicId = out.channel.topicId;\n const context = topicId !== undefined ? this.threadStore.lookup(topicId) : undefined;\n\n let subject = \"Message from agent\";\n let inReplyTo: string | undefined;\n let references: readonly string[] | undefined;\n if (context !== undefined) {\n subject = context.subject.startsWith(\"Re:\") ? context.subject : `Re: ${context.subject}`;\n inReplyTo = context.lastMessageId;\n // EC-6: dedup the chain.\n references = Array.from(new Set([...context.references, context.lastMessageId]));\n }\n\n const from =\n this.options.fromName !== undefined\n ? { name: this.options.fromName, address: this.options.address }\n : this.options.address;\n try {\n const 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 let messageId: string;\n try {\n messageId = await this.smtp.send(html === undefined ? base : { ...base, html });\n } catch (err) {\n // ADR-2: an undelivered message is worse than an unformatted one. A server that refuses\n // the html part still accepts the text one, and the recipient reading a plain-text\n // client would never have seen the difference. Only attempted when there WAS an html\n // part — otherwise this would retry a send that failed for some entirely other reason.\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 messageId = await this.smtp.send(base);\n }\n return { ok: true, messageId };\n } catch (err) {\n return { ok: false, error: mapEmailError(err) };\n }\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.handler = handler;\n // The guard is not decoration. Without it, onInbound(A) -> onInbound(B) ->\n // A's stale unsubscribe clears B, and inbound delivery stops permanently\n // with nothing logged. Email and Teams were the only two adapters of ten\n // missing it, and no test anywhere exercised the A->B->unsubA sequence.\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n /** @internal — drain UNSEEN once and dispatch each. */\n private async _drainUnseen(): Promise<void> {\n if (this.imap === undefined) return;\n let messages: FetchedMessage[] = [];\n try {\n messages = await this.imap.fetchUnseen();\n } catch (err) {\n console.error(\"[email] fetchUnseen failed:\", err instanceof Error ? err.message : err);\n return;\n }\n for (const msg of messages) {\n this._dispatchInbound(msg.uid, msg.source, msg.headers);\n }\n // Chain the flush behind this batch's dispatches rather than awaiting them\n // here: `connect()` calls this, and blocking it on a large backlog is the\n // slow-connect problem, not something to make worse.\n this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());\n }\n\n /**\n * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.\n * Fire-and-forget: never throws; errors logged.\n */\n private _dispatchInbound(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n this.dispatchQueue = this.dispatchQueue.then(() =>\n this._dispatchInboundInner(uid, rawBuffer, headers).catch((err) =>\n console.error(\"[email] dispatch error:\", err instanceof Error ? err.message : err),\n ),\n );\n return this.dispatchQueue;\n }\n\n private async _dispatchInboundInner(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n if (this.seenUids.has(uid)) return;\n this.seenUids.add(uid);\n\n try {\n await this._dispatchOrDrop(uid, rawBuffer, headers);\n } finally {\n // Every exit records, including the drops. A discarded message is finished\n // with, and leaving it UNSEEN means downloading and re-parsing it on\n // every drain forever — most of the 166-message backlog measured on the\n // live mailbox was old own-address probes being re-read and re-thrown-away.\n //\n // Recorded AFTER the attempt, not before: a crash in the window between\n // the two costs at most a duplicate of the single in-flight message,\n // where flagging first would lose it silently. Duplicates are visible and\n // apologisable; a support email nobody ever answers is neither.\n this.pendingSeen.add(uid);\n }\n }\n\n /**\n * Flush the batch to the server. Never throws — a mailbox we cannot flag is\n * not worth dropping mail over; those UIDs simply come back on the next drain.\n */\n private async _flushSeen(): Promise<void> {\n if (this.imap === undefined || this.pendingSeen.size === 0) return;\n const uids = [...this.pendingSeen];\n this.pendingSeen.clear();\n try {\n await this.imap.markSeen(uids);\n } catch (err) {\n console.error(\n `[email] could not flag ${uids.length} message(s) \\\\Seen (they will be re-delivered):`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n private async _dispatchOrDrop(\n uid: number,\n rawBuffer: Buffer,\n headers: Map<string, string>,\n ): Promise<void> {\n const event = await normalizeEmail(rawBuffer, {\n botAddress: this.options.address,\n ...(this.options.maxBodyChars !== undefined\n ? { maxBodyChars: this.options.maxBodyChars }\n : {}),\n });\n\n // EC-1 (CRITICAL): drop own-address loopback BEFORE anything else.\n if (event.email.fromAddress === this.options.address.toLowerCase()) {\n console.warn(`[email] dropped own-address loopback (uid=${uid})`);\n return;\n }\n // D332: drop automated senders unless explicitly allowed.\n if (\n this.options.allowAutomated !== true &&\n isAutomatedSender(event.email.fromAddress, headers)\n ) {\n console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);\n return;\n }\n // D333 + EC-3: enforce allowlist (both sides normalized via extractAddr).\n if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {\n console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);\n return;\n }\n // Record thread context for outbound reciprocity.\n this.threadStore.recordFromInbound(event);\n\n if (this.handler !== undefined) await this.handler(event);\n }\n\n /** Test seams. @internal */\n get _seenUidsSize(): number {\n return this.seenUids.size;\n }\n get _threadStoreSize(): number {\n return this.threadStore.size;\n }\n /** Test seam — wait for queued dispatches to drain. @internal */\n async _drainDispatchQueue(): Promise<void> {\n await this.dispatchQueue;\n }\n /** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */\n async _drainNow(): Promise<void> {\n await this._drainUnseen();\n await this.dispatchQueue;\n }\n\n /**\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"]}
|
|
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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UA,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 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, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-email",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"types": "./dist/index.d.cts",
|
|
26
26
|
"default": "./dist/index.cjs"
|
|
27
27
|
}
|
|
28
|
-
}
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
29
30
|
},
|
|
30
31
|
"sideEffects": false,
|
|
31
32
|
"files": [
|
|
@@ -38,7 +39,7 @@
|
|
|
38
39
|
"@theokit/gateway": ">=0.9.0 <1.0.0",
|
|
39
40
|
"imapflow": "^1.0.0",
|
|
40
41
|
"mailparser": "^3.0.0",
|
|
41
|
-
"nodemailer": "^
|
|
42
|
+
"nodemailer": "^10.0.6"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
45
|
"@stryker-mutator/core": "10",
|
|
@@ -48,17 +49,31 @@
|
|
|
48
49
|
"@types/nodemailer": "^8.0.1",
|
|
49
50
|
"imapflow": "^1.7.6",
|
|
50
51
|
"mailparser": "^3.9.17",
|
|
51
|
-
"nodemailer": "^
|
|
52
|
+
"nodemailer": "^10.0.6",
|
|
52
53
|
"tsup": "^8.5.0",
|
|
53
54
|
"typescript": "5.9.3",
|
|
54
55
|
"vitest": "^4.1.11",
|
|
55
56
|
"zod": "^4.0.0",
|
|
56
|
-
"@theokit/gateway": "0.
|
|
57
|
+
"@theokit/gateway": "0.15.0"
|
|
57
58
|
},
|
|
58
59
|
"publishConfig": {
|
|
59
60
|
"access": "public",
|
|
60
61
|
"provenance": true
|
|
61
62
|
},
|
|
63
|
+
"bugs": {
|
|
64
|
+
"url": "https://github.com/usetheokit/theokit-gateways/issues"
|
|
65
|
+
},
|
|
66
|
+
"homepage": "https://github.com/usetheokit/theokit-gateways/tree/main/packages/gateway-email#readme",
|
|
67
|
+
"keywords": [
|
|
68
|
+
"theokit",
|
|
69
|
+
"gateway",
|
|
70
|
+
"email",
|
|
71
|
+
"platform",
|
|
72
|
+
"adapter",
|
|
73
|
+
"community-standard",
|
|
74
|
+
"stack",
|
|
75
|
+
"nodemailer"
|
|
76
|
+
],
|
|
62
77
|
"scripts": {
|
|
63
78
|
"build": "tsup",
|
|
64
79
|
"typecheck": "tsc --noEmit",
|