@web-ts-toolkit/email-service 0.73.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/index.mjs CHANGED
@@ -682,7 +682,7 @@ import { types as types4 } from "util";
682
682
 
683
683
  // src/internal/smtp-capacity.ts
684
684
  var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
685
- var MAX_RECIPIENTS = 1e3;
685
+ var MAX_SMTP_RECIPIENTS = 1e3;
686
686
  var KIB = 1024;
687
687
  var limits = Object.freeze({
688
688
  snapshotBytes: 2 * KIB * KIB,
@@ -710,7 +710,7 @@ function readBinding(input, code) {
710
710
  return Object.freeze({
711
711
  format,
712
712
  namespace: uuidV4(namespace, code),
713
- maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
713
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
714
714
  });
715
715
  }
716
716
  function readCapacityOption(raw) {
@@ -1058,6 +1058,11 @@ function validatePreparedCommand(scope, input, capacity) {
1058
1058
  });
1059
1059
  }
1060
1060
 
1061
+ // src/internal/smtp-attachments.ts
1062
+ function assertSmtpAttachmentTypes(refs) {
1063
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
1064
+ }
1065
+
1061
1066
  // src/templates/local-sources.ts
1062
1067
  import { Buffer as Buffer2 } from "buffer";
1063
1068
  import { addAbortListener as addAbortListener3 } from "events";
@@ -1310,6 +1315,7 @@ function captureFields(raw, definition, context, scheduleAt, budget, slot, capac
1310
1315
  );
1311
1316
  const priority = boundedOption(fields.priority, PRIORITY, code);
1312
1317
  const attachments = validateAttachmentRefs(fields.attachments === void 0 ? [] : fields.attachments);
1318
+ if (context.provider.kind === "smtp") assertSmtpAttachmentTypes(attachments);
1313
1319
  const correlation = validateCorrelation(fields.correlation === void 0 ? {} : fields.correlation);
1314
1320
  const values = copyJsonObject(fields.values, MESSAGE_LIMITS.dataBytes, "invalid_data");
1315
1321
  const { parseData } = definition;
@@ -1497,6 +1503,57 @@ function readRecipientCounts(input, code, capacity) {
1497
1503
  function smtpMessageId(attemptId) {
1498
1504
  return `<${attemptId}@email.invalid>`;
1499
1505
  }
1506
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
1507
+ const seen = /* @__PURE__ */ new Set();
1508
+ let previous = -1;
1509
+ return readArray(input, limit, code, (value) => {
1510
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1511
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1512
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
1513
+ const index = integer(rawIndex, 0, limit - 1, code);
1514
+ if (ordered) {
1515
+ const position = recipientGroups.indexOf(group) * limit + index;
1516
+ if (position <= previous) invalid(code);
1517
+ previous = position;
1518
+ } else {
1519
+ const key = `${group}:${index}`;
1520
+ if (seen.has(key)) invalid(code);
1521
+ seen.add(key);
1522
+ }
1523
+ return Object.freeze({ group, index, status });
1524
+ });
1525
+ }
1526
+ function allAccepted(recipients) {
1527
+ return recipients.length !== 0 && recipients.every(({ status }) => status === "accepted");
1528
+ }
1529
+ function createSmtpAcceptanceResult(recipients, messageId) {
1530
+ const code = "invalid_command";
1531
+ if (messageId !== void 0 && (typeof messageId !== "string" || messageId.length !== 52 || messageId !== smtpMessageId(uuidV4(messageId.slice(1, 37), code)))) {
1532
+ invalid(code);
1533
+ }
1534
+ const checked = readRecipientResults(recipients, code, {
1535
+ limit: MAX_SMTP_RECIPIENTS,
1536
+ allowAccepted: true,
1537
+ ordered: false
1538
+ });
1539
+ const data = { retry: "never", stage: "data", ...messageId === void 0 ? {} : { messageId } };
1540
+ if (allAccepted(checked)) {
1541
+ return Object.freeze({ ...data, reason: "smtp_accepted", outcome: "accepted", recipients: checked });
1542
+ }
1543
+ if (!checked.some(({ status }) => status === "accepted")) invalid(code);
1544
+ return Object.freeze({
1545
+ ...data,
1546
+ reason: "smtp_partial",
1547
+ outcome: "partially_accepted",
1548
+ recipients: checked
1549
+ });
1550
+ }
1551
+ function uncertainProviderResult(stage, reason) {
1552
+ const base = { outcome: "unknown", retry: "never", stage };
1553
+ if (reason === "provider_timeout") return { ...base, reason };
1554
+ if (reason === "provider_aborted") return { ...base, reason };
1555
+ return { ...base, reason };
1556
+ }
1500
1557
  function readHint(input, reason, code) {
1501
1558
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
1502
1559
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -1530,24 +1587,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false, c
1530
1587
  let recipients;
1531
1588
  if (hasRecipients) {
1532
1589
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
1533
- const seen = /* @__PURE__ */ new Set();
1534
- const limit = recipientLimit(capacity);
1535
- let previous = -1;
1536
- recipients = readArray(raw.recipients, limit, code, (value) => {
1537
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1538
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1539
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
1540
- const index = integer(rawIndex, 0, limit - 1, code);
1541
- if (capacity) {
1542
- const position = recipientGroups.indexOf(group) * limit + index;
1543
- if (position <= previous) invalid(code);
1544
- previous = position;
1545
- } else {
1546
- const key = `${group}:${index}`;
1547
- if (seen.has(key)) invalid(code);
1548
- seen.add(key);
1549
- }
1550
- return Object.freeze({ group, index, status });
1590
+ recipients = readRecipientResults(raw.recipients, code, {
1591
+ limit: recipientLimit(capacity),
1592
+ allowAccepted: smtpSuccess,
1593
+ ordered: Boolean(capacity)
1551
1594
  });
1552
1595
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
1553
1596
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -1658,7 +1701,7 @@ function readStoreCall(input, worker = false, capacity) {
1658
1701
  timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1659
1702
  };
1660
1703
  }
1661
- function readStoreNext(value, read) {
1704
+ function readStoreNext(value, read, kind) {
1662
1705
  const code = "store_incompatible";
1663
1706
  const raw = readRecord(value, ["status"], ["value"], code);
1664
1707
  if (raw.status === "applied" && Object.hasOwn(raw, "value")) {
@@ -1667,6 +1710,9 @@ function readStoreNext(value, read) {
1667
1710
  if ((raw.status === "none" || raw.status === "contended") && !Object.hasOwn(raw, "value")) {
1668
1711
  return Object.freeze({ status: raw.status });
1669
1712
  }
1713
+ if (kind === "claim" && raw.status === "expiry_maintenance_required" && !Object.hasOwn(raw, "value")) {
1714
+ return Object.freeze({ status: raw.status });
1715
+ }
1670
1716
  return invalid(code);
1671
1717
  }
1672
1718
  function readRetryPolicy(input, code = REQUEST) {
@@ -2183,24 +2229,22 @@ var serviceAdmissions = /* @__PURE__ */ new WeakMap();
2183
2229
  function findServiceAdmission(service) {
2184
2230
  return serviceAdmissions.get(service);
2185
2231
  }
2232
+ function createEmailRelay(options) {
2233
+ const raw = readRecord(options, ["scope", "store"], ["retry", "retention", "smtpCapacity"], CONFIG);
2234
+ const { enqueuePrepared } = createAdmissionCore(raw, systemEmailClock);
2235
+ return Object.freeze({ enqueuePrepared });
2236
+ }
2186
2237
  function createEmailService(options) {
2187
2238
  return createEmailServiceWithClock(options, systemEmailClock);
2188
2239
  }
2189
2240
  function createEmailServiceWithClock(options, clock) {
2190
2241
  const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention", "smtpCapacity"], CONFIG);
2191
- const capacity = readCapacityOption(raw);
2192
- assertPortCapacity(raw.store, capacity);
2242
+ const { scope, capacity, enqueuePrepared, admitParsed, inOperation, withAdmission } = createAdmissionCore(raw, clock);
2193
2243
  assertPortCapacity(raw.registry, capacity);
2194
- const scope = scopeToken(raw.scope, CONFIG);
2195
- const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2196
- const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
2197
- const find = bindMethod(raw.store, "findAdmission");
2198
- const insert = bindMethod(raw.store, "insert");
2199
2244
  if (typeof raw.registry !== "object" || raw.registry === null || types6.isProxy(raw.registry)) invalid(CONFIG);
2200
2245
  const registry = raw.registry;
2201
2246
  const prepare = bindMethod(registry, "prepare");
2202
2247
  const internalPrepare = findRegistryPreparation(registry);
2203
- let admissions = 0;
2204
2248
  async function prepareMiss(parsed, parent) {
2205
2249
  const { identity, command } = parsed;
2206
2250
  const accept = (value) => {
@@ -2260,6 +2304,27 @@ function createEmailServiceWithClock(options, clock) {
2260
2304
  slot.close();
2261
2305
  }
2262
2306
  }
2307
+ const enqueueParsed = (parsed, budget) => admitParsed(parsed, budget, prepareMiss);
2308
+ const service = Object.freeze({
2309
+ scope,
2310
+ ...capacityTag(capacity),
2311
+ enqueue(command, call = {}) {
2312
+ return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2313
+ },
2314
+ enqueuePrepared
2315
+ });
2316
+ serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2317
+ return service;
2318
+ }
2319
+ function createAdmissionCore(raw, clock) {
2320
+ const capacity = readCapacityOption(raw);
2321
+ assertPortCapacity(raw.store, capacity);
2322
+ const scope = scopeToken(raw.scope, CONFIG);
2323
+ const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2324
+ const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
2325
+ const find = bindMethod(raw.store, "findAdmission");
2326
+ const insert = bindMethod(raw.store, "insert");
2327
+ let admissions = 0;
2263
2328
  function findWinner(key, budget) {
2264
2329
  return runStoreCall(clock, budget, {
2265
2330
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
@@ -2283,6 +2348,7 @@ function createEmailServiceWithClock(options, clock) {
2283
2348
  }
2284
2349
  async function insertOrConfirm(command, identity, budget) {
2285
2350
  budget.check();
2351
+ if (command.snapshot.kind === "smtp") assertSmtpAttachmentTypes(command.snapshot.attachments);
2286
2352
  const admission = Object.freeze({ command, jobId: randomUUID(), retry, retention });
2287
2353
  try {
2288
2354
  const job = await runStoreCall(clock, budget, {
@@ -2315,7 +2381,7 @@ function createEmailServiceWithClock(options, clock) {
2315
2381
  }
2316
2382
  return invalid("write_unconfirmed");
2317
2383
  }
2318
- async function enqueueParsed(parsed, budget) {
2384
+ async function admitParsed(parsed, budget, prepareMiss) {
2319
2385
  if (parsed.identity.scope !== scope) invalid("invalid_command");
2320
2386
  const winner = await findWinner(parsed.identity.key, budget);
2321
2387
  if (winner) return replay(winner, parsed.identity);
@@ -2343,31 +2409,23 @@ function createEmailServiceWithClock(options, clock) {
2343
2409
  }
2344
2410
  });
2345
2411
  }
2346
- const service = Object.freeze({
2347
- scope,
2348
- ...capacityTag(capacity),
2349
- enqueue(command, call = {}) {
2350
- return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2351
- },
2352
- enqueuePrepared(input, call = {}) {
2353
- return inOperation(call, async (budget) => {
2354
- const command = validatePreparedCommand(scope, input, capacity);
2355
- const identity = {
2356
- scope,
2357
- key: command.key,
2358
- templateKey: command.snapshot.template.key,
2359
- provider: command.snapshot.provider,
2360
- scheduleAt: command.scheduleAt,
2361
- intentHash: command.intentHash,
2362
- fingerprint: command.fingerprint
2363
- };
2364
- const winner = await findWinner(identity.key, budget);
2365
- return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
2366
- });
2367
- }
2368
- });
2369
- serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2370
- return service;
2412
+ function enqueuePrepared(input, call = {}) {
2413
+ return inOperation(call, async (budget) => {
2414
+ const command = validatePreparedCommand(scope, input, capacity);
2415
+ const identity = {
2416
+ scope,
2417
+ key: command.key,
2418
+ templateKey: command.snapshot.template.key,
2419
+ provider: command.snapshot.provider,
2420
+ scheduleAt: command.scheduleAt,
2421
+ intentHash: command.intentHash,
2422
+ fingerprint: command.fingerprint
2423
+ };
2424
+ const winner = await findWinner(identity.key, budget);
2425
+ return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
2426
+ });
2427
+ }
2428
+ return { scope, capacity, enqueuePrepared, admitParsed, inOperation, withAdmission };
2371
2429
  }
2372
2430
  function readPolicy(input, defaults) {
2373
2431
  const result = { ...defaults };
@@ -2420,7 +2478,7 @@ function readProfiles(input, capacity) {
2420
2478
  if (profiles.has(ref.key)) invalid(CONFIG2);
2421
2479
  profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
2422
2480
  });
2423
- if (capacity && profiles.size === 0) invalid(CONFIG2);
2481
+ if (profiles.size === 0) invalid(CONFIG2);
2424
2482
  return profiles;
2425
2483
  }
2426
2484
  function readResolvers(input) {
@@ -2905,7 +2963,7 @@ async function launch(run, owner, mark, submit, preflight) {
2905
2963
  mark.dispatchedAt + (expiresAt - mark.grant.handoffAt) - CLOCK_MARGIN_MS
2906
2964
  );
2907
2965
  const stage = provider.kind === "smtp" ? "data" : "http";
2908
- const unknown = (reason) => Object.freeze({ outcome: "unknown", retry: "never", stage, reason });
2966
+ const unknown = (reason) => Object.freeze(uncertainProviderResult(stage, reason));
2909
2967
  let io;
2910
2968
  try {
2911
2969
  run.checkLaunch();
@@ -3137,10 +3195,14 @@ function claimNext(run) {
3137
3195
  dispatchedAt = start;
3138
3196
  return store.claimNext(scope, request, call);
3139
3197
  },
3140
- accept: (value) => readStoreNext(value, (raw) => {
3141
- const claim = readClaimed(raw, scope, request, capacity);
3142
- return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
3143
- })
3198
+ accept: (value) => readStoreNext(
3199
+ value,
3200
+ (raw) => {
3201
+ const claim = readClaimed(raw, scope, request, capacity);
3202
+ return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
3203
+ },
3204
+ "claim"
3205
+ )
3144
3206
  });
3145
3207
  }
3146
3208
  async function drainClaims(run, options, items, slots) {
@@ -3176,7 +3238,7 @@ async function drainClaims(run, options, items, slots) {
3176
3238
  }
3177
3239
  if (next.status !== "applied") {
3178
3240
  slot.close();
3179
- stop = next.status === "contended" ? "contended" : "idle";
3241
+ stop = next.status === "none" ? "idle" : next.status;
3180
3242
  break;
3181
3243
  }
3182
3244
  const { claim } = next.value;
@@ -3253,7 +3315,8 @@ async function runQueue(run, options, slots, shutdown) {
3253
3315
  else if (allowedErrorCode(run.budget.signal.reason, ["deadline"])) stop = "deadline";
3254
3316
  else if (run.persistenceFailures) stop = "store_error";
3255
3317
  else if (run.budget.signal.aborted) return invalid("invalid_config");
3256
- else if (queueStop !== "contended" && slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
3318
+ else if (queueStop === "contended" || queueStop === "expiry_maintenance_required") stop = queueStop;
3319
+ else if (slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
3257
3320
  else if (queueStop === "idle" && timeLeft < 1)
3258
3321
  stop = "deadline";
3259
3322
  else stop = queueStop;
@@ -3369,10 +3432,17 @@ function readAdmissionResult(input, identity, capacity) {
3369
3432
  if (!matchesAdmissionJob(job, identity, status)) invalid(code);
3370
3433
  return { status, job };
3371
3434
  }
3372
- function createEmailBatchService(options) {
3373
- return createEmailBatchServiceWithClock(options, systemEmailClock);
3435
+ function createEmailBatchAdmission(options) {
3436
+ return createEmailBatchAdmissionWithClock(options, systemEmailClock);
3437
+ }
3438
+ function createEmailBatchAdmissionWithClock(options, clock) {
3439
+ const raw = readRecord(options, ["service"], ["smtpCapacity"], "invalid_config");
3440
+ const { service } = raw;
3441
+ const capacity = readCapacityOption(raw);
3442
+ assertPortCapacity(service, capacity);
3443
+ return createBatchAdmission(service, boundScope(service), capacity, clock);
3374
3444
  }
3375
- function createEmailBatchServiceWithClock(options, clock) {
3445
+ function createEmailBatchService(options) {
3376
3446
  const raw = readRecord(options, ["service", "worker"], ["smtpCapacity"], "invalid_config");
3377
3447
  const { service, worker } = raw;
3378
3448
  const capacity = readCapacityOption(raw);
@@ -3381,6 +3451,18 @@ function createEmailBatchServiceWithClock(options, clock) {
3381
3451
  const scope = boundScope(service);
3382
3452
  if (scope !== boundScope(worker)) invalid("invalid_config");
3383
3453
  const run = bindMethod(worker, "run");
3454
+ const { enqueueBatch } = createBatchAdmission(service, scope, capacity, systemEmailClock);
3455
+ const batch = {
3456
+ enqueueBatch,
3457
+ async run(options2) {
3458
+ if (boundScope(worker) !== scope) invalid("invalid_config");
3459
+ assertPortCapacity(worker, capacity);
3460
+ return run(options2);
3461
+ }
3462
+ };
3463
+ return Object.freeze(batch);
3464
+ }
3465
+ function createBatchAdmission(service, scope, capacity, clock) {
3384
3466
  const enqueue = bindMethod(service, "enqueue");
3385
3467
  const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
3386
3468
  if (boundScope(service) !== scope) invalid("invalid_config");
@@ -3388,10 +3470,10 @@ function createEmailBatchServiceWithClock(options, clock) {
3388
3470
  const bounds = CALL_BUDGETS.admissionOrAdmin;
3389
3471
  const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
3390
3472
  budget.check();
3391
- let raw2;
3473
+ let raw;
3392
3474
  try {
3393
3475
  const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
3394
- raw2 = types8.isPromise(pending) ? await pending : pending;
3476
+ raw = types8.isPromise(pending) ? await pending : pending;
3395
3477
  } catch (error) {
3396
3478
  if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
3397
3479
  invalid("deadline");
@@ -3399,7 +3481,7 @@ function createEmailBatchServiceWithClock(options, clock) {
3399
3481
  throw error;
3400
3482
  }
3401
3483
  try {
3402
- return readAdmissionResult(raw2, identity, capacity);
3484
+ return readAdmissionResult(raw, identity, capacity);
3403
3485
  } catch {
3404
3486
  return invalid("write_unconfirmed");
3405
3487
  }
@@ -3437,11 +3519,6 @@ function createEmailBatchServiceWithClock(options, clock) {
3437
3519
  admitting = false;
3438
3520
  budget.close();
3439
3521
  }
3440
- },
3441
- async run(options2) {
3442
- if (boundScope(worker) !== scope) invalid("invalid_config");
3443
- assertPortCapacity(worker, capacity);
3444
- return run(options2);
3445
3522
  }
3446
3523
  };
3447
3524
  return Object.freeze(batch);
@@ -3806,6 +3883,7 @@ function newJob(admission, time, capacity) {
3806
3883
  if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
3807
3884
  const nextAt = Math.max(now, scheduleAt ?? now);
3808
3885
  if (nextAt >= snapshot.expiresAt) invalid("expired");
3886
+ if (snapshot.kind === "smtp") assertSmtpAttachmentTypes(snapshot.attachments);
3809
3887
  return Object.freeze({
3810
3888
  version: EMAIL_FORMAT_VERSION,
3811
3889
  ...capacityTag(capacity),
@@ -3848,9 +3926,13 @@ function liveLease(job, fence, phase, now) {
3848
3926
  }
3849
3927
  return lease;
3850
3928
  }
3929
+ function claimEligibility(job, now) {
3930
+ if (job.state.state !== "queued" || job.state.nextAt > now) return "not_due";
3931
+ return now >= job.expiresAt ? "expired" : "eligible";
3932
+ }
3851
3933
  function claimJob(job, claim, time, capacity) {
3852
3934
  const { now } = time;
3853
- if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
3935
+ if (claimEligibility(job, now) !== "eligible") return null;
3854
3936
  const manual = hasRedrive(job);
3855
3937
  const ordinal = job.attempts.length + 1;
3856
3938
  if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
@@ -3878,6 +3960,20 @@ function claimJob(job, claim, time, capacity) {
3878
3960
  Math.min(job.expiresAt, lease.leaseEndsAt)
3879
3961
  );
3880
3962
  }
3963
+ var EXPIRY_MAINTENANCE_REQUIRED = Object.freeze({ status: "expiry_maintenance_required" });
3964
+ function claimWindow(claim, candidateLimit, capacity) {
3965
+ let expired = 0;
3966
+ return {
3967
+ decide(job, time) {
3968
+ const decision = claimJob(job, claim, time, capacity);
3969
+ if (decision === null && claimEligibility(job, time.now) === "expired") expired++;
3970
+ return decision;
3971
+ },
3972
+ result(next) {
3973
+ return next.status !== "applied" && expired === candidateLimit ? EXPIRY_MAINTENANCE_REQUIRED : next;
3974
+ }
3975
+ };
3976
+ }
3881
3977
  function renewJob(job, fence, leaseMs, time) {
3882
3978
  const lease = liveLease(job, fence, "pre_handoff", time.now);
3883
3979
  if (!lease || time.now >= job.expiresAt) return null;
@@ -4366,8 +4462,8 @@ function createMemoryEmailStore(options = {}) {
4366
4462
  },
4367
4463
  async claimNext(scope, claim, call) {
4368
4464
  return primitive(call, true, (check) => {
4369
- const safe = readClaim(claim);
4370
- return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time, capacity));
4465
+ const window = claimWindow(readClaim(claim), MAX_STORE_CANDIDATES, capacity);
4466
+ return window.result(next(scope, "nextAt", check, window.decide));
4371
4467
  });
4372
4468
  },
4373
4469
  async renew(scope, fence, leaseMs, call) {
@@ -4467,11 +4563,14 @@ function createMemoryEmailStore(options = {}) {
4467
4563
  export {
4468
4564
  EmailError,
4469
4565
  createEmailAdmin,
4566
+ createEmailBatchAdmission,
4470
4567
  createEmailBatchService,
4568
+ createEmailRelay,
4471
4569
  createEmailService,
4472
4570
  createEmailTemplateRegistry,
4473
4571
  createEmailWorker,
4474
4572
  createMemoryEmailStore,
4573
+ createSmtpAcceptanceResult,
4475
4574
  defineLocalTemplate,
4476
4575
  defineSendGridTemplate
4477
4576
  };
package/mongoose.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Connection } from 'mongoose';
2
- import { S as SmtpCapacity } from './provider-DC_av0SQ.mjs';
3
- import { d as EmailStore } from './store-DlABKTjt.mjs';
2
+ import { S as SmtpCapacity } from './provider-CeUryYAf.mjs';
3
+ import { d as EmailStore } from './store-DjCqXbPv.mjs';
4
4
 
5
5
  /** Store on a caller-owned connection. Name overrides are V1-only and use ASCII letters, numbers and `_`. */
6
6
  type MongooseEmailStoreOptions = {
package/mongoose.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Connection } from 'mongoose';
2
- import { S as SmtpCapacity } from './provider-DC_av0SQ.js';
3
- import { d as EmailStore } from './store-Bi5iZ910.js';
2
+ import { S as SmtpCapacity } from './provider-CeUryYAf.js';
3
+ import { d as EmailStore } from './store-CFasgH3C.js';
4
4
 
5
5
  /** Store on a caller-owned connection. Name overrides are V1-only and use ASCII letters, numbers and `_`. */
6
6
  type MongooseEmailStoreOptions = {
package/mongoose.js CHANGED
@@ -388,7 +388,7 @@ function encodeEvidence(input, code, capacity) {
388
388
 
389
389
  // src/internal/smtp-capacity.ts
390
390
  var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
391
- var MAX_RECIPIENTS = 1e3;
391
+ var MAX_SMTP_RECIPIENTS = 1e3;
392
392
  var KIB = 1024;
393
393
  var limits = Object.freeze({
394
394
  snapshotBytes: 2 * KIB * KIB,
@@ -416,7 +416,7 @@ function readBinding(input, code) {
416
416
  return Object.freeze({
417
417
  format,
418
418
  namespace: uuidV4(namespace, code),
419
- maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
419
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
420
420
  });
421
421
  }
422
422
  function readCapacityOption(raw) {
@@ -502,6 +502,26 @@ function readRecipientCounts(input, code, capacity) {
502
502
  function smtpMessageId(attemptId) {
503
503
  return `<${attemptId}@email.invalid>`;
504
504
  }
505
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
506
+ const seen = /* @__PURE__ */ new Set();
507
+ let previous = -1;
508
+ return readArray(input, limit, code, (value) => {
509
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
510
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
511
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
512
+ const index = integer(rawIndex, 0, limit - 1, code);
513
+ if (ordered) {
514
+ const position = recipientGroups.indexOf(group) * limit + index;
515
+ if (position <= previous) invalid(code);
516
+ previous = position;
517
+ } else {
518
+ const key = `${group}:${index}`;
519
+ if (seen.has(key)) invalid(code);
520
+ seen.add(key);
521
+ }
522
+ return Object.freeze({ group, index, status });
523
+ });
524
+ }
505
525
  function readHint(input, reason, code) {
506
526
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
507
527
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -535,24 +555,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false, c
535
555
  let recipients;
536
556
  if (hasRecipients) {
537
557
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
538
- const seen = /* @__PURE__ */ new Set();
539
- const limit = recipientLimit(capacity);
540
- let previous = -1;
541
- recipients = readArray(raw.recipients, limit, code, (value) => {
542
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
543
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
544
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
545
- const index = integer(rawIndex, 0, limit - 1, code);
546
- if (capacity) {
547
- const position = recipientGroups.indexOf(group) * limit + index;
548
- if (position <= previous) invalid(code);
549
- previous = position;
550
- } else {
551
- const key = `${group}:${index}`;
552
- if (seen.has(key)) invalid(code);
553
- seen.add(key);
554
- }
555
- return Object.freeze({ group, index, status });
558
+ recipients = readRecipientResults(raw.recipients, code, {
559
+ limit: recipientLimit(capacity),
560
+ allowAccepted: smtpSuccess,
561
+ ordered: Boolean(capacity)
556
562
  });
557
563
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
558
564
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -1711,6 +1717,11 @@ function readJobRecord(scope2, input, capacity) {
1711
1717
  return job;
1712
1718
  }
1713
1719
 
1720
+ // src/internal/smtp-attachments.ts
1721
+ function assertSmtpAttachmentTypes(refs) {
1722
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
1723
+ }
1724
+
1714
1725
  // src/internal/job-transitions.ts
1715
1726
  function guard(job, { now }, before) {
1716
1727
  if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
@@ -1741,6 +1752,7 @@ function newJob(admission, time2, capacity) {
1741
1752
  if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
1742
1753
  const nextAt = Math.max(now, scheduleAt ?? now);
1743
1754
  if (nextAt >= snapshot.expiresAt) invalid("expired");
1755
+ if (snapshot.kind === "smtp") assertSmtpAttachmentTypes(snapshot.attachments);
1744
1756
  return Object.freeze({
1745
1757
  version: EMAIL_FORMAT_VERSION,
1746
1758
  ...capacityTag(capacity),
@@ -1783,9 +1795,13 @@ function liveLease(job, fence, phase, now) {
1783
1795
  }
1784
1796
  return lease;
1785
1797
  }
1798
+ function claimEligibility(job, now) {
1799
+ if (job.state.state !== "queued" || job.state.nextAt > now) return "not_due";
1800
+ return now >= job.expiresAt ? "expired" : "eligible";
1801
+ }
1786
1802
  function claimJob(job, claim, time2, capacity) {
1787
1803
  const { now } = time2;
1788
- if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
1804
+ if (claimEligibility(job, now) !== "eligible") return null;
1789
1805
  const manual = hasRedrive(job);
1790
1806
  const ordinal2 = job.attempts.length + 1;
1791
1807
  if (ordinal2 > MAX_ATTEMPT_LEDGER || !manual && ordinal2 > job.retry.maxAttempts) invalid("store_incompatible");
@@ -1813,6 +1829,20 @@ function claimJob(job, claim, time2, capacity) {
1813
1829
  Math.min(job.expiresAt, lease.leaseEndsAt)
1814
1830
  );
1815
1831
  }
1832
+ var EXPIRY_MAINTENANCE_REQUIRED = Object.freeze({ status: "expiry_maintenance_required" });
1833
+ function claimWindow(claim, candidateLimit, capacity) {
1834
+ let expired = 0;
1835
+ return {
1836
+ decide(job, time2) {
1837
+ const decision = claimJob(job, claim, time2, capacity);
1838
+ if (decision === null && claimEligibility(job, time2.now) === "expired") expired++;
1839
+ return decision;
1840
+ },
1841
+ result(next) {
1842
+ return next.status !== "applied" && expired === candidateLimit ? EXPIRY_MAINTENANCE_REQUIRED : next;
1843
+ }
1844
+ };
1845
+ }
1816
1846
  function renewJob(job, fence, leaseMs, time2) {
1817
1847
  const lease = liveLease(job, fence, "pre_handoff", time2.now);
1818
1848
  if (!lease || time2.now >= job.expiresAt) return null;
@@ -2926,6 +2956,13 @@ var MongoOperations = class {
2926
2956
  }
2927
2957
  return invalid("busy");
2928
2958
  }
2959
+ get dueCandidateLimit() {
2960
+ return this.capacity?.limits.dueCandidates ?? MAX_STORE_CANDIDATES;
2961
+ }
2962
+ async claimNext(scope2, claim) {
2963
+ const window = claimWindow(claim, this.dueCandidateLimit, this.capacity);
2964
+ return window.result(await this.next(scope2, "nextAt", window.decide));
2965
+ }
2929
2966
  async next(scope2, due, decide) {
2930
2967
  const selectionAt = await this.now();
2931
2968
  const { name, state, sort } = dueIndexes[due];
@@ -2937,7 +2974,7 @@ var MongoOperations = class {
2937
2974
  [due]: { $exists: true, $lte: selectionAt }
2938
2975
  },
2939
2976
  name,
2940
- this.capacity?.limits.dueCandidates ?? MAX_STORE_CANDIDATES,
2977
+ this.dueCandidateLimit,
2941
2978
  "majority",
2942
2979
  sort,
2943
2980
  { _id: 0, jobId: 1 }
@@ -3218,7 +3255,7 @@ function createMongooseEmailStore(connection, options = {}) {
3218
3255
  claimNext(scope2, input, call) {
3219
3256
  return run(call, true, (ops) => {
3220
3257
  const safe = readClaim(input);
3221
- return ops.next(scopeToken(scope2), "nextAt", (job, time2) => claimJob(job, safe, time2, capacity));
3258
+ return ops.claimNext(scopeToken(scope2), safe);
3222
3259
  });
3223
3260
  },
3224
3261
  renew(scope2, fence, leaseMs, call) {