@shaferllc/keel 0.66.0 → 0.68.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 (132) hide show
  1. package/AGENTS.md +167 -0
  2. package/README.md +30 -1
  3. package/bin/keel-mcp.mjs +9 -0
  4. package/dist/core/application.d.ts +5 -5
  5. package/dist/core/application.js +2 -2
  6. package/dist/core/cache.d.ts +82 -5
  7. package/dist/core/cache.js +181 -23
  8. package/dist/core/cli/stubs.d.ts +12 -0
  9. package/dist/core/cli/stubs.js +120 -0
  10. package/dist/core/events.d.ts +129 -5
  11. package/dist/core/events.js +165 -7
  12. package/dist/core/health.d.ts +141 -0
  13. package/dist/core/health.js +226 -0
  14. package/dist/core/helpers.d.ts +9 -3
  15. package/dist/core/helpers.js +11 -3
  16. package/dist/core/index.d.ts +15 -10
  17. package/dist/core/index.js +7 -4
  18. package/dist/core/lock.d.ts +139 -0
  19. package/dist/core/lock.js +215 -0
  20. package/dist/core/logger.d.ts +82 -4
  21. package/dist/core/logger.js +141 -23
  22. package/dist/core/mail.d.ts +128 -7
  23. package/dist/core/mail.js +264 -16
  24. package/dist/core/queue.d.ts +134 -9
  25. package/dist/core/queue.js +304 -14
  26. package/dist/core/storage.d.ts +159 -6
  27. package/dist/core/storage.js +287 -7
  28. package/dist/mcp/server.d.ts +19 -0
  29. package/dist/mcp/server.js +355 -0
  30. package/docs/ai-manifest.json +2472 -0
  31. package/docs/ai.md +128 -0
  32. package/docs/architecture.md +331 -0
  33. package/docs/authentication.md +453 -0
  34. package/docs/authorization.md +167 -0
  35. package/docs/broadcasting.md +137 -0
  36. package/docs/broker.md +500 -0
  37. package/docs/cache.md +558 -0
  38. package/docs/configuration.md +311 -0
  39. package/docs/console.md +356 -0
  40. package/docs/container.md +467 -0
  41. package/docs/controllers.md +265 -0
  42. package/docs/cors.md +51 -0
  43. package/docs/database.md +530 -0
  44. package/docs/debugging.md +129 -0
  45. package/docs/decorators.md +127 -0
  46. package/docs/errors.md +395 -0
  47. package/docs/events.md +496 -0
  48. package/docs/examples/architecture-app.ts +27 -0
  49. package/docs/examples/authentication.ts +61 -0
  50. package/docs/examples/authorization.ts +79 -0
  51. package/docs/examples/broadcasting.ts +60 -0
  52. package/docs/examples/broker-cache-validate.ts +34 -0
  53. package/docs/examples/broker-fault-tolerance.ts +29 -0
  54. package/docs/examples/broker-middleware.ts +27 -0
  55. package/docs/examples/broker.ts +203 -0
  56. package/docs/examples/cache.ts +222 -0
  57. package/docs/examples/configuration.ts +81 -0
  58. package/docs/examples/container.ts +134 -0
  59. package/docs/examples/controllers.ts +86 -0
  60. package/docs/examples/database.ts +118 -0
  61. package/docs/examples/debugging.ts +41 -0
  62. package/docs/examples/decorators.ts +40 -0
  63. package/docs/examples/errors.ts +121 -0
  64. package/docs/examples/events.ts +204 -0
  65. package/docs/examples/factories.ts +84 -0
  66. package/docs/examples/hashing.ts +71 -0
  67. package/docs/examples/health.ts +94 -0
  68. package/docs/examples/helpers.ts +171 -0
  69. package/docs/examples/hooks.ts +54 -0
  70. package/docs/examples/inertia.ts +81 -0
  71. package/docs/examples/locks.ts +120 -0
  72. package/docs/examples/logger.ts +92 -0
  73. package/docs/examples/mail.ts +160 -0
  74. package/docs/examples/middleware.ts +119 -0
  75. package/docs/examples/migrations.ts +126 -0
  76. package/docs/examples/models.ts +239 -0
  77. package/docs/examples/notification.ts +124 -0
  78. package/docs/examples/providers.ts +123 -0
  79. package/docs/examples/queues.ts +254 -0
  80. package/docs/examples/rate-limiting.ts +42 -0
  81. package/docs/examples/redis.ts +99 -0
  82. package/docs/examples/request-response.ts +197 -0
  83. package/docs/examples/routing.ts +186 -0
  84. package/docs/examples/scheduling.ts +62 -0
  85. package/docs/examples/sessions.ts +102 -0
  86. package/docs/examples/static-files.ts +63 -0
  87. package/docs/examples/storage.ts +132 -0
  88. package/docs/examples/templates.ts +58 -0
  89. package/docs/examples/testing.ts +66 -0
  90. package/docs/examples/transformer.ts +141 -0
  91. package/docs/examples/transformers.ts +49 -0
  92. package/docs/examples/url-builder.ts +86 -0
  93. package/docs/examples/validation.ts +102 -0
  94. package/docs/examples/views.tsx +62 -0
  95. package/docs/examples/vite.ts +106 -0
  96. package/docs/factories.md +166 -0
  97. package/docs/getting-started.md +290 -0
  98. package/docs/hashing.md +259 -0
  99. package/docs/health.md +225 -0
  100. package/docs/helpers.md +347 -0
  101. package/docs/hono.md +186 -0
  102. package/docs/hooks.md +118 -0
  103. package/docs/inertia.md +241 -0
  104. package/docs/locks.md +323 -0
  105. package/docs/logger.md +290 -0
  106. package/docs/mail.md +678 -0
  107. package/docs/middleware.md +425 -0
  108. package/docs/migrations.md +476 -0
  109. package/docs/models.md +810 -0
  110. package/docs/notifications.md +474 -0
  111. package/docs/providers.md +363 -0
  112. package/docs/queues.md +679 -0
  113. package/docs/rate-limiting.md +155 -0
  114. package/docs/redis.md +178 -0
  115. package/docs/request-response.md +953 -0
  116. package/docs/routing.md +804 -0
  117. package/docs/scheduling.md +110 -0
  118. package/docs/security.md +85 -0
  119. package/docs/sessions.md +354 -0
  120. package/docs/social-auth.md +174 -0
  121. package/docs/static-files.md +211 -0
  122. package/docs/storage.md +450 -0
  123. package/docs/templates.md +315 -0
  124. package/docs/testing.md +125 -0
  125. package/docs/transformers.md +381 -0
  126. package/docs/url-builder.md +295 -0
  127. package/docs/validation.md +288 -0
  128. package/docs/views.md +267 -0
  129. package/docs/vite.md +434 -0
  130. package/llms-full.txt +17694 -0
  131. package/llms.txt +116 -0
  132. package/package.json +26 -7
@@ -13,8 +13,28 @@
13
13
  * .html("<h1>Hi</h1>")
14
14
  * .send();
15
15
  *
16
- * In tests, register an `ArrayTransport` and assert on `transport.sent`.
16
+ * Sending is slow and it fails which is exactly what a queue is for. `sendLater()`
17
+ * puts the message on the queue instead of holding the request open for an SMTP
18
+ * round trip:
19
+ *
20
+ * await mail().to(user.email).subject("Welcome").html(body).sendLater();
21
+ *
22
+ * In tests, `fakeMail()` swaps the transport for one that records and asserts.
17
23
  */
24
+ import { Job } from "./queue.js";
25
+ /** A file travelling with the message. */
26
+ export interface Attachment {
27
+ filename: string;
28
+ /** Raw bytes, or a string (UTF-8 encoded). */
29
+ content: string | Uint8Array;
30
+ /** MIME type. Inferred from the filename's extension when omitted. */
31
+ contentType?: string;
32
+ /**
33
+ * A content id, for embedding in the HTML body: an attachment with `cid: "logo"`
34
+ * is referenced as `<img src="cid:logo">`. Implies an inline disposition.
35
+ */
36
+ cid?: string;
37
+ }
18
38
  /** A normalized, ready-to-send message. */
19
39
  export interface Message {
20
40
  to: string[];
@@ -26,6 +46,7 @@ export interface Message {
26
46
  text?: string;
27
47
  html?: string;
28
48
  headers?: Record<string, string>;
49
+ attachments?: Attachment[];
29
50
  }
30
51
  /** The bridge to your email provider. */
31
52
  export interface Transport {
@@ -34,8 +55,10 @@ export interface Transport {
34
55
  export interface MailerOptions {
35
56
  /** Default `from` address for messages that don't set one. */
36
57
  from?: string;
58
+ /** Default `replyTo` for messages that don't set one. */
59
+ replyTo?: string;
37
60
  }
38
- /** A fluent, immutable-ish builder — chain setters, then `send()`. */
61
+ /** A fluent, immutable-ish builder — chain setters, then `send()` or `sendLater()`. */
39
62
  export declare class PendingMail {
40
63
  private mailer;
41
64
  private message;
@@ -49,23 +72,76 @@ export declare class PendingMail {
49
72
  text(text: string): this;
50
73
  html(html: string): this;
51
74
  header(name: string, value: string): this;
75
+ /** Attach a file. The content type is inferred from the extension if omitted. */
76
+ attach(filename: string, content: string | Uint8Array, contentType?: string): this;
77
+ /**
78
+ * Attach an image and give it a content id, so the HTML body can show it inline:
79
+ *
80
+ * .embed("logo", bytes, "logo.png").html(`<img src="cid:logo">`)
81
+ */
82
+ embed(cid: string, content: string | Uint8Array, filename?: string, contentType?: string): this;
52
83
  /** Seed several fields at once (merges into what's been chained). */
53
84
  fill(partial: Partial<{
54
85
  to: string | string[];
55
86
  cc: string | string[];
56
87
  bcc: string | string[];
57
88
  } & Omit<Message, "to" | "cc" | "bcc">>): this;
89
+ /** The message as composed so far — before the mailer applies its defaults. */
90
+ toMessage(): Message;
58
91
  /** Freeze and hand the message to the mailer. */
59
92
  send(): Promise<Message>;
93
+ /**
94
+ * Queue the message instead of sending it now — the request returns without
95
+ * waiting on the provider, and a failed send retries on the queue rather than
96
+ * failing the user's action.
97
+ *
98
+ * With the default `SyncDriver` this still sends inline; register a real queue
99
+ * driver to actually defer it.
100
+ */
101
+ sendLater(): Promise<void>;
102
+ }
103
+ /**
104
+ * A reusable, testable email as a class — the mail equivalent of a `Job`.
105
+ * Implement `build()` to compose the message; the mailer calls it for you.
106
+ *
107
+ * export class WelcomeEmail extends BaseMail {
108
+ * constructor(private user: User) { super(); }
109
+ *
110
+ * build(message: PendingMail) {
111
+ * message.to(this.user.email).subject("Welcome").html(`<h1>Hi ${this.user.name}</h1>`);
112
+ * }
113
+ * }
114
+ *
115
+ * await send(new WelcomeEmail(user)); // or sendLater(new WelcomeEmail(user))
116
+ */
117
+ export declare abstract class BaseMail {
118
+ abstract build(message: PendingMail): void | Promise<void>;
119
+ }
120
+ /** The job that carries a queued message. Exported so a driver can recognize it. */
121
+ export declare class SendMailJob extends Job {
122
+ readonly message: Message;
123
+ readonly mailerName: string;
124
+ constructor(message: Message, mailerName: string);
125
+ handle(): Promise<void>;
60
126
  }
61
127
  export declare class Mailer {
62
128
  private transport;
63
129
  private options;
64
- constructor(transport: Transport, options?: MailerOptions);
130
+ /** The name this mailer is registered under — carried onto queued jobs. */
131
+ readonly name: string;
132
+ constructor(transport: Transport, options?: MailerOptions,
133
+ /** The name this mailer is registered under — carried onto queued jobs. */
134
+ name?: string);
65
135
  /** Start composing a message. */
66
136
  message(): PendingMail;
137
+ /** Apply this mailer's defaults and check the message is sendable. */
138
+ protected prepare(message: Message): Message;
67
139
  /** Validate, apply defaults, and dispatch through the transport. */
68
140
  send(message: Message): Promise<Message>;
141
+ /** Validate, apply defaults, and put the message on the queue. */
142
+ sendLater(message: Message): Promise<Message>;
143
+ /** The underlying transport, for provider-specific operations. */
144
+ get driver(): Transport;
69
145
  }
70
146
  /** Collects sent messages in memory — the default, and ideal for tests. */
71
147
  export declare class ArrayTransport implements Transport {
@@ -86,9 +162,54 @@ export interface FetchTransportOptions {
86
162
  }
87
163
  /** A generic HTTP transport for provider APIs (Resend, Postmark, …), via `fetch`. */
88
164
  export declare function fetchTransport(options: FetchTransportOptions): Transport;
89
- /** Register the default mailer used by `mail()`. */
90
- export declare function setMailer(transport: Transport, options?: MailerOptions): Mailer;
165
+ /** A message recorded by the fake, and whether it was sent now or queued. */
166
+ export interface RecordedMail {
167
+ message: Message;
168
+ queued: boolean;
169
+ }
170
+ /**
171
+ * A `Mailer` that records instead of delivering, with assertions — what
172
+ * `fakeMail()` installs so tests never talk to a provider.
173
+ */
174
+ export declare class FakeMailer extends Mailer {
175
+ readonly mails: RecordedMail[];
176
+ constructor(name?: string, options?: MailerOptions);
177
+ send(message: Message): Promise<Message>;
178
+ sendLater(message: Message): Promise<Message>;
179
+ /** Everything sent immediately. */
180
+ sent(): Message[];
181
+ /** Everything queued with `sendLater()`. */
182
+ queued(): Message[];
183
+ assertSent(where?: (message: Message) => boolean): void;
184
+ assertNotSent(where?: (message: Message) => boolean): void;
185
+ assertSentCount(expected: number): void;
186
+ assertQueued(where?: (message: Message) => boolean): void;
187
+ assertNotQueued(where?: (message: Message) => boolean): void;
188
+ assertQueuedCount(expected: number): void;
189
+ /** Nothing sent and nothing queued. */
190
+ assertNothingSent(): void;
191
+ private summary;
192
+ }
193
+ /** Register a mailer, optionally under a name (default: `"default"`). */
194
+ export declare function setMailer(transport: Transport, options?: MailerOptions, name?: string): Mailer;
195
+ /** The default mailer, or a named one registered with `setMailer(…, …, name)`. */
196
+ export declare function mailer(name?: string): Mailer;
91
197
  /** The default mailer instance. */
92
198
  export declare function getMailer(): Mailer;
93
- /** Start a message on the default mailer: `mail().to(…).subject(…).send()`. */
94
- export declare function mail(): PendingMail;
199
+ /** Start a message on a mailer: `mail().to(…).subject(…).send()`. */
200
+ export declare function mail(name?: string): PendingMail;
201
+ /** Send a class-based mail now. */
202
+ export declare function send(email: BaseMail, name?: string): Promise<Message>;
203
+ /** Queue a class-based mail. */
204
+ export declare function sendLater(email: BaseMail, name?: string): Promise<Message>;
205
+ /**
206
+ * Swap a mailer for a `FakeMailer` so tests never talk to a provider, and assert
207
+ * on what was sent or queued. Undo with `restoreMail()`.
208
+ *
209
+ * const mail = fakeMail();
210
+ * await registerUser();
211
+ * mail.assertQueued((m) => m.subject === "Welcome");
212
+ */
213
+ export declare function fakeMail(name?: string): FakeMailer;
214
+ /** Restore the real mailer after `fakeMail()`. With no name, restores them all. */
215
+ export declare function restoreMail(name?: string): void;
package/dist/core/mail.js CHANGED
@@ -13,15 +13,33 @@
13
13
  * .html("<h1>Hi</h1>")
14
14
  * .send();
15
15
  *
16
- * In tests, register an `ArrayTransport` and assert on `transport.sent`.
16
+ * Sending is slow and it fails which is exactly what a queue is for. `sendLater()`
17
+ * puts the message on the queue instead of holding the request open for an SMTP
18
+ * round trip:
19
+ *
20
+ * await mail().to(user.email).subject("Welcome").html(body).sendLater();
21
+ *
22
+ * In tests, `fakeMail()` swaps the transport for one that records and asserts.
23
+ */
24
+ import { logger, emit, hasApplication } from "./helpers.js";
25
+ import { dispatch, Job } from "./queue.js";
26
+ import { contentTypeFor } from "./storage.js";
27
+ /**
28
+ * Fire a mail lifecycle event, but only if there's an application to fire it on —
29
+ * the mailer has to work in a unit test that never bootstrapped one. A listener
30
+ * that throws still surfaces; it's only the missing-app case we skip.
17
31
  */
18
- import { logger } from "./helpers.js";
32
+ async function notify(event, message) {
33
+ if (hasApplication())
34
+ await emit(event, message);
35
+ }
19
36
  function list(value) {
20
37
  if (value === undefined)
21
38
  return [];
22
39
  return Array.isArray(value) ? value : [value];
23
40
  }
24
- /** A fluent, immutable-ish builder chain setters, then `send()`. */
41
+ /* --------------------------------- builder -------------------------------- */
42
+ /** A fluent, immutable-ish builder — chain setters, then `send()` or `sendLater()`. */
25
43
  export class PendingMail {
26
44
  mailer;
27
45
  message = { to: [], subject: "" };
@@ -64,6 +82,29 @@ export class PendingMail {
64
82
  (this.message.headers ??= {})[name] = value;
65
83
  return this;
66
84
  }
85
+ /** Attach a file. The content type is inferred from the extension if omitted. */
86
+ attach(filename, content, contentType) {
87
+ (this.message.attachments ??= []).push({
88
+ filename,
89
+ content,
90
+ contentType: contentType ?? contentTypeFor(filename),
91
+ });
92
+ return this;
93
+ }
94
+ /**
95
+ * Attach an image and give it a content id, so the HTML body can show it inline:
96
+ *
97
+ * .embed("logo", bytes, "logo.png").html(`<img src="cid:logo">`)
98
+ */
99
+ embed(cid, content, filename = cid, contentType) {
100
+ (this.message.attachments ??= []).push({
101
+ filename,
102
+ content,
103
+ contentType: contentType ?? contentTypeFor(filename),
104
+ cid,
105
+ });
106
+ return this;
107
+ }
67
108
  /** Seed several fields at once (merges into what's been chained). */
68
109
  fill(partial) {
69
110
  const { to, cc, bcc, ...rest } = partial;
@@ -76,25 +117,79 @@ export class PendingMail {
76
117
  Object.assign(this.message, rest);
77
118
  return this;
78
119
  }
120
+ /** The message as composed so far — before the mailer applies its defaults. */
121
+ toMessage() {
122
+ return { ...this.message };
123
+ }
79
124
  /** Freeze and hand the message to the mailer. */
80
125
  async send() {
81
126
  return this.mailer.send(this.message);
82
127
  }
128
+ /**
129
+ * Queue the message instead of sending it now — the request returns without
130
+ * waiting on the provider, and a failed send retries on the queue rather than
131
+ * failing the user's action.
132
+ *
133
+ * With the default `SyncDriver` this still sends inline; register a real queue
134
+ * driver to actually defer it.
135
+ */
136
+ async sendLater() {
137
+ await this.mailer.sendLater(this.message);
138
+ }
139
+ }
140
+ /* ------------------------------- class mails ------------------------------ */
141
+ /**
142
+ * A reusable, testable email as a class — the mail equivalent of a `Job`.
143
+ * Implement `build()` to compose the message; the mailer calls it for you.
144
+ *
145
+ * export class WelcomeEmail extends BaseMail {
146
+ * constructor(private user: User) { super(); }
147
+ *
148
+ * build(message: PendingMail) {
149
+ * message.to(this.user.email).subject("Welcome").html(`<h1>Hi ${this.user.name}</h1>`);
150
+ * }
151
+ * }
152
+ *
153
+ * await send(new WelcomeEmail(user)); // or sendLater(new WelcomeEmail(user))
154
+ */
155
+ export class BaseMail {
156
+ }
157
+ /** The job that carries a queued message. Exported so a driver can recognize it. */
158
+ export class SendMailJob extends Job {
159
+ message;
160
+ mailerName;
161
+ constructor(message, mailerName) {
162
+ super();
163
+ this.message = message;
164
+ this.mailerName = mailerName;
165
+ }
166
+ async handle() {
167
+ await mailer(this.mailerName).send(this.message);
168
+ }
83
169
  }
170
+ /* --------------------------------- mailer --------------------------------- */
84
171
  export class Mailer {
85
172
  transport;
86
173
  options;
87
- constructor(transport, options = {}) {
174
+ name;
175
+ constructor(transport, options = {},
176
+ /** The name this mailer is registered under — carried onto queued jobs. */
177
+ name = "default") {
88
178
  this.transport = transport;
89
179
  this.options = options;
180
+ this.name = name;
90
181
  }
91
182
  /** Start composing a message. */
92
183
  message() {
93
184
  return new PendingMail(this);
94
185
  }
95
- /** Validate, apply defaults, and dispatch through the transport. */
96
- async send(message) {
97
- const final = { ...message, from: message.from ?? this.options.from };
186
+ /** Apply this mailer's defaults and check the message is sendable. */
187
+ prepare(message) {
188
+ const final = {
189
+ ...message,
190
+ from: message.from ?? this.options.from,
191
+ replyTo: message.replyTo ?? this.options.replyTo,
192
+ };
98
193
  if (!final.to.length)
99
194
  throw new Error("Mail: at least one recipient (to) is required.");
100
195
  if (!final.subject)
@@ -103,9 +198,29 @@ export class Mailer {
103
198
  throw new Error("Mail: a text or html body is required.");
104
199
  if (!final.from)
105
200
  throw new Error("Mail: a from address is required (set one or a default).");
201
+ return final;
202
+ }
203
+ /** Validate, apply defaults, and dispatch through the transport. */
204
+ async send(message) {
205
+ const final = this.prepare(message);
206
+ await notify("mail.sending", final);
106
207
  await this.transport.send(final);
208
+ await notify("mail.sent", final);
209
+ return final;
210
+ }
211
+ /** Validate, apply defaults, and put the message on the queue. */
212
+ async sendLater(message) {
213
+ // Validate *now*, not on the worker: a malformed message should blow up at
214
+ // the call site, where the stack trace means something.
215
+ const final = this.prepare(message);
216
+ await dispatch(new SendMailJob(final, this.name));
217
+ await notify("mail.queued", final);
107
218
  return final;
108
219
  }
220
+ /** The underlying transport, for provider-specific operations. */
221
+ get driver() {
222
+ return this.transport;
223
+ }
109
224
  }
110
225
  /* ------------------------------- transports ------------------------------- */
111
226
  /** Collects sent messages in memory — the default, and ideal for tests. */
@@ -140,18 +255,151 @@ export function fetchTransport(options) {
140
255
  },
141
256
  };
142
257
  }
258
+ /**
259
+ * A `Mailer` that records instead of delivering, with assertions — what
260
+ * `fakeMail()` installs so tests never talk to a provider.
261
+ */
262
+ export class FakeMailer extends Mailer {
263
+ mails = [];
264
+ constructor(name = "default", options = {}) {
265
+ // A from address so a fake never trips the "from is required" check.
266
+ super(new ArrayTransport(), { from: "fake@example.com", ...options }, name);
267
+ }
268
+ async send(message) {
269
+ const final = await super.send(message);
270
+ this.mails.push({ message: final, queued: false });
271
+ return final;
272
+ }
273
+ async sendLater(message) {
274
+ // Validate exactly as a real mailer would, but don't touch the queue —
275
+ // recording the intent *is* the point.
276
+ const final = this.prepare(message);
277
+ this.mails.push({ message: final, queued: true });
278
+ await notify("mail.queued", final);
279
+ return final;
280
+ }
281
+ /** Everything sent immediately. */
282
+ sent() {
283
+ return this.mails.filter((m) => !m.queued).map((m) => m.message);
284
+ }
285
+ /** Everything queued with `sendLater()`. */
286
+ queued() {
287
+ return this.mails.filter((m) => m.queued).map((m) => m.message);
288
+ }
289
+ assertSent(where) {
290
+ const matches = this.sent().filter((m) => where?.(m) ?? true);
291
+ if (matches.length)
292
+ return;
293
+ throw new Error(where && this.sent().length
294
+ ? `Expected a sent mail matching the predicate. ${this.sent().length} were sent, but none matched.`
295
+ : `Expected a mail to be sent, but none was. ${this.summary()}`);
296
+ }
297
+ assertNotSent(where) {
298
+ const found = this.sent().filter((m) => where?.(m) ?? true).length;
299
+ if (found)
300
+ throw new Error(`Expected no matching mail to be sent, but ${found} was.`);
301
+ }
302
+ assertSentCount(expected) {
303
+ const found = this.sent().length;
304
+ if (found !== expected) {
305
+ throw new Error(`Expected ${expected} mail(s) to be sent, but ${found} were.`);
306
+ }
307
+ }
308
+ assertQueued(where) {
309
+ const matches = this.queued().filter((m) => where?.(m) ?? true);
310
+ if (matches.length)
311
+ return;
312
+ throw new Error(where && this.queued().length
313
+ ? `Expected a queued mail matching the predicate. ${this.queued().length} were queued, but none matched.`
314
+ : `Expected a mail to be queued, but none was. ${this.summary()}`);
315
+ }
316
+ assertNotQueued(where) {
317
+ const found = this.queued().filter((m) => where?.(m) ?? true).length;
318
+ if (found)
319
+ throw new Error(`Expected no matching mail to be queued, but ${found} was.`);
320
+ }
321
+ assertQueuedCount(expected) {
322
+ const found = this.queued().length;
323
+ if (found !== expected) {
324
+ throw new Error(`Expected ${expected} mail(s) to be queued, but ${found} were.`);
325
+ }
326
+ }
327
+ /** Nothing sent and nothing queued. */
328
+ assertNothingSent() {
329
+ if (this.mails.length) {
330
+ throw new Error(`Expected no mail at all, but ${this.mails.length} were recorded. ${this.summary()}`);
331
+ }
332
+ }
333
+ summary() {
334
+ if (!this.mails.length)
335
+ return "No mail was sent or queued.";
336
+ const subjects = this.mails.map((m) => `"${m.message.subject}"`).join(", ");
337
+ return `Recorded: ${subjects}.`;
338
+ }
339
+ }
143
340
  /* --------------------------------- global --------------------------------- */
144
- let mailer = new Mailer(new ArrayTransport());
145
- /** Register the default mailer used by `mail()`. */
146
- export function setMailer(transport, options = {}) {
147
- mailer = new Mailer(transport, options);
148
- return mailer;
341
+ const mailers = new Map([["default", new Mailer(new ArrayTransport())]]);
342
+ /** Mailers displaced by `fakeMail()`, so `restoreMail()` can put them back. */
343
+ const realMailers = new Map();
344
+ /** Register a mailer, optionally under a name (default: `"default"`). */
345
+ export function setMailer(transport, options = {}, name = "default") {
346
+ const instance = new Mailer(transport, options, name);
347
+ mailers.set(name, instance);
348
+ return instance;
349
+ }
350
+ /** The default mailer, or a named one registered with `setMailer(…, …, name)`. */
351
+ export function mailer(name = "default") {
352
+ const instance = mailers.get(name);
353
+ if (!instance)
354
+ throw new Error(`No mailer named "${name}". Register it with setMailer().`);
355
+ return instance;
149
356
  }
150
357
  /** The default mailer instance. */
151
358
  export function getMailer() {
152
- return mailer;
359
+ return mailer();
360
+ }
361
+ /** Start a message on a mailer: `mail().to(…).subject(…).send()`. */
362
+ export function mail(name = "default") {
363
+ return mailer(name).message();
364
+ }
365
+ /** Build a `BaseMail` into a message on the given mailer. */
366
+ async function build(email, name) {
367
+ const pending = mailer(name).message();
368
+ await email.build(pending);
369
+ return pending.toMessage();
153
370
  }
154
- /** Start a message on the default mailer: `mail().to(…).subject(…).send()`. */
155
- export function mail() {
156
- return mailer.message();
371
+ /** Send a class-based mail now. */
372
+ export async function send(email, name = "default") {
373
+ return mailer(name).send(await build(email, name));
374
+ }
375
+ /** Queue a class-based mail. */
376
+ export async function sendLater(email, name = "default") {
377
+ return mailer(name).sendLater(await build(email, name));
378
+ }
379
+ /**
380
+ * Swap a mailer for a `FakeMailer` so tests never talk to a provider, and assert
381
+ * on what was sent or queued. Undo with `restoreMail()`.
382
+ *
383
+ * const mail = fakeMail();
384
+ * await registerUser();
385
+ * mail.assertQueued((m) => m.subject === "Welcome");
386
+ */
387
+ export function fakeMail(name = "default") {
388
+ const existing = mailers.get(name);
389
+ // Only remember the *real* mailer — faking twice must not stash a fake.
390
+ if (existing && !realMailers.has(name))
391
+ realMailers.set(name, existing);
392
+ const fake = new FakeMailer(name);
393
+ mailers.set(name, fake);
394
+ return fake;
395
+ }
396
+ /** Restore the real mailer after `fakeMail()`. With no name, restores them all. */
397
+ export function restoreMail(name) {
398
+ const names = name ? [name] : [...realMailers.keys()];
399
+ for (const key of names) {
400
+ const real = realMailers.get(key);
401
+ if (real)
402
+ mailers.set(key, real);
403
+ realMailers.delete(key);
404
+ }
157
405
  }