@shware/workflow 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +96 -2
  2. package/dist/apns-relay.cjs +4 -17
  3. package/dist/apns-relay.cjs.map +1 -1
  4. package/dist/apns-relay.mjs +4 -17
  5. package/dist/apns-relay.mjs.map +1 -1
  6. package/dist/aws/engine-step.cjs +104 -0
  7. package/dist/aws/engine-step.cjs.map +1 -0
  8. package/dist/aws/engine-step.d.cts +28 -0
  9. package/dist/aws/engine-step.d.cts.map +1 -0
  10. package/dist/aws/engine-step.d.mts +28 -0
  11. package/dist/aws/engine-step.d.mts.map +1 -0
  12. package/dist/aws/engine-step.mjs +102 -0
  13. package/dist/aws/engine-step.mjs.map +1 -0
  14. package/dist/aws/function-url.cjs +62 -0
  15. package/dist/aws/function-url.cjs.map +1 -0
  16. package/dist/aws/function-url.d.cts +38 -0
  17. package/dist/aws/function-url.d.cts.map +1 -0
  18. package/dist/aws/function-url.d.mts +38 -0
  19. package/dist/aws/function-url.d.mts.map +1 -0
  20. package/dist/aws/function-url.mjs +59 -0
  21. package/dist/aws/function-url.mjs.map +1 -0
  22. package/dist/aws/index.cjs +160 -0
  23. package/dist/aws/index.cjs.map +1 -0
  24. package/dist/aws/index.d.cts +62 -0
  25. package/dist/aws/index.d.cts.map +1 -0
  26. package/dist/aws/index.d.mts +62 -0
  27. package/dist/aws/index.d.mts.map +1 -0
  28. package/dist/aws/index.mjs +148 -0
  29. package/dist/aws/index.mjs.map +1 -0
  30. package/dist/aws/instances.cjs +176 -0
  31. package/dist/aws/instances.cjs.map +1 -0
  32. package/dist/aws/instances.d.cts +75 -0
  33. package/dist/aws/instances.d.cts.map +1 -0
  34. package/dist/aws/instances.d.mts +75 -0
  35. package/dist/aws/instances.d.mts.map +1 -0
  36. package/dist/aws/instances.mjs +172 -0
  37. package/dist/aws/instances.mjs.map +1 -0
  38. package/dist/aws/lambda-api.cjs +89 -0
  39. package/dist/aws/lambda-api.cjs.map +1 -0
  40. package/dist/aws/lambda-api.d.cts +43 -0
  41. package/dist/aws/lambda-api.d.cts.map +1 -0
  42. package/dist/aws/lambda-api.d.mts +43 -0
  43. package/dist/aws/lambda-api.d.mts.map +1 -0
  44. package/dist/aws/lambda-api.mjs +88 -0
  45. package/dist/aws/lambda-api.mjs.map +1 -0
  46. package/dist/client.d.cts +1 -1
  47. package/dist/client.d.mts +1 -1
  48. package/dist/cloudflare/bindings.cjs +19 -0
  49. package/dist/cloudflare/bindings.cjs.map +1 -1
  50. package/dist/cloudflare/bindings.d.cts +37 -0
  51. package/dist/cloudflare/bindings.d.cts.map +1 -1
  52. package/dist/cloudflare/bindings.d.mts +37 -0
  53. package/dist/cloudflare/bindings.d.mts.map +1 -1
  54. package/dist/cloudflare/bindings.mjs +18 -1
  55. package/dist/cloudflare/bindings.mjs.map +1 -1
  56. package/dist/cloudflare/index.cjs +32 -28
  57. package/dist/cloudflare/index.d.cts +8 -6
  58. package/dist/cloudflare/index.d.mts +8 -6
  59. package/dist/cloudflare/index.mjs +12 -10
  60. package/dist/cloudflare/runner.cjs +27 -76
  61. package/dist/cloudflare/runner.cjs.map +1 -1
  62. package/dist/cloudflare/runner.d.cts +7 -2
  63. package/dist/cloudflare/runner.d.cts.map +1 -1
  64. package/dist/cloudflare/runner.d.mts +7 -2
  65. package/dist/cloudflare/runner.d.mts.map +1 -1
  66. package/dist/cloudflare/runner.mjs +26 -75
  67. package/dist/cloudflare/runner.mjs.map +1 -1
  68. package/dist/cloudflare/worker.cjs +22 -203
  69. package/dist/cloudflare/worker.cjs.map +1 -1
  70. package/dist/cloudflare/worker.d.cts +10 -56
  71. package/dist/cloudflare/worker.d.cts.map +1 -1
  72. package/dist/cloudflare/worker.d.mts +10 -56
  73. package/dist/cloudflare/worker.d.mts.map +1 -1
  74. package/dist/cloudflare/worker.mjs +20 -199
  75. package/dist/cloudflare/worker.mjs.map +1 -1
  76. package/dist/config.cjs +2 -2
  77. package/dist/config.cjs.map +1 -1
  78. package/dist/config.d.cts +1 -1
  79. package/dist/config.d.mts +1 -1
  80. package/dist/config.mjs +2 -2
  81. package/dist/config.mjs.map +1 -1
  82. package/dist/contract.cjs.map +1 -1
  83. package/dist/contract.d.cts +1 -1
  84. package/dist/contract.d.cts.map +1 -1
  85. package/dist/contract.d.mts +1 -1
  86. package/dist/contract.d.mts.map +1 -1
  87. package/dist/contract.mjs.map +1 -1
  88. package/dist/dsl/action.cjs.map +1 -1
  89. package/dist/dsl/action.d.cts +2 -2
  90. package/dist/dsl/action.d.cts.map +1 -1
  91. package/dist/dsl/action.d.mts +2 -2
  92. package/dist/dsl/action.d.mts.map +1 -1
  93. package/dist/dsl/action.mjs.map +1 -1
  94. package/dist/dsl/bundle.cjs.map +1 -1
  95. package/dist/dsl/bundle.d.cts +1 -1
  96. package/dist/dsl/bundle.d.mts +1 -1
  97. package/dist/dsl/bundle.mjs.map +1 -1
  98. package/dist/dsl/flow.cjs.map +1 -1
  99. package/dist/dsl/flow.d.cts +1 -1
  100. package/dist/dsl/flow.d.cts.map +1 -1
  101. package/dist/dsl/flow.d.mts +1 -1
  102. package/dist/dsl/flow.d.mts.map +1 -1
  103. package/dist/dsl/flow.mjs.map +1 -1
  104. package/dist/dsl/refs.cjs.map +1 -1
  105. package/dist/dsl/refs.d.cts +5 -4
  106. package/dist/dsl/refs.d.cts.map +1 -1
  107. package/dist/dsl/refs.d.mts +5 -4
  108. package/dist/dsl/refs.d.mts.map +1 -1
  109. package/dist/dsl/refs.mjs.map +1 -1
  110. package/dist/dsl/template.cjs.map +1 -1
  111. package/dist/dsl/template.d.cts +2 -2
  112. package/dist/dsl/template.d.cts.map +1 -1
  113. package/dist/dsl/template.d.mts +2 -2
  114. package/dist/dsl/template.d.mts.map +1 -1
  115. package/dist/dsl/template.mjs.map +1 -1
  116. package/dist/email-sender.cjs +62 -0
  117. package/dist/email-sender.cjs.map +1 -0
  118. package/dist/email-sender.d.cts +70 -0
  119. package/dist/email-sender.d.cts.map +1 -0
  120. package/dist/email-sender.d.mts +70 -0
  121. package/dist/email-sender.d.mts.map +1 -0
  122. package/dist/email-sender.mjs +60 -0
  123. package/dist/email-sender.mjs.map +1 -0
  124. package/dist/email.cjs +21 -0
  125. package/dist/email.cjs.map +1 -1
  126. package/dist/email.d.cts +6 -0
  127. package/dist/email.d.cts.map +1 -1
  128. package/dist/email.d.mts +6 -0
  129. package/dist/email.d.mts.map +1 -1
  130. package/dist/email.mjs +21 -1
  131. package/dist/email.mjs.map +1 -1
  132. package/dist/engine/index.cjs +1 -1
  133. package/dist/engine/index.mjs +1 -1
  134. package/dist/engine/interpreter.cjs +1 -1
  135. package/dist/engine/interpreter.cjs.map +1 -1
  136. package/dist/engine/interpreter.d.cts.map +1 -1
  137. package/dist/engine/interpreter.d.mts.map +1 -1
  138. package/dist/engine/interpreter.mjs +1 -1
  139. package/dist/engine/interpreter.mjs.map +1 -1
  140. package/dist/engine/ports.d.cts +6 -1
  141. package/dist/engine/ports.d.cts.map +1 -1
  142. package/dist/engine/ports.d.mts +6 -1
  143. package/dist/engine/ports.d.mts.map +1 -1
  144. package/dist/{cloudflare → host}/channels.cjs +13 -11
  145. package/dist/host/channels.cjs.map +1 -0
  146. package/dist/{cloudflare → host}/channels.d.cts +8 -3
  147. package/dist/host/channels.d.cts.map +1 -0
  148. package/dist/{cloudflare → host}/channels.d.mts +8 -3
  149. package/dist/host/channels.d.mts.map +1 -0
  150. package/dist/{cloudflare → host}/channels.mjs +9 -7
  151. package/dist/host/channels.mjs.map +1 -0
  152. package/dist/host/execute.cjs +82 -0
  153. package/dist/host/execute.cjs.map +1 -0
  154. package/dist/host/execute.d.cts +41 -0
  155. package/dist/host/execute.d.cts.map +1 -0
  156. package/dist/host/execute.d.mts +41 -0
  157. package/dist/host/execute.d.mts.map +1 -0
  158. package/dist/host/execute.mjs +81 -0
  159. package/dist/host/execute.mjs.map +1 -0
  160. package/dist/host/journey-host.cjs +214 -0
  161. package/dist/host/journey-host.cjs.map +1 -0
  162. package/dist/host/journey-host.d.cts +105 -0
  163. package/dist/host/journey-host.d.cts.map +1 -0
  164. package/dist/host/journey-host.d.mts +105 -0
  165. package/dist/host/journey-host.d.mts.map +1 -0
  166. package/dist/host/journey-host.mjs +210 -0
  167. package/dist/host/journey-host.mjs.map +1 -0
  168. package/dist/{cloudflare → host}/router.cjs +28 -9
  169. package/dist/host/router.cjs.map +1 -0
  170. package/dist/{cloudflare → host}/router.d.cts +2 -2
  171. package/dist/host/router.d.cts.map +1 -0
  172. package/dist/{cloudflare → host}/router.d.mts +2 -2
  173. package/dist/host/router.d.mts.map +1 -0
  174. package/dist/{cloudflare → host}/router.mjs +28 -9
  175. package/dist/host/router.mjs.map +1 -0
  176. package/dist/host/senders.cjs +63 -0
  177. package/dist/host/senders.cjs.map +1 -0
  178. package/dist/host/senders.d.cts +31 -0
  179. package/dist/host/senders.d.cts.map +1 -0
  180. package/dist/host/senders.d.mts +31 -0
  181. package/dist/host/senders.d.mts.map +1 -0
  182. package/dist/host/senders.mjs +59 -0
  183. package/dist/host/senders.mjs.map +1 -0
  184. package/dist/http2-client.cjs +88 -0
  185. package/dist/http2-client.cjs.map +1 -0
  186. package/dist/http2-client.d.cts +44 -0
  187. package/dist/http2-client.d.cts.map +1 -0
  188. package/dist/http2-client.d.mts +44 -0
  189. package/dist/http2-client.d.mts.map +1 -0
  190. package/dist/http2-client.mjs +86 -0
  191. package/dist/http2-client.mjs.map +1 -0
  192. package/dist/index.cjs +1 -0
  193. package/dist/index.d.cts +2 -2
  194. package/dist/index.d.mts +2 -2
  195. package/dist/index.mjs +2 -2
  196. package/dist/react-email.cjs.map +1 -1
  197. package/dist/react-email.d.cts +1 -2
  198. package/dist/react-email.d.cts.map +1 -1
  199. package/dist/react-email.d.mts +1 -2
  200. package/dist/react-email.d.mts.map +1 -1
  201. package/dist/react-email.mjs.map +1 -1
  202. package/dist/reporting/tracking.cjs +5 -1
  203. package/dist/reporting/tracking.cjs.map +1 -1
  204. package/dist/reporting/tracking.d.cts.map +1 -1
  205. package/dist/reporting/tracking.d.mts.map +1 -1
  206. package/dist/reporting/tracking.mjs +5 -1
  207. package/dist/reporting/tracking.mjs.map +1 -1
  208. package/dist/store/d1.cjs +1 -0
  209. package/dist/store/d1.cjs.map +1 -1
  210. package/dist/store/d1.d.cts.map +1 -1
  211. package/dist/store/d1.d.mts.map +1 -1
  212. package/dist/store/d1.mjs +1 -0
  213. package/dist/store/d1.mjs.map +1 -1
  214. package/dist/store/index.cjs.map +1 -1
  215. package/dist/store/index.d.cts +63 -0
  216. package/dist/store/index.d.cts.map +1 -1
  217. package/dist/store/index.d.mts +63 -0
  218. package/dist/store/index.d.mts.map +1 -1
  219. package/dist/store/index.mjs.map +1 -1
  220. package/dist/store/postgres-reporting.cjs +5 -5
  221. package/dist/store/postgres-reporting.cjs.map +1 -1
  222. package/dist/store/postgres-reporting.mjs +5 -5
  223. package/dist/store/postgres-reporting.mjs.map +1 -1
  224. package/dist/store/postgres.cjs +143 -2
  225. package/dist/store/postgres.cjs.map +1 -1
  226. package/dist/store/postgres.d.cts +4 -1
  227. package/dist/store/postgres.d.cts.map +1 -1
  228. package/dist/store/postgres.d.mts +4 -1
  229. package/dist/store/postgres.d.mts.map +1 -1
  230. package/dist/store/postgres.mjs +143 -2
  231. package/dist/store/postgres.mjs.map +1 -1
  232. package/dist/store/tables.cjs +26 -0
  233. package/dist/store/tables.cjs.map +1 -1
  234. package/dist/store/tables.d.cts +1 -0
  235. package/dist/store/tables.d.cts.map +1 -1
  236. package/dist/store/tables.d.mts +1 -0
  237. package/dist/store/tables.d.mts.map +1 -1
  238. package/dist/store/tables.mjs +26 -0
  239. package/dist/store/tables.mjs.map +1 -1
  240. package/dist/templates.cjs.map +1 -1
  241. package/dist/templates.mjs.map +1 -1
  242. package/dist/transports/cloudflare-email.cjs +59 -0
  243. package/dist/transports/cloudflare-email.cjs.map +1 -0
  244. package/dist/transports/cloudflare-email.d.cts +38 -0
  245. package/dist/transports/cloudflare-email.d.cts.map +1 -0
  246. package/dist/transports/cloudflare-email.d.mts +38 -0
  247. package/dist/transports/cloudflare-email.d.mts.map +1 -0
  248. package/dist/transports/cloudflare-email.mjs +57 -0
  249. package/dist/transports/cloudflare-email.mjs.map +1 -0
  250. package/dist/transports/ses.cjs +91 -0
  251. package/dist/transports/ses.cjs.map +1 -0
  252. package/dist/transports/ses.d.cts +39 -0
  253. package/dist/transports/ses.d.cts.map +1 -0
  254. package/dist/transports/ses.d.mts +39 -0
  255. package/dist/transports/ses.d.mts.map +1 -0
  256. package/dist/transports/ses.mjs +89 -0
  257. package/dist/transports/ses.mjs.map +1 -0
  258. package/dist/transports/sigv4.cjs +83 -0
  259. package/dist/transports/sigv4.cjs.map +1 -0
  260. package/dist/transports/sigv4.d.cts +27 -0
  261. package/dist/transports/sigv4.d.cts.map +1 -0
  262. package/dist/transports/sigv4.d.mts +27 -0
  263. package/dist/transports/sigv4.d.mts.map +1 -0
  264. package/dist/transports/sigv4.mjs +82 -0
  265. package/dist/transports/sigv4.mjs.map +1 -0
  266. package/package.json +53 -1
  267. package/dist/cloudflare/channels.cjs.map +0 -1
  268. package/dist/cloudflare/channels.d.cts.map +0 -1
  269. package/dist/cloudflare/channels.d.mts.map +0 -1
  270. package/dist/cloudflare/channels.mjs.map +0 -1
  271. package/dist/cloudflare/router.cjs.map +0 -1
  272. package/dist/cloudflare/router.d.cts.map +0 -1
  273. package/dist/cloudflare/router.d.mts.map +0 -1
  274. package/dist/cloudflare/router.mjs.map +0 -1
  275. package/dist/cloudflare/senders.cjs +0 -121
  276. package/dist/cloudflare/senders.cjs.map +0 -1
  277. package/dist/cloudflare/senders.d.cts +0 -72
  278. package/dist/cloudflare/senders.d.cts.map +0 -1
  279. package/dist/cloudflare/senders.d.mts +0 -72
  280. package/dist/cloudflare/senders.d.mts.map +0 -1
  281. package/dist/cloudflare/senders.mjs +0 -115
  282. package/dist/cloudflare/senders.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"templates.mjs","names":[],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as core.$ZodType | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;;;;AAMA,SAAgB,cACd,YACkB;CAClB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,oBAAoB,YAAY,kBAAkB,WAAW,GAAG,GAAG;CACnE,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;AAGA,SAAgB,aACd,YACiB;CACjB,iBAAiB,WAAW,IAAI,cAAc;CAC9C,sB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Ae,SAAS,WAAW,QAAQ;GACzD,qBAAqB,OAAO,KAAK;GACjC,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,eAAe,OAAO,SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
1
+ {"version":3,"file":"templates.mjs","names":[],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as { _zod?: { def?: core.$ZodTypeDef } } | null | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;;;;AAMA,SAAgB,cACd,YACkB;CAClB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,oBAA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,SAAS;EACrC,IAAI,YAAY,SAEd,OAAO,mBADO,eAAe,OAAO,SAAS,QACf,GAAG,KAAK;EAExC,IAAI,YAAY,QAAQ;GACtB,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ;GACnD,kBAAkB,OAAO,KAAK;GAC9B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,WAAW;GACzB,MAAM,QAAQ,eAAe,SAAS,WAAW,QAAQ;GACzD,qBAAqB,OAAO,KAAK;GACjC,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,eAAe,OAAO,SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
@@ -0,0 +1,59 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_email = require("../email.cjs");
3
+ //#region src/transports/cloudflare-email.ts
4
+ /** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */
5
+ var CloudflareEmailError = class extends Error {
6
+ status;
7
+ errors;
8
+ name = "CloudflareEmailError";
9
+ constructor(status, errors) {
10
+ const said = errors.map((e) => `${e.code ?? "?"} ${e.message ?? ""}`.trim()).join("; ");
11
+ super(`Cloudflare Email send failed (${status})${said === "" ? "" : `: ${said}`}`);
12
+ this.status = status;
13
+ this.errors = errors;
14
+ }
15
+ };
16
+ function cloudflareEmailTransport(options) {
17
+ if (options.binding !== void 0) {
18
+ const { binding } = options;
19
+ return { async send(message) {
20
+ const id = (await binding.send(message))?.messageId;
21
+ return typeof id === "string" ? { providerMessageId: id } : {};
22
+ } };
23
+ }
24
+ const given = options;
25
+ if (typeof given.accountId !== "string" || typeof given.apiToken !== "string") throw new TypeError("cloudflareEmailTransport needs { binding } or { accountId, apiToken }");
26
+ const { accountId, apiToken } = options;
27
+ const endpoint = (options.endpoint ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, "");
28
+ const fetchImpl = options.fetch ?? fetch;
29
+ return { async send(message) {
30
+ const response = await fetchImpl(`${endpoint}/accounts/${encodeURIComponent(accountId)}/email/sending/send`, {
31
+ method: "POST",
32
+ headers: {
33
+ authorization: `Bearer ${apiToken}`,
34
+ "content-type": "application/json"
35
+ },
36
+ body: JSON.stringify({
37
+ from: require_email.mimeAddress(message.from),
38
+ to: message.to,
39
+ ...message.replyTo === void 0 ? {} : { reply_to: require_email.mimeAddress(message.replyTo) },
40
+ subject: message.subject,
41
+ html: message.html
42
+ })
43
+ });
44
+ let body = {};
45
+ try {
46
+ body = await response.json();
47
+ } catch {
48
+ body = {};
49
+ }
50
+ if (!response.ok || body.success !== true) throw new CloudflareEmailError(response.status, Array.isArray(body.errors) ? body.errors : []);
51
+ const id = body.result?.message_id;
52
+ return typeof id === "string" ? { providerMessageId: id } : {};
53
+ } };
54
+ }
55
+ //#endregion
56
+ exports.CloudflareEmailError = CloudflareEmailError;
57
+ exports.cloudflareEmailTransport = cloudflareEmailTransport;
58
+
59
+ //# sourceMappingURL=cloudflare-email.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-email.cjs","names":["mimeAddress"],"sources":["../../src/transports/cloudflare-email.ts"],"sourcesContent":["import type { EmailBindingLike } from '../cloudflare/bindings';\nimport { mimeAddress } from '../email';\nimport type { EmailMessage, EmailTransport } from '../email-sender';\n\n/**\n * `@shware/workflow/transports/cloudflare-email` — Cloudflare Email Service, through the\n * Worker's `send_email` binding or, from anywhere else (a Lambda), its REST API. Both take the\n * same finished email; only the call and the way each reports a failure differ.\n */\n\nexport type CloudflareEmailTransportOptions =\n | {\n /** The Worker's `send_email` binding. */\n binding: EmailBindingLike;\n accountId?: never;\n apiToken?: never;\n }\n | {\n binding?: never;\n accountId: string;\n /** An API token allowed to send email for the account. */\n apiToken: string;\n /** Defaults to `https://api.cloudflare.com/client/v4`. */\n endpoint?: string;\n fetch?: typeof fetch;\n };\n\n/** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */\nexport class CloudflareEmailError extends Error {\n override readonly name = 'CloudflareEmailError';\n constructor(\n readonly status: number,\n readonly errors: readonly { code?: number; message?: string }[]\n ) {\n const said = errors.map((e) => `${e.code ?? '?'} ${e.message ?? ''}`.trim()).join('; ');\n super(`Cloudflare Email send failed (${status})${said === '' ? '' : `: ${said}`}`);\n }\n}\n\nexport function cloudflareEmailTransport(options: CloudflareEmailTransportOptions): EmailTransport {\n if (options.binding !== undefined) {\n const { binding } = options;\n return {\n async send(message) {\n // The binding takes the key and drops the duplicate a retry or replay produces\n const result: unknown = await binding.send(message);\n const id = (result as { messageId?: unknown } | null | undefined)?.messageId;\n return typeof id === 'string' ? { providerMessageId: id } : {};\n },\n };\n }\n // Checked at runtime too: a JS caller can pass neither\n const given = options as { accountId?: unknown; apiToken?: unknown };\n if (typeof given.accountId !== 'string' || typeof given.apiToken !== 'string') {\n throw new TypeError('cloudflareEmailTransport needs { binding } or { accountId, apiToken }');\n }\n const { accountId, apiToken } = options;\n const endpoint = (options.endpoint ?? 'https://api.cloudflare.com/client/v4').replace(/\\/$/, '');\n const fetchImpl = options.fetch ?? fetch;\n return {\n async send(message: EmailMessage) {\n const response = await fetchImpl(\n `${endpoint}/accounts/${encodeURIComponent(accountId)}/email/sending/send`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n from: mimeAddress(message.from),\n to: message.to,\n ...(message.replyTo === undefined ? {} : { reply_to: mimeAddress(message.replyTo) }),\n subject: message.subject,\n html: message.html,\n }),\n }\n );\n let body: { success?: unknown; errors?: unknown; result?: { message_id?: unknown } } = {};\n try {\n body = (await response.json()) as typeof body;\n } catch {\n body = {};\n }\n if (!response.ok || body.success !== true) {\n throw new CloudflareEmailError(\n response.status,\n Array.isArray(body.errors) ? (body.errors as { code?: number; message?: string }[]) : []\n );\n }\n // No server-side de-duplication is documented for the REST API: a retry after an accepted\n // send can deliver twice (at least once, like SES)\n const id = body.result?.message_id;\n return typeof id === 'string' ? { providerMessageId: id } : {};\n },\n };\n}\n"],"mappings":";;;;AA4BA,IAAa,uBAAb,cAA0C,MAAM;CAGnC;CACA;CAHX,OAAyB;CACzB,YACE,QACA,QACA;EACA,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG,EAAE,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI;EACtF,MAAM,iCAAiC,OAAO,GAAG,SAAS,KAAK,KAAK,KAAK,QAAQ;EAJxE,KAAA,SAAA;EACA,KAAA,SAAA;CAIX;AACF;AAEA,SAAgB,yBAAyB,SAA0D;CACjG,IAAI,QAAQ,YAAY,KAAA,GAAW;EACjC,MAAM,EAAE,YAAY;EACpB,OAAO,EACL,MAAM,KAAK,SAAS;GAGlB,MAAM,MAAM,MADkB,QAAQ,KAAK,OAAO,EAAA,EACiB;GACnE,OAAO,OAAO,OAAO,WAAW,EAAE,mBAAmB,GAAG,IAAI,CAAC;EAC/D,EACF;CACF;CAEA,MAAM,QAAQ;CACd,IAAI,OAAO,MAAM,cAAc,YAAY,OAAO,MAAM,aAAa,UACnE,MAAM,IAAI,UAAU,uEAAuE;CAE7F,MAAM,EAAE,WAAW,aAAa;CAChC,MAAM,YAAY,QAAQ,YAAY,uCAAA,CAAwC,QAAQ,OAAO,EAAE;CAC/F,MAAM,YAAY,QAAQ,SAAS;CACnC,OAAO,EACL,MAAM,KAAK,SAAuB;EAChC,MAAM,WAAW,MAAM,UACrB,GAAG,SAAS,YAAY,mBAAmB,SAAS,EAAE,sBACtD;GACE,QAAQ;GACR,SAAS;IACP,eAAe,UAAU;IACzB,gBAAgB;GAClB;GACA,MAAM,KAAK,UAAU;IACnB,MAAMA,cAAAA,YAAY,QAAQ,IAAI;IAC9B,IAAI,QAAQ;IACZ,GAAI,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,UAAUA,cAAAA,YAAY,QAAQ,OAAO,EAAE;IAClF,SAAS,QAAQ;IACjB,MAAM,QAAQ;GAChB,CAAC;EACH,CACF;EACA,IAAI,OAAmF,CAAC;EACxF,IAAI;GACF,OAAQ,MAAM,SAAS,KAAK;EAC9B,QAAQ;GACN,OAAO,CAAC;EACV;EACA,IAAI,CAAC,SAAS,MAAM,KAAK,YAAY,MACnC,MAAM,IAAI,qBACR,SAAS,QACT,MAAM,QAAQ,KAAK,MAAM,IAAK,KAAK,SAAmD,CAAC,CACzF;EAIF,MAAM,KAAK,KAAK,QAAQ;EACxB,OAAO,OAAO,OAAO,WAAW,EAAE,mBAAmB,GAAG,IAAI,CAAC;CAC/D,EACF;AACF"}
@@ -0,0 +1,38 @@
1
+ import { EmailBindingLike } from "../cloudflare/bindings.cjs";
2
+ import { EmailTransport } from "../email-sender.cjs";
3
+ //#region src/transports/cloudflare-email.d.ts
4
+ /**
5
+ * `@shware/workflow/transports/cloudflare-email` — Cloudflare Email Service, through the
6
+ * Worker's `send_email` binding or, from anywhere else (a Lambda), its REST API. Both take the
7
+ * same finished email; only the call and the way each reports a failure differ.
8
+ */
9
+ export type CloudflareEmailTransportOptions = {
10
+ /** The Worker's `send_email` binding. */
11
+ binding: EmailBindingLike;
12
+ accountId?: never;
13
+ apiToken?: never;
14
+ } | {
15
+ binding?: never;
16
+ accountId: string;
17
+ /** An API token allowed to send email for the account. */
18
+ apiToken: string;
19
+ /** Defaults to `https://api.cloudflare.com/client/v4`. */
20
+ endpoint?: string;
21
+ fetch?: typeof fetch;
22
+ };
23
+ /** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */
24
+ export declare class CloudflareEmailError extends Error {
25
+ readonly status: number;
26
+ readonly errors: readonly {
27
+ code?: number;
28
+ message?: string;
29
+ }[];
30
+ readonly name = "CloudflareEmailError";
31
+ constructor(status: number, errors: readonly {
32
+ code?: number;
33
+ message?: string;
34
+ }[]);
35
+ }
36
+ export declare function cloudflareEmailTransport(options: CloudflareEmailTransportOptions): EmailTransport;
37
+ //#endregion
38
+ //# sourceMappingURL=cloudflare-email.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-email.d.cts","names":[],"sources":["../../src/transports/cloudflare-email.ts"],"mappings":";;;;;;;;YAUY;;EAGN,SAAS;EACT;EACA;;EAGA;EACA;;EAEA;;EAEA;EACA,eAAe;;;qBAIR,6BAA6B;WAG7B;WACA;IAAmB;IAAe;;WAH3B;EAClB,YACW,gBACA;IAAmB;IAAe;;;wBAO/B,yBAAyB,SAAS,kCAAkC"}
@@ -0,0 +1,38 @@
1
+ import { EmailBindingLike } from "../cloudflare/bindings.mjs";
2
+ import { EmailTransport } from "../email-sender.mjs";
3
+ //#region src/transports/cloudflare-email.d.ts
4
+ /**
5
+ * `@shware/workflow/transports/cloudflare-email` — Cloudflare Email Service, through the
6
+ * Worker's `send_email` binding or, from anywhere else (a Lambda), its REST API. Both take the
7
+ * same finished email; only the call and the way each reports a failure differ.
8
+ */
9
+ export type CloudflareEmailTransportOptions = {
10
+ /** The Worker's `send_email` binding. */
11
+ binding: EmailBindingLike;
12
+ accountId?: never;
13
+ apiToken?: never;
14
+ } | {
15
+ binding?: never;
16
+ accountId: string;
17
+ /** An API token allowed to send email for the account. */
18
+ apiToken: string;
19
+ /** Defaults to `https://api.cloudflare.com/client/v4`. */
20
+ endpoint?: string;
21
+ fetch?: typeof fetch;
22
+ };
23
+ /** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */
24
+ export declare class CloudflareEmailError extends Error {
25
+ readonly status: number;
26
+ readonly errors: readonly {
27
+ code?: number;
28
+ message?: string;
29
+ }[];
30
+ readonly name = "CloudflareEmailError";
31
+ constructor(status: number, errors: readonly {
32
+ code?: number;
33
+ message?: string;
34
+ }[]);
35
+ }
36
+ export declare function cloudflareEmailTransport(options: CloudflareEmailTransportOptions): EmailTransport;
37
+ //#endregion
38
+ //# sourceMappingURL=cloudflare-email.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-email.d.mts","names":[],"sources":["../../src/transports/cloudflare-email.ts"],"mappings":";;;;;;;;YAUY;;EAGN,SAAS;EACT;EACA;;EAGA;EACA;;EAEA;;EAEA;EACA,eAAe;;;qBAIR,6BAA6B;WAG7B;WACA;IAAmB;IAAe;;WAH3B;EAClB,YACW,gBACA;IAAmB;IAAe;;;wBAO/B,yBAAyB,SAAS,kCAAkC"}
@@ -0,0 +1,57 @@
1
+ import { mimeAddress } from "../email.mjs";
2
+ //#region src/transports/cloudflare-email.ts
3
+ /** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */
4
+ var CloudflareEmailError = class extends Error {
5
+ status;
6
+ errors;
7
+ name = "CloudflareEmailError";
8
+ constructor(status, errors) {
9
+ const said = errors.map((e) => `${e.code ?? "?"} ${e.message ?? ""}`.trim()).join("; ");
10
+ super(`Cloudflare Email send failed (${status})${said === "" ? "" : `: ${said}`}`);
11
+ this.status = status;
12
+ this.errors = errors;
13
+ }
14
+ };
15
+ function cloudflareEmailTransport(options) {
16
+ if (options.binding !== void 0) {
17
+ const { binding } = options;
18
+ return { async send(message) {
19
+ const id = (await binding.send(message))?.messageId;
20
+ return typeof id === "string" ? { providerMessageId: id } : {};
21
+ } };
22
+ }
23
+ const given = options;
24
+ if (typeof given.accountId !== "string" || typeof given.apiToken !== "string") throw new TypeError("cloudflareEmailTransport needs { binding } or { accountId, apiToken }");
25
+ const { accountId, apiToken } = options;
26
+ const endpoint = (options.endpoint ?? "https://api.cloudflare.com/client/v4").replace(/\/$/, "");
27
+ const fetchImpl = options.fetch ?? fetch;
28
+ return { async send(message) {
29
+ const response = await fetchImpl(`${endpoint}/accounts/${encodeURIComponent(accountId)}/email/sending/send`, {
30
+ method: "POST",
31
+ headers: {
32
+ authorization: `Bearer ${apiToken}`,
33
+ "content-type": "application/json"
34
+ },
35
+ body: JSON.stringify({
36
+ from: mimeAddress(message.from),
37
+ to: message.to,
38
+ ...message.replyTo === void 0 ? {} : { reply_to: mimeAddress(message.replyTo) },
39
+ subject: message.subject,
40
+ html: message.html
41
+ })
42
+ });
43
+ let body = {};
44
+ try {
45
+ body = await response.json();
46
+ } catch {
47
+ body = {};
48
+ }
49
+ if (!response.ok || body.success !== true) throw new CloudflareEmailError(response.status, Array.isArray(body.errors) ? body.errors : []);
50
+ const id = body.result?.message_id;
51
+ return typeof id === "string" ? { providerMessageId: id } : {};
52
+ } };
53
+ }
54
+ //#endregion
55
+ export { CloudflareEmailError, cloudflareEmailTransport };
56
+
57
+ //# sourceMappingURL=cloudflare-email.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-email.mjs","names":[],"sources":["../../src/transports/cloudflare-email.ts"],"sourcesContent":["import type { EmailBindingLike } from '../cloudflare/bindings';\nimport { mimeAddress } from '../email';\nimport type { EmailMessage, EmailTransport } from '../email-sender';\n\n/**\n * `@shware/workflow/transports/cloudflare-email` — Cloudflare Email Service, through the\n * Worker's `send_email` binding or, from anywhere else (a Lambda), its REST API. Both take the\n * same finished email; only the call and the way each reports a failure differ.\n */\n\nexport type CloudflareEmailTransportOptions =\n | {\n /** The Worker's `send_email` binding. */\n binding: EmailBindingLike;\n accountId?: never;\n apiToken?: never;\n }\n | {\n binding?: never;\n accountId: string;\n /** An API token allowed to send email for the account. */\n apiToken: string;\n /** Defaults to `https://api.cloudflare.com/client/v4`. */\n endpoint?: string;\n fetch?: typeof fetch;\n };\n\n/** The REST API refused the email: `errors` are Cloudflare's `{ code, message }` pairs. */\nexport class CloudflareEmailError extends Error {\n override readonly name = 'CloudflareEmailError';\n constructor(\n readonly status: number,\n readonly errors: readonly { code?: number; message?: string }[]\n ) {\n const said = errors.map((e) => `${e.code ?? '?'} ${e.message ?? ''}`.trim()).join('; ');\n super(`Cloudflare Email send failed (${status})${said === '' ? '' : `: ${said}`}`);\n }\n}\n\nexport function cloudflareEmailTransport(options: CloudflareEmailTransportOptions): EmailTransport {\n if (options.binding !== undefined) {\n const { binding } = options;\n return {\n async send(message) {\n // The binding takes the key and drops the duplicate a retry or replay produces\n const result: unknown = await binding.send(message);\n const id = (result as { messageId?: unknown } | null | undefined)?.messageId;\n return typeof id === 'string' ? { providerMessageId: id } : {};\n },\n };\n }\n // Checked at runtime too: a JS caller can pass neither\n const given = options as { accountId?: unknown; apiToken?: unknown };\n if (typeof given.accountId !== 'string' || typeof given.apiToken !== 'string') {\n throw new TypeError('cloudflareEmailTransport needs { binding } or { accountId, apiToken }');\n }\n const { accountId, apiToken } = options;\n const endpoint = (options.endpoint ?? 'https://api.cloudflare.com/client/v4').replace(/\\/$/, '');\n const fetchImpl = options.fetch ?? fetch;\n return {\n async send(message: EmailMessage) {\n const response = await fetchImpl(\n `${endpoint}/accounts/${encodeURIComponent(accountId)}/email/sending/send`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n from: mimeAddress(message.from),\n to: message.to,\n ...(message.replyTo === undefined ? {} : { reply_to: mimeAddress(message.replyTo) }),\n subject: message.subject,\n html: message.html,\n }),\n }\n );\n let body: { success?: unknown; errors?: unknown; result?: { message_id?: unknown } } = {};\n try {\n body = (await response.json()) as typeof body;\n } catch {\n body = {};\n }\n if (!response.ok || body.success !== true) {\n throw new CloudflareEmailError(\n response.status,\n Array.isArray(body.errors) ? (body.errors as { code?: number; message?: string }[]) : []\n );\n }\n // No server-side de-duplication is documented for the REST API: a retry after an accepted\n // send can deliver twice (at least once, like SES)\n const id = body.result?.message_id;\n return typeof id === 'string' ? { providerMessageId: id } : {};\n },\n };\n}\n"],"mappings":";;;AA4BA,IAAa,uBAAb,cAA0C,MAAM;CAGnC;CACA;CAHX,OAAyB;CACzB,YACE,QACA,QACA;EACA,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG,EAAE,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI;EACtF,MAAM,iCAAiC,OAAO,GAAG,SAAS,K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AAO,OAAO,OAAO,WAAW,EAAE,mBAAmB,GAAG,IAAI,CAAC;CAC/D,EACF;AACF"}
@@ -0,0 +1,91 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_email = require("../email.cjs");
3
+ const require_transports_sigv4 = require("./sigv4.cjs");
4
+ //#region src/transports/ses.ts
5
+ /** An SES error response: `type` is SES's error code (`MessageRejected`, `TooManyRequestsException`, ...). */
6
+ var SesSendError = class extends Error {
7
+ status;
8
+ type;
9
+ name = "SesSendError";
10
+ constructor(status, type, message) {
11
+ super(`SES SendEmail failed (${status}${type === void 0 ? "" : ` ${type}`}): ${message}`);
12
+ this.status = status;
13
+ this.type = type;
14
+ }
15
+ };
16
+ function environmentCredentials() {
17
+ const env = globalThis.process?.env;
18
+ const accessKeyId = env?.AWS_ACCESS_KEY_ID;
19
+ const secretAccessKey = env?.AWS_SECRET_ACCESS_KEY;
20
+ if (accessKeyId === void 0 || secretAccessKey === void 0) throw new Error("sesEmailTransport: no credentials — pass `credentials`, or run where AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set (a Lambda execution role)");
21
+ return {
22
+ accessKeyId,
23
+ secretAccessKey,
24
+ sessionToken: env?.AWS_SESSION_TOKEN
25
+ };
26
+ }
27
+ function sesEmailTransport(options) {
28
+ const endpoint = (options.endpoint ?? `https://email.${options.region}.amazonaws.com`).replace(/\/$/, "");
29
+ const credentials = async () => {
30
+ const configured = options.credentials;
31
+ if (configured === void 0) return environmentCredentials();
32
+ return typeof configured === "function" ? configured() : configured;
33
+ };
34
+ const fetchImpl = options.fetch ?? fetch;
35
+ return { async send(message) {
36
+ const body = JSON.stringify({
37
+ FromEmailAddress: require_email.mimeAddress(message.from),
38
+ Destination: { ToAddresses: [message.to] },
39
+ ...message.replyTo === void 0 ? {} : { ReplyToAddresses: [require_email.mimeAddress(message.replyTo)] },
40
+ Content: { Simple: {
41
+ Subject: {
42
+ Data: message.subject,
43
+ Charset: "UTF-8"
44
+ },
45
+ Body: { Html: {
46
+ Data: message.html,
47
+ Charset: "UTF-8"
48
+ } }
49
+ } },
50
+ ...options.configurationSetName === void 0 ? {} : { ConfigurationSetName: options.configurationSetName }
51
+ });
52
+ const url = `${endpoint}/v2/email/outbound-emails`;
53
+ const headers = await require_transports_sigv4.signRequest({
54
+ method: "POST",
55
+ url,
56
+ headers: { "content-type": "application/json" },
57
+ body,
58
+ credentials: await credentials(),
59
+ region: options.region,
60
+ service: "ses"
61
+ });
62
+ const response = await fetchImpl(url, {
63
+ method: "POST",
64
+ headers,
65
+ body
66
+ });
67
+ const text = await response.text();
68
+ if (!response.ok) {
69
+ let detail = text;
70
+ try {
71
+ const parsed = JSON.parse(text);
72
+ const said = parsed.message ?? parsed.Message;
73
+ if (typeof said === "string") detail = said;
74
+ } catch {}
75
+ const type = response.headers.get("x-amzn-errortype")?.split(":")[0];
76
+ throw new SesSendError(response.status, type, detail);
77
+ }
78
+ let messageId;
79
+ try {
80
+ messageId = JSON.parse(text).MessageId;
81
+ } catch {
82
+ messageId = void 0;
83
+ }
84
+ return typeof messageId === "string" ? { providerMessageId: messageId } : {};
85
+ } };
86
+ }
87
+ //#endregion
88
+ exports.SesSendError = SesSendError;
89
+ exports.sesEmailTransport = sesEmailTransport;
90
+
91
+ //# sourceMappingURL=ses.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ses.cjs","names":["mimeAddress","signRequest"],"sources":["../../src/transports/ses.ts"],"sourcesContent":["import { mimeAddress } from '../email';\nimport type { EmailMessage, EmailTransport } from '../email-sender';\nimport { signRequest } from './sigv4';\n\n/**\n * `@shware/workflow/transports/ses` — email through Amazon SES (the v2 `SendEmail` API) over\n * plain `fetch` with a SigV4 signature, so the same transport runs in a Lambda and in a Worker.\n * Nothing here loads the AWS SDK or a Node-only credential chain.\n */\n\nexport interface AwsCredentials {\n accessKeyId: string;\n secretAccessKey: string;\n /** Present for temporary credentials (a role's): signed with the request. */\n sessionToken?: string | undefined;\n}\n\n/** Called on every send, so rotated temporary credentials are picked up rather than frozen. */\nexport type AwsCredentialProvider = () => AwsCredentials | Promise<AwsCredentials>;\n\nexport interface SesEmailTransportOptions {\n region: string;\n /**\n * Fixed credentials, or a provider read on every send. Defaults to the process environment's\n * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`, read at send time —\n * a Lambda's execution role. A Worker passes them explicitly from its validated env.\n */\n credentials?: AwsCredentials | AwsCredentialProvider;\n /** An SES configuration set (event publishing, a dedicated IP pool). */\n configurationSetName?: string;\n /** Defaults to `https://email.<region>.amazonaws.com`. */\n endpoint?: string;\n fetch?: typeof fetch;\n}\n\n/** An SES error response: `type` is SES's error code (`MessageRejected`, `TooManyRequestsException`, ...). */\nexport class SesSendError extends Error {\n override readonly name = 'SesSendError';\n constructor(\n readonly status: number,\n readonly type: string | undefined,\n message: string\n ) {\n super(`SES SendEmail failed (${status}${type === undefined ? '' : ` ${type}`}): ${message}`);\n }\n}\n\nfunction environmentCredentials(): AwsCredentials {\n // Read through globalThis: a Worker has no `process`, and must pass credentials instead\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n const accessKeyId = env?.AWS_ACCESS_KEY_ID;\n const secretAccessKey = env?.AWS_SECRET_ACCESS_KEY;\n if (accessKeyId === undefined || secretAccessKey === undefined) {\n throw new Error(\n 'sesEmailTransport: no credentials — pass `credentials`, or run where AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set (a Lambda execution role)'\n );\n }\n return { accessKeyId, secretAccessKey, sessionToken: env?.AWS_SESSION_TOKEN };\n}\n\nexport function sesEmailTransport(options: SesEmailTransportOptions): EmailTransport {\n const endpoint = (options.endpoint ?? `https://email.${options.region}.amazonaws.com`).replace(\n /\\/$/,\n ''\n );\n const credentials = async (): Promise<AwsCredentials> => {\n const configured = options.credentials;\n if (configured === undefined) return environmentCredentials();\n return typeof configured === 'function' ? configured() : configured;\n };\n const fetchImpl = options.fetch ?? fetch;\n\n return {\n async send(message: EmailMessage) {\n const body = JSON.stringify({\n FromEmailAddress: mimeAddress(message.from),\n Destination: { ToAddresses: [message.to] },\n ...(message.replyTo === undefined\n ? {}\n : { ReplyToAddresses: [mimeAddress(message.replyTo)] }),\n Content: {\n Simple: {\n Subject: { Data: message.subject, Charset: 'UTF-8' },\n Body: { Html: { Data: message.html, Charset: 'UTF-8' } },\n },\n },\n ...(options.configurationSetName === undefined\n ? {}\n : { ConfigurationSetName: options.configurationSetName }),\n });\n const url = `${endpoint}/v2/email/outbound-emails`;\n const headers = await signRequest({\n method: 'POST',\n url,\n headers: { 'content-type': 'application/json' },\n body,\n credentials: await credentials(),\n region: options.region,\n service: 'ses',\n });\n // No retries here: the durable step owns them, and counts them — SES cannot de-duplicate,\n // so every extra attempt of an accepted send is another chance to deliver twice\n const response = await fetchImpl(url, { method: 'POST', headers, body });\n const text = await response.text();\n if (!response.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { message?: unknown; Message?: unknown };\n const said = parsed.message ?? parsed.Message;\n if (typeof said === 'string') detail = said;\n } catch {\n // Not JSON: the raw body says what went wrong\n }\n const type = response.headers.get('x-amzn-errortype')?.split(':')[0];\n throw new SesSendError(response.status, type, detail);\n }\n let messageId: unknown;\n try {\n messageId = (JSON.parse(text) as { MessageId?: unknown }).MessageId;\n } catch {\n messageId = undefined;\n }\n return typeof messageId === 'string' ? { providerMessageId: messageId } : {};\n },\n };\n}\n"],"mappings":";;;;;AAoCA,IAAa,eAAb,cAAkC,MAAM;CAG3B;CACA;CAHX,OAAyB;CACzB,YACE,QACA,MACA,SACA;EACA,MAAM,yBAAyB,SAAS,SAAS,KAAA,IAAY,KAAK,IAAI,OAAO,KAAK,SAAS;EAJlF,KAAA,SAAA;EACA,KAAA,OAAA;CAIX;AACF;AAEA,SAAS,yBAAyC;CAEhD,MAAM,MAAO,WAA0E,SACnF;CACJ,MAAM,cAAc,KAAK;CACzB,MAAM,kBAAkB,KAAK;CA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,KAAK;EACjC,IAAI,CAAC,SAAS,IAAI;GAChB,IAAI,SAAS;GACb,IAAI;IACF,MAAM,SAAS,KAAK,MAAM,IAAI;IAC9B,MAAM,OAAO,OAAO,WAAW,OAAO;IACtC,IAAI,OAAO,SAAS,UAAU,SAAS;GACzC,QAAQ,CAER;GACA,MAAM,OAAO,SAAS,QAAQ,IAAI,kBAAkB,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC;GAClE,MAAM,IAAI,aAAa,SAAS,QAAQ,MAAM,MAAM;EACtD;EACA,IAAI;EACJ,IAAI;GACF,YAAa,KAAK,MAAM,IAAI,CAAC,CAA6B;EAC5D,QAAQ;GACN,YAAY,KAAA;EACd;EACA,OAAO,OAAO,cAAc,WAAW,EAAE,mBAAmB,UAAU,IAAI,CAAC;CAC7E,EACF;AACF"}
@@ -0,0 +1,39 @@
1
+ import { EmailTransport } from "../email-sender.cjs";
2
+ //#region src/transports/ses.d.ts
3
+ /**
4
+ * `@shware/workflow/transports/ses` — email through Amazon SES (the v2 `SendEmail` API) over
5
+ * plain `fetch` with a SigV4 signature, so the same transport runs in a Lambda and in a Worker.
6
+ * Nothing here loads the AWS SDK or a Node-only credential chain.
7
+ */
8
+ export interface AwsCredentials {
9
+ accessKeyId: string;
10
+ secretAccessKey: string;
11
+ /** Present for temporary credentials (a role's): signed with the request. */
12
+ sessionToken?: string | undefined;
13
+ }
14
+ /** Called on every send, so rotated temporary credentials are picked up rather than frozen. */
15
+ export type AwsCredentialProvider = () => AwsCredentials | Promise<AwsCredentials>;
16
+ export interface SesEmailTransportOptions {
17
+ region: string;
18
+ /**
19
+ * Fixed credentials, or a provider read on every send. Defaults to the process environment's
20
+ * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`, read at send time —
21
+ * a Lambda's execution role. A Worker passes them explicitly from its validated env.
22
+ */
23
+ credentials?: AwsCredentials | AwsCredentialProvider;
24
+ /** An SES configuration set (event publishing, a dedicated IP pool). */
25
+ configurationSetName?: string;
26
+ /** Defaults to `https://email.<region>.amazonaws.com`. */
27
+ endpoint?: string;
28
+ fetch?: typeof fetch;
29
+ }
30
+ /** An SES error response: `type` is SES's error code (`MessageRejected`, `TooManyRequestsException`, ...). */
31
+ export declare class SesSendError extends Error {
32
+ readonly status: number;
33
+ readonly type: string | undefined;
34
+ readonly name = "SesSendError";
35
+ constructor(status: number, type: string | undefined, message: string);
36
+ }
37
+ export declare function sesEmailTransport(options: SesEmailTransportOptions): EmailTransport;
38
+ //#endregion
39
+ //# sourceMappingURL=ses.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ses.d.cts","names":[],"sources":["../../src/transports/ses.ts"],"mappings":";;;;;;;iBAUiB;EACf;EACA;;EAEA;;;YAIU,8BAA8B,iBAAiB,QAAQ;iBAElD;EACf;;;;;;EAMA,cAAc,iBAAiB;;EAE/B;;EAEA;EACA,eAAe;;;qBAIJ,qBAAqB;WAGrB;WACA;WAHO;EAClB,YACW,gBACA,0BACT;;wBAoBY,kBAAkB,SAAS,2BAA2B"}
@@ -0,0 +1,39 @@
1
+ import { EmailTransport } from "../email-sender.mjs";
2
+ //#region src/transports/ses.d.ts
3
+ /**
4
+ * `@shware/workflow/transports/ses` — email through Amazon SES (the v2 `SendEmail` API) over
5
+ * plain `fetch` with a SigV4 signature, so the same transport runs in a Lambda and in a Worker.
6
+ * Nothing here loads the AWS SDK or a Node-only credential chain.
7
+ */
8
+ export interface AwsCredentials {
9
+ accessKeyId: string;
10
+ secretAccessKey: string;
11
+ /** Present for temporary credentials (a role's): signed with the request. */
12
+ sessionToken?: string | undefined;
13
+ }
14
+ /** Called on every send, so rotated temporary credentials are picked up rather than frozen. */
15
+ export type AwsCredentialProvider = () => AwsCredentials | Promise<AwsCredentials>;
16
+ export interface SesEmailTransportOptions {
17
+ region: string;
18
+ /**
19
+ * Fixed credentials, or a provider read on every send. Defaults to the process environment's
20
+ * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`, read at send time —
21
+ * a Lambda's execution role. A Worker passes them explicitly from its validated env.
22
+ */
23
+ credentials?: AwsCredentials | AwsCredentialProvider;
24
+ /** An SES configuration set (event publishing, a dedicated IP pool). */
25
+ configurationSetName?: string;
26
+ /** Defaults to `https://email.<region>.amazonaws.com`. */
27
+ endpoint?: string;
28
+ fetch?: typeof fetch;
29
+ }
30
+ /** An SES error response: `type` is SES's error code (`MessageRejected`, `TooManyRequestsException`, ...). */
31
+ export declare class SesSendError extends Error {
32
+ readonly status: number;
33
+ readonly type: string | undefined;
34
+ readonly name = "SesSendError";
35
+ constructor(status: number, type: string | undefined, message: string);
36
+ }
37
+ export declare function sesEmailTransport(options: SesEmailTransportOptions): EmailTransport;
38
+ //#endregion
39
+ //# sourceMappingURL=ses.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ses.d.mts","names":[],"sources":["../../src/transports/ses.ts"],"mappings":";;;;;;;iBAUiB;EACf;EACA;;EAEA;;;YAIU,8BAA8B,iBAAiB,QAAQ;iBAElD;EACf;;;;;;EAMA,cAAc,iBAAiB;;EAE/B;;EAEA;EACA,eAAe;;;qBAIJ,qBAAqB;WAGrB;WACA;WAHO;EAClB,YACW,gBACA,0BACT;;wBAoBY,kBAAkB,SAAS,2BAA2B"}