@ultimat3/mail 29.4.0 → 30.1.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.
package/CLAUDE.md CHANGED
@@ -233,6 +233,7 @@
233
233
  - The SNS test key and its X.509 certificate are generated per run (`delivery-event-fixture.ts`);
234
234
  no private key is committed. The DER was checked once against openssl (`openssl verify`, and
235
235
  `openssl x509 -pubkey` gave the SPKI `x509-spki.ts` extracts).
236
+ - **`send()` refuses on the renderer's record, never on the bytes** (`X_MAIL_KEY_MISSING`, terminal, before the transform). A `⟦` may be user data. `recordingTranslator` (`@ultimat3/i18n`) selects through `selectMessageKey`, the selector `t()` uses, because `has()` says yes for a plural family read without a `count`, where `t()` renders `⟦key⟧`. A catalog value that is a marker is a miss: it is what `x i18n sync` seeds, so the refusal's fix must not turn it into a delivery. Templates get the recording `t` too. `renderMessage` drops `misses` (previews show the brackets); nothing on `MailMessage` carries them.
236
237
 
237
238
  ## Commands
238
239
 
package/README.md CHANGED
@@ -3,6 +3,8 @@
3
3
  Transactional email as data. One template renders **both** an HTML part and a plain-text part,
4
4
  every string is an i18n key, every colour is a design token, and delivery is a job.
5
5
 
6
+ `bun add @ultimat3/mail` · guide: [Mail](https://github.com/developerz-ai/ultimate/wiki/Mail)
7
+
6
8
  ```ts
7
9
  import { defineMail, send, blocks, t } from '@ultimat3/mail';
8
10
 
@@ -54,6 +56,7 @@ setMailTransform(async (rendered, meta) =>
54
56
  | Rule | Why |
55
57
  |---|---|
56
58
  | `locale` is required by the **type** | a mail is read hours later; there is no ambient request locale to fall back to. `X_MAIL_LOCALE_MISSING` is the backstop for JS callers |
59
+ | An unresolved key is never sent | `send()` refuses a key the locale lacks, a catalog value still holding `⟦…⟧`, or a `{slot}` with no value (`X_MAIL_KEY_MISSING`, terminal), before the transform and the queue. `renderMessage()` keeps the `⟦…⟧` for a preview, and `renderMail()` reports it as `misses` (`TranslationMiss[]`, recorded by `@ultimat3/i18n`'s `recordingTranslator`). It reads what the renderer resolved, never the bytes: a `⟦` from data sends |
57
60
  | Text part is mandatory | HTML-only mail scores as spam and is unreadable to screen readers. Empty text ⇒ `X_MAIL_TEXT_MISSING` |
58
61
  | Text is derived from blocks | never scraped out of the HTML, so the two parts cannot drift |
59
62
  | Every string is a key | `mail.<id>.<slot>`; English lives in `src/catalog.ts` and app catalogs override it |
@@ -192,8 +195,16 @@ export const resend = resendEventReceiver({ secret: env['RESEND_WEBHOOK_SECRET']
192
195
  ## Framework mails
193
196
 
194
197
  Registered by importing them — the import IS the registration. `FRAMEWORK_MAILS` is the list, and
195
- `registeredMails()` / `registeredMailIds()` answer for an app's own mails as well. There is no
196
- `x mail` command; a host that wants to list or preview a mail calls those and `renderMessage()`.
198
+ `registeredMails()` / `registeredMailIds()` answer for an app's own mails as well.
199
+
200
+ ## Previews — `defineMail({ preview })`
201
+
202
+ `As of 2026-11-06`. Sample data a template is checked by, in every locale, with no flow triggered
203
+ and never production rows. A value is parsed by `input` at definition (`X_MAIL_PREVIEW_INVALID`);
204
+ `(locale) => data` is parsed at each render. `previewMail(id, { locale, tz? })` answers
205
+ `{ subject, html, text, misses }` and sends nothing; `x mail preview <id> [--locale] [--out]` is
206
+ it on the command line, and `x verify`'s `i18n` step renders every declared preview in every
207
+ locale, so a miss a `send` would refuse is red at the gate. No preview: `X_MAIL_PREVIEW_MISSING`.
197
208
 
198
209
  | id | Input |
199
210
  |---|---|
@@ -213,6 +224,7 @@ Translating them = shipping `mail.*` keys in an app catalog. Never edit a templa
213
224
  | `X_MAIL_LOCALE_MISSING` | `send(mail, data, { to, locale: ctx.locale })` |
214
225
  | `X_MAIL_TEMPLATE_UNKNOWN` | export a `defineMail({ id })` and import it (also raised for an unregistered layout) |
215
226
  | `X_MAIL_DUPLICATE` | rename one of two `defineMail({ id })` declarations |
227
+ | `X_MAIL_KEY_MISSING` | `x i18n sync <locale>`, then translate `meta.keys`; pass the vars `meta.slots` names |
216
228
  | `X_MAIL_TEXT_MISSING` | add a text-bearing block to the template |
217
229
  | `X_MAIL_DRIVER_UNAVAILABLE` | `setMailDriver(memoryMailDriver())` at boot — a wiring bug |
218
230
  | `X_MAIL_CREDENTIAL_MISSING` | set `SMTP_URL` (or `RESEND_API_KEY`) and `MAIL_FROM` in the deployment — an operations one |
package/package.json CHANGED
@@ -1,7 +1,16 @@
1
1
  {
2
2
  "name": "@ultimat3/mail",
3
- "version": "29.4.0",
3
+ "version": "30.1.0",
4
4
  "description": "Transactional email as data: one template renders HTML and text, sent through a job.",
5
+ "keywords": [
6
+ "ultimate",
7
+ "bun",
8
+ "framework",
9
+ "email",
10
+ "mail",
11
+ "templates"
12
+ ],
13
+ "homepage": "https://github.com/developerz-ai/ultimate/wiki/Mail",
5
14
  "license": "MIT",
6
15
  "type": "module",
7
16
  "repository": {
@@ -33,10 +42,10 @@
33
42
  "test": "bun test"
34
43
  },
35
44
  "dependencies": {
36
- "@ultimat3/core": "29.4.0",
37
- "@ultimat3/i18n": "29.4.0",
38
- "@ultimat3/jobs": "29.4.0",
39
- "@ultimat3/schema": "29.4.0",
40
- "@ultimat3/time": "29.4.0"
45
+ "@ultimat3/core": "30.1.0",
46
+ "@ultimat3/i18n": "30.1.0",
47
+ "@ultimat3/jobs": "30.1.0",
48
+ "@ultimat3/schema": "30.1.0",
49
+ "@ultimat3/time": "30.1.0"
41
50
  }
42
51
  }
@@ -15,6 +15,7 @@ import {
15
15
  nanoid,
16
16
  renderThrowable,
17
17
  } from '@ultimat3/core';
18
+ import { outboundResponse } from '@ultimat3/core/outbound';
18
19
  import type { MailDriver, MailMessage, SendResult } from './driver';
19
20
  import { messageHeaders, resultFor } from './driver';
20
21
  import { sendFailed } from './errors';
@@ -144,7 +145,10 @@ export function resendMailDriver(options: ResendDriverOptions): MailDriver {
144
145
  );
145
146
  // A bare reference to `globalThis.fetch` risks "Illegal invocation" on some hosts; closing
146
147
  // over the call keeps it detached from any receiver, in production and in tests alike.
147
- const doFetch: MailFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
148
+ // `outbound()` always hands it the attempt's signal.
149
+ const doFetch: MailFetch =
150
+ options.fetch ??
151
+ ((input, init) => globalThis.fetch(input, { ...init, signal: init.signal ?? null }));
148
152
 
149
153
  return {
150
154
  name: 'resend',
@@ -160,12 +164,22 @@ export function resendMailDriver(options: ResendDriverOptions): MailDriver {
160
164
 
161
165
  let response: Response;
162
166
  try {
163
- response = await doFetch(`${baseUrl}/emails`, {
164
- method: 'POST',
165
- headers,
166
- body: JSON.stringify(bodyFor(message, from)),
167
- signal: AbortSignal.timeout(timeoutMs),
168
- });
167
+ // Through core's `outbound()`: `timeoutMs` bounds the WHOLE send, and the ambient job's
168
+ // signal ends it. Retried on a 5xx or a throttle because the key above makes a replay the
169
+ // same one email (`idempotent: true`); the final answer comes back for the table below.
170
+ response = await outboundResponse(
171
+ {
172
+ url: `${baseUrl}/emails`,
173
+ vendor: 'resend',
174
+ dial: 'named',
175
+ method: 'POST',
176
+ idempotent: true,
177
+ deadlineMs: timeoutMs,
178
+ headers,
179
+ body: JSON.stringify(bodyFor(message, from)),
180
+ },
181
+ { fetch: doFetch },
182
+ );
169
183
  } catch (error) {
170
184
  // DNS/TLS/reset, or the timeout firing — none of them got far enough to have a status,
171
185
  // and every one of them can succeed unchanged on the job's next attempt.
package/src/driver-ses.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  signAwsRequest,
17
17
  systemClock,
18
18
  } from '@ultimat3/core';
19
+ import { outboundResponse } from '@ultimat3/core/outbound';
19
20
  import { base64Utf8 } from './base64';
20
21
  import type { MailDriver, MailMessage, SendResult } from './driver';
21
22
  import { resultFor } from './driver';
@@ -133,7 +134,10 @@ export function sesMailDriver(options: SesDriverOptions): MailDriver {
133
134
  );
134
135
  const retain = resolveRetainMime('sesMailDriver', options.retainMime);
135
136
  const clock = options.clock ?? systemClock;
136
- const doFetch: MailFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
137
+ // `outbound()` always hands it the attempt's signal.
138
+ const doFetch: MailFetch =
139
+ options.fetch ??
140
+ ((input, init) => globalThis.fetch(input, { ...init, signal: init.signal ?? null }));
137
141
 
138
142
  return { name: 'ses', send };
139
143
 
@@ -161,15 +165,24 @@ export function sesMailDriver(options: SesDriverOptions): MailDriver {
161
165
  service: 'ses',
162
166
  clock,
163
167
  });
164
- response = await doFetch(signed.url, {
165
- method: 'POST',
166
- headers: signed.headers,
167
- body,
168
- signal: AbortSignal.timeout(timeoutMs),
169
- });
168
+ // Through core's `outbound()`: `timeoutMs` bounds the send, the ambient job's signal ends it,
169
+ // and it is ONE attempt — a signed POST with no idempotency header is never replayed.
170
+ response = await outboundResponse(
171
+ {
172
+ url: signed.url,
173
+ vendor: 'ses',
174
+ dial: 'named',
175
+ method: 'POST',
176
+ deadlineMs: timeoutMs,
177
+ headers: signed.headers,
178
+ body,
179
+ },
180
+ { fetch: doFetch },
181
+ );
170
182
  } catch (error) {
171
- // The signer's own refusals are coded and say which input to fix; only the network is left.
172
- if (isUltimateError(error)) throw error;
183
+ // The signer's own refusals are coded and say which input to fix, and a caller's abort is
184
+ // its own: only the network — `outbound()`'s transport codes — is left to translate.
185
+ if (isUltimateError(error) && !error.code.startsWith('X_OUTBOUND_')) throw error;
173
186
  throw sendFailed({
174
187
  driver: 'ses',
175
188
  stage: 'request',
package/src/errors.ts CHANGED
@@ -7,8 +7,10 @@ import {
7
7
  type ErrorRetry,
8
8
  registerErrorCodes,
9
9
  registerErrorRetry,
10
+ renderFixShellArg,
10
11
  UltimateError,
11
12
  } from '@ultimat3/core';
13
+ import type { TranslationMiss } from '@ultimat3/i18n';
12
14
 
13
15
  export const MAIL_ERROR_CODES = [
14
16
  'X_MAIL_LOCALE_MISSING',
@@ -24,6 +26,9 @@ export const MAIL_ERROR_CODES = [
24
26
  'X_MAIL_EVENT_UNVERIFIED',
25
27
  'X_MAIL_EVENT_INVALID',
26
28
  'X_MAIL_EVENT_PROVIDER_UNREACHABLE',
29
+ 'X_MAIL_KEY_MISSING',
30
+ 'X_MAIL_PREVIEW_INVALID',
31
+ 'X_MAIL_PREVIEW_MISSING',
27
32
  ] as const;
28
33
 
29
34
  export type MailErrorCode = (typeof MAIL_ERROR_CODES)[number];
@@ -42,6 +47,9 @@ export const MAIL_ERROR_TITLES: Readonly<Record<MailErrorCode, string>> = {
42
47
  X_MAIL_EVENT_UNVERIFIED: 'a delivery notification is not signed by its provider',
43
48
  X_MAIL_EVENT_INVALID: 'a delivery notification is not a shape this receiver reads',
44
49
  X_MAIL_EVENT_PROVIDER_UNREACHABLE: 'an SNS endpoint the receiver needed did not answer',
50
+ X_MAIL_KEY_MISSING: 'a mail rendered a key or slot with no value in its locale',
51
+ X_MAIL_PREVIEW_INVALID: "a mail's declared preview fails its own input schema",
52
+ X_MAIL_PREVIEW_MISSING: 'this mail declares no preview',
45
53
  };
46
54
 
47
55
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
@@ -52,8 +60,9 @@ registerErrorCodes(
52
60
  );
53
61
 
54
62
  /**
55
- * The one code in this package a queue may retry, and it is registered rather than merely written
56
- * down: `classifyThrown` reads a per-instance `terminal` only for a code somebody REGISTERED, so a
63
+ * The one code in this package a queue may retry, plus the one refused content fault listed so a
64
+ * job around `send()` dead-letters it: no retry can translate a catalog. Registered rather than
65
+ * merely written down: `classifyThrown` reads a per-instance `terminal` only for a code somebody REGISTERED, so a
57
66
  * table with no `registerErrorRetry` call behind it lets `sendMailJob` spend all five attempts on
58
67
  * a 401 or a 550 hard bounce — the `cause` saying "permanent, retrying cannot help" while the
59
68
  * worker retries it four more times.
@@ -65,6 +74,7 @@ registerErrorCodes(
65
74
  */
66
75
  export const MAIL_ERROR_RETRY = {
67
76
  X_MAIL_SEND_FAILED: 'retryable',
77
+ X_MAIL_KEY_MISSING: 'terminal',
68
78
  } as const satisfies Readonly<Partial<Record<MailErrorCode, ErrorRetry>>>;
69
79
 
70
80
  registerErrorRetry(MAIL_ERROR_RETRY);
@@ -161,6 +171,35 @@ export const textMissing = (mailId: string): MailError =>
161
171
  meta: { mailId },
162
172
  });
163
173
 
174
+ /**
175
+ * `send()` rendered a key or a slot with no value, so nothing left. Two repairs, one code: a key is
176
+ * a catalog edit, a slot is the call site's. A framework mail's keys live in `mail/src/catalog.ts`,
177
+ * not in the app's `en` catalog, so `x i18n sync` may seed none of them, and the fix names the file
178
+ * to add them to. Key names are template constants: no value from `data` reaches this text.
179
+ */
180
+ export const mailKeyMissing = (
181
+ mailId: string,
182
+ locale: string,
183
+ misses: readonly TranslationMiss[],
184
+ ): MailError => {
185
+ const keys = misses.filter((miss) => miss.slot === undefined).map((miss) => miss.key);
186
+ const slots = misses.flatMap((miss) =>
187
+ miss.slot === undefined ? [] : [`${miss.key}{${miss.slot}}`],
188
+ );
189
+ const [firstSlot] = misses.filter((miss) => miss.slot !== undefined);
190
+ // A request can carry the locale, and a fix is pasted from its first character.
191
+ const shownLocale = renderFixShellArg(locale, '<locale>');
192
+ return new MailError({
193
+ code: 'X_MAIL_KEY_MISSING',
194
+ cause: `mail "${mailId}" has no value in locale "${locale}" for ${[...keys, ...slots].join(', ')}, so it was not sent — its reader would have seen the raw ⟦key⟧`,
195
+ fix:
196
+ keys.length > 0 || firstSlot === undefined
197
+ ? `x i18n sync ${shownLocale} # then translate these in packages/i18n/catalogs/${shownLocale}.json, adding any it did not seed: ${keys.join(', ')}`
198
+ : `blocks.paragraph('${firstSlot.key}', { ${firstSlot.slot}: value }) # pass every slot of ${slots.join(', ')} from the "${mailId}" template; a subject reads the input's top-level fields`,
199
+ meta: { mailId, locale, keys, slots },
200
+ });
201
+ };
202
+
164
203
  export const driverUnavailable = (what: string): MailError =>
165
204
  new MailError({
166
205
  code: 'X_MAIL_DRIVER_UNAVAILABLE',
package/src/index.ts CHANGED
@@ -63,6 +63,7 @@ export {
63
63
  MailError,
64
64
  mailCredentialMissing,
65
65
  mailDuplicate,
66
+ mailKeyMissing,
66
67
  mailLayoutDuplicate,
67
68
  sendFailed,
68
69
  templateUnknown,
@@ -91,7 +92,13 @@ export {
91
92
  registerLayout,
92
93
  token,
93
94
  } from './layout';
94
- export type { AnyMailDefinition, MailDefinition, MailInit, SendOptions } from './mail';
95
+ export type {
96
+ AnyMailDefinition,
97
+ MailDefinition,
98
+ MailInit,
99
+ MailPreview,
100
+ SendOptions,
101
+ } from './mail';
95
102
  export {
96
103
  defineMail,
97
104
  mailFor,
@@ -102,6 +109,9 @@ export {
102
109
  send,
103
110
  sendById,
104
111
  } from './mail';
112
+ export type { MailPreviewResult, PreviewOptions } from './preview';
113
+ export { PREVIEW_RECIPIENT, previewableMailIds, previewMail } from './preview';
114
+ export { previewMissing } from './preview-check';
105
115
  export type { RenderableMail, RenderedMail, RenderOptions } from './render';
106
116
  export { renderMail, textOf } from './render';
107
117
  export type { RetainedMime, RetainedMimeEntry, RetainMimeOptions } from './retain-mime';
package/src/job.ts CHANGED
@@ -52,11 +52,14 @@ export const sendMailJob: JobHandle<MailMessage> = job<MailMessage>({
52
52
  retry: { attempts: 5, backoff: 'exponential' },
53
53
  // `async`, so the refusal below is a REJECTED promise: a synchronous throw from a body whose
54
54
  // signature promises one escapes every caller that only awaits it.
55
- run: async ({ input }): Promise<SendResult> => {
55
+ run: async ({ input, step }): Promise<SendResult> => {
56
56
  // The second boundary the header rule is checked at, and the one `renderMessage` cannot cover:
57
57
  // a queue row is not necessarily one this process rendered — `mailMessageSchema` proves the
58
58
  // SHAPE of a payload and says nothing about a break inside a string it accepted.
59
59
  assertHeaderSafe(input);
60
- return await mailDriver().send(input);
60
+ // A step, so a worker that dies after the provider accepted the message and before the ack
61
+ // replays the recorded result instead of sending the mail a second time (the exercise pass's
62
+ // crash proof found the double send: `X_JOB_CRASH_DIVERGED`).
63
+ return await step.run('send', () => mailDriver().send(input));
61
64
  },
62
65
  });
package/src/mail.ts CHANGED
@@ -4,16 +4,18 @@
4
4
  // piece of context that a background send cannot recover after the fact.
5
5
 
6
6
  import { assert, DEFAULT_TIME_ZONE, tryUseContext } from '@ultimat3/core';
7
+ import type { TranslationMiss } from '@ultimat3/i18n';
7
8
  import { jobDriver, jobsFacade } from '@ultimat3/jobs';
8
9
  import { parse, type StandardSchemaV1, t } from '@ultimat3/schema';
9
10
  import type { MailTemplate } from './blocks';
10
11
  import { envelopeRecipients, type MailMessage, mailDriver, type SendResult } from './driver';
11
12
  import { assertRecipientAddress } from './envelope-address';
12
- import { localeMissing, mailDuplicate, templateUnknown } from './errors';
13
+ import { localeMissing, mailDuplicate, mailKeyMissing, templateUnknown } from './errors';
13
14
  import { assertHeaderSafe } from './header-safety';
14
15
  import { mailIdempotencyKey } from './idempotency';
15
16
  import { sendMailJob } from './job';
16
17
  import { BASE_LAYOUT } from './layout';
18
+ import { assertPreview } from './preview-check';
17
19
  import { type RenderableMail, renderMail } from './render';
18
20
  import { applyMailTransform } from './transform';
19
21
 
@@ -24,8 +26,13 @@ export interface MailDefinition<I> extends RenderableMail<I> {
24
26
  readonly template: MailTemplate<I>;
25
27
  readonly input: StandardSchemaV1<unknown, I>;
26
28
  readonly layout: string;
29
+ /** Sample data a preview renders: never production rows. */
30
+ readonly preview?: MailPreview<I> | undefined;
27
31
  }
28
32
 
33
+ /** A preview's data, or a function of the locale for copy that differs by language. */
34
+ export type MailPreview<I> = I | ((locale: string) => I);
35
+
29
36
  export interface MailInit<I> {
30
37
  readonly id: string;
31
38
  readonly subject: string;
@@ -33,6 +40,12 @@ export interface MailInit<I> {
33
40
  readonly input: StandardSchemaV1<unknown, I>;
34
41
  /** Defaults to the framework's `base` layout. */
35
42
  readonly layout?: string | undefined;
43
+ /**
44
+ * What `x mail preview` and the `/_x` mail panel render, in every locale, with no flow
45
+ * triggered. Type-checked against `input` here, and a value is parsed by it at definition
46
+ * (`X_MAIL_PREVIEW_INVALID`); a function is parsed at each render.
47
+ */
48
+ readonly preview?: MailPreview<I> | undefined;
36
49
  }
37
50
 
38
51
  export interface SendOptions {
@@ -69,18 +82,24 @@ export interface AnyMailDefinition {
69
82
  readonly layout: string;
70
83
  readonly input: StandardSchemaV1<unknown, unknown>;
71
84
  readonly template: MailTemplate<never>;
85
+ readonly preview?: unknown;
72
86
  }
73
87
 
74
88
  const registry = new Map<string, AnyMailDefinition>();
75
89
 
76
90
  export function defineMail<I>(init: MailInit<I>): MailDefinition<I> {
77
91
  if (registry.has(init.id)) throw mailDuplicate(init.id);
92
+ // A value is checked where it is written; a function of the locale, at each render.
93
+ if (init.preview !== undefined && typeof init.preview !== 'function') {
94
+ assertPreview(init.id, init.input, init.preview);
95
+ }
78
96
  const definition: MailDefinition<I> = {
79
97
  id: init.id,
80
98
  subject: init.subject,
81
99
  template: init.template,
82
100
  input: init.input,
83
101
  layout: init.layout ?? BASE_LAYOUT,
102
+ ...(init.preview === undefined ? {} : { preview: init.preview }),
84
103
  };
85
104
  registry.set(init.id, definition);
86
105
  return definition;
@@ -115,6 +134,26 @@ export function renderMessage<I>(
115
134
  data: I,
116
135
  options: SendOptions,
117
136
  ): MailMessage {
137
+ return renderChecked(mail, data, options).message;
138
+ }
139
+
140
+ /**
141
+ * Render without delivering, with the misses a preview shows instead of refusing on: the `/_x`
142
+ * panel and `x mail preview` (`preview.ts`) read this, `send` never does.
143
+ */
144
+ export function renderWithMisses<I>(
145
+ mail: MailDefinition<I>,
146
+ data: I,
147
+ options: SendOptions,
148
+ ): { readonly message: MailMessage; readonly misses: readonly TranslationMiss[] } {
149
+ return renderChecked(mail, data, options);
150
+ }
151
+
152
+ function renderChecked<I>(
153
+ mail: MailDefinition<I>,
154
+ data: I,
155
+ options: SendOptions,
156
+ ): { readonly message: MailMessage; readonly misses: readonly TranslationMiss[] } {
118
157
  assertLocale(mail.id, options.locale);
119
158
  if (registry.get(mail.id) === undefined) throw templateUnknown(mail.id, registeredMailIds());
120
159
 
@@ -165,7 +204,7 @@ export function renderMessage<I>(
165
204
  for (const address of [...envelopeRecipients(message), ...replyTo]) {
166
205
  assertRecipientAddress('recipient', address);
167
206
  }
168
- return message;
207
+ return { message, misses: rendered.misses };
169
208
  }
170
209
 
171
210
  /**
@@ -178,9 +217,13 @@ export async function send<I>(
178
217
  data: I,
179
218
  options: SendOptions,
180
219
  ): Promise<SendResult> {
220
+ const { message: rendered, misses } = renderChecked(mail, data, options);
221
+ // Here and not in `renderMessage`: a preview should show the miss, and a customer never should.
222
+ // A mail is the one surface where a loud miss cannot be taken back.
223
+ if (misses.length > 0) throw mailKeyMissing(mail.id, options.locale, misses);
181
224
  // Transform BEFORE the key: the key, the queue row and every retry carry the transformed bytes,
182
225
  // and the job never re-runs the hook. Not in `renderMessage`, which previews call.
183
- const message = await applyMailTransform(renderMessage(mail, data, options));
226
+ const message = await applyMailTransform(rendered);
184
227
  const key = mailIdempotencyKey(message);
185
228
 
186
229
  if (options.sync === true || jobDriver() === undefined) {
@@ -0,0 +1,34 @@
1
+ // Single responsibility: a mail's declared preview held to its own input schema — the one data a
2
+ // person checks a template by must be data the mail could really be sent with.
3
+
4
+ import { isUltimateError, renderFixShellArg, renderThrowable } from '@ultimat3/core';
5
+ import { parse, type StandardSchemaV1 } from '@ultimat3/schema';
6
+ import { MailError } from './errors';
7
+
8
+ /** The parsed preview, or `X_MAIL_PREVIEW_INVALID` naming the schema's own words. */
9
+ export function assertPreview<I>(
10
+ mailId: string,
11
+ input: StandardSchemaV1<unknown, I>,
12
+ data: unknown,
13
+ ): I {
14
+ try {
15
+ return parse(input, data, `${mailId}.preview`);
16
+ } catch (error) {
17
+ const reason = isUltimateError(error) ? error.cause : renderThrowable(error);
18
+ throw new MailError({
19
+ code: 'X_MAIL_PREVIEW_INVALID',
20
+ cause: `the preview declared for mail "${mailId}" fails its input schema: ${reason}`,
21
+ fix: `x mail preview ${renderFixShellArg(mailId, '<mail-id>')} --json # then correct preview in the defineMail({ id: '${mailId}' }) call to match its input`,
22
+ meta: { mailId },
23
+ });
24
+ }
25
+ }
26
+
27
+ /** A preview asked of a mail that declares none. */
28
+ export const previewMissing = (mailId: string): MailError =>
29
+ new MailError({
30
+ code: 'X_MAIL_PREVIEW_MISSING',
31
+ cause: `mail "${mailId}" declares no preview, so there is no data to render it with`,
32
+ fix: `x mail preview ${renderFixShellArg(mailId, '<mail-id>')} --json # after adding preview: { ... } to its defineMail({ id: '${mailId}' }) call, shaped like its input`,
33
+ meta: { mailId },
34
+ });
package/src/preview.ts ADDED
@@ -0,0 +1,62 @@
1
+ // Single responsibility: render a mail's declared preview in one locale, with no flow triggered
2
+ // and nothing sent — what `x mail preview`, the `/_x` mail panel and `x verify`'s `i18n` step read.
3
+ // A miss is reported, never refused: a preview exists to show it.
4
+
5
+ import type { TranslationMiss } from '@ultimat3/i18n';
6
+ import type { MailMessage } from './driver';
7
+ import { templateUnknown } from './errors';
8
+ import { type MailDefinition, mailFor, registeredMailIds, renderWithMisses } from './mail';
9
+ import { assertPreview, previewMissing } from './preview-check';
10
+
11
+ /** A recipient no transport can reach: a preview is never a send. */
12
+ export const PREVIEW_RECIPIENT = 'preview@preview.invalid';
13
+
14
+ export interface MailPreviewResult {
15
+ readonly id: string;
16
+ readonly locale: string;
17
+ readonly subject: string;
18
+ readonly html: string;
19
+ readonly text: string;
20
+ /** Every catalog key the render could not resolve in this locale: `send` would refuse these. */
21
+ readonly misses: readonly TranslationMiss[];
22
+ }
23
+
24
+ export interface PreviewOptions {
25
+ readonly locale: string;
26
+ /** IANA zone for every date in the body. Default: the request context, then UTC. */
27
+ readonly tz?: string | undefined;
28
+ }
29
+
30
+ /** Ids of every registered mail that declares a preview, in the registry's order. */
31
+ export function previewableMailIds(): readonly string[] {
32
+ return registeredMailIds().filter((id) => mailFor(id)?.preview !== undefined);
33
+ }
34
+
35
+ export function previewMail(id: string, options: PreviewOptions): MailPreviewResult {
36
+ const mail = mailFor(id);
37
+ if (mail === undefined) throw templateUnknown(id, registeredMailIds());
38
+ const declared = mail.preview;
39
+ if (declared === undefined) throw previewMissing(id);
40
+ const raw: unknown =
41
+ typeof declared === 'function'
42
+ ? Reflect.apply(declared, undefined, [options.locale])
43
+ : declared;
44
+ const data = assertPreview(id, mail.input, raw);
45
+ // The registry erases the payload type; `data` was just parsed by this mail's own schema.
46
+ const typed = mail as unknown as MailDefinition<unknown>;
47
+ const { message, misses } = renderWithMisses(typed, data, {
48
+ to: PREVIEW_RECIPIENT,
49
+ locale: options.locale,
50
+ ...(options.tz === undefined ? {} : { tz: options.tz }),
51
+ });
52
+ return resultOf(message, misses);
53
+ }
54
+
55
+ const resultOf = (message: MailMessage, misses: readonly TranslationMiss[]): MailPreviewResult => ({
56
+ id: message.mailId,
57
+ locale: message.locale,
58
+ subject: message.subject,
59
+ html: message.html,
60
+ text: message.text,
61
+ misses,
62
+ });
package/src/render.ts CHANGED
@@ -4,7 +4,13 @@
4
4
  // clients drop <style>; the dark-mode block is the one exception, for clients that honour it.
5
5
 
6
6
  import { directionOf, escapeHtml } from '@ultimat3/core';
7
- import { type TranslateVars, type Translator, translatorFor } from '@ultimat3/i18n';
7
+ import {
8
+ recordingTranslator,
9
+ type TranslateVars,
10
+ type TranslationMiss,
11
+ type Translator,
12
+ translatorFor,
13
+ } from '@ultimat3/i18n';
8
14
  import type { CalloutTone, MailBlock, MailTemplate } from './blocks';
9
15
  // The renderer depends on the strings it renders. This is the only module that resolves a `mail.*`
10
16
  // key, and `catalog.ts` installs them at ITS module scope — so importing it here is what makes
@@ -36,6 +42,11 @@ export interface RenderedMail {
36
42
  readonly preheader: string;
37
43
  readonly html: string;
38
44
  readonly text: string;
45
+ /**
46
+ * What this render could not answer. Never on a `MailMessage`: `send()` refuses on it and a
47
+ * preview shows the `⟦…⟧` the same render left in the parts above.
48
+ */
49
+ readonly misses: readonly TranslationMiss[];
39
50
  }
40
51
 
41
52
  export const FOOTER_KEYS = ['mail.footer.legal', 'mail.footer.help'] as const;
@@ -49,7 +60,8 @@ export function renderMail<I>(
49
60
  const layout = layoutFor(mail.layout);
50
61
  if (layout === undefined) throw layoutUnknown(mail.id, mail.layout, registeredLayouts());
51
62
 
52
- const t = translatorFor(options.locale);
63
+ const recorded = recordingTranslator(translatorFor(options.locale));
64
+ const t = recorded.t;
53
65
  const vars = toVars(data);
54
66
  const subject = t(mail.subject, vars);
55
67
  const preheaderKey = `mail.${mail.id}.preheader`;
@@ -80,7 +92,7 @@ export function renderMail<I>(
80
92
  tail.push(`${unsubscribe.label}: ${safeMailHref(unsubscribe.url)}`);
81
93
  const text = tail.length === 0 ? bodyText : `${bodyText}\n\n--\n${tail.join('\n')}`;
82
94
 
83
- return { subject, preheader, html, text };
95
+ return { subject, preheader, html, text, misses: recorded.misses() };
84
96
  }
85
97
 
86
98
  /** The text part, block by block. Never derived from the HTML. */
@@ -7,9 +7,10 @@ import {
7
7
  type Clock,
8
8
  ConfigInvalidError,
9
9
  finiteCount,
10
- readWithinLimit,
10
+ isUltimateError,
11
11
  renderThrowable,
12
12
  } from '@ultimat3/core';
13
+ import { outbound } from '@ultimat3/core/outbound';
13
14
  import {
14
15
  type DeliveryOutcome,
15
16
  type DeliveryReceiver,
@@ -54,22 +55,36 @@ export interface SesEventReceiverOptions {
54
55
  readonly fetch?: MailFetch | undefined;
55
56
  }
56
57
 
58
+ /**
59
+ * Why an `outbound()` call to SNS got no usable answer, in this receiver's own words, or the
60
+ * error itself when it is not outbound's (a caller's abort keeps its meaning). `dial: 'named'`:
61
+ * both URLs were already pinned to `sns.<region>.amazonaws.com` before this is reached.
62
+ */
63
+ function providerReason(error: unknown): string {
64
+ if (!isUltimateError(error) || !error.code.startsWith('X_OUTBOUND_')) throw error;
65
+ if (error.code === 'X_OUTBOUND_TOO_LARGE') return 'the answer was too large';
66
+ const status = error.meta?.['status'];
67
+ return typeof status === 'number' ? `HTTP ${status}` : renderThrowable(error);
68
+ }
69
+
57
70
  /** The default download: pinned https, no redirect (a redirect would leave the pinned host). */
58
71
  function defaultCertificateFetch(fetch: MailFetch): SnsCertificateFetch {
59
72
  return async (url) => {
60
- const response = await fetch(url, {
61
- method: 'GET',
62
- redirect: 'error',
63
- signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS),
64
- });
65
- if (!response.ok) {
66
- await response.body?.cancel();
67
- throw deliveryProviderUnreachable('certificate', `HTTP ${response.status}`);
73
+ try {
74
+ const answer = await outbound(
75
+ {
76
+ url,
77
+ vendor: 'sns',
78
+ dial: 'named',
79
+ deadlineMs: PROVIDER_TIMEOUT_MS,
80
+ maxBytes: CERTIFICATE_MAX_BYTES,
81
+ },
82
+ { fetch },
83
+ );
84
+ return answer.text();
85
+ } catch (error) {
86
+ throw deliveryProviderUnreachable('certificate', providerReason(error));
68
87
  }
69
- const read = await readWithinLimit(response.body, CERTIFICATE_MAX_BYTES);
70
- if ('over' in read)
71
- throw deliveryProviderUnreachable('certificate', 'the answer was too large');
72
- return new TextDecoder().decode(read.bytes);
73
88
  };
74
89
  }
75
90
 
@@ -85,7 +100,10 @@ export function sesEventReceiver(options: SesEventReceiverOptions): DeliveryRece
85
100
  options.toleranceMs ?? DEFAULT_SNS_TOLERANCE_MS,
86
101
  1,
87
102
  );
88
- const doFetch: MailFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
103
+ // `outbound()` always hands it the attempt's signal.
104
+ const doFetch: MailFetch =
105
+ options.fetch ??
106
+ ((input, init) => globalThis.fetch(input, { ...init, signal: init.signal ?? null }));
89
107
  const verify = {
90
108
  topicArns,
91
109
  toleranceMs,
@@ -117,18 +135,14 @@ export function sesEventReceiver(options: SesEventReceiverOptions): DeliveryRece
117
135
  if (options.confirmSubscriptions !== true) {
118
136
  return { type: 'subscription', topicArn: message.TopicArn, confirmUrl, confirmed: false };
119
137
  }
120
- let response: Response;
121
138
  try {
122
- response = await doFetch(confirmUrl, {
123
- method: 'GET',
124
- redirect: 'error',
125
- signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS),
126
- });
139
+ await outbound(
140
+ { url: confirmUrl, vendor: 'sns', dial: 'named', deadlineMs: PROVIDER_TIMEOUT_MS },
141
+ { fetch: doFetch },
142
+ );
127
143
  } catch (error) {
128
- throw deliveryProviderUnreachable('subscription', renderThrowable(error));
144
+ throw deliveryProviderUnreachable('subscription', providerReason(error));
129
145
  }
130
- await response.body?.cancel();
131
- if (!response.ok) throw deliveryProviderUnreachable('subscription', `HTTP ${response.status}`);
132
146
  return { type: 'subscription', topicArn: message.TopicArn, confirmUrl, confirmed: true };
133
147
  }
134
148
  }
@@ -165,24 +165,49 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
165
165
  else queue.end();
166
166
  };
167
167
 
168
- const handlers: SocketHandlers = {
168
+ /**
169
+ * Bun keeps calling the ORIGINAL socket's handlers after `upgradeTLS` — with TLS ciphertext and
170
+ * the raw socket's own `close`/`end`/`error` (oven-sh/bun#26297). Flipped once the upgrade has
171
+ * actually handed back a TLS socket, the connect-time handlers go deaf here: those bytes would
172
+ * enter the queue as garbage — reply-shaped ones become phantom replies — and those lifecycle
173
+ * events would kill a conversation the TLS side is still carrying. Same shape as
174
+ * `packages/realtime/src/pg-socket.ts`, which fixed the identical bug.
175
+ */
176
+ let upgraded = false;
177
+
178
+ /** The five socket events; a socket the upgrade retired answers none of them. */
179
+ const makeHandlers = (live: () => boolean): SocketHandlers => ({
169
180
  data: (_socket, data) => {
181
+ if (!live()) return;
170
182
  handshake = undefined;
171
183
  queue.push(decoder.decode(data));
172
184
  },
173
- close: () => died('the socket closed'),
174
- end: () => died('the server half-closed the socket'),
185
+ close: () => {
186
+ if (!live()) return;
187
+ died('the socket closed');
188
+ },
189
+ end: () => {
190
+ if (!live()) return;
191
+ died('the server half-closed the socket');
192
+ },
175
193
  drain: () => {
194
+ if (!live()) return;
176
195
  const waiter = draining;
177
196
  draining = undefined;
178
197
  waiter?.resolve();
179
198
  },
180
199
  error: (_socket, error) => {
200
+ if (!live()) return;
181
201
  const failure = socketFailure(error.message);
182
202
  failDrain(failure);
183
203
  queue.fail(failure);
184
204
  },
185
- };
205
+ });
206
+
207
+ // Registered on the RAW socket at `connect`; deaf once `upgraded` flips.
208
+ const handlers = makeHandlers(() => !upgraded);
209
+ // Registered on the TLS socket at `upgradeTLS`; every event on it is real, so no guard.
210
+ const tlsHandlers = makeHandlers(() => true);
186
211
 
187
212
  const opening = runtime.connect({
188
213
  hostname: target.host,
@@ -241,13 +266,15 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
241
266
  buffered: () => queue.size > 0,
242
267
  write: (data: string) => flush(encoder.encode(data)),
243
268
  startTls: () => {
244
- // Bun hands back `[raw, tls]`; every later read and write goes through the second one, and
245
- // the handlers are re-registered because the upgraded socket is a different object.
246
- const upgraded = socket.upgradeTLS({
269
+ // Bun hands back `[raw, tls]`; every later read and write goes through the second one. The
270
+ // upgraded socket gets its OWN handlers — the raw socket keeps its registered set, which
271
+ // goes deaf above, because Bun keeps feeding it ciphertext and lifecycle events.
272
+ const tls = socket.upgradeTLS({
247
273
  tls: { serverName: target.host },
248
- socket: handlers,
274
+ socket: tlsHandlers,
249
275
  })[1];
250
- if (upgraded === undefined) {
276
+ if (tls === undefined) {
277
+ // Nothing was upgraded, so the raw socket and its handlers stay live.
251
278
  return Promise.reject(
252
279
  sendFailed({
253
280
  driver: 'smtp',
@@ -258,7 +285,8 @@ export function smtpStreamOver(runtime: BunConnect, target: SmtpTarget): Promise
258
285
  }),
259
286
  );
260
287
  }
261
- socket = upgraded;
288
+ upgraded = true;
289
+ socket = tls;
262
290
  // Writes made now are buffered by the runtime until the handshake completes, so the client
263
291
  // may send EHLO straight away — what changes is how a failure from here is reported.
264
292
  handshake = 'starttls';