@web-ts-toolkit/email-service 0.72.0 → 0.74.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@web-ts-toolkit/email-service",
3
3
  "description": "Typed email preparation, queue and submission contracts for Node.js",
4
- "version": "0.72.0",
4
+ "version": "0.74.0",
5
5
  "keywords": [
6
6
  "email",
7
7
  "handlebars",
@@ -5,6 +5,17 @@ type EmailScope = string;
5
5
  type EmailJobId = string;
6
6
  type EmailAttemptId = string;
7
7
  type Awaitable<T> = T | PromiseLike<T>;
8
+ /**
9
+ * Trusted live SMTP opt-in. Pass the same tuple at each factory in the queue; omit it for V1 (50 recipients).
10
+ * `namespace` is a canonical lowercase UUIDv4 for one logical backing. Keep its cap fixed; use a new namespace
11
+ * to change it. `maxRecipients` is an integer from 51 to 1,000, counting To, Cc and Bcc together.
12
+ * `format` selects storage, not the DTO's `version: 1`. Never select the binding from request data.
13
+ */
14
+ type SmtpCapacity = Readonly<{
15
+ format: 'smtp-v2';
16
+ namespace: string;
17
+ maxRecipients: number;
18
+ }>;
8
19
  /** Plain JSON at the validation boundary; this type alone does not check serialization or size. */
9
20
  type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;
10
21
  type JsonObject = {
@@ -51,6 +62,7 @@ type AttachmentRef = {
51
62
  readonly id: string;
52
63
  readonly version: string;
53
64
  readonly filename: string;
65
+ /** Lower-case MIME `type/subtype` without parameters. New SMTP messages reject `message/*` and `multipart/*`. */
54
66
  readonly contentType: string;
55
67
  readonly byteLength: number;
56
68
  readonly sha256: string;
@@ -87,6 +99,7 @@ type EmailSnapshot = SnapshotFields & ({
87
99
  readonly provider: Extract<ProviderRef, {
88
100
  kind: 'smtp';
89
101
  }>;
102
+ readonly smtpCapacity?: SmtpCapacity;
90
103
  readonly subject: string;
91
104
  readonly html?: string;
92
105
  readonly text?: string;
@@ -95,12 +108,15 @@ type EmailSnapshot = SnapshotFields & ({
95
108
  readonly provider: Extract<ProviderRef, {
96
109
  kind: 'sendgrid';
97
110
  }>;
111
+ readonly smtpCapacity?: never;
98
112
  readonly templateId: string;
99
113
  readonly data: JsonObject;
100
114
  });
101
115
  /** Versioned, sensitive outbox value. Store it with the host's business write, then relay it unchanged. */
102
116
  type PreparedEmailCommand = {
103
117
  readonly version: 1;
118
+ /** Present on every staged message from an opted-in SMTP lane, even below 51 recipients. */
119
+ readonly smtpCapacity?: SmtpCapacity;
104
120
  readonly scope: EmailScope;
105
121
  readonly key: EmailAdmissionKey;
106
122
  readonly scheduleAt: UnixMs | null;
@@ -137,7 +153,7 @@ type RetryHint = {
137
153
  readonly notBefore?: UnixMs;
138
154
  };
139
155
  /** Normalized, bounded evidence; never a raw SDK code or response message. */
140
- type ProviderReason = 'smtp_accepted' | 'smtp_partial' | 'smtp_transient_reply' | 'smtp_permanent_reply' | 'sendgrid_accepted' | 'sendgrid_validated' | 'sendgrid_throttled' | 'sendgrid_rejected' | 'not_transmitted' | 'provider_configuration' | 'transport_uncertain' | 'provider_timeout' | 'provider_aborted';
156
+ type ProviderReason = ProviderResult['reason'];
141
157
  type AttemptReason = ProviderReason | 'attachment_unavailable' | 'attachment_timeout' | 'attachment_invalid' | 'attachment_resolver_error' | 'rate_deferred' | 'rate_timeout' | 'rate_error' | 'profile_unavailable' | 'provider_preflight_error' | 'pre_handoff_timeout' | 'worker_stopped' | 'pre_handoff_lease_expired' | 'launch_window_closed' | 'post_handoff_lease_expired' | 'expired' | 'cancelled';
142
158
  type AttemptResult = {
143
159
  readonly outcome: SubmissionOutcome;
@@ -149,10 +165,51 @@ type AttemptResult = {
149
165
  readonly messageId?: string;
150
166
  readonly providerMessageId?: string;
151
167
  };
152
- type ProviderResult = Omit<AttemptResult, 'stage' | 'reason'> & {
153
- readonly stage: Exclude<SubmissionStage, 'pre_handoff' | 'attachment' | 'rate_limit'>;
154
- readonly reason: ProviderReason;
155
- };
168
+ type ProviderStage = Exclude<SubmissionStage, 'pre_handoff' | 'attachment' | 'rate_limit'>;
169
+ type SmtpStage = Exclude<ProviderStage, 'http'>;
170
+ type EvidenceField = 'recipients' | 'messageId' | 'providerMessageId' | 'retryHint';
171
+ type ProviderEvidence<Reason extends string, Outcome extends SubmissionOutcome, Retry extends RetryClass, Stage extends ProviderStage, Details = Record<never, never>> = Readonly<{
172
+ reason: Reason;
173
+ outcome: Outcome;
174
+ retry: Retry;
175
+ stage: Stage;
176
+ }> & Readonly<Details> & {
177
+ readonly [Field in Exclude<EvidenceField, keyof Details>]?: never;
178
+ };
179
+ type RecipientWithStatus<Status extends RecipientResult['status']> = RecipientResult & {
180
+ readonly status: Status;
181
+ };
182
+ type AcceptedSmtpRecipients = readonly [RecipientWithStatus<'accepted'>, ...RecipientWithStatus<'accepted'>[]];
183
+ type MixedSmtpRecipients = readonly [RecipientResult, RecipientResult, ...RecipientResult[]] & {
184
+ readonly __checkedSmtpMixedRecipients: never;
185
+ };
186
+ type SmtpAcceptance<Recipients extends readonly RecipientResult[]> = {
187
+ recipients: Recipients;
188
+ messageId?: string;
189
+ };
190
+ type RejectedRecipients = {
191
+ readonly recipients?: never;
192
+ } | {
193
+ readonly stage: 'envelope' | 'data';
194
+ readonly recipients: readonly RecipientWithStatus<'rejected'>[];
195
+ };
196
+ type ThrottleHint = RetryHint & (Readonly<{
197
+ delayMs: number;
198
+ }> | Readonly<{
199
+ notBefore: UnixMs;
200
+ }>);
201
+ type TransportEvidence<Reason extends string, Outcome extends SubmissionOutcome, Retry extends RetryClass> = Reason extends string ? ProviderEvidence<Reason, Outcome, Retry, ProviderStage, RejectedRecipients> : never;
202
+ /**
203
+ * Submission evidence discriminated by `reason`. Full SMTP acceptance requires a nonempty
204
+ * all-accepted tuple. Use `createSmtpAcceptanceResult` to check a dynamic list or produce
205
+ * partial acceptance. The worker still checks the actual envelope and profile kind/mode.
206
+ * Invalid evidence after handoff is unknown, not permission to retry.
207
+ */
208
+ type ProviderResult = ProviderEvidence<'smtp_accepted', 'accepted', 'never', 'data', SmtpAcceptance<AcceptedSmtpRecipients>> | ProviderEvidence<'smtp_partial', 'partially_accepted', 'never', 'data', SmtpAcceptance<MixedSmtpRecipients>> | ProviderEvidence<'smtp_transient_reply', 'rejected', 'safe_transient', SmtpStage, RejectedRecipients> | ProviderEvidence<'smtp_permanent_reply', 'rejected', 'never', SmtpStage, RejectedRecipients> | ProviderEvidence<'sendgrid_accepted', 'accepted', 'never', 'http', {
209
+ providerMessageId?: string;
210
+ }> | ProviderEvidence<'sendgrid_validated', 'validated', 'never', 'http'> | ProviderEvidence<'sendgrid_throttled', 'rejected', 'safe_transient', 'http', {
211
+ retryHint?: ThrottleHint;
212
+ }> | ProviderEvidence<'sendgrid_rejected', 'rejected', 'never', 'http'> | TransportEvidence<'not_transmitted', 'unsubmitted', 'safe_transient'> | TransportEvidence<'provider_configuration', 'unsubmitted', 'never'> | TransportEvidence<'transport_uncertain' | 'provider_timeout' | 'provider_aborted', 'unknown', 'never'>;
156
213
  type ProviderSubmission<M extends EmailSnapshot> = {
157
214
  readonly jobId: EmailJobId;
158
215
  readonly attemptId: EmailAttemptId;
@@ -175,9 +232,10 @@ interface PreparedEmailSubmission {
175
232
  }
176
233
  interface EmailProvider<M extends EmailSnapshot> {
177
234
  readonly ref: M['provider'];
235
+ readonly smtpCapacity?: SmtpCapacity;
178
236
  /** Validate and prepare without I/O. Direct unmanaged submission has no queue or retry guarantees. */
179
237
  prepare(input: ProviderSubmission<M>): PreparedEmailSubmission;
180
238
  }
181
239
  type ConfiguredEmailProvider = EmailProvider<SmtpSnapshot> | EmailProvider<SendGridSnapshot>;
182
240
 
183
- export type { Awaitable as A, SubmissionStage as B, Correlation as C, EmailEnvelope as E, JsonObject as J, Mailbox as M, ProviderRef as P, RecipientResult as R, SendGridSnapshot as S, TemplateIdentity as T, UnixMs as U, EmailScope as a, EmailAdmissionKey as b, AttachmentRef as c, JsonValue as d, CallOptions as e, PreparedEmailCommand as f, EmailClock as g, AttachmentResolution as h, AttachmentResolver as i, AttemptReason as j, AttemptResult as k, ConfiguredEmailProvider as l, EmailAttemptId as m, EmailJobId as n, EmailProvider as o, EmailSnapshot as p, PreparedEmailSubmission as q, ProviderCall as r, ProviderReason as s, ProviderResult as t, ProviderSubmission as u, ResolvedAttachment as v, RetryClass as w, RetryHint as x, SmtpSnapshot as y, SubmissionOutcome as z };
241
+ export type { Awaitable as A, SubmissionOutcome as B, Correlation as C, SubmissionStage as D, EmailEnvelope as E, JsonObject as J, Mailbox as M, ProviderRef as P, RecipientResult as R, SmtpCapacity as S, TemplateIdentity as T, UnixMs as U, EmailScope as a, EmailAdmissionKey as b, AttachmentRef as c, JsonValue as d, CallOptions as e, PreparedEmailCommand as f, EmailClock as g, ProviderResult as h, AttachmentResolution as i, AttachmentResolver as j, AttemptReason as k, AttemptResult as l, ConfiguredEmailProvider as m, EmailAttemptId as n, EmailJobId as o, EmailProvider as p, EmailSnapshot as q, PreparedEmailSubmission as r, ProviderCall as s, ProviderReason as t, ProviderSubmission as u, ResolvedAttachment as v, RetryClass as w, RetryHint as x, SendGridSnapshot as y, SmtpSnapshot as z };
@@ -5,6 +5,17 @@ type EmailScope = string;
5
5
  type EmailJobId = string;
6
6
  type EmailAttemptId = string;
7
7
  type Awaitable<T> = T | PromiseLike<T>;
8
+ /**
9
+ * Trusted live SMTP opt-in. Pass the same tuple at each factory in the queue; omit it for V1 (50 recipients).
10
+ * `namespace` is a canonical lowercase UUIDv4 for one logical backing. Keep its cap fixed; use a new namespace
11
+ * to change it. `maxRecipients` is an integer from 51 to 1,000, counting To, Cc and Bcc together.
12
+ * `format` selects storage, not the DTO's `version: 1`. Never select the binding from request data.
13
+ */
14
+ type SmtpCapacity = Readonly<{
15
+ format: 'smtp-v2';
16
+ namespace: string;
17
+ maxRecipients: number;
18
+ }>;
8
19
  /** Plain JSON at the validation boundary; this type alone does not check serialization or size. */
9
20
  type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;
10
21
  type JsonObject = {
@@ -51,6 +62,7 @@ type AttachmentRef = {
51
62
  readonly id: string;
52
63
  readonly version: string;
53
64
  readonly filename: string;
65
+ /** Lower-case MIME `type/subtype` without parameters. New SMTP messages reject `message/*` and `multipart/*`. */
54
66
  readonly contentType: string;
55
67
  readonly byteLength: number;
56
68
  readonly sha256: string;
@@ -87,6 +99,7 @@ type EmailSnapshot = SnapshotFields & ({
87
99
  readonly provider: Extract<ProviderRef, {
88
100
  kind: 'smtp';
89
101
  }>;
102
+ readonly smtpCapacity?: SmtpCapacity;
90
103
  readonly subject: string;
91
104
  readonly html?: string;
92
105
  readonly text?: string;
@@ -95,12 +108,15 @@ type EmailSnapshot = SnapshotFields & ({
95
108
  readonly provider: Extract<ProviderRef, {
96
109
  kind: 'sendgrid';
97
110
  }>;
111
+ readonly smtpCapacity?: never;
98
112
  readonly templateId: string;
99
113
  readonly data: JsonObject;
100
114
  });
101
115
  /** Versioned, sensitive outbox value. Store it with the host's business write, then relay it unchanged. */
102
116
  type PreparedEmailCommand = {
103
117
  readonly version: 1;
118
+ /** Present on every staged message from an opted-in SMTP lane, even below 51 recipients. */
119
+ readonly smtpCapacity?: SmtpCapacity;
104
120
  readonly scope: EmailScope;
105
121
  readonly key: EmailAdmissionKey;
106
122
  readonly scheduleAt: UnixMs | null;
@@ -137,7 +153,7 @@ type RetryHint = {
137
153
  readonly notBefore?: UnixMs;
138
154
  };
139
155
  /** Normalized, bounded evidence; never a raw SDK code or response message. */
140
- type ProviderReason = 'smtp_accepted' | 'smtp_partial' | 'smtp_transient_reply' | 'smtp_permanent_reply' | 'sendgrid_accepted' | 'sendgrid_validated' | 'sendgrid_throttled' | 'sendgrid_rejected' | 'not_transmitted' | 'provider_configuration' | 'transport_uncertain' | 'provider_timeout' | 'provider_aborted';
156
+ type ProviderReason = ProviderResult['reason'];
141
157
  type AttemptReason = ProviderReason | 'attachment_unavailable' | 'attachment_timeout' | 'attachment_invalid' | 'attachment_resolver_error' | 'rate_deferred' | 'rate_timeout' | 'rate_error' | 'profile_unavailable' | 'provider_preflight_error' | 'pre_handoff_timeout' | 'worker_stopped' | 'pre_handoff_lease_expired' | 'launch_window_closed' | 'post_handoff_lease_expired' | 'expired' | 'cancelled';
142
158
  type AttemptResult = {
143
159
  readonly outcome: SubmissionOutcome;
@@ -149,10 +165,51 @@ type AttemptResult = {
149
165
  readonly messageId?: string;
150
166
  readonly providerMessageId?: string;
151
167
  };
152
- type ProviderResult = Omit<AttemptResult, 'stage' | 'reason'> & {
153
- readonly stage: Exclude<SubmissionStage, 'pre_handoff' | 'attachment' | 'rate_limit'>;
154
- readonly reason: ProviderReason;
155
- };
168
+ type ProviderStage = Exclude<SubmissionStage, 'pre_handoff' | 'attachment' | 'rate_limit'>;
169
+ type SmtpStage = Exclude<ProviderStage, 'http'>;
170
+ type EvidenceField = 'recipients' | 'messageId' | 'providerMessageId' | 'retryHint';
171
+ type ProviderEvidence<Reason extends string, Outcome extends SubmissionOutcome, Retry extends RetryClass, Stage extends ProviderStage, Details = Record<never, never>> = Readonly<{
172
+ reason: Reason;
173
+ outcome: Outcome;
174
+ retry: Retry;
175
+ stage: Stage;
176
+ }> & Readonly<Details> & {
177
+ readonly [Field in Exclude<EvidenceField, keyof Details>]?: never;
178
+ };
179
+ type RecipientWithStatus<Status extends RecipientResult['status']> = RecipientResult & {
180
+ readonly status: Status;
181
+ };
182
+ type AcceptedSmtpRecipients = readonly [RecipientWithStatus<'accepted'>, ...RecipientWithStatus<'accepted'>[]];
183
+ type MixedSmtpRecipients = readonly [RecipientResult, RecipientResult, ...RecipientResult[]] & {
184
+ readonly __checkedSmtpMixedRecipients: never;
185
+ };
186
+ type SmtpAcceptance<Recipients extends readonly RecipientResult[]> = {
187
+ recipients: Recipients;
188
+ messageId?: string;
189
+ };
190
+ type RejectedRecipients = {
191
+ readonly recipients?: never;
192
+ } | {
193
+ readonly stage: 'envelope' | 'data';
194
+ readonly recipients: readonly RecipientWithStatus<'rejected'>[];
195
+ };
196
+ type ThrottleHint = RetryHint & (Readonly<{
197
+ delayMs: number;
198
+ }> | Readonly<{
199
+ notBefore: UnixMs;
200
+ }>);
201
+ type TransportEvidence<Reason extends string, Outcome extends SubmissionOutcome, Retry extends RetryClass> = Reason extends string ? ProviderEvidence<Reason, Outcome, Retry, ProviderStage, RejectedRecipients> : never;
202
+ /**
203
+ * Submission evidence discriminated by `reason`. Full SMTP acceptance requires a nonempty
204
+ * all-accepted tuple. Use `createSmtpAcceptanceResult` to check a dynamic list or produce
205
+ * partial acceptance. The worker still checks the actual envelope and profile kind/mode.
206
+ * Invalid evidence after handoff is unknown, not permission to retry.
207
+ */
208
+ type ProviderResult = ProviderEvidence<'smtp_accepted', 'accepted', 'never', 'data', SmtpAcceptance<AcceptedSmtpRecipients>> | ProviderEvidence<'smtp_partial', 'partially_accepted', 'never', 'data', SmtpAcceptance<MixedSmtpRecipients>> | ProviderEvidence<'smtp_transient_reply', 'rejected', 'safe_transient', SmtpStage, RejectedRecipients> | ProviderEvidence<'smtp_permanent_reply', 'rejected', 'never', SmtpStage, RejectedRecipients> | ProviderEvidence<'sendgrid_accepted', 'accepted', 'never', 'http', {
209
+ providerMessageId?: string;
210
+ }> | ProviderEvidence<'sendgrid_validated', 'validated', 'never', 'http'> | ProviderEvidence<'sendgrid_throttled', 'rejected', 'safe_transient', 'http', {
211
+ retryHint?: ThrottleHint;
212
+ }> | ProviderEvidence<'sendgrid_rejected', 'rejected', 'never', 'http'> | TransportEvidence<'not_transmitted', 'unsubmitted', 'safe_transient'> | TransportEvidence<'provider_configuration', 'unsubmitted', 'never'> | TransportEvidence<'transport_uncertain' | 'provider_timeout' | 'provider_aborted', 'unknown', 'never'>;
156
213
  type ProviderSubmission<M extends EmailSnapshot> = {
157
214
  readonly jobId: EmailJobId;
158
215
  readonly attemptId: EmailAttemptId;
@@ -175,9 +232,10 @@ interface PreparedEmailSubmission {
175
232
  }
176
233
  interface EmailProvider<M extends EmailSnapshot> {
177
234
  readonly ref: M['provider'];
235
+ readonly smtpCapacity?: SmtpCapacity;
178
236
  /** Validate and prepare without I/O. Direct unmanaged submission has no queue or retry guarantees. */
179
237
  prepare(input: ProviderSubmission<M>): PreparedEmailSubmission;
180
238
  }
181
239
  type ConfiguredEmailProvider = EmailProvider<SmtpSnapshot> | EmailProvider<SendGridSnapshot>;
182
240
 
183
- export type { Awaitable as A, SubmissionStage as B, Correlation as C, EmailEnvelope as E, JsonObject as J, Mailbox as M, ProviderRef as P, RecipientResult as R, SendGridSnapshot as S, TemplateIdentity as T, UnixMs as U, EmailScope as a, EmailAdmissionKey as b, AttachmentRef as c, JsonValue as d, CallOptions as e, PreparedEmailCommand as f, EmailClock as g, AttachmentResolution as h, AttachmentResolver as i, AttemptReason as j, AttemptResult as k, ConfiguredEmailProvider as l, EmailAttemptId as m, EmailJobId as n, EmailProvider as o, EmailSnapshot as p, PreparedEmailSubmission as q, ProviderCall as r, ProviderReason as s, ProviderResult as t, ProviderSubmission as u, ResolvedAttachment as v, RetryClass as w, RetryHint as x, SmtpSnapshot as y, SubmissionOutcome as z };
241
+ export type { Awaitable as A, SubmissionOutcome as B, Correlation as C, SubmissionStage as D, EmailEnvelope as E, JsonObject as J, Mailbox as M, ProviderRef as P, RecipientResult as R, SmtpCapacity as S, TemplateIdentity as T, UnixMs as U, EmailScope as a, EmailAdmissionKey as b, AttachmentRef as c, JsonValue as d, CallOptions as e, PreparedEmailCommand as f, EmailClock as g, ProviderResult as h, AttachmentResolution as i, AttachmentResolver as j, AttemptReason as k, AttemptResult as l, ConfiguredEmailProvider as m, EmailAttemptId as n, EmailJobId as o, EmailProvider as p, EmailSnapshot as q, PreparedEmailSubmission as r, ProviderCall as s, ProviderReason as t, ProviderSubmission as u, ResolvedAttachment as v, RetryClass as w, RetryHint as x, SendGridSnapshot as y, SmtpSnapshot as z };
package/sendgrid.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as EmailProvider, S as SendGridSnapshot } from './provider-HisBc6hk.mjs';
1
+ import { p as EmailProvider, y as SendGridSnapshot } from './provider-CeUryYAf.mjs';
2
2
 
3
3
  /** Instance-owned credentials for HTTPS Mail Send only, not for template administration. */
4
4
  type SendGridProviderOptions = {
package/sendgrid.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as EmailProvider, S as SendGridSnapshot } from './provider-HisBc6hk.js';
1
+ import { p as EmailProvider, y as SendGridSnapshot } from './provider-CeUryYAf.js';
2
2
 
3
3
  /** Instance-owned credentials for HTTPS Mail Send only, not for template administration. */
4
4
  type SendGridProviderOptions = {
package/sendgrid.js CHANGED
@@ -262,6 +262,12 @@ function opaqueToken(value, maxBytes, code) {
262
262
  function identifier(value, code) {
263
263
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
264
264
  }
265
+ function uuidV4(value, code) {
266
+ if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
267
+ invalid(code);
268
+ }
269
+ return value;
270
+ }
265
271
  function hashToken(value, code) {
266
272
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
267
273
  return value;
@@ -275,9 +281,9 @@ function jsonKey(key, code) {
275
281
 
276
282
  // src/internal/canonical-json.ts
277
283
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
278
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
284
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
279
285
  let bytesLeft = maxBytes;
280
- let valuesLeft = limits.values;
286
+ let valuesLeft = limits2.values;
281
287
  const chunks = [];
282
288
  const ancestors = /* @__PURE__ */ new Set();
283
289
  function append(text, bytes = text.length) {
@@ -296,7 +302,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
296
302
  append(JSON.stringify(text), bytes);
297
303
  }
298
304
  function visit(value2, depth) {
299
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
305
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
300
306
  switch (typeof value2) {
301
307
  case "string":
302
308
  appendString(value2);
@@ -320,7 +326,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
320
326
  if (ancestors.has(value2)) invalid(code);
321
327
  ancestors.add(value2);
322
328
  try {
323
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
329
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
324
330
  if (isArray(value2, code)) {
325
331
  const length = denseArrayLength(value2, maxChildren, code);
326
332
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -360,6 +366,67 @@ function copyJsonObject(input, maxBytes, code) {
360
366
  function sha256(input) {
361
367
  return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
362
368
  }
369
+ function encodeEvidence(input, code, capacity) {
370
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
371
+ }
372
+
373
+ // src/internal/smtp-capacity.ts
374
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
375
+ var MAX_SMTP_RECIPIENTS = 1e3;
376
+ var KIB = 1024;
377
+ var limits = Object.freeze({
378
+ snapshotBytes: 2 * KIB * KIB,
379
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
380
+ evidenceBytes: 64 * KIB,
381
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
382
+ jobBsonBytes: 4 * KIB * KIB,
383
+ activityBsonBytes: 128 * KIB,
384
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
385
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
386
+ servicePending: 4,
387
+ workerProfiles: 16,
388
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
389
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
390
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
391
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
392
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
393
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
394
+ mongoInFlight: 4,
395
+ dueCandidates: 4
396
+ });
397
+ function readBinding(input, code) {
398
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
399
+ if (format !== "smtp-v2") invalid(code);
400
+ return Object.freeze({
401
+ format,
402
+ namespace: uuidV4(namespace, code),
403
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
404
+ });
405
+ }
406
+ function capacityTag(capacity) {
407
+ return capacity ? { smtpCapacity: capacity.binding } : {};
408
+ }
409
+ function recipientLimit(capacity) {
410
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
411
+ }
412
+ function matchesBinding(input, capacity, code) {
413
+ const binding = readBinding(input, code);
414
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
415
+ invalid(code);
416
+ }
417
+ }
418
+ function assertCapacityTag(raw, capacity, code) {
419
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
420
+ if (capacity) {
421
+ if (!tagged) invalid(code);
422
+ matchesBinding(raw.smtpCapacity, capacity, code);
423
+ } else if (tagged) {
424
+ invalid(code);
425
+ }
426
+ }
427
+ function assertCapacityProvider(provider, capacity, code) {
428
+ if (capacity && provider.kind !== "smtp") invalid(code);
429
+ }
363
430
 
364
431
  // src/internal/attempt-codecs.ts
365
432
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -399,12 +466,33 @@ function readAttemptReason(value, code) {
399
466
  if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
400
467
  return value;
401
468
  }
469
+ var recipientGroups = ["to", "cc", "bcc"];
402
470
  function recipientCounts(envelope) {
403
471
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
404
472
  }
405
473
  function smtpMessageId(attemptId) {
406
474
  return `<${attemptId}@email.invalid>`;
407
475
  }
476
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
477
+ const seen = /* @__PURE__ */ new Set();
478
+ let previous = -1;
479
+ return readArray(input, limit, code, (value) => {
480
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
481
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
482
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
483
+ const index = integer(rawIndex, 0, limit - 1, code);
484
+ if (ordered) {
485
+ const position = recipientGroups.indexOf(group) * limit + index;
486
+ if (position <= previous) invalid(code);
487
+ previous = position;
488
+ } else {
489
+ const key = `${group}:${index}`;
490
+ if (seen.has(key)) invalid(code);
491
+ seen.add(key);
492
+ }
493
+ return Object.freeze({ group, index, status });
494
+ });
495
+ }
408
496
  function readHint(input, reason, code) {
409
497
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
410
498
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -418,7 +506,7 @@ function readHint(input, reason, code) {
418
506
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
419
507
  });
420
508
  }
421
- function readAttemptResult(input, code = "invalid_command", projected = false) {
509
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
422
510
  const raw = readRecord(
423
511
  input,
424
512
  ["outcome", "retry", "stage", "reason"],
@@ -429,6 +517,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
429
517
  const [outcome, retry, stages, origin] = evidence[reason];
430
518
  const stage = stages.find((value) => value === raw.stage);
431
519
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
520
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
432
521
  const hasHint = Object.hasOwn(raw, "retryHint");
433
522
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
434
523
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -437,16 +526,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
437
526
  let recipients;
438
527
  if (hasRecipients) {
439
528
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
440
- const seen = /* @__PURE__ */ new Set();
441
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
442
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
443
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
444
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
445
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
446
- const key = `${group}:${index}`;
447
- if (seen.has(key)) invalid(code);
448
- seen.add(key);
449
- return Object.freeze({ group, index, status });
529
+ recipients = readRecipientResults(raw.recipients, code, {
530
+ limit: recipientLimit(capacity),
531
+ allowAccepted: smtpSuccess,
532
+ ordered: Boolean(capacity)
450
533
  });
451
534
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
452
535
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -460,7 +543,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
460
543
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
461
544
  invalid(code);
462
545
  }
463
- return Object.freeze({
546
+ const result = Object.freeze({
464
547
  outcome,
465
548
  retry,
466
549
  stage,
@@ -470,6 +553,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
470
553
  ...typeof messageId === "string" ? { messageId } : {},
471
554
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
472
555
  });
556
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
557
+ return result;
473
558
  }
474
559
  function assertEvidenceContext(result, provider, attemptId, counts, code) {
475
560
  const { reason, stage, recipients, messageId } = result;
@@ -486,9 +571,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
486
571
  }
487
572
  }
488
573
  }
489
- function readProviderResult(input, provider, attemptId, envelope) {
574
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
490
575
  const code = "invalid_command";
491
- const result = readAttemptResult(input, code);
576
+ const result = readAttemptResult(input, code, false, capacity);
492
577
  const origin = evidence[result.reason][3];
493
578
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
494
579
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -638,7 +723,8 @@ function validateMailbox(input, code = SNAPSHOT) {
638
723
  ...Object.hasOwn(mailbox2, "name") ? { name: headerString(mailbox2.name, L.displayNameBytes, code) } : {}
639
724
  });
640
725
  }
641
- function validateEnvelope(input, kind, code = SNAPSHOT) {
726
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
727
+ const limit = recipientLimit(capacity);
642
728
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
643
729
  const seen = /* @__PURE__ */ new Set();
644
730
  const recipient = (raw) => {
@@ -649,9 +735,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
649
735
  return mailbox2;
650
736
  };
651
737
  const from = validateMailbox(envelope.from, code);
652
- const to = readArray(envelope.to, L.recipients, code, recipient);
653
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
654
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
738
+ const to = readArray(envelope.to, limit, code, recipient);
739
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
740
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
655
741
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
656
742
  return Object.freeze({
657
743
  from,
@@ -739,12 +825,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
739
825
  }
740
826
  return expiresAt;
741
827
  }
742
- function hashSnapshot(snapshot) {
828
+ function hashSnapshot(snapshot, capacity) {
743
829
  return sha256(
744
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
830
+ canonicalJson(
831
+ snapshot,
832
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
833
+ SNAPSHOT,
834
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
835
+ ).encoded
745
836
  );
746
837
  }
747
- function readSnapshot(input) {
838
+ function readSnapshot(input, capacity) {
748
839
  const dto = readRecord(
749
840
  input,
750
841
  [
@@ -759,17 +850,19 @@ function readSnapshot(input) {
759
850
  "attachments",
760
851
  "correlation"
761
852
  ],
762
- ["subject", "html", "text", "templateId", "data"],
853
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
763
854
  SNAPSHOT
764
855
  );
765
856
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
857
+ assertCapacityTag(dto, capacity, SNAPSHOT);
766
858
  const provider = validateProviderRef(dto.provider);
767
859
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
860
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
768
861
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
769
862
  const common = {
770
863
  version: EMAIL_FORMAT_VERSION,
771
864
  template: validateTemplateIdentity(dto.template),
772
- envelope: validateEnvelope(dto.envelope, provider.kind),
865
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
773
866
  preparedAt,
774
867
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
775
868
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -783,7 +876,7 @@ function readSnapshot(input) {
783
876
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
784
877
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
785
878
  });
786
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
879
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
787
880
  }
788
881
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
789
882
  return Object.freeze({
@@ -794,31 +887,28 @@ function readSnapshot(input) {
794
887
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
795
888
  });
796
889
  }
797
- function validateSnapshot(input) {
798
- const snapshot = readSnapshot(input);
799
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
890
+ function validateSnapshot(input, capacity) {
891
+ const snapshot = readSnapshot(input, capacity);
892
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
800
893
  }
801
894
 
802
895
  // src/internal/store-codecs.ts
803
896
  var REQUEST = "invalid_command";
804
897
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
805
898
  function readStoreId(value, code = REQUEST) {
806
- if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
807
- invalid(code);
808
- }
809
- return value;
899
+ return uuidV4(value, code);
810
900
  }
811
901
 
812
902
  // src/internal/provider-preparation.ts
813
903
  function sameRef(a, b) {
814
904
  return a.resolverKey === b.resolverKey && a.id === b.id && a.version === b.version && a.filename === b.filename && a.contentType === b.contentType && a.byteLength === b.byteLength && a.sha256 === b.sha256;
815
905
  }
816
- function readProviderSubmission(input, ref) {
906
+ function readProviderSubmission(input, ref, capacity) {
817
907
  const code = "invalid_snapshot";
818
908
  const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
819
909
  const jobId = readStoreId(raw.jobId, code);
820
910
  const attemptId = readStoreId(raw.attemptId, code);
821
- const { snapshot } = validateSnapshot(raw.snapshot);
911
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
822
912
  if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
823
913
  invalid("provider_mismatch");
824
914
  }
@@ -898,11 +988,9 @@ function retryHint(after, reset, now) {
898
988
  const delayMs = after !== void 0 && SECONDS.test(after) ? secondsMs(after) : void 0;
899
989
  const date = after !== void 0 && delayMs === void 0 ? httpDate(after, now) : void 0;
900
990
  const resetMs = reset !== void 0 && SECONDS.test(reset) ? secondsMs(reset) : void 0;
901
- if (delayMs === void 0 && date === void 0 && resetMs === void 0) return;
902
- return {
903
- ...delayMs === void 0 ? {} : { delayMs },
904
- ...date === void 0 && resetMs === void 0 ? {} : { notBefore: Math.max(date ?? 0, resetMs ?? 0) }
905
- };
991
+ const notBefore = date === void 0 && resetMs === void 0 ? void 0 : Math.max(date ?? 0, resetMs ?? 0);
992
+ if (delayMs !== void 0) return notBefore === void 0 ? { delayMs } : { delayMs, notBefore };
993
+ if (notBefore !== void 0) return { notBefore };
906
994
  }
907
995
 
908
996
  // src/providers/sendgrid/response.ts