@pithy-sh/email 0.1.2 → 0.1.4

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