@pithy-sh/email 0.1.2 → 0.1.3

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.
Files changed (176) hide show
  1. package/dist/analytics.d.ts +19 -0
  2. package/dist/analytics.d.ts.map +1 -0
  3. package/dist/analytics.js +13 -0
  4. package/dist/audit/actions.d.ts +45 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +45 -0
  7. package/dist/bounce/classify.d.ts +38 -0
  8. package/dist/bounce/classify.d.ts.map +1 -0
  9. package/dist/bounce/classify.js +46 -0
  10. package/dist/bounce/handler.d.ts +32 -0
  11. package/dist/bounce/handler.d.ts.map +1 -0
  12. package/dist/bounce/handler.js +81 -0
  13. package/dist/capability.d.ts +158 -0
  14. package/dist/capability.d.ts.map +1 -0
  15. package/dist/capability.js +255 -0
  16. package/dist/crypto/signingKey.d.ts +36 -0
  17. package/dist/crypto/signingKey.d.ts.map +1 -0
  18. package/dist/crypto/signingKey.js +36 -0
  19. package/dist/crypto/token.d.ts +47 -0
  20. package/dist/crypto/token.d.ts.map +1 -0
  21. package/dist/crypto/token.js +99 -0
  22. package/dist/data/emailEvent.d.ts +28 -0
  23. package/dist/data/emailEvent.d.ts.map +1 -0
  24. package/dist/data/emailEvent.js +22 -0
  25. package/dist/data/emailJob.d.ts +76 -0
  26. package/dist/data/emailJob.d.ts.map +1 -0
  27. package/dist/data/emailJob.js +62 -0
  28. package/dist/data/emailSuppression.d.ts +23 -0
  29. package/dist/data/emailSuppression.d.ts.map +1 -0
  30. package/dist/data/emailSuppression.js +21 -0
  31. package/dist/data/enums.d.ts +76 -0
  32. package/dist/data/enums.d.ts.map +1 -0
  33. package/dist/data/enums.js +65 -0
  34. package/dist/data/tables.d.ts +114 -0
  35. package/dist/data/tables.d.ts.map +1 -0
  36. package/dist/data/tables.js +30 -0
  37. package/dist/error/errors.d.ts +60 -0
  38. package/dist/error/errors.d.ts.map +1 -0
  39. package/dist/error/errors.js +82 -0
  40. package/dist/http/callbacks.d.ts +21 -0
  41. package/dist/http/callbacks.d.ts.map +1 -0
  42. package/dist/http/callbacks.js +110 -0
  43. package/dist/http/guards.d.ts +99 -0
  44. package/dist/http/guards.d.ts.map +1 -0
  45. package/dist/http/guards.js +144 -0
  46. package/dist/http/responses.d.ts +295 -0
  47. package/dist/http/responses.d.ts.map +1 -0
  48. package/dist/http/responses.js +115 -0
  49. package/dist/http/routes.d.ts +71 -0
  50. package/dist/http/routes.d.ts.map +1 -0
  51. package/dist/http/routes.js +292 -0
  52. package/dist/http/schemas.d.ts +90 -0
  53. package/dist/http/schemas.d.ts.map +1 -0
  54. package/dist/http/schemas.js +91 -0
  55. package/dist/http/view.d.ts +78 -0
  56. package/dist/http/view.d.ts.map +1 -0
  57. package/dist/http/view.js +130 -0
  58. package/dist/index.d.ts +46 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +11 -0
  61. package/dist/jobs/read.d.ts +191 -0
  62. package/dist/jobs/read.d.ts.map +1 -0
  63. package/dist/jobs/read.js +143 -0
  64. package/dist/jobs/retry.d.ts +99 -0
  65. package/dist/jobs/retry.d.ts.map +1 -0
  66. package/dist/jobs/retry.js +67 -0
  67. package/dist/migrations/0001_init.d.ts +32 -0
  68. package/dist/migrations/0001_init.d.ts.map +1 -0
  69. package/dist/migrations/0001_init.js +60 -0
  70. package/dist/migrations/0001_suppressions.d.ts +10 -0
  71. package/dist/migrations/0001_suppressions.d.ts.map +1 -0
  72. package/dist/migrations/0001_suppressions.js +20 -0
  73. package/dist/provision/devDelivery.d.ts +32 -0
  74. package/dist/provision/devDelivery.d.ts.map +1 -0
  75. package/dist/provision/devDelivery.js +37 -0
  76. package/dist/provision/hostCatalogs.d.ts +10 -0
  77. package/dist/provision/hostCatalogs.d.ts.map +1 -0
  78. package/dist/provision/hostCatalogs.js +78 -0
  79. package/dist/provision/provisionEmail.d.ts +143 -0
  80. package/dist/provision/provisionEmail.d.ts.map +1 -0
  81. package/dist/provision/provisionEmail.js +118 -0
  82. package/dist/provision/resolveEmailConfig.d.ts +122 -0
  83. package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
  84. package/dist/provision/resolveEmailConfig.js +124 -0
  85. package/dist/provision/settingsCheck.d.ts +40 -0
  86. package/dist/provision/settingsCheck.d.ts.map +1 -0
  87. package/dist/provision/settingsCheck.js +138 -0
  88. package/dist/send/batchIdentity.d.ts +42 -0
  89. package/dist/send/batchIdentity.d.ts.map +1 -0
  90. package/dist/send/batchIdentity.js +46 -0
  91. package/dist/send/enqueue.d.ts +216 -0
  92. package/dist/send/enqueue.d.ts.map +1 -0
  93. package/dist/send/enqueue.js +153 -0
  94. package/dist/send/errorMapping.d.ts +27 -0
  95. package/dist/send/errorMapping.d.ts.map +1 -0
  96. package/dist/send/errorMapping.js +52 -0
  97. package/dist/send/events.d.ts +15 -0
  98. package/dist/send/events.d.ts.map +1 -0
  99. package/dist/send/events.js +17 -0
  100. package/dist/send/fromComposition.d.ts +47 -0
  101. package/dist/send/fromComposition.d.ts.map +1 -0
  102. package/dist/send/fromComposition.js +53 -0
  103. package/dist/send/retryPolicy.d.ts +32 -0
  104. package/dist/send/retryPolicy.d.ts.map +1 -0
  105. package/dist/send/retryPolicy.js +39 -0
  106. package/dist/send/runSend.d.ts +106 -0
  107. package/dist/send/runSend.d.ts.map +1 -0
  108. package/dist/send/runSend.js +218 -0
  109. package/dist/send/sendAt.d.ts +6 -0
  110. package/dist/send/sendAt.d.ts.map +1 -0
  111. package/dist/send/sendAt.js +62 -0
  112. package/dist/send/sender.d.ts +42 -0
  113. package/dist/send/sender.d.ts.map +1 -0
  114. package/dist/send/sender.js +0 -0
  115. package/dist/send/senderBinding.d.ts +44 -0
  116. package/dist/send/senderBinding.d.ts.map +1 -0
  117. package/dist/send/senderBinding.js +21 -0
  118. package/dist/send/suppression.d.ts +93 -0
  119. package/dist/send/suppression.d.ts.map +1 -0
  120. package/dist/send/suppression.js +132 -0
  121. package/dist/templates/engine.d.ts +109 -0
  122. package/dist/templates/engine.d.ts.map +1 -0
  123. package/dist/templates/engine.js +258 -0
  124. package/dist/templates/messages.d.ts +94 -0
  125. package/dist/templates/messages.d.ts.map +1 -0
  126. package/dist/templates/messages.es.d.ts +29 -0
  127. package/dist/templates/messages.es.d.ts.map +1 -0
  128. package/dist/templates/messages.es.js +82 -0
  129. package/dist/templates/messages.js +266 -0
  130. package/dist/templates/partials.d.ts +5 -0
  131. package/dist/templates/partials.d.ts.map +1 -0
  132. package/dist/templates/partials.js +59 -0
  133. package/dist/templates/precompiled.generated.d.ts +266 -0
  134. package/dist/templates/precompiled.generated.d.ts.map +1 -0
  135. package/dist/templates/precompiled.generated.js +4039 -0
  136. package/dist/templates/registry.d.ts +118 -0
  137. package/dist/templates/registry.d.ts.map +1 -0
  138. package/dist/templates/registry.js +323 -0
  139. package/dist/templates/samples.d.ts +7 -0
  140. package/dist/templates/samples.d.ts.map +1 -0
  141. package/dist/templates/samples.js +98 -0
  142. package/dist/templates/severity.d.ts +40 -0
  143. package/dist/templates/severity.d.ts.map +1 -0
  144. package/dist/templates/severity.js +81 -0
  145. package/dist/templates/theme.d.ts +193 -0
  146. package/dist/templates/theme.d.ts.map +1 -0
  147. package/dist/templates/theme.js +168 -0
  148. package/dist/version.generated.d.ts +5 -0
  149. package/dist/version.generated.d.ts.map +1 -0
  150. package/dist/version.generated.js +7 -0
  151. package/dist/workflows/hostApp.d.ts +33 -0
  152. package/dist/workflows/hostApp.d.ts.map +1 -0
  153. package/dist/workflows/hostApp.js +19 -0
  154. package/dist/workflows/hostEnv.d.ts +129 -0
  155. package/dist/workflows/hostEnv.d.ts.map +1 -0
  156. package/dist/workflows/hostEnv.js +147 -0
  157. package/dist/workflows/instanceLiveness.d.ts +3 -0
  158. package/dist/workflows/instanceLiveness.d.ts.map +1 -0
  159. package/dist/workflows/instanceLiveness.js +37 -0
  160. package/dist/workflows/instances.d.ts +18 -0
  161. package/dist/workflows/instances.d.ts.map +1 -0
  162. package/dist/workflows/instances.js +0 -0
  163. package/dist/workflows/params.d.ts +23 -0
  164. package/dist/workflows/params.d.ts.map +1 -0
  165. package/dist/workflows/params.js +21 -0
  166. package/dist/workflows/scheduler.d.ts +82 -0
  167. package/dist/workflows/scheduler.d.ts.map +1 -0
  168. package/dist/workflows/scheduler.js +111 -0
  169. package/dist/workflows/sendBatch.d.ts +85 -0
  170. package/dist/workflows/sendBatch.d.ts.map +1 -0
  171. package/dist/workflows/sendBatch.js +50 -0
  172. package/dist/workflows/worker.d.ts +100 -0
  173. package/dist/workflows/worker.d.ts.map +1 -0
  174. package/dist/workflows/worker.js +117 -0
  175. package/package.json +22 -11
  176. package/src/version.generated.ts +1 -1
@@ -0,0 +1,19 @@
1
+ import { EmailEventType } from "./data/enums";
2
+ import type { EmailDatabase } from "./data/tables";
3
+ /**
4
+ * Per-batch email analytics, read from `pithy_email_events` in the app database. A "batch" is a
5
+ * `campaignId` (set on marketing sends and any send that passes one), so a single grouped query yields
6
+ * how many were sent, opened, clicked, bounced, complained, and unsubscribed.
7
+ *
8
+ * Events live in the **per-environment** app DB and are written where the action happens: `sent` by the
9
+ * send Workflow, `open`/`click`/`unsubscribe` by the callbacks (whose links point at the sending
10
+ * environment's worker), and `bounce`/`complaint` by the inbound handler. So a production campaign's
11
+ * full funnel lands in production's app DB; cross-environment bounce attribution is platform-limited
12
+ * (one inbound worker per domain), so feature/staging see their own opens/clicks/unsubscribes but not
13
+ * asynchronously-routed bounces.
14
+ */
15
+ /** Event counts for a campaign, one per `EmailEventType`. Types with no events are `0`. */
16
+ export type CampaignStats = Record<EmailEventType, number>;
17
+ /** Aggregate the events recorded for one campaign into per-type counts. */
18
+ export declare function campaignStats(db: EmailDatabase, campaignId: string): Promise<CampaignStats>;
19
+ //# sourceMappingURL=analytics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../src/analytics.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;;;;;;GAWG;AAEH,2FAA2F;AAC3F,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;AAK3D,2EAA2E;AAC3E,wBAAsB,aAAa,CAAC,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAYjG"}
@@ -0,0 +1,13 @@
1
+ import { EmailEventType } from "./data/enums.js";
2
+ //#region src/analytics.ts
3
+ /** Every event type at zero — derived from the enum so a new `EmailEventType` can't be forgotten here. */
4
+ const ZERO = Object.fromEntries(EmailEventType.options.map((type) => [type, 0]));
5
+ /** Aggregate the events recorded for one campaign into per-type counts. */
6
+ async function campaignStats(db, campaignId) {
7
+ const rows = await db.selectFrom("pithyEmailEvents").select(["type"]).select((eb) => eb.fn.countAll().as("count")).where("campaignId", "=", campaignId).groupBy("type").execute();
8
+ const stats = { ...ZERO };
9
+ for (const row of rows) stats[row.type] = Number(row.count);
10
+ return stats;
11
+ }
12
+ //#endregion
13
+ export { campaignStats };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The audit actions this capability emits, through the core `emit()` seam.
3
+ *
4
+ * **Reads are audited here, not only writes.** The job log is a list of who was mailed what and when,
5
+ * and the suppression list is every address in the project that ever bounced, complained, or opted
6
+ * out — reading either is a disclosure of other people's personal data, and a management credential
7
+ * quietly paging through one of them at three in the morning is exactly the event an adopter needs to
8
+ * be able to find afterwards. "Which operator read the suppression list on the twelfth" is a question
9
+ * with an answer, and these are what make it one.
10
+ *
11
+ * Emitted with `c.var.emit`, never by importing `@pithy-sh/audit` — the seam is always present
12
+ * (`noopEmit` when no audit capability is composed), so there is no null check and no hard dependency.
13
+ * Identifiers, counts, and filters in metadata: never a rendered subject, never a template payload.
14
+ */
15
+ export declare const EmailAuditActions: {
16
+ /**
17
+ * A page of the job log was read. Recorded with the filter and the page size, not the rows — the
18
+ * point is that somebody read *some* of it, and how much.
19
+ */
20
+ readonly jobsRead: "email/jobs_read";
21
+ /** One job was opened in full, which is where a recipient's whole address is disclosed. */
22
+ readonly jobRead: "email/job_read";
23
+ /**
24
+ * A failed job was put back in the queue.
25
+ *
26
+ * The one operation here that sends mail to a real person, so it is recorded at `warning` with the
27
+ * job id and the status it came from.
28
+ */
29
+ readonly jobRetried: "email/job_retried";
30
+ /** A page of the global suppression list was read — addresses, in bulk, across every environment. */
31
+ readonly suppressionsRead: "email/suppressions_read";
32
+ /** An address was blocked by hand. Silent to the recipient, so the trail is the only record. */
33
+ readonly suppressionAdded: "email/suppression_added";
34
+ /**
35
+ * An address was unblocked.
36
+ *
37
+ * The most dangerous line in this file: it re-opens sending to somebody who hard-bounced, reported
38
+ * spam, or asked to be left alone. Recorded at `warning` with the reason the row carried, so the
39
+ * trail says what was undone and not merely that something was.
40
+ */
41
+ readonly suppressionRemoved: "email/suppression_removed";
42
+ };
43
+ /** One of the email capability's audit actions. */
44
+ export type EmailAuditAction = (typeof EmailAuditActions)[keyof typeof EmailAuditActions];
45
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/audit/actions.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iBAAiB;IAC5B;;;OAGG;aACH,QAAQ,EAAE,iBAAiB;IAC3B,2FAA2F;aAC3F,OAAO,EAAE,gBAAgB;IACzB;;;;;OAKG;aACH,UAAU,EAAE,mBAAmB;IAC/B,qGAAqG;aACrG,gBAAgB,EAAE,yBAAyB;IAC3C,gGAAgG;aAChG,gBAAgB,EAAE,yBAAyB;IAC3C;;;;;;OAMG;aACH,kBAAkB,EAAE,2BAA2B;CACvC,CAAC;AAEX,mDAAmD;AACnD,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC"}
@@ -0,0 +1,45 @@
1
+ //#region src/audit/actions.ts
2
+ /**
3
+ * The audit actions this capability emits, through the core `emit()` seam.
4
+ *
5
+ * **Reads are audited here, not only writes.** The job log is a list of who was mailed what and when,
6
+ * and the suppression list is every address in the project that ever bounced, complained, or opted
7
+ * out — reading either is a disclosure of other people's personal data, and a management credential
8
+ * quietly paging through one of them at three in the morning is exactly the event an adopter needs to
9
+ * be able to find afterwards. "Which operator read the suppression list on the twelfth" is a question
10
+ * with an answer, and these are what make it one.
11
+ *
12
+ * Emitted with `c.var.emit`, never by importing `@pithy-sh/audit` — the seam is always present
13
+ * (`noopEmit` when no audit capability is composed), so there is no null check and no hard dependency.
14
+ * Identifiers, counts, and filters in metadata: never a rendered subject, never a template payload.
15
+ */
16
+ const EmailAuditActions = {
17
+ /**
18
+ * A page of the job log was read. Recorded with the filter and the page size, not the rows — the
19
+ * point is that somebody read *some* of it, and how much.
20
+ */
21
+ jobsRead: "email/jobs_read",
22
+ /** One job was opened in full, which is where a recipient's whole address is disclosed. */
23
+ jobRead: "email/job_read",
24
+ /**
25
+ * A failed job was put back in the queue.
26
+ *
27
+ * The one operation here that sends mail to a real person, so it is recorded at `warning` with the
28
+ * job id and the status it came from.
29
+ */
30
+ jobRetried: "email/job_retried",
31
+ /** A page of the global suppression list was read — addresses, in bulk, across every environment. */
32
+ suppressionsRead: "email/suppressions_read",
33
+ /** An address was blocked by hand. Silent to the recipient, so the trail is the only record. */
34
+ suppressionAdded: "email/suppression_added",
35
+ /**
36
+ * An address was unblocked.
37
+ *
38
+ * The most dangerous line in this file: it re-opens sending to somebody who hard-bounced, reported
39
+ * spam, or asked to be left alone. Recorded at `warning` with the reason the row carried, so the
40
+ * trail says what was undone and not merely that something was.
41
+ */
42
+ suppressionRemoved: "email/suppression_removed"
43
+ };
44
+ //#endregion
45
+ export { EmailAuditActions };
@@ -0,0 +1,38 @@
1
+ import type { BounceType } from "../data/enums";
2
+ /**
3
+ * Classify an inbound message as a bounce, complaint, auto-reply, or something to ignore. With the
4
+ * modern Email Service, hard bounces are auto-suppressed at the platform and surfaced synchronously on
5
+ * send; this handles delivery-status notifications (DSNs) and feedback-loop complaints (ARF) that are
6
+ * *routed back* to the worker, plus vacation auto-replies (a deliberate no-op).
7
+ *
8
+ * The classifier is pure and works on the already-parsed pieces of the message — its headers and the
9
+ * raw body text — so it is unit-testable without the Workers runtime. Identification is best-effort:
10
+ * the failed recipient comes from the DSN's `Final-Recipient`, and the originating job is matched later
11
+ * by the original `Message-ID` against the stored send `messageId` (no custom VERP return path, which
12
+ * the simple send binding cannot set).
13
+ */
14
+ /** What an inbound message turned out to be. `ignore` and `auto_reply` produce no side effects. */
15
+ export interface InboundClassification {
16
+ /** The classification — `ignore` for anything that isn't a recognized bounce/complaint/auto-reply. */
17
+ type: BounceType | "ignore";
18
+ /** The affected recipient address, when the message identifies one. */
19
+ recipient?: string;
20
+ /** The SMTP/DSN status or diagnostic code, for the row and the event detail. */
21
+ code?: string;
22
+ /** The original message's `Message-ID`, used to match the job that bounced. */
23
+ originalMessageId?: string;
24
+ }
25
+ /** The inbound message's parsed pieces the classifier needs. */
26
+ export interface InboundMessage {
27
+ /** The top-level `Content-Type` header value (carries `report-type` for DSN/ARF). */
28
+ contentType?: string;
29
+ /** The `Auto-Submitted` header value, if present. */
30
+ autoSubmitted?: string;
31
+ /** Whether any auto-responder header (`X-Autoreply`, `X-Autorespond`) is present. */
32
+ autoReplyHeader?: boolean;
33
+ /** The raw message body text — DSN/ARF fields are line-structured within it. */
34
+ raw: string;
35
+ }
36
+ /** Classify an inbound message. */
37
+ export declare function classifyInbound(message: InboundMessage): InboundClassification;
38
+ //# sourceMappingURL=classify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classify.d.ts","sourceRoot":"","sources":["../../src/bounce/classify.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAEhD;;;;;;;;;;;GAWG;AAEH,mGAAmG;AACnG,MAAM,WAAW,qBAAqB;IACpC,sGAAsG;IACtG,IAAI,EAAE,UAAU,GAAG,QAAQ,CAAC;IAC5B,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,+EAA+E;IAC/E,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAyBD,gEAAgE;AAChE,MAAM,WAAW,cAAc;IAC7B,qFAAqF;IACrF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,qDAAqD;IACrD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,qFAAqF;IACrF,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gFAAgF;IAChF,GAAG,EAAE,MAAM,CAAC;CACb;AAED,mCAAmC;AACnC,wBAAgB,eAAe,CAAC,OAAO,EAAE,cAAc,GAAG,qBAAqB,CAoC9E"}
@@ -0,0 +1,46 @@
1
+ //#region src/bounce/classify.ts
2
+ /** Read a header-style field (`Name: value`) from a block of text, case-insensitively. */
3
+ function field(text, name) {
4
+ return new RegExp(`^${name}:\\s*(.+)$`, "im").exec(text)?.[1]?.trim();
5
+ }
6
+ /** Extract the address from an RFC822 recipient line like `rfc822;user@example.com` or `<user@x>`. */
7
+ function extractAddress(value) {
8
+ if (!value) return void 0;
9
+ const afterSemicolon = value.includes(";") ? value.slice(value.indexOf(";") + 1) : value;
10
+ const addr = (/<([^>]+)>/.exec(afterSemicolon)?.[1] ?? afterSemicolon).trim();
11
+ return addr.includes("@") ? addr : void 0;
12
+ }
13
+ /** The original message id — the explicit DSN field, else the last `Message-ID` (the embedded original). */
14
+ function originalMessageId(raw) {
15
+ const explicit = field(raw, "Original-Message-ID");
16
+ if (explicit) return explicit.replace(/^<|>$/g, "");
17
+ const ids = [...raw.matchAll(/^Message-ID:\s*<([^>]+)>/gim)].map((m) => m[1]);
18
+ return ids.length > 0 ? ids[ids.length - 1] : void 0;
19
+ }
20
+ /** Classify an inbound message. */
21
+ function classifyInbound(message) {
22
+ const contentType = (message.contentType ?? "").toLowerCase();
23
+ const raw = message.raw;
24
+ if (contentType.includes("report-type=delivery-status") || /^Action:\s*failed/im.test(raw)) {
25
+ const status = field(raw, "Status");
26
+ const diagnostic = field(raw, "Diagnostic-Code");
27
+ const recipient = extractAddress(field(raw, "Final-Recipient") ?? field(raw, "Original-Recipient"));
28
+ return {
29
+ type: status?.startsWith("4") ?? false ? "soft" : "hard",
30
+ recipient,
31
+ code: status ?? diagnostic,
32
+ originalMessageId: originalMessageId(raw)
33
+ };
34
+ }
35
+ if (contentType.includes("report-type=feedback-report") || /^Feedback-Type:/im.test(raw)) return {
36
+ type: "complaint",
37
+ recipient: extractAddress(field(raw, "Original-Rcpt-To") ?? field(raw, "Removal-Recipient")),
38
+ code: field(raw, "Feedback-Type") ?? "complaint",
39
+ originalMessageId: originalMessageId(raw)
40
+ };
41
+ const autoSubmitted = (message.autoSubmitted ?? "").toLowerCase();
42
+ if (message.autoReplyHeader || autoSubmitted && autoSubmitted !== "no") return { type: "auto_reply" };
43
+ return { type: "ignore" };
44
+ }
45
+ //#endregion
46
+ export { classifyInbound };
@@ -0,0 +1,32 @@
1
+ import type { CapabilityEmailHandler } from "@pithy-sh/core/src/capability/capability";
2
+ import { type EmailDatabase, type EmailSuppressionDatabase } from "../data/tables";
3
+ import { type InboundClassification } from "./classify";
4
+ /**
5
+ * The inbound bounce/complaint handler — the capability's `email()` seam. The Worker entrypoint fans
6
+ * incoming mail to it; it parses the message, classifies it, and applies the result: a hard bounce or
7
+ * complaint suppresses the address and marks the originating job bounced; a soft bounce records the
8
+ * event but does not suppress (Cloudflare auto-retries those); an auto-reply or anything unrecognized is
9
+ * a no-op. The job is matched by the original `Message-ID` against the stored send `messageId`.
10
+ */
11
+ /** What `applyInbound` did, for logging and tests. */
12
+ export interface InboundOutcome {
13
+ /** Whether any side effect was applied (false for auto-reply / ignore). */
14
+ acted: boolean;
15
+ /** The classification type. */
16
+ type: InboundClassification["type"];
17
+ /** The job id matched by original Message-ID, if any. */
18
+ jobId?: string;
19
+ /** Whether the address was added to the suppression list. */
20
+ suppressed: boolean;
21
+ }
22
+ /**
23
+ * Apply a classification's side effects. Suppression is written to the **shared** suppression database
24
+ * (so it applies in every environment); the job lookup and the bounce/complaint event use the app
25
+ * database. Pure of any MIME parsing — unit-testable. Note the single inbound worker only reaches its
26
+ * own app DB, so a job-row update is best-effort (the originating job may live in another environment),
27
+ * whereas the suppression — the safety-critical part — is always global.
28
+ */
29
+ export declare function applyInbound(db: EmailDatabase, suppressionDb: EmailSuppressionDatabase, c: InboundClassification, now: Date, environment?: string): Promise<InboundOutcome>;
30
+ /** Build the inbound-email handler for the `Capability.email` seam. Reads `DB` + `EMAIL_SUPPRESSIONS` from env. */
31
+ export declare function createBounceHandler(): CapabilityEmailHandler;
32
+ //# sourceMappingURL=handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../src/bounce/handler.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAC;AAGvF,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAG9B,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAmB,KAAK,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEzE;;;;;;GAMG;AAEH,sDAAsD;AACtD,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,KAAK,EAAE,OAAO,CAAC;IACf,+BAA+B;IAC/B,IAAI,EAAE,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACpC,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,aAAa,EACjB,aAAa,EAAE,wBAAwB,EACvC,CAAC,EAAE,qBAAqB,EACxB,GAAG,EAAE,IAAI,EACT,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,cAAc,CAAC,CA0DzB;AAED,mHAAmH;AACnH,wBAAgB,mBAAmB,IAAI,sBAAsB,CAuB5D"}
@@ -0,0 +1,81 @@
1
+ import { emailDatabase, emailSuppressionDatabase } from "../data/tables.js";
2
+ import { recordEvent } from "../send/events.js";
3
+ import { suppress } from "../send/suppression.js";
4
+ import { classifyInbound } from "./classify.js";
5
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
6
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
+ import PostalMime from "postal-mime";
8
+ //#region src/bounce/handler.ts
9
+ /**
10
+ * Apply a classification's side effects. Suppression is written to the **shared** suppression database
11
+ * (so it applies in every environment); the job lookup and the bounce/complaint event use the app
12
+ * database. Pure of any MIME parsing — unit-testable. Note the single inbound worker only reaches its
13
+ * own app DB, so a job-row update is best-effort (the originating job may live in another environment),
14
+ * whereas the suppression — the safety-critical part — is always global.
15
+ */
16
+ async function applyInbound(db, suppressionDb, c, now, environment) {
17
+ if (c.type === "ignore" || c.type === "auto_reply") return {
18
+ acted: false,
19
+ type: c.type,
20
+ suppressed: false
21
+ };
22
+ const job = c.originalMessageId ? await db.selectFrom("pithyEmailJobs").select([
23
+ "id",
24
+ "toAddress",
25
+ "status",
26
+ "campaignId"
27
+ ]).where("messageId", "=", c.originalMessageId).executeTakeFirst() : void 0;
28
+ const recipient = c.recipient ? normalizeAddress(c.recipient) : job ? normalizeAddress(job.toAddress) : void 0;
29
+ const isSuppressing = c.type === "hard" || c.type === "complaint";
30
+ let suppressed = false;
31
+ if (recipient && isSuppressing) {
32
+ await suppress(suppressionDb, {
33
+ email: recipient,
34
+ reason: c.type === "complaint" ? "complaint" : "hard_bounce",
35
+ jobId: job?.id ?? null,
36
+ environment,
37
+ detail: c.code ?? null
38
+ }, now);
39
+ suppressed = true;
40
+ }
41
+ if (job) {
42
+ await db.updateTable("pithyEmailJobs").set({
43
+ bounceCode: c.code ?? null,
44
+ bounceType: c.type,
45
+ status: isSuppressing ? "bounced" : job.status,
46
+ updatedAt: SQLiteDate.encode(now)
47
+ }).where("id", "=", job.id).execute();
48
+ await recordEvent(db, {
49
+ jobId: job.id,
50
+ recipient: recipient ?? normalizeAddress(job.toAddress),
51
+ type: c.type === "complaint" ? "complaint" : "bounce",
52
+ campaignId: job.campaignId ?? null,
53
+ detail: c.code ?? null
54
+ }, now);
55
+ }
56
+ return {
57
+ acted: suppressed || Boolean(job),
58
+ type: c.type,
59
+ jobId: job?.id,
60
+ suppressed
61
+ };
62
+ }
63
+ /** Build the inbound-email handler for the `Capability.email` seam. Reads `DB` + `EMAIL_SUPPRESSIONS` from env. */
64
+ function createBounceHandler() {
65
+ return async (message, env) => {
66
+ const raw = await new Response(message.raw).text();
67
+ const parsed = await PostalMime.parse(raw);
68
+ const headers = {};
69
+ for (const header of parsed.headers) headers[header.key.toLowerCase()] = header.value;
70
+ const classification = classifyInbound({
71
+ contentType: headers["content-type"],
72
+ autoSubmitted: headers["auto-submitted"],
73
+ autoReplyHeader: "x-autoreply" in headers || "x-autorespond" in headers,
74
+ raw
75
+ });
76
+ const bindings = env;
77
+ await applyInbound(emailDatabase(bindings.DB), emailSuppressionDatabase(bindings.EMAIL_SUPPRESSIONS), classification, /* @__PURE__ */ new Date(), bindings.ENVIRONMENT);
78
+ };
79
+ }
80
+ //#endregion
81
+ export { applyInbound, createBounceHandler };
@@ -0,0 +1,158 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ import { type Capability } from "@pithy-sh/core/src/capability/capability";
3
+ import type { LocaleCatalogs } from "@pithy-sh/core/src/i18n/catalog";
4
+ import { z } from "zod";
5
+ import { type EmailSuppressionDatabase } from "./data/tables";
6
+ import { DevMailDelivery } from "./provision/devDelivery";
7
+ import { type EnqueueInput, type EnqueueResult } from "./send/enqueue";
8
+ import { type EmailSenderEnv } from "./send/senderBinding";
9
+ import { type EmailTheme } from "./templates/theme";
10
+ /**
11
+ * The bindings the enqueue seam reads from the request env: the shared `DB`, the send Workflow, and the
12
+ * global suppression database. A consumer (e.g. `@pithy-sh/auth`) forwards its worker env; it never
13
+ * names these bindings itself.
14
+ *
15
+ * **`EMAIL_SUPPRESSIONS` is on this list, and that is the whole of pithy-sh/pithy#355.** The wiring is
16
+ * not the adopter's problem: the capability declares the binding, `pithy add email` provisions it,
17
+ * `enqueue` reads it off the env, and no consumer config, route option, or constant names it. What an
18
+ * adopter *may* do — because it is their database — is ask for it back through
19
+ * {@link EmailCapability.suppressions} and read or write it like any other table.
20
+ */
21
+ export interface EmailEnqueueEnv extends EmailSenderEnv {
22
+ DB: D1Database;
23
+ /**
24
+ * The global, durable suppression list.
25
+ *
26
+ * Optional in the type for the same reason `EMAIL_SENDER` is — a hand-built env in a test harness has
27
+ * neither — and required in practice: it is in `requiredBindings` below, so `validateBindings` refuses
28
+ * the first request of a composed worker that lacks it. Absent, `enqueue` queues the job and
29
+ * `runSend` still refuses a blocked recipient before anything leaves.
30
+ */
31
+ EMAIL_SUPPRESSIONS?: D1Database;
32
+ }
33
+ /**
34
+ * Sort order of the email migrations within the app database, relative to other capabilities
35
+ * (core low, app high). Unique per database; the migration registry composes the key
36
+ * `0200_email_0001_init`.
37
+ */
38
+ export declare const EMAIL_MIGRATION_ORDER = 200;
39
+ /** Sort order of the suppression migration within the dedicated `EMAIL_SUPPRESSIONS` database. */
40
+ export declare const EMAIL_SUPPRESSIONS_MIGRATION_ORDER = 100;
41
+ /**
42
+ * Configuration for the email capability, passed in `pithy.config.ts` — the thin user-owned surface.
43
+ * `fromAddress` and `baseUrl` are required; branding is one `theme` preset plus an optional
44
+ * `customTheme` that deep-merges over it (so a project tweaks just an accent or a palette color, not a
45
+ * dozen fields). Body width is intentionally *not* here — it is a property of each template (newsletters
46
+ * render wide, transactional narrow). The resolved theme is attached to the capability and serialized
47
+ * into the email worker's single `EMAIL_THEME` var at provision.
48
+ */
49
+ export declare const EmailConfig: z.ZodObject<{
50
+ fromAddress: z.ZodString;
51
+ fromName: z.ZodDefault<z.ZodString>;
52
+ baseUrl: z.ZodString;
53
+ basePath: z.ZodDefault<z.ZodString>;
54
+ theme: z.ZodDefault<z.ZodEnum<{
55
+ forest: "forest";
56
+ midnight: "midnight";
57
+ rose: "rose";
58
+ saffron: "saffron";
59
+ }>>;
60
+ customTheme: z.ZodOptional<z.ZodObject<{
61
+ appName: z.ZodOptional<z.ZodString>;
62
+ accent: z.ZodOptional<z.ZodString>;
63
+ logoUrl: z.ZodOptional<z.ZodString>;
64
+ logoDarkUrl: z.ZodOptional<z.ZodString>;
65
+ footerAddress: z.ZodOptional<z.ZodString>;
66
+ links: z.ZodOptional<z.ZodArray<z.ZodObject<{
67
+ label: z.ZodString;
68
+ href: z.ZodString;
69
+ }, z.core.$strip>>>;
70
+ light: z.ZodOptional<z.ZodObject<{
71
+ background: z.ZodOptional<z.ZodString>;
72
+ cardBackground: z.ZodOptional<z.ZodString>;
73
+ text: z.ZodOptional<z.ZodString>;
74
+ textMuted: z.ZodOptional<z.ZodString>;
75
+ textSubtle: z.ZodOptional<z.ZodString>;
76
+ separator: z.ZodOptional<z.ZodString>;
77
+ }, z.core.$strip>>;
78
+ dark: z.ZodOptional<z.ZodObject<{
79
+ background: z.ZodOptional<z.ZodString>;
80
+ cardBackground: z.ZodOptional<z.ZodString>;
81
+ text: z.ZodOptional<z.ZodString>;
82
+ textMuted: z.ZodOptional<z.ZodString>;
83
+ textSubtle: z.ZodOptional<z.ZodString>;
84
+ separator: z.ZodOptional<z.ZodString>;
85
+ }, z.core.$strip>>;
86
+ }, z.core.$strip>>;
87
+ schedulerEnabled: z.ZodDefault<z.ZodBoolean>;
88
+ devDelivery: z.ZodDefault<z.ZodEnum<{
89
+ remote: "remote";
90
+ simulator: "simulator";
91
+ }>>;
92
+ }, z.core.$strip>;
93
+ export type EmailConfig = z.output<typeof EmailConfig>;
94
+ export type EmailConfigInput = z.input<typeof EmailConfig>;
95
+ /** The resolved from identity, base URL, and theme — what the app's enqueue calls need. */
96
+ export interface ResolvedEmailConfig {
97
+ fromAddress: string;
98
+ fromName: string;
99
+ baseUrl: string;
100
+ schedulerEnabled: boolean;
101
+ /**
102
+ * What the host's `send_email` binding does under `pithy dev` — `remote` (real mail, the default)
103
+ * or `simulator`. Attached here because `pithy dev` reads it off the composed capability when it
104
+ * resolves the host's local config; nothing inside the app worker consults it.
105
+ */
106
+ devDelivery: DevMailDelivery;
107
+ theme: EmailTheme;
108
+ }
109
+ /** The email capability, with its resolved config and a bound enqueue seam attached. */
110
+ export interface EmailCapability extends Capability {
111
+ emailConfig: ResolvedEmailConfig;
112
+ /**
113
+ * Enqueue an email job from a request env. The capability owns the `DB`/`EMAIL_SENDER` bindings, the
114
+ * from-identity, and the theme — a consumer passes only its worker env and the high-level input
115
+ * (`to`, `template`, `payload`). This is the seam other capabilities depend on; they never assemble
116
+ * `EnqueueDeps` or name the email bindings themselves.
117
+ */
118
+ enqueue: (env: EmailEnqueueEnv, input: EnqueueInput) => Promise<EnqueueResult>;
119
+ /**
120
+ * The suppression list, from a request env — **it is the adopter's database, and this is how they open
121
+ * it** (pithy-sh/pithy#355).
122
+ *
123
+ * Nobody has to call this to be protected: `enqueue` consults the list on its own and `runSend`
124
+ * refuses a blocked recipient regardless. This exists for the adopter who genuinely wants to look —
125
+ * an operator un-suppressing an address a customer has fixed, a support screen explaining why a letter
126
+ * did not go, a report of who a notice could not reach. Reading and writing it is ordinary Kysely over
127
+ * `pithyEmailSuppressions`; `send/suppression.ts` publishes `blockingSuppression`, `suppress`,
128
+ * `unsuppress` and `listSuppressions` for the four things anybody actually does with it.
129
+ *
130
+ * It takes the env and no binding name, which is the point: the capability owns which binding the list
131
+ * lives behind, exactly as it owns `DB` and `EMAIL_SENDER`.
132
+ */
133
+ suppressions: (env: EmailEnqueueEnv) => EmailSuppressionDatabase;
134
+ /**
135
+ * The catalogs `pithy email provision` stamps into the host worker's `EMAIL_MESSAGES` var.
136
+ *
137
+ * A function rather than a field, and read after composition rather than at construction, for the
138
+ * reason the `compose` hook below exists at all: a capability sees only itself when it is built, and
139
+ * the translations belong to a capability that may be composed after this one. A snapshot taken in
140
+ * the returned object literal would be the pre-compose English, permanently — the same trap
141
+ * `@pithy-sh/i18n` names on its own `composedMessages` accessor.
142
+ *
143
+ * Empty when nothing composed an i18n capability, which is what a project serving one language wants:
144
+ * no var is written and the host renders the English it bundles.
145
+ */
146
+ hostCatalogs: () => LocaleCatalogs;
147
+ }
148
+ /**
149
+ * The email capability. It contributes the three email tables to the app `DB`, mounts the
150
+ * click/open/unsubscribe callback routes, and registers the inbound bounce/complaint `email()` handler.
151
+ * It requires the `DB` binding and the `EMAIL_SENDER` Workflow binding (to start an immediate send at
152
+ * enqueue). The send and scheduler Workflows and the every-minute cron live in the prebuilt email
153
+ * worker (`workflows/worker.ts`), deployed per environment by `pithy add email`.
154
+ */
155
+ export declare function email(config: EmailConfigInput): EmailCapability;
156
+ /** Whether a capability is the email capability — carries its resolved config. */
157
+ export declare function isEmailCapability(capability: Capability): capability is EmailCapability;
158
+ //# sourceMappingURL=capability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,KAAK,UAAU,EAAoB,MAAM,0CAA0C,CAAC;AAE7F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EACL,KAAK,wBAAwB,EAK9B,MAAM,eAAe,CAAC;AAMvB,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAgB,MAAM,gBAAgB,CAAC;AACrF,OAAO,EAAE,KAAK,cAAc,EAAsB,MAAM,sBAAsB,CAAC;AAE/E,OAAO,EAAe,KAAK,UAAU,EAAgB,MAAM,mBAAmB,CAAC;AAI/E;;;;;;;;;;GAUG;AACH,MAAM,WAAW,eAAgB,SAAQ,cAAc;IACrD,EAAE,EAAE,UAAU,CAAC;IACf;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,UAAU,CAAC;CACjC;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,kGAAkG;AAClG,eAAO,MAAM,kCAAkC,MAAM,CAAC;AAEtD;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiC8B,CAAC;AACvD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AACvD,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAE3D,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,WAAW,EAAE,eAAe,CAAC;IAC7B,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,wFAAwF;AACxF,MAAM,WAAW,eAAgB,SAAQ,UAAU;IACjD,WAAW,EAAE,mBAAmB,CAAC;IACjC;;;;;OAKG;IACH,OAAO,EAAE,CAAC,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;IAC/E;;;;;;;;;;;;;OAaG;IACH,YAAY,EAAE,CAAC,GAAG,EAAE,eAAe,KAAK,wBAAwB,CAAC;IACjE;;;;;;;;;;;OAWG;IACH,YAAY,EAAE,MAAM,cAAc,CAAC;CACpC;AAED;;;;;;GAMG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,gBAAgB,GAAG,eAAe,CA8M/D;AAED,kFAAkF;AAClF,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,eAAe,CAEvF"}