@theokit/gateway-email 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bc799e9: Export `matrixChannel`, `mattermostChannel` and `emailChannel`: `ChannelDescriptor`s with `MATRIX_*`, `MATTERMOST_*` and `EMAIL_*` environment bindings for `createChannels` and `configFromEnv`. The peer range on `@theokit/gateway` is now `>=0.21.0`.
8
+
9
+ ### Patch Changes
10
+
11
+ - fc94485: The email, IRC, Matrix, Nextcloud Talk and Signal channel descriptors build their configuration fields with the shared `field` helper, and email and Matrix read their env-string numbers and booleans through one shared reader instead of two copies. The descriptors and the values they accept are unchanged.
12
+
13
+ ## 0.5.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 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.
18
+
3
19
  ## 0.4.0
4
20
 
5
21
  ### Minor Changes
package/README.md CHANGED
@@ -9,3 +9,32 @@ Status: **v0.1.0 pre-release**. Pre-1.0 contract per ADR D338 — breaking chang
9
9
  **IMAP IDLE.** The adapter polls the mailbox over its own connection; messages reach `onInbound`
10
10
  once `connect()` resolves. There is no webhook to host and nothing for an application to
11
11
  authenticate.
12
+
13
+ ## Channel descriptor
14
+
15
+ `emailChannel` describes the channel as data for `createChannels` and `configFromEnv` from `@theokit/gateway`. Its transport is `socket`.
16
+
17
+ ```ts
18
+ import { configFromEnv, createChannels } from "@theokit/gateway";
19
+ import { emailChannel } from "@theokit/gateway-email";
20
+
21
+ const { config, missing, secrets } = configFromEnv(emailChannel, process.env, "APP_");
22
+ const { adapters, rejected } = createChannels([{ descriptor: emailChannel, config, envPrefix: "APP_" }]);
23
+ ```
24
+
25
+ | Config key | Env name | Required | Secret |
26
+ | --- | --- | --- | --- |
27
+ | `address` | `EMAIL_ADDRESS` | yes | no |
28
+ | `password` | `EMAIL_PASSWORD` | yes | yes |
29
+ | `imapHost` | `EMAIL_IMAP_HOST` | yes | no |
30
+ | `imapPort` | `EMAIL_IMAP_PORT` | no | no |
31
+ | `smtpHost` | `EMAIL_SMTP_HOST` | yes | no |
32
+ | `smtpPort` | `EMAIL_SMTP_PORT` | no | no |
33
+ | `fromName` | `EMAIL_FROM_NAME` | no | no |
34
+ | `allowedSenders` | `EMAIL_ALLOWED_SENDERS` | no | no |
35
+ | `allowAutomated` | `EMAIL_ALLOW_AUTOMATED` | no | no |
36
+ | `pollIntervalMs` | `EMAIL_POLL_INTERVAL_MS` | no | no |
37
+ | `maxBodyChars` | `EMAIL_MAX_BODY_CHARS` | no | no |
38
+ | `cursorStore` | none (object) | no | no |
39
+
40
+ The `APP_` prefix is the app's choice. A value of the wrong type throws `invalid_config` naming the key; a list may be an array or a comma-separated string, a boolean `true`/`false` or the same strings, a number a number or a digit string.
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
- for await (const raw of this.client.fetch({ seen: false }, {
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
@@ -376,6 +383,8 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
376
383
  // EC-4: serialize concurrent _dispatchInbound calls.
377
384
  dispatchQueue = Promise.resolve();
378
385
  pollTimer;
386
+ /** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
387
+ cursor;
379
388
  constructor(opts) {
380
389
  super();
381
390
  for (const k of ["address", "password", "imapHost", "smtpHost"]) {
@@ -416,13 +425,13 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
416
425
  });
417
426
  await this.smtp.verify();
418
427
  await this.imap.connect();
428
+ await this._establishCursor(this.imap);
419
429
  if (this.imap.supportsIdle()) {
420
430
  await this.imap.startIdle(() => {
421
431
  void this._drainUnseen().catch(reportDrainFailure);
422
432
  });
423
- await this._drainUnseen();
433
+ void this._drainUnseen().catch(reportDrainFailure);
424
434
  } else {
425
- await this._drainUnseen();
426
435
  const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
427
436
  this.pollTimer = setInterval(() => {
428
437
  void this._drainUnseen().catch(reportDrainFailure);
@@ -497,21 +506,50 @@ var EmailAdapter = class extends gateway.BasePlatformAdapter {
497
506
  if (this.handler === handler) this.handler = void 0;
498
507
  };
499
508
  }
500
- /** @internal — drain UNSEEN once and dispatch each. */
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. */
501
525
  async _drainUnseen() {
502
- if (this.imap === void 0) return;
526
+ if (this.imap === void 0 || this.cursor === void 0) return;
527
+ const since = this.cursor.uid;
503
528
  let messages = [];
504
529
  try {
505
- messages = await this.imap.fetchUnseen();
530
+ messages = await this.imap.fetchUnseen(since);
506
531
  } catch (err) {
507
532
  console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
508
533
  return;
509
534
  }
535
+ messages = messages.filter((m) => m.uid >= since);
510
536
  for (const msg of messages) {
511
537
  this._dispatchInbound(msg.uid, msg.source, msg.headers);
512
538
  }
539
+ await this._advanceCursor(messages);
513
540
  this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
514
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
+ }
515
553
  /**
516
554
  * EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
517
555
  * Fire-and-forget: never throws; errors logged.
@@ -617,9 +655,141 @@ async function sendWithTextFallback(smtp, base, html) {
617
655
  }
618
656
  }
619
657
 
658
+ // ../../shared/channel-config-field.ts
659
+ var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
660
+
661
+ // ../../shared/env-value-readers.ts
662
+ function readEnvNumber(invalid2, config, key) {
663
+ const value = config[key];
664
+ if (value === void 0) return void 0;
665
+ if (typeof value === "number" && Number.isFinite(value)) return value;
666
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
667
+ const parsed = Number(value.trim());
668
+ if (Number.isFinite(parsed)) return parsed;
669
+ }
670
+ throw invalid2(key, "a number or a digit string");
671
+ }
672
+ function readEnvBoolean(invalid2, config, key) {
673
+ const value = config[key];
674
+ if (value === void 0) return void 0;
675
+ if (value === true || value === "true") return true;
676
+ if (value === false || value === "false") return false;
677
+ throw invalid2(key, 'a boolean or the string "true" or "false"');
678
+ }
679
+ function envValueReaders(invalid2) {
680
+ return {
681
+ number: (config, key) => readEnvNumber(invalid2, config, key),
682
+ boolean: (config, key) => readEnvBoolean(invalid2, config, key)
683
+ };
684
+ }
685
+
686
+ // src/channel.ts
687
+ var readers = gateway.channelConfigReaders("gateway-email");
688
+ var { invalid } = readers;
689
+ var isAbsent = (value) => value === void 0;
690
+ var read = {
691
+ ...envValueReaders(invalid),
692
+ string: readers.requiredString,
693
+ optionalString: (config, key) => config[key] === void 0 ? void 0 : readers.requiredString(config, key),
694
+ list(config, key) {
695
+ const value = config[key];
696
+ if (value === void 0) return void 0;
697
+ if (typeof value === "string") {
698
+ return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
699
+ }
700
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
701
+ throw invalid(key, "an array of strings or a comma-separated string");
702
+ }
703
+ };
704
+ function readCursorStore(config) {
705
+ const value = config.cursorStore;
706
+ if (isAbsent(value)) return void 0;
707
+ const store = value;
708
+ if (typeof value !== "object" || typeof store?.load !== "function" || typeof store.save !== "function") {
709
+ throw invalid("cursorStore", "an object with load and save functions");
710
+ }
711
+ return value;
712
+ }
713
+ var CONFIG = [
714
+ field(
715
+ "address",
716
+ "EMAIL_ADDRESS",
717
+ "Email address the bot listens on; also the From address of outbound mail."
718
+ ),
719
+ field("password", "EMAIL_PASSWORD", "Password or app password for the IMAP and SMTP login.", {
720
+ secret: true
721
+ }),
722
+ field("imapHost", "EMAIL_IMAP_HOST", "IMAP server host name."),
723
+ field("imapPort", "EMAIL_IMAP_PORT", "IMAP server port.", { required: false }),
724
+ field("smtpHost", "EMAIL_SMTP_HOST", "SMTP server host name."),
725
+ field("smtpPort", "EMAIL_SMTP_PORT", "SMTP server port.", { required: false }),
726
+ field("fromName", "EMAIL_FROM_NAME", "Display name for outbound mail.", { required: false }),
727
+ field(
728
+ "allowedSenders",
729
+ "EMAIL_ALLOWED_SENDERS",
730
+ "Sender addresses allowed through, as a list or comma-separated string.",
731
+ { required: false }
732
+ ),
733
+ field(
734
+ "allowAutomated",
735
+ "EMAIL_ALLOW_AUTOMATED",
736
+ "When true, automated senders (no-reply, bulk mail) are not filtered out.",
737
+ { required: false }
738
+ ),
739
+ field("pollIntervalMs", "EMAIL_POLL_INTERVAL_MS", "Milliseconds between mailbox polls.", {
740
+ required: false
741
+ }),
742
+ field("maxBodyChars", "EMAIL_MAX_BODY_CHARS", "Longest inbound body kept, in characters.", {
743
+ required: false
744
+ }),
745
+ {
746
+ key: "cursorStore",
747
+ required: false,
748
+ secret: false,
749
+ description: "Programmatic store that persists the IMAP cursor; no env binding."
750
+ }
751
+ ];
752
+ var emailChannel = {
753
+ platform: "email",
754
+ transport: "socket",
755
+ senderIdentity: {
756
+ unauthenticated: "an email From header is written by the sender and can be forged"
757
+ },
758
+ config: CONFIG,
759
+ create(config) {
760
+ const address = read.string(config, "address");
761
+ const password = read.string(config, "password");
762
+ const imapHost = read.string(config, "imapHost");
763
+ const smtpHost = read.string(config, "smtpHost");
764
+ const imapPort = read.number(config, "imapPort");
765
+ const smtpPort = read.number(config, "smtpPort");
766
+ const fromName = read.optionalString(config, "fromName");
767
+ const allowedSenders = read.list(config, "allowedSenders");
768
+ const allowAutomated = read.boolean(config, "allowAutomated");
769
+ const pollIntervalMs = read.number(config, "pollIntervalMs");
770
+ const maxBodyChars = read.number(config, "maxBodyChars");
771
+ const cursorStore = readCursorStore(config);
772
+ return new EmailAdapter({
773
+ address,
774
+ password,
775
+ imapHost,
776
+ smtpHost,
777
+ ...imapPort === void 0 ? {} : { imapPort },
778
+ ...smtpPort === void 0 ? {} : { smtpPort },
779
+ ...fromName === void 0 ? {} : { fromName },
780
+ ...allowedSenders === void 0 ? {} : { allowedSenders },
781
+ ...allowAutomated === void 0 ? {} : { allowAutomated },
782
+ ...pollIntervalMs === void 0 ? {} : { pollIntervalMs },
783
+ ...maxBodyChars === void 0 ? {} : { maxBodyChars },
784
+ ...cursorStore === void 0 ? {} : { cursorStore }
785
+ });
786
+ }
787
+ };
788
+
620
789
  exports.EmailAdapter = EmailAdapter;
621
790
  exports.SeenUidSet = SeenUidSet;
622
791
  exports.ThreadStore = ThreadStore;
792
+ exports.emailChannel = emailChannel;
623
793
  exports.extractAddr = extractAddr;
624
794
  exports.isAllowedSender = isAllowedSender;
625
795
  exports.isAutomatedSender = isAutomatedSender;