@web-ts-toolkit/email-service 0.72.0 → 0.73.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/smtp.mjs CHANGED
@@ -236,6 +236,12 @@ function opaqueToken(value, maxBytes, code) {
236
236
  function identifier(value, code) {
237
237
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
238
238
  }
239
+ function uuidV4(value, code) {
240
+ 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)) {
241
+ invalid(code);
242
+ }
243
+ return value;
244
+ }
239
245
  function hashToken(value, code) {
240
246
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
241
247
  return value;
@@ -249,9 +255,9 @@ function jsonKey(key, code) {
249
255
 
250
256
  // src/internal/canonical-json.ts
251
257
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
252
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
258
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
253
259
  let bytesLeft = maxBytes;
254
- let valuesLeft = limits.values;
260
+ let valuesLeft = limits2.values;
255
261
  const chunks = [];
256
262
  const ancestors = /* @__PURE__ */ new Set();
257
263
  function append(text, bytes = text.length) {
@@ -270,7 +276,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
270
276
  append(JSON.stringify(text), bytes);
271
277
  }
272
278
  function visit(value2, depth) {
273
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
279
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
274
280
  switch (typeof value2) {
275
281
  case "string":
276
282
  appendString(value2);
@@ -294,7 +300,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
294
300
  if (ancestors.has(value2)) invalid(code);
295
301
  ancestors.add(value2);
296
302
  try {
297
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
303
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
298
304
  if (isArray(value2, code)) {
299
305
  const length = denseArrayLength(value2, maxChildren, code);
300
306
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -334,6 +340,71 @@ function copyJsonObject(input, maxBytes, code) {
334
340
  function sha256(input) {
335
341
  return createHash("sha256").update(input).digest("hex");
336
342
  }
343
+ function encodeEvidence(input, code, capacity) {
344
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
345
+ }
346
+
347
+ // src/internal/smtp-capacity.ts
348
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
349
+ var MAX_RECIPIENTS = 1e3;
350
+ var KIB = 1024;
351
+ var limits = Object.freeze({
352
+ snapshotBytes: 2 * KIB * KIB,
353
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
354
+ evidenceBytes: 64 * KIB,
355
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
356
+ jobBsonBytes: 4 * KIB * KIB,
357
+ activityBsonBytes: 128 * KIB,
358
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
359
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
360
+ servicePending: 4,
361
+ workerProfiles: 16,
362
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
363
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
364
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
365
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
366
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
367
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
368
+ mongoInFlight: 4,
369
+ dueCandidates: 4
370
+ });
371
+ function readBinding(input, code) {
372
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
373
+ if (format !== "smtp-v2") invalid(code);
374
+ return Object.freeze({
375
+ format,
376
+ namespace: uuidV4(namespace, code),
377
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
378
+ });
379
+ }
380
+ function readCapacityOption(raw) {
381
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
382
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
383
+ }
384
+ function capacityTag(capacity) {
385
+ return capacity ? { smtpCapacity: capacity.binding } : {};
386
+ }
387
+ function recipientLimit(capacity) {
388
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
389
+ }
390
+ function matchesBinding(input, capacity, code) {
391
+ const binding = readBinding(input, code);
392
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
393
+ invalid(code);
394
+ }
395
+ }
396
+ function assertCapacityTag(raw, capacity, code) {
397
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
398
+ if (capacity) {
399
+ if (!tagged) invalid(code);
400
+ matchesBinding(raw.smtpCapacity, capacity, code);
401
+ } else if (tagged) {
402
+ invalid(code);
403
+ }
404
+ }
405
+ function assertCapacityProvider(provider, capacity, code) {
406
+ if (capacity && provider.kind !== "smtp") invalid(code);
407
+ }
337
408
 
338
409
  // src/internal/attempt-codecs.ts
339
410
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -393,7 +464,7 @@ function readHint(input, reason, code) {
393
464
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
394
465
  });
395
466
  }
396
- function readAttemptResult(input, code = "invalid_command", projected = false) {
467
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
397
468
  const raw = readRecord(
398
469
  input,
399
470
  ["outcome", "retry", "stage", "reason"],
@@ -404,6 +475,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
404
475
  const [outcome, retry, stages, origin] = evidence[reason];
405
476
  const stage = stages.find((value) => value === raw.stage);
406
477
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
478
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
407
479
  const hasHint = Object.hasOwn(raw, "retryHint");
408
480
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
409
481
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -413,14 +485,22 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
413
485
  if (hasRecipients) {
414
486
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
415
487
  const seen = /* @__PURE__ */ new Set();
416
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
488
+ const limit = recipientLimit(capacity);
489
+ let previous = -1;
490
+ recipients = readArray(raw.recipients, limit, code, (value) => {
417
491
  const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
418
492
  if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
419
493
  if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
420
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
421
- const key = `${group}:${index}`;
422
- if (seen.has(key)) invalid(code);
423
- seen.add(key);
494
+ const index = integer(rawIndex, 0, limit - 1, code);
495
+ if (capacity) {
496
+ const position = recipientGroups.indexOf(group) * limit + index;
497
+ if (position <= previous) invalid(code);
498
+ previous = position;
499
+ } else {
500
+ const key = `${group}:${index}`;
501
+ if (seen.has(key)) invalid(code);
502
+ seen.add(key);
503
+ }
424
504
  return Object.freeze({ group, index, status });
425
505
  });
426
506
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
@@ -435,7 +515,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
435
515
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
436
516
  invalid(code);
437
517
  }
438
- return Object.freeze({
518
+ const result = Object.freeze({
439
519
  outcome,
440
520
  retry,
441
521
  stage,
@@ -445,6 +525,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
445
525
  ...typeof messageId === "string" ? { messageId } : {},
446
526
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
447
527
  });
528
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
529
+ return result;
448
530
  }
449
531
  function assertEvidenceContext(result, provider, attemptId, counts, code) {
450
532
  const { reason, stage, recipients, messageId } = result;
@@ -461,9 +543,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
461
543
  }
462
544
  }
463
545
  }
464
- function readProviderResult(input, provider, attemptId, envelope) {
546
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
465
547
  const code = "invalid_command";
466
- const result = readAttemptResult(input, code);
548
+ const result = readAttemptResult(input, code, false, capacity);
467
549
  const origin = evidence[result.reason][3];
468
550
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
469
551
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -613,7 +695,8 @@ function validateMailbox(input, code = SNAPSHOT) {
613
695
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
614
696
  });
615
697
  }
616
- function validateEnvelope(input, kind, code = SNAPSHOT) {
698
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
699
+ const limit = recipientLimit(capacity);
617
700
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
618
701
  const seen = /* @__PURE__ */ new Set();
619
702
  const recipient = (raw) => {
@@ -624,9 +707,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
624
707
  return mailbox;
625
708
  };
626
709
  const from = validateMailbox(envelope.from, code);
627
- const to = readArray(envelope.to, L.recipients, code, recipient);
628
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
629
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
710
+ const to = readArray(envelope.to, limit, code, recipient);
711
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
712
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
630
713
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
631
714
  return Object.freeze({
632
715
  from,
@@ -714,12 +797,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
714
797
  }
715
798
  return expiresAt;
716
799
  }
717
- function hashSnapshot(snapshot) {
800
+ function hashSnapshot(snapshot, capacity) {
718
801
  return sha256(
719
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
802
+ canonicalJson(
803
+ snapshot,
804
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
805
+ SNAPSHOT,
806
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
807
+ ).encoded
720
808
  );
721
809
  }
722
- function readSnapshot(input) {
810
+ function readSnapshot(input, capacity) {
723
811
  const dto = readRecord(
724
812
  input,
725
813
  [
@@ -734,17 +822,19 @@ function readSnapshot(input) {
734
822
  "attachments",
735
823
  "correlation"
736
824
  ],
737
- ["subject", "html", "text", "templateId", "data"],
825
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
738
826
  SNAPSHOT
739
827
  );
740
828
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
829
+ assertCapacityTag(dto, capacity, SNAPSHOT);
741
830
  const provider = validateProviderRef(dto.provider);
742
831
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
832
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
743
833
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
744
834
  const common = {
745
835
  version: EMAIL_FORMAT_VERSION,
746
836
  template: validateTemplateIdentity(dto.template),
747
- envelope: validateEnvelope(dto.envelope, provider.kind),
837
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
748
838
  preparedAt,
749
839
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
750
840
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -758,7 +848,7 @@ function readSnapshot(input) {
758
848
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
759
849
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
760
850
  });
761
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
851
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
762
852
  }
763
853
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
764
854
  return Object.freeze({
@@ -769,31 +859,28 @@ function readSnapshot(input) {
769
859
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
770
860
  });
771
861
  }
772
- function validateSnapshot(input) {
773
- const snapshot = readSnapshot(input);
774
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
862
+ function validateSnapshot(input, capacity) {
863
+ const snapshot = readSnapshot(input, capacity);
864
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
775
865
  }
776
866
 
777
867
  // src/internal/store-codecs.ts
778
868
  var REQUEST = "invalid_command";
779
869
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
780
870
  function readStoreId(value, code = REQUEST) {
781
- 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)) {
782
- invalid(code);
783
- }
784
- return value;
871
+ return uuidV4(value, code);
785
872
  }
786
873
 
787
874
  // src/internal/provider-preparation.ts
788
875
  function sameRef(a, b) {
789
876
  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;
790
877
  }
791
- function readProviderSubmission(input, ref) {
878
+ function readProviderSubmission(input, ref, capacity) {
792
879
  const code = "invalid_snapshot";
793
880
  const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
794
881
  const jobId = readStoreId(raw.jobId, code);
795
882
  const attemptId = readStoreId(raw.attemptId, code);
796
- const { snapshot } = validateSnapshot(raw.snapshot);
883
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
797
884
  if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
798
885
  invalid("provider_mismatch");
799
886
  }
@@ -921,7 +1008,8 @@ function readAuth(input) {
921
1008
  return Object.freeze({ user, pass });
922
1009
  }
923
1010
  function readSmtpConfig(input) {
924
- const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth"], CONFIG);
1011
+ const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth", "smtpCapacity"], CONFIG);
1012
+ const capacity = readCapacityOption(raw);
925
1013
  const ref = Object.freeze({ kind: "smtp", key: identifier(raw.key, CONFIG), mode: "live" });
926
1014
  const { tls } = raw;
927
1015
  if (tls !== "implicit" && tls !== "starttls") invalid(CONFIG);
@@ -936,7 +1024,17 @@ function readSmtpConfig(input) {
936
1024
  if (ca?.length === 0) invalid(CONFIG);
937
1025
  try {
938
1026
  const secureContext = createSecureContext({ minVersion: SMTP_MIN_TLS_VERSION, ...ca ? { ca: [...ca] } : {} });
939
- return Object.freeze({ ref, host, port, tls, identity: servername ?? host, servername, secureContext, auth });
1027
+ return Object.freeze({
1028
+ ref,
1029
+ host,
1030
+ port,
1031
+ tls,
1032
+ identity: servername ?? host,
1033
+ servername,
1034
+ secureContext,
1035
+ auth,
1036
+ capacity
1037
+ });
940
1038
  } catch {
941
1039
  return invalid(CONFIG);
942
1040
  }
@@ -1374,11 +1472,12 @@ async function submitSmtp(config, message, call, resolverFactory) {
1374
1472
  // src/smtp.ts
1375
1473
  function createSmtpProvider(options) {
1376
1474
  const config = readSmtpConfig(options);
1377
- const { ref } = config;
1475
+ const { ref, capacity } = config;
1378
1476
  const provider = {
1379
1477
  ref,
1478
+ ...capacityTag(capacity),
1380
1479
  prepare(input) {
1381
- const prepared = readProviderSubmission(input, ref);
1480
+ const prepared = readProviderSubmission(input, ref, capacity);
1382
1481
  const {
1383
1482
  attemptId,
1384
1483
  snapshot: { envelope }
@@ -1392,13 +1491,14 @@ function createSmtpProvider(options) {
1392
1491
  message = void 0;
1393
1492
  const result = await submitSmtp(config, send, call);
1394
1493
  try {
1395
- return readProviderResult(result, ref, attemptId, envelope);
1494
+ return readProviderResult(result, ref, attemptId, envelope, capacity);
1396
1495
  } catch {
1397
1496
  return readProviderResult(
1398
1497
  { outcome: "unknown", retry: "never", stage: result.stage, reason: "transport_uncertain" },
1399
1498
  ref,
1400
1499
  attemptId,
1401
- envelope
1500
+ envelope,
1501
+ capacity
1402
1502
  );
1403
1503
  }
1404
1504
  }
@@ -1,4 +1,4 @@
1
- import { U as UnixMs, j as AttemptReason, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, z as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-HisBc6hk.mjs';
1
+ import { U as UnixMs, j as AttemptReason, S as SmtpCapacity, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, B as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, R as RecipientResult, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-DC_av0SQ.js';
2
2
 
3
3
  /** Ordinary attempt budget and capped exponential backoff, frozen at admission. */
4
4
  type RetryPolicy = {
@@ -34,6 +34,7 @@ type EmailJobState = {
34
34
  /** Authoritative redacted job state, available without waiting for activity projection. */
35
35
  type EmailJobSummary = EmailJobState & {
36
36
  readonly version: 1;
37
+ readonly smtpCapacity?: SmtpCapacity;
37
38
  readonly scope: EmailScope;
38
39
  readonly jobId: EmailJobId;
39
40
  readonly key: EmailAdmissionKey;
@@ -144,6 +145,7 @@ type EmailShutdownReport = {
144
145
  };
145
146
  interface EmailWorker {
146
147
  readonly scope: EmailScope;
148
+ readonly smtpCapacity?: SmtpCapacity;
147
149
  /** Do bounded work in this scope. The host schedules runs; only one run per instance may be active. */
148
150
  run(options?: EmailRunOptions): Promise<EmailRunReport>;
149
151
  /** Stop permanently. `stopped` means no active run or provider I/O, not remote recall. */
@@ -152,6 +154,8 @@ interface EmailWorker {
152
154
  /** Dependencies for a bounded worker; provider profile keys must be unique. */
153
155
  type EmailWorkerOptions = {
154
156
  scope: EmailScope;
157
+ /** Must match the store and every profile. Only live SMTP profiles are allowed with this option. */
158
+ smtpCapacity?: SmtpCapacity;
155
159
  store: EmailStore;
156
160
  providers: readonly ConfiguredEmailProvider[];
157
161
  attachmentResolvers?: Readonly<Record<string, AttachmentResolver>>;
@@ -163,6 +167,9 @@ type EmailWorkerOptions = {
163
167
  /** Redacted projection of a finalized attempt; never a queue payload or a delivery receipt. */
164
168
  type EmailActivity = {
165
169
  readonly version: 1;
170
+ readonly smtpCapacity?: SmtpCapacity;
171
+ /** Present in opted-in history; counts refer to the original To, Cc and Bcc groups, never addresses. */
172
+ readonly recipientCounts?: Readonly<Record<RecipientResult['group'], number>>;
166
173
  readonly scope: EmailScope;
167
174
  readonly jobId: EmailJobId;
168
175
  readonly attemptId: EmailAttemptId;
@@ -188,7 +195,7 @@ type EmailActivityPage = {
188
195
  readonly items: readonly EmailActivity[];
189
196
  readonly nextCursor?: string;
190
197
  };
191
- /** One sequential sweep; limit defaults to 20 and accepts 1–100. */
198
+ /** One sequential sweep; V1 defaults to 20 (1–100); SMTP opt-in defaults to 4 (1–16). */
192
199
  type MaintenanceOptions = CallOptions & {
193
200
  limit?: number;
194
201
  };
@@ -217,7 +224,7 @@ interface EmailAdmin {
217
224
  cancel(jobId: EmailJobId, options?: CallOptions): Promise<CancelResult>;
218
225
  /** Dismiss or requeue an exact unknown attempt. Redrive can duplicate a previously accepted submission. */
219
226
  resolveUnknown(command: ResolveUnknownCommand, options?: CallOptions): Promise<ResolveUnknownResult>;
220
- /** Read a bounded page of committed activities (default 25, max 100), even if the source ACK is pending. */
227
+ /** Read committed activities even before source ACK. V1 default/max: 25/100; SMTP opt-in: 8/16. */
221
228
  listActivities(query?: EmailActivityQuery, options?: CallOptions): Promise<EmailActivityPage>;
222
229
  /** Project from the authoritative ledger; no send can result from this operation. */
223
230
  reconcile(options?: MaintenanceOptions): Promise<ReconcileReport>;
@@ -226,6 +233,8 @@ interface EmailAdmin {
226
233
  }
227
234
  type EmailAdminOptions = {
228
235
  scope: EmailScope;
236
+ /** Must match the store. Opted-in history stays redacted and cursors remain bound to this tuple. */
237
+ smtpCapacity?: SmtpCapacity;
229
238
  store: EmailStore;
230
239
  /** Best effort after a new confirmed projection ACK. One unresolved callback per admin; no wait or retry. */
231
240
  onActivity?: (activity: EmailActivity) => Awaitable<void>;
@@ -234,6 +243,8 @@ type EmailAdminOptions = {
234
243
  type StoreCall = {
235
244
  signal: AbortSignal;
236
245
  timeoutMs: number;
246
+ /** An opted-in store must check this exact binding before every primitive. V1 calls omit it. */
247
+ readonly smtpCapacity?: SmtpCapacity;
237
248
  };
238
249
  type StoreNext<T> = {
239
250
  readonly status: 'applied';
@@ -294,6 +305,7 @@ type CleanupStep = 'payload_pruned' | 'retirement_started' | 'purged';
294
305
  * time for durable guards. Do not report an unconfirmed write as a definite miss or fall back to memory.
295
306
  */
296
307
  interface EmailStore {
308
+ readonly smtpCapacity?: SmtpCapacity;
297
309
  ready(options?: CallOptions): Promise<void>;
298
310
  findAdmission(scope: EmailScope, key: EmailAdmissionKey, call: StoreCall): Promise<{
299
311
  readonly job: EmailJobSummary;
@@ -337,9 +349,11 @@ interface EmailStore {
337
349
  }
338
350
  /** Settings for a single-process, non-durable development/test store. */
339
351
  type MemoryEmailStoreOptions = {
352
+ /** Opt into the SMTP queue format. Assign a different namespace to each independent backing. */
353
+ smtpCapacity?: SmtpCapacity;
340
354
  /** Store wall time governs transitions; elapsed time enforces call budgets. Defaults to system time. */
341
355
  clock?: EmailClock;
342
- /** Capacity across all scopes in this instance; default 256, range 1–4096. */
356
+ /** Across all scopes: default 256, range 1–4,096 (SMTP opt-in: default 8, range 1–16). */
343
357
  maxJobs?: number;
344
358
  };
345
359
 
@@ -1,4 +1,4 @@
1
- import { U as UnixMs, j as AttemptReason, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, z as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-HisBc6hk.js';
1
+ import { U as UnixMs, j as AttemptReason, S as SmtpCapacity, a as EmailScope, n as EmailJobId, b as EmailAdmissionKey, P as ProviderRef, T as TemplateIdentity, C as Correlation, m as EmailAttemptId, B as SubmissionOutcome, e as CallOptions, A as Awaitable, l as ConfiguredEmailProvider, i as AttachmentResolver, g as EmailClock, R as RecipientResult, k as AttemptResult, p as EmailSnapshot, f as PreparedEmailCommand } from './provider-DC_av0SQ.mjs';
2
2
 
3
3
  /** Ordinary attempt budget and capped exponential backoff, frozen at admission. */
4
4
  type RetryPolicy = {
@@ -34,6 +34,7 @@ type EmailJobState = {
34
34
  /** Authoritative redacted job state, available without waiting for activity projection. */
35
35
  type EmailJobSummary = EmailJobState & {
36
36
  readonly version: 1;
37
+ readonly smtpCapacity?: SmtpCapacity;
37
38
  readonly scope: EmailScope;
38
39
  readonly jobId: EmailJobId;
39
40
  readonly key: EmailAdmissionKey;
@@ -144,6 +145,7 @@ type EmailShutdownReport = {
144
145
  };
145
146
  interface EmailWorker {
146
147
  readonly scope: EmailScope;
148
+ readonly smtpCapacity?: SmtpCapacity;
147
149
  /** Do bounded work in this scope. The host schedules runs; only one run per instance may be active. */
148
150
  run(options?: EmailRunOptions): Promise<EmailRunReport>;
149
151
  /** Stop permanently. `stopped` means no active run or provider I/O, not remote recall. */
@@ -152,6 +154,8 @@ interface EmailWorker {
152
154
  /** Dependencies for a bounded worker; provider profile keys must be unique. */
153
155
  type EmailWorkerOptions = {
154
156
  scope: EmailScope;
157
+ /** Must match the store and every profile. Only live SMTP profiles are allowed with this option. */
158
+ smtpCapacity?: SmtpCapacity;
155
159
  store: EmailStore;
156
160
  providers: readonly ConfiguredEmailProvider[];
157
161
  attachmentResolvers?: Readonly<Record<string, AttachmentResolver>>;
@@ -163,6 +167,9 @@ type EmailWorkerOptions = {
163
167
  /** Redacted projection of a finalized attempt; never a queue payload or a delivery receipt. */
164
168
  type EmailActivity = {
165
169
  readonly version: 1;
170
+ readonly smtpCapacity?: SmtpCapacity;
171
+ /** Present in opted-in history; counts refer to the original To, Cc and Bcc groups, never addresses. */
172
+ readonly recipientCounts?: Readonly<Record<RecipientResult['group'], number>>;
166
173
  readonly scope: EmailScope;
167
174
  readonly jobId: EmailJobId;
168
175
  readonly attemptId: EmailAttemptId;
@@ -188,7 +195,7 @@ type EmailActivityPage = {
188
195
  readonly items: readonly EmailActivity[];
189
196
  readonly nextCursor?: string;
190
197
  };
191
- /** One sequential sweep; limit defaults to 20 and accepts 1–100. */
198
+ /** One sequential sweep; V1 defaults to 20 (1–100); SMTP opt-in defaults to 4 (1–16). */
192
199
  type MaintenanceOptions = CallOptions & {
193
200
  limit?: number;
194
201
  };
@@ -217,7 +224,7 @@ interface EmailAdmin {
217
224
  cancel(jobId: EmailJobId, options?: CallOptions): Promise<CancelResult>;
218
225
  /** Dismiss or requeue an exact unknown attempt. Redrive can duplicate a previously accepted submission. */
219
226
  resolveUnknown(command: ResolveUnknownCommand, options?: CallOptions): Promise<ResolveUnknownResult>;
220
- /** Read a bounded page of committed activities (default 25, max 100), even if the source ACK is pending. */
227
+ /** Read committed activities even before source ACK. V1 default/max: 25/100; SMTP opt-in: 8/16. */
221
228
  listActivities(query?: EmailActivityQuery, options?: CallOptions): Promise<EmailActivityPage>;
222
229
  /** Project from the authoritative ledger; no send can result from this operation. */
223
230
  reconcile(options?: MaintenanceOptions): Promise<ReconcileReport>;
@@ -226,6 +233,8 @@ interface EmailAdmin {
226
233
  }
227
234
  type EmailAdminOptions = {
228
235
  scope: EmailScope;
236
+ /** Must match the store. Opted-in history stays redacted and cursors remain bound to this tuple. */
237
+ smtpCapacity?: SmtpCapacity;
229
238
  store: EmailStore;
230
239
  /** Best effort after a new confirmed projection ACK. One unresolved callback per admin; no wait or retry. */
231
240
  onActivity?: (activity: EmailActivity) => Awaitable<void>;
@@ -234,6 +243,8 @@ type EmailAdminOptions = {
234
243
  type StoreCall = {
235
244
  signal: AbortSignal;
236
245
  timeoutMs: number;
246
+ /** An opted-in store must check this exact binding before every primitive. V1 calls omit it. */
247
+ readonly smtpCapacity?: SmtpCapacity;
237
248
  };
238
249
  type StoreNext<T> = {
239
250
  readonly status: 'applied';
@@ -294,6 +305,7 @@ type CleanupStep = 'payload_pruned' | 'retirement_started' | 'purged';
294
305
  * time for durable guards. Do not report an unconfirmed write as a definite miss or fall back to memory.
295
306
  */
296
307
  interface EmailStore {
308
+ readonly smtpCapacity?: SmtpCapacity;
297
309
  ready(options?: CallOptions): Promise<void>;
298
310
  findAdmission(scope: EmailScope, key: EmailAdmissionKey, call: StoreCall): Promise<{
299
311
  readonly job: EmailJobSummary;
@@ -337,9 +349,11 @@ interface EmailStore {
337
349
  }
338
350
  /** Settings for a single-process, non-durable development/test store. */
339
351
  type MemoryEmailStoreOptions = {
352
+ /** Opt into the SMTP queue format. Assign a different namespace to each independent backing. */
353
+ smtpCapacity?: SmtpCapacity;
340
354
  /** Store wall time governs transitions; elapsed time enforces call budgets. Defaults to system time. */
341
355
  clock?: EmailClock;
342
- /** Capacity across all scopes in this instance; default 256, range 1–4096. */
356
+ /** Across all scopes: default 256, range 1–4,096 (SMTP opt-in: default 8, range 1–16). */
343
357
  maxJobs?: number;
344
358
  };
345
359