@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/sendgrid.mjs CHANGED
@@ -236,6 +236,12 @@ function opaqueToken(value, maxBytes, code) {
236
236
  function identifier(value, code) {
237
237
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
238
238
  }
239
+ function uuidV4(value, code) {
240
+ if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
241
+ invalid(code);
242
+ }
243
+ return value;
244
+ }
239
245
  function hashToken(value, code) {
240
246
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
241
247
  return value;
@@ -249,9 +255,9 @@ function jsonKey(key, code) {
249
255
 
250
256
  // src/internal/canonical-json.ts
251
257
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
252
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
258
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
253
259
  let bytesLeft = maxBytes;
254
- let valuesLeft = limits.values;
260
+ let valuesLeft = limits2.values;
255
261
  const chunks = [];
256
262
  const ancestors = /* @__PURE__ */ new Set();
257
263
  function append(text, bytes = text.length) {
@@ -270,7 +276,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
270
276
  append(JSON.stringify(text), bytes);
271
277
  }
272
278
  function visit(value2, depth) {
273
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
279
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
274
280
  switch (typeof value2) {
275
281
  case "string":
276
282
  appendString(value2);
@@ -294,7 +300,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
294
300
  if (ancestors.has(value2)) invalid(code);
295
301
  ancestors.add(value2);
296
302
  try {
297
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
303
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
298
304
  if (isArray(value2, code)) {
299
305
  const length = denseArrayLength(value2, maxChildren, code);
300
306
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -334,6 +340,67 @@ function copyJsonObject(input, maxBytes, code) {
334
340
  function sha256(input) {
335
341
  return createHash("sha256").update(input).digest("hex");
336
342
  }
343
+ function encodeEvidence(input, code, capacity) {
344
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
345
+ }
346
+
347
+ // src/internal/smtp-capacity.ts
348
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
349
+ var MAX_SMTP_RECIPIENTS = 1e3;
350
+ var KIB = 1024;
351
+ var limits = Object.freeze({
352
+ snapshotBytes: 2 * KIB * KIB,
353
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
354
+ evidenceBytes: 64 * KIB,
355
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
356
+ jobBsonBytes: 4 * KIB * KIB,
357
+ activityBsonBytes: 128 * KIB,
358
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
359
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
360
+ servicePending: 4,
361
+ workerProfiles: 16,
362
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
363
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
364
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
365
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
366
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
367
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
368
+ mongoInFlight: 4,
369
+ dueCandidates: 4
370
+ });
371
+ function readBinding(input, code) {
372
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
373
+ if (format !== "smtp-v2") invalid(code);
374
+ return Object.freeze({
375
+ format,
376
+ namespace: uuidV4(namespace, code),
377
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
378
+ });
379
+ }
380
+ function capacityTag(capacity) {
381
+ return capacity ? { smtpCapacity: capacity.binding } : {};
382
+ }
383
+ function recipientLimit(capacity) {
384
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
385
+ }
386
+ function matchesBinding(input, capacity, code) {
387
+ const binding = readBinding(input, code);
388
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
389
+ invalid(code);
390
+ }
391
+ }
392
+ function assertCapacityTag(raw, capacity, code) {
393
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
394
+ if (capacity) {
395
+ if (!tagged) invalid(code);
396
+ matchesBinding(raw.smtpCapacity, capacity, code);
397
+ } else if (tagged) {
398
+ invalid(code);
399
+ }
400
+ }
401
+ function assertCapacityProvider(provider, capacity, code) {
402
+ if (capacity && provider.kind !== "smtp") invalid(code);
403
+ }
337
404
 
338
405
  // src/internal/attempt-codecs.ts
339
406
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -373,12 +440,33 @@ function readAttemptReason(value, code) {
373
440
  if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
374
441
  return value;
375
442
  }
443
+ var recipientGroups = ["to", "cc", "bcc"];
376
444
  function recipientCounts(envelope) {
377
445
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
378
446
  }
379
447
  function smtpMessageId(attemptId) {
380
448
  return `<${attemptId}@email.invalid>`;
381
449
  }
450
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
451
+ const seen = /* @__PURE__ */ new Set();
452
+ let previous = -1;
453
+ return readArray(input, limit, code, (value) => {
454
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
455
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
456
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
457
+ const index = integer(rawIndex, 0, limit - 1, code);
458
+ if (ordered) {
459
+ const position = recipientGroups.indexOf(group) * limit + index;
460
+ if (position <= previous) invalid(code);
461
+ previous = position;
462
+ } else {
463
+ const key = `${group}:${index}`;
464
+ if (seen.has(key)) invalid(code);
465
+ seen.add(key);
466
+ }
467
+ return Object.freeze({ group, index, status });
468
+ });
469
+ }
382
470
  function readHint(input, reason, code) {
383
471
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
384
472
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -392,7 +480,7 @@ function readHint(input, reason, code) {
392
480
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
393
481
  });
394
482
  }
395
- function readAttemptResult(input, code = "invalid_command", projected = false) {
483
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
396
484
  const raw = readRecord(
397
485
  input,
398
486
  ["outcome", "retry", "stage", "reason"],
@@ -403,6 +491,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
403
491
  const [outcome, retry, stages, origin] = evidence[reason];
404
492
  const stage = stages.find((value) => value === raw.stage);
405
493
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
494
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
406
495
  const hasHint = Object.hasOwn(raw, "retryHint");
407
496
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
408
497
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -411,16 +500,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
411
500
  let recipients;
412
501
  if (hasRecipients) {
413
502
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
414
- const seen = /* @__PURE__ */ new Set();
415
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
416
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
417
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
418
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
419
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
420
- const key = `${group}:${index}`;
421
- if (seen.has(key)) invalid(code);
422
- seen.add(key);
423
- return Object.freeze({ group, index, status });
503
+ recipients = readRecipientResults(raw.recipients, code, {
504
+ limit: recipientLimit(capacity),
505
+ allowAccepted: smtpSuccess,
506
+ ordered: Boolean(capacity)
424
507
  });
425
508
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
426
509
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -434,7 +517,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
434
517
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
435
518
  invalid(code);
436
519
  }
437
- return Object.freeze({
520
+ const result = Object.freeze({
438
521
  outcome,
439
522
  retry,
440
523
  stage,
@@ -444,6 +527,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
444
527
  ...typeof messageId === "string" ? { messageId } : {},
445
528
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
446
529
  });
530
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
531
+ return result;
447
532
  }
448
533
  function assertEvidenceContext(result, provider, attemptId, counts, code) {
449
534
  const { reason, stage, recipients, messageId } = result;
@@ -460,9 +545,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
460
545
  }
461
546
  }
462
547
  }
463
- function readProviderResult(input, provider, attemptId, envelope) {
548
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
464
549
  const code = "invalid_command";
465
- const result = readAttemptResult(input, code);
550
+ const result = readAttemptResult(input, code, false, capacity);
466
551
  const origin = evidence[result.reason][3];
467
552
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
468
553
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -612,7 +697,8 @@ function validateMailbox(input, code = SNAPSHOT) {
612
697
  ...Object.hasOwn(mailbox2, "name") ? { name: headerString(mailbox2.name, L.displayNameBytes, code) } : {}
613
698
  });
614
699
  }
615
- function validateEnvelope(input, kind, code = SNAPSHOT) {
700
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
701
+ const limit = recipientLimit(capacity);
616
702
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
617
703
  const seen = /* @__PURE__ */ new Set();
618
704
  const recipient = (raw) => {
@@ -623,9 +709,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
623
709
  return mailbox2;
624
710
  };
625
711
  const from = validateMailbox(envelope.from, code);
626
- const to = readArray(envelope.to, L.recipients, code, recipient);
627
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
628
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
712
+ const to = readArray(envelope.to, limit, code, recipient);
713
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
714
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
629
715
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
630
716
  return Object.freeze({
631
717
  from,
@@ -713,12 +799,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
713
799
  }
714
800
  return expiresAt;
715
801
  }
716
- function hashSnapshot(snapshot) {
802
+ function hashSnapshot(snapshot, capacity) {
717
803
  return sha256(
718
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
804
+ canonicalJson(
805
+ snapshot,
806
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
807
+ SNAPSHOT,
808
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
809
+ ).encoded
719
810
  );
720
811
  }
721
- function readSnapshot(input) {
812
+ function readSnapshot(input, capacity) {
722
813
  const dto = readRecord(
723
814
  input,
724
815
  [
@@ -733,17 +824,19 @@ function readSnapshot(input) {
733
824
  "attachments",
734
825
  "correlation"
735
826
  ],
736
- ["subject", "html", "text", "templateId", "data"],
827
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
737
828
  SNAPSHOT
738
829
  );
739
830
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
831
+ assertCapacityTag(dto, capacity, SNAPSHOT);
740
832
  const provider = validateProviderRef(dto.provider);
741
833
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
834
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
742
835
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
743
836
  const common = {
744
837
  version: EMAIL_FORMAT_VERSION,
745
838
  template: validateTemplateIdentity(dto.template),
746
- envelope: validateEnvelope(dto.envelope, provider.kind),
839
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
747
840
  preparedAt,
748
841
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
749
842
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -757,7 +850,7 @@ function readSnapshot(input) {
757
850
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
758
851
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
759
852
  });
760
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
853
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
761
854
  }
762
855
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
763
856
  return Object.freeze({
@@ -768,31 +861,28 @@ function readSnapshot(input) {
768
861
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
769
862
  });
770
863
  }
771
- function validateSnapshot(input) {
772
- const snapshot = readSnapshot(input);
773
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
864
+ function validateSnapshot(input, capacity) {
865
+ const snapshot = readSnapshot(input, capacity);
866
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
774
867
  }
775
868
 
776
869
  // src/internal/store-codecs.ts
777
870
  var REQUEST = "invalid_command";
778
871
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
779
872
  function readStoreId(value, code = REQUEST) {
780
- 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)) {
781
- invalid(code);
782
- }
783
- return value;
873
+ return uuidV4(value, code);
784
874
  }
785
875
 
786
876
  // src/internal/provider-preparation.ts
787
877
  function sameRef(a, b) {
788
878
  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;
789
879
  }
790
- function readProviderSubmission(input, ref) {
880
+ function readProviderSubmission(input, ref, capacity) {
791
881
  const code = "invalid_snapshot";
792
882
  const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
793
883
  const jobId = readStoreId(raw.jobId, code);
794
884
  const attemptId = readStoreId(raw.attemptId, code);
795
- const { snapshot } = validateSnapshot(raw.snapshot);
885
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
796
886
  if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
797
887
  invalid("provider_mismatch");
798
888
  }
@@ -872,11 +962,9 @@ function retryHint(after, reset, now) {
872
962
  const delayMs = after !== void 0 && SECONDS.test(after) ? secondsMs(after) : void 0;
873
963
  const date = after !== void 0 && delayMs === void 0 ? httpDate(after, now) : void 0;
874
964
  const resetMs = reset !== void 0 && SECONDS.test(reset) ? secondsMs(reset) : void 0;
875
- if (delayMs === void 0 && date === void 0 && resetMs === void 0) return;
876
- return {
877
- ...delayMs === void 0 ? {} : { delayMs },
878
- ...date === void 0 && resetMs === void 0 ? {} : { notBefore: Math.max(date ?? 0, resetMs ?? 0) }
879
- };
965
+ const notBefore = date === void 0 && resetMs === void 0 ? void 0 : Math.max(date ?? 0, resetMs ?? 0);
966
+ if (delayMs !== void 0) return notBefore === void 0 ? { delayMs } : { delayMs, notBefore };
967
+ if (notBefore !== void 0) return { notBefore };
880
968
  }
881
969
 
882
970
  // src/providers/sendgrid/response.ts
package/smtp.d.mts CHANGED
@@ -1,14 +1,19 @@
1
- import { o as EmailProvider, y as SmtpSnapshot } from './provider-HisBc6hk.mjs';
1
+ import { S as SmtpCapacity, p as EmailProvider, z as SmtpSnapshot } from './provider-CeUryYAf.mjs';
2
2
 
3
3
  /** Configuration for a direct, unpooled ESMTP connection with verified TLS 1.2 or newer. */
4
4
  type SmtpProviderOptions = {
5
5
  key: string;
6
+ /** Must match the prepared snapshot and worker for opted-in messages. Omit for the V1 cap of 50. */
7
+ smtpCapacity?: SmtpCapacity;
6
8
  /** ASCII DNS hostname or IP literal, without a URL, port or IPv6 brackets. */
7
9
  host: string;
8
10
  /** Defaults to 465 for implicit TLS or 587 for required STARTTLS. */
9
11
  port?: number;
10
12
  tls: 'implicit' | 'starttls';
11
- /** Optional DNS name for SNI and certificate verification. Otherwise verify `host`, including IP SANs. */
13
+ /**
14
+ * Optional DNS name for TLS SNI and server certificate verification. Otherwise verify `host`,
15
+ * including IP SANs. This does not change the fixed `EHLO email.invalid` client greeting.
16
+ */
12
17
  servername?: string;
13
18
  /** PEM CA certificates (one per entry). Replaces the default Node trust roots when provided. */
14
19
  ca?: readonly string[];
package/smtp.d.ts CHANGED
@@ -1,14 +1,19 @@
1
- import { o as EmailProvider, y as SmtpSnapshot } from './provider-HisBc6hk.js';
1
+ import { S as SmtpCapacity, p as EmailProvider, z as SmtpSnapshot } from './provider-CeUryYAf.js';
2
2
 
3
3
  /** Configuration for a direct, unpooled ESMTP connection with verified TLS 1.2 or newer. */
4
4
  type SmtpProviderOptions = {
5
5
  key: string;
6
+ /** Must match the prepared snapshot and worker for opted-in messages. Omit for the V1 cap of 50. */
7
+ smtpCapacity?: SmtpCapacity;
6
8
  /** ASCII DNS hostname or IP literal, without a URL, port or IPv6 brackets. */
7
9
  host: string;
8
10
  /** Defaults to 465 for implicit TLS or 587 for required STARTTLS. */
9
11
  port?: number;
10
12
  tls: 'implicit' | 'starttls';
11
- /** Optional DNS name for SNI and certificate verification. Otherwise verify `host`, including IP SANs. */
13
+ /**
14
+ * Optional DNS name for TLS SNI and server certificate verification. Otherwise verify `host`,
15
+ * including IP SANs. This does not change the fixed `EHLO email.invalid` client greeting.
16
+ */
12
17
  servername?: string;
13
18
  /** PEM CA certificates (one per entry). Replaces the default Node trust roots when provided. */
14
19
  ca?: readonly string[];