@fabrika/email 0.9.0-dev.3 → 0.9.0-dev.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/resend.ts CHANGED
@@ -1,80 +1,65 @@
1
1
  import { z } from 'zod'
2
- import { type EmailProvider, type EmailSenderIdentity, parseProviderVariables } from './config.js'
2
+ import { type EmailProvider, parseProviderVariables } from './config.js'
3
3
  import { base64Of } from './content.js'
4
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
4
5
  import {
5
- EmailDeliveryError,
6
- type EmailDeliveryResult,
7
- type EmailFetch,
8
- type EmailMessage,
9
- type EmailSender,
10
- type EmailSenderCapabilities,
11
- oneClickUnsubscribeHeaders,
12
- } from './email.js'
13
- import { parseTimeout, postToProvider, type ProviderResponse } from './http.js'
14
- import { isValidEmailSenderIdentity, isVisibleAscii, validateEmailAttachments, validateEmailMessage } from './validation.js'
6
+ credentialVariable,
7
+ formatMailbox,
8
+ type HttpEmailRequest,
9
+ HttpEmailSender,
10
+ type HttpEmailSenderOptions,
11
+ isCredential,
12
+ } from './http-sender.js'
13
+ import type { ProviderResponse } from './http.js'
15
14
 
16
15
  const RESEND_EMAILS_URL = 'https://api.resend.com/emails'
17
16
  const LABEL = 'Resend'
18
- const resendSuccessSchema = z.object({ id: z.string().min(1) })
17
+ const BROADCAST_TAG = { name: 'category', value: 'broadcast' }
18
+ const resendSuccessSchema = z.object({ id: z.string() })
19
19
  const resendErrorSchema = z.object({ name: z.string() })
20
20
  const QUOTA_ERRORS: ReadonlySet<string> = new Set(['daily_quota_exceeded', 'monthly_quota_exceeded'])
21
- /** RFC 5322 specials a display name may still hold after validation; any of them makes the name a quoted string. */
22
- const DISPLAY_NAME_SPECIALS = /[()[\]:;@,.]/
23
21
  /** Resend refuses a message over 40 MB once its attachments are base64; 25 MiB of bytes leaves room for the rest. */
24
22
  const RESEND_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
25
23
 
26
- export interface ResendEmailSenderOptions {
24
+ export interface ResendEmailSenderOptions extends HttpEmailSenderOptions {
27
25
  readonly apiKey: string
28
- readonly from: EmailSenderIdentity
29
- readonly fetch?: EmailFetch
30
- readonly timeoutMs?: number
31
26
  }
32
27
 
33
- export class ResendEmailSender implements EmailSender {
28
+ export class ResendEmailSender extends HttpEmailSender {
34
29
  readonly capabilities: EmailSenderCapabilities = {
35
30
  idempotent: true,
36
31
  confirmation: 'sync',
37
32
  maxBatch: 1,
38
33
  listUnsubscribe: true,
39
34
  maxAttachmentBytes: RESEND_MAX_ATTACHMENT_BYTES,
35
+ // Resend takes one-to-one marketing mail through this API, with consent and an unsubscribe; it has no channel apart.
36
+ broadcast: true,
40
37
  }
41
38
  readonly #apiKey: string
42
- readonly #from: EmailSenderIdentity
43
- readonly #fetch: EmailFetch
44
- readonly #timeoutMs: number
45
39
 
46
40
  constructor(options: ResendEmailSenderOptions) {
47
- if (!validApiKey(options.apiKey)) {
41
+ if (!isCredential(options.apiKey)) {
48
42
  throw new EmailDeliveryError('Resend API key is invalid', { code: 'invalid_configuration' })
49
43
  }
50
- if (!isValidEmailSenderIdentity(options.from)) {
51
- throw new EmailDeliveryError('Resend sender is invalid', { code: 'invalid_configuration' })
52
- }
53
-
44
+ super({ label: LABEL, provider: 'resend' }, options)
54
45
  this.#apiKey = options.apiKey
55
- this.#from = options.from
56
- this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init))
57
- this.#timeoutMs = parseTimeout(LABEL, options.timeoutMs)
58
46
  }
59
47
 
60
- async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
61
- validateEmailMessage(message)
62
- validateEmailAttachments(message, this.capabilities, LABEL)
48
+ protected request(message: EmailMessage): HttpEmailRequest {
63
49
  const attachments = message.attachments ?? []
64
-
65
- const response = await postToProvider({
66
- label: LABEL,
67
- fetch: this.#fetch,
50
+ return {
68
51
  url: RESEND_EMAILS_URL,
69
52
  headers: { Authorization: `Bearer ${this.#apiKey}`, 'Idempotency-Key': message.idempotencyKey },
70
53
  body: {
71
- from: formatMailbox(this.#from.address, message.fromName ?? this.#from.name),
54
+ from: formatMailbox(this.from.address, message.fromName ?? this.from.name),
72
55
  to: message.to,
73
56
  subject: message.subject,
74
57
  text: message.text,
75
58
  ...(message.html === undefined ? {} : { html: message.html }),
76
59
  ...(message.replyTo === undefined ? {} : { reply_to: message.replyTo }),
77
60
  ...(message.unsubscribeUrl === undefined ? {} : { headers: oneClickUnsubscribeHeaders(message.unsubscribeUrl) }),
61
+ // Tagged, so the account's logs and webhooks tell broadcast mail from transactional.
62
+ ...(message.broadcast === true ? { tags: [BROADCAST_TAG] } : {}),
78
63
  ...(attachments.length === 0
79
64
  ? {}
80
65
  : {
@@ -85,22 +70,37 @@ export class ResendEmailSender implements EmailSender {
85
70
  })),
86
71
  }),
87
72
  },
88
- signal,
89
- timeoutMs: this.#timeoutMs,
90
- })
73
+ }
74
+ }
91
75
 
92
- if (!response.ok) throw responseError(response)
76
+ protected messageId(response: ProviderResponse): string | undefined {
77
+ return resendSuccessSchema.safeParse(response.body).data?.id
78
+ }
93
79
 
94
- const parsed = resendSuccessSchema.safeParse(response.body)
95
- if (!parsed.success) {
96
- throw new EmailDeliveryError('Resend returned an invalid success response', { code: 'malformed_response', httpStatus: response.status })
80
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
81
+ const status = response.status
82
+ const name = resendErrorSchema.safeParse(response.body).data?.name
83
+ if (status === 401 || status === 403) {
84
+ // A 403 is also an unverified sender domain.
85
+ return new EmailDeliveryError(`Resend refused the credentials or the sender (${status})`, { code: 'provider_unauthorized', httpStatus: status })
97
86
  }
98
-
99
- return { status: 'accepted', provider: 'resend', messageId: parsed.data.id }
87
+ if (status === 409 && name === 'concurrent_idempotent_requests') {
88
+ return new EmailDeliveryError('A matching Resend request is still in progress', { code: 'request_in_progress', httpStatus: status })
89
+ }
90
+ if (status === 409 && name === 'invalid_idempotent_request') {
91
+ return new EmailDeliveryError('Resend already accepted a different message under this idempotency key', {
92
+ code: 'idempotency_conflict',
93
+ httpStatus: status,
94
+ })
95
+ }
96
+ if (status === 429 && name !== undefined && QUOTA_ERRORS.has(name)) {
97
+ return new EmailDeliveryError('Resend sending quota exceeded', { code: 'quota_exceeded', httpStatus: status })
98
+ }
99
+ return undefined
100
100
  }
101
101
  }
102
102
 
103
- const resendVariablesSchema = z.object({ FABRIKA_EMAIL_RESEND_API_KEY: z.string().refine(validApiKey) })
103
+ const resendVariablesSchema = z.object({ FABRIKA_EMAIL_RESEND_API_KEY: credentialVariable })
104
104
 
105
105
  export const resendEmailProvider: EmailProvider = {
106
106
  variables: [{ name: 'FABRIKA_EMAIL_RESEND_API_KEY', secret: true, required: true }],
@@ -109,40 +109,3 @@ export const resendEmailProvider: EmailProvider = {
109
109
  return new ResendEmailSender({ apiKey: variables.FABRIKA_EMAIL_RESEND_API_KEY, from, fetch })
110
110
  },
111
111
  }
112
-
113
- function responseError(response: ProviderResponse): EmailDeliveryError {
114
- const status = response.status
115
- const parsed = resendErrorSchema.safeParse(response.body)
116
- const name = parsed.success ? parsed.data.name : undefined
117
- if (status === 401 || status === 403) {
118
- return new EmailDeliveryError(`Resend refused the credentials or the sender (${status})`, { code: 'provider_unauthorized', httpStatus: status })
119
- }
120
- if (status === 409 && name === 'concurrent_idempotent_requests') {
121
- return new EmailDeliveryError('A matching Resend request is still in progress', { code: 'request_in_progress', httpStatus: status })
122
- }
123
- if (status === 409 && name === 'invalid_idempotent_request') {
124
- return new EmailDeliveryError('Resend already accepted a different message under this idempotency key', {
125
- code: 'idempotency_conflict',
126
- httpStatus: status,
127
- })
128
- }
129
- if (status === 429 && name !== undefined && QUOTA_ERRORS.has(name)) {
130
- return new EmailDeliveryError('Resend sending quota exceeded', { code: 'quota_exceeded', httpStatus: status })
131
- }
132
- if (status === 429) {
133
- return new EmailDeliveryError('Resend rate limit exceeded', { code: 'rate_limited', httpStatus: status })
134
- }
135
- if (status >= 500) {
136
- return new EmailDeliveryError('Resend is unavailable', { code: 'provider_unavailable', httpStatus: status })
137
- }
138
- return new EmailDeliveryError(`Resend rejected the request (${status})`, { code: 'provider_rejected', httpStatus: status })
139
- }
140
-
141
- function formatMailbox(address: string, name: string | undefined): string {
142
- if (name === undefined) return address
143
- return DISPLAY_NAME_SPECIALS.test(name) ? `"${name}" <${address}>` : `${name} <${address}>`
144
- }
145
-
146
- function validApiKey(value: string): boolean {
147
- return value.length > 0 && isVisibleAscii(value)
148
- }
@@ -2,83 +2,66 @@
2
2
  // verified only against a stubbed fetch. It has no idempotency key, and a 201 only queues the request.
3
3
 
4
4
  import { z } from 'zod'
5
- import { type EmailProvider, type EmailSenderIdentity, parseProviderVariables } from './config.js'
5
+ import { type EmailProvider, parseProviderVariables } from './config.js'
6
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js'
6
7
  import {
7
- EmailDeliveryError,
8
- type EmailDeliveryResult,
9
- type EmailFetch,
10
- type EmailMessage,
11
- type EmailSender,
12
- type EmailSenderCapabilities,
13
- } from './email.js'
14
- import { parseTimeout, postToProvider } from './http.js'
15
- import { isValidEmailSenderIdentity, isVisibleAscii, validateEmailAttachments, validateEmailMessage } from './validation.js'
8
+ credentialVariable,
9
+ type HttpEmailRequest,
10
+ HttpEmailSender,
11
+ type HttpEmailSenderOptions,
12
+ isCredential,
13
+ optionalVariable,
14
+ } from './http-sender.js'
15
+ import type { ProviderResponse } from './http.js'
16
16
 
17
17
  const SMARTEMAILING_SEND_URL = 'https://app.smartemailing.cz/api/v3/send/transactional-emails-bulk'
18
- const LABEL = 'SmartEmailing'
19
18
  const DEFAULT_TAG = 'fabrika'
20
19
  const TAG_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
21
- const smartEmailingSuccessSchema = z.object({ data: z.tuple([z.object({ id: z.string().min(1) })]) })
20
+ const smartEmailingSuccessSchema = z.object({ data: z.tuple([z.object({ id: z.string() })]) })
22
21
 
23
- export interface SmartEmailingEmailSenderOptions {
22
+ export interface SmartEmailingEmailSenderOptions extends HttpEmailSenderOptions {
24
23
  /** The account's user name or e-mail: the first half of the Basic credential. */
25
24
  readonly username: string
26
25
  readonly apiKey: string
27
- readonly from: EmailSenderIdentity
28
26
  /** Groups the messages in SmartEmailing's statistics. */
29
27
  readonly tag?: string
30
- readonly fetch?: EmailFetch
31
- readonly timeoutMs?: number
32
28
  }
33
29
 
34
- export class SmartEmailingEmailSender implements EmailSender {
35
- /** The API takes up to five tasks a request, but `send` carries one. */
30
+ /** Its error body's `message` is free text that may quote the request, so a refusal is classified by status alone. */
31
+ export class SmartEmailingEmailSender extends HttpEmailSender {
32
+ /**
33
+ * The API takes up to five tasks a request, but `send` carries one. Its API documents no message headers, so a
34
+ * one-click unsubscribe is refused rather than sent without one.
35
+ */
36
36
  readonly capabilities: EmailSenderCapabilities = { idempotent: false, confirmation: 'queued', maxBatch: 1 }
37
37
  readonly #authorization: string
38
- readonly #from: EmailSenderIdentity
39
38
  readonly #tag: string
40
- readonly #fetch: EmailFetch
41
- readonly #timeoutMs: number
42
39
 
43
40
  constructor(options: SmartEmailingEmailSenderOptions) {
44
41
  if (!validUsername(options.username)) {
45
42
  throw new EmailDeliveryError('SmartEmailing username is invalid', { code: 'invalid_configuration' })
46
43
  }
47
- if (!validApiKey(options.apiKey)) {
44
+ if (!isCredential(options.apiKey)) {
48
45
  throw new EmailDeliveryError('SmartEmailing API key is invalid', { code: 'invalid_configuration' })
49
46
  }
50
- if (!isValidEmailSenderIdentity(options.from)) {
51
- throw new EmailDeliveryError('SmartEmailing sender is invalid', { code: 'invalid_configuration' })
52
- }
47
+ super({ label: 'SmartEmailing', provider: 'smartemailing' }, options)
53
48
  const tag = options.tag ?? DEFAULT_TAG
54
49
  if (!TAG_PATTERN.test(tag)) {
55
50
  throw new EmailDeliveryError('SmartEmailing tag is invalid', { code: 'invalid_configuration' })
56
51
  }
57
52
 
58
53
  this.#authorization = `Basic ${btoa(`${options.username}:${options.apiKey}`)}`
59
- this.#from = options.from
60
54
  this.#tag = tag
61
- this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init))
62
- this.#timeoutMs = parseTimeout(LABEL, options.timeoutMs)
63
55
  }
64
56
 
65
- async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
66
- validateEmailMessage(message)
67
- // Its API documents no message headers, so a one-click unsubscribe is refused rather than sent without one.
68
- if (message.unsubscribeUrl !== undefined) {
69
- throw new EmailDeliveryError('SmartEmailing cannot write the List-Unsubscribe headers', { code: 'invalid_message' })
70
- }
71
- validateEmailAttachments(message, this.capabilities, LABEL)
72
-
73
- const senderName = message.fromName ?? this.#from.name
74
- const response = await postToProvider({
75
- label: LABEL,
76
- fetch: this.#fetch,
57
+ protected request(message: EmailMessage): HttpEmailRequest {
58
+ const senderName = message.fromName ?? this.from.name
59
+ return {
77
60
  url: SMARTEMAILING_SEND_URL,
78
61
  headers: { Authorization: this.#authorization },
79
62
  body: {
80
63
  sender_credentials: {
81
- from: this.#from.address,
64
+ from: this.from.address,
82
65
  ...(senderName === undefined ? {} : { sender_name: senderName }),
83
66
  ...(message.replyTo === undefined ? {} : { reply_to: message.replyTo }),
84
67
  },
@@ -91,28 +74,18 @@ export class SmartEmailingEmailSender implements EmailSender {
91
74
  },
92
75
  tasks: [{ recipient: { emailaddress: message.to } }],
93
76
  },
94
- signal,
95
- timeoutMs: this.#timeoutMs,
96
- })
97
-
98
- // The error body's `message` is free text that may quote the request, so only the status is classified.
99
- if (!response.ok) throw responseError(response.status)
100
-
101
- const parsed = smartEmailingSuccessSchema.safeParse(response.body)
102
- if (!parsed.success) {
103
- throw new EmailDeliveryError('SmartEmailing returned an invalid success response', { code: 'malformed_response', httpStatus: response.status })
104
77
  }
78
+ }
105
79
 
106
- return { status: 'accepted', provider: 'smartemailing', messageId: parsed.data.data[0].id }
80
+ protected messageId(response: ProviderResponse): string | undefined {
81
+ return smartEmailingSuccessSchema.safeParse(response.body).data?.data[0].id
107
82
  }
108
83
  }
109
84
 
110
85
  const smartEmailingVariablesSchema = z.object({
111
86
  FABRIKA_EMAIL_SMARTEMAILING_USERNAME: z.string().refine(validUsername),
112
- FABRIKA_EMAIL_SMARTEMAILING_API_KEY: z.string().refine(validApiKey),
113
- FABRIKA_EMAIL_SMARTEMAILING_TAG: z.string().optional().transform((value) => (value === '' ? undefined : value)).refine((value) =>
114
- value === undefined || TAG_PATTERN.test(value)
115
- ),
87
+ FABRIKA_EMAIL_SMARTEMAILING_API_KEY: credentialVariable,
88
+ FABRIKA_EMAIL_SMARTEMAILING_TAG: optionalVariable((value) => TAG_PATTERN.test(value)),
116
89
  })
117
90
 
118
91
  export const smartEmailingEmailProvider: EmailProvider = {
@@ -133,23 +106,6 @@ export const smartEmailingEmailProvider: EmailProvider = {
133
106
  },
134
107
  }
135
108
 
136
- function responseError(status: number): EmailDeliveryError {
137
- if (status === 401 || status === 403) {
138
- return new EmailDeliveryError(`SmartEmailing refused the credentials (${status})`, { code: 'provider_unauthorized', httpStatus: status })
139
- }
140
- if (status === 429) {
141
- return new EmailDeliveryError('SmartEmailing rate limit exceeded', { code: 'rate_limited', httpStatus: status })
142
- }
143
- if (status >= 500) {
144
- return new EmailDeliveryError('SmartEmailing is unavailable', { code: 'provider_unavailable', httpStatus: status })
145
- }
146
- return new EmailDeliveryError(`SmartEmailing rejected the request (${status})`, { code: 'provider_rejected', httpStatus: status })
147
- }
148
-
149
109
  function validUsername(value: string): boolean {
150
- return validApiKey(value) && !value.includes(':')
151
- }
152
-
153
- function validApiKey(value: string): boolean {
154
- return value.length > 0 && isVisibleAscii(value)
110
+ return isCredential(value) && !value.includes(':')
155
111
  }
package/src/validation.ts CHANGED
@@ -64,6 +64,7 @@ export function validateEmailMessage(message: EmailMessage): void {
64
64
  if (message.replyTo !== undefined && !isValidEmailAddress(message.replyTo)) throw invalidMessage('Email reply-to address is invalid')
65
65
  if (message.fromName !== undefined && !isValidEmailDisplayName(message.fromName)) throw invalidMessage('Email sender name is invalid')
66
66
  if (message.unsubscribeUrl !== undefined && !isUnsubscribeUrl(message.unsubscribeUrl)) throw invalidMessage('Email unsubscribe URL is invalid')
67
+ if (message.broadcast === true && message.unsubscribeUrl === undefined) throw invalidMessage('A broadcast email needs an unsubscribe URL')
67
68
  const attachments = message.attachments ?? []
68
69
  if (attachments.length > MAX_EMAIL_ATTACHMENTS) throw invalidMessage(`Email has more than ${MAX_EMAIL_ATTACHMENTS} attachments`)
69
70
  for (const attachment of attachments) {
@@ -73,15 +74,42 @@ export function validateEmailMessage(message: EmailMessage): void {
73
74
  }
74
75
 
75
76
  /**
76
- * Refuses a message whose attachments `capabilities` does not carry: any attachment where the transport sends none, or
77
- * more bytes together than its `maxAttachmentBytes`. `label` names the transport in the message.
77
+ * Refuses a message whose attachments `capabilities` does not carry: any attachment where the transport sends none,
78
+ * more bytes together than its `maxAttachmentBytes`, or a file whose extension it refuses. `label` names the transport
79
+ * in the message.
78
80
  */
79
81
  export function validateEmailAttachments(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
80
- if ((message.attachments ?? []).length === 0) return
82
+ const attachments = message.attachments ?? []
83
+ if (attachments.length === 0) return
81
84
  const limit = capabilities.maxAttachmentBytes
82
85
  if (limit === undefined) throw invalidMessage(`${label} sends no attachments`)
83
86
  const bytes = attachmentBytes(message)
84
87
  if (bytes > limit) throw invalidMessage(`Email attachments have ${bytes} bytes, more than the ${limit} ${label} sends`)
88
+ const refused = capabilities.refusedAttachmentExtensions ?? []
89
+ if (refused.length > 0 && attachments.some((attachment) => refused.includes(extensionOf(attachment.filename)))) {
90
+ throw invalidMessage(`${label} sends no attachment of this file type`)
91
+ }
92
+ }
93
+
94
+ /** Refuses a `broadcast` message where the transport sends none. */
95
+ export function validateEmailBroadcast(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
96
+ if (message.broadcast === true && capabilities.broadcast !== true) throw invalidMessage(`${label} sends no broadcast email`)
97
+ }
98
+
99
+ /** Refuses a text or HTML body shorter than the transport's `minBodyLength`, counted in characters once trimmed. */
100
+ export function validateEmailBodies(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
101
+ const min = capabilities.minBodyLength
102
+ if (min === undefined) return
103
+ const short = (body: string): boolean => [...body.trim()].length < min
104
+ if (short(message.text) || (message.html !== undefined && short(message.html))) {
105
+ throw invalidMessage(`${label} sends no body shorter than ${min} characters`)
106
+ }
107
+ }
108
+
109
+ /** The extension after the last dot, lowercase; empty without one. */
110
+ function extensionOf(filename: string): string {
111
+ const dot = filename.lastIndexOf('.')
112
+ return dot < 0 ? '' : filename.slice(dot + 1).toLowerCase()
85
113
  }
86
114
 
87
115
  /** The most files one message carries. */
@@ -0,0 +1,26 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface AhaSendEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** An API key v2, scoped to `messages:send:{domain}` at least. */
7
+ readonly apiKey: string;
8
+ /** The account the key belongs to: the path of every request. */
9
+ readonly accountId: string;
10
+ /**
11
+ * The address a `broadcast` message is sent from, on a domain the account has configured as a Marketing domain:
12
+ * AhaSend's terms allow marketing mail through the API from such a domain only. Without it, a broadcast is refused.
13
+ */
14
+ readonly broadcastFrom?: string;
15
+ }
16
+ /** A refusal's body is one free-text `message`, so only the status is read. */
17
+ export declare class AhaSendEmailSender extends HttpEmailSender {
18
+ #private;
19
+ /** `broadcast` only with `broadcastFrom`. */
20
+ readonly capabilities: EmailSenderCapabilities;
21
+ constructor(options: AhaSendEmailSenderOptions);
22
+ protected request(message: EmailMessage): Promise<HttpEmailRequest>;
23
+ protected messageId(response: ProviderResponse): string | undefined;
24
+ protected refusal(response: ProviderResponse): EmailDeliveryError | undefined;
25
+ }
26
+ export declare const ahaSendEmailProvider: EmailProvider;
@@ -0,0 +1,20 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface CloudflareEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** An account API token with the Email Sending Write permission and nothing else. */
7
+ readonly apiToken: string;
8
+ /** The account the token sends for: the path of every request. */
9
+ readonly accountId: string;
10
+ }
11
+ /** A refusal's body carries numeric codes and machine-readable messages; only the status is read. */
12
+ export declare class CloudflareEmailSender extends HttpEmailSender {
13
+ #private;
14
+ readonly capabilities: EmailSenderCapabilities;
15
+ constructor(options: CloudflareEmailSenderOptions);
16
+ protected request(message: EmailMessage): HttpEmailRequest;
17
+ protected messageId(response: ProviderResponse, message: EmailMessage): string | undefined;
18
+ protected refusal(response: ProviderResponse): EmailDeliveryError | undefined;
19
+ }
20
+ export declare const cloudflareEmailProvider: EmailProvider;
@@ -13,6 +13,8 @@ export interface WireMessage {
13
13
  readonly unsubscribeUrl?: string;
14
14
  /** Each attachment with its bytes as base64. */
15
15
  readonly attachments?: readonly EmailAttachmentContent[];
16
+ /** Whether the provider got it as broadcast mail, on its channel for them where it has one. */
17
+ readonly broadcast?: boolean;
16
18
  }
17
19
  /** A stored or sent message in wire terms: what a local harness answers for an `EmailMessage` it kept. */
18
20
  export declare function wireMessageOf(message: EmailMessage): WireMessage;
@@ -14,6 +14,7 @@ export interface EmailContent {
14
14
  readonly replyTo?: string;
15
15
  readonly fromName?: string;
16
16
  readonly unsubscribeUrl?: string;
17
+ readonly broadcast?: true;
17
18
  readonly attachments?: readonly EmailAttachmentContent[];
18
19
  }
19
20
  export declare function sameEmailContent(left: EmailContent, right: EmailContent): boolean;
@@ -11,6 +11,7 @@ declare const capturedEmailSchema: z.ZodObject<{
11
11
  replyTo: z.ZodOptional<z.ZodString>;
12
12
  fromName: z.ZodOptional<z.ZodString>;
13
13
  unsubscribeUrl: z.ZodOptional<z.ZodString>;
14
+ broadcast: z.ZodOptional<z.ZodLiteral<true>>;
14
15
  attachments: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
15
16
  filename: z.ZodString;
16
17
  contentType: z.ZodString;
@@ -36,6 +37,7 @@ declare const capturedEmailSchema: z.ZodObject<{
36
37
  replyTo?: string | undefined;
37
38
  fromName?: string | undefined;
38
39
  unsubscribeUrl?: string | undefined;
40
+ broadcast?: true | undefined;
39
41
  attachments?: readonly {
40
42
  filename: string;
41
43
  contentType: string;
@@ -52,6 +54,7 @@ declare const capturedEmailSchema: z.ZodObject<{
52
54
  replyTo?: string | undefined;
53
55
  fromName?: string | undefined;
54
56
  unsubscribeUrl?: string | undefined;
57
+ broadcast?: true | undefined;
55
58
  attachments?: readonly {
56
59
  filename: string;
57
60
  contentType: string;
@@ -21,6 +21,12 @@ export interface EmailMessage {
21
21
  * <url>` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. A transport without `listUnsubscribe` refuses it.
22
22
  */
23
23
  readonly unsubscribeUrl?: string;
24
+ /**
25
+ * One message of a send to many recipients (a newsletter, an announcement), not a reply to what the recipient did.
26
+ * A provider keeps such mail apart from transactional mail, and the law and the mailbox providers ask it to carry
27
+ * an unsubscribe, so it needs `unsubscribeUrl`. A transport without `broadcast` refuses it.
28
+ */
29
+ readonly broadcast?: boolean;
24
30
  /**
25
31
  * Files the message carries, at most `MAX_EMAIL_ATTACHMENTS`, together at most the transport's `maxAttachmentBytes`.
26
32
  * A transport without `maxAttachmentBytes` refuses a message that has any; an empty list is none.
@@ -43,6 +49,12 @@ export interface EmailSenderCapabilities {
43
49
  readonly listUnsubscribe?: boolean;
44
50
  /** The most attachment bytes one message carries, every file together; absent: it sends no attachments. */
45
51
  readonly maxAttachmentBytes?: number;
52
+ /** File extensions it refuses an attachment for, lowercase and without the dot; absent: none. */
53
+ readonly refusedAttachmentExtensions?: readonly string[];
54
+ /** The fewest characters a text or HTML body has once trimmed; absent: any body that is not blank. */
55
+ readonly minBodyLength?: number;
56
+ /** Whether it sends a `broadcast` message, on its provider's channel for them where it has one; absent is no. */
57
+ readonly broadcast?: boolean;
46
58
  }
47
59
  export interface EmailSender {
48
60
  readonly capabilities: EmailSenderCapabilities;
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ import type { EmailSenderIdentity } from './config.js';
3
+ import { EmailDeliveryError, type EmailDeliveryResult, type EmailFetch, type EmailMessage, type EmailSender, type EmailSenderCapabilities } from './email.js';
4
+ import { type ProviderResponse } from './http.js';
5
+ /** The options every HTTP adapter takes beside its credentials. */
6
+ export interface HttpEmailSenderOptions {
7
+ readonly from: EmailSenderIdentity;
8
+ readonly fetch?: EmailFetch;
9
+ readonly timeoutMs?: number;
10
+ }
11
+ export interface HttpEmailRequest {
12
+ readonly url: string;
13
+ readonly headers: Readonly<Record<string, string>>;
14
+ readonly body: unknown;
15
+ }
16
+ export declare abstract class HttpEmailSender implements EmailSender {
17
+ #private;
18
+ abstract readonly capabilities: EmailSenderCapabilities;
19
+ protected readonly from: EmailSenderIdentity;
20
+ /** `label` names the provider in every message, `provider` in every result. An adapter checks its credentials first. */
21
+ protected constructor(names: {
22
+ readonly label: string;
23
+ readonly provider: string;
24
+ }, options: HttpEmailSenderOptions);
25
+ /** The request for a message that passed validation. */
26
+ protected abstract request(message: EmailMessage): HttpEmailRequest | Promise<HttpEmailRequest>;
27
+ /** The message id of a 2xx answer to `message`; undefined when the answer is not a valid success. May throw a refusal. */
28
+ protected abstract messageId(response: ProviderResponse, message: EmailMessage): string | undefined;
29
+ /** A failed answer to the message the provider tells apart beyond its status; undefined leaves it to `refusalByStatus`. */
30
+ protected refusal(_response: ProviderResponse, _message: EmailMessage): EmailDeliveryError | undefined;
31
+ send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult>;
32
+ }
33
+ /** The classification of a failed answer by its status alone, for every answer an adapter does not tell apart. */
34
+ export declare function refusalByStatus(label: string, status: number): EmailDeliveryError;
35
+ /** `Name <address>` for an API that takes the sender as one header value; validation keeps the name quotable. */
36
+ export declare function formatMailbox(address: string, name: string | undefined): string;
37
+ /** An API key or token: non-empty visible ASCII, so it fits a header unchanged. */
38
+ export declare function isCredential(value: string): boolean;
39
+ /** The name of a provider's stream or route: 1..64 letters, digits, `_` and `-`. */
40
+ export declare function isChannelName(value: string): boolean;
41
+ /** A provider variable that holds a credential. */
42
+ export declare const credentialVariable: z.ZodEffects<z.ZodString, string, string>;
43
+ /** An optional provider variable: empty is absent, and a present value must pass `valid`. */
44
+ export declare function optionalVariable(valid: (value: string) => boolean): z.ZodEffects<z.ZodEffects<z.ZodOptional<z.ZodString>, string | undefined, string | undefined>, string | undefined, string | undefined>;
45
+ /**
46
+ * The message's key as a provider that takes at most `maxLength` characters sends it. A longer key is sent as its
47
+ * SHA-256, which keeps one key one key: a retry sends the same digest, another message another.
48
+ */
49
+ export declare function providerIdempotencyKey(key: string, maxLength: number): Promise<string>;
@@ -2,4 +2,4 @@ export { EMAIL_PROVIDER_VARIABLE, emailSenderFromEnv, NO_EMAIL_PROVIDER, parsePr
2
2
  export type { EmailEnvironment, EmailProvider, EmailProviderRegistry, EmailProviderVariable, EmailSenderIdentity, EmailTransportConfig, } from './config.js';
3
3
  export { attachmentBytes, EMAIL_DELIVERY_ERRORS, EmailDeliveryError, mayRetryDelivery, oneClickUnsubscribeHeaders } from './email.js';
4
4
  export type { EmailAttachment, EmailDeliveryErrorCode, EmailDeliveryErrorOptions, EmailDeliveryOutcome, EmailDeliveryResult, EmailFetch, EmailMessage, EmailSender, EmailSenderCapabilities, } from './email.js';
5
- export { isUnsubscribeUrl, isValidAttachmentFilename, isValidEmailAddress, isValidEmailDisplayName, isValidEmailFrom, MAX_EMAIL_ATTACHMENTS, MAX_EMAIL_SUBJECT_LENGTH, MAX_UNSUBSCRIBE_URL_LENGTH, validateEmailAttachments, validateEmailMessage, } from './validation.js';
5
+ export { isUnsubscribeUrl, isValidAttachmentFilename, isValidEmailAddress, isValidEmailDisplayName, isValidEmailFrom, MAX_EMAIL_ATTACHMENTS, MAX_EMAIL_SUBJECT_LENGTH, MAX_UNSUBSCRIBE_URL_LENGTH, validateEmailAttachments, validateEmailBodies, validateEmailBroadcast, validateEmailMessage, } from './validation.js';
@@ -0,0 +1,19 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface LettermintEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** A project API token: it sends through that project's default route. */
7
+ readonly projectToken: string;
8
+ /** The slug of the project's broadcast route, which a `broadcast` message goes through; `broadcast` by default. */
9
+ readonly broadcastRoute?: string;
10
+ }
11
+ export declare class LettermintEmailSender extends HttpEmailSender {
12
+ #private;
13
+ readonly capabilities: EmailSenderCapabilities;
14
+ constructor(options: LettermintEmailSenderOptions);
15
+ protected request(message: EmailMessage): Promise<HttpEmailRequest>;
16
+ protected messageId(response: ProviderResponse): string | undefined;
17
+ protected refusal(response: ProviderResponse, message: EmailMessage): EmailDeliveryError | undefined;
18
+ }
19
+ export declare const lettermintEmailProvider: EmailProvider;
@@ -0,0 +1,19 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface PostmarkEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** A server token: it sends through that server's default transactional stream. */
7
+ readonly serverToken: string;
8
+ /** The ID of the server's broadcast stream, which a `broadcast` message goes through; `broadcast` by default. */
9
+ readonly broadcastStream?: string;
10
+ }
11
+ export declare class PostmarkEmailSender extends HttpEmailSender {
12
+ #private;
13
+ readonly capabilities: EmailSenderCapabilities;
14
+ constructor(options: PostmarkEmailSenderOptions);
15
+ protected request(message: EmailMessage): HttpEmailRequest;
16
+ protected messageId(response: ProviderResponse): string | undefined;
17
+ protected refusal(response: ProviderResponse): EmailDeliveryError | undefined;
18
+ }
19
+ export declare const postmarkEmailProvider: EmailProvider;