@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,54 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { EmailRateLimitedError, EmailSendFailedError, EmailSuppressedError } from "../error/errors.js";
4
+ //#region src/send/errorMapping.ts
5
+ /** Codes the Email Service retries past — rate, daily quota, and transient delivery/server faults. */
6
+ const RETRYABLE = /* @__PURE__ */ new Set([
7
+ "E_RATE_LIMIT_EXCEEDED",
8
+ "E_DAILY_LIMIT_EXCEEDED",
9
+ "E_DELIVERY_FAILED",
10
+ "E_INTERNAL_SERVER_ERROR"
11
+ ]);
12
+ /** Rate/quota codes map to the dedicated 429 error so the cause reads clearly in logs. */
13
+ const RATE_LIMITED = /* @__PURE__ */ new Set(["E_RATE_LIMIT_EXCEEDED", "E_DAILY_LIMIT_EXCEEDED"]);
14
+ /** Read a thrown value's `.code`/`.message` without assuming its shape. */
15
+ function readError(err) {
16
+ if (err && typeof err === "object") return {
17
+ code: "code" in err && typeof err.code === "string" ? err.code : "E_UNKNOWN",
18
+ message: "message" in err && typeof err.message === "string" ? err.message : ""
19
+ };
20
+ return {
21
+ code: "E_UNKNOWN",
22
+ message: typeof err === "string" ? err : ""
23
+ };
24
+ }
25
+ /**
26
+ * Classify a send failure. `E_RECIPIENT_SUPPRESSED` is terminal and means the address must be
27
+ * suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
28
+ * (validation, sender, content, headers) is terminal. An unknown code is treated as a transient
29
+ * failure so a momentary fault gets one bounded retry rather than failing the job outright.
30
+ */
31
+ function classifySendError(err) {
32
+ const { code, message } = readError(err);
33
+ const detail = `email send failed: ${code}${message ? ` — ${message}` : ""}`;
34
+ if (code === "E_RECIPIENT_SUPPRESSED") return {
35
+ code,
36
+ retryable: false,
37
+ suppressed: true,
38
+ error: new EmailSuppressedError({ detail }, { cause: err })
39
+ };
40
+ if (RATE_LIMITED.has(code)) return {
41
+ code,
42
+ retryable: true,
43
+ suppressed: false,
44
+ error: new EmailRateLimitedError({ detail }, { cause: err })
45
+ };
46
+ return {
47
+ code,
48
+ retryable: RETRYABLE.has(code) || code === "E_UNKNOWN",
49
+ suppressed: false,
50
+ error: new EmailSendFailedError({ detail }, { cause: err })
51
+ };
52
+ }
53
+ //#endregion
54
+ export { classifySendError };
@@ -0,0 +1,17 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { EmailEventType } from "../data/enums";
4
+ import type { EmailDatabase } from "../data/tables";
5
+ /** A per-recipient event to append to `pithy_email_events`. */
6
+ export interface EventInput {
7
+ jobId: string;
8
+ recipient: string;
9
+ type: EmailEventType;
10
+ linkLabel?: string | null;
11
+ linkUrl?: string | null;
12
+ campaignId?: string | null;
13
+ detail?: string | null;
14
+ }
15
+ /** Append one event row. The history/attribution log written by the send path, callbacks, and bounce handler. */
16
+ export declare function recordEvent(db: EmailDatabase, event: EventInput, now: Date): Promise<void>;
17
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/send/events.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD,+DAA+D;AAC/D,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,cAAc,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED,iHAAiH;AACjH,wBAAsB,WAAW,CAAC,EAAE,EAAE,aAAa,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAchG"}
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
4
+ //#region src/send/events.ts
5
+ /** Append one event row. The history/attribution log written by the send path, callbacks, and bounce handler. */
6
+ async function recordEvent(db, event, now) {
7
+ await db.insertInto("pithyEmailEvents").values({
8
+ jobId: event.jobId,
9
+ recipient: event.recipient,
10
+ type: event.type,
11
+ linkLabel: event.linkLabel ?? null,
12
+ linkUrl: event.linkUrl ?? null,
13
+ campaignId: event.campaignId ?? null,
14
+ detail: event.detail ?? null,
15
+ createdAt: SQLiteDate.encode(now)
16
+ }).execute();
17
+ }
18
+ //#endregion
19
+ export { recordEvent };
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type EmailCapability, type EmailEnqueueEnv } from "../capability";
4
+ import type { EnqueueInput, EnqueueResult } from "./enqueue";
5
+ /**
6
+ * Sending mail from a Workflow (pithy-sh/pithy#356).
7
+ *
8
+ * A route reaches `enqueue` through the `compose` hook, and should keep doing that — it is typed, it is
9
+ * explicit, and it does not depend on module load order. **A Workflow class has no such route.** The
10
+ * runtime constructs it with the worker `env` and nothing else, `enqueue` is a closure rather than a
11
+ * binding, and Workflow params are serialized so a closure cannot travel in one either. Until this
12
+ * existed, a durable job could not send mail without rebuilding the sending identity from `env` — the
13
+ * same from-address in a second place, free to drift from `pithy.config.ts` — which is exactly what this
14
+ * capability's own doc asks consumers not to do.
15
+ *
16
+ * So: one function, taking the env a Workflow already has, restating nothing.
17
+ *
18
+ * ```ts
19
+ * export class RotationWorkflow extends WorkflowEntrypoint<Env, RotationParams> {
20
+ * override async run(event: WorkflowEvent<RotationParams>, step: WorkflowStep) {
21
+ * await step.do("notify", async () => {
22
+ * await enqueueFromEnv(this.env, { to, template: "operationalNotice", payload });
23
+ * });
24
+ * }
25
+ * }
26
+ * ```
27
+ *
28
+ * The Workflow class must be exported from the same worker entrypoint that calls `createBackend` —
29
+ * which Cloudflare requires anyway — so the composition has already happened in this isolate by the time
30
+ * a step body runs. Where it has not, this raises a wiring fault naming what to compose rather than
31
+ * sending mail as some invented identity.
32
+ */
33
+ /**
34
+ * The composed email capability, or a raised wiring fault.
35
+ *
36
+ * Narrowed by `isEmailCapability`, the capability's own guard, so a capability composed under the name
37
+ * `email` but carrying no seams is caught here rather than at a call site whose `enqueue` is undefined.
38
+ */
39
+ export declare function composedEmail(): EmailCapability;
40
+ /**
41
+ * Enqueue an email from a worker env alone — the seam a Workflow step uses.
42
+ *
43
+ * Identical in every respect to `EmailCapability.enqueue`, because it *is* that function: the
44
+ * from-identity, the theme, the bindings and the automatic suppression check (pithy-sh/pithy#355) all
45
+ * come from the one composed capability. Nothing about a durable send differs from a request-time one
46
+ * except how the caller got here.
47
+ */
48
+ export declare function enqueueFromEnv(env: EmailEnqueueEnv, input: EnqueueInput): Promise<EnqueueResult>;
49
+ //# sourceMappingURL=fromComposition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fromComposition.d.ts","sourceRoot":"","sources":["../../src/send/fromComposition.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,eAAe,EAAqB,MAAM,eAAe,CAAC;AAC9F,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH;;;;;GAKG;AACH,wBAAgB,aAAa,IAAI,eAAe,CAE/C;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAEhG"}
@@ -0,0 +1,55 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { isEmailCapability } from "../capability.js";
4
+ import { composedCapability } from "@pithy-sh/core/src/capability/composition";
5
+ //#region src/send/fromComposition.ts
6
+ /**
7
+ * Sending mail from a Workflow (pithy-sh/pithy#356).
8
+ *
9
+ * A route reaches `enqueue` through the `compose` hook, and should keep doing that — it is typed, it is
10
+ * explicit, and it does not depend on module load order. **A Workflow class has no such route.** The
11
+ * runtime constructs it with the worker `env` and nothing else, `enqueue` is a closure rather than a
12
+ * binding, and Workflow params are serialized so a closure cannot travel in one either. Until this
13
+ * existed, a durable job could not send mail without rebuilding the sending identity from `env` — the
14
+ * same from-address in a second place, free to drift from `pithy.config.ts` — which is exactly what this
15
+ * capability's own doc asks consumers not to do.
16
+ *
17
+ * So: one function, taking the env a Workflow already has, restating nothing.
18
+ *
19
+ * ```ts
20
+ * export class RotationWorkflow extends WorkflowEntrypoint<Env, RotationParams> {
21
+ * override async run(event: WorkflowEvent<RotationParams>, step: WorkflowStep) {
22
+ * await step.do("notify", async () => {
23
+ * await enqueueFromEnv(this.env, { to, template: "operationalNotice", payload });
24
+ * });
25
+ * }
26
+ * }
27
+ * ```
28
+ *
29
+ * The Workflow class must be exported from the same worker entrypoint that calls `createBackend` —
30
+ * which Cloudflare requires anyway — so the composition has already happened in this isolate by the time
31
+ * a step body runs. Where it has not, this raises a wiring fault naming what to compose rather than
32
+ * sending mail as some invented identity.
33
+ */
34
+ /**
35
+ * The composed email capability, or a raised wiring fault.
36
+ *
37
+ * Narrowed by `isEmailCapability`, the capability's own guard, so a capability composed under the name
38
+ * `email` but carrying no seams is caught here rather than at a call site whose `enqueue` is undefined.
39
+ */
40
+ function composedEmail() {
41
+ return composedCapability("email", isEmailCapability);
42
+ }
43
+ /**
44
+ * Enqueue an email from a worker env alone — the seam a Workflow step uses.
45
+ *
46
+ * Identical in every respect to `EmailCapability.enqueue`, because it *is* that function: the
47
+ * from-identity, the theme, the bindings and the automatic suppression check (pithy-sh/pithy#355) all
48
+ * come from the one composed capability. Nothing about a durable send differs from a request-time one
49
+ * except how the caller got here.
50
+ */
51
+ function enqueueFromEnv(env, input) {
52
+ return composedEmail().enqueue(env, input);
53
+ }
54
+ //#endregion
55
+ export { composedEmail, enqueueFromEnv };
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { WorkflowRetryPolicy } from "@pithy-sh/core/src/workflow/faults";
4
+ /**
5
+ * **What a send retries, and what it refuses to.**
6
+ *
7
+ * Email already classified the *provider's* vocabulary — `errorMapping.ts` maps every `E_*` code the
8
+ * Email Service returns to retryable or terminal, and says why. This is the other half: the same
9
+ * decision in the form the durable step reads, covering the faults that never came from the binding at
10
+ * all (pithy-sh/pithy#338).
11
+ *
12
+ * ## Retryable
13
+ *
14
+ * - **`email/rate_limited`** — the per-second or daily quota. The next window is a different answer.
15
+ * - **`email/send_failed`** — raised by `runSend` **only** when `classifySendError` judged the code
16
+ * transient (`E_DELIVERY_FAILED`, `E_INTERNAL_SERVER_ERROR`, or an unknown code getting its one
17
+ * bounded retry). A validation, sender, or content code takes the terminal branch there and never
18
+ * reaches a throw, which is why this entry is not the hole it looks like — and `retryPolicy.test.ts`
19
+ * holds the two classifications to each other rather than trusting this sentence.
20
+ * - **A transient D1 fault** — the jobs, events and suppression tables. Classified in core.
21
+ *
22
+ * ## Terminal
23
+ *
24
+ * - **`core/not_found`** — the job row is gone. A send cannot invent the message it was asked to send,
25
+ * and a deleted row does not come back over a backoff.
26
+ * - **`email/template_not_found`, `email/invalid_payload`** — a render that cannot be attempted twice
27
+ * with a different result.
28
+ * - **Anything unclassified**, including a payload that will not parse.
29
+ *
30
+ * A suppressed recipient is neither: `runSend` records it and returns, because a person who asked not to
31
+ * be mailed is an outcome rather than a failure.
32
+ */
33
+ export declare const emailWorkflowRetry: WorkflowRetryPolicy;
34
+ //# sourceMappingURL=retryPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retryPolicy.d.ts","sourceRoot":"","sources":["../../src/send/retryPolicy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAE9E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,kBAAkB,EAAE,mBAOhC,CAAC"}
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/send/retryPolicy.ts
4
+ /**
5
+ * **What a send retries, and what it refuses to.**
6
+ *
7
+ * Email already classified the *provider's* vocabulary — `errorMapping.ts` maps every `E_*` code the
8
+ * Email Service returns to retryable or terminal, and says why. This is the other half: the same
9
+ * decision in the form the durable step reads, covering the faults that never came from the binding at
10
+ * all (pithy-sh/pithy#338).
11
+ *
12
+ * ## Retryable
13
+ *
14
+ * - **`email/rate_limited`** — the per-second or daily quota. The next window is a different answer.
15
+ * - **`email/send_failed`** — raised by `runSend` **only** when `classifySendError` judged the code
16
+ * transient (`E_DELIVERY_FAILED`, `E_INTERNAL_SERVER_ERROR`, or an unknown code getting its one
17
+ * bounded retry). A validation, sender, or content code takes the terminal branch there and never
18
+ * reaches a throw, which is why this entry is not the hole it looks like — and `retryPolicy.test.ts`
19
+ * holds the two classifications to each other rather than trusting this sentence.
20
+ * - **A transient D1 fault** — the jobs, events and suppression tables. Classified in core.
21
+ *
22
+ * ## Terminal
23
+ *
24
+ * - **`core/not_found`** — the job row is gone. A send cannot invent the message it was asked to send,
25
+ * and a deleted row does not come back over a backoff.
26
+ * - **`email/template_not_found`, `email/invalid_payload`** — a render that cannot be attempted twice
27
+ * with a different result.
28
+ * - **Anything unclassified**, including a payload that will not parse.
29
+ *
30
+ * A suppressed recipient is neither: `runSend` records it and returns, because a person who asked not to
31
+ * be mailed is an outcome rather than a failure.
32
+ */
33
+ const emailWorkflowRetry = {
34
+ capability: "email",
35
+ retryable: {
36
+ "email/rate_limited": "The send was over a rate or daily quota; the next window admits it.",
37
+ "email/send_failed": "Only thrown for a code classifySendError judged transient — delivery, an upstream 5xx, or one bounded retry of an unknown code."
38
+ }
39
+ };
40
+ //#endregion
41
+ export { emailWorkflowRetry };
@@ -0,0 +1,108 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { EmailJobStatus, SuppressionReason } from "../data/enums";
4
+ import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
5
+ import { type EmailMessageLayers } from "../templates/messages";
6
+ import type { EmailTheme } from "../templates/theme";
7
+ import type { EmailSender } from "./sender";
8
+ /**
9
+ * Send one job — the body the send Workflow runs inside a durable step. Never called from a request
10
+ * handler. It loads the job, skips a suppressed recipient, renders (with tracking per the job's flags),
11
+ * sends through the binding, and records the outcome on the row plus an event. On a retryable failure
12
+ * it throws (the Workflow step retries with backoff) until `maxAttempts`, then marks the job failed.
13
+ *
14
+ * **Whether a suppression applies depends on the message.** The kind comes from the template, not from
15
+ * the job row and not from a caller, so a magic link is transactional by declaration and an unrelated
16
+ * unsubscribe cannot swallow it.
17
+ *
18
+ * **A delivered job's inputs are dropped here, and "delivered" is the only place they can be.** The
19
+ * payload of a magic link *is* the sign-in link, so a row that keeps it after the message is out is a
20
+ * second, permanent copy of a live credential in a table nobody thinks of as holding secrets — which is
21
+ * what made an adopter's digested invitation token worth nothing the moment it was mailed. The line is
22
+ * `sent`, and every other outcome keeps its payload on purpose: `failed` can be retried, `suppressed`
23
+ * can be unblocked, and a payload dropped before the last attempt is a message that cannot be resent —
24
+ * a worse failure than the one being fixed. `sent` is the one status a retry is *already* refused for,
25
+ * because the mail has gone to a real person, so nothing here can ever need those inputs again.
26
+ */
27
+ /** The current signing key plus the valid version set, for minting tracking/unsubscribe links. */
28
+ export interface SendSigning {
29
+ /** The current signing key value. */
30
+ key: string;
31
+ /** The current signing key version, recorded as the token `kid`. */
32
+ kid: string;
33
+ }
34
+ /** Everything a send needs that isn't on the job row. */
35
+ export interface SendDeps {
36
+ /** The per-environment jobs/events database. */
37
+ db: EmailDatabase;
38
+ /** The global, shared suppression database — checked before every send, fed by bounces/complaints. */
39
+ suppressionDb: EmailSuppressionDatabase;
40
+ sender: EmailSender;
41
+ theme: EmailTheme;
42
+ /**
43
+ * Where the words for a locale come from.
44
+ *
45
+ * The host that runs this is a standalone Worker — nothing composes capabilities inside it — so it
46
+ * cannot be handed a composed project's layers the way the app worker's enqueue is. It reads the
47
+ * catalogs off its own env instead (`EMAIL_MESSAGES`) and turns them into this. Absent walks the
48
+ * kit's English, which is what a project that never opted into a second language gets.
49
+ */
50
+ layersFor?: EmailMessageLayers;
51
+ /** The public base URL for callback links. */
52
+ baseUrl: string;
53
+ /** The signing key for tracking/unsubscribe links. Absent disables tracking (and blocks marketing sends). */
54
+ signing?: SendSigning;
55
+ /** How long a tracked link stays valid. */
56
+ linkTtlDays: number;
57
+ /** The most attempts before a retryable failure becomes terminal. */
58
+ maxAttempts: number;
59
+ /** This worker's environment name, stamped on each send (X-Pithy-Env) so the single inbound worker can route. */
60
+ environment?: string;
61
+ /**
62
+ * When this pass began — **stable across a Workflow resume** (pithy-sh/pithy#327).
63
+ *
64
+ * Everything that dates the work reads this: `sentAt`, the redaction stamp, the events, and how long a
65
+ * tracked link stays valid. A driver body re-executes from the top on a resume, so a clock read there
66
+ * answers with the resume — and a batch that backed off overnight dated its remaining jobs, and the
67
+ * expiry of every link in them, a day late. `runSendBatch` journals this in a step so a resume reads
68
+ * back the instant the batch began.
69
+ *
70
+ * A link minted on the resumed half expires from the pass, not from the mint. Two people in one batch
71
+ * are promised the same window; which attempt happened to render their message is not something they
72
+ * can see and not something their link should depend on.
73
+ */
74
+ passStartedAt: Date;
75
+ /**
76
+ * "This job is being worked on, now" — **read fresh on every call**, and never journaled.
77
+ *
78
+ * This is not a stamp with a tidier name. `updatedAt` is the scheduler's only evidence that a `sending`
79
+ * job is alive: `runScheduler` claims and re-drives anything in `sending` older than `stuckMs`, on the
80
+ * assumption its dispatch died. Freeze it and a batch that resumes past that window reports the job it
81
+ * is actively retrying as stranded, so the next tick starts a second send Workflow against it — and
82
+ * `runSend` short-circuits only a job already `sent`, so both attempts render and both call `send`. One
83
+ * person, two emails. A sweep journaled the single `now` this replaced and was reverted for exactly
84
+ * that.
85
+ *
86
+ * The suppression liveness read takes it too, because "is this address blocked *right now*" is a
87
+ * present-tense question and an hour-old answer to it is simply wrong.
88
+ */
89
+ heartbeatAt: () => Date;
90
+ }
91
+ /** The outcome of a send attempt. */
92
+ export interface SendOutcome {
93
+ jobId: string;
94
+ status: EmailJobStatus;
95
+ messageId?: string;
96
+ skipped?: boolean;
97
+ /**
98
+ * Why nothing was sent, when the recipient was on the suppression list.
99
+ *
100
+ * A skipped send has to be reported, not swallowed. Without this the caller sees an outcome that is
101
+ * not `failed` and the person sees an empty inbox, which is what made the whole class of bug invisible
102
+ * from both ends. "Suppressed" alone is not enough either — an operator deciding what to do next needs
103
+ * to know whether the address bounced, complained, or opted out.
104
+ */
105
+ suppressionReason?: SuppressionReason;
106
+ }
107
+ export declare function runSend(deps: SendDeps, jobId: string): Promise<SendOutcome>;
108
+ //# sourceMappingURL=runSend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runSend.d.ts","sourceRoot":"","sources":["../../src/send/runSend.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAe,MAAM,gBAAgB,CAAC;AAE3F,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG5C;;;;;;;;;;;;;;;;;;GAkBG;AAEH,kGAAkG;AAClG,MAAM,WAAW,WAAW;IAC1B,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,yDAAyD;AACzD,MAAM,WAAW,QAAQ;IACvB,gDAAgD;IAChD,EAAE,EAAE,aAAa,CAAC;IAClB,sGAAsG;IACtG,aAAa,EAAE,wBAAwB,CAAC;IACxC,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,UAAU,CAAC;IAClB;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,6GAA6G;IAC7G,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,WAAW,EAAE,MAAM,CAAC;IACpB,iHAAiH;IACjH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,aAAa,EAAE,IAAI,CAAC;IACpB;;;;;;;;;;;;;OAaG;IACH,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED,qCAAqC;AACrC,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAuBD,wBAAsB,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAgLjF"}
@@ -0,0 +1,220 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { EmailJob, SPENT_PAYLOAD } from "../data/emailJob.js";
4
+ import { recordEvent } from "./events.js";
5
+ import { blockingSuppression, suppress } from "./suppression.js";
6
+ import { emailTranslator, kitEmailLayers } from "../templates/messages.js";
7
+ import { redactsPayloadOnDelivery, renderEmail, templateKind } from "../templates/engine.js";
8
+ import { classifySendError } from "./errorMapping.js";
9
+ import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
10
+ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
11
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
12
+ //#region src/send/runSend.ts
13
+ const DAY_MS = 864e5;
14
+ /**
15
+ * Patch a job row by id, always bumping `updatedAt` — **on the heartbeat clock, not the pass instant.**
16
+ *
17
+ * Every write this function makes is also a statement that the job is still being worked on, because
18
+ * `updatedAt` is what the scheduler's `sending` re-drive reads. That is why the bump is here rather than
19
+ * at each call site: a patch that did not say "still alive" would be a patch that invited a second send
20
+ * Workflow. See {@link SendDeps.heartbeatAt}.
21
+ */
22
+ async function patchJob(deps, jobId, patch) {
23
+ await deps.db.updateTable("pithyEmailJobs").set({
24
+ ...patch,
25
+ updatedAt: SQLiteDate.encode(deps.heartbeatAt())
26
+ }).where("id", "=", jobId).execute();
27
+ }
28
+ async function runSend(deps, jobId) {
29
+ const row = await deps.db.selectFrom("pithyEmailJobs").selectAll().where("id", "=", jobId).executeTakeFirst();
30
+ if (!row) throw new NotFoundError({ detail: `email job '${jobId}' not found` });
31
+ const job = EmailJob.parse(row);
32
+ if (job.status === "sent") return {
33
+ jobId,
34
+ status: "sent",
35
+ messageId: job.messageId ?? void 0
36
+ };
37
+ if (job.status === "canceled") return {
38
+ jobId,
39
+ status: "canceled",
40
+ skipped: true
41
+ };
42
+ const recipient = normalizeAddress(job.toAddress);
43
+ if (job.payloadRedactedAt) {
44
+ await patchJob(deps, jobId, {
45
+ status: "failed",
46
+ error: "payload dropped after delivery"
47
+ });
48
+ await recordEvent(deps.db, {
49
+ jobId,
50
+ recipient,
51
+ type: "failed",
52
+ detail: "payload already redacted"
53
+ }, deps.passStartedAt);
54
+ return {
55
+ jobId,
56
+ status: "failed"
57
+ };
58
+ }
59
+ const kind = templateKind(job.template);
60
+ const blocked = await blockingSuppression(deps.suppressionDb, recipient, deps.heartbeatAt(), kind);
61
+ if (blocked) {
62
+ await patchJob(deps, jobId, {
63
+ status: "suppressed",
64
+ error: `recipient suppressed: ${blocked}`
65
+ });
66
+ await recordEvent(deps.db, {
67
+ jobId,
68
+ recipient,
69
+ type: "suppressed",
70
+ detail: blocked
71
+ }, deps.passStartedAt);
72
+ return {
73
+ jobId,
74
+ status: "suppressed",
75
+ skipped: true,
76
+ suppressionReason: blocked
77
+ };
78
+ }
79
+ if (job.category === "marketing" && !deps.signing) {
80
+ await patchJob(deps, jobId, {
81
+ status: "failed",
82
+ error: "no signing key for marketing unsubscribe link"
83
+ });
84
+ await recordEvent(deps.db, {
85
+ jobId,
86
+ recipient,
87
+ type: "failed",
88
+ detail: "no signing key"
89
+ }, deps.passStartedAt);
90
+ return {
91
+ jobId,
92
+ status: "failed"
93
+ };
94
+ }
95
+ const tracking = deps.signing ? {
96
+ baseUrl: deps.baseUrl,
97
+ jobId,
98
+ recipient,
99
+ campaignId: job.campaignId ?? void 0,
100
+ key: deps.signing.key,
101
+ kid: deps.signing.kid,
102
+ expiresAt: new Date(deps.passStartedAt.getTime() + deps.linkTtlDays * DAY_MS),
103
+ openTracking: job.openTracking,
104
+ clickTracking: job.clickTracking
105
+ } : void 0;
106
+ const attempts = job.attempts + 1;
107
+ await patchJob(deps, jobId, {
108
+ status: "sending",
109
+ attempts
110
+ });
111
+ const rendered = await renderEmail(job.template, job.payload, deps.theme, tracking, emailTranslator(job.locale, deps.layersFor ?? kitEmailLayers));
112
+ const headers = { "X-Pithy-Job": jobId };
113
+ if (deps.environment) headers["X-Pithy-Env"] = deps.environment;
114
+ if (job.inReplyTo) headers["In-Reply-To"] = job.inReplyTo;
115
+ if (job.references) headers.References = job.references;
116
+ if (rendered.unsubscribeUrl) {
117
+ headers["List-Unsubscribe"] = `<${rendered.unsubscribeUrl}>`;
118
+ headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
119
+ }
120
+ const message = {
121
+ to: recipient,
122
+ from: {
123
+ email: job.fromAddress,
124
+ name: job.fromName
125
+ },
126
+ ...job.replyTo ? { replyTo: job.replyTo } : {},
127
+ subject: rendered.subject,
128
+ html: rendered.html,
129
+ text: rendered.text,
130
+ headers
131
+ };
132
+ try {
133
+ const result = await deps.sender.send(message);
134
+ const spent = redactsPayloadOnDelivery(job.template);
135
+ await patchJob(deps, jobId, {
136
+ status: "sent",
137
+ sentAt: SQLiteDate.encode(deps.passStartedAt),
138
+ messageId: result.messageId ?? null,
139
+ subject: rendered.subject,
140
+ error: null,
141
+ ...spent ? {
142
+ payload: SPENT_PAYLOAD,
143
+ payloadRedactedAt: SQLiteDate.encode(deps.passStartedAt)
144
+ } : {}
145
+ });
146
+ await recordEvent(deps.db, {
147
+ jobId,
148
+ recipient,
149
+ type: "sent",
150
+ campaignId: job.campaignId
151
+ }, deps.passStartedAt);
152
+ for (const bounced of result.permanentBounces ?? []) {
153
+ await suppress(deps.suppressionDb, {
154
+ email: bounced,
155
+ reason: "hard_bounce",
156
+ jobId,
157
+ environment: deps.environment,
158
+ detail: "permanent bounce on send"
159
+ }, deps.passStartedAt);
160
+ await recordEvent(deps.db, {
161
+ jobId,
162
+ recipient: normalizeAddress(bounced),
163
+ type: "bounce",
164
+ detail: "permanent bounce on send"
165
+ }, deps.passStartedAt);
166
+ }
167
+ return {
168
+ jobId,
169
+ status: "sent",
170
+ messageId: result.messageId
171
+ };
172
+ } catch (err) {
173
+ const classified = classifySendError(err);
174
+ if (classified.suppressed) {
175
+ await patchJob(deps, jobId, {
176
+ status: "suppressed",
177
+ error: classified.code,
178
+ bounceCode: classified.code
179
+ });
180
+ await suppress(deps.suppressionDb, {
181
+ email: recipient,
182
+ reason: "hard_bounce",
183
+ jobId,
184
+ environment: deps.environment,
185
+ detail: classified.code
186
+ }, deps.passStartedAt);
187
+ await recordEvent(deps.db, {
188
+ jobId,
189
+ recipient,
190
+ type: "suppressed",
191
+ detail: classified.code
192
+ }, deps.passStartedAt);
193
+ return {
194
+ jobId,
195
+ status: "suppressed",
196
+ skipped: true
197
+ };
198
+ }
199
+ if (classified.retryable && attempts < deps.maxAttempts) {
200
+ await patchJob(deps, jobId, { error: classified.code });
201
+ throw classified.error;
202
+ }
203
+ await patchJob(deps, jobId, {
204
+ status: "failed",
205
+ error: classified.code
206
+ });
207
+ await recordEvent(deps.db, {
208
+ jobId,
209
+ recipient,
210
+ type: "failed",
211
+ detail: classified.code
212
+ }, deps.passStartedAt);
213
+ return {
214
+ jobId,
215
+ status: "failed"
216
+ };
217
+ }
218
+ }
219
+ //#endregion
220
+ export { runSend };
@@ -0,0 +1,8 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The next absolute instant when the wall clock reads `hour:minute` in `timezone`, at or after `now`.
5
+ * Computes the candidate for the zone-local date of `now`, advancing a day if it has already passed.
6
+ */
7
+ export declare function resolveTimezoneSendAt(localTime: string, timezone: string, now: Date): Date;
8
+ //# sourceMappingURL=sendAt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sendAt.d.ts","sourceRoot":"","sources":["../../src/send/sendAt.ts"],"names":[],"mappings":"AA4CA;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,IAAI,CA4B1F"}