@web-ts-toolkit/email-service 0.0.0-stage → 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/mongoose.js ADDED
@@ -0,0 +1,3311 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/mongoose.ts
21
+ var mongoose_exports = {};
22
+ __export(mongoose_exports, {
23
+ createMongooseEmailStore: () => createMongooseEmailStore
24
+ });
25
+ module.exports = __toCommonJS(mongoose_exports);
26
+ var import_node_crypto3 = require("crypto");
27
+
28
+ // src/constants.ts
29
+ var KiB = 1024;
30
+ var MiB = 1024 * KiB;
31
+ var DAY_MS = 864e5;
32
+ function bounded(defaultValue, min, max) {
33
+ return Object.freeze({ default: defaultValue, min, max });
34
+ }
35
+ var EMAIL_FORMAT_VERSION = 1;
36
+ var MAX_UNIX_MS = 253402300799999;
37
+ var CLOCK_MARGIN_MS = 1e3;
38
+ var MAX_EXPIRY_MS = 30 * DAY_MS;
39
+ var MAX_PREPARED_AT_SKEW_MS = 6e4;
40
+ var MESSAGE_LIMITS = Object.freeze({
41
+ scopeBytes: 64,
42
+ identifierBytes: 128,
43
+ jsonDepth: 12,
44
+ jsonValues: 2048,
45
+ jsonKeyBytes: 128,
46
+ intentBytes: 16 * KiB,
47
+ dataBytes: 64 * KiB,
48
+ snapshotBytes: MiB,
49
+ recipients: 50,
50
+ addressBytes: 254,
51
+ localPartBytes: 64,
52
+ displayNameBytes: 128,
53
+ subjectBytes: 512,
54
+ templateSourceBytes: 256 * KiB,
55
+ htmlBytes: 512 * KiB,
56
+ textBytes: 256 * KiB,
57
+ correlationEntries: 8,
58
+ correlationKeyBytes: 32,
59
+ correlationValueBytes: 96,
60
+ attachments: 5,
61
+ filenameBytes: 128,
62
+ contentTypeBytes: 127,
63
+ attachmentBytes: 2 * MiB,
64
+ totalAttachmentBytes: 5 * MiB
65
+ });
66
+ var PRIORITY = bounded(0, 0, 9);
67
+ var TEMPLATE_CACHE_ENTRIES = bounded(32, 0, 128);
68
+ var TEMPLATE_MAX_PENDING = bounded(8, 1, 32);
69
+ var CALL_BUDGETS = Object.freeze({
70
+ prepare: bounded(5e3, 50, 3e4),
71
+ admissionOrAdmin: bounded(1e4, 50, 6e4),
72
+ batchOrRun: bounded(3e4, 50, 12e4),
73
+ shutdown: bounded(15e3, 50, 6e4)
74
+ });
75
+ var DEFAULT_RETRY_POLICY = Object.freeze({
76
+ maxAttempts: 3,
77
+ baseDelayMs: 1e3,
78
+ maxDelayMs: 6e4
79
+ });
80
+ var RETRY_POLICY_BOUNDS = Object.freeze({
81
+ maxAttempts: bounded(DEFAULT_RETRY_POLICY.maxAttempts, 1, 10),
82
+ baseDelayMs: bounded(DEFAULT_RETRY_POLICY.baseDelayMs, 100, 6e4),
83
+ // Also require maxDelayMs >= the configured baseDelayMs.
84
+ maxDelayMs: bounded(DEFAULT_RETRY_POLICY.maxDelayMs, 100, 36e5)
85
+ });
86
+ var MAX_MANUAL_ATTEMPTS = 1;
87
+ var MAX_ATTEMPT_LEDGER = RETRY_POLICY_BOUNDS.maxAttempts.max + MAX_MANUAL_ATTEMPTS;
88
+ var MAX_RATE_DEFERRAL_MS = 30 * DAY_MS;
89
+ var DEFAULT_RETENTION_POLICY = Object.freeze({
90
+ payloadMs: 7 * DAY_MS,
91
+ historyMs: 30 * DAY_MS,
92
+ idempotencyMs: 30 * DAY_MS
93
+ });
94
+ var RETENTION_POLICY_BOUNDS = Object.freeze({
95
+ payloadMs: bounded(DEFAULT_RETENTION_POLICY.payloadMs, 0, 30 * DAY_MS),
96
+ historyMs: bounded(DEFAULT_RETENTION_POLICY.historyMs, DAY_MS, 90 * DAY_MS),
97
+ idempotencyMs: bounded(DEFAULT_RETENTION_POLICY.idempotencyMs, DAY_MS, 90 * DAY_MS)
98
+ });
99
+ var DEFAULT_WORKER_LIMITS = Object.freeze({
100
+ maxConcurrency: 4,
101
+ storeTimeoutMs: 5e3,
102
+ leaseMs: 6e4,
103
+ preHandoffTimeoutMs: 8e3,
104
+ attachmentTimeoutMs: 5e3,
105
+ rateTimeoutMs: 500,
106
+ providerTimeoutMs: 15e3,
107
+ finalizeGraceMs: 1e4
108
+ });
109
+ var WORKER_LIMIT_BOUNDS = Object.freeze({
110
+ maxConcurrency: bounded(DEFAULT_WORKER_LIMITS.maxConcurrency, 1, 16),
111
+ storeTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.storeTimeoutMs, 50, 3e4),
112
+ leaseMs: bounded(DEFAULT_WORKER_LIMITS.leaseMs, 5e3, 3e5),
113
+ preHandoffTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.preHandoffTimeoutMs, 50, 6e4),
114
+ attachmentTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.attachmentTimeoutMs, 50, 3e4),
115
+ rateTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.rateTimeoutMs, 10, 5e3),
116
+ providerTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.providerTimeoutMs, 50, 6e4),
117
+ finalizeGraceMs: bounded(DEFAULT_WORKER_LIMITS.finalizeGraceMs, 100, 3e4)
118
+ });
119
+ var RUN_CLAIM_LIMIT = bounded(20, 1, 100);
120
+ var RUN_MAINTENANCE_LIMIT = bounded(10, 0, 100);
121
+ var ACTIVITY_PAGE_LIMIT = bounded(25, 1, 100);
122
+ var MAX_ACTIVITY_CURSOR_BYTES = 512;
123
+ var ADMIN_MAINTENANCE_LIMIT = bounded(20, 1, 100);
124
+ var PROJECTION_PERMIT_MS = 6e4;
125
+ var ACTIVITY_STUB_TTL_MS = 6e4;
126
+ var PROJECTION_DRAIN_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max + CLOCK_MARGIN_MS;
127
+ var STORE_PRIMITIVE_TIMEOUT_MS = 5e3;
128
+ var MAX_STORE_CANDIDATES = 16;
129
+ var MAX_STORE_CAS_SUBMISSIONS = 3;
130
+ var MEMORY_MAX_JOBS = bounded(256, 1, 4096);
131
+ var MONGOOSE_DEFAULT_NAMES = Object.freeze({
132
+ jobsCollection: "email_jobs",
133
+ activitiesCollection: "email_activities",
134
+ jobsModelName: "EmailJobV1",
135
+ activitiesModelName: "EmailActivityV1"
136
+ });
137
+ var SMTP_DEFAULT_PORTS = Object.freeze({ implicit: 465, starttls: 587 });
138
+ var SENDGRID_REQUEST_MAX_BYTES = 8 * MiB;
139
+ var SENDGRID_RESPONSE_MAX_BYTES = 64 * KiB;
140
+
141
+ // src/internal/activity-codecs.ts
142
+ var import_node_buffer2 = require("buffer");
143
+
144
+ // src/internal/canonical-json.ts
145
+ var import_node_crypto = require("crypto");
146
+
147
+ // src/internal/validation.ts
148
+ var import_node_buffer = require("buffer");
149
+ var import_node_util = require("util");
150
+
151
+ // src/errors.ts
152
+ var messages = Object.freeze({
153
+ invalid_config: "Invalid email service configuration.",
154
+ invalid_command: "Invalid email command.",
155
+ invalid_input: "Invalid template input.",
156
+ invalid_data: "Invalid prepared template data.",
157
+ invalid_snapshot: "Invalid prepared email snapshot.",
158
+ preparation_failed: "Email preparation failed.",
159
+ template_not_found: "Email template not found.",
160
+ template_source: "Email template source could not be loaded.",
161
+ template_render: "Email template could not be rendered.",
162
+ provider_mismatch: "Email provider does not match the template or snapshot.",
163
+ expired: "Email has expired.",
164
+ idempotency_conflict: "Email admission key was used with different intent.",
165
+ not_found: "Email job not found.",
166
+ resolution_conflict: "Unknown attempt cannot be resolved with this action.",
167
+ store_capacity: "Email store is at capacity.",
168
+ store_unavailable: "Email store is unavailable.",
169
+ store_incompatible: "Email store does not meet the required guarantees.",
170
+ write_unconfirmed: "Email store write not confirmed; it may have committed.",
171
+ invalid_cursor: "Invalid email activity cursor.",
172
+ aborted: "Email operation was aborted.",
173
+ deadline: "Email operation deadline elapsed.",
174
+ busy: "Email service has no available capacity for this operation.",
175
+ closed: "Email service is closed."
176
+ });
177
+ var EmailError = class extends Error {
178
+ /** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
179
+ code;
180
+ constructor(code) {
181
+ const safeCode = typeof code === "string" && Object.hasOwn(messages, code) ? code : "invalid_config";
182
+ super(messages[safeCode]);
183
+ this.name = "EmailError";
184
+ this.code = safeCode;
185
+ }
186
+ };
187
+
188
+ // src/internal/validation.ts
189
+ function invalid(code) {
190
+ throw new EmailError(code);
191
+ }
192
+ function dataObject(value, code) {
193
+ if (typeof value !== "object" || value === null || import_node_util.types.isProxy(value)) invalid(code);
194
+ return value;
195
+ }
196
+ function isArray(value, code) {
197
+ return Array.isArray(dataObject(value, code));
198
+ }
199
+ function plainKeys(value, maxKeys, code) {
200
+ const object = dataObject(value, code);
201
+ const proto = Object.getPrototypeOf(object);
202
+ if (Array.isArray(object) || proto !== null && proto !== Object.prototype) invalid(code);
203
+ const keys = Reflect.ownKeys(object);
204
+ if (keys.length > maxKeys || keys.some((key) => typeof key !== "string")) invalid(code);
205
+ return keys;
206
+ }
207
+ function ownData(value, key, code) {
208
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
209
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) invalid(code);
210
+ return descriptor.value;
211
+ }
212
+ function readRecord(value, required, optional, code) {
213
+ const keys = plainKeys(value, required.length + optional.length, code);
214
+ const copy = /* @__PURE__ */ Object.create(null);
215
+ for (const key of keys) {
216
+ if (!required.includes(key) && !optional.includes(key)) invalid(code);
217
+ copy[key] = ownData(value, key, code);
218
+ }
219
+ for (const key of required) {
220
+ if (!Object.hasOwn(copy, key)) invalid(code);
221
+ }
222
+ return copy;
223
+ }
224
+ function denseArrayLength(value, maxLength, code) {
225
+ const object = dataObject(value, code);
226
+ if (!Array.isArray(object) || Object.getPrototypeOf(object) !== Array.prototype) invalid(code);
227
+ const { length } = object;
228
+ if (length > maxLength || Reflect.ownKeys(object).length !== length + 1) invalid(code);
229
+ return length;
230
+ }
231
+ function readArray(value, maxLength, code, read) {
232
+ const length = denseArrayLength(value, maxLength, code);
233
+ const copy = [];
234
+ for (let i = 0; i < length; i++) copy.push(read(ownData(value, String(i), code)));
235
+ return Object.freeze(copy);
236
+ }
237
+ function integer(value, min, max, code) {
238
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) invalid(code);
239
+ return value === 0 ? 0 : value;
240
+ }
241
+ function boundedOption(value, bounds, code = "invalid_config") {
242
+ return value === void 0 ? bounds.default : integer(value, bounds.min, bounds.max, code);
243
+ }
244
+ function unixMs(value, code) {
245
+ return integer(value, 0, MAX_UNIX_MS, code);
246
+ }
247
+ function utf8Length(value, maxBytes, code) {
248
+ if (value.length > maxBytes || /[\uD800-\uDFFF]/u.test(value)) invalid(code);
249
+ const bytes = import_node_buffer.Buffer.byteLength(value, "utf8");
250
+ if (bytes > maxBytes) invalid(code);
251
+ return bytes;
252
+ }
253
+ function utf8String(value, maxBytes, code) {
254
+ if (typeof value !== "string") invalid(code);
255
+ utf8Length(value, maxBytes, code);
256
+ return value;
257
+ }
258
+ function headerString(value, maxBytes, code) {
259
+ const text = utf8String(value, maxBytes, code);
260
+ for (let i = 0; i < text.length; i++) {
261
+ const ch = text.charCodeAt(i);
262
+ if (ch < 32 || ch === 127) invalid(code);
263
+ }
264
+ return text;
265
+ }
266
+ function opaqueToken(value, maxBytes, code) {
267
+ if (typeof value !== "string" || value.length > maxBytes || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
268
+ invalid(code);
269
+ }
270
+ return value;
271
+ }
272
+ function scopeToken(value, code = "invalid_command") {
273
+ return opaqueToken(value, MESSAGE_LIMITS.scopeBytes, code);
274
+ }
275
+ function identifier(value, code) {
276
+ return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
277
+ }
278
+ function uuidV4(value, code) {
279
+ 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)) {
280
+ invalid(code);
281
+ }
282
+ return value;
283
+ }
284
+ function hashToken(value, code) {
285
+ if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
286
+ return value;
287
+ }
288
+ function jsonKey(key, code) {
289
+ utf8Length(key, MESSAGE_LIMITS.jsonKeyBytes, code);
290
+ if (key === "__proto__" || key === "prototype" || key === "constructor" || key.includes(".") || key.includes("$") || key.includes("\0")) {
291
+ invalid(code);
292
+ }
293
+ }
294
+
295
+ // src/internal/canonical-json.ts
296
+ var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
297
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
298
+ let bytesLeft = maxBytes;
299
+ let valuesLeft = limits2.values;
300
+ const chunks = [];
301
+ const ancestors = /* @__PURE__ */ new Set();
302
+ function append(text, bytes = text.length) {
303
+ if (bytes > bytesLeft) invalid(code);
304
+ bytesLeft -= bytes;
305
+ chunks.push(text);
306
+ }
307
+ function appendString(text) {
308
+ let bytes = 2 + utf8Length(text, bytesLeft - 2, code);
309
+ for (let i = 0; i < text.length; i++) {
310
+ const ch = text.charCodeAt(i);
311
+ if (ch === 34 || ch === 92 || ch === 8 || ch === 9 || ch === 10 || ch === 12 || ch === 13) bytes++;
312
+ else if (ch < 32) bytes += 5;
313
+ if (bytes > bytesLeft) invalid(code);
314
+ }
315
+ append(JSON.stringify(text), bytes);
316
+ }
317
+ function visit(value2, depth) {
318
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
319
+ switch (typeof value2) {
320
+ case "string":
321
+ appendString(value2);
322
+ return value2;
323
+ case "number":
324
+ if (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2)) invalid(code);
325
+ append(JSON.stringify(value2));
326
+ return value2 === 0 ? 0 : value2;
327
+ case "boolean":
328
+ append(value2 ? "true" : "false");
329
+ return value2;
330
+ case "object":
331
+ if (value2 === null) {
332
+ append("null");
333
+ return null;
334
+ }
335
+ break;
336
+ default:
337
+ invalid(code);
338
+ }
339
+ if (ancestors.has(value2)) invalid(code);
340
+ ancestors.add(value2);
341
+ try {
342
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
343
+ if (isArray(value2, code)) {
344
+ const length = denseArrayLength(value2, maxChildren, code);
345
+ if (length && 2 * length + 1 > bytesLeft) invalid(code);
346
+ const copy2 = [];
347
+ append("[");
348
+ for (let i = 0; i < length; i++) {
349
+ if (i) append(",");
350
+ copy2.push(visit(ownData(value2, String(i), code), depth + 1));
351
+ }
352
+ append("]");
353
+ return Object.freeze(copy2);
354
+ }
355
+ const keys = plainKeys(value2, maxChildren, code);
356
+ if (keys.length && 5 * keys.length + 1 > bytesLeft) invalid(code);
357
+ for (const key of keys) jsonKey(key, code);
358
+ const copy = /* @__PURE__ */ Object.create(null);
359
+ append("{");
360
+ for (const [index, key] of keys.sort().entries()) {
361
+ if (index) append(",");
362
+ appendString(key);
363
+ append(":");
364
+ copy[key] = visit(ownData(value2, key, code), depth + 1);
365
+ }
366
+ append("}");
367
+ return Object.freeze(copy);
368
+ } finally {
369
+ ancestors.delete(value2);
370
+ }
371
+ }
372
+ const value = visit(input, 0);
373
+ return { value, encoded: chunks.join("") };
374
+ }
375
+ function copyJsonObject(input, maxBytes, code) {
376
+ if (typeof input !== "object" || input === null || isArray(input, code)) invalid(code);
377
+ return canonicalJson(input, maxBytes, code).value;
378
+ }
379
+ function sha256(input) {
380
+ return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
381
+ }
382
+ function hashJson(input, maxBytes, code = "invalid_snapshot") {
383
+ return sha256(canonicalJson(input, maxBytes, code).encoded);
384
+ }
385
+ function encodeEvidence(input, code, capacity) {
386
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
387
+ }
388
+
389
+ // src/internal/smtp-capacity.ts
390
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
391
+ var MAX_RECIPIENTS = 1e3;
392
+ var KIB = 1024;
393
+ var limits = Object.freeze({
394
+ snapshotBytes: 2 * KIB * KIB,
395
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
396
+ evidenceBytes: 64 * KIB,
397
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
398
+ jobBsonBytes: 4 * KIB * KIB,
399
+ activityBsonBytes: 128 * KIB,
400
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
401
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
402
+ servicePending: 4,
403
+ workerProfiles: 16,
404
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
405
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
406
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
407
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
408
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
409
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
410
+ mongoInFlight: 4,
411
+ dueCandidates: 4
412
+ });
413
+ function readBinding(input, code) {
414
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
415
+ if (format !== "smtp-v2") invalid(code);
416
+ return Object.freeze({
417
+ format,
418
+ namespace: uuidV4(namespace, code),
419
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
420
+ });
421
+ }
422
+ function readCapacityOption(raw) {
423
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
424
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
425
+ }
426
+ function capacityTag(capacity) {
427
+ return capacity ? { smtpCapacity: capacity.binding } : {};
428
+ }
429
+ function recipientLimit(capacity) {
430
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
431
+ }
432
+ function matchesBinding(input, capacity, code) {
433
+ const binding = readBinding(input, code);
434
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
435
+ invalid(code);
436
+ }
437
+ }
438
+ function assertCapacityTag(raw, capacity, code) {
439
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
440
+ if (capacity) {
441
+ if (!tagged) invalid(code);
442
+ matchesBinding(raw.smtpCapacity, capacity, code);
443
+ } else if (tagged) {
444
+ invalid(code);
445
+ }
446
+ }
447
+ function assertCapacityProvider(provider2, capacity, code) {
448
+ if (capacity && provider2.kind !== "smtp") invalid(code);
449
+ }
450
+
451
+ // src/internal/attempt-codecs.ts
452
+ var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
453
+ var providerStages = [...smtpStages, "http"];
454
+ var evidence = Object.freeze({
455
+ smtp_accepted: ["accepted", "never", ["data"], "smtp"],
456
+ smtp_partial: ["partially_accepted", "never", ["data"], "smtp"],
457
+ smtp_transient_reply: ["rejected", "safe_transient", smtpStages, "smtp"],
458
+ smtp_permanent_reply: ["rejected", "never", smtpStages, "smtp"],
459
+ sendgrid_accepted: ["accepted", "never", ["http"], "sendgrid"],
460
+ sendgrid_validated: ["validated", "never", ["http"], "sendgrid"],
461
+ sendgrid_throttled: ["rejected", "safe_transient", ["http"], "sendgrid"],
462
+ sendgrid_rejected: ["rejected", "never", ["http"], "sendgrid"],
463
+ not_transmitted: ["unsubmitted", "safe_transient", providerStages, "provider"],
464
+ provider_configuration: ["unsubmitted", "never", providerStages, "provider"],
465
+ transport_uncertain: ["unknown", "never", providerStages, "provider"],
466
+ provider_timeout: ["unknown", "never", providerStages, "provider"],
467
+ provider_aborted: ["unknown", "never", providerStages, "provider"],
468
+ attachment_unavailable: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
469
+ attachment_timeout: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
470
+ attachment_invalid: ["unsubmitted", "never", ["attachment"], "pre"],
471
+ attachment_resolver_error: ["unsubmitted", "never", ["attachment"], "pre"],
472
+ rate_deferred: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
473
+ rate_timeout: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
474
+ rate_error: ["unsubmitted", "never", ["rate_limit"], "pre"],
475
+ profile_unavailable: ["unsubmitted", "never", ["pre_handoff"], "pre"],
476
+ provider_preflight_error: ["unsubmitted", "never", ["pre_handoff"], "pre"],
477
+ pre_handoff_timeout: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
478
+ worker_stopped: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
479
+ pre_handoff_lease_expired: ["unsubmitted", "safe_transient", ["pre_handoff"], "recovery"],
480
+ launch_window_closed: ["unsubmitted", "safe_transient", ["pre_handoff"], "launch"],
481
+ post_handoff_lease_expired: ["unknown", "never", ["pre_handoff"], "recovery"],
482
+ expired: ["unsubmitted", "never", ["pre_handoff"], "pre"],
483
+ cancelled: ["unsubmitted", "never", ["pre_handoff"], "cancel"]
484
+ });
485
+ function readAttemptReason(value, code) {
486
+ if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
487
+ return value;
488
+ }
489
+ var recipientGroups = ["to", "cc", "bcc"];
490
+ function recipientCounts(envelope) {
491
+ return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
492
+ }
493
+ function readRecipientCounts(input, code, capacity) {
494
+ const limit = recipientLimit(capacity);
495
+ const counts = readRecord(input, recipientGroups, [], code);
496
+ const to = integer(counts.to, 0, limit, code);
497
+ const cc = integer(counts.cc, 0, limit - to, code);
498
+ const bcc = integer(counts.bcc, 0, limit - to - cc, code);
499
+ if (to + cc + bcc === 0) invalid(code);
500
+ return Object.freeze({ to, cc, bcc });
501
+ }
502
+ function smtpMessageId(attemptId) {
503
+ return `<${attemptId}@email.invalid>`;
504
+ }
505
+ function readHint(input, reason, code) {
506
+ if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
507
+ const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
508
+ const hasDelay = Object.hasOwn(raw, "delayMs");
509
+ const hasFloor = Object.hasOwn(raw, "notBefore");
510
+ if (!hasDelay && (!hasFloor || reason === "rate_deferred")) invalid(code);
511
+ return Object.freeze({
512
+ ...hasDelay ? {
513
+ delayMs: reason === "rate_deferred" ? integer(raw.delayMs, 1, MAX_RATE_DEFERRAL_MS, code) : integer(raw.delayMs, 0, Number.MAX_SAFE_INTEGER, code)
514
+ } : {},
515
+ ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
516
+ });
517
+ }
518
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
519
+ const raw = readRecord(
520
+ input,
521
+ ["outcome", "retry", "stage", "reason"],
522
+ ["retryHint", "recipients", "messageId", "providerMessageId"],
523
+ code
524
+ );
525
+ const reason = readAttemptReason(raw.reason, code);
526
+ const [outcome, retry, stages, origin] = evidence[reason];
527
+ const stage = stages.find((value) => value === raw.stage);
528
+ if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
529
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
530
+ const hasHint = Object.hasOwn(raw, "retryHint");
531
+ if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
532
+ const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
533
+ const hasRecipients = Object.hasOwn(raw, "recipients");
534
+ if (smtpSuccess && !hasRecipients) invalid(code);
535
+ let recipients;
536
+ if (hasRecipients) {
537
+ 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 });
556
+ });
557
+ const accepted = recipients.filter(({ status }) => status === "accepted").length;
558
+ if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
559
+ invalid(code);
560
+ }
561
+ }
562
+ const hasMessageId = Object.hasOwn(raw, "messageId");
563
+ const { messageId, providerMessageId } = raw;
564
+ if (hasMessageId && (!smtpSuccess || typeof messageId !== "string" || messageId.length !== 52)) invalid(code);
565
+ const hasProviderId = Object.hasOwn(raw, "providerMessageId");
566
+ if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
567
+ invalid(code);
568
+ }
569
+ const result = Object.freeze({
570
+ outcome,
571
+ retry,
572
+ stage,
573
+ reason,
574
+ ...hasHint ? { retryHint: readHint(raw.retryHint, reason, code) } : {},
575
+ ...recipients === void 0 ? {} : { recipients },
576
+ ...typeof messageId === "string" ? { messageId } : {},
577
+ ...typeof providerMessageId === "string" ? { providerMessageId } : {}
578
+ });
579
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
580
+ return result;
581
+ }
582
+ function assertEvidencePhase(reason, phase, source, code) {
583
+ const origin = evidence[reason][3];
584
+ if (source === "ledger") {
585
+ if (origin === "recovery" && reason === "post_handoff_lease_expired" === (phase === "handed_off")) return;
586
+ if (origin === "cancel" && phase === "pre_handoff") return;
587
+ }
588
+ const allowed = phase === "pre_handoff" ? origin === "pre" : origin === "smtp" || origin === "sendgrid" || origin === "provider" || origin === "launch";
589
+ if (!allowed) invalid(code);
590
+ }
591
+ function assertEvidenceContext(result, provider2, attemptId, counts, code) {
592
+ const { reason, stage, recipients, messageId } = result;
593
+ const origin = evidence[reason][3];
594
+ 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)) {
595
+ invalid(code);
596
+ }
597
+ if (recipients) {
598
+ if (provider2.kind !== "smtp") invalid(code);
599
+ if (counts) {
600
+ if (recipients.some(({ group, index }) => index >= counts[group])) invalid(code);
601
+ const needsPartition = reason === "smtp_accepted" || reason === "smtp_partial" || stage === "envelope" && (reason === "smtp_transient_reply" || reason === "smtp_permanent_reply");
602
+ if (needsPartition && recipients.length !== counts.to + counts.cc + counts.bcc) invalid(code);
603
+ }
604
+ }
605
+ }
606
+ function lifecycleEvidence(reason) {
607
+ const [outcome, retry] = evidence[reason];
608
+ return Object.freeze({ outcome, retry, reason, stage: "pre_handoff" });
609
+ }
610
+ function attemptEffect(result, attemptId, ordinal2, manual, policy, expiresAt, now) {
611
+ const { outcome, reason } = result;
612
+ if (outcome !== "unsubmitted" && outcome !== "rejected") return { disposition: outcome, reason };
613
+ if (reason === "cancelled" || reason === "expired") return { disposition: reason, reason };
614
+ const disposition = outcome === "unsubmitted" ? "failed" : "rejected";
615
+ if (result.retry === "never") return { disposition, reason };
616
+ if (now >= expiresAt) return { disposition: "expired", reason: "expired" };
617
+ if (manual || ordinal2 >= policy.maxAttempts) return { disposition, reason: "attempts_exhausted" };
618
+ const cap = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (ordinal2 - 1));
619
+ const half = Math.floor(cap / 2);
620
+ const jitter = half + Number.parseInt(sha256(attemptId).slice(0, 8), 16) % (cap - half + 1);
621
+ const delay = Math.max(jitter, result.retryHint?.delayMs ?? 0);
622
+ const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result.retryHint?.notBefore ?? 0);
623
+ if (retryAt >= expiresAt) return { disposition: "expired", reason: "expired" };
624
+ return { disposition: "retry_scheduled", reason, retryAt };
625
+ }
626
+
627
+ // src/internal/message-codecs.ts
628
+ var import_node_net = require("net");
629
+ var import_node_util2 = require("util");
630
+ var L = MESSAGE_LIMITS;
631
+ var SNAPSHOT = "invalid_snapshot";
632
+ var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
633
+ var DNS_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
634
+ var MIME_TYPE = /^[-a-z0-9!#$%&'*+.^_`{|}~]+\/[-a-z0-9!#$%&'*+.^_`{|}~]+$/;
635
+ function validateProviderRef(input, code = SNAPSHOT) {
636
+ const { kind, key, mode } = readRecord(input, ["kind", "key", "mode"], [], code);
637
+ const profile = identifier(key, code);
638
+ if (kind === "smtp" && mode === "live") return Object.freeze({ kind, key: profile, mode });
639
+ if (kind === "sendgrid" && (mode === "live" || mode === "sandbox")) {
640
+ return Object.freeze({ kind, key: profile, mode });
641
+ }
642
+ return invalid(code);
643
+ }
644
+ function validateTemplateIdentity(input, code = SNAPSHOT) {
645
+ const { key, revision } = readRecord(input, ["key", "revision"], [], code);
646
+ return Object.freeze({ key: identifier(key, code), revision: identifier(revision, code) });
647
+ }
648
+ function sendGridTemplateId(input, code = SNAPSHOT) {
649
+ if (typeof input !== "string" || input.length !== 34 || !/^d-[0-9a-fA-F]{32}$/.test(input)) invalid(code);
650
+ return input;
651
+ }
652
+ function validateMailbox(input, code = SNAPSHOT) {
653
+ const mailbox = readRecord(input, ["address"], ["name"], code);
654
+ const address = headerString(mailbox.address, L.addressBytes, code);
655
+ const at = address.indexOf("@");
656
+ const local = address.slice(0, at);
657
+ const domain = address.slice(at + 1);
658
+ if (at < 1 || at > L.localPartBytes || !DOT_ATOM.test(local) || !domain.split(".").every((label) => DNS_LABEL.test(label)) || (0, import_node_net.isIP)(domain) !== 0) {
659
+ invalid(code);
660
+ }
661
+ return Object.freeze({
662
+ address,
663
+ ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
664
+ });
665
+ }
666
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
667
+ const limit = recipientLimit(capacity);
668
+ const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
669
+ const seen = /* @__PURE__ */ new Set();
670
+ const recipient = (raw) => {
671
+ const mailbox = validateMailbox(raw, code);
672
+ const address = mailbox.address.toLowerCase();
673
+ if (seen.has(address)) invalid(code);
674
+ seen.add(address);
675
+ return mailbox;
676
+ };
677
+ const from = validateMailbox(envelope.from, code);
678
+ const to = readArray(envelope.to, limit, code, recipient);
679
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
680
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
681
+ if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
682
+ return Object.freeze({
683
+ from,
684
+ to,
685
+ cc,
686
+ bcc,
687
+ ...Object.hasOwn(envelope, "replyTo") ? { replyTo: validateMailbox(envelope.replyTo, code) } : {}
688
+ });
689
+ }
690
+ function validateCorrelation(input, code = SNAPSHOT) {
691
+ const keys = plainKeys(input, L.correlationEntries, code);
692
+ const copy = /* @__PURE__ */ Object.create(null);
693
+ for (const key of keys) {
694
+ jsonKey(key, code);
695
+ opaqueToken(key, L.correlationKeyBytes, code);
696
+ copy[key] = opaqueToken(ownData(input, key, code), L.correlationValueBytes, code);
697
+ }
698
+ return Object.freeze(copy);
699
+ }
700
+ function validateAttachmentRef(input, code = SNAPSHOT) {
701
+ const ref = readRecord(
702
+ input,
703
+ ["resolverKey", "id", "version", "filename", "contentType", "byteLength", "sha256"],
704
+ [],
705
+ code
706
+ );
707
+ const filename = headerString(ref.filename, L.filenameBytes, code);
708
+ if (!filename || filename === "." || filename === ".." || /[/\\:]/.test(filename)) invalid(code);
709
+ const contentType = headerString(ref.contentType, L.contentTypeBytes, code);
710
+ if (!MIME_TYPE.test(contentType)) invalid(code);
711
+ return Object.freeze({
712
+ resolverKey: identifier(ref.resolverKey, code),
713
+ id: identifier(ref.id, code),
714
+ version: identifier(ref.version, code),
715
+ filename,
716
+ contentType,
717
+ byteLength: integer(ref.byteLength, 1, L.attachmentBytes, code),
718
+ sha256: hashToken(ref.sha256, code)
719
+ });
720
+ }
721
+ function validateAttachmentRefs(input, code = SNAPSHOT) {
722
+ let total = 0;
723
+ return readArray(input, L.attachments, code, (raw) => {
724
+ const ref = validateAttachmentRef(raw, code);
725
+ total += ref.byteLength;
726
+ if (total > L.totalAttachmentBytes) invalid(code);
727
+ return ref;
728
+ });
729
+ }
730
+ function validateSubject(input, code = SNAPSHOT) {
731
+ const subject = headerString(input, L.subjectBytes, code);
732
+ if (!subject.trim()) invalid(code);
733
+ return subject;
734
+ }
735
+ function smtpParts(subject, html, text, code) {
736
+ if (!html && !text) invalid(code);
737
+ return Object.freeze({ subject, ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } });
738
+ }
739
+ function validateSmtpContent(input, code = SNAPSHOT) {
740
+ const content = readRecord(input, ["subject"], ["html", "text"], code);
741
+ return smtpParts(
742
+ validateSubject(content.subject, code),
743
+ Object.hasOwn(content, "html") ? utf8String(content.html, L.htmlBytes, code) : void 0,
744
+ Object.hasOwn(content, "text") ? utf8String(content.text, L.textBytes, code) : void 0,
745
+ code
746
+ );
747
+ }
748
+ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
749
+ const expiresAt = unixMs(input, code);
750
+ if (expiresAt <= preparedAt || expiresAt - preparedAt > MAX_EXPIRY_MS || scheduleAt !== null && scheduleAt >= expiresAt) {
751
+ invalid(code);
752
+ }
753
+ return expiresAt;
754
+ }
755
+ function hashSnapshot(snapshot, capacity) {
756
+ return sha256(
757
+ canonicalJson(
758
+ snapshot,
759
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
760
+ SNAPSHOT,
761
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
762
+ ).encoded
763
+ );
764
+ }
765
+ function readSnapshot(input, capacity) {
766
+ const dto = readRecord(
767
+ input,
768
+ [
769
+ "version",
770
+ "kind",
771
+ "provider",
772
+ "template",
773
+ "envelope",
774
+ "preparedAt",
775
+ "expiresAt",
776
+ "priority",
777
+ "attachments",
778
+ "correlation"
779
+ ],
780
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
781
+ SNAPSHOT
782
+ );
783
+ if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
784
+ assertCapacityTag(dto, capacity, SNAPSHOT);
785
+ const provider2 = validateProviderRef(dto.provider);
786
+ if (provider2.kind !== dto.kind) invalid("provider_mismatch");
787
+ assertCapacityProvider(provider2, capacity, "provider_mismatch");
788
+ const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
789
+ const common = {
790
+ version: EMAIL_FORMAT_VERSION,
791
+ template: validateTemplateIdentity(dto.template),
792
+ envelope: validateEnvelope(dto.envelope, provider2.kind, SNAPSHOT, capacity),
793
+ preparedAt,
794
+ expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
795
+ priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
796
+ attachments: validateAttachmentRefs(dto.attachments),
797
+ correlation: validateCorrelation(dto.correlation)
798
+ };
799
+ if (provider2.kind === "smtp") {
800
+ if (Object.hasOwn(dto, "templateId") || Object.hasOwn(dto, "data")) invalid(SNAPSHOT);
801
+ const content = validateSmtpContent({
802
+ subject: dto.subject,
803
+ ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
804
+ ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
805
+ });
806
+ return Object.freeze({ ...common, kind: provider2.kind, provider: provider2, ...capacityTag(capacity), ...content });
807
+ }
808
+ if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
809
+ return Object.freeze({
810
+ ...common,
811
+ kind: provider2.kind,
812
+ provider: provider2,
813
+ templateId: sendGridTemplateId(dto.templateId),
814
+ data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
815
+ });
816
+ }
817
+ function validateSnapshot(input, capacity) {
818
+ const snapshot = readSnapshot(input, capacity);
819
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
820
+ }
821
+
822
+ // src/internal/budget.ts
823
+ var import_node_events = require("events");
824
+ var import_node_perf_hooks = require("perf_hooks");
825
+ var import_promises = require("timers/promises");
826
+ var import_node_util3 = require("util");
827
+ var systemEmailClock = Object.freeze({
828
+ now: Date.now,
829
+ monotonicNow: () => import_node_perf_hooks.performance.now(),
830
+ sleep: (ms, signal) => (0, import_promises.setTimeout)(ms, void 0, { signal })
831
+ });
832
+ function readCallOptions(input, bounds) {
833
+ const code = "invalid_config";
834
+ const { signal, timeoutMs } = readRecord(input, [], ["signal", "timeoutMs"], code);
835
+ const timeout = boundedOption(timeoutMs, bounds, code);
836
+ if (signal === void 0) return { timeoutMs: timeout };
837
+ try {
838
+ if (!import_node_util3.types.isProxy(signal) && signal instanceof AbortSignal && typeof Reflect.get(AbortSignal.prototype, "aborted", signal) === "boolean") {
839
+ return { signal, timeoutMs: timeout };
840
+ }
841
+ } catch {
842
+ invalid(code);
843
+ }
844
+ return invalid(code);
845
+ }
846
+ function monotonicNow(clock) {
847
+ try {
848
+ const now = clock.monotonicNow();
849
+ if (Number.isFinite(now)) return now;
850
+ } catch {
851
+ invalid("invalid_config");
852
+ }
853
+ return invalid("invalid_config");
854
+ }
855
+ function createBudget(clock, timeoutMs, external) {
856
+ return createBudgetUntil(clock, monotonicNow(clock) + timeoutMs, external);
857
+ }
858
+ function createBudgetUntil(clock, end, external) {
859
+ const operation = new AbortController();
860
+ const timer = new AbortController();
861
+ let externalListener;
862
+ let closed = false;
863
+ let reason;
864
+ function close() {
865
+ if (closed) return;
866
+ closed = true;
867
+ externalListener?.[Symbol.dispose]();
868
+ timer.abort();
869
+ }
870
+ function stop(code) {
871
+ if (closed) return;
872
+ reason = code;
873
+ close();
874
+ operation.abort(new EmailError(code));
875
+ }
876
+ function remainingMs() {
877
+ if (closed) return 0;
878
+ if (external?.aborted) {
879
+ stop("aborted");
880
+ } else {
881
+ try {
882
+ const remaining = end - monotonicNow(clock);
883
+ if (remaining > 0) return remaining;
884
+ stop("deadline");
885
+ } catch {
886
+ stop("invalid_config");
887
+ }
888
+ }
889
+ return 0;
890
+ }
891
+ function arm(remaining) {
892
+ void Promise.resolve(clock.sleep(Math.ceil(remaining), timer.signal)).then(
893
+ () => {
894
+ try {
895
+ const left = remainingMs();
896
+ if (left <= 0) return;
897
+ if (left >= remaining) stop("invalid_config");
898
+ else arm(left);
899
+ } catch {
900
+ stop("invalid_config");
901
+ }
902
+ },
903
+ () => stop("invalid_config")
904
+ );
905
+ }
906
+ try {
907
+ if (external && !external.aborted) externalListener = (0, import_node_events.addAbortListener)(external, () => stop("aborted"));
908
+ const remaining = remainingMs();
909
+ if (remaining > 0) arm(remaining);
910
+ } catch {
911
+ stop("invalid_config");
912
+ }
913
+ return {
914
+ signal: operation.signal,
915
+ deadline: end,
916
+ remainingMs,
917
+ check() {
918
+ remainingMs();
919
+ if (reason) invalid(reason);
920
+ if (closed) invalid("aborted");
921
+ },
922
+ close
923
+ };
924
+ }
925
+
926
+ // src/internal/command-codecs.ts
927
+ function validateAdmissionKey(input, code = "invalid_command") {
928
+ const key = readRecord(input, ["kind"], ["idempotencyKey", "batchId", "itemId"], code);
929
+ if (key.kind === "single" && !Object.hasOwn(key, "batchId") && !Object.hasOwn(key, "itemId")) {
930
+ return Object.freeze({ kind: key.kind, idempotencyKey: identifier(key.idempotencyKey, code) });
931
+ }
932
+ if (key.kind === "batch" && !Object.hasOwn(key, "idempotencyKey")) {
933
+ return Object.freeze({
934
+ kind: key.kind,
935
+ batchId: identifier(key.batchId, code),
936
+ itemId: identifier(key.itemId, code)
937
+ });
938
+ }
939
+ return invalid(code);
940
+ }
941
+ function encodeAdmissionKey(key) {
942
+ return key.kind === "single" ? `s:${key.idempotencyKey}` : `b:${key.batchId}:${key.itemId}`;
943
+ }
944
+ function fingerprintFor(identity, capacity) {
945
+ const { scope: scope2, key, templateKey, provider: provider2, scheduleAt, intentHash } = identity;
946
+ return hashJson(
947
+ [
948
+ ...capacity ? ["smtp-v2-admission", capacity.binding] : [],
949
+ EMAIL_FORMAT_VERSION,
950
+ scope2,
951
+ key,
952
+ templateKey,
953
+ provider2,
954
+ scheduleAt,
955
+ intentHash
956
+ ],
957
+ MESSAGE_LIMITS.intentBytes
958
+ );
959
+ }
960
+ function validatePreparedCommand(scope2, input, capacity) {
961
+ const expectedScope = scopeToken(scope2);
962
+ const code = "invalid_snapshot";
963
+ const dto = readRecord(
964
+ input,
965
+ ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
966
+ ["smtpCapacity"],
967
+ code
968
+ );
969
+ if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
970
+ assertCapacityTag(dto, capacity, code);
971
+ const key = validateAdmissionKey(dto.key, code);
972
+ const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
973
+ const intentHash = hashToken(dto.intentHash, code);
974
+ const fingerprint = hashToken(dto.fingerprint, code);
975
+ const storedSnapshotHash = hashToken(dto.snapshotHash, code);
976
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot, capacity);
977
+ validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
978
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor(
979
+ {
980
+ scope: expectedScope,
981
+ key,
982
+ templateKey: snapshot.template.key,
983
+ provider: snapshot.provider,
984
+ scheduleAt,
985
+ intentHash
986
+ },
987
+ capacity
988
+ )) {
989
+ invalid(code);
990
+ }
991
+ return Object.freeze({
992
+ version: EMAIL_FORMAT_VERSION,
993
+ ...capacityTag(capacity),
994
+ scope: expectedScope,
995
+ key,
996
+ scheduleAt,
997
+ intentHash,
998
+ fingerprint,
999
+ snapshotHash,
1000
+ snapshot
1001
+ });
1002
+ }
1003
+
1004
+ // src/internal/store-codecs.ts
1005
+ var REQUEST = "invalid_command";
1006
+ var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
1007
+ function readStoreId(value, code = REQUEST) {
1008
+ return uuidV4(value, code);
1009
+ }
1010
+ function readLeaseToken(value, code = REQUEST) {
1011
+ 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)) {
1012
+ invalid(code);
1013
+ }
1014
+ return value;
1015
+ }
1016
+ function readLeaseMs(value) {
1017
+ return integer(value, LEASE.min, LEASE.max, REQUEST);
1018
+ }
1019
+ function timeAfter(start, delayMs) {
1020
+ return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
1021
+ }
1022
+ function readStoreCall(input, worker = false, capacity) {
1023
+ const code = "invalid_config";
1024
+ const { smtpCapacity, ...raw } = readRecord(input, ["signal", "timeoutMs"], capacity ? ["smtpCapacity"] : [], code);
1025
+ if (capacity) assertCapacityTag({ smtpCapacity }, capacity, "store_incompatible");
1026
+ const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
1027
+ const timeoutMs = integer(raw.timeoutMs, 1, max, code);
1028
+ const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
1029
+ if (!call.signal) invalid(code);
1030
+ return {
1031
+ signal: call.signal,
1032
+ timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1033
+ };
1034
+ }
1035
+ function readRetryPolicy(input, code = REQUEST) {
1036
+ const raw = readRecord(input, ["maxAttempts", "baseDelayMs", "maxDelayMs"], [], code);
1037
+ const bounds = RETRY_POLICY_BOUNDS;
1038
+ const baseDelayMs = integer(raw.baseDelayMs, bounds.baseDelayMs.min, bounds.baseDelayMs.max, code);
1039
+ return Object.freeze({
1040
+ maxAttempts: integer(raw.maxAttempts, bounds.maxAttempts.min, bounds.maxAttempts.max, code),
1041
+ baseDelayMs,
1042
+ maxDelayMs: integer(raw.maxDelayMs, baseDelayMs, bounds.maxDelayMs.max, code)
1043
+ });
1044
+ }
1045
+ function readRetentionPolicy(input, code = REQUEST) {
1046
+ const { payloadMs, historyMs, idempotencyMs } = readRecord(
1047
+ input,
1048
+ ["payloadMs", "historyMs", "idempotencyMs"],
1049
+ [],
1050
+ code
1051
+ );
1052
+ const bounds = RETENTION_POLICY_BOUNDS;
1053
+ return Object.freeze({
1054
+ payloadMs: integer(payloadMs, bounds.payloadMs.min, bounds.payloadMs.max, code),
1055
+ historyMs: integer(historyMs, bounds.historyMs.min, bounds.historyMs.max, code),
1056
+ idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
1057
+ });
1058
+ }
1059
+ function readStoreAdmission(scope2, input, capacity) {
1060
+ const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
1061
+ const command = validatePreparedCommand(scope2, raw.command, capacity);
1062
+ return Object.freeze({
1063
+ command,
1064
+ admissionKey: encodeAdmissionKey(command.key),
1065
+ jobId: readStoreId(raw.jobId),
1066
+ retry: readRetryPolicy(raw.retry),
1067
+ retention: readRetentionPolicy(raw.retention)
1068
+ });
1069
+ }
1070
+ function readFence(input) {
1071
+ const { jobId, attemptId, token } = readRecord(input, ["jobId", "attemptId", "token"], [], REQUEST);
1072
+ return Object.freeze({ jobId: readStoreId(jobId), attemptId: readStoreId(attemptId), token: readLeaseToken(token) });
1073
+ }
1074
+ function readClaim(input) {
1075
+ const { attemptId, token, leaseMs } = readRecord(input, ["attemptId", "token", "leaseMs"], [], REQUEST);
1076
+ return Object.freeze({
1077
+ attemptId: readStoreId(attemptId),
1078
+ token: readLeaseToken(token),
1079
+ leaseMs: readLeaseMs(leaseMs)
1080
+ });
1081
+ }
1082
+ function readFinish(input, capacity) {
1083
+ const { fence, phase, operationId, result } = readRecord(
1084
+ input,
1085
+ ["fence", "phase", "operationId", "result"],
1086
+ [],
1087
+ REQUEST
1088
+ );
1089
+ if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
1090
+ const evidence2 = readAttemptResult(result, REQUEST, false, capacity);
1091
+ assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
1092
+ return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
1093
+ }
1094
+ function readResolution(input) {
1095
+ const raw = readRecord(input, ["jobId", "attemptId", "action"], ["acknowledgeDuplicateRisk"], REQUEST);
1096
+ const ids = { jobId: readStoreId(raw.jobId), attemptId: readStoreId(raw.attemptId) };
1097
+ if (raw.action === "dismiss" && !Object.hasOwn(raw, "acknowledgeDuplicateRisk")) {
1098
+ return Object.freeze({ ...ids, action: raw.action });
1099
+ }
1100
+ if (raw.action === "redrive" && raw.acknowledgeDuplicateRisk === true) {
1101
+ return Object.freeze({ ...ids, action: raw.action, acknowledgeDuplicateRisk: true });
1102
+ }
1103
+ return invalid(REQUEST);
1104
+ }
1105
+
1106
+ // src/internal/activity-codecs.ts
1107
+ var dispositions = [
1108
+ "accepted",
1109
+ "partially_accepted",
1110
+ "validated",
1111
+ "rejected",
1112
+ "unknown",
1113
+ "failed",
1114
+ "expired",
1115
+ "cancelled"
1116
+ ];
1117
+ function readDisposition(input, code) {
1118
+ const disposition = dispositions.find((value) => value === input);
1119
+ if (disposition) return disposition;
1120
+ if (input === "retry_scheduled") return input;
1121
+ return invalid(code);
1122
+ }
1123
+ function assertActivityDisposition(result, disposition, code) {
1124
+ const { outcome, reason } = result;
1125
+ if (outcome !== "rejected" && outcome !== "unsubmitted") {
1126
+ if (disposition !== outcome) invalid(code);
1127
+ } else if (reason === "expired" || reason === "cancelled") {
1128
+ if (disposition !== reason) invalid(code);
1129
+ } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
1130
+ invalid(code);
1131
+ }
1132
+ }
1133
+ function captureActivity(scope2, input, code, capacity) {
1134
+ const raw = readRecord(
1135
+ input,
1136
+ [
1137
+ "version",
1138
+ "scope",
1139
+ "jobId",
1140
+ "attemptId",
1141
+ "ordinal",
1142
+ "provider",
1143
+ "template",
1144
+ "correlation",
1145
+ "startedAt",
1146
+ "finishedAt",
1147
+ "result",
1148
+ "disposition"
1149
+ ],
1150
+ ["handedOffAt", "smtpCapacity", "recipientCounts"],
1151
+ code
1152
+ );
1153
+ if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope2) invalid(code);
1154
+ assertCapacityTag(raw, capacity, code);
1155
+ if (!capacity && Object.hasOwn(raw, "recipientCounts")) invalid(code);
1156
+ const counts = capacity ? readRecipientCounts(raw.recipientCounts, code, capacity) : void 0;
1157
+ const jobId = readStoreId(raw.jobId, code);
1158
+ const attemptId = readStoreId(raw.attemptId, code);
1159
+ const provider2 = validateProviderRef(raw.provider, code);
1160
+ assertCapacityProvider(provider2, capacity, code);
1161
+ const startedAt = unixMs(raw.startedAt, code);
1162
+ const finishedAt = unixMs(raw.finishedAt, code);
1163
+ const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1164
+ if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1165
+ invalid(code);
1166
+ }
1167
+ const result = readAttemptResult(raw.result, code, true, capacity);
1168
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1169
+ assertEvidenceContext(result, provider2, attemptId, counts, code);
1170
+ const disposition = readDisposition(raw.disposition, code);
1171
+ assertActivityDisposition(result, disposition, code);
1172
+ return Object.freeze({
1173
+ version: EMAIL_FORMAT_VERSION,
1174
+ ...capacityTag(capacity),
1175
+ ...counts ? { recipientCounts: counts } : {},
1176
+ scope: scope2,
1177
+ jobId,
1178
+ attemptId,
1179
+ ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, code),
1180
+ provider: provider2,
1181
+ template: validateTemplateIdentity(raw.template, code),
1182
+ correlation: validateCorrelation(raw.correlation, code),
1183
+ startedAt,
1184
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
1185
+ finishedAt,
1186
+ result,
1187
+ disposition
1188
+ });
1189
+ }
1190
+ function readActivity(scope2, input, code = "store_incompatible", capacity) {
1191
+ const activity = captureActivity(scope2, input, code, capacity);
1192
+ if (capacity) encodeEvidence(activity, code, capacity);
1193
+ return activity;
1194
+ }
1195
+ function activityFor(job, commit, capacity) {
1196
+ const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
1197
+ return captureActivity(
1198
+ job.scope,
1199
+ {
1200
+ version: EMAIL_FORMAT_VERSION,
1201
+ ...capacityTag(capacity),
1202
+ ...capacity ? { recipientCounts: job.recipientCounts } : {},
1203
+ scope: job.scope,
1204
+ jobId: job.jobId,
1205
+ attemptId: commit.attemptId,
1206
+ ordinal: commit.ordinal,
1207
+ provider: job.provider,
1208
+ template: job.template,
1209
+ correlation: job.correlation,
1210
+ startedAt: commit.startedAt,
1211
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1212
+ finishedAt: commit.finishedAt,
1213
+ disposition: commit.disposition,
1214
+ result: {
1215
+ outcome,
1216
+ retry,
1217
+ stage,
1218
+ reason,
1219
+ ...recipients === void 0 ? {} : { recipients },
1220
+ ...messageId === void 0 ? {} : { messageId },
1221
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1222
+ }
1223
+ },
1224
+ "store_incompatible",
1225
+ capacity
1226
+ );
1227
+ }
1228
+ function activityDigest(activity, capacity) {
1229
+ return sha256(encodeEvidence(activity, "store_incompatible", capacity));
1230
+ }
1231
+ function readStoredActivity(scope2, input, code = "store_incompatible", capacity) {
1232
+ const raw = readRecord(input, ["activity", "digest"], [], code);
1233
+ const activity = captureActivity(scope2, raw.activity, code, capacity);
1234
+ const digest2 = hashToken(raw.digest, code);
1235
+ if (activityDigest(activity, capacity) !== digest2) invalid(code);
1236
+ return Object.freeze({ activity, digest: digest2 });
1237
+ }
1238
+ function readProjectionPermit(scope2, input, capacity) {
1239
+ const code = "invalid_command";
1240
+ const {
1241
+ activity,
1242
+ digest: digest2,
1243
+ permitUntil: rawUntil
1244
+ } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1245
+ const stored = readStoredActivity(scope2, { activity, digest: digest2 }, code, capacity);
1246
+ const permitUntil = unixMs(rawUntil, code);
1247
+ if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1248
+ return Object.freeze({ ...stored, permitUntil });
1249
+ }
1250
+ function compareAscii(a, b) {
1251
+ return a < b ? -1 : a > b ? 1 : 0;
1252
+ }
1253
+ function compareActivity(a, b) {
1254
+ return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1255
+ }
1256
+ function cursorPayload(criteria, position) {
1257
+ const binding = criteria.capacity?.binding;
1258
+ return {
1259
+ v: EMAIL_FORMAT_VERSION,
1260
+ s: criteria.scope,
1261
+ j: criteria.jobId,
1262
+ f: criteria.from,
1263
+ b: criteria.before,
1264
+ p: [position.finishedAt, position.jobId, position.attemptId],
1265
+ ...binding ? { c: [binding.format, binding.namespace, binding.maxRecipients] } : {}
1266
+ };
1267
+ }
1268
+ function encodeCursor(criteria, position) {
1269
+ const code = "invalid_cursor";
1270
+ const { encoded } = canonicalJson(cursorPayload(criteria, position), MAX_ACTIVITY_CURSOR_BYTES, code);
1271
+ const cursor = import_node_buffer2.Buffer.from(encoded).toString("base64url");
1272
+ if (cursor.length > MAX_ACTIVITY_CURSOR_BYTES) invalid(code);
1273
+ return cursor;
1274
+ }
1275
+ function decodeCursor(criteria, cursor) {
1276
+ const code = "invalid_cursor";
1277
+ if (typeof cursor !== "string" || cursor.length === 0 || cursor.length > MAX_ACTIVITY_CURSOR_BYTES || !/^[A-Za-z0-9_-]+$/.test(cursor)) {
1278
+ invalid(code);
1279
+ }
1280
+ let input;
1281
+ try {
1282
+ input = JSON.parse(import_node_buffer2.Buffer.from(cursor, "base64url").toString("utf8"));
1283
+ } catch {
1284
+ invalid(code);
1285
+ }
1286
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], criteria.capacity ? ["c"] : [], code);
1287
+ const tuple = readArray(p, 3, code, (entry) => entry);
1288
+ const position = Object.freeze({
1289
+ finishedAt: unixMs(tuple[0], code),
1290
+ jobId: readStoreId(tuple[1], code),
1291
+ attemptId: readStoreId(tuple[2], code)
1292
+ });
1293
+ if (criteria.jobId !== null && position.jobId !== criteria.jobId || criteria.from !== null && position.finishedAt < criteria.from || criteria.before !== null && position.finishedAt >= criteria.before || encodeCursor(criteria, position) !== cursor) {
1294
+ invalid(code);
1295
+ }
1296
+ return position;
1297
+ }
1298
+ function readActivityCriteria(scope2, input, capacity) {
1299
+ const code = "invalid_command";
1300
+ const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1301
+ const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1302
+ const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1303
+ const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1304
+ if (from !== null && before !== null && from > before) invalid(code);
1305
+ const page = capacity?.limits.page ?? ACTIVITY_PAGE_LIMIT;
1306
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, page.min, page.max, code) : page.default;
1307
+ const criteria = { scope: scope2, jobId, from, before, limit, ...capacity ? { capacity } : {} };
1308
+ return Object.freeze({
1309
+ ...criteria,
1310
+ ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
1311
+ });
1312
+ }
1313
+ function readOrderedActivities(criteria, input, maxRows) {
1314
+ const code = "store_incompatible";
1315
+ let previous = criteria.after;
1316
+ return readArray(input, maxRows, code, (row) => {
1317
+ const activity = readActivity(criteria.scope, row, code, criteria.capacity);
1318
+ 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) {
1319
+ invalid(code);
1320
+ }
1321
+ previous = activity;
1322
+ return activity;
1323
+ });
1324
+ }
1325
+ function activityPage(criteria, ordered) {
1326
+ const rows = readOrderedActivities(criteria, ordered, criteria.limit + 1);
1327
+ const more = rows.length > criteria.limit;
1328
+ const items = more ? Object.freeze(rows.slice(0, criteria.limit)) : rows;
1329
+ const last = items.at(-1);
1330
+ return Object.freeze({ items, ...more && last ? { nextCursor: encodeCursor(criteria, last) } : {} });
1331
+ }
1332
+
1333
+ // src/internal/job-summary.ts
1334
+ var STORED = "store_incompatible";
1335
+ function readUnknownResolution(input) {
1336
+ const { attemptId, at, action } = readRecord(input, ["attemptId", "at", "action"], [], STORED);
1337
+ if (action !== "dismiss" && action !== "redrive") invalid(STORED);
1338
+ return Object.freeze({ attemptId: readStoreId(attemptId, STORED), at: unixMs(at, STORED), action });
1339
+ }
1340
+
1341
+ // src/internal/job-record.ts
1342
+ var STORED2 = "store_incompatible";
1343
+ function leasePhase(lease) {
1344
+ return lease.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
1345
+ }
1346
+ function terminalState(disposition, terminalReason, now) {
1347
+ return Object.freeze({
1348
+ state: "terminal",
1349
+ disposition,
1350
+ terminalReason,
1351
+ terminalAt: now,
1352
+ ...disposition === "unknown" ? {} : { settledAt: now }
1353
+ });
1354
+ }
1355
+ function hasRedrive(job) {
1356
+ return job.resolutions.some(({ action }) => action === "redrive");
1357
+ }
1358
+ function pendingAttempt(job) {
1359
+ return job.attempts.find(({ projectionAckAt }) => projectionAckAt === void 0);
1360
+ }
1361
+ function retirementAt(job) {
1362
+ if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
1363
+ const { settledAt } = job.state;
1364
+ const payload = timeAfter(settledAt, job.retention.payloadMs);
1365
+ const history = timeAfter(settledAt, job.retention.historyMs);
1366
+ const identity = timeAfter(settledAt, job.retention.idempotencyMs);
1367
+ const drain = job.projectionPermitUntil === void 0 ? 0 : timeAfter(job.projectionPermitUntil, PROJECTION_DRAIN_MS);
1368
+ if (payload === void 0 || history === void 0 || identity === void 0 || drain === void 0) return;
1369
+ return Math.max(payload, history, identity, drain);
1370
+ }
1371
+ function cleanupAt(job) {
1372
+ if (job.retiring) return job.updatedAt;
1373
+ if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
1374
+ if (job.snapshot) {
1375
+ const payloadAt = timeAfter(job.state.settledAt, job.retention.payloadMs);
1376
+ if (payloadAt === void 0) return;
1377
+ return Math.max(payloadAt, job.attempts.at(-1)?.projectionAckAt ?? 0);
1378
+ }
1379
+ const retireAt = retirementAt(job);
1380
+ return retireAt === void 0 ? void 0 : Math.max(retireAt, job.updatedAt);
1381
+ }
1382
+ function jobSelectors(job) {
1383
+ const { state } = job;
1384
+ const pendingAt = pendingAttempt(job)?.commit.finishedAt;
1385
+ const nextCleanupAt = cleanupAt(job);
1386
+ return {
1387
+ state: state.state,
1388
+ ...state.state === "queued" ? { nextAt: state.nextAt, queuedExpiresAt: job.expiresAt } : {},
1389
+ ...state.state === "leased" ? { leaseEndsAt: state.lease.leaseEndsAt } : {},
1390
+ ...pendingAt === void 0 ? {} : { pendingAt },
1391
+ ...nextCleanupAt === void 0 ? {} : { nextCleanupAt }
1392
+ };
1393
+ }
1394
+ function jobSummary(job) {
1395
+ const { state } = job;
1396
+ let summaryState;
1397
+ if (state.state === "terminal") {
1398
+ const { disposition, terminalReason, terminalAt } = state;
1399
+ summaryState = { state: "terminal", disposition, terminalReason, terminalAt };
1400
+ } else if (state.state === "leased") {
1401
+ summaryState = { state: "leased", phase: leasePhase(state.lease) };
1402
+ } else {
1403
+ summaryState = { state: "queued", nextAt: state.nextAt };
1404
+ }
1405
+ const latest = job.attempts.at(-1)?.commit;
1406
+ return Object.freeze({
1407
+ version: EMAIL_FORMAT_VERSION,
1408
+ ...job.smtpCapacity ? { smtpCapacity: job.smtpCapacity } : {},
1409
+ scope: job.scope,
1410
+ jobId: job.jobId,
1411
+ key: Object.freeze({ ...job.key }),
1412
+ provider: Object.freeze({ ...job.provider }),
1413
+ template: Object.freeze({ ...job.template }),
1414
+ correlation: validateCorrelation(job.correlation, STORED2),
1415
+ scheduleAt: job.scheduleAt,
1416
+ createdAt: job.createdAt,
1417
+ updatedAt: job.updatedAt,
1418
+ expiresAt: job.expiresAt,
1419
+ priority: job.priority,
1420
+ attemptCount: job.attempts.length + Number(state.state === "leased"),
1421
+ ...latest ? {
1422
+ latestAttempt: Object.freeze({
1423
+ attemptId: latest.attemptId,
1424
+ outcome: latest.result.outcome,
1425
+ reason: latest.result.reason
1426
+ })
1427
+ } : {},
1428
+ unknownOpen: state.state === "terminal" && state.disposition === "unknown" && state.settledAt === void 0,
1429
+ resolutions: Object.freeze(job.resolutions.map((entry) => Object.freeze({ ...entry }))),
1430
+ ...summaryState
1431
+ });
1432
+ }
1433
+ function copyCommit(commit, capacity) {
1434
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED2, false, capacity) });
1435
+ }
1436
+ function readStoredSnapshot(job, input, capacity) {
1437
+ let validated;
1438
+ try {
1439
+ validated = validateSnapshot(input, capacity);
1440
+ } catch {
1441
+ return invalid(STORED2);
1442
+ }
1443
+ const { snapshot, snapshotHash } = validated;
1444
+ const metadata = (value, counts) => canonicalJson([value.provider, value.template, value.correlation, counts], 4096, STORED2).encoded;
1445
+ if (snapshotHash !== job.snapshotHash || snapshot.preparedAt - job.createdAt > MAX_PREPARED_AT_SKEW_MS || snapshot.expiresAt !== job.expiresAt || snapshot.priority !== job.priority || metadata(snapshot, recipientCounts(snapshot.envelope)) !== metadata(job, job.recipientCounts)) {
1446
+ invalid(STORED2);
1447
+ }
1448
+ return snapshot;
1449
+ }
1450
+ function optionalTime(raw, key) {
1451
+ return Object.hasOwn(raw, key) ? unixMs(Reflect.get(raw, key), STORED2) : void 0;
1452
+ }
1453
+ function readState(input) {
1454
+ const raw = readRecord(
1455
+ input,
1456
+ ["state"],
1457
+ ["nextAt", "lease", "disposition", "terminalReason", "terminalAt", "settledAt"],
1458
+ STORED2
1459
+ );
1460
+ if (raw.state === "queued") {
1461
+ const { nextAt } = readRecord(raw, ["state", "nextAt"], [], STORED2);
1462
+ return Object.freeze({ state: raw.state, nextAt: unixMs(nextAt, STORED2) });
1463
+ }
1464
+ if (raw.state === "leased") {
1465
+ const { lease } = readRecord(raw, ["state", "lease"], [], STORED2);
1466
+ const active = readRecord(
1467
+ lease,
1468
+ ["attemptId", "token", "startedAt", "grantedAt", "leaseEndsAt"],
1469
+ ["handedOffAt"],
1470
+ STORED2
1471
+ );
1472
+ const startedAt = unixMs(active.startedAt, STORED2);
1473
+ const grantedAt = unixMs(active.grantedAt, STORED2);
1474
+ const leaseEndsAt = unixMs(active.leaseEndsAt, STORED2);
1475
+ const handedOffAt = optionalTime(active, "handedOffAt");
1476
+ const bounds = WORKER_LIMIT_BOUNDS.leaseMs;
1477
+ integer(leaseEndsAt - grantedAt, bounds.min, bounds.max, STORED2);
1478
+ if (grantedAt < startedAt || handedOffAt !== void 0 && handedOffAt !== grantedAt) invalid(STORED2);
1479
+ return Object.freeze({
1480
+ state: raw.state,
1481
+ lease: Object.freeze({
1482
+ attemptId: readStoreId(active.attemptId, STORED2),
1483
+ token: readLeaseToken(active.token, STORED2),
1484
+ startedAt,
1485
+ grantedAt,
1486
+ leaseEndsAt,
1487
+ ...handedOffAt === void 0 ? {} : { handedOffAt }
1488
+ })
1489
+ });
1490
+ }
1491
+ if (raw.state === "terminal") {
1492
+ readRecord(raw, ["state", "disposition", "terminalReason", "terminalAt"], ["settledAt"], STORED2);
1493
+ const disposition = readDisposition(raw.disposition, STORED2);
1494
+ if (disposition === "retry_scheduled") invalid(STORED2);
1495
+ const settledAt = optionalTime(raw, "settledAt");
1496
+ return Object.freeze({
1497
+ state: raw.state,
1498
+ disposition,
1499
+ terminalReason: raw.terminalReason === "attempts_exhausted" ? raw.terminalReason : readAttemptReason(raw.terminalReason, STORED2),
1500
+ terminalAt: unixMs(raw.terminalAt, STORED2),
1501
+ ...settledAt === void 0 ? {} : { settledAt }
1502
+ });
1503
+ }
1504
+ return invalid(STORED2);
1505
+ }
1506
+ function readLedgerAttempt(input, job, capacity) {
1507
+ const entry = readRecord(input, ["commit", "digest"], ["ownerDigest", "permitUntil", "projectionAckAt"], STORED2);
1508
+ const raw = readRecord(
1509
+ entry.commit,
1510
+ ["jobId", "attemptId", "ordinal", "operationId", "startedAt", "finishedAt", "result", "disposition", "reason"],
1511
+ ["handedOffAt", "retryAt"],
1512
+ STORED2
1513
+ );
1514
+ const attemptId = readStoreId(raw.attemptId, STORED2);
1515
+ const startedAt = unixMs(raw.startedAt, STORED2);
1516
+ const handedOffAt = optionalTime(raw, "handedOffAt");
1517
+ const finishedAt = unixMs(raw.finishedAt, STORED2);
1518
+ const retryAt = optionalTime(raw, "retryAt");
1519
+ const result = readAttemptResult(raw.result, STORED2, false, capacity);
1520
+ const ownerDigest = Object.hasOwn(entry, "ownerDigest") ? hashToken(entry.ownerDigest, STORED2) : void 0;
1521
+ const internal = result.reason === "pre_handoff_lease_expired" || result.reason === "post_handoff_lease_expired" || result.reason === "cancelled";
1522
+ 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) {
1523
+ invalid(STORED2);
1524
+ }
1525
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED2);
1526
+ assertEvidenceContext(result, job.provider, attemptId, job.recipientCounts, STORED2);
1527
+ const commit = Object.freeze({
1528
+ jobId: job.jobId,
1529
+ attemptId,
1530
+ ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED2),
1531
+ operationId: readStoreId(raw.operationId, STORED2),
1532
+ startedAt,
1533
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
1534
+ finishedAt,
1535
+ result,
1536
+ disposition: readDisposition(raw.disposition, STORED2),
1537
+ reason: raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED2),
1538
+ ...retryAt === void 0 ? {} : { retryAt }
1539
+ });
1540
+ const permitUntil = optionalTime(entry, "permitUntil");
1541
+ const projectionAckAt = optionalTime(entry, "projectionAckAt");
1542
+ if (permitUntil !== void 0 && (permitUntil - finishedAt < PROJECTION_PERMIT_MS || permitUntil - job.updatedAt > PROJECTION_PERMIT_MS) || projectionAckAt !== void 0 && (permitUntil === void 0 || projectionAckAt < permitUntil - PROJECTION_PERMIT_MS || projectionAckAt > job.updatedAt)) {
1543
+ invalid(STORED2);
1544
+ }
1545
+ const digest2 = hashToken(entry.digest, STORED2);
1546
+ if (digest2 !== activityDigest(activityFor(job, commit, capacity), capacity)) invalid(STORED2);
1547
+ return Object.freeze({
1548
+ commit,
1549
+ digest: digest2,
1550
+ ...ownerDigest === void 0 ? {} : { ownerDigest },
1551
+ ...permitUntil === void 0 ? {} : { permitUntil },
1552
+ ...projectionAckAt === void 0 ? {} : { projectionAckAt }
1553
+ });
1554
+ }
1555
+ function assertHistory(job) {
1556
+ const { state, retry, expiresAt } = job;
1557
+ const seen = /* @__PURE__ */ new Set();
1558
+ let nextAt = Math.max(job.createdAt, job.scheduleAt ?? job.createdAt);
1559
+ let transitionAt = job.createdAt;
1560
+ let resolved = 0;
1561
+ let manual = false;
1562
+ let terminal;
1563
+ let highWater;
1564
+ let pending = false;
1565
+ let lastAck = 0;
1566
+ for (const { commit, permitUntil, projectionAckAt } of job.attempts) {
1567
+ const { attemptId, ordinal: ordinal2, startedAt, finishedAt, result, disposition, reason, retryAt } = commit;
1568
+ if (nextAt === void 0 || startedAt < nextAt || seen.has(attemptId) || ordinal2 !== seen.size + 1 || !manual && ordinal2 > retry.maxAttempts) {
1569
+ invalid(STORED2);
1570
+ }
1571
+ seen.add(attemptId);
1572
+ const expected = attemptEffect(result, attemptId, ordinal2, manual, retry, expiresAt, finishedAt);
1573
+ if (disposition !== expected.disposition || reason !== expected.reason || retryAt !== expected.retryAt)
1574
+ invalid(STORED2);
1575
+ if (permitUntil !== void 0) {
1576
+ if (pending || permitUntil - PROJECTION_PERMIT_MS < lastAck) invalid(STORED2);
1577
+ highWater = permitUntil;
1578
+ }
1579
+ if (projectionAckAt === void 0) pending = true;
1580
+ else lastAck = projectionAckAt;
1581
+ transitionAt = finishedAt;
1582
+ nextAt = retryAt;
1583
+ if (disposition === "retry_scheduled") continue;
1584
+ terminal = terminalState(disposition, reason, finishedAt);
1585
+ const resolution = job.resolutions[resolved];
1586
+ if (disposition === "unknown" && resolution?.attemptId === attemptId) {
1587
+ resolved++;
1588
+ if (resolution.at < finishedAt || resolution.at > job.updatedAt) invalid(STORED2);
1589
+ transitionAt = resolution.at;
1590
+ if (resolution.action === "dismiss") {
1591
+ terminal = { ...terminal, settledAt: resolution.at };
1592
+ } else {
1593
+ if (manual || resolution.at >= expiresAt) invalid(STORED2);
1594
+ manual = true;
1595
+ terminal = void 0;
1596
+ nextAt = resolution.at;
1597
+ }
1598
+ }
1599
+ }
1600
+ if (resolved !== job.resolutions.length || highWater !== job.projectionPermitUntil) invalid(STORED2);
1601
+ if (state.state === "queued") {
1602
+ if (nextAt === void 0 || nextAt !== state.nextAt || !manual && seen.size >= retry.maxAttempts) invalid(STORED2);
1603
+ } else if (state.state === "leased") {
1604
+ const { lease } = state;
1605
+ if (nextAt === void 0 || lease.startedAt < nextAt || lease.startedAt >= expiresAt || lease.grantedAt >= expiresAt || lease.grantedAt > job.updatedAt || seen.has(lease.attemptId) || !manual && seen.size >= retry.maxAttempts) {
1606
+ invalid(STORED2);
1607
+ }
1608
+ } else {
1609
+ if (!terminal) {
1610
+ const { disposition, terminalAt } = state;
1611
+ const expired = terminalAt >= expiresAt;
1612
+ if (nextAt === void 0 || disposition !== "expired" && disposition !== "cancelled" || disposition === "expired" !== expired || terminalAt < transitionAt) {
1613
+ invalid(STORED2);
1614
+ }
1615
+ terminal = terminalState(disposition, disposition, terminalAt);
1616
+ }
1617
+ if (state.disposition !== terminal.disposition || state.terminalReason !== terminal.terminalReason || state.terminalAt !== terminal.terminalAt || state.terminalAt > job.updatedAt || state.settledAt !== terminal.settledAt) {
1618
+ invalid(STORED2);
1619
+ }
1620
+ }
1621
+ if (!job.snapshot) {
1622
+ const pruneAt = state.state === "terminal" && state.settledAt !== void 0 && !pendingAttempt(job) ? timeAfter(state.settledAt, job.retention.payloadMs) : void 0;
1623
+ if (pruneAt === void 0 || pruneAt > job.updatedAt) invalid(STORED2);
1624
+ }
1625
+ if (job.retiring) {
1626
+ const retireAt = retirementAt(job);
1627
+ if (job.snapshot || retireAt === void 0 || retireAt > job.updatedAt) invalid(STORED2);
1628
+ }
1629
+ }
1630
+ function readJobRecord(scope2, input, capacity) {
1631
+ const raw = readRecord(
1632
+ input,
1633
+ [
1634
+ "version",
1635
+ "scope",
1636
+ "jobId",
1637
+ "key",
1638
+ "admissionKey",
1639
+ "fingerprint",
1640
+ "snapshotHash",
1641
+ "retry",
1642
+ "retention",
1643
+ "provider",
1644
+ "template",
1645
+ "correlation",
1646
+ "recipientCounts",
1647
+ "scheduleAt",
1648
+ "createdAt",
1649
+ "updatedAt",
1650
+ "expiresAt",
1651
+ "priority",
1652
+ "revision",
1653
+ "state",
1654
+ "attempts",
1655
+ "resolutions"
1656
+ ],
1657
+ ["snapshot", "projectionPermitUntil", "retiring", "smtpCapacity", "intentHash"],
1658
+ STORED2
1659
+ );
1660
+ if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED2) !== scope2) invalid(STORED2);
1661
+ assertCapacityTag(raw, capacity, STORED2);
1662
+ const recipients = readRecipientCounts(raw.recipientCounts, STORED2, capacity);
1663
+ const key = validateAdmissionKey(raw.key, STORED2);
1664
+ const admissionKey = encodeAdmissionKey(key);
1665
+ if (raw.admissionKey !== admissionKey) invalid(STORED2);
1666
+ if (!capacity && Object.hasOwn(raw, "intentHash")) invalid(STORED2);
1667
+ const intentHash = capacity ? hashToken(raw.intentHash, STORED2) : void 0;
1668
+ const base = {
1669
+ version: EMAIL_FORMAT_VERSION,
1670
+ ...capacityTag(capacity),
1671
+ scope: scope2,
1672
+ jobId: readStoreId(raw.jobId, STORED2),
1673
+ key,
1674
+ admissionKey,
1675
+ fingerprint: hashToken(raw.fingerprint, STORED2),
1676
+ ...intentHash === void 0 ? {} : { intentHash },
1677
+ snapshotHash: hashToken(raw.snapshotHash, STORED2),
1678
+ retry: readRetryPolicy(raw.retry, STORED2),
1679
+ retention: readRetentionPolicy(raw.retention, STORED2),
1680
+ provider: validateProviderRef(raw.provider, STORED2),
1681
+ template: validateTemplateIdentity(raw.template, STORED2),
1682
+ correlation: validateCorrelation(raw.correlation, STORED2),
1683
+ recipientCounts: recipients,
1684
+ scheduleAt: raw.scheduleAt === null ? null : unixMs(raw.scheduleAt, STORED2),
1685
+ createdAt: unixMs(raw.createdAt, STORED2),
1686
+ updatedAt: unixMs(raw.updatedAt, STORED2),
1687
+ expiresAt: unixMs(raw.expiresAt, STORED2),
1688
+ priority: integer(raw.priority, PRIORITY.min, PRIORITY.max, STORED2),
1689
+ revision: readStoreId(raw.revision, STORED2),
1690
+ state: readState(raw.state)
1691
+ };
1692
+ assertCapacityProvider(base.provider, capacity, STORED2);
1693
+ if (intentHash !== void 0 && base.fingerprint !== fingerprintFor({ ...base, templateKey: base.template.key, intentHash }, capacity)) {
1694
+ invalid(STORED2);
1695
+ }
1696
+ if (base.createdAt > base.updatedAt || Math.max(base.createdAt, base.scheduleAt ?? 0) >= base.expiresAt || base.provider.kind === "sendgrid" && !recipients.to) {
1697
+ invalid(STORED2);
1698
+ }
1699
+ const projectionPermitUntil = optionalTime(raw, "projectionPermitUntil");
1700
+ const retiring = Object.hasOwn(raw, "retiring");
1701
+ if (retiring && raw.retiring !== true) invalid(STORED2);
1702
+ const job = Object.freeze({
1703
+ ...base,
1704
+ ...Object.hasOwn(raw, "snapshot") ? { snapshot: readStoredSnapshot(base, raw.snapshot, capacity) } : {},
1705
+ attempts: readArray(raw.attempts, MAX_ATTEMPT_LEDGER, STORED2, (entry) => readLedgerAttempt(entry, base, capacity)),
1706
+ resolutions: readArray(raw.resolutions, 2, STORED2, readUnknownResolution),
1707
+ ...projectionPermitUntil === void 0 ? {} : { projectionPermitUntil },
1708
+ ...retiring ? { retiring: true } : {}
1709
+ });
1710
+ assertHistory(job);
1711
+ return job;
1712
+ }
1713
+
1714
+ // src/internal/job-transitions.ts
1715
+ function guard(job, { now }, before) {
1716
+ if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
1717
+ invalid("store_unavailable");
1718
+ }
1719
+ return {
1720
+ scope: job.scope,
1721
+ jobId: job.jobId,
1722
+ revision: job.revision,
1723
+ state: job.state,
1724
+ ...job.retiring ? { retiring: true } : {},
1725
+ atOrAfter: now,
1726
+ ...before === void 0 ? {} : { before }
1727
+ };
1728
+ }
1729
+ function replace(job, time2, patch, value, before, pendingAck) {
1730
+ const expect = guard(job, time2, before);
1731
+ const next = Object.freeze({ ...patch, updatedAt: time2.now, revision: time2.revision });
1732
+ return {
1733
+ value: value(next),
1734
+ write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
1735
+ };
1736
+ }
1737
+ function newJob(admission, time2, capacity) {
1738
+ const { command, jobId, retry, retention, admissionKey } = admission;
1739
+ const { scope: scope2, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
1740
+ const now = unixMs(time2.now, "store_unavailable");
1741
+ if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
1742
+ const nextAt = Math.max(now, scheduleAt ?? now);
1743
+ if (nextAt >= snapshot.expiresAt) invalid("expired");
1744
+ return Object.freeze({
1745
+ version: EMAIL_FORMAT_VERSION,
1746
+ ...capacityTag(capacity),
1747
+ ...capacity ? { intentHash: command.intentHash } : {},
1748
+ scope: scope2,
1749
+ jobId,
1750
+ key,
1751
+ admissionKey,
1752
+ fingerprint,
1753
+ snapshotHash,
1754
+ snapshot,
1755
+ retry,
1756
+ retention,
1757
+ provider: snapshot.provider,
1758
+ template: snapshot.template,
1759
+ correlation: snapshot.correlation,
1760
+ recipientCounts: recipientCounts(snapshot.envelope),
1761
+ scheduleAt,
1762
+ createdAt: now,
1763
+ updatedAt: now,
1764
+ expiresAt: snapshot.expiresAt,
1765
+ priority: snapshot.priority,
1766
+ revision: time2.revision,
1767
+ state: Object.freeze({ state: "queued", nextAt }),
1768
+ attempts: Object.freeze([]),
1769
+ resolutions: Object.freeze([])
1770
+ });
1771
+ }
1772
+ function endOfGrant(now, leaseMs) {
1773
+ return timeAfter(now, leaseMs) ?? invalid("store_unavailable");
1774
+ }
1775
+ function withLease(job, lease) {
1776
+ return { ...job, state: Object.freeze({ state: "leased", lease: Object.freeze(lease) }) };
1777
+ }
1778
+ function liveLease(job, fence, phase, now) {
1779
+ if (job.jobId !== fence.jobId || job.state.state !== "leased") return;
1780
+ const { lease } = job.state;
1781
+ if (lease.attemptId !== fence.attemptId || lease.token !== fence.token || leasePhase(lease) !== phase || now >= lease.leaseEndsAt) {
1782
+ return;
1783
+ }
1784
+ return lease;
1785
+ }
1786
+ function claimJob(job, claim, time2, capacity) {
1787
+ const { now } = time2;
1788
+ if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
1789
+ const manual = hasRedrive(job);
1790
+ const ordinal2 = job.attempts.length + 1;
1791
+ if (ordinal2 > MAX_ATTEMPT_LEDGER || !manual && ordinal2 > job.retry.maxAttempts) invalid("store_incompatible");
1792
+ if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
1793
+ const snapshot = readStoredSnapshot(job, job.snapshot, capacity);
1794
+ const lease = Object.freeze({
1795
+ attemptId: claim.attemptId,
1796
+ token: claim.token,
1797
+ startedAt: now,
1798
+ grantedAt: now,
1799
+ leaseEndsAt: endOfGrant(now, claim.leaseMs)
1800
+ });
1801
+ return replace(
1802
+ job,
1803
+ time2,
1804
+ withLease(job, lease),
1805
+ (next) => Object.freeze({
1806
+ job: jobSummary(next),
1807
+ snapshot,
1808
+ fence: Object.freeze({ jobId: job.jobId, attemptId: lease.attemptId, token: lease.token }),
1809
+ lease: Object.freeze({ grantedAt: lease.grantedAt, leaseEndsAt: lease.leaseEndsAt }),
1810
+ ordinal: ordinal2,
1811
+ manual
1812
+ }),
1813
+ Math.min(job.expiresAt, lease.leaseEndsAt)
1814
+ );
1815
+ }
1816
+ function renewJob(job, fence, leaseMs, time2) {
1817
+ const lease = liveLease(job, fence, "pre_handoff", time2.now);
1818
+ if (!lease || time2.now >= job.expiresAt) return null;
1819
+ const grant = Object.freeze({
1820
+ grantedAt: time2.now,
1821
+ // A renewal never shortens a still-live grant, even if the caller requests a smaller duration.
1822
+ leaseEndsAt: Math.max(lease.leaseEndsAt, endOfGrant(time2.now, leaseMs))
1823
+ });
1824
+ return replace(
1825
+ job,
1826
+ time2,
1827
+ withLease(job, { ...lease, ...grant }),
1828
+ () => grant,
1829
+ Math.min(job.expiresAt, lease.leaseEndsAt)
1830
+ );
1831
+ }
1832
+ function markJob(job, fence, leaseMs, time2) {
1833
+ const lease = liveLease(job, fence, "pre_handoff", time2.now);
1834
+ if (!lease || time2.now >= job.expiresAt) return null;
1835
+ const grant = Object.freeze({
1836
+ grantedAt: time2.now,
1837
+ handoffAt: time2.now,
1838
+ leaseEndsAt: endOfGrant(time2.now, leaseMs)
1839
+ });
1840
+ return replace(
1841
+ job,
1842
+ time2,
1843
+ withLease(job, {
1844
+ ...lease,
1845
+ grantedAt: grant.grantedAt,
1846
+ handedOffAt: grant.handoffAt,
1847
+ leaseEndsAt: grant.leaseEndsAt
1848
+ }),
1849
+ () => grant,
1850
+ Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
1851
+ );
1852
+ }
1853
+ function finalize(job, lease, operationId, result, time2, owner, capacity) {
1854
+ const { now } = time2;
1855
+ const { attemptId, startedAt, handedOffAt } = lease;
1856
+ const ordinal2 = job.attempts.length + 1;
1857
+ const effect = attemptEffect(result, attemptId, ordinal2, hasRedrive(job), job.retry, job.expiresAt, now);
1858
+ const commit = Object.freeze({
1859
+ jobId: job.jobId,
1860
+ attemptId,
1861
+ ordinal: ordinal2,
1862
+ operationId,
1863
+ startedAt,
1864
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
1865
+ finishedAt: now,
1866
+ result,
1867
+ ...effect
1868
+ });
1869
+ const entry = Object.freeze({
1870
+ commit,
1871
+ digest: activityDigest(activityFor(job, commit, capacity), capacity),
1872
+ ...owner ? { ownerDigest: sha256(lease.token) } : {}
1873
+ });
1874
+ const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
1875
+ let before = owner ? lease.leaseEndsAt : void 0;
1876
+ if (result.reason === "cancelled" || result.retry === "safe_transient" && effect.disposition !== "expired") {
1877
+ before = Math.min(before ?? job.expiresAt, job.expiresAt);
1878
+ }
1879
+ return replace(
1880
+ job,
1881
+ time2,
1882
+ { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
1883
+ () => copyCommit(commit, capacity),
1884
+ before
1885
+ );
1886
+ }
1887
+ function finishJob(job, request, time2, capacity) {
1888
+ const { fence, phase, operationId, result } = request;
1889
+ if (job.jobId !== fence.jobId) return null;
1890
+ assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
1891
+ const previous = job.attempts.find(({ commit }) => commit.attemptId === fence.attemptId);
1892
+ if (previous) {
1893
+ const { commit } = previous;
1894
+ const previousPhase = commit.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
1895
+ if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
1896
+ return null;
1897
+ }
1898
+ if (sha256(encodeEvidence(result, "invalid_command", capacity)) !== sha256(encodeEvidence(commit.result, "store_incompatible", capacity))) {
1899
+ invalid("invalid_command");
1900
+ }
1901
+ return { value: copyCommit(commit, capacity) };
1902
+ }
1903
+ const lease = liveLease(job, fence, phase, time2.now);
1904
+ if (!lease) return null;
1905
+ if (result.reason === "expired" && time2.now < job.expiresAt) invalid("invalid_command");
1906
+ assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
1907
+ return finalize(job, lease, operationId, result, time2, true, capacity);
1908
+ }
1909
+ function recoverJob(job, operationId, time2, capacity) {
1910
+ if (job.state.state !== "leased" || time2.now < job.state.lease.leaseEndsAt) return null;
1911
+ const { lease } = job.state;
1912
+ const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
1913
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time2, false, capacity);
1914
+ }
1915
+ function expireJob(job, time2) {
1916
+ if (job.state.state !== "queued" || time2.now < job.expiresAt) return null;
1917
+ return replace(job, time2, { ...job, state: terminalState("expired", "expired", time2.now) }, jobSummary);
1918
+ }
1919
+ function cancelJob(job, operationId, time2, capacity) {
1920
+ const { state } = job;
1921
+ if (state.state === "terminal") {
1922
+ return {
1923
+ value: Object.freeze({
1924
+ status: state.disposition === "cancelled" ? "cancelled" : "too_late",
1925
+ job: jobSummary(job)
1926
+ })
1927
+ };
1928
+ }
1929
+ if (time2.now >= job.expiresAt || state.state === "leased" && state.lease.handedOffAt !== void 0) {
1930
+ return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
1931
+ }
1932
+ if (state.state === "leased") {
1933
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time2, false, capacity);
1934
+ const { write } = decision;
1935
+ if (write?.kind !== "replace") invalid("store_incompatible");
1936
+ return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
1937
+ }
1938
+ return replace(
1939
+ job,
1940
+ time2,
1941
+ { ...job, state: terminalState("cancelled", "cancelled", time2.now) },
1942
+ (next) => Object.freeze({ status: "cancelled", job: jobSummary(next) }),
1943
+ job.expiresAt
1944
+ );
1945
+ }
1946
+ function resolveJob(job, request, time2) {
1947
+ if (job.jobId !== request.jobId) invalid("not_found");
1948
+ const replay = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
1949
+ if (replay) {
1950
+ if (replay.action !== request.action) invalid("resolution_conflict");
1951
+ return { value: Object.freeze({ status: "replayed", job: jobSummary(job) }) };
1952
+ }
1953
+ const { state } = job;
1954
+ if (state.state !== "terminal" || state.disposition !== "unknown" || state.settledAt !== void 0 || job.attempts.at(-1)?.commit.attemptId !== request.attemptId) {
1955
+ invalid("resolution_conflict");
1956
+ }
1957
+ const redrive = request.action === "redrive";
1958
+ if (redrive) {
1959
+ if (hasRedrive(job) || !job.snapshot) invalid("resolution_conflict");
1960
+ if (time2.now >= job.expiresAt) invalid("expired");
1961
+ }
1962
+ const resolutions = Object.freeze([
1963
+ ...job.resolutions,
1964
+ Object.freeze({ attemptId: request.attemptId, action: request.action, at: time2.now })
1965
+ ]);
1966
+ const nextState = redrive ? Object.freeze({ state: "queued", nextAt: time2.now }) : Object.freeze({ ...state, settledAt: time2.now });
1967
+ return replace(
1968
+ job,
1969
+ time2,
1970
+ { ...job, resolutions, state: nextState },
1971
+ (next) => Object.freeze({ status: "resolved", job: jobSummary(next) }),
1972
+ redrive ? job.expiresAt : void 0
1973
+ );
1974
+ }
1975
+ function replaceAttempt(job, previous, entry) {
1976
+ return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
1977
+ }
1978
+ function reserveJobProjection(job, time2, capacity) {
1979
+ const entry = pendingAttempt(job);
1980
+ if (job.retiring || !entry || entry.commit.finishedAt > time2.now) return null;
1981
+ const permitUntil = timeAfter(time2.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
1982
+ const activity = activityFor(job, entry.commit, capacity);
1983
+ const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
1984
+ const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
1985
+ return replace(
1986
+ job,
1987
+ time2,
1988
+ { ...job, attempts, projectionPermitUntil: Math.max(job.projectionPermitUntil ?? 0, permitUntil) },
1989
+ () => permit,
1990
+ permitUntil
1991
+ );
1992
+ }
1993
+ function matchingProjection(job, permit) {
1994
+ const { scope: scope2, jobId, attemptId } = permit.activity;
1995
+ if (!job || job.scope !== scope2 || job.jobId !== jobId) return;
1996
+ return job.attempts.find(
1997
+ (entry) => entry.commit.attemptId === attemptId && entry.digest === permit.digest && entry.permitUntil !== void 0 && permit.permitUntil <= entry.permitUntil && permit.permitUntil - entry.commit.finishedAt >= PROJECTION_PERMIT_MS
1998
+ );
1999
+ }
2000
+ function assertMatchingActivity(stored, permit) {
2001
+ const { activity } = permit;
2002
+ if (stored.activity.scope !== activity.scope || stored.activity.jobId !== activity.jobId || stored.activity.attemptId !== activity.attemptId || stored.digest !== permit.digest) {
2003
+ invalid("store_incompatible");
2004
+ }
2005
+ }
2006
+ function decideActivityPut(job, permit, existing, now) {
2007
+ if (existing) assertMatchingActivity(existing, permit);
2008
+ if (!existing && now >= permit.permitUntil) return "permit_expired";
2009
+ const entry = matchingProjection(job, permit);
2010
+ if (!entry) invalid("invalid_command");
2011
+ if (existing) return "present";
2012
+ if (entry.projectionAckAt !== void 0 || job?.retiring) invalid("store_incompatible");
2013
+ if (now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
2014
+ return "insert";
2015
+ }
2016
+ function acknowledgeJobProjection(job, permit, proof, time2) {
2017
+ const entry = matchingProjection(job, permit);
2018
+ if (!entry) return { value: "stale" };
2019
+ if (proof) assertMatchingActivity(proof, permit);
2020
+ if (entry.projectionAckAt !== void 0) return { value: "already_acknowledged" };
2021
+ if (!proof || job.retiring) return { value: "stale" };
2022
+ if (time2.now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
2023
+ const attempts = replaceAttempt(job, entry, { ...entry, projectionAckAt: time2.now });
2024
+ return replace(job, time2, { ...job, attempts }, () => "acknowledged", void 0, {
2025
+ attemptId: entry.commit.attemptId,
2026
+ digest: entry.digest
2027
+ });
2028
+ }
2029
+ function cleanupJob(job, time2) {
2030
+ const due = jobSelectors(job).nextCleanupAt;
2031
+ if (due === void 0 || due > time2.now) return null;
2032
+ if (job.retiring) {
2033
+ return {
2034
+ write: {
2035
+ kind: "purge",
2036
+ guard: guard(job, time2),
2037
+ attemptIds: Object.freeze(job.attempts.map(({ commit }) => commit.attemptId))
2038
+ },
2039
+ value: "purged"
2040
+ };
2041
+ }
2042
+ if (job.snapshot) {
2043
+ const pruned = { ...job };
2044
+ delete pruned.snapshot;
2045
+ return replace(job, time2, pruned, () => "payload_pruned");
2046
+ }
2047
+ return replace(job, time2, { ...job, retiring: true }, () => "retirement_started");
2048
+ }
2049
+
2050
+ // src/stores/mongoose/connection.ts
2051
+ var import_node_perf_hooks2 = require("perf_hooks");
2052
+ var import_node_util4 = require("util");
2053
+ var SIMPLE = Object.freeze({ locale: "simple" });
2054
+ var MAX_SERVER_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max;
2055
+ function durable(maxTimeMS) {
2056
+ return { w: "majority", j: true, wtimeout: maxTimeMS };
2057
+ }
2058
+ function doc(value, code) {
2059
+ if (typeof value !== "object" || value === null || Object.getPrototypeOf(value) !== Object.prototype) invalid(code);
2060
+ return value;
2061
+ }
2062
+ function batch(reply, max, expectedNamespace) {
2063
+ const { cursor } = reply;
2064
+ const { firstBatch, id, ns } = doc(cursor, "store_incompatible");
2065
+ if (id !== 0 || expectedNamespace !== void 0 && ns !== expectedNamespace || !Array.isArray(firstBatch) || firstBatch.length > max)
2066
+ invalid("store_incompatible");
2067
+ return firstBatch.map((row) => doc(row, "store_incompatible"));
2068
+ }
2069
+ function serverCode(error) {
2070
+ if (error instanceof Error && error.name === "MongoServerError" && "code" in error && typeof error.code === "number")
2071
+ return error.code;
2072
+ }
2073
+ function checkConnectionType(connection) {
2074
+ if (!connection || typeof connection !== "object" || import_node_util4.types.isProxy(connection) || typeof connection.base?.Connection !== "function" || !(connection instanceof connection.base.Connection) || connection === connection.base.connection)
2075
+ invalid("invalid_config");
2076
+ const version2 = connection.base.version;
2077
+ if (typeof version2 !== "string" || !/^9\.\d+\.\d+$/.test(version2)) invalid("invalid_config");
2078
+ const [, minor = 0, patch = 0] = version2.split(".").map(Number);
2079
+ if (minor < 12 || minor === 12 && patch < 2) {
2080
+ invalid("invalid_config");
2081
+ }
2082
+ }
2083
+ var MongoConnection = class {
2084
+ constructor(connection, names) {
2085
+ this.connection = connection;
2086
+ this.names = names;
2087
+ }
2088
+ connection;
2089
+ names;
2090
+ setName;
2091
+ timeFloor = 0;
2092
+ bind() {
2093
+ const { connection, names } = this;
2094
+ if (connection.readyState !== 1 || !connection.db) invalid("store_unavailable");
2095
+ for (const model of Object.values(connection.models)) {
2096
+ if (model.modelName === names.jobsModelName || model.modelName === names.activitiesModelName || model.collection.name === names.jobsCollection || model.collection.name === names.activitiesCollection) {
2097
+ invalid("store_incompatible");
2098
+ }
2099
+ }
2100
+ const client = connection.getClient();
2101
+ const options = client.options;
2102
+ if (options.directConnection || options.loadBalanced || options.autoEncryption || options.compressors.some((name) => name !== "none") || !!options.proxyHost || options.retryReads && options.retryWrites && options.maxAdaptiveRetries !== 0 || options.connectTimeoutMS <= 0 || !Number.isFinite(options.connectTimeoutMS))
2103
+ invalid("store_incompatible");
2104
+ return { db: connection.db, client };
2105
+ }
2106
+ ensureBound(binding, write) {
2107
+ const c = this.connection;
2108
+ if (c.readyState !== 1 || binding.db !== c.db || binding.client !== c.getClient())
2109
+ invalid(write ? "write_unconfirmed" : "store_unavailable");
2110
+ }
2111
+ async exec(binding, budget, command, target = "store", write = false, definite = []) {
2112
+ this.ensureBound(binding, false);
2113
+ budget.check();
2114
+ const timeLeft = budget.remainingMs();
2115
+ if (timeLeft <= 0) budget.check();
2116
+ const maxTimeMS = Math.min(MAX_SERVER_MS, Math.max(1, Math.floor(timeLeft)));
2117
+ const db = target === "admin" ? binding.client.db("admin") : binding.db;
2118
+ const wire = { ...command, maxTimeMS, ...write ? { writeConcern: durable(maxTimeMS) } : {} };
2119
+ let raw;
2120
+ try {
2121
+ raw = await db.command(wire, {
2122
+ signal: budget.signal,
2123
+ readPreference: "primary",
2124
+ promoteValues: true,
2125
+ promoteLongs: true,
2126
+ useBigInt64: false,
2127
+ raw: false
2128
+ });
2129
+ } catch (error) {
2130
+ const code = budget.signal.aborted ? void 0 : serverCode(error);
2131
+ if (code !== void 0 && definite.includes(code)) return { kind: "definite_error", code };
2132
+ if (write) invalid("write_unconfirmed");
2133
+ budget.check();
2134
+ if (code === 50 || code === 262) invalid("deadline");
2135
+ return invalid(code === 72 || code === 115 || code === 148 ? "store_incompatible" : "store_unavailable");
2136
+ }
2137
+ try {
2138
+ budget.check();
2139
+ } catch (error) {
2140
+ if (write) invalid("write_unconfirmed");
2141
+ throw error;
2142
+ }
2143
+ this.ensureBound(binding, write);
2144
+ const failure = write ? "write_unconfirmed" : "store_unavailable";
2145
+ const reply = doc(raw, failure);
2146
+ if (reply.ok !== 1 || Object.hasOwn(reply, "writeConcernError") || Object.hasOwn(reply, "writeConcernErrors"))
2147
+ invalid(failure);
2148
+ return { kind: "ack", reply };
2149
+ }
2150
+ async read(binding, budget, command, target) {
2151
+ const result = await this.exec(binding, budget, command, target);
2152
+ if (result.kind !== "ack") return invalid("store_unavailable");
2153
+ return result.reply;
2154
+ }
2155
+ async write(binding, budget, command, definite) {
2156
+ return this.exec(binding, budget, command, "store", true, definite);
2157
+ }
2158
+ async hello(binding, budget) {
2159
+ const started = import_node_perf_hooks2.performance.now();
2160
+ const hello = await this.read(binding, budget, { hello: 1 }, "admin");
2161
+ if (typeof hello.setName !== "string" || !hello.setName || hello.msg === "isdbgrid" || hello.serviceId !== void 0 || hello.readOnly !== false || !Number.isInteger(hello.logicalSessionTimeoutMinutes) || this.setName !== void 0 && hello.setName !== this.setName)
2162
+ invalid("store_incompatible");
2163
+ if (hello.isWritablePrimary !== true || hello.secondary !== false || hello.me !== hello.primary)
2164
+ invalid("store_unavailable");
2165
+ if (!(hello.localTime instanceof Date) || import_node_perf_hooks2.performance.now() - started >= CLOCK_MARGIN_MS)
2166
+ invalid("store_unavailable");
2167
+ const now = unixMs(hello.localTime.getTime(), "store_unavailable");
2168
+ return { now, setName: hello.setName };
2169
+ }
2170
+ async now(binding, budget) {
2171
+ const floor = this.timeFloor;
2172
+ const { now } = await this.hello(binding, budget);
2173
+ if (now < floor) invalid("store_unavailable");
2174
+ this.timeFloor = Math.max(now, this.timeFloor);
2175
+ return now;
2176
+ }
2177
+ /** Verify the selected primary, not merely the URI or initial seed. */
2178
+ async verifyTopology(binding, budget) {
2179
+ const { setName } = await this.hello(binding, budget);
2180
+ const status = await this.read(binding, budget, { serverStatus: 1, none: 1, storageEngine: 1, repl: 1 }, "admin");
2181
+ const engine = doc(status.storageEngine, "store_incompatible");
2182
+ const repl = doc(status.repl, "store_incompatible");
2183
+ if (typeof status.version !== "string" || !/^8\.\d+\.\d+$/.test(status.version) || engine.name !== "wiredTiger" || engine.persistent !== true || engine.supportsCommittedReads !== true || engine.readOnly !== false || repl.setName !== setName || repl.userWriteBlockMode !== void 0 && repl.userWriteBlockMode !== 1)
2184
+ invalid("store_incompatible");
2185
+ if (repl.isWritablePrimary !== true) invalid("store_unavailable");
2186
+ const { config } = await this.read(binding, budget, { replSetGetConfig: 1 }, "admin");
2187
+ const policy = doc(config, "store_incompatible");
2188
+ if (policy._id !== setName || policy.configsvr === true || policy.writeConcernMajorityJournalDefault !== true)
2189
+ invalid("store_incompatible");
2190
+ const { parsed } = await this.read(binding, budget, { getCmdLineOpts: 1 }, "admin");
2191
+ const settings = doc(parsed, "store_incompatible");
2192
+ if (settings.sharding !== void 0) invalid("store_incompatible");
2193
+ this.setName = setName;
2194
+ }
2195
+ };
2196
+ function serverWindow(atOrAfter, before) {
2197
+ const since = { $gte: ["$$NOW", new Date(atOrAfter)] };
2198
+ return before === void 0 ? since : { $and: [since, { $lt: ["$$NOW", new Date(before)] }] };
2199
+ }
2200
+
2201
+ // src/stores/mongoose/operations.ts
2202
+ var import_node_crypto2 = require("crypto");
2203
+
2204
+ // src/stores/mongoose/records.ts
2205
+ var STORED3 = "store_incompatible";
2206
+ function jobIdKey(scope2, jobId) {
2207
+ return `${scope2}:${jobId}`;
2208
+ }
2209
+ function activityKey({ scope: scope2, jobId, attemptId }) {
2210
+ return { scope: scope2, jobId, attemptId };
2211
+ }
2212
+ function jobBson(job) {
2213
+ const { state, expiresAt, ...logical } = job;
2214
+ const { queuedExpiresAt, ...selectors } = jobSelectors(job);
2215
+ return {
2216
+ _id: jobIdKey(job.scope, job.jobId),
2217
+ ...logical,
2218
+ ...selectors,
2219
+ lifecycle: state,
2220
+ messageExpiresAt: expiresAt,
2221
+ ...queuedExpiresAt === void 0 ? {} : { expiresAt: queuedExpiresAt }
2222
+ };
2223
+ }
2224
+ function activityBson({ activity, digest: digest2 }) {
2225
+ return { ...activity, complete: true, digest: digest2 };
2226
+ }
2227
+ var jobRequired = [
2228
+ "_id",
2229
+ "version",
2230
+ "scope",
2231
+ "jobId",
2232
+ "key",
2233
+ "admissionKey",
2234
+ "fingerprint",
2235
+ "snapshotHash",
2236
+ "retry",
2237
+ "retention",
2238
+ "provider",
2239
+ "template",
2240
+ "correlation",
2241
+ "recipientCounts",
2242
+ "scheduleAt",
2243
+ "createdAt",
2244
+ "updatedAt",
2245
+ "messageExpiresAt",
2246
+ "priority",
2247
+ "revision",
2248
+ "lifecycle",
2249
+ "state",
2250
+ "attempts",
2251
+ "resolutions"
2252
+ ];
2253
+ var jobOptional = [
2254
+ "snapshot",
2255
+ "projectionPermitUntil",
2256
+ "retiring",
2257
+ "nextAt",
2258
+ "expiresAt",
2259
+ "leaseEndsAt",
2260
+ "pendingAt",
2261
+ "nextCleanupAt"
2262
+ ];
2263
+ function readJobBson(scope2, raw, capacity) {
2264
+ const { _id, lifecycle: lifecycle2, messageExpiresAt, state, nextAt, expiresAt, leaseEndsAt, pendingAt, nextCleanupAt, ...rest } = readRecord(raw, jobRequired, capacity ? [...jobOptional, "smtpCapacity", "intentHash"] : jobOptional, STORED3);
2265
+ const job = readJobRecord(scope2, { ...rest, state: lifecycle2, expiresAt: messageExpiresAt }, capacity);
2266
+ const selectors = jobSelectors(job);
2267
+ for (const [key, value, expected] of [
2268
+ ["state", state, selectors.state],
2269
+ ["nextAt", nextAt, selectors.nextAt],
2270
+ ["expiresAt", expiresAt, selectors.queuedExpiresAt],
2271
+ ["leaseEndsAt", leaseEndsAt, selectors.leaseEndsAt],
2272
+ ["pendingAt", pendingAt, selectors.pendingAt],
2273
+ ["nextCleanupAt", nextCleanupAt, selectors.nextCleanupAt]
2274
+ ]) {
2275
+ if (expected === void 0 ? Object.hasOwn(raw, key) : value !== expected) invalid(STORED3);
2276
+ }
2277
+ if (_id !== jobIdKey(scope2, job.jobId)) invalid(STORED3);
2278
+ return job;
2279
+ }
2280
+ var activityIdentity = ["_id", "scope", "jobId", "attemptId"];
2281
+ var activityRequired = [
2282
+ ...activityIdentity,
2283
+ "version",
2284
+ "complete",
2285
+ "digest",
2286
+ "ordinal",
2287
+ "provider",
2288
+ "template",
2289
+ "correlation",
2290
+ "startedAt",
2291
+ "finishedAt",
2292
+ "result",
2293
+ "disposition"
2294
+ ];
2295
+ var activityOptional = ["handedOffAt"];
2296
+ function readActivityBson(expectedScope, row, capacity) {
2297
+ if (!Object.hasOwn(row, "complete")) {
2298
+ const { _id: _id2, scope: scope2, jobId, attemptId, stubDeleteAt, ...tag } = readRecord(
2299
+ row,
2300
+ [...activityIdentity, "stubDeleteAt"],
2301
+ capacity ? ["smtpCapacity"] : [],
2302
+ STORED3
2303
+ );
2304
+ assertCapacityTag(tag, capacity, STORED3);
2305
+ readStoreId(_id2, STORED3);
2306
+ readStoreId(jobId, STORED3);
2307
+ readStoreId(attemptId, STORED3);
2308
+ if (scopeToken(scope2, STORED3) !== expectedScope || !(stubDeleteAt instanceof Date)) invalid(STORED3);
2309
+ unixMs(stubDeleteAt.getTime(), STORED3);
2310
+ return;
2311
+ }
2312
+ const { _id, complete, digest: digest2, ...activity } = readRecord(
2313
+ row,
2314
+ activityRequired,
2315
+ capacity ? [...activityOptional, "smtpCapacity", "recipientCounts"] : activityOptional,
2316
+ STORED3
2317
+ );
2318
+ readStoreId(_id, STORED3);
2319
+ const stored = readStoredActivity(expectedScope, { activity, digest: digest2 }, STORED3, capacity);
2320
+ if (complete !== true) invalid(STORED3);
2321
+ return stored;
2322
+ }
2323
+ function objectSchema(properties, optional = []) {
2324
+ const required = Object.keys(properties).filter((field) => !optional.includes(field));
2325
+ return {
2326
+ bsonType: "object",
2327
+ ...required.length ? { required } : {},
2328
+ additionalProperties: false,
2329
+ properties
2330
+ };
2331
+ }
2332
+ var bsonObject = { bsonType: "object" };
2333
+ var string = { bsonType: "string" };
2334
+ var numeric = { bsonType: ["int", "long", "double"], multipleOf: 1 };
2335
+ var version = { ...numeric, enum: [EMAIL_FORMAT_VERSION] };
2336
+ var time = { ...numeric, minimum: 0, maximum: MAX_UNIX_MS };
2337
+ var ordinal = { ...numeric, minimum: 1, maximum: MAX_ATTEMPT_LEDGER };
2338
+ var scope = { bsonType: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$" };
2339
+ var uuidPattern = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
2340
+ var uuid = { bsonType: "string", pattern: `^${uuidPattern}$` };
2341
+ var digest = { bsonType: "string", pattern: "^[0-9a-f]{64}$" };
2342
+ var provider = objectSchema({
2343
+ kind: { enum: ["smtp", "sendgrid"] },
2344
+ key: string,
2345
+ mode: { enum: ["live", "sandbox"] }
2346
+ });
2347
+ var template = objectSchema({ key: string, revision: string });
2348
+ var correlation = { ...bsonObject, maxProperties: MESSAGE_LIMITS.correlationEntries, additionalProperties: string };
2349
+ var smtpProvider = objectSchema({ kind: { enum: ["smtp"] }, key: string, mode: { enum: ["live"] } });
2350
+ function resultFields(capacity) {
2351
+ const max = recipientLimit(capacity);
2352
+ const recipient = objectSchema({
2353
+ group: { enum: ["to", "cc", "bcc"] },
2354
+ index: { ...numeric, minimum: 0, maximum: max - 1 },
2355
+ status: { enum: ["accepted", "rejected"] }
2356
+ });
2357
+ return {
2358
+ outcome: string,
2359
+ retry: { enum: ["never", "safe_transient"] },
2360
+ stage: string,
2361
+ reason: string,
2362
+ recipients: { bsonType: "array", maxItems: max, items: recipient },
2363
+ messageId: { ...string, maxLength: "<00000000-0000-4000-8000-000000000000@email.invalid>".length },
2364
+ ...capacity ? {} : { providerMessageId: { ...string, maxLength: 128 } }
2365
+ };
2366
+ }
2367
+ var resultOptional = ["recipients", "messageId", "providerMessageId"];
2368
+ function ledgerAttempt(capacity) {
2369
+ return objectSchema(
2370
+ {
2371
+ commit: objectSchema(
2372
+ {
2373
+ jobId: uuid,
2374
+ attemptId: uuid,
2375
+ ordinal,
2376
+ operationId: uuid,
2377
+ startedAt: time,
2378
+ handedOffAt: time,
2379
+ finishedAt: time,
2380
+ result: objectSchema(
2381
+ {
2382
+ ...resultFields(capacity),
2383
+ retryHint: objectSchema({ delayMs: numeric, notBefore: time }, ["delayMs", "notBefore"])
2384
+ },
2385
+ [...resultOptional, "retryHint"]
2386
+ ),
2387
+ disposition: string,
2388
+ reason: string,
2389
+ retryAt: time
2390
+ },
2391
+ ["handedOffAt", "retryAt"]
2392
+ ),
2393
+ digest,
2394
+ ownerDigest: digest,
2395
+ permitUntil: time,
2396
+ projectionAckAt: time
2397
+ },
2398
+ ["ownerDigest", "permitUntil", "projectionAckAt"]
2399
+ );
2400
+ }
2401
+ var lifecycle = {
2402
+ oneOf: [
2403
+ objectSchema({ state: { enum: ["queued"] }, nextAt: time }),
2404
+ objectSchema({
2405
+ state: { enum: ["leased"] },
2406
+ lease: objectSchema(
2407
+ {
2408
+ attemptId: uuid,
2409
+ token: { bsonType: "string", pattern: "^[A-Za-z0-9_-]{22,128}$" },
2410
+ startedAt: time,
2411
+ grantedAt: time,
2412
+ leaseEndsAt: time,
2413
+ handedOffAt: time
2414
+ },
2415
+ ["handedOffAt"]
2416
+ )
2417
+ }),
2418
+ objectSchema(
2419
+ {
2420
+ state: { enum: ["terminal"] },
2421
+ disposition: string,
2422
+ terminalReason: string,
2423
+ terminalAt: time,
2424
+ settledAt: time
2425
+ },
2426
+ ["settledAt"]
2427
+ )
2428
+ ]
2429
+ };
2430
+ function capacityField({ binding }) {
2431
+ return {
2432
+ smtpCapacity: objectSchema({
2433
+ format: { enum: [binding.format] },
2434
+ namespace: { enum: [binding.namespace] },
2435
+ maxRecipients: { ...numeric, enum: [binding.maxRecipients] }
2436
+ })
2437
+ };
2438
+ }
2439
+ function countsSchema(capacity) {
2440
+ const count = capacity ? { ...numeric, minimum: 0, maximum: recipientLimit(capacity) } : numeric;
2441
+ return objectSchema({ to: count, cc: count, bcc: count });
2442
+ }
2443
+ function smtpSnapshot(capacity) {
2444
+ const mailbox = objectSchema({ address: string, name: string }, ["name"]);
2445
+ const recipients = { bsonType: "array", maxItems: recipientLimit(capacity), items: mailbox };
2446
+ return objectSchema(
2447
+ {
2448
+ version,
2449
+ ...capacityField(capacity),
2450
+ kind: { enum: ["smtp"] },
2451
+ provider: smtpProvider,
2452
+ template,
2453
+ envelope: objectSchema({ from: mailbox, to: recipients, cc: recipients, bcc: recipients, replyTo: mailbox }, [
2454
+ "replyTo"
2455
+ ]),
2456
+ preparedAt: time,
2457
+ expiresAt: time,
2458
+ priority: { ...numeric, minimum: PRIORITY.min, maximum: PRIORITY.max },
2459
+ attachments: { bsonType: "array", maxItems: MESSAGE_LIMITS.attachments, items: bsonObject },
2460
+ correlation,
2461
+ subject: string,
2462
+ html: string,
2463
+ text: string
2464
+ },
2465
+ ["html", "text"]
2466
+ );
2467
+ }
2468
+ function withBsonLimit(validator, maxBytes) {
2469
+ return maxBytes === void 0 ? validator : {
2470
+ $and: [validator, { $expr: { $lte: [{ $bsonSize: "$$ROOT" }, maxBytes] } }]
2471
+ };
2472
+ }
2473
+ function jobValidator(capacity) {
2474
+ const validator = {
2475
+ $jsonSchema: {
2476
+ ...objectSchema(
2477
+ {
2478
+ _id: string,
2479
+ version,
2480
+ ...capacity ? { ...capacityField(capacity), intentHash: digest } : {},
2481
+ scope,
2482
+ jobId: uuid,
2483
+ key: {
2484
+ oneOf: [
2485
+ objectSchema({ kind: { enum: ["single"] }, idempotencyKey: string }),
2486
+ objectSchema({ kind: { enum: ["batch"] }, batchId: string, itemId: string })
2487
+ ]
2488
+ },
2489
+ admissionKey: string,
2490
+ fingerprint: digest,
2491
+ snapshotHash: digest,
2492
+ snapshot: capacity ? smtpSnapshot(capacity) : bsonObject,
2493
+ retry: objectSchema({ maxAttempts: numeric, baseDelayMs: numeric, maxDelayMs: numeric }),
2494
+ retention: objectSchema({ payloadMs: numeric, historyMs: numeric, idempotencyMs: numeric }),
2495
+ provider: capacity ? smtpProvider : provider,
2496
+ template,
2497
+ correlation,
2498
+ recipientCounts: countsSchema(capacity),
2499
+ scheduleAt: { anyOf: [time, { bsonType: "null" }] },
2500
+ createdAt: time,
2501
+ updatedAt: time,
2502
+ messageExpiresAt: time,
2503
+ priority: { ...numeric, minimum: PRIORITY.min, maximum: PRIORITY.max },
2504
+ revision: uuid,
2505
+ lifecycle,
2506
+ state: { enum: ["queued", "leased", "terminal"] },
2507
+ attempts: { bsonType: "array", items: ledgerAttempt(capacity), maxItems: MAX_ATTEMPT_LEDGER },
2508
+ resolutions: {
2509
+ bsonType: "array",
2510
+ maxItems: 2,
2511
+ items: objectSchema({ attemptId: uuid, at: time, action: { enum: ["dismiss", "redrive"] } })
2512
+ },
2513
+ projectionPermitUntil: time,
2514
+ retiring: { enum: [true] },
2515
+ nextAt: time,
2516
+ expiresAt: time,
2517
+ leaseEndsAt: time,
2518
+ pendingAt: time,
2519
+ nextCleanupAt: time
2520
+ },
2521
+ jobOptional
2522
+ ),
2523
+ oneOf: [
2524
+ {
2525
+ properties: { state: { enum: ["queued"] } },
2526
+ required: ["nextAt", "expiresAt"],
2527
+ not: { required: ["leaseEndsAt"] }
2528
+ },
2529
+ {
2530
+ properties: { state: { enum: ["leased"] } },
2531
+ required: ["leaseEndsAt"],
2532
+ not: { anyOf: [{ required: ["nextAt"] }, { required: ["expiresAt"] }] }
2533
+ },
2534
+ {
2535
+ properties: { state: { enum: ["terminal"] } },
2536
+ not: { anyOf: [{ required: ["nextAt"] }, { required: ["expiresAt"] }, { required: ["leaseEndsAt"] }] }
2537
+ }
2538
+ ]
2539
+ }
2540
+ };
2541
+ return withBsonLimit(validator, capacity?.limits.jobBsonBytes);
2542
+ }
2543
+ function activityValidator(capacity) {
2544
+ const identity = { _id: uuid, scope, jobId: uuid, attemptId: uuid, ...capacity ? capacityField(capacity) : {} };
2545
+ const validator = {
2546
+ $jsonSchema: {
2547
+ oneOf: [
2548
+ objectSchema(
2549
+ {
2550
+ ...identity,
2551
+ version,
2552
+ complete: { enum: [true] },
2553
+ digest,
2554
+ ordinal,
2555
+ provider: capacity ? smtpProvider : provider,
2556
+ ...capacity ? { recipientCounts: countsSchema(capacity) } : {},
2557
+ template,
2558
+ correlation,
2559
+ startedAt: time,
2560
+ handedOffAt: time,
2561
+ finishedAt: time,
2562
+ result: objectSchema(resultFields(capacity), resultOptional),
2563
+ disposition: string
2564
+ },
2565
+ activityOptional
2566
+ ),
2567
+ objectSchema({ ...identity, stubDeleteAt: { bsonType: "date" } })
2568
+ ]
2569
+ }
2570
+ };
2571
+ return withBsonLimit(validator, capacity?.limits.activityBsonBytes);
2572
+ }
2573
+
2574
+ // src/stores/mongoose/schema.ts
2575
+ var import_node_util5 = require("util");
2576
+ var JOB_ID = "v1_job_identity";
2577
+ var ADMISSION_ID = "v1_admission_identity";
2578
+ var ACTIVITY_ID = "v1_activity_identity";
2579
+ var ACTIVITY_PAGE = "v1_activity_page";
2580
+ var JOB_ACTIVITY_PAGE = "v1_job_activity_page";
2581
+ var dueIndexes = {
2582
+ nextAt: { name: "v1_due_claim", state: "queued", sort: { nextAt: 1, priority: -1, jobId: 1 } },
2583
+ expiresAt: { name: "v1_due_expiry", state: "queued", sort: { expiresAt: 1, jobId: 1 } },
2584
+ leaseEndsAt: { name: "v1_due_lease", state: "leased", sort: { leaseEndsAt: 1, jobId: 1 } },
2585
+ pendingAt: { name: "v1_due_projection", state: null, sort: { pendingAt: 1, jobId: 1 } },
2586
+ nextCleanupAt: { name: "v1_due_cleanup", state: null, sort: { nextCleanupAt: 1, jobId: 1 } }
2587
+ };
2588
+ var activityOrder = { finishedAt: -1, jobId: 1, attemptId: 1 };
2589
+ var jobActivityOrder = { finishedAt: -1, attemptId: 1 };
2590
+ var jobIndexes = [
2591
+ { name: JOB_ID, key: { scope: 1, jobId: 1 }, unique: true },
2592
+ { name: ADMISSION_ID, key: { scope: 1, admissionKey: 1 }, unique: true },
2593
+ ...Object.entries(dueIndexes).map(
2594
+ ([field, { name, state, sort }]) => ({
2595
+ name,
2596
+ key: { scope: 1, ...state ? { state: 1 } : {}, ...sort },
2597
+ partialFilterExpression: { [field]: { $exists: true } }
2598
+ })
2599
+ )
2600
+ ];
2601
+ var activityIndexes = [
2602
+ { name: ACTIVITY_ID, key: { scope: 1, jobId: 1, attemptId: 1 }, unique: true },
2603
+ { name: ACTIVITY_PAGE, key: { scope: 1, ...activityOrder }, partialFilterExpression: { complete: true } },
2604
+ {
2605
+ name: JOB_ACTIVITY_PAGE,
2606
+ key: { scope: 1, jobId: 1, ...jobActivityOrder },
2607
+ partialFilterExpression: { complete: true }
2608
+ },
2609
+ { name: "v1_activity_stub_ttl", key: { stubDeleteAt: 1 }, expireAfterSeconds: 0 }
2610
+ ];
2611
+ function indexName(v1Name, capacity) {
2612
+ return capacity ? `v2_${v1Name.slice(3)}` : v1Name;
2613
+ }
2614
+ function laneIndexes(indexes, capacity) {
2615
+ return capacity ? indexes.map((index) => ({ ...index, name: indexName(index.name, capacity) })) : indexes;
2616
+ }
2617
+ function jobSchema(name, capacity) {
2618
+ return { name, validator: jobValidator(capacity), indexes: laneIndexes(jobIndexes, capacity) };
2619
+ }
2620
+ function activitySchema(name, capacity) {
2621
+ return { name, validator: activityValidator(capacity), indexes: laneIndexes(activityIndexes, capacity) };
2622
+ }
2623
+ function simple(collation) {
2624
+ return collation === void 0 || (0, import_node_util5.isDeepStrictEqual)(collation, SIMPLE);
2625
+ }
2626
+ async function getCollection(io, binding, budget, name) {
2627
+ const result = await io.read(binding, budget, { listCollections: 1, filter: { name }, cursor: { batchSize: 2 } });
2628
+ const rows = batch(result, 1, `${binding.db.databaseName}.$cmd.listCollections`);
2629
+ return rows[0] === void 0 ? void 0 : doc(rows[0], "store_incompatible");
2630
+ }
2631
+ function checkCollection(row, schema) {
2632
+ if (row?.name !== schema.name || row.type !== "collection") invalid("store_incompatible");
2633
+ const options = doc(row.options, "store_incompatible");
2634
+ const known = ["validator", "validationLevel", "validationAction", "collation"];
2635
+ if (Object.keys(options).some((key) => !known.includes(key)) || !simple(options.collation) || (options.validationLevel ?? "strict") !== "strict" || (options.validationAction ?? "error") !== "error" || !(0, import_node_util5.isDeepStrictEqual)(options.validator, schema.validator))
2636
+ invalid("store_incompatible");
2637
+ }
2638
+ function matchesIndex(raw, index) {
2639
+ const fields = ["v", "name", "key", "unique", "partialFilterExpression", "expireAfterSeconds", "collation"];
2640
+ const key = doc(raw.key, "store_incompatible");
2641
+ return raw.v === 2 && raw.name === index.name && simple(raw.collation) && (0, import_node_util5.isDeepStrictEqual)(Object.entries(key), Object.entries(index.key)) && raw.unique === index.unique && raw.expireAfterSeconds === index.expireAfterSeconds && (0, import_node_util5.isDeepStrictEqual)(raw.partialFilterExpression, index.partialFilterExpression) && Object.keys(raw).every((field) => fields.includes(field));
2642
+ }
2643
+ async function missingIndexes(io, binding, budget, { name, indexes }) {
2644
+ const max = 64;
2645
+ const result = await io.read(binding, budget, { listIndexes: name, cursor: { batchSize: max + 1 } });
2646
+ const defs = batch(result, max, `${binding.db.databaseName}.${name}`);
2647
+ const required = [{ name: "_id_", key: { _id: 1 } }, ...indexes];
2648
+ const seen = /* @__PURE__ */ new Set();
2649
+ for (const def of defs) {
2650
+ const raw = doc(def, "store_incompatible");
2651
+ const expected = required.find((index) => index.name === raw.name);
2652
+ if (!expected || seen.has(expected.name) || !matchesIndex(raw, expected)) invalid("store_incompatible");
2653
+ seen.add(expected.name);
2654
+ }
2655
+ if (!seen.has("_id_")) invalid("store_incompatible");
2656
+ return indexes.filter((index) => !seen.has(index.name));
2657
+ }
2658
+ async function checkExistingCollection(io, binding, budget, schema) {
2659
+ const row = await getCollection(io, binding, budget, schema.name);
2660
+ if (!row) return;
2661
+ checkCollection(row, schema);
2662
+ await missingIndexes(io, binding, budget, schema);
2663
+ }
2664
+ async function prepareCollection(io, binding, budget, schema) {
2665
+ if (!await getCollection(io, binding, budget, schema.name)) {
2666
+ const result = await io.write(
2667
+ binding,
2668
+ budget,
2669
+ {
2670
+ create: schema.name,
2671
+ collation: SIMPLE,
2672
+ validator: schema.validator,
2673
+ validationLevel: "strict",
2674
+ validationAction: "error"
2675
+ },
2676
+ [48, 2, 9, 72, 115]
2677
+ );
2678
+ if (result.kind === "definite_error" && result.code !== 48) invalid("store_incompatible");
2679
+ }
2680
+ checkCollection(await getCollection(io, binding, budget, schema.name), schema);
2681
+ const missing = await missingIndexes(io, binding, budget, schema);
2682
+ if (missing.length) {
2683
+ const result = await io.write(
2684
+ binding,
2685
+ budget,
2686
+ {
2687
+ createIndexes: schema.name,
2688
+ indexes: missing.map((index) => ({ ...index, collation: SIMPLE }))
2689
+ },
2690
+ [2, 67, 68, 72, 85, 86, 11e3]
2691
+ );
2692
+ if (result.kind === "definite_error") invalid("store_incompatible");
2693
+ if ((await missingIndexes(io, binding, budget, schema)).length) invalid("store_incompatible");
2694
+ }
2695
+ }
2696
+
2697
+ // src/stores/mongoose/operations.ts
2698
+ var NONE = Object.freeze({ status: "none" });
2699
+ var CONTENDED = Object.freeze({ status: "contended" });
2700
+ var NOT_APPLIED = /* @__PURE__ */ Symbol("definite guard miss");
2701
+ function writeCount(raw, max) {
2702
+ const { n } = raw;
2703
+ if (Object.hasOwn(raw, "writeErrors") || typeof n !== "number" || !Number.isInteger(n) || n < 0 || n > max)
2704
+ invalid("write_unconfirmed");
2705
+ return n;
2706
+ }
2707
+ function modifiedValue(reply) {
2708
+ if (Object.hasOwn(reply, "writeErrors")) invalid("write_unconfirmed");
2709
+ const n = writeCount(doc(reply.lastErrorObject, "write_unconfirmed"), 1);
2710
+ if (n !== (reply.value === null ? 0 : 1) || reply.value === void 0) invalid("write_unconfirmed");
2711
+ return reply.value;
2712
+ }
2713
+ function capacityFilter(capacity) {
2714
+ const binding = capacity?.binding;
2715
+ return binding ? {
2716
+ "smtpCapacity.format": binding.format,
2717
+ "smtpCapacity.namespace": binding.namespace,
2718
+ "smtpCapacity.maxRecipients": binding.maxRecipients
2719
+ } : {};
2720
+ }
2721
+ function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck, atOrAfter, before }, capacity) {
2722
+ const lease = state.state === "leased" ? state.lease : void 0;
2723
+ return {
2724
+ _id: jobIdKey(scope2, jobId),
2725
+ scope: scope2,
2726
+ jobId,
2727
+ version: EMAIL_FORMAT_VERSION,
2728
+ ...capacityFilter(capacity),
2729
+ revision,
2730
+ state: state.state,
2731
+ "lifecycle.state": state.state,
2732
+ retiring: retiring === true ? true : { $exists: false },
2733
+ ...lease ? {
2734
+ "lifecycle.lease.attemptId": lease.attemptId,
2735
+ "lifecycle.lease.token": lease.token,
2736
+ "lifecycle.lease.startedAt": lease.startedAt,
2737
+ "lifecycle.lease.grantedAt": lease.grantedAt,
2738
+ "lifecycle.lease.leaseEndsAt": lease.leaseEndsAt,
2739
+ "lifecycle.lease.handedOffAt": lease.handedOffAt ?? { $exists: false },
2740
+ leaseEndsAt: lease.leaseEndsAt
2741
+ } : { "lifecycle.lease": { $exists: false } },
2742
+ ...pendingAck ? {
2743
+ attempts: {
2744
+ $elemMatch: {
2745
+ "commit.attemptId": pendingAck.attemptId,
2746
+ digest: pendingAck.digest,
2747
+ projectionAckAt: { $exists: false }
2748
+ }
2749
+ }
2750
+ } : {},
2751
+ $expr: serverWindow(atOrAfter, before)
2752
+ };
2753
+ }
2754
+ var MongoOperations = class {
2755
+ constructor(io, binding, budget, names, capacity) {
2756
+ this.io = io;
2757
+ this.binding = binding;
2758
+ this.budget = budget;
2759
+ this.names = names;
2760
+ this.capacity = capacity;
2761
+ }
2762
+ io;
2763
+ binding;
2764
+ budget;
2765
+ names;
2766
+ capacity;
2767
+ check() {
2768
+ this.budget.check();
2769
+ }
2770
+ now() {
2771
+ return this.io.now(this.binding, this.budget);
2772
+ }
2773
+ async time() {
2774
+ return { now: await this.now(), revision: (0, import_node_crypto2.randomUUID)() };
2775
+ }
2776
+ async find(find, filter, hint, limit, level, sort, projection) {
2777
+ const reply = await this.io.read(this.binding, this.budget, {
2778
+ find,
2779
+ filter,
2780
+ hint: indexName(hint, this.capacity),
2781
+ collation: SIMPLE,
2782
+ readConcern: { level },
2783
+ limit,
2784
+ batchSize: limit,
2785
+ singleBatch: true,
2786
+ ...sort ? { sort } : {},
2787
+ ...projection ? { projection } : {}
2788
+ });
2789
+ return batch(reply, limit, `${this.binding.db.databaseName}.${find}`);
2790
+ }
2791
+ async byJob(scope2, jobId) {
2792
+ const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, jobId }, JOB_ID, 1, "linearizable");
2793
+ if (!raw) return;
2794
+ const job = readJobBson(scope2, raw, this.capacity);
2795
+ if (job.jobId !== jobId) invalid("store_incompatible");
2796
+ this.check();
2797
+ return job;
2798
+ }
2799
+ async byAdmission(scope2, admissionKey) {
2800
+ const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, admissionKey }, ADMISSION_ID, 1, "linearizable");
2801
+ if (!raw) return;
2802
+ const job = readJobBson(scope2, raw, this.capacity);
2803
+ if (job.admissionKey !== admissionKey) invalid("store_incompatible");
2804
+ this.check();
2805
+ return job;
2806
+ }
2807
+ async byActivity(identity) {
2808
+ const [raw] = await this.find(this.names.activitiesCollection, identity, ACTIVITY_ID, 1, "linearizable");
2809
+ if (!raw) return;
2810
+ const { jobId, attemptId } = doc(raw, "store_incompatible");
2811
+ if (jobId !== identity.jobId || attemptId !== identity.attemptId) invalid("store_incompatible");
2812
+ const row = readActivityBson(identity.scope, raw, this.capacity);
2813
+ this.check();
2814
+ return row;
2815
+ }
2816
+ async insert(job) {
2817
+ const result = await this.io.write(this.binding, this.budget, {
2818
+ insert: this.names.jobsCollection,
2819
+ documents: [jobBson(job)]
2820
+ });
2821
+ if (result.kind !== "ack") invalid("write_unconfirmed");
2822
+ const { n, writeErrors } = result.reply;
2823
+ if (n === 1 && !Object.hasOwn(result.reply, "writeErrors")) return "inserted";
2824
+ if (n === 0 && Array.isArray(writeErrors) && writeErrors.length === 1) {
2825
+ const { code } = doc(writeErrors[0], "write_unconfirmed");
2826
+ if (code === 121) invalid("store_incompatible");
2827
+ if (code === 11e3) {
2828
+ let conflictingJob;
2829
+ try {
2830
+ if (await this.byAdmission(job.scope, job.admissionKey)) return "duplicate";
2831
+ conflictingJob = await this.byJob(job.scope, job.jobId);
2832
+ } catch {
2833
+ return invalid("write_unconfirmed");
2834
+ }
2835
+ if (conflictingJob) invalid("invalid_command");
2836
+ }
2837
+ }
2838
+ return invalid("write_unconfirmed");
2839
+ }
2840
+ async replace(write) {
2841
+ const { guard: guard2, next } = write;
2842
+ const result = await this.io.write(
2843
+ this.binding,
2844
+ this.budget,
2845
+ {
2846
+ findAndModify: this.names.jobsCollection,
2847
+ query: casFilter(guard2, this.capacity),
2848
+ // Treat the whole replacement as literal, including rendered strings beginning with '$'.
2849
+ update: [{ $replaceWith: { $literal: jobBson(next) } }],
2850
+ fields: { _id: 1, revision: 1 },
2851
+ new: true,
2852
+ hint: indexName(JOB_ID, this.capacity),
2853
+ collation: SIMPLE
2854
+ },
2855
+ [121]
2856
+ );
2857
+ if (result.kind === "definite_error") invalid("store_incompatible");
2858
+ const value = modifiedValue(result.reply);
2859
+ if (value === null) return false;
2860
+ const { _id, revision } = doc(value, "write_unconfirmed");
2861
+ if (_id !== jobIdKey(next.scope, next.jobId) || revision !== next.revision) invalid("write_unconfirmed");
2862
+ return true;
2863
+ }
2864
+ async purge({ guard: guard2, attemptIds }) {
2865
+ if (!guard2.retiring) invalid("store_incompatible");
2866
+ const { scope: scope2, jobId } = guard2;
2867
+ if (attemptIds.length) {
2868
+ const exact = [];
2869
+ for (const attemptId of attemptIds) {
2870
+ const identity = { scope: scope2, jobId, attemptId };
2871
+ const [raw] = await this.find(this.names.activitiesCollection, identity, ACTIVITY_ID, 1, "linearizable");
2872
+ if (raw) {
2873
+ readActivityBson(scope2, raw, this.capacity);
2874
+ exact.push({ ...identity, _id: readStoreId(doc(raw, "store_incompatible")._id, "store_incompatible") });
2875
+ }
2876
+ }
2877
+ const source = await this.byJob(scope2, jobId);
2878
+ if (source?.revision !== guard2.revision || !source.retiring) return false;
2879
+ if (exact.length) {
2880
+ const outcome2 = await this.io.write(this.binding, this.budget, {
2881
+ delete: this.names.activitiesCollection,
2882
+ // An exact indexed delete per attempt in one ordered command.
2883
+ deletes: exact.map((identity) => ({
2884
+ q: { ...identity, ...capacityFilter(this.capacity), $expr: serverWindow(guard2.atOrAfter) },
2885
+ limit: 1,
2886
+ hint: indexName(ACTIVITY_ID, this.capacity),
2887
+ collation: SIMPLE
2888
+ }))
2889
+ });
2890
+ if (outcome2.kind !== "ack") invalid("write_unconfirmed");
2891
+ writeCount(outcome2.reply, exact.length);
2892
+ for (const { attemptId } of exact) {
2893
+ if (await this.byActivity({ scope: scope2, jobId, attemptId })) return false;
2894
+ }
2895
+ }
2896
+ }
2897
+ const outcome = await this.io.write(this.binding, this.budget, {
2898
+ delete: this.names.jobsCollection,
2899
+ deletes: [
2900
+ {
2901
+ q: casFilter(guard2, this.capacity),
2902
+ limit: 1,
2903
+ hint: indexName(JOB_ID, this.capacity),
2904
+ collation: SIMPLE
2905
+ }
2906
+ ]
2907
+ });
2908
+ if (outcome.kind !== "ack") invalid("write_unconfirmed");
2909
+ return writeCount(outcome.reply, 1) === 1;
2910
+ }
2911
+ async apply(decision) {
2912
+ this.check();
2913
+ const { write } = decision ?? {};
2914
+ if (write) {
2915
+ const ok = write.kind === "replace" ? await this.replace(write) : await this.purge(write);
2916
+ if (!ok) return NOT_APPLIED;
2917
+ }
2918
+ return decision?.value ?? null;
2919
+ }
2920
+ async point(scope2, jobId, decide) {
2921
+ for (let i = 0; i < MAX_STORE_CAS_SUBMISSIONS; i++) {
2922
+ const job = await this.byJob(scope2, jobId);
2923
+ if (!job) return null;
2924
+ const value = await this.apply(await decide(job, await this.time()));
2925
+ if (value !== NOT_APPLIED) return value;
2926
+ }
2927
+ return invalid("busy");
2928
+ }
2929
+ async next(scope2, due, decide) {
2930
+ const selectionAt = await this.now();
2931
+ const { name, state, sort } = dueIndexes[due];
2932
+ const candidates = await this.find(
2933
+ this.names.jobsCollection,
2934
+ {
2935
+ scope: scope2,
2936
+ ...state ? { state } : {},
2937
+ [due]: { $exists: true, $lte: selectionAt }
2938
+ },
2939
+ name,
2940
+ this.capacity?.limits.dueCandidates ?? MAX_STORE_CANDIDATES,
2941
+ "majority",
2942
+ sort,
2943
+ { _id: 0, jobId: 1 }
2944
+ );
2945
+ let contended = false;
2946
+ let submissions = 0;
2947
+ for (const row of candidates) {
2948
+ const { jobId } = doc(row, "store_incompatible");
2949
+ const job = await this.byJob(scope2, readStoreId(jobId, "store_incompatible"));
2950
+ if (!job) {
2951
+ contended = true;
2952
+ continue;
2953
+ }
2954
+ const time2 = await this.time();
2955
+ const decision = decide(job, time2);
2956
+ if (!decision) {
2957
+ contended = true;
2958
+ continue;
2959
+ }
2960
+ const value = await this.apply(decision);
2961
+ if (value !== NOT_APPLIED) {
2962
+ if (value === null) invalid("store_incompatible");
2963
+ return Object.freeze({ status: "applied", value });
2964
+ }
2965
+ contended = true;
2966
+ if (++submissions === MAX_STORE_CAS_SUBMISSIONS) break;
2967
+ }
2968
+ this.check();
2969
+ return contended ? CONTENDED : NONE;
2970
+ }
2971
+ async upsertActivity(permit, sampledAt) {
2972
+ const identity = activityKey(permit.activity);
2973
+ const activity = activityBson(permit);
2974
+ const candidateId = (0, import_node_crypto2.randomUUID)();
2975
+ const result = await this.io.write(
2976
+ this.binding,
2977
+ this.budget,
2978
+ {
2979
+ findAndModify: this.names.activitiesCollection,
2980
+ query: { ...identity, ...capacityFilter(this.capacity) },
2981
+ new: true,
2982
+ upsert: true,
2983
+ hint: indexName(ACTIVITY_ID, this.capacity),
2984
+ collation: SIMPLE,
2985
+ update: [
2986
+ {
2987
+ $replaceWith: {
2988
+ $switch: {
2989
+ branches: [
2990
+ { case: { $eq: ["$complete", true] }, then: "$$ROOT" },
2991
+ {
2992
+ case: serverWindow(sampledAt, permit.permitUntil),
2993
+ then: {
2994
+ $mergeObjects: [
2995
+ { $literal: activity },
2996
+ { _id: { $ifNull: ["$_id", { $literal: candidateId }] } }
2997
+ ]
2998
+ }
2999
+ },
3000
+ { case: { $eq: [{ $type: "$stubDeleteAt" }, "date"] }, then: "$$ROOT" }
3001
+ ],
3002
+ default: {
3003
+ $mergeObjects: [
3004
+ { $literal: { ...identity, ...capacityTag(this.capacity) } },
3005
+ { _id: { $literal: candidateId }, stubDeleteAt: { $add: ["$$NOW", ACTIVITY_STUB_TTL_MS] } }
3006
+ ]
3007
+ }
3008
+ }
3009
+ }
3010
+ }
3011
+ ]
3012
+ },
3013
+ [11e3, 121]
3014
+ );
3015
+ if (result.kind === "definite_error" && result.code === 121) invalid("store_incompatible");
3016
+ let confirmedComplete = false;
3017
+ if (result.kind === "ack") {
3018
+ const row = readActivityBson(
3019
+ identity.scope,
3020
+ doc(modifiedValue(result.reply), "write_unconfirmed"),
3021
+ this.capacity
3022
+ );
3023
+ if (row && row.digest !== permit.digest) invalid("store_incompatible");
3024
+ confirmedComplete = row !== void 0;
3025
+ }
3026
+ let stored;
3027
+ try {
3028
+ stored = await this.byActivity(identity);
3029
+ } catch {
3030
+ return invalid("write_unconfirmed");
3031
+ }
3032
+ if (stored) {
3033
+ if (stored.digest !== permit.digest) invalid("store_incompatible");
3034
+ return "present";
3035
+ }
3036
+ if (confirmedComplete) invalid("write_unconfirmed");
3037
+ let now;
3038
+ try {
3039
+ now = await this.now();
3040
+ } catch {
3041
+ return invalid("write_unconfirmed");
3042
+ }
3043
+ if (now >= permit.permitUntil) return "permit_expired";
3044
+ return invalid("write_unconfirmed");
3045
+ }
3046
+ async list(criteria) {
3047
+ const { scope: scope2, jobId, from, before, after, limit } = criteria;
3048
+ const base = {
3049
+ scope: scope2,
3050
+ complete: true,
3051
+ ...jobId === null ? {} : { jobId }
3052
+ };
3053
+ const hint = jobId === null ? ACTIVITY_PAGE : JOB_ACTIVITY_PAGE;
3054
+ const sort = jobId === null ? activityOrder : jobActivityOrder;
3055
+ const rows = [];
3056
+ const readRange = async (bounds) => {
3057
+ if (rows.length <= limit)
3058
+ rows.push(
3059
+ ...await this.find(
3060
+ this.names.activitiesCollection,
3061
+ { ...base, ...bounds },
3062
+ hint,
3063
+ limit + 1 - rows.length,
3064
+ "majority",
3065
+ sort
3066
+ )
3067
+ );
3068
+ };
3069
+ if (after) {
3070
+ await readRange({ jobId: after.jobId, finishedAt: after.finishedAt, attemptId: { $gt: after.attemptId } });
3071
+ if (jobId === null) await readRange({ finishedAt: after.finishedAt, jobId: { $gt: after.jobId } });
3072
+ }
3073
+ const range = {
3074
+ ...from === null ? {} : { $gte: from },
3075
+ ...after ? { $lt: after.finishedAt } : before === null ? {} : { $lt: before }
3076
+ };
3077
+ await readRange(Object.keys(range).length ? { finishedAt: range } : {});
3078
+ const page = activityPage(
3079
+ criteria,
3080
+ rows.map((row) => readActivityBson(scope2, row, this.capacity)?.activity ?? invalid("store_incompatible"))
3081
+ );
3082
+ this.check();
3083
+ return page;
3084
+ }
3085
+ };
3086
+
3087
+ // src/mongoose.ts
3088
+ var MAX_IN_FLIGHT = 32;
3089
+ var NAME_KEYS = ["jobsCollection", "activitiesCollection", "jobsModelName", "activitiesModelName"];
3090
+ function readStoreConfig(options) {
3091
+ const input = readRecord(options, [], [...NAME_KEYS, "smtpCapacity"], "invalid_config");
3092
+ const capacity = readCapacityOption(input);
3093
+ if (capacity) {
3094
+ if (NAME_KEYS.some((key) => Object.hasOwn(input, key))) invalid("invalid_config");
3095
+ const { namespace } = capacity.binding;
3096
+ const prefix = `email_smtp_v2.${namespace}`;
3097
+ const modelId = namespace.replaceAll("-", "_");
3098
+ const names2 = Object.freeze({
3099
+ jobsCollection: `${prefix}.jobs`,
3100
+ activitiesCollection: `${prefix}.activities`,
3101
+ jobsModelName: `EmailSmtpV2Job_${modelId}`,
3102
+ activitiesModelName: `EmailSmtpV2Activity_${modelId}`
3103
+ });
3104
+ return { names: names2, capacity };
3105
+ }
3106
+ const names = { ...MONGOOSE_DEFAULT_NAMES };
3107
+ for (const key of NAME_KEYS) {
3108
+ const value = input[key];
3109
+ if (value === void 0) continue;
3110
+ if (typeof value !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(value)) invalid("invalid_config");
3111
+ names[key] = value;
3112
+ }
3113
+ if (names.jobsCollection === names.activitiesCollection || names.jobsModelName === names.activitiesModelName)
3114
+ invalid("invalid_config");
3115
+ return { names: Object.freeze(names), capacity };
3116
+ }
3117
+ function createMongooseEmailStore(connection, options = {}) {
3118
+ checkConnectionType(connection);
3119
+ const { names, capacity } = readStoreConfig(options);
3120
+ const io = new MongoConnection(connection, names);
3121
+ let readyBinding;
3122
+ let preparing = false;
3123
+ let inFlight = 0;
3124
+ async function run(call, worker, fn) {
3125
+ const { signal, timeoutMs } = readStoreCall(call, worker, capacity);
3126
+ if (inFlight >= (capacity?.limits.mongoInFlight ?? MAX_IN_FLIGHT)) invalid("busy");
3127
+ const budget = createBudget(systemEmailClock, Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS), signal);
3128
+ inFlight++;
3129
+ try {
3130
+ budget.check();
3131
+ if (!readyBinding) invalid("store_unavailable");
3132
+ const binding = io.bind();
3133
+ if (binding.client !== readyBinding.client || binding.db !== readyBinding.db) invalid("store_unavailable");
3134
+ return await fn(new MongoOperations(io, binding, budget, names, capacity));
3135
+ } finally {
3136
+ inFlight--;
3137
+ budget.close();
3138
+ }
3139
+ }
3140
+ const store = {
3141
+ ...capacityTag(capacity),
3142
+ async ready(options2 = {}) {
3143
+ const { timeoutMs, signal } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
3144
+ if (preparing || inFlight) invalid("busy");
3145
+ const budget = createBudget(systemEmailClock, timeoutMs, signal);
3146
+ preparing = true;
3147
+ readyBinding = void 0;
3148
+ try {
3149
+ budget.check();
3150
+ const binding = io.bind();
3151
+ await io.verifyTopology(binding, budget);
3152
+ const jobs = jobSchema(names.jobsCollection, capacity);
3153
+ const activities = activitySchema(names.activitiesCollection, capacity);
3154
+ if (capacity) {
3155
+ await checkExistingCollection(io, binding, budget, jobs);
3156
+ await checkExistingCollection(io, binding, budget, activities);
3157
+ }
3158
+ await prepareCollection(io, binding, budget, jobs);
3159
+ await prepareCollection(io, binding, budget, activities);
3160
+ const jobId = (0, import_node_crypto3.randomUUID)();
3161
+ const probe = { scope: "!readiness", jobId };
3162
+ for (const [find, filter, hint] of [
3163
+ [names.jobsCollection, probe, JOB_ID],
3164
+ [names.jobsCollection, { scope: probe.scope, admissionKey: "!readiness" }, ADMISSION_ID],
3165
+ [names.activitiesCollection, { ...probe, attemptId: (0, import_node_crypto3.randomUUID)() }, ACTIVITY_ID]
3166
+ ]) {
3167
+ await io.read(binding, budget, {
3168
+ find,
3169
+ filter,
3170
+ hint: indexName(hint, capacity),
3171
+ collation: SIMPLE,
3172
+ readConcern: { level: "linearizable" },
3173
+ singleBatch: true,
3174
+ limit: 1,
3175
+ batchSize: 1
3176
+ });
3177
+ }
3178
+ await io.now(binding, budget);
3179
+ const current = io.bind();
3180
+ if (binding.client !== current.client || binding.db !== current.db) invalid("store_unavailable");
3181
+ budget.check();
3182
+ readyBinding = binding;
3183
+ } finally {
3184
+ budget.close();
3185
+ preparing = false;
3186
+ }
3187
+ },
3188
+ findAdmission(scope2, key, call) {
3189
+ return run(call, false, async (ops) => {
3190
+ const job = await ops.byAdmission(scopeToken(scope2), encodeAdmissionKey(validateAdmissionKey(key)));
3191
+ return job ? Object.freeze({ job: jobSummary(job), fingerprint: job.fingerprint }) : null;
3192
+ });
3193
+ },
3194
+ insert(scope2, input, call) {
3195
+ return run(call, false, async (ops) => {
3196
+ const safe = readStoreAdmission(scopeToken(scope2), input, capacity);
3197
+ if (await ops.byAdmission(scope2, safe.admissionKey)) return Object.freeze({ status: "duplicate" });
3198
+ if (await ops.byJob(scope2, safe.jobId)) invalid("invalid_command");
3199
+ const job = newJob(safe, { now: await ops.now(), revision: (0, import_node_crypto3.randomUUID)() }, capacity);
3200
+ const summary = jobSummary(job);
3201
+ return await ops.insert(job) === "inserted" ? Object.freeze({ status: "inserted", job: summary }) : Object.freeze({ status: "duplicate" });
3202
+ });
3203
+ },
3204
+ findJob(scope2, jobId, call) {
3205
+ return run(call, false, async (ops) => {
3206
+ const job = await ops.byJob(scopeToken(scope2), readStoreId(jobId));
3207
+ return job ? jobSummary(job) : null;
3208
+ });
3209
+ },
3210
+ findAttempt(scope2, jobId, attemptId, call) {
3211
+ return run(call, true, async (ops) => {
3212
+ const id = readStoreId(attemptId);
3213
+ const job = await ops.byJob(scopeToken(scope2), readStoreId(jobId));
3214
+ const commit = job?.attempts.find((entry) => entry.commit.attemptId === id)?.commit;
3215
+ return commit ? copyCommit(commit, capacity) : null;
3216
+ });
3217
+ },
3218
+ claimNext(scope2, input, call) {
3219
+ return run(call, true, (ops) => {
3220
+ const safe = readClaim(input);
3221
+ return ops.next(scopeToken(scope2), "nextAt", (job, time2) => claimJob(job, safe, time2, capacity));
3222
+ });
3223
+ },
3224
+ renew(scope2, fence, leaseMs, call) {
3225
+ return run(call, true, (ops) => {
3226
+ const safe = readFence(fence);
3227
+ const duration = readLeaseMs(leaseMs);
3228
+ return ops.point(scopeToken(scope2), safe.jobId, (job, time2) => renewJob(job, safe, duration, time2));
3229
+ });
3230
+ },
3231
+ markHandoff(scope2, fence, leaseMs, call) {
3232
+ return run(call, true, (ops) => {
3233
+ const safe = readFence(fence);
3234
+ const duration = readLeaseMs(leaseMs);
3235
+ return ops.point(scopeToken(scope2), safe.jobId, (job, time2) => markJob(job, safe, duration, time2));
3236
+ });
3237
+ },
3238
+ finish(scope2, input, call) {
3239
+ return run(call, true, (ops) => {
3240
+ const safe = readFinish(input, capacity);
3241
+ return ops.point(scopeToken(scope2), safe.fence.jobId, (job, time2) => finishJob(job, safe, time2, capacity));
3242
+ });
3243
+ },
3244
+ recoverNext(scope2, call) {
3245
+ return run(call, true, (ops) => {
3246
+ const operationId = (0, import_node_crypto3.randomUUID)();
3247
+ return ops.next(scopeToken(scope2), "leaseEndsAt", (job, time2) => recoverJob(job, operationId, time2, capacity));
3248
+ });
3249
+ },
3250
+ expireNext(scope2, call) {
3251
+ return run(call, true, (ops) => ops.next(scopeToken(scope2), "expiresAt", expireJob));
3252
+ },
3253
+ cancel(scope2, jobId, call) {
3254
+ return run(call, false, async (ops) => {
3255
+ const operationId = (0, import_node_crypto3.randomUUID)();
3256
+ return await ops.point(
3257
+ scopeToken(scope2),
3258
+ readStoreId(jobId),
3259
+ (job, time2) => cancelJob(job, operationId, time2, capacity)
3260
+ ) ?? Object.freeze({ status: "not_found" });
3261
+ });
3262
+ },
3263
+ resolveUnknown(scope2, input, call) {
3264
+ return run(call, false, async (ops) => {
3265
+ const safe = readResolution(input);
3266
+ return await ops.point(scopeToken(scope2), safe.jobId, (job, time2) => resolveJob(job, safe, time2)) ?? invalid("not_found");
3267
+ });
3268
+ },
3269
+ reserveProjection(scope2, call) {
3270
+ return run(
3271
+ call,
3272
+ false,
3273
+ (ops) => ops.next(scopeToken(scope2), "pendingAt", (job, time2) => reserveJobProjection(job, time2, capacity))
3274
+ );
3275
+ },
3276
+ putActivity(scope2, input, call) {
3277
+ return run(call, false, async (ops) => {
3278
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
3279
+ const identity = activityKey(permit.activity);
3280
+ const job = await ops.byJob(scope2, identity.jobId);
3281
+ const activity = await ops.byActivity(identity);
3282
+ const now = await ops.now();
3283
+ const decision = decideActivityPut(job, permit, activity, now);
3284
+ ops.check();
3285
+ return decision === "insert" ? ops.upsertActivity(permit, now) : decision;
3286
+ });
3287
+ },
3288
+ ackProjection(scope2, input, call) {
3289
+ return run(call, false, async (ops) => {
3290
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
3291
+ const identity = activityKey(permit.activity);
3292
+ return await ops.point(
3293
+ scope2,
3294
+ identity.jobId,
3295
+ async (job, time2) => acknowledgeJobProjection(job, permit, await ops.byActivity(identity), time2)
3296
+ ) ?? "stale";
3297
+ });
3298
+ },
3299
+ listActivities(scope2, query, call) {
3300
+ return run(call, false, (ops) => ops.list(readActivityCriteria(scopeToken(scope2), query, capacity)));
3301
+ },
3302
+ cleanupNext(scope2, call) {
3303
+ return run(call, false, (ops) => ops.next(scopeToken(scope2), "nextCleanupAt", cleanupJob));
3304
+ }
3305
+ };
3306
+ return Object.freeze(store);
3307
+ }
3308
+ // Annotate the CommonJS export names for ESM import in node:
3309
+ 0 && (module.exports = {
3310
+ createMongooseEmailStore
3311
+ });