@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/mongoose.mjs CHANGED
@@ -251,6 +251,12 @@ function scopeToken(value, code = "invalid_command") {
251
251
  function identifier(value, code) {
252
252
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
253
253
  }
254
+ function uuidV4(value, code) {
255
+ 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)) {
256
+ invalid(code);
257
+ }
258
+ return value;
259
+ }
254
260
  function hashToken(value, code) {
255
261
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
256
262
  return value;
@@ -264,9 +270,9 @@ function jsonKey(key, code) {
264
270
 
265
271
  // src/internal/canonical-json.ts
266
272
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
267
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
273
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
268
274
  let bytesLeft = maxBytes;
269
- let valuesLeft = limits.values;
275
+ let valuesLeft = limits2.values;
270
276
  const chunks = [];
271
277
  const ancestors = /* @__PURE__ */ new Set();
272
278
  function append(text, bytes = text.length) {
@@ -285,7 +291,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
285
291
  append(JSON.stringify(text), bytes);
286
292
  }
287
293
  function visit(value2, depth) {
288
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
294
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
289
295
  switch (typeof value2) {
290
296
  case "string":
291
297
  appendString(value2);
@@ -309,7 +315,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
309
315
  if (ancestors.has(value2)) invalid(code);
310
316
  ancestors.add(value2);
311
317
  try {
312
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
318
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
313
319
  if (isArray(value2, code)) {
314
320
  const length = denseArrayLength(value2, maxChildren, code);
315
321
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -352,6 +358,71 @@ function sha256(input) {
352
358
  function hashJson(input, maxBytes, code = "invalid_snapshot") {
353
359
  return sha256(canonicalJson(input, maxBytes, code).encoded);
354
360
  }
361
+ function encodeEvidence(input, code, capacity) {
362
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
363
+ }
364
+
365
+ // src/internal/smtp-capacity.ts
366
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
367
+ var MAX_SMTP_RECIPIENTS = 1e3;
368
+ var KIB = 1024;
369
+ var limits = Object.freeze({
370
+ snapshotBytes: 2 * KIB * KIB,
371
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
372
+ evidenceBytes: 64 * KIB,
373
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
374
+ jobBsonBytes: 4 * KIB * KIB,
375
+ activityBsonBytes: 128 * KIB,
376
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
377
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
378
+ servicePending: 4,
379
+ workerProfiles: 16,
380
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
381
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
382
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
383
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
384
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
385
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
386
+ mongoInFlight: 4,
387
+ dueCandidates: 4
388
+ });
389
+ function readBinding(input, code) {
390
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
391
+ if (format !== "smtp-v2") invalid(code);
392
+ return Object.freeze({
393
+ format,
394
+ namespace: uuidV4(namespace, code),
395
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
396
+ });
397
+ }
398
+ function readCapacityOption(raw) {
399
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
400
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
401
+ }
402
+ function capacityTag(capacity) {
403
+ return capacity ? { smtpCapacity: capacity.binding } : {};
404
+ }
405
+ function recipientLimit(capacity) {
406
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
407
+ }
408
+ function matchesBinding(input, capacity, code) {
409
+ const binding = readBinding(input, code);
410
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
411
+ invalid(code);
412
+ }
413
+ }
414
+ function assertCapacityTag(raw, capacity, code) {
415
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
416
+ if (capacity) {
417
+ if (!tagged) invalid(code);
418
+ matchesBinding(raw.smtpCapacity, capacity, code);
419
+ } else if (tagged) {
420
+ invalid(code);
421
+ }
422
+ }
423
+ function assertCapacityProvider(provider2, capacity, code) {
424
+ if (capacity && provider2.kind !== "smtp") invalid(code);
425
+ }
355
426
 
356
427
  // src/internal/attempt-codecs.ts
357
428
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -391,12 +462,42 @@ function readAttemptReason(value, code) {
391
462
  if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
392
463
  return value;
393
464
  }
465
+ var recipientGroups = ["to", "cc", "bcc"];
394
466
  function recipientCounts(envelope) {
395
467
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
396
468
  }
469
+ function readRecipientCounts(input, code, capacity) {
470
+ const limit = recipientLimit(capacity);
471
+ const counts = readRecord(input, recipientGroups, [], code);
472
+ const to = integer(counts.to, 0, limit, code);
473
+ const cc = integer(counts.cc, 0, limit - to, code);
474
+ const bcc = integer(counts.bcc, 0, limit - to - cc, code);
475
+ if (to + cc + bcc === 0) invalid(code);
476
+ return Object.freeze({ to, cc, bcc });
477
+ }
397
478
  function smtpMessageId(attemptId) {
398
479
  return `<${attemptId}@email.invalid>`;
399
480
  }
481
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
482
+ const seen = /* @__PURE__ */ new Set();
483
+ let previous = -1;
484
+ return readArray(input, limit, code, (value) => {
485
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
486
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
487
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
488
+ const index = integer(rawIndex, 0, limit - 1, code);
489
+ if (ordered) {
490
+ const position = recipientGroups.indexOf(group) * limit + index;
491
+ if (position <= previous) invalid(code);
492
+ previous = position;
493
+ } else {
494
+ const key = `${group}:${index}`;
495
+ if (seen.has(key)) invalid(code);
496
+ seen.add(key);
497
+ }
498
+ return Object.freeze({ group, index, status });
499
+ });
500
+ }
400
501
  function readHint(input, reason, code) {
401
502
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
402
503
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -410,7 +511,7 @@ function readHint(input, reason, code) {
410
511
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
411
512
  });
412
513
  }
413
- function readAttemptResult(input, code = "invalid_command", projected = false) {
514
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
414
515
  const raw = readRecord(
415
516
  input,
416
517
  ["outcome", "retry", "stage", "reason"],
@@ -421,6 +522,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
421
522
  const [outcome, retry, stages, origin] = evidence[reason];
422
523
  const stage = stages.find((value) => value === raw.stage);
423
524
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
525
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
424
526
  const hasHint = Object.hasOwn(raw, "retryHint");
425
527
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
426
528
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -429,16 +531,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
429
531
  let recipients;
430
532
  if (hasRecipients) {
431
533
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
432
- const seen = /* @__PURE__ */ new Set();
433
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
434
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
435
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
436
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
437
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
438
- const key = `${group}:${index}`;
439
- if (seen.has(key)) invalid(code);
440
- seen.add(key);
441
- return Object.freeze({ group, index, status });
534
+ recipients = readRecipientResults(raw.recipients, code, {
535
+ limit: recipientLimit(capacity),
536
+ allowAccepted: smtpSuccess,
537
+ ordered: Boolean(capacity)
442
538
  });
443
539
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
444
540
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -452,7 +548,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
452
548
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
453
549
  invalid(code);
454
550
  }
455
- return Object.freeze({
551
+ const result = Object.freeze({
456
552
  outcome,
457
553
  retry,
458
554
  stage,
@@ -462,6 +558,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
462
558
  ...typeof messageId === "string" ? { messageId } : {},
463
559
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
464
560
  });
561
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
562
+ return result;
465
563
  }
466
564
  function assertEvidencePhase(reason, phase, source, code) {
467
565
  const origin = evidence[reason][3];
@@ -472,8 +570,8 @@ function assertEvidencePhase(reason, phase, source, code) {
472
570
  const allowed = phase === "pre_handoff" ? origin === "pre" : origin === "smtp" || origin === "sendgrid" || origin === "provider" || origin === "launch";
473
571
  if (!allowed) invalid(code);
474
572
  }
475
- function assertEvidenceContext(result2, provider2, attemptId, counts, code) {
476
- const { reason, stage, recipients, messageId } = result2;
573
+ function assertEvidenceContext(result, provider2, attemptId, counts, code) {
574
+ const { reason, stage, recipients, messageId } = result;
477
575
  const origin = evidence[reason][3];
478
576
  if (origin === "smtp" && provider2.kind !== "smtp" || origin === "sendgrid" && provider2.kind !== "sendgrid" || origin === "provider" && (provider2.kind === "smtp" ? stage === "http" : stage !== "http" && stage !== "connect" && stage !== "tls") || reason === "sendgrid_accepted" && provider2.mode !== "live" || reason === "sendgrid_validated" && provider2.mode !== "sandbox" || messageId !== void 0 && messageId !== smtpMessageId(attemptId)) {
479
577
  invalid(code);
@@ -491,19 +589,19 @@ function lifecycleEvidence(reason) {
491
589
  const [outcome, retry] = evidence[reason];
492
590
  return Object.freeze({ outcome, retry, reason, stage: "pre_handoff" });
493
591
  }
494
- function attemptEffect(result2, attemptId, ordinal2, manual, policy, expiresAt, now) {
495
- const { outcome, reason } = result2;
592
+ function attemptEffect(result, attemptId, ordinal2, manual, policy, expiresAt, now) {
593
+ const { outcome, reason } = result;
496
594
  if (outcome !== "unsubmitted" && outcome !== "rejected") return { disposition: outcome, reason };
497
595
  if (reason === "cancelled" || reason === "expired") return { disposition: reason, reason };
498
596
  const disposition = outcome === "unsubmitted" ? "failed" : "rejected";
499
- if (result2.retry === "never") return { disposition, reason };
597
+ if (result.retry === "never") return { disposition, reason };
500
598
  if (now >= expiresAt) return { disposition: "expired", reason: "expired" };
501
599
  if (manual || ordinal2 >= policy.maxAttempts) return { disposition, reason: "attempts_exhausted" };
502
600
  const cap = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (ordinal2 - 1));
503
601
  const half = Math.floor(cap / 2);
504
602
  const jitter = half + Number.parseInt(sha256(attemptId).slice(0, 8), 16) % (cap - half + 1);
505
- const delay = Math.max(jitter, result2.retryHint?.delayMs ?? 0);
506
- const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result2.retryHint?.notBefore ?? 0);
603
+ const delay = Math.max(jitter, result.retryHint?.delayMs ?? 0);
604
+ const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result.retryHint?.notBefore ?? 0);
507
605
  if (retryAt >= expiresAt) return { disposition: "expired", reason: "expired" };
508
606
  return { disposition: "retry_scheduled", reason, retryAt };
509
607
  }
@@ -547,10 +645,11 @@ function validateMailbox(input, code = SNAPSHOT) {
547
645
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
548
646
  });
549
647
  }
550
- function validateEnvelope(input, kind, code = SNAPSHOT) {
648
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
649
+ const limit = recipientLimit(capacity);
551
650
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
552
651
  const seen = /* @__PURE__ */ new Set();
553
- const recipient2 = (raw) => {
652
+ const recipient = (raw) => {
554
653
  const mailbox = validateMailbox(raw, code);
555
654
  const address = mailbox.address.toLowerCase();
556
655
  if (seen.has(address)) invalid(code);
@@ -558,9 +657,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
558
657
  return mailbox;
559
658
  };
560
659
  const from = validateMailbox(envelope.from, code);
561
- const to = readArray(envelope.to, L.recipients, code, recipient2);
562
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient2);
563
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient2);
660
+ const to = readArray(envelope.to, limit, code, recipient);
661
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
662
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
564
663
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
565
664
  return Object.freeze({
566
665
  from,
@@ -635,12 +734,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
635
734
  }
636
735
  return expiresAt;
637
736
  }
638
- function hashSnapshot(snapshot) {
737
+ function hashSnapshot(snapshot, capacity) {
639
738
  return sha256(
640
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
739
+ canonicalJson(
740
+ snapshot,
741
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
742
+ SNAPSHOT,
743
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
744
+ ).encoded
641
745
  );
642
746
  }
643
- function readSnapshot(input) {
747
+ function readSnapshot(input, capacity) {
644
748
  const dto = readRecord(
645
749
  input,
646
750
  [
@@ -655,17 +759,19 @@ function readSnapshot(input) {
655
759
  "attachments",
656
760
  "correlation"
657
761
  ],
658
- ["subject", "html", "text", "templateId", "data"],
762
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
659
763
  SNAPSHOT
660
764
  );
661
765
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
766
+ assertCapacityTag(dto, capacity, SNAPSHOT);
662
767
  const provider2 = validateProviderRef(dto.provider);
663
768
  if (provider2.kind !== dto.kind) invalid("provider_mismatch");
769
+ assertCapacityProvider(provider2, capacity, "provider_mismatch");
664
770
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
665
771
  const common = {
666
772
  version: EMAIL_FORMAT_VERSION,
667
773
  template: validateTemplateIdentity(dto.template),
668
- envelope: validateEnvelope(dto.envelope, provider2.kind),
774
+ envelope: validateEnvelope(dto.envelope, provider2.kind, SNAPSHOT, capacity),
669
775
  preparedAt,
670
776
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
671
777
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -679,7 +785,7 @@ function readSnapshot(input) {
679
785
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
680
786
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
681
787
  });
682
- return Object.freeze({ ...common, kind: provider2.kind, provider: provider2, ...content });
788
+ return Object.freeze({ ...common, kind: provider2.kind, provider: provider2, ...capacityTag(capacity), ...content });
683
789
  }
684
790
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
685
791
  return Object.freeze({
@@ -690,9 +796,9 @@ function readSnapshot(input) {
690
796
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
691
797
  });
692
798
  }
693
- function validateSnapshot(input) {
694
- const snapshot = readSnapshot(input);
695
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
799
+ function validateSnapshot(input, capacity) {
800
+ const snapshot = readSnapshot(input, capacity);
801
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
696
802
  }
697
803
 
698
804
  // src/internal/budget.ts
@@ -817,42 +923,56 @@ function validateAdmissionKey(input, code = "invalid_command") {
817
923
  function encodeAdmissionKey(key) {
818
924
  return key.kind === "single" ? `s:${key.idempotencyKey}` : `b:${key.batchId}:${key.itemId}`;
819
925
  }
820
- function fingerprintFor(identity) {
926
+ function fingerprintFor(identity, capacity) {
821
927
  const { scope: scope2, key, templateKey, provider: provider2, scheduleAt, intentHash } = identity;
822
928
  return hashJson(
823
- [EMAIL_FORMAT_VERSION, scope2, key, templateKey, provider2, scheduleAt, intentHash],
929
+ [
930
+ ...capacity ? ["smtp-v2-admission", capacity.binding] : [],
931
+ EMAIL_FORMAT_VERSION,
932
+ scope2,
933
+ key,
934
+ templateKey,
935
+ provider2,
936
+ scheduleAt,
937
+ intentHash
938
+ ],
824
939
  MESSAGE_LIMITS.intentBytes
825
940
  );
826
941
  }
827
- function validatePreparedCommand(scope2, input) {
942
+ function validatePreparedCommand(scope2, input, capacity) {
828
943
  const expectedScope = scopeToken(scope2);
829
944
  const code = "invalid_snapshot";
830
945
  const dto = readRecord(
831
946
  input,
832
947
  ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
833
- [],
948
+ ["smtpCapacity"],
834
949
  code
835
950
  );
836
951
  if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
952
+ assertCapacityTag(dto, capacity, code);
837
953
  const key = validateAdmissionKey(dto.key, code);
838
954
  const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
839
955
  const intentHash = hashToken(dto.intentHash, code);
840
956
  const fingerprint = hashToken(dto.fingerprint, code);
841
957
  const storedSnapshotHash = hashToken(dto.snapshotHash, code);
842
- const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
958
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot, capacity);
843
959
  validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
844
- if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor({
845
- scope: expectedScope,
846
- key,
847
- templateKey: snapshot.template.key,
848
- provider: snapshot.provider,
849
- scheduleAt,
850
- intentHash
851
- })) {
960
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor(
961
+ {
962
+ scope: expectedScope,
963
+ key,
964
+ templateKey: snapshot.template.key,
965
+ provider: snapshot.provider,
966
+ scheduleAt,
967
+ intentHash
968
+ },
969
+ capacity
970
+ )) {
852
971
  invalid(code);
853
972
  }
854
973
  return Object.freeze({
855
974
  version: EMAIL_FORMAT_VERSION,
975
+ ...capacityTag(capacity),
856
976
  scope: expectedScope,
857
977
  key,
858
978
  scheduleAt,
@@ -867,10 +987,7 @@ function validatePreparedCommand(scope2, input) {
867
987
  var REQUEST = "invalid_command";
868
988
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
869
989
  function readStoreId(value, code = REQUEST) {
870
- 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)) {
871
- invalid(code);
872
- }
873
- return value;
990
+ return uuidV4(value, code);
874
991
  }
875
992
  function readLeaseToken(value, code = REQUEST) {
876
993
  if (typeof value !== "string" || value.length < 22 || value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
@@ -884,14 +1001,18 @@ function readLeaseMs(value) {
884
1001
  function timeAfter(start, delayMs) {
885
1002
  return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
886
1003
  }
887
- function readStoreCall(input, worker = false) {
1004
+ function readStoreCall(input, worker = false, capacity) {
888
1005
  const code = "invalid_config";
889
- const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
1006
+ const { smtpCapacity, ...raw } = readRecord(input, ["signal", "timeoutMs"], capacity ? ["smtpCapacity"] : [], code);
1007
+ if (capacity) assertCapacityTag({ smtpCapacity }, capacity, "store_incompatible");
890
1008
  const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
891
1009
  const timeoutMs = integer(raw.timeoutMs, 1, max, code);
892
1010
  const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
893
1011
  if (!call.signal) invalid(code);
894
- return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
1012
+ return {
1013
+ signal: call.signal,
1014
+ timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1015
+ };
895
1016
  }
896
1017
  function readRetryPolicy(input, code = REQUEST) {
897
1018
  const raw = readRecord(input, ["maxAttempts", "baseDelayMs", "maxDelayMs"], [], code);
@@ -917,9 +1038,9 @@ function readRetentionPolicy(input, code = REQUEST) {
917
1038
  idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
918
1039
  });
919
1040
  }
920
- function readStoreAdmission(scope2, input) {
1041
+ function readStoreAdmission(scope2, input, capacity) {
921
1042
  const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
922
- const command = validatePreparedCommand(scope2, raw.command);
1043
+ const command = validatePreparedCommand(scope2, raw.command, capacity);
923
1044
  return Object.freeze({
924
1045
  command,
925
1046
  admissionKey: encodeAdmissionKey(command.key),
@@ -940,15 +1061,15 @@ function readClaim(input) {
940
1061
  leaseMs: readLeaseMs(leaseMs)
941
1062
  });
942
1063
  }
943
- function readFinish(input) {
944
- const { fence, phase, operationId, result: result2 } = readRecord(
1064
+ function readFinish(input, capacity) {
1065
+ const { fence, phase, operationId, result } = readRecord(
945
1066
  input,
946
1067
  ["fence", "phase", "operationId", "result"],
947
1068
  [],
948
1069
  REQUEST
949
1070
  );
950
1071
  if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
951
- const evidence2 = readAttemptResult(result2);
1072
+ const evidence2 = readAttemptResult(result, REQUEST, false, capacity);
952
1073
  assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
953
1074
  return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
954
1075
  }
@@ -965,7 +1086,6 @@ function readResolution(input) {
965
1086
  }
966
1087
 
967
1088
  // src/internal/activity-codecs.ts
968
- var ACTIVITY_BYTES = 8192;
969
1089
  var dispositions = [
970
1090
  "accepted",
971
1091
  "partially_accepted",
@@ -982,17 +1102,17 @@ function readDisposition(input, code) {
982
1102
  if (input === "retry_scheduled") return input;
983
1103
  return invalid(code);
984
1104
  }
985
- function assertActivityDisposition(result2, disposition, code) {
986
- const { outcome, reason } = result2;
1105
+ function assertActivityDisposition(result, disposition, code) {
1106
+ const { outcome, reason } = result;
987
1107
  if (outcome !== "rejected" && outcome !== "unsubmitted") {
988
1108
  if (disposition !== outcome) invalid(code);
989
1109
  } else if (reason === "expired" || reason === "cancelled") {
990
1110
  if (disposition !== reason) invalid(code);
991
- } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result2.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
1111
+ } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
992
1112
  invalid(code);
993
1113
  }
994
1114
  }
995
- function readActivity(scope2, input, code = "store_incompatible") {
1115
+ function captureActivity(scope2, input, code, capacity) {
996
1116
  const raw = readRecord(
997
1117
  input,
998
1118
  [
@@ -1009,26 +1129,32 @@ function readActivity(scope2, input, code = "store_incompatible") {
1009
1129
  "result",
1010
1130
  "disposition"
1011
1131
  ],
1012
- ["handedOffAt"],
1132
+ ["handedOffAt", "smtpCapacity", "recipientCounts"],
1013
1133
  code
1014
1134
  );
1015
1135
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope2) invalid(code);
1136
+ assertCapacityTag(raw, capacity, code);
1137
+ if (!capacity && Object.hasOwn(raw, "recipientCounts")) invalid(code);
1138
+ const counts = capacity ? readRecipientCounts(raw.recipientCounts, code, capacity) : void 0;
1016
1139
  const jobId = readStoreId(raw.jobId, code);
1017
1140
  const attemptId = readStoreId(raw.attemptId, code);
1018
1141
  const provider2 = validateProviderRef(raw.provider, code);
1142
+ assertCapacityProvider(provider2, capacity, code);
1019
1143
  const startedAt = unixMs(raw.startedAt, code);
1020
1144
  const finishedAt = unixMs(raw.finishedAt, code);
1021
1145
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1022
1146
  if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1023
1147
  invalid(code);
1024
1148
  }
1025
- const result2 = readAttemptResult(raw.result, code, true);
1026
- assertEvidencePhase(result2.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1027
- assertEvidenceContext(result2, provider2, attemptId, void 0, code);
1149
+ const result = readAttemptResult(raw.result, code, true, capacity);
1150
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1151
+ assertEvidenceContext(result, provider2, attemptId, counts, code);
1028
1152
  const disposition = readDisposition(raw.disposition, code);
1029
- assertActivityDisposition(result2, disposition, code);
1153
+ assertActivityDisposition(result, disposition, code);
1030
1154
  return Object.freeze({
1031
1155
  version: EMAIL_FORMAT_VERSION,
1156
+ ...capacityTag(capacity),
1157
+ ...counts ? { recipientCounts: counts } : {},
1032
1158
  scope: scope2,
1033
1159
  jobId,
1034
1160
  attemptId,
@@ -1039,54 +1165,66 @@ function readActivity(scope2, input, code = "store_incompatible") {
1039
1165
  startedAt,
1040
1166
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1041
1167
  finishedAt,
1042
- result: result2,
1168
+ result,
1043
1169
  disposition
1044
1170
  });
1045
1171
  }
1046
- function activityFor(job, commit) {
1172
+ function readActivity(scope2, input, code = "store_incompatible", capacity) {
1173
+ const activity = captureActivity(scope2, input, code, capacity);
1174
+ if (capacity) encodeEvidence(activity, code, capacity);
1175
+ return activity;
1176
+ }
1177
+ function activityFor(job, commit, capacity) {
1047
1178
  const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
1048
- return readActivity(job.scope, {
1049
- version: EMAIL_FORMAT_VERSION,
1050
- scope: job.scope,
1051
- jobId: job.jobId,
1052
- attemptId: commit.attemptId,
1053
- ordinal: commit.ordinal,
1054
- provider: job.provider,
1055
- template: job.template,
1056
- correlation: job.correlation,
1057
- startedAt: commit.startedAt,
1058
- ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1059
- finishedAt: commit.finishedAt,
1060
- disposition: commit.disposition,
1061
- result: {
1062
- outcome,
1063
- retry,
1064
- stage,
1065
- reason,
1066
- ...recipients === void 0 ? {} : { recipients },
1067
- ...messageId === void 0 ? {} : { messageId },
1068
- ...providerMessageId === void 0 ? {} : { providerMessageId }
1069
- }
1070
- });
1179
+ return captureActivity(
1180
+ job.scope,
1181
+ {
1182
+ version: EMAIL_FORMAT_VERSION,
1183
+ ...capacityTag(capacity),
1184
+ ...capacity ? { recipientCounts: job.recipientCounts } : {},
1185
+ scope: job.scope,
1186
+ jobId: job.jobId,
1187
+ attemptId: commit.attemptId,
1188
+ ordinal: commit.ordinal,
1189
+ provider: job.provider,
1190
+ template: job.template,
1191
+ correlation: job.correlation,
1192
+ startedAt: commit.startedAt,
1193
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1194
+ finishedAt: commit.finishedAt,
1195
+ disposition: commit.disposition,
1196
+ result: {
1197
+ outcome,
1198
+ retry,
1199
+ stage,
1200
+ reason,
1201
+ ...recipients === void 0 ? {} : { recipients },
1202
+ ...messageId === void 0 ? {} : { messageId },
1203
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1204
+ }
1205
+ },
1206
+ "store_incompatible",
1207
+ capacity
1208
+ );
1071
1209
  }
1072
- function activityDigest(activity) {
1073
- return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
1210
+ function activityDigest(activity, capacity) {
1211
+ return sha256(encodeEvidence(activity, "store_incompatible", capacity));
1074
1212
  }
1075
- function readStoredActivity(scope2, input, code = "store_incompatible") {
1213
+ function readStoredActivity(scope2, input, code = "store_incompatible", capacity) {
1076
1214
  const raw = readRecord(input, ["activity", "digest"], [], code);
1077
- const activity = readActivity(scope2, raw.activity, code);
1215
+ const activity = captureActivity(scope2, raw.activity, code, capacity);
1078
1216
  const digest2 = hashToken(raw.digest, code);
1079
- if (activityDigest(activity) !== digest2) invalid(code);
1217
+ if (activityDigest(activity, capacity) !== digest2) invalid(code);
1080
1218
  return Object.freeze({ activity, digest: digest2 });
1081
1219
  }
1082
- function readProjectionPermit(scope2, input) {
1220
+ function readProjectionPermit(scope2, input, capacity) {
1083
1221
  const code = "invalid_command";
1084
1222
  const {
1085
1223
  activity,
1086
1224
  digest: digest2,
1087
1225
  permitUntil: rawUntil
1088
1226
  } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1089
- const stored = readStoredActivity(scope2, { activity, digest: digest2 }, code);
1227
+ const stored = readStoredActivity(scope2, { activity, digest: digest2 }, code, capacity);
1090
1228
  const permitUntil = unixMs(rawUntil, code);
1091
1229
  if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1092
1230
  return Object.freeze({ ...stored, permitUntil });
@@ -1098,13 +1236,15 @@ function compareActivity(a, b) {
1098
1236
  return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1099
1237
  }
1100
1238
  function cursorPayload(criteria, position) {
1239
+ const binding = criteria.capacity?.binding;
1101
1240
  return {
1102
1241
  v: EMAIL_FORMAT_VERSION,
1103
1242
  s: criteria.scope,
1104
1243
  j: criteria.jobId,
1105
1244
  f: criteria.from,
1106
1245
  b: criteria.before,
1107
- p: [position.finishedAt, position.jobId, position.attemptId]
1246
+ p: [position.finishedAt, position.jobId, position.attemptId],
1247
+ ...binding ? { c: [binding.format, binding.namespace, binding.maxRecipients] } : {}
1108
1248
  };
1109
1249
  }
1110
1250
  function encodeCursor(criteria, position) {
@@ -1125,7 +1265,7 @@ function decodeCursor(criteria, cursor) {
1125
1265
  } catch {
1126
1266
  invalid(code);
1127
1267
  }
1128
- const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
1268
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], criteria.capacity ? ["c"] : [], code);
1129
1269
  const tuple = readArray(p, 3, code, (entry) => entry);
1130
1270
  const position = Object.freeze({
1131
1271
  finishedAt: unixMs(tuple[0], code),
@@ -1137,15 +1277,16 @@ function decodeCursor(criteria, cursor) {
1137
1277
  }
1138
1278
  return position;
1139
1279
  }
1140
- function readActivityCriteria(scope2, input) {
1280
+ function readActivityCriteria(scope2, input, capacity) {
1141
1281
  const code = "invalid_command";
1142
1282
  const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1143
1283
  const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1144
1284
  const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1145
1285
  const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1146
1286
  if (from !== null && before !== null && from > before) invalid(code);
1147
- const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, ACTIVITY_PAGE_LIMIT.min, ACTIVITY_PAGE_LIMIT.max, code) : ACTIVITY_PAGE_LIMIT.default;
1148
- const criteria = { scope: scope2, jobId, from, before, limit };
1287
+ const page = capacity?.limits.page ?? ACTIVITY_PAGE_LIMIT;
1288
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, page.min, page.max, code) : page.default;
1289
+ const criteria = { scope: scope2, jobId, from, before, limit, ...capacity ? { capacity } : {} };
1149
1290
  return Object.freeze({
1150
1291
  ...criteria,
1151
1292
  ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
@@ -1155,7 +1296,7 @@ function readOrderedActivities(criteria, input, maxRows) {
1155
1296
  const code = "store_incompatible";
1156
1297
  let previous = criteria.after;
1157
1298
  return readArray(input, maxRows, code, (row) => {
1158
- const activity = readActivity(criteria.scope, row);
1299
+ const activity = readActivity(criteria.scope, row, code, criteria.capacity);
1159
1300
  if (previous && compareActivity(previous, activity) >= 0 || criteria.jobId !== null && criteria.jobId !== activity.jobId || criteria.from !== null && activity.finishedAt < criteria.from || criteria.before !== null && activity.finishedAt >= criteria.before) {
1160
1301
  invalid(code);
1161
1302
  }
@@ -1246,6 +1387,7 @@ function jobSummary(job) {
1246
1387
  const latest = job.attempts.at(-1)?.commit;
1247
1388
  return Object.freeze({
1248
1389
  version: EMAIL_FORMAT_VERSION,
1390
+ ...job.smtpCapacity ? { smtpCapacity: job.smtpCapacity } : {},
1249
1391
  scope: job.scope,
1250
1392
  jobId: job.jobId,
1251
1393
  key: Object.freeze({ ...job.key }),
@@ -1270,13 +1412,13 @@ function jobSummary(job) {
1270
1412
  ...summaryState
1271
1413
  });
1272
1414
  }
1273
- function copyCommit(commit) {
1274
- return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED2) });
1415
+ function copyCommit(commit, capacity) {
1416
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED2, false, capacity) });
1275
1417
  }
1276
- function readStoredSnapshot(job, input) {
1418
+ function readStoredSnapshot(job, input, capacity) {
1277
1419
  let validated;
1278
1420
  try {
1279
- validated = validateSnapshot(input);
1421
+ validated = validateSnapshot(input, capacity);
1280
1422
  } catch {
1281
1423
  return invalid(STORED2);
1282
1424
  }
@@ -1343,7 +1485,7 @@ function readState(input) {
1343
1485
  }
1344
1486
  return invalid(STORED2);
1345
1487
  }
1346
- function readLedgerAttempt(input, job) {
1488
+ function readLedgerAttempt(input, job, capacity) {
1347
1489
  const entry = readRecord(input, ["commit", "digest"], ["ownerDigest", "permitUntil", "projectionAckAt"], STORED2);
1348
1490
  const raw = readRecord(
1349
1491
  entry.commit,
@@ -1356,14 +1498,14 @@ function readLedgerAttempt(input, job) {
1356
1498
  const handedOffAt = optionalTime(raw, "handedOffAt");
1357
1499
  const finishedAt = unixMs(raw.finishedAt, STORED2);
1358
1500
  const retryAt = optionalTime(raw, "retryAt");
1359
- const result2 = readAttemptResult(raw.result, STORED2);
1501
+ const result = readAttemptResult(raw.result, STORED2, false, capacity);
1360
1502
  const ownerDigest = Object.hasOwn(entry, "ownerDigest") ? hashToken(entry.ownerDigest, STORED2) : void 0;
1361
- const internal = result2.reason === "pre_handoff_lease_expired" || result2.reason === "post_handoff_lease_expired" || result2.reason === "cancelled";
1362
- if (raw.jobId !== job.jobId || startedAt >= job.expiresAt || finishedAt < startedAt || finishedAt > job.updatedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt >= job.expiresAt || handedOffAt > finishedAt) || result2.reason === "cancelled" && finishedAt >= job.expiresAt || result2.reason === "expired" && finishedAt < job.expiresAt || result2.reason === "pre_handoff_lease_expired" && finishedAt - startedAt < WORKER_LIMIT_BOUNDS.leaseMs.min || result2.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < WORKER_LIMIT_BOUNDS.leaseMs.min) || ownerDigest === void 0 !== internal) {
1503
+ const internal = result.reason === "pre_handoff_lease_expired" || result.reason === "post_handoff_lease_expired" || result.reason === "cancelled";
1504
+ if (raw.jobId !== job.jobId || startedAt >= job.expiresAt || finishedAt < startedAt || finishedAt > job.updatedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt >= job.expiresAt || handedOffAt > finishedAt) || result.reason === "cancelled" && finishedAt >= job.expiresAt || result.reason === "expired" && finishedAt < job.expiresAt || result.reason === "pre_handoff_lease_expired" && finishedAt - startedAt < WORKER_LIMIT_BOUNDS.leaseMs.min || result.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < WORKER_LIMIT_BOUNDS.leaseMs.min) || ownerDigest === void 0 !== internal) {
1363
1505
  invalid(STORED2);
1364
1506
  }
1365
- assertEvidencePhase(result2.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED2);
1366
- assertEvidenceContext(result2, job.provider, attemptId, job.recipientCounts, STORED2);
1507
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED2);
1508
+ assertEvidenceContext(result, job.provider, attemptId, job.recipientCounts, STORED2);
1367
1509
  const commit = Object.freeze({
1368
1510
  jobId: job.jobId,
1369
1511
  attemptId,
@@ -1372,7 +1514,7 @@ function readLedgerAttempt(input, job) {
1372
1514
  startedAt,
1373
1515
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1374
1516
  finishedAt,
1375
- result: result2,
1517
+ result,
1376
1518
  disposition: readDisposition(raw.disposition, STORED2),
1377
1519
  reason: raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED2),
1378
1520
  ...retryAt === void 0 ? {} : { retryAt }
@@ -1383,7 +1525,7 @@ function readLedgerAttempt(input, job) {
1383
1525
  invalid(STORED2);
1384
1526
  }
1385
1527
  const digest2 = hashToken(entry.digest, STORED2);
1386
- if (digest2 !== activityDigest(activityFor(job, commit))) invalid(STORED2);
1528
+ if (digest2 !== activityDigest(activityFor(job, commit, capacity), capacity)) invalid(STORED2);
1387
1529
  return Object.freeze({
1388
1530
  commit,
1389
1531
  digest: digest2,
@@ -1404,12 +1546,12 @@ function assertHistory(job) {
1404
1546
  let pending = false;
1405
1547
  let lastAck = 0;
1406
1548
  for (const { commit, permitUntil, projectionAckAt } of job.attempts) {
1407
- const { attemptId, ordinal: ordinal2, startedAt, finishedAt, result: result2, disposition, reason, retryAt } = commit;
1549
+ const { attemptId, ordinal: ordinal2, startedAt, finishedAt, result, disposition, reason, retryAt } = commit;
1408
1550
  if (nextAt === void 0 || startedAt < nextAt || seen.has(attemptId) || ordinal2 !== seen.size + 1 || !manual && ordinal2 > retry.maxAttempts) {
1409
1551
  invalid(STORED2);
1410
1552
  }
1411
1553
  seen.add(attemptId);
1412
- const expected = attemptEffect(result2, attemptId, ordinal2, manual, retry, expiresAt, finishedAt);
1554
+ const expected = attemptEffect(result, attemptId, ordinal2, manual, retry, expiresAt, finishedAt);
1413
1555
  if (disposition !== expected.disposition || reason !== expected.reason || retryAt !== expected.retryAt)
1414
1556
  invalid(STORED2);
1415
1557
  if (permitUntil !== void 0) {
@@ -1467,7 +1609,7 @@ function assertHistory(job) {
1467
1609
  if (job.snapshot || retireAt === void 0 || retireAt > job.updatedAt) invalid(STORED2);
1468
1610
  }
1469
1611
  }
1470
- function readJobRecord(scope2, input) {
1612
+ function readJobRecord(scope2, input, capacity) {
1471
1613
  const raw = readRecord(
1472
1614
  input,
1473
1615
  [
@@ -1494,27 +1636,26 @@ function readJobRecord(scope2, input) {
1494
1636
  "attempts",
1495
1637
  "resolutions"
1496
1638
  ],
1497
- ["snapshot", "projectionPermitUntil", "retiring"],
1639
+ ["snapshot", "projectionPermitUntil", "retiring", "smtpCapacity", "intentHash"],
1498
1640
  STORED2
1499
1641
  );
1500
1642
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED2) !== scope2) invalid(STORED2);
1501
- const counts = readRecord(raw.recipientCounts, ["to", "cc", "bcc"], [], STORED2);
1502
- const recipients = Object.freeze({
1503
- to: integer(counts.to, 0, MESSAGE_LIMITS.recipients, STORED2),
1504
- cc: integer(counts.cc, 0, MESSAGE_LIMITS.recipients, STORED2),
1505
- bcc: integer(counts.bcc, 0, MESSAGE_LIMITS.recipients, STORED2)
1506
- });
1507
- integer(recipients.to + recipients.cc + recipients.bcc, 1, MESSAGE_LIMITS.recipients, STORED2);
1643
+ assertCapacityTag(raw, capacity, STORED2);
1644
+ const recipients = readRecipientCounts(raw.recipientCounts, STORED2, capacity);
1508
1645
  const key = validateAdmissionKey(raw.key, STORED2);
1509
1646
  const admissionKey = encodeAdmissionKey(key);
1510
1647
  if (raw.admissionKey !== admissionKey) invalid(STORED2);
1648
+ if (!capacity && Object.hasOwn(raw, "intentHash")) invalid(STORED2);
1649
+ const intentHash = capacity ? hashToken(raw.intentHash, STORED2) : void 0;
1511
1650
  const base = {
1512
1651
  version: EMAIL_FORMAT_VERSION,
1652
+ ...capacityTag(capacity),
1513
1653
  scope: scope2,
1514
1654
  jobId: readStoreId(raw.jobId, STORED2),
1515
1655
  key,
1516
1656
  admissionKey,
1517
1657
  fingerprint: hashToken(raw.fingerprint, STORED2),
1658
+ ...intentHash === void 0 ? {} : { intentHash },
1518
1659
  snapshotHash: hashToken(raw.snapshotHash, STORED2),
1519
1660
  retry: readRetryPolicy(raw.retry, STORED2),
1520
1661
  retention: readRetentionPolicy(raw.retention, STORED2),
@@ -1530,6 +1671,10 @@ function readJobRecord(scope2, input) {
1530
1671
  revision: readStoreId(raw.revision, STORED2),
1531
1672
  state: readState(raw.state)
1532
1673
  };
1674
+ assertCapacityProvider(base.provider, capacity, STORED2);
1675
+ if (intentHash !== void 0 && base.fingerprint !== fingerprintFor({ ...base, templateKey: base.template.key, intentHash }, capacity)) {
1676
+ invalid(STORED2);
1677
+ }
1533
1678
  if (base.createdAt > base.updatedAt || Math.max(base.createdAt, base.scheduleAt ?? 0) >= base.expiresAt || base.provider.kind === "sendgrid" && !recipients.to) {
1534
1679
  invalid(STORED2);
1535
1680
  }
@@ -1538,8 +1683,8 @@ function readJobRecord(scope2, input) {
1538
1683
  if (retiring && raw.retiring !== true) invalid(STORED2);
1539
1684
  const job = Object.freeze({
1540
1685
  ...base,
1541
- ...Object.hasOwn(raw, "snapshot") ? { snapshot: readStoredSnapshot(base, raw.snapshot) } : {},
1542
- attempts: readArray(raw.attempts, MAX_ATTEMPT_LEDGER, STORED2, (entry) => readLedgerAttempt(entry, base)),
1686
+ ...Object.hasOwn(raw, "snapshot") ? { snapshot: readStoredSnapshot(base, raw.snapshot, capacity) } : {},
1687
+ attempts: readArray(raw.attempts, MAX_ATTEMPT_LEDGER, STORED2, (entry) => readLedgerAttempt(entry, base, capacity)),
1543
1688
  resolutions: readArray(raw.resolutions, 2, STORED2, readUnknownResolution),
1544
1689
  ...projectionPermitUntil === void 0 ? {} : { projectionPermitUntil },
1545
1690
  ...retiring ? { retiring: true } : {}
@@ -1548,6 +1693,11 @@ function readJobRecord(scope2, input) {
1548
1693
  return job;
1549
1694
  }
1550
1695
 
1696
+ // src/internal/smtp-attachments.ts
1697
+ function assertSmtpAttachmentTypes(refs) {
1698
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
1699
+ }
1700
+
1551
1701
  // src/internal/job-transitions.ts
1552
1702
  function guard(job, { now }, before) {
1553
1703
  if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
@@ -1571,15 +1721,18 @@ function replace(job, time2, patch, value, before, pendingAck) {
1571
1721
  write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
1572
1722
  };
1573
1723
  }
1574
- function newJob(admission, time2) {
1724
+ function newJob(admission, time2, capacity) {
1575
1725
  const { command, jobId, retry, retention, admissionKey } = admission;
1576
1726
  const { scope: scope2, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
1577
1727
  const now = unixMs(time2.now, "store_unavailable");
1578
1728
  if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
1579
1729
  const nextAt = Math.max(now, scheduleAt ?? now);
1580
1730
  if (nextAt >= snapshot.expiresAt) invalid("expired");
1731
+ if (snapshot.kind === "smtp") assertSmtpAttachmentTypes(snapshot.attachments);
1581
1732
  return Object.freeze({
1582
1733
  version: EMAIL_FORMAT_VERSION,
1734
+ ...capacityTag(capacity),
1735
+ ...capacity ? { intentHash: command.intentHash } : {},
1583
1736
  scope: scope2,
1584
1737
  jobId,
1585
1738
  key,
@@ -1618,14 +1771,18 @@ function liveLease(job, fence, phase, now) {
1618
1771
  }
1619
1772
  return lease;
1620
1773
  }
1621
- function claimJob(job, claim, time2) {
1774
+ function claimEligibility(job, now) {
1775
+ if (job.state.state !== "queued" || job.state.nextAt > now) return "not_due";
1776
+ return now >= job.expiresAt ? "expired" : "eligible";
1777
+ }
1778
+ function claimJob(job, claim, time2, capacity) {
1622
1779
  const { now } = time2;
1623
- if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
1780
+ if (claimEligibility(job, now) !== "eligible") return null;
1624
1781
  const manual = hasRedrive(job);
1625
1782
  const ordinal2 = job.attempts.length + 1;
1626
1783
  if (ordinal2 > MAX_ATTEMPT_LEDGER || !manual && ordinal2 > job.retry.maxAttempts) invalid("store_incompatible");
1627
1784
  if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
1628
- const snapshot = readStoredSnapshot(job, job.snapshot);
1785
+ const snapshot = readStoredSnapshot(job, job.snapshot, capacity);
1629
1786
  const lease = Object.freeze({
1630
1787
  attemptId: claim.attemptId,
1631
1788
  token: claim.token,
@@ -1648,6 +1805,20 @@ function claimJob(job, claim, time2) {
1648
1805
  Math.min(job.expiresAt, lease.leaseEndsAt)
1649
1806
  );
1650
1807
  }
1808
+ var EXPIRY_MAINTENANCE_REQUIRED = Object.freeze({ status: "expiry_maintenance_required" });
1809
+ function claimWindow(claim, candidateLimit, capacity) {
1810
+ let expired = 0;
1811
+ return {
1812
+ decide(job, time2) {
1813
+ const decision = claimJob(job, claim, time2, capacity);
1814
+ if (decision === null && claimEligibility(job, time2.now) === "expired") expired++;
1815
+ return decision;
1816
+ },
1817
+ result(next) {
1818
+ return next.status !== "applied" && expired === candidateLimit ? EXPIRY_MAINTENANCE_REQUIRED : next;
1819
+ }
1820
+ };
1821
+ }
1651
1822
  function renewJob(job, fence, leaseMs, time2) {
1652
1823
  const lease = liveLease(job, fence, "pre_handoff", time2.now);
1653
1824
  if (!lease || time2.now >= job.expiresAt) return null;
@@ -1685,11 +1856,11 @@ function markJob(job, fence, leaseMs, time2) {
1685
1856
  Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
1686
1857
  );
1687
1858
  }
1688
- function finalize(job, lease, operationId, result2, time2, owner) {
1859
+ function finalize(job, lease, operationId, result, time2, owner, capacity) {
1689
1860
  const { now } = time2;
1690
1861
  const { attemptId, startedAt, handedOffAt } = lease;
1691
1862
  const ordinal2 = job.attempts.length + 1;
1692
- const effect = attemptEffect(result2, attemptId, ordinal2, hasRedrive(job), job.retry, job.expiresAt, now);
1863
+ const effect = attemptEffect(result, attemptId, ordinal2, hasRedrive(job), job.retry, job.expiresAt, now);
1693
1864
  const commit = Object.freeze({
1694
1865
  jobId: job.jobId,
1695
1866
  attemptId,
@@ -1698,31 +1869,31 @@ function finalize(job, lease, operationId, result2, time2, owner) {
1698
1869
  startedAt,
1699
1870
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1700
1871
  finishedAt: now,
1701
- result: result2,
1872
+ result,
1702
1873
  ...effect
1703
1874
  });
1704
1875
  const entry = Object.freeze({
1705
1876
  commit,
1706
- digest: activityDigest(activityFor(job, commit)),
1877
+ digest: activityDigest(activityFor(job, commit, capacity), capacity),
1707
1878
  ...owner ? { ownerDigest: sha256(lease.token) } : {}
1708
1879
  });
1709
1880
  const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
1710
1881
  let before = owner ? lease.leaseEndsAt : void 0;
1711
- if (result2.reason === "cancelled" || result2.retry === "safe_transient" && effect.disposition !== "expired") {
1882
+ if (result.reason === "cancelled" || result.retry === "safe_transient" && effect.disposition !== "expired") {
1712
1883
  before = Math.min(before ?? job.expiresAt, job.expiresAt);
1713
1884
  }
1714
1885
  return replace(
1715
1886
  job,
1716
1887
  time2,
1717
1888
  { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
1718
- () => copyCommit(commit),
1889
+ () => copyCommit(commit, capacity),
1719
1890
  before
1720
1891
  );
1721
1892
  }
1722
- function finishJob(job, request, time2) {
1723
- const { fence, phase, operationId, result: result2 } = request;
1893
+ function finishJob(job, request, time2, capacity) {
1894
+ const { fence, phase, operationId, result } = request;
1724
1895
  if (job.jobId !== fence.jobId) return null;
1725
- assertEvidencePhase(result2.reason, phase, "owner", "invalid_command");
1896
+ assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
1726
1897
  const previous = job.attempts.find(({ commit }) => commit.attemptId === fence.attemptId);
1727
1898
  if (previous) {
1728
1899
  const { commit } = previous;
@@ -1730,28 +1901,28 @@ function finishJob(job, request, time2) {
1730
1901
  if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
1731
1902
  return null;
1732
1903
  }
1733
- if (hashJson(result2, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
1904
+ if (sha256(encodeEvidence(result, "invalid_command", capacity)) !== sha256(encodeEvidence(commit.result, "store_incompatible", capacity))) {
1734
1905
  invalid("invalid_command");
1735
1906
  }
1736
- return { value: copyCommit(commit) };
1907
+ return { value: copyCommit(commit, capacity) };
1737
1908
  }
1738
1909
  const lease = liveLease(job, fence, phase, time2.now);
1739
1910
  if (!lease) return null;
1740
- if (result2.reason === "expired" && time2.now < job.expiresAt) invalid("invalid_command");
1741
- assertEvidenceContext(result2, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
1742
- return finalize(job, lease, operationId, result2, time2, true);
1911
+ if (result.reason === "expired" && time2.now < job.expiresAt) invalid("invalid_command");
1912
+ assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
1913
+ return finalize(job, lease, operationId, result, time2, true, capacity);
1743
1914
  }
1744
- function recoverJob(job, operationId, time2) {
1915
+ function recoverJob(job, operationId, time2, capacity) {
1745
1916
  if (job.state.state !== "leased" || time2.now < job.state.lease.leaseEndsAt) return null;
1746
1917
  const { lease } = job.state;
1747
1918
  const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
1748
- return finalize(job, lease, operationId, lifecycleEvidence(reason), time2, false);
1919
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time2, false, capacity);
1749
1920
  }
1750
1921
  function expireJob(job, time2) {
1751
1922
  if (job.state.state !== "queued" || time2.now < job.expiresAt) return null;
1752
1923
  return replace(job, time2, { ...job, state: terminalState("expired", "expired", time2.now) }, jobSummary);
1753
1924
  }
1754
- function cancelJob(job, operationId, time2) {
1925
+ function cancelJob(job, operationId, time2, capacity) {
1755
1926
  const { state } = job;
1756
1927
  if (state.state === "terminal") {
1757
1928
  return {
@@ -1765,7 +1936,7 @@ function cancelJob(job, operationId, time2) {
1765
1936
  return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
1766
1937
  }
1767
1938
  if (state.state === "leased") {
1768
- const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time2, false);
1939
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time2, false, capacity);
1769
1940
  const { write } = decision;
1770
1941
  if (write?.kind !== "replace") invalid("store_incompatible");
1771
1942
  return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
@@ -1810,11 +1981,11 @@ function resolveJob(job, request, time2) {
1810
1981
  function replaceAttempt(job, previous, entry) {
1811
1982
  return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
1812
1983
  }
1813
- function reserveJobProjection(job, time2) {
1984
+ function reserveJobProjection(job, time2, capacity) {
1814
1985
  const entry = pendingAttempt(job);
1815
1986
  if (job.retiring || !entry || entry.commit.finishedAt > time2.now) return null;
1816
1987
  const permitUntil = timeAfter(time2.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
1817
- const activity = activityFor(job, entry.commit);
1988
+ const activity = activityFor(job, entry.commit, capacity);
1818
1989
  const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
1819
1990
  const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
1820
1991
  return replace(
@@ -1983,9 +2154,9 @@ var MongoConnection = class {
1983
2154
  return { kind: "ack", reply };
1984
2155
  }
1985
2156
  async read(binding, budget, command, target) {
1986
- const result2 = await this.exec(binding, budget, command, target);
1987
- if (result2.kind !== "ack") return invalid("store_unavailable");
1988
- return result2.reply;
2157
+ const result = await this.exec(binding, budget, command, target);
2158
+ if (result.kind !== "ack") return invalid("store_unavailable");
2159
+ return result.reply;
1989
2160
  }
1990
2161
  async write(binding, budget, command, definite) {
1991
2162
  return this.exec(binding, budget, command, "store", true, definite);
@@ -2095,9 +2266,9 @@ var jobOptional = [
2095
2266
  "pendingAt",
2096
2267
  "nextCleanupAt"
2097
2268
  ];
2098
- function readJobBson(scope2, raw) {
2099
- const { _id, lifecycle: lifecycle2, messageExpiresAt, state, nextAt, expiresAt, leaseEndsAt, pendingAt, nextCleanupAt, ...rest } = readRecord(raw, jobRequired, jobOptional, STORED3);
2100
- const job = readJobRecord(scope2, { ...rest, state: lifecycle2, expiresAt: messageExpiresAt });
2269
+ function readJobBson(scope2, raw, capacity) {
2270
+ const { _id, lifecycle: lifecycle2, messageExpiresAt, state, nextAt, expiresAt, leaseEndsAt, pendingAt, nextCleanupAt, ...rest } = readRecord(raw, jobRequired, capacity ? [...jobOptional, "smtpCapacity", "intentHash"] : jobOptional, STORED3);
2271
+ const job = readJobRecord(scope2, { ...rest, state: lifecycle2, expiresAt: messageExpiresAt }, capacity);
2101
2272
  const selectors = jobSelectors(job);
2102
2273
  for (const [key, value, expected] of [
2103
2274
  ["state", state, selectors.state],
@@ -2128,14 +2299,15 @@ var activityRequired = [
2128
2299
  "disposition"
2129
2300
  ];
2130
2301
  var activityOptional = ["handedOffAt"];
2131
- function readActivityBson(expectedScope, row) {
2302
+ function readActivityBson(expectedScope, row, capacity) {
2132
2303
  if (!Object.hasOwn(row, "complete")) {
2133
- const { _id: _id2, scope: scope2, jobId, attemptId, stubDeleteAt } = readRecord(
2304
+ const { _id: _id2, scope: scope2, jobId, attemptId, stubDeleteAt, ...tag } = readRecord(
2134
2305
  row,
2135
2306
  [...activityIdentity, "stubDeleteAt"],
2136
- [],
2307
+ capacity ? ["smtpCapacity"] : [],
2137
2308
  STORED3
2138
2309
  );
2310
+ assertCapacityTag(tag, capacity, STORED3);
2139
2311
  readStoreId(_id2, STORED3);
2140
2312
  readStoreId(jobId, STORED3);
2141
2313
  readStoreId(attemptId, STORED3);
@@ -2143,9 +2315,14 @@ function readActivityBson(expectedScope, row) {
2143
2315
  unixMs(stubDeleteAt.getTime(), STORED3);
2144
2316
  return;
2145
2317
  }
2146
- const { _id, complete, digest: digest2, ...activity } = readRecord(row, activityRequired, activityOptional, STORED3);
2318
+ const { _id, complete, digest: digest2, ...activity } = readRecord(
2319
+ row,
2320
+ activityRequired,
2321
+ capacity ? [...activityOptional, "smtpCapacity", "recipientCounts"] : activityOptional,
2322
+ STORED3
2323
+ );
2147
2324
  readStoreId(_id, STORED3);
2148
- const stored = readStoredActivity(expectedScope, { activity, digest: digest2 });
2325
+ const stored = readStoredActivity(expectedScope, { activity, digest: digest2 }, STORED3, capacity);
2149
2326
  if (complete !== true) invalid(STORED3);
2150
2327
  return stored;
2151
2328
  }
@@ -2175,49 +2352,58 @@ var provider = objectSchema({
2175
2352
  });
2176
2353
  var template = objectSchema({ key: string, revision: string });
2177
2354
  var correlation = { ...bsonObject, maxProperties: MESSAGE_LIMITS.correlationEntries, additionalProperties: string };
2178
- var recipient = objectSchema({
2179
- group: { enum: ["to", "cc", "bcc"] },
2180
- index: { ...numeric, minimum: 0, maximum: MESSAGE_LIMITS.recipients - 1 },
2181
- status: { enum: ["accepted", "rejected"] }
2182
- });
2183
- var result = {
2184
- outcome: string,
2185
- retry: { enum: ["never", "safe_transient"] },
2186
- stage: string,
2187
- reason: string,
2188
- recipients: { bsonType: "array", maxItems: MESSAGE_LIMITS.recipients, items: recipient },
2189
- messageId: { ...string, maxLength: "<00000000-0000-4000-8000-000000000000@email.invalid>".length },
2190
- providerMessageId: { ...string, maxLength: 128 }
2191
- };
2355
+ var smtpProvider = objectSchema({ kind: { enum: ["smtp"] }, key: string, mode: { enum: ["live"] } });
2356
+ function resultFields(capacity) {
2357
+ const max = recipientLimit(capacity);
2358
+ const recipient = objectSchema({
2359
+ group: { enum: ["to", "cc", "bcc"] },
2360
+ index: { ...numeric, minimum: 0, maximum: max - 1 },
2361
+ status: { enum: ["accepted", "rejected"] }
2362
+ });
2363
+ return {
2364
+ outcome: string,
2365
+ retry: { enum: ["never", "safe_transient"] },
2366
+ stage: string,
2367
+ reason: string,
2368
+ recipients: { bsonType: "array", maxItems: max, items: recipient },
2369
+ messageId: { ...string, maxLength: "<00000000-0000-4000-8000-000000000000@email.invalid>".length },
2370
+ ...capacity ? {} : { providerMessageId: { ...string, maxLength: 128 } }
2371
+ };
2372
+ }
2192
2373
  var resultOptional = ["recipients", "messageId", "providerMessageId"];
2193
- var ledgerAttempt = objectSchema(
2194
- {
2195
- commit: objectSchema(
2196
- {
2197
- jobId: uuid,
2198
- attemptId: uuid,
2199
- ordinal,
2200
- operationId: uuid,
2201
- startedAt: time,
2202
- handedOffAt: time,
2203
- finishedAt: time,
2204
- result: objectSchema(
2205
- { ...result, retryHint: objectSchema({ delayMs: numeric, notBefore: time }, ["delayMs", "notBefore"]) },
2206
- [...resultOptional, "retryHint"]
2207
- ),
2208
- disposition: string,
2209
- reason: string,
2210
- retryAt: time
2211
- },
2212
- ["handedOffAt", "retryAt"]
2213
- ),
2214
- digest,
2215
- ownerDigest: digest,
2216
- permitUntil: time,
2217
- projectionAckAt: time
2218
- },
2219
- ["ownerDigest", "permitUntil", "projectionAckAt"]
2220
- );
2374
+ function ledgerAttempt(capacity) {
2375
+ return objectSchema(
2376
+ {
2377
+ commit: objectSchema(
2378
+ {
2379
+ jobId: uuid,
2380
+ attemptId: uuid,
2381
+ ordinal,
2382
+ operationId: uuid,
2383
+ startedAt: time,
2384
+ handedOffAt: time,
2385
+ finishedAt: time,
2386
+ result: objectSchema(
2387
+ {
2388
+ ...resultFields(capacity),
2389
+ retryHint: objectSchema({ delayMs: numeric, notBefore: time }, ["delayMs", "notBefore"])
2390
+ },
2391
+ [...resultOptional, "retryHint"]
2392
+ ),
2393
+ disposition: string,
2394
+ reason: string,
2395
+ retryAt: time
2396
+ },
2397
+ ["handedOffAt", "retryAt"]
2398
+ ),
2399
+ digest,
2400
+ ownerDigest: digest,
2401
+ permitUntil: time,
2402
+ projectionAckAt: time
2403
+ },
2404
+ ["ownerDigest", "permitUntil", "projectionAckAt"]
2405
+ );
2406
+ }
2221
2407
  var lifecycle = {
2222
2408
  oneOf: [
2223
2409
  objectSchema({ state: { enum: ["queued"] }, nextAt: time }),
@@ -2247,13 +2433,57 @@ var lifecycle = {
2247
2433
  )
2248
2434
  ]
2249
2435
  };
2250
- function jobValidator() {
2436
+ function capacityField({ binding }) {
2251
2437
  return {
2438
+ smtpCapacity: objectSchema({
2439
+ format: { enum: [binding.format] },
2440
+ namespace: { enum: [binding.namespace] },
2441
+ maxRecipients: { ...numeric, enum: [binding.maxRecipients] }
2442
+ })
2443
+ };
2444
+ }
2445
+ function countsSchema(capacity) {
2446
+ const count = capacity ? { ...numeric, minimum: 0, maximum: recipientLimit(capacity) } : numeric;
2447
+ return objectSchema({ to: count, cc: count, bcc: count });
2448
+ }
2449
+ function smtpSnapshot(capacity) {
2450
+ const mailbox = objectSchema({ address: string, name: string }, ["name"]);
2451
+ const recipients = { bsonType: "array", maxItems: recipientLimit(capacity), items: mailbox };
2452
+ return objectSchema(
2453
+ {
2454
+ version,
2455
+ ...capacityField(capacity),
2456
+ kind: { enum: ["smtp"] },
2457
+ provider: smtpProvider,
2458
+ template,
2459
+ envelope: objectSchema({ from: mailbox, to: recipients, cc: recipients, bcc: recipients, replyTo: mailbox }, [
2460
+ "replyTo"
2461
+ ]),
2462
+ preparedAt: time,
2463
+ expiresAt: time,
2464
+ priority: { ...numeric, minimum: PRIORITY.min, maximum: PRIORITY.max },
2465
+ attachments: { bsonType: "array", maxItems: MESSAGE_LIMITS.attachments, items: bsonObject },
2466
+ correlation,
2467
+ subject: string,
2468
+ html: string,
2469
+ text: string
2470
+ },
2471
+ ["html", "text"]
2472
+ );
2473
+ }
2474
+ function withBsonLimit(validator, maxBytes) {
2475
+ return maxBytes === void 0 ? validator : {
2476
+ $and: [validator, { $expr: { $lte: [{ $bsonSize: "$$ROOT" }, maxBytes] } }]
2477
+ };
2478
+ }
2479
+ function jobValidator(capacity) {
2480
+ const validator = {
2252
2481
  $jsonSchema: {
2253
2482
  ...objectSchema(
2254
2483
  {
2255
2484
  _id: string,
2256
2485
  version,
2486
+ ...capacity ? { ...capacityField(capacity), intentHash: digest } : {},
2257
2487
  scope,
2258
2488
  jobId: uuid,
2259
2489
  key: {
@@ -2265,13 +2495,13 @@ function jobValidator() {
2265
2495
  admissionKey: string,
2266
2496
  fingerprint: digest,
2267
2497
  snapshotHash: digest,
2268
- snapshot: bsonObject,
2498
+ snapshot: capacity ? smtpSnapshot(capacity) : bsonObject,
2269
2499
  retry: objectSchema({ maxAttempts: numeric, baseDelayMs: numeric, maxDelayMs: numeric }),
2270
2500
  retention: objectSchema({ payloadMs: numeric, historyMs: numeric, idempotencyMs: numeric }),
2271
- provider,
2501
+ provider: capacity ? smtpProvider : provider,
2272
2502
  template,
2273
2503
  correlation,
2274
- recipientCounts: objectSchema({ to: numeric, cc: numeric, bcc: numeric }),
2504
+ recipientCounts: countsSchema(capacity),
2275
2505
  scheduleAt: { anyOf: [time, { bsonType: "null" }] },
2276
2506
  createdAt: time,
2277
2507
  updatedAt: time,
@@ -2280,7 +2510,7 @@ function jobValidator() {
2280
2510
  revision: uuid,
2281
2511
  lifecycle,
2282
2512
  state: { enum: ["queued", "leased", "terminal"] },
2283
- attempts: { bsonType: "array", items: ledgerAttempt, maxItems: MAX_ATTEMPT_LEDGER },
2513
+ attempts: { bsonType: "array", items: ledgerAttempt(capacity), maxItems: MAX_ATTEMPT_LEDGER },
2284
2514
  resolutions: {
2285
2515
  bsonType: "array",
2286
2516
  maxItems: 2,
@@ -2314,10 +2544,11 @@ function jobValidator() {
2314
2544
  ]
2315
2545
  }
2316
2546
  };
2547
+ return withBsonLimit(validator, capacity?.limits.jobBsonBytes);
2317
2548
  }
2318
- function activityValidator() {
2319
- const identity = { _id: uuid, scope, jobId: uuid, attemptId: uuid };
2320
- return {
2549
+ function activityValidator(capacity) {
2550
+ const identity = { _id: uuid, scope, jobId: uuid, attemptId: uuid, ...capacity ? capacityField(capacity) : {} };
2551
+ const validator = {
2321
2552
  $jsonSchema: {
2322
2553
  oneOf: [
2323
2554
  objectSchema(
@@ -2327,13 +2558,14 @@ function activityValidator() {
2327
2558
  complete: { enum: [true] },
2328
2559
  digest,
2329
2560
  ordinal,
2330
- provider,
2561
+ provider: capacity ? smtpProvider : provider,
2562
+ ...capacity ? { recipientCounts: countsSchema(capacity) } : {},
2331
2563
  template,
2332
2564
  correlation,
2333
2565
  startedAt: time,
2334
2566
  handedOffAt: time,
2335
2567
  finishedAt: time,
2336
- result: objectSchema(result, resultOptional),
2568
+ result: objectSchema(resultFields(capacity), resultOptional),
2337
2569
  disposition: string
2338
2570
  },
2339
2571
  activityOptional
@@ -2342,6 +2574,7 @@ function activityValidator() {
2342
2574
  ]
2343
2575
  }
2344
2576
  };
2577
+ return withBsonLimit(validator, capacity?.limits.activityBsonBytes);
2345
2578
  }
2346
2579
 
2347
2580
  // src/stores/mongoose/schema.ts
@@ -2381,18 +2614,24 @@ var activityIndexes = [
2381
2614
  },
2382
2615
  { name: "v1_activity_stub_ttl", key: { stubDeleteAt: 1 }, expireAfterSeconds: 0 }
2383
2616
  ];
2384
- function jobSchema(name) {
2385
- return { name, validator: jobValidator(), indexes: jobIndexes };
2617
+ function indexName(v1Name, capacity) {
2618
+ return capacity ? `v2_${v1Name.slice(3)}` : v1Name;
2619
+ }
2620
+ function laneIndexes(indexes, capacity) {
2621
+ return capacity ? indexes.map((index) => ({ ...index, name: indexName(index.name, capacity) })) : indexes;
2386
2622
  }
2387
- function activitySchema(name) {
2388
- return { name, validator: activityValidator(), indexes: activityIndexes };
2623
+ function jobSchema(name, capacity) {
2624
+ return { name, validator: jobValidator(capacity), indexes: laneIndexes(jobIndexes, capacity) };
2625
+ }
2626
+ function activitySchema(name, capacity) {
2627
+ return { name, validator: activityValidator(capacity), indexes: laneIndexes(activityIndexes, capacity) };
2389
2628
  }
2390
2629
  function simple(collation) {
2391
2630
  return collation === void 0 || isDeepStrictEqual(collation, SIMPLE);
2392
2631
  }
2393
2632
  async function getCollection(io, binding, budget, name) {
2394
- const result2 = await io.read(binding, budget, { listCollections: 1, filter: { name }, cursor: { batchSize: 2 } });
2395
- const rows = batch(result2, 1, `${binding.db.databaseName}.$cmd.listCollections`);
2633
+ const result = await io.read(binding, budget, { listCollections: 1, filter: { name }, cursor: { batchSize: 2 } });
2634
+ const rows = batch(result, 1, `${binding.db.databaseName}.$cmd.listCollections`);
2396
2635
  return rows[0] === void 0 ? void 0 : doc(rows[0], "store_incompatible");
2397
2636
  }
2398
2637
  function checkCollection(row, schema) {
@@ -2409,8 +2648,8 @@ function matchesIndex(raw, index) {
2409
2648
  }
2410
2649
  async function missingIndexes(io, binding, budget, { name, indexes }) {
2411
2650
  const max = 64;
2412
- const result2 = await io.read(binding, budget, { listIndexes: name, cursor: { batchSize: max + 1 } });
2413
- const defs = batch(result2, max, `${binding.db.databaseName}.${name}`);
2651
+ const result = await io.read(binding, budget, { listIndexes: name, cursor: { batchSize: max + 1 } });
2652
+ const defs = batch(result, max, `${binding.db.databaseName}.${name}`);
2414
2653
  const required = [{ name: "_id_", key: { _id: 1 } }, ...indexes];
2415
2654
  const seen = /* @__PURE__ */ new Set();
2416
2655
  for (const def of defs) {
@@ -2422,9 +2661,15 @@ async function missingIndexes(io, binding, budget, { name, indexes }) {
2422
2661
  if (!seen.has("_id_")) invalid("store_incompatible");
2423
2662
  return indexes.filter((index) => !seen.has(index.name));
2424
2663
  }
2664
+ async function checkExistingCollection(io, binding, budget, schema) {
2665
+ const row = await getCollection(io, binding, budget, schema.name);
2666
+ if (!row) return;
2667
+ checkCollection(row, schema);
2668
+ await missingIndexes(io, binding, budget, schema);
2669
+ }
2425
2670
  async function prepareCollection(io, binding, budget, schema) {
2426
2671
  if (!await getCollection(io, binding, budget, schema.name)) {
2427
- const result2 = await io.write(
2672
+ const result = await io.write(
2428
2673
  binding,
2429
2674
  budget,
2430
2675
  {
@@ -2436,12 +2681,12 @@ async function prepareCollection(io, binding, budget, schema) {
2436
2681
  },
2437
2682
  [48, 2, 9, 72, 115]
2438
2683
  );
2439
- if (result2.kind === "definite_error" && result2.code !== 48) invalid("store_incompatible");
2684
+ if (result.kind === "definite_error" && result.code !== 48) invalid("store_incompatible");
2440
2685
  }
2441
2686
  checkCollection(await getCollection(io, binding, budget, schema.name), schema);
2442
2687
  const missing = await missingIndexes(io, binding, budget, schema);
2443
2688
  if (missing.length) {
2444
- const result2 = await io.write(
2689
+ const result = await io.write(
2445
2690
  binding,
2446
2691
  budget,
2447
2692
  {
@@ -2450,7 +2695,7 @@ async function prepareCollection(io, binding, budget, schema) {
2450
2695
  },
2451
2696
  [2, 67, 68, 72, 85, 86, 11e3]
2452
2697
  );
2453
- if (result2.kind === "definite_error") invalid("store_incompatible");
2698
+ if (result.kind === "definite_error") invalid("store_incompatible");
2454
2699
  if ((await missingIndexes(io, binding, budget, schema)).length) invalid("store_incompatible");
2455
2700
  }
2456
2701
  }
@@ -2471,13 +2716,22 @@ function modifiedValue(reply) {
2471
2716
  if (n !== (reply.value === null ? 0 : 1) || reply.value === void 0) invalid("write_unconfirmed");
2472
2717
  return reply.value;
2473
2718
  }
2474
- function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck, atOrAfter, before }) {
2719
+ function capacityFilter(capacity) {
2720
+ const binding = capacity?.binding;
2721
+ return binding ? {
2722
+ "smtpCapacity.format": binding.format,
2723
+ "smtpCapacity.namespace": binding.namespace,
2724
+ "smtpCapacity.maxRecipients": binding.maxRecipients
2725
+ } : {};
2726
+ }
2727
+ function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck, atOrAfter, before }, capacity) {
2475
2728
  const lease = state.state === "leased" ? state.lease : void 0;
2476
2729
  return {
2477
2730
  _id: jobIdKey(scope2, jobId),
2478
2731
  scope: scope2,
2479
2732
  jobId,
2480
2733
  version: EMAIL_FORMAT_VERSION,
2734
+ ...capacityFilter(capacity),
2481
2735
  revision,
2482
2736
  state: state.state,
2483
2737
  "lifecycle.state": state.state,
@@ -2504,16 +2758,18 @@ function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck
2504
2758
  };
2505
2759
  }
2506
2760
  var MongoOperations = class {
2507
- constructor(io, binding, budget, names) {
2761
+ constructor(io, binding, budget, names, capacity) {
2508
2762
  this.io = io;
2509
2763
  this.binding = binding;
2510
2764
  this.budget = budget;
2511
2765
  this.names = names;
2766
+ this.capacity = capacity;
2512
2767
  }
2513
2768
  io;
2514
2769
  binding;
2515
2770
  budget;
2516
2771
  names;
2772
+ capacity;
2517
2773
  check() {
2518
2774
  this.budget.check();
2519
2775
  }
@@ -2527,7 +2783,7 @@ var MongoOperations = class {
2527
2783
  const reply = await this.io.read(this.binding, this.budget, {
2528
2784
  find,
2529
2785
  filter,
2530
- hint,
2786
+ hint: indexName(hint, this.capacity),
2531
2787
  collation: SIMPLE,
2532
2788
  readConcern: { level },
2533
2789
  limit,
@@ -2541,7 +2797,7 @@ var MongoOperations = class {
2541
2797
  async byJob(scope2, jobId) {
2542
2798
  const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, jobId }, JOB_ID, 1, "linearizable");
2543
2799
  if (!raw) return;
2544
- const job = readJobBson(scope2, raw);
2800
+ const job = readJobBson(scope2, raw, this.capacity);
2545
2801
  if (job.jobId !== jobId) invalid("store_incompatible");
2546
2802
  this.check();
2547
2803
  return job;
@@ -2549,7 +2805,7 @@ var MongoOperations = class {
2549
2805
  async byAdmission(scope2, admissionKey) {
2550
2806
  const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, admissionKey }, ADMISSION_ID, 1, "linearizable");
2551
2807
  if (!raw) return;
2552
- const job = readJobBson(scope2, raw);
2808
+ const job = readJobBson(scope2, raw, this.capacity);
2553
2809
  if (job.admissionKey !== admissionKey) invalid("store_incompatible");
2554
2810
  this.check();
2555
2811
  return job;
@@ -2559,18 +2815,18 @@ var MongoOperations = class {
2559
2815
  if (!raw) return;
2560
2816
  const { jobId, attemptId } = doc(raw, "store_incompatible");
2561
2817
  if (jobId !== identity.jobId || attemptId !== identity.attemptId) invalid("store_incompatible");
2562
- const row = readActivityBson(identity.scope, raw);
2818
+ const row = readActivityBson(identity.scope, raw, this.capacity);
2563
2819
  this.check();
2564
2820
  return row;
2565
2821
  }
2566
2822
  async insert(job) {
2567
- const result2 = await this.io.write(this.binding, this.budget, {
2823
+ const result = await this.io.write(this.binding, this.budget, {
2568
2824
  insert: this.names.jobsCollection,
2569
2825
  documents: [jobBson(job)]
2570
2826
  });
2571
- if (result2.kind !== "ack") invalid("write_unconfirmed");
2572
- const { n, writeErrors } = result2.reply;
2573
- if (n === 1 && !Object.hasOwn(result2.reply, "writeErrors")) return "inserted";
2827
+ if (result.kind !== "ack") invalid("write_unconfirmed");
2828
+ const { n, writeErrors } = result.reply;
2829
+ if (n === 1 && !Object.hasOwn(result.reply, "writeErrors")) return "inserted";
2574
2830
  if (n === 0 && Array.isArray(writeErrors) && writeErrors.length === 1) {
2575
2831
  const { code } = doc(writeErrors[0], "write_unconfirmed");
2576
2832
  if (code === 121) invalid("store_incompatible");
@@ -2589,23 +2845,23 @@ var MongoOperations = class {
2589
2845
  }
2590
2846
  async replace(write) {
2591
2847
  const { guard: guard2, next } = write;
2592
- const result2 = await this.io.write(
2848
+ const result = await this.io.write(
2593
2849
  this.binding,
2594
2850
  this.budget,
2595
2851
  {
2596
2852
  findAndModify: this.names.jobsCollection,
2597
- query: casFilter(guard2),
2853
+ query: casFilter(guard2, this.capacity),
2598
2854
  // Treat the whole replacement as literal, including rendered strings beginning with '$'.
2599
2855
  update: [{ $replaceWith: { $literal: jobBson(next) } }],
2600
2856
  fields: { _id: 1, revision: 1 },
2601
2857
  new: true,
2602
- hint: JOB_ID,
2858
+ hint: indexName(JOB_ID, this.capacity),
2603
2859
  collation: SIMPLE
2604
2860
  },
2605
2861
  [121]
2606
2862
  );
2607
- if (result2.kind === "definite_error") invalid("store_incompatible");
2608
- const value = modifiedValue(result2.reply);
2863
+ if (result.kind === "definite_error") invalid("store_incompatible");
2864
+ const value = modifiedValue(result.reply);
2609
2865
  if (value === null) return false;
2610
2866
  const { _id, revision } = doc(value, "write_unconfirmed");
2611
2867
  if (_id !== jobIdKey(next.scope, next.jobId) || revision !== next.revision) invalid("write_unconfirmed");
@@ -2620,7 +2876,7 @@ var MongoOperations = class {
2620
2876
  const identity = { scope: scope2, jobId, attemptId };
2621
2877
  const [raw] = await this.find(this.names.activitiesCollection, identity, ACTIVITY_ID, 1, "linearizable");
2622
2878
  if (raw) {
2623
- readActivityBson(scope2, raw);
2879
+ readActivityBson(scope2, raw, this.capacity);
2624
2880
  exact.push({ ...identity, _id: readStoreId(doc(raw, "store_incompatible")._id, "store_incompatible") });
2625
2881
  }
2626
2882
  }
@@ -2631,9 +2887,9 @@ var MongoOperations = class {
2631
2887
  delete: this.names.activitiesCollection,
2632
2888
  // An exact indexed delete per attempt in one ordered command.
2633
2889
  deletes: exact.map((identity) => ({
2634
- q: { ...identity, $expr: serverWindow(guard2.atOrAfter) },
2890
+ q: { ...identity, ...capacityFilter(this.capacity), $expr: serverWindow(guard2.atOrAfter) },
2635
2891
  limit: 1,
2636
- hint: ACTIVITY_ID,
2892
+ hint: indexName(ACTIVITY_ID, this.capacity),
2637
2893
  collation: SIMPLE
2638
2894
  }))
2639
2895
  });
@@ -2646,7 +2902,14 @@ var MongoOperations = class {
2646
2902
  }
2647
2903
  const outcome = await this.io.write(this.binding, this.budget, {
2648
2904
  delete: this.names.jobsCollection,
2649
- deletes: [{ q: casFilter(guard2), limit: 1, hint: JOB_ID, collation: SIMPLE }]
2905
+ deletes: [
2906
+ {
2907
+ q: casFilter(guard2, this.capacity),
2908
+ limit: 1,
2909
+ hint: indexName(JOB_ID, this.capacity),
2910
+ collation: SIMPLE
2911
+ }
2912
+ ]
2650
2913
  });
2651
2914
  if (outcome.kind !== "ack") invalid("write_unconfirmed");
2652
2915
  return writeCount(outcome.reply, 1) === 1;
@@ -2669,6 +2932,13 @@ var MongoOperations = class {
2669
2932
  }
2670
2933
  return invalid("busy");
2671
2934
  }
2935
+ get dueCandidateLimit() {
2936
+ return this.capacity?.limits.dueCandidates ?? MAX_STORE_CANDIDATES;
2937
+ }
2938
+ async claimNext(scope2, claim) {
2939
+ const window = claimWindow(claim, this.dueCandidateLimit, this.capacity);
2940
+ return window.result(await this.next(scope2, "nextAt", window.decide));
2941
+ }
2672
2942
  async next(scope2, due, decide) {
2673
2943
  const selectionAt = await this.now();
2674
2944
  const { name, state, sort } = dueIndexes[due];
@@ -2680,7 +2950,7 @@ var MongoOperations = class {
2680
2950
  [due]: { $exists: true, $lte: selectionAt }
2681
2951
  },
2682
2952
  name,
2683
- MAX_STORE_CANDIDATES,
2953
+ this.dueCandidateLimit,
2684
2954
  "majority",
2685
2955
  sort,
2686
2956
  { _id: 0, jobId: 1 }
@@ -2715,15 +2985,15 @@ var MongoOperations = class {
2715
2985
  const identity = activityKey(permit.activity);
2716
2986
  const activity = activityBson(permit);
2717
2987
  const candidateId = randomUUID();
2718
- const result2 = await this.io.write(
2988
+ const result = await this.io.write(
2719
2989
  this.binding,
2720
2990
  this.budget,
2721
2991
  {
2722
2992
  findAndModify: this.names.activitiesCollection,
2723
- query: identity,
2993
+ query: { ...identity, ...capacityFilter(this.capacity) },
2724
2994
  new: true,
2725
2995
  upsert: true,
2726
- hint: ACTIVITY_ID,
2996
+ hint: indexName(ACTIVITY_ID, this.capacity),
2727
2997
  collation: SIMPLE,
2728
2998
  update: [
2729
2999
  {
@@ -2744,7 +3014,7 @@ var MongoOperations = class {
2744
3014
  ],
2745
3015
  default: {
2746
3016
  $mergeObjects: [
2747
- { $literal: identity },
3017
+ { $literal: { ...identity, ...capacityTag(this.capacity) } },
2748
3018
  { _id: { $literal: candidateId }, stubDeleteAt: { $add: ["$$NOW", ACTIVITY_STUB_TTL_MS] } }
2749
3019
  ]
2750
3020
  }
@@ -2755,10 +3025,14 @@ var MongoOperations = class {
2755
3025
  },
2756
3026
  [11e3, 121]
2757
3027
  );
2758
- if (result2.kind === "definite_error" && result2.code === 121) invalid("store_incompatible");
3028
+ if (result.kind === "definite_error" && result.code === 121) invalid("store_incompatible");
2759
3029
  let confirmedComplete = false;
2760
- if (result2.kind === "ack") {
2761
- const row = readActivityBson(identity.scope, doc(modifiedValue(result2.reply), "write_unconfirmed"));
3030
+ if (result.kind === "ack") {
3031
+ const row = readActivityBson(
3032
+ identity.scope,
3033
+ doc(modifiedValue(result.reply), "write_unconfirmed"),
3034
+ this.capacity
3035
+ );
2762
3036
  if (row && row.digest !== permit.digest) invalid("store_incompatible");
2763
3037
  confirmedComplete = row !== void 0;
2764
3038
  }
@@ -2816,7 +3090,7 @@ var MongoOperations = class {
2816
3090
  await readRange(Object.keys(range).length ? { finishedAt: range } : {});
2817
3091
  const page = activityPage(
2818
3092
  criteria,
2819
- rows.map((row) => readActivityBson(scope2, row)?.activity ?? invalid("store_incompatible"))
3093
+ rows.map((row) => readActivityBson(scope2, row, this.capacity)?.activity ?? invalid("store_incompatible"))
2820
3094
  );
2821
3095
  this.check();
2822
3096
  return page;
@@ -2825,11 +3099,25 @@ var MongoOperations = class {
2825
3099
 
2826
3100
  // src/mongoose.ts
2827
3101
  var MAX_IN_FLIGHT = 32;
2828
- function readNames(options) {
2829
- const keys = ["jobsCollection", "activitiesCollection", "jobsModelName", "activitiesModelName"];
2830
- const input = readRecord(options, [], keys, "invalid_config");
3102
+ var NAME_KEYS = ["jobsCollection", "activitiesCollection", "jobsModelName", "activitiesModelName"];
3103
+ function readStoreConfig(options) {
3104
+ const input = readRecord(options, [], [...NAME_KEYS, "smtpCapacity"], "invalid_config");
3105
+ const capacity = readCapacityOption(input);
3106
+ if (capacity) {
3107
+ if (NAME_KEYS.some((key) => Object.hasOwn(input, key))) invalid("invalid_config");
3108
+ const { namespace } = capacity.binding;
3109
+ const prefix = `email_smtp_v2.${namespace}`;
3110
+ const modelId = namespace.replaceAll("-", "_");
3111
+ const names2 = Object.freeze({
3112
+ jobsCollection: `${prefix}.jobs`,
3113
+ activitiesCollection: `${prefix}.activities`,
3114
+ jobsModelName: `EmailSmtpV2Job_${modelId}`,
3115
+ activitiesModelName: `EmailSmtpV2Activity_${modelId}`
3116
+ });
3117
+ return { names: names2, capacity };
3118
+ }
2831
3119
  const names = { ...MONGOOSE_DEFAULT_NAMES };
2832
- for (const key of keys) {
3120
+ for (const key of NAME_KEYS) {
2833
3121
  const value = input[key];
2834
3122
  if (value === void 0) continue;
2835
3123
  if (typeof value !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(value)) invalid("invalid_config");
@@ -2837,18 +3125,18 @@ function readNames(options) {
2837
3125
  }
2838
3126
  if (names.jobsCollection === names.activitiesCollection || names.jobsModelName === names.activitiesModelName)
2839
3127
  invalid("invalid_config");
2840
- return Object.freeze(names);
3128
+ return { names: Object.freeze(names), capacity };
2841
3129
  }
2842
3130
  function createMongooseEmailStore(connection, options = {}) {
2843
3131
  checkConnectionType(connection);
2844
- const names = readNames(options);
3132
+ const { names, capacity } = readStoreConfig(options);
2845
3133
  const io = new MongoConnection(connection, names);
2846
3134
  let readyBinding;
2847
3135
  let preparing = false;
2848
3136
  let inFlight = 0;
2849
3137
  async function run(call, worker, fn) {
2850
- const { signal, timeoutMs } = readStoreCall(call, worker);
2851
- if (inFlight >= MAX_IN_FLIGHT) invalid("busy");
3138
+ const { signal, timeoutMs } = readStoreCall(call, worker, capacity);
3139
+ if (inFlight >= (capacity?.limits.mongoInFlight ?? MAX_IN_FLIGHT)) invalid("busy");
2852
3140
  const budget = createBudget(systemEmailClock, Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS), signal);
2853
3141
  inFlight++;
2854
3142
  try {
@@ -2856,13 +3144,14 @@ function createMongooseEmailStore(connection, options = {}) {
2856
3144
  if (!readyBinding) invalid("store_unavailable");
2857
3145
  const binding = io.bind();
2858
3146
  if (binding.client !== readyBinding.client || binding.db !== readyBinding.db) invalid("store_unavailable");
2859
- return await fn(new MongoOperations(io, binding, budget, names));
3147
+ return await fn(new MongoOperations(io, binding, budget, names, capacity));
2860
3148
  } finally {
2861
3149
  inFlight--;
2862
3150
  budget.close();
2863
3151
  }
2864
3152
  }
2865
3153
  const store = {
3154
+ ...capacityTag(capacity),
2866
3155
  async ready(options2 = {}) {
2867
3156
  const { timeoutMs, signal } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
2868
3157
  if (preparing || inFlight) invalid("busy");
@@ -2873,8 +3162,14 @@ function createMongooseEmailStore(connection, options = {}) {
2873
3162
  budget.check();
2874
3163
  const binding = io.bind();
2875
3164
  await io.verifyTopology(binding, budget);
2876
- await prepareCollection(io, binding, budget, jobSchema(names.jobsCollection));
2877
- await prepareCollection(io, binding, budget, activitySchema(names.activitiesCollection));
3165
+ const jobs = jobSchema(names.jobsCollection, capacity);
3166
+ const activities = activitySchema(names.activitiesCollection, capacity);
3167
+ if (capacity) {
3168
+ await checkExistingCollection(io, binding, budget, jobs);
3169
+ await checkExistingCollection(io, binding, budget, activities);
3170
+ }
3171
+ await prepareCollection(io, binding, budget, jobs);
3172
+ await prepareCollection(io, binding, budget, activities);
2878
3173
  const jobId = randomUUID2();
2879
3174
  const probe = { scope: "!readiness", jobId };
2880
3175
  for (const [find, filter, hint] of [
@@ -2885,7 +3180,7 @@ function createMongooseEmailStore(connection, options = {}) {
2885
3180
  await io.read(binding, budget, {
2886
3181
  find,
2887
3182
  filter,
2888
- hint,
3183
+ hint: indexName(hint, capacity),
2889
3184
  collation: SIMPLE,
2890
3185
  readConcern: { level: "linearizable" },
2891
3186
  singleBatch: true,
@@ -2911,10 +3206,10 @@ function createMongooseEmailStore(connection, options = {}) {
2911
3206
  },
2912
3207
  insert(scope2, input, call) {
2913
3208
  return run(call, false, async (ops) => {
2914
- const safe = readStoreAdmission(scopeToken(scope2), input);
3209
+ const safe = readStoreAdmission(scopeToken(scope2), input, capacity);
2915
3210
  if (await ops.byAdmission(scope2, safe.admissionKey)) return Object.freeze({ status: "duplicate" });
2916
3211
  if (await ops.byJob(scope2, safe.jobId)) invalid("invalid_command");
2917
- const job = newJob(safe, { now: await ops.now(), revision: randomUUID2() });
3212
+ const job = newJob(safe, { now: await ops.now(), revision: randomUUID2() }, capacity);
2918
3213
  const summary = jobSummary(job);
2919
3214
  return await ops.insert(job) === "inserted" ? Object.freeze({ status: "inserted", job: summary }) : Object.freeze({ status: "duplicate" });
2920
3215
  });
@@ -2930,13 +3225,13 @@ function createMongooseEmailStore(connection, options = {}) {
2930
3225
  const id = readStoreId(attemptId);
2931
3226
  const job = await ops.byJob(scopeToken(scope2), readStoreId(jobId));
2932
3227
  const commit = job?.attempts.find((entry) => entry.commit.attemptId === id)?.commit;
2933
- return commit ? copyCommit(commit) : null;
3228
+ return commit ? copyCommit(commit, capacity) : null;
2934
3229
  });
2935
3230
  },
2936
3231
  claimNext(scope2, input, call) {
2937
3232
  return run(call, true, (ops) => {
2938
3233
  const safe = readClaim(input);
2939
- return ops.next(scopeToken(scope2), "nextAt", (job, time2) => claimJob(job, safe, time2));
3234
+ return ops.claimNext(scopeToken(scope2), safe);
2940
3235
  });
2941
3236
  },
2942
3237
  renew(scope2, fence, leaseMs, call) {
@@ -2955,14 +3250,14 @@ function createMongooseEmailStore(connection, options = {}) {
2955
3250
  },
2956
3251
  finish(scope2, input, call) {
2957
3252
  return run(call, true, (ops) => {
2958
- const safe = readFinish(input);
2959
- return ops.point(scopeToken(scope2), safe.fence.jobId, (job, time2) => finishJob(job, safe, time2));
3253
+ const safe = readFinish(input, capacity);
3254
+ return ops.point(scopeToken(scope2), safe.fence.jobId, (job, time2) => finishJob(job, safe, time2, capacity));
2960
3255
  });
2961
3256
  },
2962
3257
  recoverNext(scope2, call) {
2963
3258
  return run(call, true, (ops) => {
2964
3259
  const operationId = randomUUID2();
2965
- return ops.next(scopeToken(scope2), "leaseEndsAt", (job, time2) => recoverJob(job, operationId, time2));
3260
+ return ops.next(scopeToken(scope2), "leaseEndsAt", (job, time2) => recoverJob(job, operationId, time2, capacity));
2966
3261
  });
2967
3262
  },
2968
3263
  expireNext(scope2, call) {
@@ -2971,7 +3266,11 @@ function createMongooseEmailStore(connection, options = {}) {
2971
3266
  cancel(scope2, jobId, call) {
2972
3267
  return run(call, false, async (ops) => {
2973
3268
  const operationId = randomUUID2();
2974
- return await ops.point(scopeToken(scope2), readStoreId(jobId), (job, time2) => cancelJob(job, operationId, time2)) ?? Object.freeze({ status: "not_found" });
3269
+ return await ops.point(
3270
+ scopeToken(scope2),
3271
+ readStoreId(jobId),
3272
+ (job, time2) => cancelJob(job, operationId, time2, capacity)
3273
+ ) ?? Object.freeze({ status: "not_found" });
2975
3274
  });
2976
3275
  },
2977
3276
  resolveUnknown(scope2, input, call) {
@@ -2981,11 +3280,15 @@ function createMongooseEmailStore(connection, options = {}) {
2981
3280
  });
2982
3281
  },
2983
3282
  reserveProjection(scope2, call) {
2984
- return run(call, false, (ops) => ops.next(scopeToken(scope2), "pendingAt", reserveJobProjection));
3283
+ return run(
3284
+ call,
3285
+ false,
3286
+ (ops) => ops.next(scopeToken(scope2), "pendingAt", (job, time2) => reserveJobProjection(job, time2, capacity))
3287
+ );
2985
3288
  },
2986
3289
  putActivity(scope2, input, call) {
2987
3290
  return run(call, false, async (ops) => {
2988
- const permit = readProjectionPermit(scopeToken(scope2), input);
3291
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
2989
3292
  const identity = activityKey(permit.activity);
2990
3293
  const job = await ops.byJob(scope2, identity.jobId);
2991
3294
  const activity = await ops.byActivity(identity);
@@ -2997,7 +3300,7 @@ function createMongooseEmailStore(connection, options = {}) {
2997
3300
  },
2998
3301
  ackProjection(scope2, input, call) {
2999
3302
  return run(call, false, async (ops) => {
3000
- const permit = readProjectionPermit(scopeToken(scope2), input);
3303
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
3001
3304
  const identity = activityKey(permit.activity);
3002
3305
  return await ops.point(
3003
3306
  scope2,
@@ -3007,7 +3310,7 @@ function createMongooseEmailStore(connection, options = {}) {
3007
3310
  });
3008
3311
  },
3009
3312
  listActivities(scope2, query, call) {
3010
- return run(call, false, (ops) => ops.list(readActivityCriteria(scopeToken(scope2), query)));
3313
+ return run(call, false, (ops) => ops.list(readActivityCriteria(scopeToken(scope2), query, capacity)));
3011
3314
  },
3012
3315
  cleanupNext(scope2, call) {
3013
3316
  return run(call, false, (ops) => ops.next(scopeToken(scope2), "nextCleanupAt", cleanupJob));