@web-ts-toolkit/email-service 0.72.0 → 0.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/smtp.js CHANGED
@@ -272,6 +272,12 @@ function opaqueToken(value, maxBytes, code) {
272
272
  function identifier(value, code) {
273
273
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
274
274
  }
275
+ function uuidV4(value, code) {
276
+ 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)) {
277
+ invalid(code);
278
+ }
279
+ return value;
280
+ }
275
281
  function hashToken(value, code) {
276
282
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
277
283
  return value;
@@ -285,9 +291,9 @@ function jsonKey(key, code) {
285
291
 
286
292
  // src/internal/canonical-json.ts
287
293
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
288
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
294
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
289
295
  let bytesLeft = maxBytes;
290
- let valuesLeft = limits.values;
296
+ let valuesLeft = limits2.values;
291
297
  const chunks = [];
292
298
  const ancestors = /* @__PURE__ */ new Set();
293
299
  function append(text, bytes = text.length) {
@@ -306,7 +312,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
306
312
  append(JSON.stringify(text), bytes);
307
313
  }
308
314
  function visit(value2, depth) {
309
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
315
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
310
316
  switch (typeof value2) {
311
317
  case "string":
312
318
  appendString(value2);
@@ -330,7 +336,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
330
336
  if (ancestors.has(value2)) invalid(code);
331
337
  ancestors.add(value2);
332
338
  try {
333
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
339
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
334
340
  if (isArray(value2, code)) {
335
341
  const length = denseArrayLength(value2, maxChildren, code);
336
342
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -370,6 +376,71 @@ function copyJsonObject(input, maxBytes, code) {
370
376
  function sha256(input) {
371
377
  return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
372
378
  }
379
+ function encodeEvidence(input, code, capacity) {
380
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
381
+ }
382
+
383
+ // src/internal/smtp-capacity.ts
384
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
385
+ var MAX_RECIPIENTS = 1e3;
386
+ var KIB = 1024;
387
+ var limits = Object.freeze({
388
+ snapshotBytes: 2 * KIB * KIB,
389
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
390
+ evidenceBytes: 64 * KIB,
391
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
392
+ jobBsonBytes: 4 * KIB * KIB,
393
+ activityBsonBytes: 128 * KIB,
394
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
395
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
396
+ servicePending: 4,
397
+ workerProfiles: 16,
398
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
399
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
400
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
401
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
402
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
403
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
404
+ mongoInFlight: 4,
405
+ dueCandidates: 4
406
+ });
407
+ function readBinding(input, code) {
408
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
409
+ if (format !== "smtp-v2") invalid(code);
410
+ return Object.freeze({
411
+ format,
412
+ namespace: uuidV4(namespace, code),
413
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
414
+ });
415
+ }
416
+ function readCapacityOption(raw) {
417
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
418
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
419
+ }
420
+ function capacityTag(capacity) {
421
+ return capacity ? { smtpCapacity: capacity.binding } : {};
422
+ }
423
+ function recipientLimit(capacity) {
424
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
425
+ }
426
+ function matchesBinding(input, capacity, code) {
427
+ const binding = readBinding(input, code);
428
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
429
+ invalid(code);
430
+ }
431
+ }
432
+ function assertCapacityTag(raw, capacity, code) {
433
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
434
+ if (capacity) {
435
+ if (!tagged) invalid(code);
436
+ matchesBinding(raw.smtpCapacity, capacity, code);
437
+ } else if (tagged) {
438
+ invalid(code);
439
+ }
440
+ }
441
+ function assertCapacityProvider(provider, capacity, code) {
442
+ if (capacity && provider.kind !== "smtp") invalid(code);
443
+ }
373
444
 
374
445
  // src/internal/attempt-codecs.ts
375
446
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -429,7 +500,7 @@ function readHint(input, reason, code) {
429
500
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
430
501
  });
431
502
  }
432
- function readAttemptResult(input, code = "invalid_command", projected = false) {
503
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
433
504
  const raw = readRecord(
434
505
  input,
435
506
  ["outcome", "retry", "stage", "reason"],
@@ -440,6 +511,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
440
511
  const [outcome, retry, stages, origin] = evidence[reason];
441
512
  const stage = stages.find((value) => value === raw.stage);
442
513
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
514
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
443
515
  const hasHint = Object.hasOwn(raw, "retryHint");
444
516
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
445
517
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -449,14 +521,22 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
449
521
  if (hasRecipients) {
450
522
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
451
523
  const seen = /* @__PURE__ */ new Set();
452
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
524
+ const limit = recipientLimit(capacity);
525
+ let previous = -1;
526
+ recipients = readArray(raw.recipients, limit, code, (value) => {
453
527
  const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
454
528
  if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
455
529
  if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
456
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
457
- const key = `${group}:${index}`;
458
- if (seen.has(key)) invalid(code);
459
- seen.add(key);
530
+ const index = integer(rawIndex, 0, limit - 1, code);
531
+ if (capacity) {
532
+ const position = recipientGroups.indexOf(group) * limit + index;
533
+ if (position <= previous) invalid(code);
534
+ previous = position;
535
+ } else {
536
+ const key = `${group}:${index}`;
537
+ if (seen.has(key)) invalid(code);
538
+ seen.add(key);
539
+ }
460
540
  return Object.freeze({ group, index, status });
461
541
  });
462
542
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
@@ -471,7 +551,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
471
551
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
472
552
  invalid(code);
473
553
  }
474
- return Object.freeze({
554
+ const result = Object.freeze({
475
555
  outcome,
476
556
  retry,
477
557
  stage,
@@ -481,6 +561,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
481
561
  ...typeof messageId === "string" ? { messageId } : {},
482
562
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
483
563
  });
564
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
565
+ return result;
484
566
  }
485
567
  function assertEvidenceContext(result, provider, attemptId, counts, code) {
486
568
  const { reason, stage, recipients, messageId } = result;
@@ -497,9 +579,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
497
579
  }
498
580
  }
499
581
  }
500
- function readProviderResult(input, provider, attemptId, envelope) {
582
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
501
583
  const code = "invalid_command";
502
- const result = readAttemptResult(input, code);
584
+ const result = readAttemptResult(input, code, false, capacity);
503
585
  const origin = evidence[result.reason][3];
504
586
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
505
587
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -649,7 +731,8 @@ function validateMailbox(input, code = SNAPSHOT) {
649
731
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
650
732
  });
651
733
  }
652
- function validateEnvelope(input, kind, code = SNAPSHOT) {
734
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
735
+ const limit = recipientLimit(capacity);
653
736
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
654
737
  const seen = /* @__PURE__ */ new Set();
655
738
  const recipient = (raw) => {
@@ -660,9 +743,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
660
743
  return mailbox;
661
744
  };
662
745
  const from = validateMailbox(envelope.from, code);
663
- const to = readArray(envelope.to, L.recipients, code, recipient);
664
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
665
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
746
+ const to = readArray(envelope.to, limit, code, recipient);
747
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
748
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
666
749
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
667
750
  return Object.freeze({
668
751
  from,
@@ -750,12 +833,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
750
833
  }
751
834
  return expiresAt;
752
835
  }
753
- function hashSnapshot(snapshot) {
836
+ function hashSnapshot(snapshot, capacity) {
754
837
  return sha256(
755
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
838
+ canonicalJson(
839
+ snapshot,
840
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
841
+ SNAPSHOT,
842
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
843
+ ).encoded
756
844
  );
757
845
  }
758
- function readSnapshot(input) {
846
+ function readSnapshot(input, capacity) {
759
847
  const dto = readRecord(
760
848
  input,
761
849
  [
@@ -770,17 +858,19 @@ function readSnapshot(input) {
770
858
  "attachments",
771
859
  "correlation"
772
860
  ],
773
- ["subject", "html", "text", "templateId", "data"],
861
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
774
862
  SNAPSHOT
775
863
  );
776
864
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
865
+ assertCapacityTag(dto, capacity, SNAPSHOT);
777
866
  const provider = validateProviderRef(dto.provider);
778
867
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
868
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
779
869
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
780
870
  const common = {
781
871
  version: EMAIL_FORMAT_VERSION,
782
872
  template: validateTemplateIdentity(dto.template),
783
- envelope: validateEnvelope(dto.envelope, provider.kind),
873
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
784
874
  preparedAt,
785
875
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
786
876
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -794,7 +884,7 @@ function readSnapshot(input) {
794
884
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
795
885
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
796
886
  });
797
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
887
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
798
888
  }
799
889
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
800
890
  return Object.freeze({
@@ -805,31 +895,28 @@ function readSnapshot(input) {
805
895
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
806
896
  });
807
897
  }
808
- function validateSnapshot(input) {
809
- const snapshot = readSnapshot(input);
810
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
898
+ function validateSnapshot(input, capacity) {
899
+ const snapshot = readSnapshot(input, capacity);
900
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
811
901
  }
812
902
 
813
903
  // src/internal/store-codecs.ts
814
904
  var REQUEST = "invalid_command";
815
905
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
816
906
  function readStoreId(value, code = REQUEST) {
817
- 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)) {
818
- invalid(code);
819
- }
820
- return value;
907
+ return uuidV4(value, code);
821
908
  }
822
909
 
823
910
  // src/internal/provider-preparation.ts
824
911
  function sameRef(a, b) {
825
912
  return a.resolverKey === b.resolverKey && a.id === b.id && a.version === b.version && a.filename === b.filename && a.contentType === b.contentType && a.byteLength === b.byteLength && a.sha256 === b.sha256;
826
913
  }
827
- function readProviderSubmission(input, ref) {
914
+ function readProviderSubmission(input, ref, capacity) {
828
915
  const code = "invalid_snapshot";
829
916
  const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
830
917
  const jobId = readStoreId(raw.jobId, code);
831
918
  const attemptId = readStoreId(raw.attemptId, code);
832
- const { snapshot } = validateSnapshot(raw.snapshot);
919
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
833
920
  if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
834
921
  invalid("provider_mismatch");
835
922
  }
@@ -957,7 +1044,8 @@ function readAuth(input) {
957
1044
  return Object.freeze({ user, pass });
958
1045
  }
959
1046
  function readSmtpConfig(input) {
960
- const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth"], CONFIG);
1047
+ const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth", "smtpCapacity"], CONFIG);
1048
+ const capacity = readCapacityOption(raw);
961
1049
  const ref = Object.freeze({ kind: "smtp", key: identifier(raw.key, CONFIG), mode: "live" });
962
1050
  const { tls } = raw;
963
1051
  if (tls !== "implicit" && tls !== "starttls") invalid(CONFIG);
@@ -972,7 +1060,17 @@ function readSmtpConfig(input) {
972
1060
  if (ca?.length === 0) invalid(CONFIG);
973
1061
  try {
974
1062
  const secureContext = (0, import_node_tls.createSecureContext)({ minVersion: SMTP_MIN_TLS_VERSION, ...ca ? { ca: [...ca] } : {} });
975
- return Object.freeze({ ref, host, port, tls, identity: servername ?? host, servername, secureContext, auth });
1063
+ return Object.freeze({
1064
+ ref,
1065
+ host,
1066
+ port,
1067
+ tls,
1068
+ identity: servername ?? host,
1069
+ servername,
1070
+ secureContext,
1071
+ auth,
1072
+ capacity
1073
+ });
976
1074
  } catch {
977
1075
  return invalid(CONFIG);
978
1076
  }
@@ -1410,11 +1508,12 @@ async function submitSmtp(config, message, call, resolverFactory) {
1410
1508
  // src/smtp.ts
1411
1509
  function createSmtpProvider(options) {
1412
1510
  const config = readSmtpConfig(options);
1413
- const { ref } = config;
1511
+ const { ref, capacity } = config;
1414
1512
  const provider = {
1415
1513
  ref,
1514
+ ...capacityTag(capacity),
1416
1515
  prepare(input) {
1417
- const prepared = readProviderSubmission(input, ref);
1516
+ const prepared = readProviderSubmission(input, ref, capacity);
1418
1517
  const {
1419
1518
  attemptId,
1420
1519
  snapshot: { envelope }
@@ -1428,13 +1527,14 @@ function createSmtpProvider(options) {
1428
1527
  message = void 0;
1429
1528
  const result = await submitSmtp(config, send, call);
1430
1529
  try {
1431
- return readProviderResult(result, ref, attemptId, envelope);
1530
+ return readProviderResult(result, ref, attemptId, envelope, capacity);
1432
1531
  } catch {
1433
1532
  return readProviderResult(
1434
1533
  { outcome: "unknown", retry: "never", stage: result.stage, reason: "transport_uncertain" },
1435
1534
  ref,
1436
1535
  attemptId,
1437
- envelope
1536
+ envelope,
1537
+ capacity
1438
1538
  );
1439
1539
  }
1440
1540
  }