@web-ts-toolkit/email-service 0.0.0-stage → 0.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,4289 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ EmailError: () => EmailError,
34
+ createEmailAdmin: () => createEmailAdmin,
35
+ createEmailBatchService: () => createEmailBatchService,
36
+ createEmailService: () => createEmailService,
37
+ createEmailTemplateRegistry: () => createEmailTemplateRegistry,
38
+ createEmailWorker: () => createEmailWorker,
39
+ createMemoryEmailStore: () => createMemoryEmailStore,
40
+ defineLocalTemplate: () => defineLocalTemplate,
41
+ defineSendGridTemplate: () => defineSendGridTemplate
42
+ });
43
+ module.exports = __toCommonJS(src_exports);
44
+
45
+ // src/errors.ts
46
+ var messages = Object.freeze({
47
+ invalid_config: "Invalid email service configuration.",
48
+ invalid_command: "Invalid email command.",
49
+ invalid_input: "Invalid template input.",
50
+ invalid_data: "Invalid prepared template data.",
51
+ invalid_snapshot: "Invalid prepared email snapshot.",
52
+ preparation_failed: "Email preparation failed.",
53
+ template_not_found: "Email template not found.",
54
+ template_source: "Email template source could not be loaded.",
55
+ template_render: "Email template could not be rendered.",
56
+ provider_mismatch: "Email provider does not match the template or snapshot.",
57
+ expired: "Email has expired.",
58
+ idempotency_conflict: "Email admission key was used with different intent.",
59
+ not_found: "Email job not found.",
60
+ resolution_conflict: "Unknown attempt cannot be resolved with this action.",
61
+ store_capacity: "Email store is at capacity.",
62
+ store_unavailable: "Email store is unavailable.",
63
+ store_incompatible: "Email store does not meet the required guarantees.",
64
+ write_unconfirmed: "Email store write not confirmed; it may have committed.",
65
+ invalid_cursor: "Invalid email activity cursor.",
66
+ aborted: "Email operation was aborted.",
67
+ deadline: "Email operation deadline elapsed.",
68
+ busy: "Email service has no available capacity for this operation.",
69
+ closed: "Email service is closed."
70
+ });
71
+ var EmailError = class extends Error {
72
+ /** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
73
+ code;
74
+ constructor(code) {
75
+ const safeCode = typeof code === "string" && Object.hasOwn(messages, code) ? code : "invalid_config";
76
+ super(messages[safeCode]);
77
+ this.name = "EmailError";
78
+ this.code = safeCode;
79
+ }
80
+ };
81
+
82
+ // src/constants.ts
83
+ var KiB = 1024;
84
+ var MiB = 1024 * KiB;
85
+ var DAY_MS = 864e5;
86
+ function bounded(defaultValue, min, max) {
87
+ return Object.freeze({ default: defaultValue, min, max });
88
+ }
89
+ var EMAIL_FORMAT_VERSION = 1;
90
+ var MAX_UNIX_MS = 253402300799999;
91
+ var CLOCK_MARGIN_MS = 1e3;
92
+ var DEFAULT_EXPIRY_MS = DAY_MS;
93
+ var MAX_EXPIRY_MS = 30 * DAY_MS;
94
+ var MAX_PREPARED_AT_SKEW_MS = 6e4;
95
+ var MESSAGE_LIMITS = Object.freeze({
96
+ scopeBytes: 64,
97
+ identifierBytes: 128,
98
+ jsonDepth: 12,
99
+ jsonValues: 2048,
100
+ jsonKeyBytes: 128,
101
+ intentBytes: 16 * KiB,
102
+ dataBytes: 64 * KiB,
103
+ snapshotBytes: MiB,
104
+ recipients: 50,
105
+ addressBytes: 254,
106
+ localPartBytes: 64,
107
+ displayNameBytes: 128,
108
+ subjectBytes: 512,
109
+ templateSourceBytes: 256 * KiB,
110
+ htmlBytes: 512 * KiB,
111
+ textBytes: 256 * KiB,
112
+ correlationEntries: 8,
113
+ correlationKeyBytes: 32,
114
+ correlationValueBytes: 96,
115
+ attachments: 5,
116
+ filenameBytes: 128,
117
+ contentTypeBytes: 127,
118
+ attachmentBytes: 2 * MiB,
119
+ totalAttachmentBytes: 5 * MiB
120
+ });
121
+ var PRIORITY = bounded(0, 0, 9);
122
+ var TEMPLATE_CACHE_ENTRIES = bounded(32, 0, 128);
123
+ var TEMPLATE_MAX_PENDING = bounded(8, 1, 32);
124
+ var MAX_BATCH_ITEMS = 100;
125
+ var CALL_BUDGETS = Object.freeze({
126
+ prepare: bounded(5e3, 50, 3e4),
127
+ admissionOrAdmin: bounded(1e4, 50, 6e4),
128
+ batchOrRun: bounded(3e4, 50, 12e4),
129
+ shutdown: bounded(15e3, 50, 6e4)
130
+ });
131
+ var DEFAULT_RETRY_POLICY = Object.freeze({
132
+ maxAttempts: 3,
133
+ baseDelayMs: 1e3,
134
+ maxDelayMs: 6e4
135
+ });
136
+ var RETRY_POLICY_BOUNDS = Object.freeze({
137
+ maxAttempts: bounded(DEFAULT_RETRY_POLICY.maxAttempts, 1, 10),
138
+ baseDelayMs: bounded(DEFAULT_RETRY_POLICY.baseDelayMs, 100, 6e4),
139
+ // Also require maxDelayMs >= the configured baseDelayMs.
140
+ maxDelayMs: bounded(DEFAULT_RETRY_POLICY.maxDelayMs, 100, 36e5)
141
+ });
142
+ var MAX_MANUAL_ATTEMPTS = 1;
143
+ var MAX_ATTEMPT_LEDGER = RETRY_POLICY_BOUNDS.maxAttempts.max + MAX_MANUAL_ATTEMPTS;
144
+ var MAX_RATE_DEFERRAL_MS = 30 * DAY_MS;
145
+ var DEFAULT_RETENTION_POLICY = Object.freeze({
146
+ payloadMs: 7 * DAY_MS,
147
+ historyMs: 30 * DAY_MS,
148
+ idempotencyMs: 30 * DAY_MS
149
+ });
150
+ var RETENTION_POLICY_BOUNDS = Object.freeze({
151
+ payloadMs: bounded(DEFAULT_RETENTION_POLICY.payloadMs, 0, 30 * DAY_MS),
152
+ historyMs: bounded(DEFAULT_RETENTION_POLICY.historyMs, DAY_MS, 90 * DAY_MS),
153
+ idempotencyMs: bounded(DEFAULT_RETENTION_POLICY.idempotencyMs, DAY_MS, 90 * DAY_MS)
154
+ });
155
+ var DEFAULT_WORKER_LIMITS = Object.freeze({
156
+ maxConcurrency: 4,
157
+ storeTimeoutMs: 5e3,
158
+ leaseMs: 6e4,
159
+ preHandoffTimeoutMs: 8e3,
160
+ attachmentTimeoutMs: 5e3,
161
+ rateTimeoutMs: 500,
162
+ providerTimeoutMs: 15e3,
163
+ finalizeGraceMs: 1e4
164
+ });
165
+ var WORKER_LIMIT_BOUNDS = Object.freeze({
166
+ maxConcurrency: bounded(DEFAULT_WORKER_LIMITS.maxConcurrency, 1, 16),
167
+ storeTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.storeTimeoutMs, 50, 3e4),
168
+ leaseMs: bounded(DEFAULT_WORKER_LIMITS.leaseMs, 5e3, 3e5),
169
+ preHandoffTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.preHandoffTimeoutMs, 50, 6e4),
170
+ attachmentTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.attachmentTimeoutMs, 50, 3e4),
171
+ rateTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.rateTimeoutMs, 10, 5e3),
172
+ providerTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.providerTimeoutMs, 50, 6e4),
173
+ finalizeGraceMs: bounded(DEFAULT_WORKER_LIMITS.finalizeGraceMs, 100, 3e4)
174
+ });
175
+ var RUN_CLAIM_LIMIT = bounded(20, 1, 100);
176
+ var RUN_MAINTENANCE_LIMIT = bounded(10, 0, 100);
177
+ var ACTIVITY_PAGE_LIMIT = bounded(25, 1, 100);
178
+ var MAX_ACTIVITY_CURSOR_BYTES = 512;
179
+ var ADMIN_MAINTENANCE_LIMIT = bounded(20, 1, 100);
180
+ var MAX_OBSERVER_PENDING = 1;
181
+ var PROJECTION_PERMIT_MS = 6e4;
182
+ var PROJECTION_DRAIN_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max + CLOCK_MARGIN_MS;
183
+ var STORE_PRIMITIVE_TIMEOUT_MS = 5e3;
184
+ var MAX_STORE_CANDIDATES = 16;
185
+ var MAX_STORE_CAS_SUBMISSIONS = 3;
186
+ var MEMORY_MAX_JOBS = bounded(256, 1, 4096);
187
+ var MONGOOSE_DEFAULT_NAMES = Object.freeze({
188
+ jobsCollection: "email_jobs",
189
+ activitiesCollection: "email_activities",
190
+ jobsModelName: "EmailJobV1",
191
+ activitiesModelName: "EmailActivityV1"
192
+ });
193
+ var SMTP_DEFAULT_PORTS = Object.freeze({ implicit: 465, starttls: 587 });
194
+ var SENDGRID_REQUEST_MAX_BYTES = 8 * MiB;
195
+ var SENDGRID_RESPONSE_MAX_BYTES = 64 * KiB;
196
+
197
+ // src/internal/budget.ts
198
+ var import_node_events2 = require("events");
199
+ var import_node_perf_hooks = require("perf_hooks");
200
+ var import_promises = require("timers/promises");
201
+ var import_node_util3 = require("util");
202
+
203
+ // src/internal/callbacks.ts
204
+ var import_node_events = require("events");
205
+ var import_node_util2 = require("util");
206
+
207
+ // src/internal/validation.ts
208
+ var import_node_buffer = require("buffer");
209
+ var import_node_util = require("util");
210
+ function invalid(code) {
211
+ throw new EmailError(code);
212
+ }
213
+ function allowedErrorCode(error, allowed) {
214
+ if (typeof error !== "object" || error === null || import_node_util.types.isProxy(error)) return;
215
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
216
+ return allowed.find((candidate) => candidate === code);
217
+ }
218
+ function dataObject(value, code) {
219
+ if (typeof value !== "object" || value === null || import_node_util.types.isProxy(value)) invalid(code);
220
+ return value;
221
+ }
222
+ function isArray(value, code) {
223
+ return Array.isArray(dataObject(value, code));
224
+ }
225
+ function plainKeys(value, maxKeys, code) {
226
+ const object = dataObject(value, code);
227
+ const proto = Object.getPrototypeOf(object);
228
+ if (Array.isArray(object) || proto !== null && proto !== Object.prototype) invalid(code);
229
+ const keys = Reflect.ownKeys(object);
230
+ if (keys.length > maxKeys || keys.some((key) => typeof key !== "string")) invalid(code);
231
+ return keys;
232
+ }
233
+ function ownData(value, key, code) {
234
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
235
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) invalid(code);
236
+ return descriptor.value;
237
+ }
238
+ function readRecord(value, required, optional, code) {
239
+ const keys = plainKeys(value, required.length + optional.length, code);
240
+ const copy = /* @__PURE__ */ Object.create(null);
241
+ for (const key of keys) {
242
+ if (!required.includes(key) && !optional.includes(key)) invalid(code);
243
+ copy[key] = ownData(value, key, code);
244
+ }
245
+ for (const key of required) {
246
+ if (!Object.hasOwn(copy, key)) invalid(code);
247
+ }
248
+ return copy;
249
+ }
250
+ function denseArrayLength(value, maxLength, code) {
251
+ const object = dataObject(value, code);
252
+ if (!Array.isArray(object) || Object.getPrototypeOf(object) !== Array.prototype) invalid(code);
253
+ const { length } = object;
254
+ if (length > maxLength || Reflect.ownKeys(object).length !== length + 1) invalid(code);
255
+ return length;
256
+ }
257
+ function readArray(value, maxLength, code, read) {
258
+ const length = denseArrayLength(value, maxLength, code);
259
+ const copy = [];
260
+ for (let i = 0; i < length; i++) copy.push(read(ownData(value, String(i), code)));
261
+ return Object.freeze(copy);
262
+ }
263
+ function integer(value, min, max, code) {
264
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) invalid(code);
265
+ return value === 0 ? 0 : value;
266
+ }
267
+ function boundedOption(value, bounds, code = "invalid_config") {
268
+ return value === void 0 ? bounds.default : integer(value, bounds.min, bounds.max, code);
269
+ }
270
+ function unixMs(value, code) {
271
+ return integer(value, 0, MAX_UNIX_MS, code);
272
+ }
273
+ function utf8Length(value, maxBytes, code) {
274
+ if (value.length > maxBytes || /[\uD800-\uDFFF]/u.test(value)) invalid(code);
275
+ const bytes = import_node_buffer.Buffer.byteLength(value, "utf8");
276
+ if (bytes > maxBytes) invalid(code);
277
+ return bytes;
278
+ }
279
+ function utf8String(value, maxBytes, code) {
280
+ if (typeof value !== "string") invalid(code);
281
+ utf8Length(value, maxBytes, code);
282
+ return value;
283
+ }
284
+ function headerString(value, maxBytes, code) {
285
+ const text = utf8String(value, maxBytes, code);
286
+ for (let i = 0; i < text.length; i++) {
287
+ const ch = text.charCodeAt(i);
288
+ if (ch < 32 || ch === 127) invalid(code);
289
+ }
290
+ return text;
291
+ }
292
+ function opaqueToken(value, maxBytes, code) {
293
+ if (typeof value !== "string" || value.length > maxBytes || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
294
+ invalid(code);
295
+ }
296
+ return value;
297
+ }
298
+ function scopeToken(value, code = "invalid_command") {
299
+ return opaqueToken(value, MESSAGE_LIMITS.scopeBytes, code);
300
+ }
301
+ function identifier(value, code) {
302
+ return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
303
+ }
304
+ function hashToken(value, code) {
305
+ if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
306
+ return value;
307
+ }
308
+ function jsonKey(key, code) {
309
+ utf8Length(key, MESSAGE_LIMITS.jsonKeyBytes, code);
310
+ if (key === "__proto__" || key === "prototype" || key === "constructor" || key.includes(".") || key.includes("$") || key.includes("\0")) {
311
+ invalid(code);
312
+ }
313
+ }
314
+
315
+ // src/internal/callbacks.ts
316
+ var promiseThen = Promise.prototype.then;
317
+ var CallbackSlot = class {
318
+ #pending = 0;
319
+ #closed = false;
320
+ #release;
321
+ constructor(release) {
322
+ this.#release = release;
323
+ }
324
+ get pending() {
325
+ return this.#pending;
326
+ }
327
+ hold(task) {
328
+ const settled = () => {
329
+ this.#pending--;
330
+ if (this.#closed && this.#pending === 0) this.#release();
331
+ };
332
+ void promiseThen.call(task, settled, settled);
333
+ this.#pending++;
334
+ }
335
+ close() {
336
+ if (this.#closed) return;
337
+ this.#closed = true;
338
+ if (this.#pending === 0) this.#release();
339
+ }
340
+ };
341
+ function requireCallback(value, code = "invalid_config") {
342
+ if (typeof value !== "function" || import_node_util2.types.isProxy(value)) invalid(code);
343
+ return value;
344
+ }
345
+ function readPortMember(target, key) {
346
+ if (typeof target !== "object" || target === null) invalid("invalid_config");
347
+ let owner = target;
348
+ while (owner && owner !== Object.prototype) {
349
+ if (import_node_util2.types.isProxy(owner)) invalid("invalid_config");
350
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
351
+ if (descriptor) {
352
+ if (!Object.hasOwn(descriptor, "value")) invalid("invalid_config");
353
+ return descriptor.value;
354
+ }
355
+ owner = Object.getPrototypeOf(owner);
356
+ }
357
+ }
358
+ function bindMethod(target, key) {
359
+ const method = requireCallback(readPortMember(target, key));
360
+ return ((...args) => Reflect.apply(method, target, args));
361
+ }
362
+ function dataThen(value) {
363
+ if (value === null || typeof value !== "object" && typeof value !== "function") return void 0;
364
+ let owner = value;
365
+ while (owner && owner !== Object.prototype && !import_node_util2.types.isProxy(owner)) {
366
+ const descriptor = Object.getOwnPropertyDescriptor(owner, "then");
367
+ if (descriptor) return typeof descriptor.value === "function" ? descriptor.value : void 0;
368
+ owner = Object.getPrototypeOf(owner);
369
+ }
370
+ }
371
+ function observeThenable(receiver, then, capture) {
372
+ return new Promise((resolve, reject) => {
373
+ let settled = false;
374
+ const fail = (error) => {
375
+ if (settled) return;
376
+ settled = true;
377
+ reject(error);
378
+ };
379
+ const fulfill = (raw) => {
380
+ if (settled) return;
381
+ settled = true;
382
+ try {
383
+ const result = capture(raw);
384
+ resolve(() => result);
385
+ } catch (error) {
386
+ resolve(() => {
387
+ throw error;
388
+ });
389
+ }
390
+ };
391
+ try {
392
+ Reflect.apply(then, receiver, [fulfill, fail]);
393
+ } catch (error) {
394
+ fail(error);
395
+ }
396
+ });
397
+ }
398
+ function pendingCallback(value) {
399
+ if (import_node_util2.types.isPromise(value)) return Promise.resolve(value);
400
+ const then = dataThen(value);
401
+ if (then) return observeThenable(value, then, () => void 0);
402
+ }
403
+ function runSyncCallback(budget, slot, code, invoke) {
404
+ budget.check();
405
+ let value;
406
+ try {
407
+ value = invoke();
408
+ if (import_node_util2.types.isPromise(value)) slot.hold(Promise.resolve(value));
409
+ } catch {
410
+ budget.check();
411
+ return invalid(code);
412
+ }
413
+ budget.check();
414
+ if (import_node_util2.types.isPromise(value)) invalid(code);
415
+ return value;
416
+ }
417
+ async function runHostCallback(budget, slot, code, invoke, accept, knownErrors = []) {
418
+ budget.check();
419
+ const capture = (raw) => {
420
+ budget.check();
421
+ const result = accept(raw);
422
+ budget.check();
423
+ return result;
424
+ };
425
+ let value;
426
+ let task;
427
+ let read = capture;
428
+ try {
429
+ value = invoke();
430
+ if (import_node_util2.types.isPromise(value)) task = Promise.resolve(value);
431
+ else {
432
+ const then = dataThen(value);
433
+ if (then) {
434
+ budget.check();
435
+ task = observeThenable(value, then, capture);
436
+ read = (readCaptured) => readCaptured();
437
+ }
438
+ }
439
+ if (task) slot.hold(task);
440
+ } catch (error) {
441
+ budget.check();
442
+ return invalid(allowedErrorCode(error, knownErrors) ?? code);
443
+ }
444
+ budget.check();
445
+ if (!task) return capture(value);
446
+ return new Promise((resolve, reject) => {
447
+ const abort = (0, import_node_events.addAbortListener)(budget.signal, () => {
448
+ try {
449
+ budget.check();
450
+ } catch (error) {
451
+ reject(error);
452
+ }
453
+ });
454
+ const settle = (receive) => {
455
+ abort[Symbol.dispose]();
456
+ try {
457
+ budget.check();
458
+ resolve(receive());
459
+ } catch (error) {
460
+ reject(error);
461
+ }
462
+ };
463
+ try {
464
+ void promiseThen.call(
465
+ task,
466
+ (result) => settle(() => read(result)),
467
+ (error) => settle(() => invalid(allowedErrorCode(error, knownErrors) ?? code))
468
+ );
469
+ } catch {
470
+ settle(() => invalid(code));
471
+ }
472
+ });
473
+ }
474
+
475
+ // src/internal/budget.ts
476
+ var systemEmailClock = Object.freeze({
477
+ now: Date.now,
478
+ monotonicNow: () => import_node_perf_hooks.performance.now(),
479
+ sleep: (ms, signal) => (0, import_promises.setTimeout)(ms, void 0, { signal })
480
+ });
481
+ function readClock(value) {
482
+ if (value === void 0) return systemEmailClock;
483
+ return Object.freeze({
484
+ now: bindMethod(value, "now"),
485
+ monotonicNow: bindMethod(value, "monotonicNow"),
486
+ sleep: bindMethod(value, "sleep")
487
+ });
488
+ }
489
+ function readCallOptions(input, bounds) {
490
+ const code = "invalid_config";
491
+ const { signal, timeoutMs } = readRecord(input, [], ["signal", "timeoutMs"], code);
492
+ const timeout = boundedOption(timeoutMs, bounds, code);
493
+ if (signal === void 0) return { timeoutMs: timeout };
494
+ try {
495
+ if (!import_node_util3.types.isProxy(signal) && signal instanceof AbortSignal && typeof Reflect.get(AbortSignal.prototype, "aborted", signal) === "boolean") {
496
+ return { signal, timeoutMs: timeout };
497
+ }
498
+ } catch {
499
+ invalid(code);
500
+ }
501
+ return invalid(code);
502
+ }
503
+ function monotonicNow(clock) {
504
+ try {
505
+ const now = clock.monotonicNow();
506
+ if (Number.isFinite(now)) return now;
507
+ } catch {
508
+ invalid("invalid_config");
509
+ }
510
+ return invalid("invalid_config");
511
+ }
512
+ function createBudget(clock, timeoutMs, external) {
513
+ return createBudgetUntil(clock, monotonicNow(clock) + timeoutMs, external);
514
+ }
515
+ function createBudgetUntil(clock, end, external) {
516
+ const operation = new AbortController();
517
+ const timer = new AbortController();
518
+ let externalListener;
519
+ let closed = false;
520
+ let reason;
521
+ function close() {
522
+ if (closed) return;
523
+ closed = true;
524
+ externalListener?.[Symbol.dispose]();
525
+ timer.abort();
526
+ }
527
+ function stop(code) {
528
+ if (closed) return;
529
+ reason = code;
530
+ close();
531
+ operation.abort(new EmailError(code));
532
+ }
533
+ function remainingMs() {
534
+ if (closed) return 0;
535
+ if (external?.aborted) {
536
+ stop("aborted");
537
+ } else {
538
+ try {
539
+ const remaining = end - monotonicNow(clock);
540
+ if (remaining > 0) return remaining;
541
+ stop("deadline");
542
+ } catch {
543
+ stop("invalid_config");
544
+ }
545
+ }
546
+ return 0;
547
+ }
548
+ function arm(remaining) {
549
+ void Promise.resolve(clock.sleep(Math.ceil(remaining), timer.signal)).then(
550
+ () => {
551
+ try {
552
+ const left = remainingMs();
553
+ if (left <= 0) return;
554
+ if (left >= remaining) stop("invalid_config");
555
+ else arm(left);
556
+ } catch {
557
+ stop("invalid_config");
558
+ }
559
+ },
560
+ () => stop("invalid_config")
561
+ );
562
+ }
563
+ try {
564
+ if (external && !external.aborted) externalListener = (0, import_node_events2.addAbortListener)(external, () => stop("aborted"));
565
+ const remaining = remainingMs();
566
+ if (remaining > 0) arm(remaining);
567
+ } catch {
568
+ stop("invalid_config");
569
+ }
570
+ return {
571
+ signal: operation.signal,
572
+ deadline: end,
573
+ remainingMs,
574
+ check() {
575
+ remainingMs();
576
+ if (reason) invalid(reason);
577
+ if (closed) invalid("aborted");
578
+ },
579
+ close
580
+ };
581
+ }
582
+ function createChildBudget(clock, parent, maxMs) {
583
+ return createChildBudgetUntil(clock, parent, monotonicNow(clock) + maxMs);
584
+ }
585
+ function createChildBudgetUntil(clock, parent, end, stop) {
586
+ parent.check();
587
+ const signal = stop ? AbortSignal.any([parent.signal, stop]) : parent.signal;
588
+ const child = createBudgetUntil(clock, Math.min(parent.deadline, end), signal);
589
+ return {
590
+ signal: child.signal,
591
+ deadline: child.deadline,
592
+ remainingMs: () => Math.min(parent.remainingMs(), child.remainingMs()),
593
+ check() {
594
+ parent.check();
595
+ child.check();
596
+ },
597
+ close: child.close
598
+ };
599
+ }
600
+ function waitForAbort(signal) {
601
+ if (signal.aborted) return Promise.resolve();
602
+ return new Promise((resolve) => {
603
+ const listener = (0, import_node_events2.addAbortListener)(signal, () => {
604
+ listener[Symbol.dispose]();
605
+ resolve();
606
+ });
607
+ });
608
+ }
609
+ function syncStage(budget, code, run) {
610
+ budget.check();
611
+ let result;
612
+ try {
613
+ result = run();
614
+ } catch {
615
+ budget.check();
616
+ return invalid(code);
617
+ }
618
+ budget.check();
619
+ return result;
620
+ }
621
+
622
+ // src/internal/canonical-json.ts
623
+ var import_node_crypto = require("crypto");
624
+ var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
625
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
626
+ let bytesLeft = maxBytes;
627
+ let valuesLeft = limits.values;
628
+ const chunks = [];
629
+ const ancestors = /* @__PURE__ */ new Set();
630
+ function append(text, bytes = text.length) {
631
+ if (bytes > bytesLeft) invalid(code);
632
+ bytesLeft -= bytes;
633
+ chunks.push(text);
634
+ }
635
+ function appendString(text) {
636
+ let bytes = 2 + utf8Length(text, bytesLeft - 2, code);
637
+ for (let i = 0; i < text.length; i++) {
638
+ const ch = text.charCodeAt(i);
639
+ if (ch === 34 || ch === 92 || ch === 8 || ch === 9 || ch === 10 || ch === 12 || ch === 13) bytes++;
640
+ else if (ch < 32) bytes += 5;
641
+ if (bytes > bytesLeft) invalid(code);
642
+ }
643
+ append(JSON.stringify(text), bytes);
644
+ }
645
+ function visit(value2, depth) {
646
+ if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
647
+ switch (typeof value2) {
648
+ case "string":
649
+ appendString(value2);
650
+ return value2;
651
+ case "number":
652
+ if (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2)) invalid(code);
653
+ append(JSON.stringify(value2));
654
+ return value2 === 0 ? 0 : value2;
655
+ case "boolean":
656
+ append(value2 ? "true" : "false");
657
+ return value2;
658
+ case "object":
659
+ if (value2 === null) {
660
+ append("null");
661
+ return null;
662
+ }
663
+ break;
664
+ default:
665
+ invalid(code);
666
+ }
667
+ if (ancestors.has(value2)) invalid(code);
668
+ ancestors.add(value2);
669
+ try {
670
+ const maxChildren = depth === limits.depth ? 0 : valuesLeft;
671
+ if (isArray(value2, code)) {
672
+ const length = denseArrayLength(value2, maxChildren, code);
673
+ if (length && 2 * length + 1 > bytesLeft) invalid(code);
674
+ const copy2 = [];
675
+ append("[");
676
+ for (let i = 0; i < length; i++) {
677
+ if (i) append(",");
678
+ copy2.push(visit(ownData(value2, String(i), code), depth + 1));
679
+ }
680
+ append("]");
681
+ return Object.freeze(copy2);
682
+ }
683
+ const keys = plainKeys(value2, maxChildren, code);
684
+ if (keys.length && 5 * keys.length + 1 > bytesLeft) invalid(code);
685
+ for (const key of keys) jsonKey(key, code);
686
+ const copy = /* @__PURE__ */ Object.create(null);
687
+ append("{");
688
+ for (const [index, key] of keys.sort().entries()) {
689
+ if (index) append(",");
690
+ appendString(key);
691
+ append(":");
692
+ copy[key] = visit(ownData(value2, key, code), depth + 1);
693
+ }
694
+ append("}");
695
+ return Object.freeze(copy);
696
+ } finally {
697
+ ancestors.delete(value2);
698
+ }
699
+ }
700
+ const value = visit(input, 0);
701
+ return { value, encoded: chunks.join("") };
702
+ }
703
+ function copyJsonObject(input, maxBytes, code) {
704
+ if (typeof input !== "object" || input === null || isArray(input, code)) invalid(code);
705
+ return canonicalJson(input, maxBytes, code).value;
706
+ }
707
+ function sha256(input) {
708
+ return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
709
+ }
710
+ function hashJson(input, maxBytes, code = "invalid_snapshot") {
711
+ return sha256(canonicalJson(input, maxBytes, code).encoded);
712
+ }
713
+
714
+ // src/internal/message-codecs.ts
715
+ var import_node_net = require("net");
716
+ var import_node_util4 = require("util");
717
+ var L = MESSAGE_LIMITS;
718
+ var SNAPSHOT = "invalid_snapshot";
719
+ var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
720
+ var DNS_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
721
+ var MIME_TYPE = /^[-a-z0-9!#$%&'*+.^_`{|}~]+\/[-a-z0-9!#$%&'*+.^_`{|}~]+$/;
722
+ function validateProviderRef(input, code = SNAPSHOT) {
723
+ const { kind, key, mode } = readRecord(input, ["kind", "key", "mode"], [], code);
724
+ const profile = identifier(key, code);
725
+ if (kind === "smtp" && mode === "live") return Object.freeze({ kind, key: profile, mode });
726
+ if (kind === "sendgrid" && (mode === "live" || mode === "sandbox")) {
727
+ return Object.freeze({ kind, key: profile, mode });
728
+ }
729
+ return invalid(code);
730
+ }
731
+ function validateTemplateIdentity(input, code = SNAPSHOT) {
732
+ const { key, revision } = readRecord(input, ["key", "revision"], [], code);
733
+ return Object.freeze({ key: identifier(key, code), revision: identifier(revision, code) });
734
+ }
735
+ function sendGridTemplateId(input, code = SNAPSHOT) {
736
+ if (typeof input !== "string" || input.length !== 34 || !/^d-[0-9a-fA-F]{32}$/.test(input)) invalid(code);
737
+ return input;
738
+ }
739
+ function validateMailbox(input, code = SNAPSHOT) {
740
+ const mailbox = readRecord(input, ["address"], ["name"], code);
741
+ const address = headerString(mailbox.address, L.addressBytes, code);
742
+ const at = address.indexOf("@");
743
+ const local = address.slice(0, at);
744
+ const domain = address.slice(at + 1);
745
+ 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) {
746
+ invalid(code);
747
+ }
748
+ return Object.freeze({
749
+ address,
750
+ ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
751
+ });
752
+ }
753
+ function validateEnvelope(input, kind, code = SNAPSHOT) {
754
+ const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
755
+ const seen = /* @__PURE__ */ new Set();
756
+ const recipient = (raw) => {
757
+ const mailbox = validateMailbox(raw, code);
758
+ const address = mailbox.address.toLowerCase();
759
+ if (seen.has(address)) invalid(code);
760
+ seen.add(address);
761
+ return mailbox;
762
+ };
763
+ const from = validateMailbox(envelope.from, code);
764
+ const to = readArray(envelope.to, L.recipients, code, recipient);
765
+ const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
766
+ const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
767
+ if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
768
+ return Object.freeze({
769
+ from,
770
+ to,
771
+ cc,
772
+ bcc,
773
+ ...Object.hasOwn(envelope, "replyTo") ? { replyTo: validateMailbox(envelope.replyTo, code) } : {}
774
+ });
775
+ }
776
+ function validateCorrelation(input, code = SNAPSHOT) {
777
+ const keys = plainKeys(input, L.correlationEntries, code);
778
+ const copy = /* @__PURE__ */ Object.create(null);
779
+ for (const key of keys) {
780
+ jsonKey(key, code);
781
+ opaqueToken(key, L.correlationKeyBytes, code);
782
+ copy[key] = opaqueToken(ownData(input, key, code), L.correlationValueBytes, code);
783
+ }
784
+ return Object.freeze(copy);
785
+ }
786
+ function validateAttachmentRef(input, code = SNAPSHOT) {
787
+ const ref = readRecord(
788
+ input,
789
+ ["resolverKey", "id", "version", "filename", "contentType", "byteLength", "sha256"],
790
+ [],
791
+ code
792
+ );
793
+ const filename = headerString(ref.filename, L.filenameBytes, code);
794
+ if (!filename || filename === "." || filename === ".." || /[/\\:]/.test(filename)) invalid(code);
795
+ const contentType = headerString(ref.contentType, L.contentTypeBytes, code);
796
+ if (!MIME_TYPE.test(contentType)) invalid(code);
797
+ return Object.freeze({
798
+ resolverKey: identifier(ref.resolverKey, code),
799
+ id: identifier(ref.id, code),
800
+ version: identifier(ref.version, code),
801
+ filename,
802
+ contentType,
803
+ byteLength: integer(ref.byteLength, 1, L.attachmentBytes, code),
804
+ sha256: hashToken(ref.sha256, code)
805
+ });
806
+ }
807
+ function validateAttachmentRefs(input, code = SNAPSHOT) {
808
+ let total = 0;
809
+ return readArray(input, L.attachments, code, (raw) => {
810
+ const ref = validateAttachmentRef(raw, code);
811
+ total += ref.byteLength;
812
+ if (total > L.totalAttachmentBytes) invalid(code);
813
+ return ref;
814
+ });
815
+ }
816
+ function copyAttachmentBytes(ref, input, code = SNAPSHOT) {
817
+ if (!import_node_util4.types.isUint8Array(input)) invalid(code);
818
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
819
+ const buffer = Reflect.get(typedArrayPrototype, "buffer", input);
820
+ const offset = Reflect.get(typedArrayPrototype, "byteOffset", input);
821
+ const length = Reflect.get(typedArrayPrototype, "byteLength", input);
822
+ if (import_node_util4.types.isSharedArrayBuffer(buffer) || length !== ref.byteLength || length < 1 || length > L.attachmentBytes) {
823
+ invalid(code);
824
+ }
825
+ const bytes = new Uint8Array(new Uint8Array(buffer, offset, length));
826
+ if (sha256(bytes) !== ref.sha256) invalid(code);
827
+ return bytes;
828
+ }
829
+ function validateSubject(input, code = SNAPSHOT) {
830
+ const subject = headerString(input, L.subjectBytes, code);
831
+ if (!subject.trim()) invalid(code);
832
+ return subject;
833
+ }
834
+ function smtpParts(subject, html, text, code) {
835
+ if (!html && !text) invalid(code);
836
+ return Object.freeze({ subject, ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } });
837
+ }
838
+ function validateSmtpContent(input, code = SNAPSHOT) {
839
+ const content = readRecord(input, ["subject"], ["html", "text"], code);
840
+ return smtpParts(
841
+ validateSubject(content.subject, code),
842
+ Object.hasOwn(content, "html") ? utf8String(content.html, L.htmlBytes, code) : void 0,
843
+ Object.hasOwn(content, "text") ? utf8String(content.text, L.textBytes, code) : void 0,
844
+ code
845
+ );
846
+ }
847
+ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
848
+ const expiresAt = unixMs(input, code);
849
+ if (expiresAt <= preparedAt || expiresAt - preparedAt > MAX_EXPIRY_MS || scheduleAt !== null && scheduleAt >= expiresAt) {
850
+ invalid(code);
851
+ }
852
+ return expiresAt;
853
+ }
854
+ function hashSnapshot(snapshot) {
855
+ return sha256(
856
+ canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
857
+ );
858
+ }
859
+ function readSnapshot(input) {
860
+ const dto = readRecord(
861
+ input,
862
+ [
863
+ "version",
864
+ "kind",
865
+ "provider",
866
+ "template",
867
+ "envelope",
868
+ "preparedAt",
869
+ "expiresAt",
870
+ "priority",
871
+ "attachments",
872
+ "correlation"
873
+ ],
874
+ ["subject", "html", "text", "templateId", "data"],
875
+ SNAPSHOT
876
+ );
877
+ if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
878
+ const provider = validateProviderRef(dto.provider);
879
+ if (provider.kind !== dto.kind) invalid("provider_mismatch");
880
+ const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
881
+ const common = {
882
+ version: EMAIL_FORMAT_VERSION,
883
+ template: validateTemplateIdentity(dto.template),
884
+ envelope: validateEnvelope(dto.envelope, provider.kind),
885
+ preparedAt,
886
+ expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
887
+ priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
888
+ attachments: validateAttachmentRefs(dto.attachments),
889
+ correlation: validateCorrelation(dto.correlation)
890
+ };
891
+ if (provider.kind === "smtp") {
892
+ if (Object.hasOwn(dto, "templateId") || Object.hasOwn(dto, "data")) invalid(SNAPSHOT);
893
+ const content = validateSmtpContent({
894
+ subject: dto.subject,
895
+ ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
896
+ ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
897
+ });
898
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
899
+ }
900
+ if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
901
+ return Object.freeze({
902
+ ...common,
903
+ kind: provider.kind,
904
+ provider,
905
+ templateId: sendGridTemplateId(dto.templateId),
906
+ data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
907
+ });
908
+ }
909
+ function validateSnapshot(input) {
910
+ const snapshot = readSnapshot(input);
911
+ return { snapshot, snapshotHash: hashSnapshot(snapshot) };
912
+ }
913
+
914
+ // src/internal/command-codecs.ts
915
+ function validateAdmissionKey(input, code = "invalid_command") {
916
+ const key = readRecord(input, ["kind"], ["idempotencyKey", "batchId", "itemId"], code);
917
+ if (key.kind === "single" && !Object.hasOwn(key, "batchId") && !Object.hasOwn(key, "itemId")) {
918
+ return Object.freeze({ kind: key.kind, idempotencyKey: identifier(key.idempotencyKey, code) });
919
+ }
920
+ if (key.kind === "batch" && !Object.hasOwn(key, "idempotencyKey")) {
921
+ return Object.freeze({
922
+ kind: key.kind,
923
+ batchId: identifier(key.batchId, code),
924
+ itemId: identifier(key.itemId, code)
925
+ });
926
+ }
927
+ return invalid(code);
928
+ }
929
+ function encodeAdmissionKey(key) {
930
+ return key.kind === "single" ? `s:${key.idempotencyKey}` : `b:${key.batchId}:${key.itemId}`;
931
+ }
932
+ function sameCommandMetadata(key, templateKey, provider, scheduleAt, expected) {
933
+ return encodeAdmissionKey(key) === encodeAdmissionKey(expected.key) && templateKey === expected.templateKey && provider.kind === expected.provider.kind && provider.key === expected.provider.key && provider.mode === expected.provider.mode && scheduleAt === expected.scheduleAt;
934
+ }
935
+ function fingerprintFor(identity) {
936
+ const { scope, key, templateKey, provider, scheduleAt, intentHash } = identity;
937
+ return hashJson(
938
+ [EMAIL_FORMAT_VERSION, scope, key, templateKey, provider, scheduleAt, intentHash],
939
+ MESSAGE_LIMITS.intentBytes
940
+ );
941
+ }
942
+ function parseCommandIdentity(scope, command) {
943
+ const code = "invalid_command";
944
+ const parsedScope = scopeToken(scope, code);
945
+ const raw = readRecord(command, ["key", "templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
946
+ const key = validateAdmissionKey(raw.key, code);
947
+ const templateKey = identifier(raw.templateKey, code);
948
+ const provider = validateProviderRef(raw.provider, code);
949
+ const scheduleAt = raw.scheduleAt === void 0 ? null : unixMs(raw.scheduleAt, code);
950
+ const intent = canonicalJson(raw.intent, MESSAGE_LIMITS.intentBytes, code);
951
+ const identity = { scope: parsedScope, key, templateKey, provider, scheduleAt, intentHash: sha256(intent.encoded) };
952
+ return Object.freeze({
953
+ identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity) }),
954
+ command: Object.freeze({
955
+ key,
956
+ templateKey,
957
+ provider,
958
+ input: raw.input,
959
+ intent: intent.value,
960
+ ...scheduleAt === null ? {} : { scheduleAt }
961
+ })
962
+ });
963
+ }
964
+ function validatePreparedCommand(scope, input) {
965
+ const expectedScope = scopeToken(scope);
966
+ const code = "invalid_snapshot";
967
+ const dto = readRecord(
968
+ input,
969
+ ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
970
+ [],
971
+ code
972
+ );
973
+ if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
974
+ const key = validateAdmissionKey(dto.key, code);
975
+ const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
976
+ const intentHash = hashToken(dto.intentHash, code);
977
+ const fingerprint = hashToken(dto.fingerprint, code);
978
+ const storedSnapshotHash = hashToken(dto.snapshotHash, code);
979
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
980
+ validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
981
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor({
982
+ scope: expectedScope,
983
+ key,
984
+ templateKey: snapshot.template.key,
985
+ provider: snapshot.provider,
986
+ scheduleAt,
987
+ intentHash
988
+ })) {
989
+ invalid(code);
990
+ }
991
+ return Object.freeze({
992
+ version: EMAIL_FORMAT_VERSION,
993
+ scope: expectedScope,
994
+ key,
995
+ scheduleAt,
996
+ intentHash,
997
+ fingerprint,
998
+ snapshotHash,
999
+ snapshot
1000
+ });
1001
+ }
1002
+
1003
+ // src/templates/local-sources.ts
1004
+ var import_node_buffer2 = require("buffer");
1005
+ var import_node_events3 = require("events");
1006
+ var import_node_fs = require("fs");
1007
+ var import_promises2 = require("fs/promises");
1008
+ var import_node_util5 = require("util");
1009
+ var LIMIT = MESSAGE_LIMITS.templateSourceBytes;
1010
+ var SOURCE_ERROR = "template_source";
1011
+ function readSourceConfig(input) {
1012
+ const code = "invalid_config";
1013
+ const source = readRecord(input, ["kind"], ["content", "path", "load"], code);
1014
+ if (Object.keys(source).length !== 2) invalid(code);
1015
+ if (source.kind === "inline" && typeof source.content === "string") {
1016
+ return Object.freeze({ kind: source.kind, content: source.content });
1017
+ }
1018
+ if (source.kind === "file" && typeof source.path === "string" && source.path && !source.path.includes("\0")) {
1019
+ return Object.freeze({ kind: source.kind, path: source.path });
1020
+ }
1021
+ if (source.kind === "async") {
1022
+ const load = requireCallback(source.load);
1023
+ return Object.freeze({ kind: source.kind, load });
1024
+ }
1025
+ return invalid(code);
1026
+ }
1027
+ async function readFileSource(path, budget) {
1028
+ const file = await (0, import_promises2.open)(path, import_node_fs.constants.O_RDONLY | import_node_fs.constants.O_NONBLOCK | import_node_fs.constants.O_NOCTTY);
1029
+ let closing;
1030
+ const close = () => {
1031
+ if (!closing) {
1032
+ closing = Promise.resolve().then(() => file.close());
1033
+ void closing.catch(() => void 0);
1034
+ }
1035
+ return closing;
1036
+ };
1037
+ const abort = (0, import_node_events3.addAbortListener)(budget.signal, () => {
1038
+ void close();
1039
+ });
1040
+ try {
1041
+ budget.check();
1042
+ const info = await file.stat();
1043
+ budget.check();
1044
+ if (!info.isFile() || info.size > LIMIT) invalid(SOURCE_ERROR);
1045
+ const buffer = import_node_buffer2.Buffer.allocUnsafe(LIMIT + 1);
1046
+ let length = 0;
1047
+ while (length < buffer.length) {
1048
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
1049
+ budget.check();
1050
+ if (bytesRead === 0) break;
1051
+ length += bytesRead;
1052
+ }
1053
+ if (length > LIMIT) invalid(SOURCE_ERROR);
1054
+ return new import_node_util5.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, length));
1055
+ } finally {
1056
+ abort[Symbol.dispose]();
1057
+ await close();
1058
+ }
1059
+ }
1060
+ async function loadLocalSource(source, budget, slot) {
1061
+ budget.check();
1062
+ if (source.kind === "inline")
1063
+ return syncStage(budget, SOURCE_ERROR, () => utf8String(source.content, LIMIT, SOURCE_ERROR));
1064
+ if (source.kind === "async") {
1065
+ const { load } = source;
1066
+ return runHostCallback(
1067
+ budget,
1068
+ slot,
1069
+ SOURCE_ERROR,
1070
+ () => load({ signal: budget.signal }),
1071
+ (result) => utf8String(result, LIMIT, SOURCE_ERROR)
1072
+ );
1073
+ }
1074
+ try {
1075
+ const content = await readFileSource(source.path, budget);
1076
+ budget.check();
1077
+ return content;
1078
+ } catch {
1079
+ budget.check();
1080
+ return invalid(SOURCE_ERROR);
1081
+ }
1082
+ }
1083
+
1084
+ // src/templates/local-renderer.ts
1085
+ var RENDER_ERROR = "template_render";
1086
+ function createLocalRenderer(cacheEntries, rawHelpers) {
1087
+ const code = "invalid_config";
1088
+ const helpers = /* @__PURE__ */ new Map();
1089
+ if (rawHelpers !== void 0) {
1090
+ for (const key of plainKeys(rawHelpers, Infinity, code)) {
1091
+ if (!key || ["__proto__", "prototype", "constructor", "helperMissing", "blockHelperMissing"].includes(key)) {
1092
+ invalid(code);
1093
+ }
1094
+ helpers.set(key, requireCallback(ownData(rawHelpers, key, code)));
1095
+ }
1096
+ }
1097
+ const cache = /* @__PURE__ */ new Map();
1098
+ const loading = /* @__PURE__ */ new Set();
1099
+ let environment;
1100
+ let renderFrame;
1101
+ async function getEnvironment(budget) {
1102
+ budget.check();
1103
+ if (environment) return environment;
1104
+ try {
1105
+ const { default: Handlebars } = await import("handlebars/dist/cjs/handlebars.js");
1106
+ return syncStage(budget, RENDER_ERROR, () => {
1107
+ if (environment) return environment;
1108
+ const instance = Handlebars.create();
1109
+ instance.unregisterHelper("log");
1110
+ for (const [key, helper] of helpers) {
1111
+ instance.registerHelper(key, function(...args) {
1112
+ const frame = renderFrame;
1113
+ if (!frame) invalid(RENDER_ERROR);
1114
+ return runSyncCallback(frame.budget, frame.slot, RENDER_ERROR, () => Reflect.apply(helper, this, args));
1115
+ });
1116
+ }
1117
+ environment = instance;
1118
+ return instance;
1119
+ });
1120
+ } catch {
1121
+ budget.check();
1122
+ return invalid(RENDER_ERROR);
1123
+ }
1124
+ }
1125
+ function compile(engine, source, noEscape) {
1126
+ const delegate = engine.compile(source, { strict: true, noEscape });
1127
+ return (values) => delegate(values, { allowProtoMethodsByDefault: false, allowProtoPropertiesByDefault: false });
1128
+ }
1129
+ function renderParts({ subject, html, text }, values, budget, slot) {
1130
+ const previous = renderFrame;
1131
+ renderFrame = { budget, slot };
1132
+ try {
1133
+ return smtpParts(
1134
+ syncStage(budget, RENDER_ERROR, () => validateSubject(subject(values), RENDER_ERROR)),
1135
+ html ? syncStage(budget, RENDER_ERROR, () => utf8String(html(values), MESSAGE_LIMITS.htmlBytes, RENDER_ERROR)) : void 0,
1136
+ text ? syncStage(budget, RENDER_ERROR, () => utf8String(text(values), MESSAGE_LIMITS.textBytes, RENDER_ERROR)) : void 0,
1137
+ RENDER_ERROR
1138
+ );
1139
+ } finally {
1140
+ renderFrame = previous;
1141
+ }
1142
+ }
1143
+ return {
1144
+ invalidate(key) {
1145
+ if (key === void 0) cache.clear();
1146
+ else cache.delete(key);
1147
+ for (const entry of loading) {
1148
+ if (key === void 0 || key === entry.key) entry.valid = false;
1149
+ }
1150
+ },
1151
+ async render(key, sources, values, budget, slot) {
1152
+ budget.check();
1153
+ const hit = cache.get(key);
1154
+ if (hit) {
1155
+ cache.delete(key);
1156
+ cache.set(key, hit);
1157
+ return renderParts(hit, values, budget, slot);
1158
+ }
1159
+ const entry = { key, valid: true };
1160
+ loading.add(entry);
1161
+ try {
1162
+ const subject = await loadLocalSource(sources.subject, budget, slot);
1163
+ const html = sources.html ? await loadLocalSource(sources.html, budget, slot) : void 0;
1164
+ const text = sources.text ? await loadLocalSource(sources.text, budget, slot) : void 0;
1165
+ const engine = await getEnvironment(budget);
1166
+ const compiled = syncStage(budget, RENDER_ERROR, () => ({
1167
+ subject: compile(engine, subject, true),
1168
+ ...html === void 0 ? {} : { html: compile(engine, html, false) },
1169
+ ...text === void 0 ? {} : { text: compile(engine, text, true) }
1170
+ }));
1171
+ const content = renderParts(compiled, values, budget, slot);
1172
+ budget.check();
1173
+ if (entry.valid && cacheEntries > 0) {
1174
+ cache.delete(key);
1175
+ cache.set(key, compiled);
1176
+ const oldest = cache.keys().next();
1177
+ if (cache.size > cacheEntries && !oldest.done) cache.delete(oldest.value);
1178
+ }
1179
+ return content;
1180
+ } finally {
1181
+ loading.delete(entry);
1182
+ }
1183
+ }
1184
+ };
1185
+ }
1186
+
1187
+ // src/templates/registry.ts
1188
+ function defineLocalTemplate(definition) {
1189
+ return definition;
1190
+ }
1191
+ function defineSendGridTemplate(definition) {
1192
+ return definition;
1193
+ }
1194
+ function readDefinition(value) {
1195
+ const code = "invalid_config";
1196
+ const raw = readRecord(
1197
+ value,
1198
+ ["kind", "revision", "parseInput", "parseData", "prepare"],
1199
+ ["defaults", "subject", "html", "text", "templateId"],
1200
+ code
1201
+ );
1202
+ const defaults = readRecord(raw.defaults === void 0 ? {} : raw.defaults, [], ["from", "replyTo"], code);
1203
+ const base = {
1204
+ revision: identifier(raw.revision, code),
1205
+ defaults: Object.freeze({
1206
+ ...defaults.from === void 0 ? {} : { from: validateMailbox(defaults.from, code) },
1207
+ ...defaults.replyTo === void 0 ? {} : { replyTo: validateMailbox(defaults.replyTo, code) }
1208
+ }),
1209
+ parseInput: requireCallback(raw.parseInput),
1210
+ parseData: requireCallback(raw.parseData),
1211
+ // Dispatch always pairs this callback with the input parser of this same definition.
1212
+ prepare: requireCallback(raw.prepare)
1213
+ };
1214
+ if (raw.kind === "sendgrid" && !["subject", "html", "text"].some((key) => Object.hasOwn(raw, key))) {
1215
+ return Object.freeze({ ...base, kind: raw.kind, templateId: sendGridTemplateId(raw.templateId, code) });
1216
+ }
1217
+ if (raw.kind === "handlebars" && !Object.hasOwn(raw, "templateId")) {
1218
+ const subject = readSourceConfig(raw.subject);
1219
+ const html = raw.html === void 0 ? void 0 : readSourceConfig(raw.html);
1220
+ const text = raw.text === void 0 ? void 0 : readSourceConfig(raw.text);
1221
+ if (!html && !text) invalid(code);
1222
+ return Object.freeze({ ...base, kind: raw.kind, subject, ...html ? { html } : {}, ...text ? { text } : {} });
1223
+ }
1224
+ return invalid(code);
1225
+ }
1226
+ function captureFields(raw, definition, context, scheduleAt, budget, slot) {
1227
+ const code = "invalid_snapshot";
1228
+ const fields = readRecord(
1229
+ raw,
1230
+ ["values"],
1231
+ ["from", "replyTo", "to", "cc", "bcc", "expiresAt", "priority", "attachments", "correlation"],
1232
+ code
1233
+ );
1234
+ const from = fields.from === void 0 ? definition.defaults.from : fields.from;
1235
+ const replyTo = fields.replyTo === void 0 ? definition.defaults.replyTo : fields.replyTo;
1236
+ const envelope = validateEnvelope(
1237
+ {
1238
+ from,
1239
+ to: fields.to === void 0 ? [] : fields.to,
1240
+ cc: fields.cc === void 0 ? [] : fields.cc,
1241
+ bcc: fields.bcc === void 0 ? [] : fields.bcc,
1242
+ ...replyTo === void 0 ? {} : { replyTo }
1243
+ },
1244
+ context.provider.kind
1245
+ );
1246
+ const expiresAt = validateExpiry(
1247
+ fields.expiresAt === void 0 ? context.now + DEFAULT_EXPIRY_MS : fields.expiresAt,
1248
+ context.now,
1249
+ scheduleAt
1250
+ );
1251
+ const priority = boundedOption(fields.priority, PRIORITY, code);
1252
+ const attachments = validateAttachmentRefs(fields.attachments === void 0 ? [] : fields.attachments);
1253
+ const correlation = validateCorrelation(fields.correlation === void 0 ? {} : fields.correlation);
1254
+ const values = copyJsonObject(fields.values, MESSAGE_LIMITS.dataBytes, "invalid_data");
1255
+ const { parseData } = definition;
1256
+ const parsed = runSyncCallback(budget, slot, "invalid_data", () => parseData(values));
1257
+ const data = parsed === values ? values : copyJsonObject(parsed, MESSAGE_LIMITS.dataBytes, "invalid_data");
1258
+ budget.check();
1259
+ return { envelope, expiresAt, priority, attachments, correlation, data };
1260
+ }
1261
+ var registryPreparations = /* @__PURE__ */ new WeakMap();
1262
+ function findRegistryPreparation(registry) {
1263
+ return registryPreparations.get(registry);
1264
+ }
1265
+ function createEmailTemplateRegistry(definitions, options = {}) {
1266
+ const code = "invalid_config";
1267
+ const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers"], code);
1268
+ const clock = readClock(config.clock);
1269
+ const maxPending = boundedOption(config.maxPending, TEMPLATE_MAX_PENDING);
1270
+ const renderer = createLocalRenderer(boundedOption(config.cacheEntries, TEMPLATE_CACHE_ENTRIES), config.helpers);
1271
+ const registered = /* @__PURE__ */ new Map();
1272
+ for (const key of plainKeys(definitions, Infinity, code)) {
1273
+ registered.set(identifier(key, code), readDefinition(ownData(definitions, key, code)));
1274
+ }
1275
+ let pending = 0;
1276
+ async function prepareParsed({ identity, command: safe }, budget) {
1277
+ budget.check();
1278
+ const { templateKey, provider, key, scheduleAt } = identity;
1279
+ const definition = registered.get(templateKey);
1280
+ if (!definition) invalid("template_not_found");
1281
+ if ((definition.kind === "handlebars" ? "smtp" : "sendgrid") !== provider.kind) invalid("provider_mismatch");
1282
+ if (pending >= maxPending) invalid("busy");
1283
+ pending++;
1284
+ const slot = new CallbackSlot(() => pending--);
1285
+ try {
1286
+ const now = syncStage(budget, code, () => unixMs(clock.now(), code));
1287
+ const context = Object.freeze({
1288
+ scope: identity.scope,
1289
+ key,
1290
+ templateKey,
1291
+ provider,
1292
+ now,
1293
+ signal: budget.signal
1294
+ });
1295
+ const { parseInput, prepare } = definition;
1296
+ const input = runSyncCallback(budget, slot, "invalid_input", () => parseInput(safe.input));
1297
+ const { data, ...fields } = await runHostCallback(
1298
+ budget,
1299
+ slot,
1300
+ "preparation_failed",
1301
+ () => prepare(input, context),
1302
+ (raw) => captureFields(raw, definition, context, scheduleAt, budget, slot)
1303
+ );
1304
+ budget.check();
1305
+ const base = {
1306
+ ...fields,
1307
+ version: EMAIL_FORMAT_VERSION,
1308
+ template: Object.freeze({ key: templateKey, revision: definition.revision }),
1309
+ preparedAt: now
1310
+ };
1311
+ let snapshot;
1312
+ if (provider.kind === "smtp" && definition.kind === "handlebars") {
1313
+ const content = await renderer.render(templateKey, definition, data, budget, slot);
1314
+ snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...content });
1315
+ } else if (provider.kind === "sendgrid" && definition.kind === "sendgrid") {
1316
+ snapshot = Object.freeze({ ...base, kind: provider.kind, provider, templateId: definition.templateId, data });
1317
+ } else {
1318
+ return invalid("provider_mismatch");
1319
+ }
1320
+ budget.check();
1321
+ const snapshotHash = hashSnapshot(snapshot);
1322
+ budget.check();
1323
+ return Object.freeze({
1324
+ version: EMAIL_FORMAT_VERSION,
1325
+ scope: identity.scope,
1326
+ key,
1327
+ scheduleAt,
1328
+ intentHash: identity.intentHash,
1329
+ fingerprint: identity.fingerprint,
1330
+ snapshotHash,
1331
+ snapshot
1332
+ });
1333
+ } finally {
1334
+ slot.close();
1335
+ }
1336
+ }
1337
+ const registry = Object.freeze({
1338
+ invalidate(key) {
1339
+ if (key !== void 0) identifier(key, code);
1340
+ renderer.invalidate(key);
1341
+ },
1342
+ async prepare(scope, command, options2 = {}) {
1343
+ const call = readCallOptions(options2, CALL_BUDGETS.prepare);
1344
+ const budget = createBudget(clock, call.timeoutMs, call.signal);
1345
+ try {
1346
+ budget.check();
1347
+ return await prepareParsed(parseCommandIdentity(scope, command), budget);
1348
+ } finally {
1349
+ budget.close();
1350
+ }
1351
+ }
1352
+ });
1353
+ registryPreparations.set(registry, async (parsed, parent) => {
1354
+ const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
1355
+ try {
1356
+ return await prepareParsed(parsed, budget);
1357
+ } finally {
1358
+ budget.close();
1359
+ }
1360
+ });
1361
+ return registry;
1362
+ }
1363
+
1364
+ // src/service.ts
1365
+ var import_node_crypto2 = require("crypto");
1366
+ var import_node_util7 = require("util");
1367
+
1368
+ // src/internal/activity-codecs.ts
1369
+ var import_node_buffer3 = require("buffer");
1370
+
1371
+ // src/internal/attempt-codecs.ts
1372
+ var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
1373
+ var providerStages = [...smtpStages, "http"];
1374
+ var evidence = Object.freeze({
1375
+ smtp_accepted: ["accepted", "never", ["data"], "smtp"],
1376
+ smtp_partial: ["partially_accepted", "never", ["data"], "smtp"],
1377
+ smtp_transient_reply: ["rejected", "safe_transient", smtpStages, "smtp"],
1378
+ smtp_permanent_reply: ["rejected", "never", smtpStages, "smtp"],
1379
+ sendgrid_accepted: ["accepted", "never", ["http"], "sendgrid"],
1380
+ sendgrid_validated: ["validated", "never", ["http"], "sendgrid"],
1381
+ sendgrid_throttled: ["rejected", "safe_transient", ["http"], "sendgrid"],
1382
+ sendgrid_rejected: ["rejected", "never", ["http"], "sendgrid"],
1383
+ not_transmitted: ["unsubmitted", "safe_transient", providerStages, "provider"],
1384
+ provider_configuration: ["unsubmitted", "never", providerStages, "provider"],
1385
+ transport_uncertain: ["unknown", "never", providerStages, "provider"],
1386
+ provider_timeout: ["unknown", "never", providerStages, "provider"],
1387
+ provider_aborted: ["unknown", "never", providerStages, "provider"],
1388
+ attachment_unavailable: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
1389
+ attachment_timeout: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
1390
+ attachment_invalid: ["unsubmitted", "never", ["attachment"], "pre"],
1391
+ attachment_resolver_error: ["unsubmitted", "never", ["attachment"], "pre"],
1392
+ rate_deferred: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
1393
+ rate_timeout: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
1394
+ rate_error: ["unsubmitted", "never", ["rate_limit"], "pre"],
1395
+ profile_unavailable: ["unsubmitted", "never", ["pre_handoff"], "pre"],
1396
+ provider_preflight_error: ["unsubmitted", "never", ["pre_handoff"], "pre"],
1397
+ pre_handoff_timeout: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
1398
+ worker_stopped: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
1399
+ pre_handoff_lease_expired: ["unsubmitted", "safe_transient", ["pre_handoff"], "recovery"],
1400
+ launch_window_closed: ["unsubmitted", "safe_transient", ["pre_handoff"], "launch"],
1401
+ post_handoff_lease_expired: ["unknown", "never", ["pre_handoff"], "recovery"],
1402
+ expired: ["unsubmitted", "never", ["pre_handoff"], "pre"],
1403
+ cancelled: ["unsubmitted", "never", ["pre_handoff"], "cancel"]
1404
+ });
1405
+ function readAttemptReason(value, code) {
1406
+ if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
1407
+ return value;
1408
+ }
1409
+ function attemptOutcome(reason) {
1410
+ return evidence[reason][0];
1411
+ }
1412
+ function isSafeTransient(reason) {
1413
+ return evidence[reason][1] === "safe_transient";
1414
+ }
1415
+ function recipientCounts(envelope) {
1416
+ return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
1417
+ }
1418
+ function smtpMessageId(attemptId) {
1419
+ return `<${attemptId}@email.invalid>`;
1420
+ }
1421
+ function readHint(input, reason, code) {
1422
+ if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
1423
+ const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
1424
+ const hasDelay = Object.hasOwn(raw, "delayMs");
1425
+ const hasFloor = Object.hasOwn(raw, "notBefore");
1426
+ if (!hasDelay && (!hasFloor || reason === "rate_deferred")) invalid(code);
1427
+ return Object.freeze({
1428
+ ...hasDelay ? {
1429
+ delayMs: reason === "rate_deferred" ? integer(raw.delayMs, 1, MAX_RATE_DEFERRAL_MS, code) : integer(raw.delayMs, 0, Number.MAX_SAFE_INTEGER, code)
1430
+ } : {},
1431
+ ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
1432
+ });
1433
+ }
1434
+ function readAttemptResult(input, code = "invalid_command", projected = false) {
1435
+ const raw = readRecord(
1436
+ input,
1437
+ ["outcome", "retry", "stage", "reason"],
1438
+ ["retryHint", "recipients", "messageId", "providerMessageId"],
1439
+ code
1440
+ );
1441
+ const reason = readAttemptReason(raw.reason, code);
1442
+ const [outcome, retry, stages2, origin] = evidence[reason];
1443
+ const stage = stages2.find((value) => value === raw.stage);
1444
+ if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
1445
+ const hasHint = Object.hasOwn(raw, "retryHint");
1446
+ if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
1447
+ const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
1448
+ const hasRecipients = Object.hasOwn(raw, "recipients");
1449
+ if (smtpSuccess && !hasRecipients) invalid(code);
1450
+ let recipients;
1451
+ if (hasRecipients) {
1452
+ if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
1453
+ const seen = /* @__PURE__ */ new Set();
1454
+ recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
1455
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1456
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1457
+ if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
1458
+ const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
1459
+ const key = `${group}:${index}`;
1460
+ if (seen.has(key)) invalid(code);
1461
+ seen.add(key);
1462
+ return Object.freeze({ group, index, status });
1463
+ });
1464
+ const accepted = recipients.filter(({ status }) => status === "accepted").length;
1465
+ if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
1466
+ invalid(code);
1467
+ }
1468
+ }
1469
+ const hasMessageId = Object.hasOwn(raw, "messageId");
1470
+ const { messageId, providerMessageId } = raw;
1471
+ if (hasMessageId && (!smtpSuccess || typeof messageId !== "string" || messageId.length !== 52)) invalid(code);
1472
+ const hasProviderId = Object.hasOwn(raw, "providerMessageId");
1473
+ if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
1474
+ invalid(code);
1475
+ }
1476
+ return Object.freeze({
1477
+ outcome,
1478
+ retry,
1479
+ stage,
1480
+ reason,
1481
+ ...hasHint ? { retryHint: readHint(raw.retryHint, reason, code) } : {},
1482
+ ...recipients === void 0 ? {} : { recipients },
1483
+ ...typeof messageId === "string" ? { messageId } : {},
1484
+ ...typeof providerMessageId === "string" ? { providerMessageId } : {}
1485
+ });
1486
+ }
1487
+ function assertEvidencePhase(reason, phase, source, code) {
1488
+ const origin = evidence[reason][3];
1489
+ if (source === "ledger") {
1490
+ if (origin === "recovery" && reason === "post_handoff_lease_expired" === (phase === "handed_off")) return;
1491
+ if (origin === "cancel" && phase === "pre_handoff") return;
1492
+ }
1493
+ const allowed = phase === "pre_handoff" ? origin === "pre" : origin === "smtp" || origin === "sendgrid" || origin === "provider" || origin === "launch";
1494
+ if (!allowed) invalid(code);
1495
+ }
1496
+ function assertEvidenceContext(result, provider, attemptId, counts, code) {
1497
+ const { reason, stage, recipients, messageId } = result;
1498
+ const origin = evidence[reason][3];
1499
+ if (origin === "smtp" && provider.kind !== "smtp" || origin === "sendgrid" && provider.kind !== "sendgrid" || origin === "provider" && (provider.kind === "smtp" ? stage === "http" : stage !== "http" && stage !== "connect" && stage !== "tls") || reason === "sendgrid_accepted" && provider.mode !== "live" || reason === "sendgrid_validated" && provider.mode !== "sandbox" || messageId !== void 0 && messageId !== smtpMessageId(attemptId)) {
1500
+ invalid(code);
1501
+ }
1502
+ if (recipients) {
1503
+ if (provider.kind !== "smtp") invalid(code);
1504
+ if (counts) {
1505
+ if (recipients.some(({ group, index }) => index >= counts[group])) invalid(code);
1506
+ const needsPartition = reason === "smtp_accepted" || reason === "smtp_partial" || stage === "envelope" && (reason === "smtp_transient_reply" || reason === "smtp_permanent_reply");
1507
+ if (needsPartition && recipients.length !== counts.to + counts.cc + counts.bcc) invalid(code);
1508
+ }
1509
+ }
1510
+ }
1511
+ function readProviderResult(input, provider, attemptId, envelope) {
1512
+ const code = "invalid_command";
1513
+ const result = readAttemptResult(input, code);
1514
+ const origin = evidence[result.reason][3];
1515
+ if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
1516
+ assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
1517
+ return result;
1518
+ }
1519
+ function lifecycleEvidence(reason) {
1520
+ const [outcome, retry] = evidence[reason];
1521
+ return Object.freeze({ outcome, retry, reason, stage: "pre_handoff" });
1522
+ }
1523
+ function attemptEffect(result, attemptId, ordinal, manual, policy, expiresAt, now) {
1524
+ const { outcome, reason } = result;
1525
+ if (outcome !== "unsubmitted" && outcome !== "rejected") return { disposition: outcome, reason };
1526
+ if (reason === "cancelled" || reason === "expired") return { disposition: reason, reason };
1527
+ const disposition = outcome === "unsubmitted" ? "failed" : "rejected";
1528
+ if (result.retry === "never") return { disposition, reason };
1529
+ if (now >= expiresAt) return { disposition: "expired", reason: "expired" };
1530
+ if (manual || ordinal >= policy.maxAttempts) return { disposition, reason: "attempts_exhausted" };
1531
+ const cap = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (ordinal - 1));
1532
+ const half = Math.floor(cap / 2);
1533
+ const jitter = half + Number.parseInt(sha256(attemptId).slice(0, 8), 16) % (cap - half + 1);
1534
+ const delay = Math.max(jitter, result.retryHint?.delayMs ?? 0);
1535
+ const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result.retryHint?.notBefore ?? 0);
1536
+ if (retryAt >= expiresAt) return { disposition: "expired", reason: "expired" };
1537
+ return { disposition: "retry_scheduled", reason, retryAt };
1538
+ }
1539
+
1540
+ // src/internal/store-codecs.ts
1541
+ var REQUEST = "invalid_command";
1542
+ var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
1543
+ function readStoreId(value, code = REQUEST) {
1544
+ 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)) {
1545
+ invalid(code);
1546
+ }
1547
+ return value;
1548
+ }
1549
+ function readLeaseToken(value, code = REQUEST) {
1550
+ 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)) {
1551
+ invalid(code);
1552
+ }
1553
+ return value;
1554
+ }
1555
+ function readLeaseMs(value) {
1556
+ return integer(value, LEASE.min, LEASE.max, REQUEST);
1557
+ }
1558
+ function timeAfter(start, delayMs) {
1559
+ return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
1560
+ }
1561
+ function readStoreCall(input, worker = false) {
1562
+ const code = "invalid_config";
1563
+ const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
1564
+ const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
1565
+ const timeoutMs = integer(raw.timeoutMs, 1, max, code);
1566
+ const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
1567
+ if (!call.signal) invalid(code);
1568
+ return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
1569
+ }
1570
+ function readStoreNext(value, read) {
1571
+ const code = "store_incompatible";
1572
+ const raw = readRecord(value, ["status"], ["value"], code);
1573
+ if (raw.status === "applied" && Object.hasOwn(raw, "value")) {
1574
+ return Object.freeze({ status: raw.status, value: read(raw.value) });
1575
+ }
1576
+ if ((raw.status === "none" || raw.status === "contended") && !Object.hasOwn(raw, "value")) {
1577
+ return Object.freeze({ status: raw.status });
1578
+ }
1579
+ return invalid(code);
1580
+ }
1581
+ function readRetryPolicy(input, code = REQUEST) {
1582
+ const raw = readRecord(input, ["maxAttempts", "baseDelayMs", "maxDelayMs"], [], code);
1583
+ const bounds = RETRY_POLICY_BOUNDS;
1584
+ const baseDelayMs = integer(raw.baseDelayMs, bounds.baseDelayMs.min, bounds.baseDelayMs.max, code);
1585
+ return Object.freeze({
1586
+ maxAttempts: integer(raw.maxAttempts, bounds.maxAttempts.min, bounds.maxAttempts.max, code),
1587
+ baseDelayMs,
1588
+ maxDelayMs: integer(raw.maxDelayMs, baseDelayMs, bounds.maxDelayMs.max, code)
1589
+ });
1590
+ }
1591
+ function readRetentionPolicy(input, code = REQUEST) {
1592
+ const { payloadMs, historyMs, idempotencyMs } = readRecord(
1593
+ input,
1594
+ ["payloadMs", "historyMs", "idempotencyMs"],
1595
+ [],
1596
+ code
1597
+ );
1598
+ const bounds = RETENTION_POLICY_BOUNDS;
1599
+ return Object.freeze({
1600
+ payloadMs: integer(payloadMs, bounds.payloadMs.min, bounds.payloadMs.max, code),
1601
+ historyMs: integer(historyMs, bounds.historyMs.min, bounds.historyMs.max, code),
1602
+ idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
1603
+ });
1604
+ }
1605
+ function readStoreAdmission(scope, input) {
1606
+ const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
1607
+ const command = validatePreparedCommand(scope, raw.command);
1608
+ return Object.freeze({
1609
+ command,
1610
+ admissionKey: encodeAdmissionKey(command.key),
1611
+ jobId: readStoreId(raw.jobId),
1612
+ retry: readRetryPolicy(raw.retry),
1613
+ retention: readRetentionPolicy(raw.retention)
1614
+ });
1615
+ }
1616
+ function readFence(input) {
1617
+ const { jobId, attemptId, token } = readRecord(input, ["jobId", "attemptId", "token"], [], REQUEST);
1618
+ return Object.freeze({ jobId: readStoreId(jobId), attemptId: readStoreId(attemptId), token: readLeaseToken(token) });
1619
+ }
1620
+ function readClaim(input) {
1621
+ const { attemptId, token, leaseMs } = readRecord(input, ["attemptId", "token", "leaseMs"], [], REQUEST);
1622
+ return Object.freeze({
1623
+ attemptId: readStoreId(attemptId),
1624
+ token: readLeaseToken(token),
1625
+ leaseMs: readLeaseMs(leaseMs)
1626
+ });
1627
+ }
1628
+ function readFinish(input) {
1629
+ const { fence, phase, operationId, result } = readRecord(
1630
+ input,
1631
+ ["fence", "phase", "operationId", "result"],
1632
+ [],
1633
+ REQUEST
1634
+ );
1635
+ if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
1636
+ const evidence2 = readAttemptResult(result);
1637
+ assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
1638
+ return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
1639
+ }
1640
+ function readResolution(input) {
1641
+ const raw = readRecord(input, ["jobId", "attemptId", "action"], ["acknowledgeDuplicateRisk"], REQUEST);
1642
+ const ids = { jobId: readStoreId(raw.jobId), attemptId: readStoreId(raw.attemptId) };
1643
+ if (raw.action === "dismiss" && !Object.hasOwn(raw, "acknowledgeDuplicateRisk")) {
1644
+ return Object.freeze({ ...ids, action: raw.action });
1645
+ }
1646
+ if (raw.action === "redrive" && raw.acknowledgeDuplicateRisk === true) {
1647
+ return Object.freeze({ ...ids, action: raw.action, acknowledgeDuplicateRisk: true });
1648
+ }
1649
+ return invalid(REQUEST);
1650
+ }
1651
+
1652
+ // src/internal/activity-codecs.ts
1653
+ var ACTIVITY_BYTES = 8192;
1654
+ var dispositions = [
1655
+ "accepted",
1656
+ "partially_accepted",
1657
+ "validated",
1658
+ "rejected",
1659
+ "unknown",
1660
+ "failed",
1661
+ "expired",
1662
+ "cancelled"
1663
+ ];
1664
+ function readDisposition(input, code) {
1665
+ const disposition = dispositions.find((value) => value === input);
1666
+ if (disposition) return disposition;
1667
+ if (input === "retry_scheduled") return input;
1668
+ return invalid(code);
1669
+ }
1670
+ function assertActivityDisposition(result, disposition, code) {
1671
+ const { outcome, reason } = result;
1672
+ if (outcome !== "rejected" && outcome !== "unsubmitted") {
1673
+ if (disposition !== outcome) invalid(code);
1674
+ } else if (reason === "expired" || reason === "cancelled") {
1675
+ if (disposition !== reason) invalid(code);
1676
+ } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
1677
+ invalid(code);
1678
+ }
1679
+ }
1680
+ function readActivity(scope, input, code = "store_incompatible") {
1681
+ const raw = readRecord(
1682
+ input,
1683
+ [
1684
+ "version",
1685
+ "scope",
1686
+ "jobId",
1687
+ "attemptId",
1688
+ "ordinal",
1689
+ "provider",
1690
+ "template",
1691
+ "correlation",
1692
+ "startedAt",
1693
+ "finishedAt",
1694
+ "result",
1695
+ "disposition"
1696
+ ],
1697
+ ["handedOffAt"],
1698
+ code
1699
+ );
1700
+ if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope) invalid(code);
1701
+ const jobId = readStoreId(raw.jobId, code);
1702
+ const attemptId = readStoreId(raw.attemptId, code);
1703
+ const provider = validateProviderRef(raw.provider, code);
1704
+ const startedAt = unixMs(raw.startedAt, code);
1705
+ const finishedAt = unixMs(raw.finishedAt, code);
1706
+ const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1707
+ if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1708
+ invalid(code);
1709
+ }
1710
+ const result = readAttemptResult(raw.result, code, true);
1711
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1712
+ assertEvidenceContext(result, provider, attemptId, void 0, code);
1713
+ const disposition = readDisposition(raw.disposition, code);
1714
+ assertActivityDisposition(result, disposition, code);
1715
+ return Object.freeze({
1716
+ version: EMAIL_FORMAT_VERSION,
1717
+ scope,
1718
+ jobId,
1719
+ attemptId,
1720
+ ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, code),
1721
+ provider,
1722
+ template: validateTemplateIdentity(raw.template, code),
1723
+ correlation: validateCorrelation(raw.correlation, code),
1724
+ startedAt,
1725
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
1726
+ finishedAt,
1727
+ result,
1728
+ disposition
1729
+ });
1730
+ }
1731
+ function activityFor(job, commit) {
1732
+ const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
1733
+ return readActivity(job.scope, {
1734
+ version: EMAIL_FORMAT_VERSION,
1735
+ scope: job.scope,
1736
+ jobId: job.jobId,
1737
+ attemptId: commit.attemptId,
1738
+ ordinal: commit.ordinal,
1739
+ provider: job.provider,
1740
+ template: job.template,
1741
+ correlation: job.correlation,
1742
+ startedAt: commit.startedAt,
1743
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1744
+ finishedAt: commit.finishedAt,
1745
+ disposition: commit.disposition,
1746
+ result: {
1747
+ outcome,
1748
+ retry,
1749
+ stage,
1750
+ reason,
1751
+ ...recipients === void 0 ? {} : { recipients },
1752
+ ...messageId === void 0 ? {} : { messageId },
1753
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1754
+ }
1755
+ });
1756
+ }
1757
+ function activityDigest(activity) {
1758
+ return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
1759
+ }
1760
+ function readStoredActivity(scope, input, code = "store_incompatible") {
1761
+ const raw = readRecord(input, ["activity", "digest"], [], code);
1762
+ const activity = readActivity(scope, raw.activity, code);
1763
+ const digest = hashToken(raw.digest, code);
1764
+ if (activityDigest(activity) !== digest) invalid(code);
1765
+ return Object.freeze({ activity, digest });
1766
+ }
1767
+ function readProjectionPermit(scope, input) {
1768
+ const code = "invalid_command";
1769
+ const {
1770
+ activity,
1771
+ digest,
1772
+ permitUntil: rawUntil
1773
+ } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1774
+ const stored = readStoredActivity(scope, { activity, digest }, code);
1775
+ const permitUntil = unixMs(rawUntil, code);
1776
+ if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1777
+ return Object.freeze({ ...stored, permitUntil });
1778
+ }
1779
+ function compareAscii(a, b) {
1780
+ return a < b ? -1 : a > b ? 1 : 0;
1781
+ }
1782
+ function compareActivity(a, b) {
1783
+ return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1784
+ }
1785
+ function cursorPayload(criteria, position) {
1786
+ return {
1787
+ v: EMAIL_FORMAT_VERSION,
1788
+ s: criteria.scope,
1789
+ j: criteria.jobId,
1790
+ f: criteria.from,
1791
+ b: criteria.before,
1792
+ p: [position.finishedAt, position.jobId, position.attemptId]
1793
+ };
1794
+ }
1795
+ function encodeCursor(criteria, position) {
1796
+ const code = "invalid_cursor";
1797
+ const { encoded } = canonicalJson(cursorPayload(criteria, position), MAX_ACTIVITY_CURSOR_BYTES, code);
1798
+ const cursor = import_node_buffer3.Buffer.from(encoded).toString("base64url");
1799
+ if (cursor.length > MAX_ACTIVITY_CURSOR_BYTES) invalid(code);
1800
+ return cursor;
1801
+ }
1802
+ function decodeCursor(criteria, cursor) {
1803
+ const code = "invalid_cursor";
1804
+ if (typeof cursor !== "string" || cursor.length === 0 || cursor.length > MAX_ACTIVITY_CURSOR_BYTES || !/^[A-Za-z0-9_-]+$/.test(cursor)) {
1805
+ invalid(code);
1806
+ }
1807
+ let input;
1808
+ try {
1809
+ input = JSON.parse(import_node_buffer3.Buffer.from(cursor, "base64url").toString("utf8"));
1810
+ } catch {
1811
+ invalid(code);
1812
+ }
1813
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
1814
+ const tuple = readArray(p, 3, code, (entry) => entry);
1815
+ const position = Object.freeze({
1816
+ finishedAt: unixMs(tuple[0], code),
1817
+ jobId: readStoreId(tuple[1], code),
1818
+ attemptId: readStoreId(tuple[2], code)
1819
+ });
1820
+ 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) {
1821
+ invalid(code);
1822
+ }
1823
+ return position;
1824
+ }
1825
+ function readActivityCriteria(scope, input) {
1826
+ const code = "invalid_command";
1827
+ const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1828
+ const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1829
+ const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1830
+ const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1831
+ if (from !== null && before !== null && from > before) invalid(code);
1832
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, ACTIVITY_PAGE_LIMIT.min, ACTIVITY_PAGE_LIMIT.max, code) : ACTIVITY_PAGE_LIMIT.default;
1833
+ const criteria = { scope, jobId, from, before, limit };
1834
+ return Object.freeze({
1835
+ ...criteria,
1836
+ ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
1837
+ });
1838
+ }
1839
+ function activityQuery(criteria) {
1840
+ const { jobId, from, before, limit, after } = criteria;
1841
+ return Object.freeze({
1842
+ ...jobId === null ? {} : { jobId },
1843
+ ...from === null ? {} : { from },
1844
+ ...before === null ? {} : { before },
1845
+ limit,
1846
+ ...after === void 0 ? {} : { cursor: encodeCursor(criteria, after) }
1847
+ });
1848
+ }
1849
+ function readOrderedActivities(criteria, input, maxRows) {
1850
+ const code = "store_incompatible";
1851
+ let previous = criteria.after;
1852
+ return readArray(input, maxRows, code, (row) => {
1853
+ const activity = readActivity(criteria.scope, row);
1854
+ 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) {
1855
+ invalid(code);
1856
+ }
1857
+ previous = activity;
1858
+ return activity;
1859
+ });
1860
+ }
1861
+ function activityPage(criteria, ordered) {
1862
+ const rows = readOrderedActivities(criteria, ordered, criteria.limit + 1);
1863
+ const more = rows.length > criteria.limit;
1864
+ const items = more ? Object.freeze(rows.slice(0, criteria.limit)) : rows;
1865
+ const last = items.at(-1);
1866
+ return Object.freeze({ items, ...more && last ? { nextCursor: encodeCursor(criteria, last) } : {} });
1867
+ }
1868
+ function readActivityPage(criteria, input) {
1869
+ const code = "store_incompatible";
1870
+ const raw = readRecord(input, ["items"], ["nextCursor"], code);
1871
+ const items = readOrderedActivities(criteria, raw.items, criteria.limit);
1872
+ if (!Object.hasOwn(raw, "nextCursor")) return Object.freeze({ items });
1873
+ const last = items.at(-1);
1874
+ if (!last || items.length !== criteria.limit || raw.nextCursor !== encodeCursor(criteria, last)) invalid(code);
1875
+ return Object.freeze({ items, nextCursor: raw.nextCursor });
1876
+ }
1877
+
1878
+ // src/internal/job-summary.ts
1879
+ var STORED = "store_incompatible";
1880
+ var COMMON = [
1881
+ "version",
1882
+ "scope",
1883
+ "jobId",
1884
+ "key",
1885
+ "provider",
1886
+ "template",
1887
+ "correlation",
1888
+ "scheduleAt",
1889
+ "createdAt",
1890
+ "updatedAt",
1891
+ "expiresAt",
1892
+ "priority",
1893
+ "attemptCount",
1894
+ "unknownOpen",
1895
+ "resolutions",
1896
+ "state"
1897
+ ];
1898
+ function readUnknownResolution(input) {
1899
+ const { attemptId, at, action } = readRecord(input, ["attemptId", "at", "action"], [], STORED);
1900
+ if (action !== "dismiss" && action !== "redrive") invalid(STORED);
1901
+ return Object.freeze({ attemptId: readStoreId(attemptId, STORED), at: unixMs(at, STORED), action });
1902
+ }
1903
+ function readJobSummary(scope, input) {
1904
+ const raw = readRecord(
1905
+ input,
1906
+ COMMON,
1907
+ ["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt"],
1908
+ STORED
1909
+ );
1910
+ if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED) !== scope) invalid(STORED);
1911
+ const createdAt = unixMs(raw.createdAt, STORED);
1912
+ const updatedAt = unixMs(raw.updatedAt, STORED);
1913
+ const expiresAt = unixMs(raw.expiresAt, STORED);
1914
+ const scheduleAt = raw.scheduleAt === null ? null : unixMs(raw.scheduleAt, STORED);
1915
+ const firstDue = Math.max(createdAt, scheduleAt ?? createdAt);
1916
+ if (updatedAt < createdAt || firstDue >= expiresAt) invalid(STORED);
1917
+ let state;
1918
+ if (raw.state === "queued") {
1919
+ readRecord(raw, [...COMMON, "nextAt"], ["latestAttempt"], STORED);
1920
+ const nextAt = unixMs(raw.nextAt, STORED);
1921
+ if (nextAt < firstDue || nextAt >= expiresAt) invalid(STORED);
1922
+ state = { state: raw.state, nextAt };
1923
+ } else if (raw.state === "leased") {
1924
+ readRecord(raw, [...COMMON, "phase"], ["latestAttempt"], STORED);
1925
+ if (raw.phase !== "pre_handoff" && raw.phase !== "handed_off") invalid(STORED);
1926
+ state = { state: raw.state, phase: raw.phase };
1927
+ } else if (raw.state === "terminal") {
1928
+ readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], ["latestAttempt"], STORED);
1929
+ const terminalAt = unixMs(raw.terminalAt, STORED);
1930
+ const disposition = readDisposition(raw.disposition, STORED);
1931
+ if (terminalAt < createdAt || terminalAt > updatedAt || disposition === "retry_scheduled") invalid(STORED);
1932
+ state = {
1933
+ state: raw.state,
1934
+ disposition,
1935
+ terminalAt,
1936
+ terminalReason: raw.terminalReason === "attempts_exhausted" ? raw.terminalReason : readAttemptReason(raw.terminalReason, STORED)
1937
+ };
1938
+ } else {
1939
+ return invalid(STORED);
1940
+ }
1941
+ const active = Number(state.state === "leased");
1942
+ const attemptCount = integer(raw.attemptCount, active, MAX_ATTEMPT_LEDGER, STORED);
1943
+ const latest = Object.hasOwn(raw, "latestAttempt") ? readLatestAttempt(raw.latestAttempt) : void 0;
1944
+ const hasFinalized = attemptCount > active;
1945
+ if (latest !== void 0 !== hasFinalized) invalid(STORED);
1946
+ const { unknownOpen } = raw;
1947
+ if (typeof unknownOpen !== "boolean" || unknownOpen && !(state.state === "terminal" && state.disposition === "unknown")) {
1948
+ invalid(STORED);
1949
+ }
1950
+ const resolutions = readArray(raw.resolutions, Math.min(2, attemptCount - active), STORED, readUnknownResolution);
1951
+ return Object.freeze({
1952
+ version: EMAIL_FORMAT_VERSION,
1953
+ scope,
1954
+ jobId: readStoreId(raw.jobId, STORED),
1955
+ key: validateAdmissionKey(raw.key, STORED),
1956
+ provider: validateProviderRef(raw.provider, STORED),
1957
+ template: validateTemplateIdentity(raw.template, STORED),
1958
+ correlation: validateCorrelation(raw.correlation, STORED),
1959
+ scheduleAt,
1960
+ createdAt,
1961
+ updatedAt,
1962
+ expiresAt,
1963
+ priority: integer(raw.priority, PRIORITY.min, PRIORITY.max, STORED),
1964
+ attemptCount,
1965
+ ...latest === void 0 ? {} : { latestAttempt: latest },
1966
+ unknownOpen,
1967
+ resolutions,
1968
+ ...state
1969
+ });
1970
+ }
1971
+ function matchesAdmissionJob(job, identity, status) {
1972
+ return job.scope === identity.scope && sameCommandMetadata(job.key, job.template.key, job.provider, job.scheduleAt, identity) && (status === "replayed" || job.state === "queued" && job.attemptCount === 0 && job.createdAt === job.updatedAt && job.nextAt === Math.max(job.createdAt, job.scheduleAt ?? job.createdAt));
1973
+ }
1974
+ function readLatestAttempt(input) {
1975
+ const latest = readRecord(input, ["attemptId", "outcome", "reason"], [], STORED);
1976
+ const reason = readAttemptReason(latest.reason, STORED);
1977
+ const outcome = attemptOutcome(reason);
1978
+ if (latest.outcome !== outcome) invalid(STORED);
1979
+ return Object.freeze({ attemptId: readStoreId(latest.attemptId, STORED), outcome, reason });
1980
+ }
1981
+
1982
+ // src/internal/store-call.ts
1983
+ var import_node_util6 = require("util");
1984
+ var STORE_PERSISTENCE_ERRORS = [
1985
+ "store_capacity",
1986
+ "store_unavailable",
1987
+ "store_incompatible",
1988
+ "write_unconfirmed"
1989
+ ];
1990
+ var STOP_ERRORS = ["aborted", "deadline"];
1991
+ async function runStoreCall(clock, parent, options) {
1992
+ let budget;
1993
+ try {
1994
+ budget = createChildBudgetUntil(
1995
+ clock,
1996
+ parent,
1997
+ Math.min(monotonicNow(clock) + options.maxMs, options.deadline ?? Infinity)
1998
+ );
1999
+ const mutation = options.effect === "mutation";
2000
+ options.beforeInvoke?.();
2001
+ budget.check();
2002
+ const dispatchedAt = monotonicNow(clock);
2003
+ const timeoutMs = Math.floor(budget.deadline - dispatchedAt);
2004
+ if (timeoutMs < 1 || budget.signal.aborted) {
2005
+ budget.check();
2006
+ invalid("deadline");
2007
+ }
2008
+ const call = Object.freeze({ timeoutMs, signal: budget.signal });
2009
+ let raw;
2010
+ try {
2011
+ const pending = options.invoke(call, dispatchedAt);
2012
+ raw = import_node_util6.types.isPromise(pending) ? await pending : pending;
2013
+ } catch (error) {
2014
+ const known = allowedErrorCode(error, options.definite ?? []) ?? allowedErrorCode(error, STORE_PERSISTENCE_ERRORS) ?? allowedErrorCode(error, ["busy"]);
2015
+ if (mutation) return invalid(known ?? "write_unconfirmed");
2016
+ budget.check();
2017
+ if (known === "write_unconfirmed") invalid("store_unavailable");
2018
+ return invalid(known ?? allowedErrorCode(error, STOP_ERRORS) ?? "store_unavailable");
2019
+ }
2020
+ try {
2021
+ budget.check();
2022
+ let captured;
2023
+ try {
2024
+ captured = options.accept(raw);
2025
+ } catch {
2026
+ budget.check();
2027
+ return invalid("store_incompatible");
2028
+ }
2029
+ budget.check();
2030
+ return captured;
2031
+ } catch (error) {
2032
+ if (mutation) invalid("write_unconfirmed");
2033
+ throw error;
2034
+ }
2035
+ } catch (error) {
2036
+ options.onError?.(error);
2037
+ throw error;
2038
+ } finally {
2039
+ budget?.close();
2040
+ }
2041
+ }
2042
+
2043
+ // src/service.ts
2044
+ var PREPARATION_ERRORS = [
2045
+ "invalid_config",
2046
+ "invalid_command",
2047
+ "invalid_input",
2048
+ "invalid_data",
2049
+ "invalid_snapshot",
2050
+ "preparation_failed",
2051
+ "template_not_found",
2052
+ "template_source",
2053
+ "template_render",
2054
+ "provider_mismatch",
2055
+ "expired",
2056
+ "aborted",
2057
+ "deadline",
2058
+ "busy"
2059
+ ];
2060
+ var UNCONFIRMED = ["write_unconfirmed"];
2061
+ var CONFLICT = ["idempotency_conflict"];
2062
+ var INSERT_REJECTIONS = ["invalid_command", "invalid_snapshot", "provider_mismatch", "expired"];
2063
+ var CONFIG = "invalid_config";
2064
+ var STORED2 = "store_incompatible";
2065
+ var injectedRegistrySlots = /* @__PURE__ */ new WeakMap();
2066
+ var serviceAdmissions = /* @__PURE__ */ new WeakMap();
2067
+ function findServiceAdmission(service) {
2068
+ return serviceAdmissions.get(service);
2069
+ }
2070
+ function createEmailService(options) {
2071
+ return createEmailServiceWithClock(options, systemEmailClock);
2072
+ }
2073
+ function createEmailServiceWithClock(options, clock) {
2074
+ const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention"], CONFIG);
2075
+ const scope = scopeToken(raw.scope, CONFIG);
2076
+ const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2077
+ const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
2078
+ const find = bindMethod(raw.store, "findAdmission");
2079
+ const insert = bindMethod(raw.store, "insert");
2080
+ if (typeof raw.registry !== "object" || raw.registry === null || import_node_util7.types.isProxy(raw.registry)) invalid(CONFIG);
2081
+ const registry = raw.registry;
2082
+ const prepare = bindMethod(registry, "prepare");
2083
+ const internalPrepare = findRegistryPreparation(registry);
2084
+ async function prepareMiss(parsed, parent) {
2085
+ const { identity, command } = parsed;
2086
+ const accept = (value) => {
2087
+ const staged = validatePreparedCommand(scope, value);
2088
+ if (!sameCommandMetadata(
2089
+ staged.key,
2090
+ staged.snapshot.template.key,
2091
+ staged.snapshot.provider,
2092
+ staged.scheduleAt,
2093
+ identity
2094
+ ) || staged.intentHash !== identity.intentHash || staged.fingerprint !== identity.fingerprint) {
2095
+ invalid("invalid_snapshot");
2096
+ }
2097
+ return staged;
2098
+ };
2099
+ if (internalPrepare) {
2100
+ let value;
2101
+ try {
2102
+ value = await internalPrepare(parsed, parent);
2103
+ } catch (error) {
2104
+ parent.check();
2105
+ return invalid(allowedErrorCode(error, PREPARATION_ERRORS) ?? "preparation_failed");
2106
+ }
2107
+ parent.check();
2108
+ return accept(value);
2109
+ }
2110
+ parent.check();
2111
+ let slots = injectedRegistrySlots.get(registry);
2112
+ if (!slots) {
2113
+ slots = { pending: 0 };
2114
+ injectedRegistrySlots.set(registry, slots);
2115
+ }
2116
+ if (slots.pending >= TEMPLATE_MAX_PENDING.default) invalid("busy");
2117
+ const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
2118
+ const occupied = slots;
2119
+ slots.pending++;
2120
+ const slot = new CallbackSlot(() => occupied.pending--);
2121
+ try {
2122
+ return await runHostCallback(
2123
+ budget,
2124
+ slot,
2125
+ "preparation_failed",
2126
+ () => {
2127
+ const timeoutMs = Math.max(CALL_BUDGETS.prepare.min, Math.ceil(budget.remainingMs()));
2128
+ budget.check();
2129
+ return prepare(scope, command, {
2130
+ signal: budget.signal,
2131
+ // The backing signal still has the exact narrower deadline below the public override floor.
2132
+ timeoutMs
2133
+ });
2134
+ },
2135
+ accept,
2136
+ PREPARATION_ERRORS
2137
+ );
2138
+ } finally {
2139
+ budget.close();
2140
+ slot.close();
2141
+ }
2142
+ }
2143
+ function findWinner(key, budget) {
2144
+ return runStoreCall(clock, budget, {
2145
+ maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2146
+ effect: "read",
2147
+ invoke: (call) => find(scope, key, call),
2148
+ accept(value) {
2149
+ if (value === null) return null;
2150
+ const raw2 = readRecord(value, ["job", "fingerprint"], [], STORED2);
2151
+ const job = readJobSummary(scope, raw2.job);
2152
+ if (encodeAdmissionKey(job.key) !== encodeAdmissionKey(key)) invalid(STORED2);
2153
+ return { job, fingerprint: hashToken(raw2.fingerprint, STORED2) };
2154
+ }
2155
+ });
2156
+ }
2157
+ function replay(winner, identity) {
2158
+ if (winner.fingerprint !== identity.fingerprint) invalid("idempotency_conflict");
2159
+ const { job } = winner;
2160
+ if (!matchesAdmissionJob(job, identity, "replayed")) invalid(STORED2);
2161
+ return Object.freeze({ status: "replayed", job });
2162
+ }
2163
+ async function insertOrConfirm(command, identity, budget) {
2164
+ budget.check();
2165
+ const admission = Object.freeze({ command, jobId: (0, import_node_crypto2.randomUUID)(), retry, retention });
2166
+ try {
2167
+ const job = await runStoreCall(clock, budget, {
2168
+ maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2169
+ effect: "mutation",
2170
+ definite: INSERT_REJECTIONS,
2171
+ invoke: (call) => insert(scope, admission, call),
2172
+ accept(value) {
2173
+ const raw2 = readRecord(value, ["status"], ["job"], STORED2);
2174
+ if (raw2.status === "duplicate" && !Object.hasOwn(raw2, "job")) return null;
2175
+ if (raw2.status !== "inserted") invalid(STORED2);
2176
+ const job2 = readJobSummary(scope, raw2.job);
2177
+ const { snapshot } = command;
2178
+ if (job2.jobId !== admission.jobId || !matchesAdmissionJob(job2, identity, "enqueued") || job2.template.revision !== snapshot.template.revision || snapshot.preparedAt - job2.createdAt > MAX_PREPARED_AT_SKEW_MS || job2.expiresAt !== snapshot.expiresAt || job2.priority !== snapshot.priority || !sameCorrelation(job2.correlation, snapshot.correlation)) {
2179
+ invalid(STORED2);
2180
+ }
2181
+ return job2;
2182
+ }
2183
+ });
2184
+ if (job) return Object.freeze({ status: "enqueued", job });
2185
+ } catch (error) {
2186
+ if (!allowedErrorCode(error, UNCONFIRMED)) throw error;
2187
+ }
2188
+ try {
2189
+ const winner = await findWinner(identity.key, budget);
2190
+ if (winner) return replay(winner, identity);
2191
+ } catch (error) {
2192
+ if (allowedErrorCode(error, CONFLICT)) throw error;
2193
+ }
2194
+ return invalid("write_unconfirmed");
2195
+ }
2196
+ async function enqueueParsed(parsed, budget) {
2197
+ if (parsed.identity.scope !== scope) invalid("invalid_command");
2198
+ const winner = await findWinner(parsed.identity.key, budget);
2199
+ if (winner) return replay(winner, parsed.identity);
2200
+ return insertOrConfirm(await prepareMiss(parsed, budget), parsed.identity, budget);
2201
+ }
2202
+ async function inOperation(call, run) {
2203
+ const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
2204
+ const budget = createBudget(clock, timeoutMs, signal);
2205
+ try {
2206
+ budget.check();
2207
+ return await run(budget);
2208
+ } finally {
2209
+ budget.close();
2210
+ }
2211
+ }
2212
+ const service = Object.freeze({
2213
+ scope,
2214
+ enqueue(command, call = {}) {
2215
+ return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command), budget));
2216
+ },
2217
+ enqueuePrepared(input, call = {}) {
2218
+ return inOperation(call, async (budget) => {
2219
+ const command = validatePreparedCommand(scope, input);
2220
+ const identity = {
2221
+ scope,
2222
+ key: command.key,
2223
+ templateKey: command.snapshot.template.key,
2224
+ provider: command.snapshot.provider,
2225
+ scheduleAt: command.scheduleAt,
2226
+ intentHash: command.intentHash,
2227
+ fingerprint: command.fingerprint
2228
+ };
2229
+ const winner = await findWinner(identity.key, budget);
2230
+ return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
2231
+ });
2232
+ }
2233
+ });
2234
+ serviceAdmissions.set(service, enqueueParsed);
2235
+ return service;
2236
+ }
2237
+ function readPolicy(input, defaults) {
2238
+ const result = { ...defaults };
2239
+ const keys = Object.keys(defaults);
2240
+ const raw = readRecord(input === void 0 ? {} : input, [], keys, CONFIG);
2241
+ for (const key of keys) {
2242
+ if (raw[key] !== void 0) result[key] = raw[key];
2243
+ }
2244
+ return result;
2245
+ }
2246
+ function sameCorrelation(left, right) {
2247
+ const keys = Object.keys(left);
2248
+ return keys.length === Object.keys(right).length && keys.every((key) => left[key] === right[key]);
2249
+ }
2250
+
2251
+ // src/worker.ts
2252
+ var import_node_crypto4 = require("crypto");
2253
+
2254
+ // src/internal/worker-attempt.ts
2255
+ var import_node_util8 = require("util");
2256
+
2257
+ // src/internal/worker-config.ts
2258
+ var CONFIG2 = "invalid_config";
2259
+ function readLimits(input) {
2260
+ const keys = Object.keys(WORKER_LIMIT_BOUNDS);
2261
+ const raw = readRecord(input === void 0 ? {} : input, [], keys, CONFIG2);
2262
+ const limits = {};
2263
+ for (const key of keys) limits[key] = boundedOption(raw[key], WORKER_LIMIT_BOUNDS[key]);
2264
+ const { leaseMs, storeTimeoutMs, providerTimeoutMs, finalizeGraceMs } = limits;
2265
+ if (leaseMs < Math.max(
2266
+ 3 * storeTimeoutMs + CLOCK_MARGIN_MS,
2267
+ storeTimeoutMs + providerTimeoutMs + finalizeGraceMs + CLOCK_MARGIN_MS
2268
+ )) {
2269
+ invalid(CONFIG2);
2270
+ }
2271
+ return Object.freeze(limits);
2272
+ }
2273
+ function sameProvider(a, b) {
2274
+ return a.kind === b.kind && a.key === b.key && a.mode === b.mode;
2275
+ }
2276
+ function readProfiles(input) {
2277
+ const profiles = /* @__PURE__ */ new Map();
2278
+ readArray(input, Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
2279
+ const ref = validateProviderRef(readPortMember(provider, "ref"), CONFIG2);
2280
+ if (profiles.has(ref.key)) invalid(CONFIG2);
2281
+ profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
2282
+ });
2283
+ return profiles;
2284
+ }
2285
+ function readResolvers(input) {
2286
+ const resolvers = /* @__PURE__ */ new Map();
2287
+ if (input !== void 0) {
2288
+ for (const key of plainKeys(input, Number.MAX_SAFE_INTEGER, CONFIG2)) {
2289
+ resolvers.set(
2290
+ identifier(key, CONFIG2),
2291
+ requireCallback(ownData(input, key, CONFIG2))
2292
+ );
2293
+ }
2294
+ }
2295
+ return resolvers;
2296
+ }
2297
+ function readLimiter(input) {
2298
+ if (input === void 0) return;
2299
+ const scope = readPortMember(input, "scope");
2300
+ if (scope !== "worker" && scope !== "shared") invalid(CONFIG2);
2301
+ return Object.freeze({ scope, tryAcquire: bindMethod(input, "tryAcquire") });
2302
+ }
2303
+ function readWorkerClock(input) {
2304
+ const clock = readClock(input);
2305
+ let last = -Infinity;
2306
+ return Object.freeze({
2307
+ ...clock,
2308
+ monotonicNow() {
2309
+ const now = monotonicNow(clock);
2310
+ if (now < last) invalid(CONFIG2);
2311
+ last = now;
2312
+ return now;
2313
+ }
2314
+ });
2315
+ }
2316
+ function readWorkerConfig(input) {
2317
+ const raw = readRecord(
2318
+ input,
2319
+ ["scope", "store", "providers"],
2320
+ ["attachmentResolvers", "rateLimiter", "clock", "limits"],
2321
+ CONFIG2
2322
+ );
2323
+ const { store } = raw;
2324
+ return Object.freeze({
2325
+ scope: scopeToken(raw.scope, CONFIG2),
2326
+ limits: readLimits(raw.limits),
2327
+ clock: readWorkerClock(raw.clock),
2328
+ profiles: readProfiles(raw.providers),
2329
+ resolvers: readResolvers(raw.attachmentResolvers),
2330
+ limiter: readLimiter(raw.rateLimiter),
2331
+ store: Object.freeze({
2332
+ claimNext: bindMethod(store, "claimNext"),
2333
+ recoverNext: bindMethod(store, "recoverNext"),
2334
+ expireNext: bindMethod(store, "expireNext"),
2335
+ renew: bindMethod(store, "renew"),
2336
+ markHandoff: bindMethod(store, "markHandoff"),
2337
+ finish: bindMethod(store, "finish"),
2338
+ findAttempt: bindMethod(store, "findAttempt")
2339
+ })
2340
+ });
2341
+ }
2342
+ function readRunOptions(input, limits) {
2343
+ const { limit, concurrency, maintenanceLimit, ...call } = readRecord(
2344
+ input,
2345
+ [],
2346
+ ["limit", "concurrency", "maintenanceLimit", "signal", "timeoutMs"],
2347
+ CONFIG2
2348
+ );
2349
+ return Object.freeze({
2350
+ ...readCallOptions(call, CALL_BUDGETS.batchOrRun),
2351
+ limit: boundedOption(limit, RUN_CLAIM_LIMIT),
2352
+ concurrency: boundedOption(concurrency, { min: 1, max: limits.maxConcurrency, default: limits.maxConcurrency }),
2353
+ maintenanceLimit: boundedOption(maintenanceLimit, RUN_MAINTENANCE_LIMIT)
2354
+ });
2355
+ }
2356
+ function readShutdownOptions(input) {
2357
+ return readCallOptions(readRecord(input, [], ["timeoutMs"], CONFIG2), CALL_BUDGETS.shutdown);
2358
+ }
2359
+
2360
+ // src/internal/worker-evidence.ts
2361
+ var STORED3 = "store_incompatible";
2362
+ var MAX_ORDINARY_ATTEMPTS = RETRY_POLICY_BOUNDS.maxAttempts.max;
2363
+ function readGrant(times, leaseMs) {
2364
+ const grantedAt = unixMs(times.grantedAt, STORED3);
2365
+ const leaseEndsAt = unixMs(times.leaseEndsAt, STORED3);
2366
+ if (leaseEndsAt - grantedAt !== leaseMs) invalid(STORED3);
2367
+ return Object.freeze({ grantedAt, leaseEndsAt });
2368
+ }
2369
+ function readClaimed(value, scope, expected) {
2370
+ const raw = readRecord(value, ["job", "snapshot", "fence", "lease", "ordinal", "manual"], [], STORED3);
2371
+ const job = readJobSummary(scope, raw.job);
2372
+ const { snapshot } = validateSnapshot(raw.snapshot);
2373
+ const fence = readFence(raw.fence);
2374
+ const lease = readGrant(readRecord(raw.lease, ["grantedAt", "leaseEndsAt"], [], STORED3), expected.leaseMs);
2375
+ const ordinal = integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3);
2376
+ const { manual } = raw;
2377
+ const { grantedAt } = lease;
2378
+ const [redrive, more] = job.resolutions;
2379
+ if (job.state !== "leased" || job.phase !== "pre_handoff" || fence.jobId !== job.jobId || fence.attemptId !== expected.attemptId || fence.token !== expected.token || job.latestAttempt?.attemptId === fence.attemptId || ordinal !== job.attemptCount || typeof manual !== "boolean" || (manual ? redrive?.action !== "redrive" || more !== void 0 || redrive.at < job.createdAt || redrive.at > grantedAt || redrive.attemptId !== job.latestAttempt?.attemptId || job.latestAttempt.outcome !== "unknown" : redrive !== void 0 || ordinal > MAX_ORDINARY_ATTEMPTS || job.latestAttempt !== void 0 && !isSafeTransient(job.latestAttempt.reason)) || grantedAt !== job.updatedAt || grantedAt < (job.scheduleAt ?? job.createdAt) || grantedAt >= job.expiresAt || snapshot.preparedAt - job.createdAt > MAX_PREPARED_AT_SKEW_MS || snapshot.expiresAt !== job.expiresAt || snapshot.priority !== job.priority || !sameProvider(snapshot.provider, job.provider) || snapshot.template.key !== job.template.key || snapshot.template.revision !== job.template.revision || canonicalJson(snapshot.correlation, 4096, STORED3).encoded !== canonicalJson(job.correlation, 4096, STORED3).encoded) {
2380
+ invalid(STORED3);
2381
+ }
2382
+ return Object.freeze({ job, snapshot, fence, lease, ordinal, manual });
2383
+ }
2384
+ function safeLeaseEnd({ dispatchedAt, grant }) {
2385
+ return dispatchedAt + (grant.leaseEndsAt - grant.grantedAt) - CLOCK_MARGIN_MS;
2386
+ }
2387
+ function assertLaterGrant(grant, last, expiresAt, times) {
2388
+ const elapsed = grant.grantedAt - last.grant.grantedAt;
2389
+ if (elapsed < Math.max(0, times.dispatchedAt - last.confirmedAt - CLOCK_MARGIN_MS) || elapsed > times.confirmedAt - last.dispatchedAt + CLOCK_MARGIN_MS || grant.grantedAt >= Math.min(last.grant.leaseEndsAt, expiresAt)) {
2390
+ invalid(STORED3);
2391
+ }
2392
+ }
2393
+ function readRenewed(value, last, claim, leaseMs, times) {
2394
+ const grant = readGrant(readRecord(value, ["grantedAt", "leaseEndsAt"], [], STORED3), leaseMs);
2395
+ assertLaterGrant(grant, last, claim.job.expiresAt, times);
2396
+ if (grant.leaseEndsAt <= last.grant.leaseEndsAt) invalid(STORED3);
2397
+ return grant;
2398
+ }
2399
+ function readHandoff(value, last, claim, leaseMs, times) {
2400
+ const raw = readRecord(value, ["grantedAt", "leaseEndsAt", "handoffAt"], [], STORED3);
2401
+ const grant = readGrant(raw, leaseMs);
2402
+ const handoffAt = unixMs(raw.handoffAt, STORED3);
2403
+ if (handoffAt !== grant.grantedAt) invalid(STORED3);
2404
+ assertLaterGrant(grant, last, claim.job.expiresAt, times);
2405
+ return Object.freeze({ ...grant, handoffAt });
2406
+ }
2407
+ function readCommit(value) {
2408
+ const raw = readRecord(
2409
+ value,
2410
+ ["jobId", "attemptId", "ordinal", "operationId", "startedAt", "finishedAt", "result", "disposition", "reason"],
2411
+ ["handedOffAt", "retryAt"],
2412
+ STORED3
2413
+ );
2414
+ const startedAt = unixMs(raw.startedAt, STORED3);
2415
+ const finishedAt = unixMs(raw.finishedAt, STORED3);
2416
+ const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, STORED3) : void 0;
2417
+ const retryAt = Object.hasOwn(raw, "retryAt") ? unixMs(raw.retryAt, STORED3) : void 0;
2418
+ const result = readAttemptResult(raw.result, STORED3);
2419
+ const disposition = readDisposition(raw.disposition, STORED3);
2420
+ const reason = raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED3);
2421
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED3);
2422
+ assertActivityDisposition(result, disposition, STORED3);
2423
+ const expectedReason = disposition === "expired" ? "expired" : result.retry === "safe_transient" && (disposition === "failed" || disposition === "rejected") ? "attempts_exhausted" : result.reason;
2424
+ if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt) || reason !== expectedReason || retryAt !== void 0 !== (disposition === "retry_scheduled") || retryAt !== void 0 && (retryAt <= finishedAt || retryAt - finishedAt < (result.retryHint?.delayMs ?? 0) || retryAt < (result.retryHint?.notBefore ?? 0))) {
2425
+ invalid(STORED3);
2426
+ }
2427
+ return Object.freeze({
2428
+ jobId: readStoreId(raw.jobId, STORED3),
2429
+ attemptId: readStoreId(raw.attemptId, STORED3),
2430
+ ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3),
2431
+ operationId: readStoreId(raw.operationId, STORED3),
2432
+ startedAt,
2433
+ finishedAt,
2434
+ result,
2435
+ disposition,
2436
+ reason,
2437
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
2438
+ ...retryAt === void 0 ? {} : { retryAt }
2439
+ });
2440
+ }
2441
+ function readRecovery(value) {
2442
+ const commit = readCommit(value);
2443
+ const { result, startedAt, handedOffAt, finishedAt } = commit;
2444
+ if (result.reason !== "pre_handoff_lease_expired" && result.reason !== "post_handoff_lease_expired" || finishedAt - (handedOffAt ?? startedAt) < WORKER_LIMIT_BOUNDS.leaseMs.min) {
2445
+ invalid(STORED3);
2446
+ }
2447
+ return commit;
2448
+ }
2449
+ function readQueuedExpiry(value, scope) {
2450
+ const job = readJobSummary(scope, value);
2451
+ if (job.state !== "terminal" || job.disposition !== "expired" || job.terminalReason !== "expired" || job.terminalAt < job.expiresAt || job.updatedAt !== job.terminalAt) {
2452
+ invalid(STORED3);
2453
+ }
2454
+ return job;
2455
+ }
2456
+ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct) {
2457
+ const commit = readCommit(value);
2458
+ const { attemptId, startedAt, handedOffAt, finishedAt, result, disposition, retryAt } = commit;
2459
+ const { job, snapshot, fence, ordinal, manual } = claim;
2460
+ const { expiresAt } = job;
2461
+ const canHaveRetryBudget = !manual && ordinal < MAX_ORDINARY_ATTEMPTS;
2462
+ const last = handoff && handoff !== "unconfirmed" ? handoff.grant : lease.grant;
2463
+ const markedLeaseMs = claim.lease.leaseEndsAt - claim.lease.grantedAt;
2464
+ if (commit.jobId !== fence.jobId || attemptId !== fence.attemptId || startedAt !== claim.lease.grantedAt || commit.ordinal !== ordinal || finishedAt < last.grantedAt || handoff !== "unconfirmed" && handedOffAt !== handoff?.grant.handoffAt || handedOffAt !== void 0 && (handedOffAt < lease.grant.grantedAt || handedOffAt >= Math.min(expiresAt, lease.grant.leaseEndsAt)) || result.reason === "cancelled" && finishedAt >= expiresAt || result.reason === "expired" && finishedAt < expiresAt || result.reason === "pre_handoff_lease_expired" && finishedAt < lease.grant.leaseEndsAt || result.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < markedLeaseMs) || handedOffAt !== void 0 && result.reason !== "post_handoff_lease_expired" && (result.reason === "launch_window_closed" ? providerInvoked || handoff === "unconfirmed" : !providerInvoked) || result.retry === "safe_transient" && finishedAt >= expiresAt && disposition !== "expired" || result.retry === "safe_transient" && finishedAt < expiresAt && disposition === "expired" && !canHaveRetryBudget || retryAt !== void 0 && (!canHaveRetryBudget || retryAt >= expiresAt)) {
2465
+ invalid(STORED3);
2466
+ }
2467
+ assertEvidenceContext(result, snapshot.provider, attemptId, recipientCounts(snapshot.envelope), STORED3);
2468
+ if (request && commit.operationId === request.operationId) {
2469
+ const phase = handedOffAt === void 0 ? "pre_handoff" : "handed_off";
2470
+ if (phase !== request.phase || finishedAt >= last.leaseEndsAt || canonicalJson(result, 8192, STORED3).encoded !== canonicalJson(request.result, 8192, STORED3).encoded) {
2471
+ invalid(STORED3);
2472
+ }
2473
+ } else if (direct) {
2474
+ invalid(STORED3);
2475
+ }
2476
+ return commit;
2477
+ }
2478
+
2479
+ // src/internal/worker-finish.ts
2480
+ var import_node_crypto3 = require("crypto");
2481
+ async function finishAttempt(run, evidence2, providerInvoked, result) {
2482
+ const { clock, store, scope, limits } = run.config;
2483
+ const {
2484
+ claim: { fence },
2485
+ handoff,
2486
+ lease
2487
+ } = evidence2;
2488
+ const now = monotonicNow(clock);
2489
+ const request = result && handoff !== "unconfirmed" ? Object.freeze({ fence, phase: handoff ? "handed_off" : "pre_handoff", operationId: (0, import_node_crypto3.randomUUID)(), result }) : void 0;
2490
+ const leaseEnd = safeLeaseEnd(handoff && handoff !== "unconfirmed" ? handoff : lease);
2491
+ const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits.finalizeGraceMs);
2492
+ async function confirm() {
2493
+ try {
2494
+ return await run.callStore(grace, {
2495
+ effect: "read",
2496
+ invoke: (call) => store.findAttempt(scope, fence.jobId, fence.attemptId, call),
2497
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false)
2498
+ });
2499
+ } catch {
2500
+ return null;
2501
+ }
2502
+ }
2503
+ function write(exact) {
2504
+ return run.callStore(grace, {
2505
+ effect: "mutation",
2506
+ deadline: leaseEnd,
2507
+ invoke: (call) => store.finish(scope, exact, call),
2508
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true)
2509
+ });
2510
+ }
2511
+ try {
2512
+ if (!request || now >= leaseEnd) return await confirm();
2513
+ let retry = false;
2514
+ try {
2515
+ const committed = await write(request);
2516
+ if (committed) return committed;
2517
+ } catch (error) {
2518
+ retry = allowedErrorCode(error, ["write_unconfirmed"]) !== void 0;
2519
+ }
2520
+ const winner = await confirm();
2521
+ if (winner || !retry || grace.remainingMs() < 1 || monotonicNow(clock) >= leaseEnd) return winner;
2522
+ try {
2523
+ const committed = await write(request);
2524
+ if (committed) return committed;
2525
+ } catch {
2526
+ }
2527
+ return await confirm();
2528
+ } finally {
2529
+ grace.close();
2530
+ }
2531
+ }
2532
+
2533
+ // src/internal/worker-preflight.ts
2534
+ var stages = {
2535
+ attachment_unavailable: ["attachment", "safe_transient"],
2536
+ attachment_timeout: ["attachment", "safe_transient"],
2537
+ attachment_invalid: ["attachment", "never"],
2538
+ attachment_resolver_error: ["attachment", "never"],
2539
+ rate_deferred: ["rate_limit", "safe_transient"],
2540
+ rate_timeout: ["rate_limit", "safe_transient"],
2541
+ rate_error: ["rate_limit", "never"],
2542
+ profile_unavailable: ["pre_handoff", "never"],
2543
+ provider_preflight_error: ["pre_handoff", "never"],
2544
+ pre_handoff_timeout: ["pre_handoff", "safe_transient"],
2545
+ worker_stopped: ["pre_handoff", "safe_transient"],
2546
+ launch_window_closed: ["pre_handoff", "safe_transient"]
2547
+ };
2548
+ function unsubmitted(reason, delayMs) {
2549
+ const [stage, retry] = stages[reason];
2550
+ return Object.freeze({
2551
+ outcome: "unsubmitted",
2552
+ stage,
2553
+ retry,
2554
+ reason,
2555
+ ...delayMs === void 0 ? {} : { retryHint: Object.freeze({ delayMs }) }
2556
+ });
2557
+ }
2558
+ function stoppedPreflight(error) {
2559
+ return unsubmitted(allowedErrorCode(error, ["deadline"]) ? "pre_handoff_timeout" : "worker_stopped");
2560
+ }
2561
+ async function resolveAttachments(config, { snapshot }, budget, slot) {
2562
+ const attachments = [];
2563
+ if (!snapshot.attachments.length) return { attachments: Object.freeze(attachments) };
2564
+ const stage = createChildBudget(config.clock, budget, config.limits.attachmentTimeoutMs);
2565
+ const context = Object.freeze({ scope: config.scope, signal: stage.signal });
2566
+ try {
2567
+ for (const ref of snapshot.attachments) {
2568
+ stage.check();
2569
+ const resolve = config.resolvers.get(ref.resolverKey);
2570
+ if (!resolve) return { result: unsubmitted("attachment_invalid") };
2571
+ const bytes = await runHostCallback(
2572
+ stage,
2573
+ slot,
2574
+ "preparation_failed",
2575
+ () => resolve(ref, context),
2576
+ (value) => {
2577
+ const raw = readRecord(value, ["status"], ["bytes"], "invalid_snapshot");
2578
+ if (raw.status === "unavailable" && !Object.hasOwn(raw, "bytes")) return null;
2579
+ if (raw.status !== "found") invalid("invalid_snapshot");
2580
+ return copyAttachmentBytes(ref, raw.bytes);
2581
+ }
2582
+ );
2583
+ if (!bytes) return { result: unsubmitted("attachment_unavailable") };
2584
+ attachments.push(Object.freeze({ ref, bytes }));
2585
+ }
2586
+ return { attachments: Object.freeze(attachments) };
2587
+ } catch (error) {
2588
+ budget.check();
2589
+ const code = allowedErrorCode(error, ["deadline", "invalid_snapshot"]);
2590
+ return {
2591
+ result: unsubmitted(
2592
+ code === "deadline" ? "attachment_timeout" : code === "invalid_snapshot" ? "attachment_invalid" : "attachment_resolver_error"
2593
+ )
2594
+ };
2595
+ } finally {
2596
+ stage.close();
2597
+ }
2598
+ }
2599
+ async function ratePermission(config, { snapshot }, budget, slot) {
2600
+ if (!config.limiter) return;
2601
+ const { tryAcquire } = config.limiter;
2602
+ const stage = createChildBudget(config.clock, budget, config.limits.rateTimeoutMs);
2603
+ try {
2604
+ const retryAfter = await runHostCallback(
2605
+ stage,
2606
+ slot,
2607
+ "preparation_failed",
2608
+ () => tryAcquire(Object.freeze({ scope: config.scope, provider: snapshot.provider, signal: stage.signal })),
2609
+ (value) => {
2610
+ const raw = readRecord(value, ["status"], ["retryAfterMs"], "invalid_config");
2611
+ if (raw.status === "granted" && !Object.hasOwn(raw, "retryAfterMs")) return void 0;
2612
+ if (raw.status !== "deferred") invalid("invalid_config");
2613
+ return integer(raw.retryAfterMs, 1, MAX_RATE_DEFERRAL_MS, "invalid_config");
2614
+ }
2615
+ );
2616
+ return retryAfter === void 0 ? void 0 : unsubmitted("rate_deferred", retryAfter);
2617
+ } catch (error) {
2618
+ budget.check();
2619
+ return unsubmitted(allowedErrorCode(error, ["deadline"]) ? "rate_timeout" : "rate_error");
2620
+ } finally {
2621
+ stage.close();
2622
+ }
2623
+ }
2624
+ async function prepareAttempt(config, claim, budget, slot) {
2625
+ const { snapshot, fence } = claim;
2626
+ try {
2627
+ budget.check();
2628
+ const profile = config.profiles.get(snapshot.provider.key);
2629
+ if (!profile || !sameProvider(profile.ref, snapshot.provider))
2630
+ return { result: unsubmitted("profile_unavailable") };
2631
+ const resolved = await resolveAttachments(config, claim, budget, slot);
2632
+ if ("result" in resolved) return resolved;
2633
+ let submit;
2634
+ try {
2635
+ const prepared = runSyncCallback(
2636
+ budget,
2637
+ slot,
2638
+ "preparation_failed",
2639
+ () => profile.prepare(
2640
+ Object.freeze({
2641
+ jobId: fence.jobId,
2642
+ attemptId: fence.attemptId,
2643
+ snapshot,
2644
+ attachments: resolved.attachments
2645
+ })
2646
+ )
2647
+ );
2648
+ if (readPortMember(prepared, "then") !== void 0) invalid("preparation_failed");
2649
+ submit = bindMethod(prepared, "submit");
2650
+ } catch {
2651
+ budget.check();
2652
+ return { result: unsubmitted("provider_preflight_error") };
2653
+ }
2654
+ const deferred = await ratePermission(config, claim, budget, slot);
2655
+ if (deferred) return { result: deferred };
2656
+ budget.check();
2657
+ return { submit };
2658
+ } catch (error) {
2659
+ return { result: stoppedPreflight(error) };
2660
+ }
2661
+ }
2662
+
2663
+ // src/internal/worker-attempt.ts
2664
+ var AttemptOwner = class {
2665
+ constructor(run, claim, times) {
2666
+ this.run = run;
2667
+ this.claim = claim;
2668
+ this.lease = { ...times, grant: claim.lease };
2669
+ }
2670
+ run;
2671
+ claim;
2672
+ lease;
2673
+ handoff;
2674
+ #lost = new AbortController();
2675
+ get lost() {
2676
+ return this.#lost.signal;
2677
+ }
2678
+ checkLease() {
2679
+ if (this.lost.aborted || monotonicNow(this.run.config.clock) >= safeLeaseEnd(this.lease)) {
2680
+ this.#lost.abort();
2681
+ invalid("aborted");
2682
+ }
2683
+ }
2684
+ async renewWhile(budget, stopped) {
2685
+ const { clock, limits } = this.run.config;
2686
+ const cadence = Math.floor(limits.leaseMs / 3);
2687
+ const waitSignal = AbortSignal.any([stopped, this.run.noLaunch]);
2688
+ while (!waitSignal.aborted) {
2689
+ try {
2690
+ budget.check();
2691
+ const due = this.lease.dispatchedAt + cadence;
2692
+ if (due >= budget.deadline) return;
2693
+ if (monotonicNow(clock) < due) {
2694
+ const wait = createChildBudgetUntil(clock, budget, due, waitSignal);
2695
+ try {
2696
+ await waitForAbort(wait.signal);
2697
+ if (allowedErrorCode(wait.signal.reason, ["invalid_config"])) invalid("invalid_config");
2698
+ } finally {
2699
+ wait.close();
2700
+ }
2701
+ }
2702
+ if (waitSignal.aborted) return;
2703
+ budget.check();
2704
+ this.checkLease();
2705
+ const grant = await this.#ownerWrite(budget, this.run.config.store.renew, readRenewed);
2706
+ if (!grant) return;
2707
+ this.lease = grant;
2708
+ } catch (error) {
2709
+ if (allowedErrorCode(error, ["invalid_config"])) this.#lost.abort();
2710
+ return;
2711
+ }
2712
+ }
2713
+ }
2714
+ async mark(budget) {
2715
+ const grant = await this.#ownerWrite(budget, this.run.config.store.markHandoff, readHandoff, () => {
2716
+ this.handoff = "unconfirmed";
2717
+ });
2718
+ this.handoff = grant ?? void 0;
2719
+ return grant;
2720
+ }
2721
+ async #ownerWrite(budget, invoke, read, onDispatch) {
2722
+ const {
2723
+ clock,
2724
+ scope,
2725
+ limits: { leaseMs }
2726
+ } = this.run.config;
2727
+ const { claim, lease } = this;
2728
+ const { fence } = claim;
2729
+ let dispatchedAt;
2730
+ try {
2731
+ const grant = await this.run.callStore(budget, {
2732
+ effect: "mutation",
2733
+ authorize: true,
2734
+ deadline: safeLeaseEnd(lease),
2735
+ beforeInvoke: () => this.checkLease(),
2736
+ invoke: (call, start) => {
2737
+ dispatchedAt = start;
2738
+ onDispatch?.();
2739
+ return invoke(scope, fence, leaseMs, call);
2740
+ },
2741
+ accept: (value) => {
2742
+ if (value === null) return null;
2743
+ const times = { dispatchedAt, confirmedAt: monotonicNow(clock) };
2744
+ return Object.freeze({ ...times, grant: read(value, lease, claim, leaseMs, times) });
2745
+ }
2746
+ });
2747
+ if (!grant) this.#lost.abort();
2748
+ return grant;
2749
+ } catch (error) {
2750
+ if (dispatchedAt !== void 0) this.#lost.abort();
2751
+ throw error;
2752
+ }
2753
+ }
2754
+ };
2755
+ async function launch(run, owner, mark, submit, preflight) {
2756
+ const { clock, limits } = run.config;
2757
+ const { provider, envelope, expiresAt } = owner.claim.snapshot;
2758
+ const { attemptId } = owner.claim.fence;
2759
+ const launchEnd = Math.min(
2760
+ preflight.deadline,
2761
+ mark.dispatchedAt + (expiresAt - mark.grant.handoffAt) - CLOCK_MARGIN_MS
2762
+ );
2763
+ const stage = provider.kind === "smtp" ? "data" : "http";
2764
+ const unknown = (reason) => Object.freeze({ outcome: "unknown", retry: "never", stage, reason });
2765
+ let io;
2766
+ try {
2767
+ run.checkLaunch();
2768
+ preflight.check();
2769
+ const now = monotonicNow(clock);
2770
+ if (now >= launchEnd) return;
2771
+ io = createChildBudgetUntil(
2772
+ clock,
2773
+ run.budget,
2774
+ Math.min(now + limits.providerTimeoutMs, safeLeaseEnd(mark) - limits.finalizeGraceMs)
2775
+ );
2776
+ run.checkLaunch();
2777
+ io.check();
2778
+ const before = monotonicNow(clock);
2779
+ const timeoutMs = Math.floor(io.deadline - before);
2780
+ if (before >= launchEnd || timeoutMs < 1 || io.signal.aborted || preflight.signal.aborted || run.noLaunch.aborted)
2781
+ return;
2782
+ try {
2783
+ const returned = submit(Object.freeze({ signal: io.signal, timeoutMs }));
2784
+ const pending = pendingCallback(returned);
2785
+ if (!pending) return unknown("transport_uncertain");
2786
+ const raw = await pending;
2787
+ if (!import_node_util8.types.isPromise(returned)) return unknown("transport_uncertain");
2788
+ let result;
2789
+ try {
2790
+ result = readProviderResult(raw, provider, attemptId, envelope);
2791
+ } catch {
2792
+ return unknown("transport_uncertain");
2793
+ }
2794
+ try {
2795
+ io.check();
2796
+ } catch (error) {
2797
+ const code = allowedErrorCode(error, ["deadline", "aborted"]);
2798
+ return unknown(
2799
+ code === "deadline" ? "provider_timeout" : code === "aborted" ? "provider_aborted" : "transport_uncertain"
2800
+ );
2801
+ }
2802
+ return result;
2803
+ } catch {
2804
+ return unknown("transport_uncertain");
2805
+ }
2806
+ } catch {
2807
+ return;
2808
+ } finally {
2809
+ io?.close();
2810
+ }
2811
+ }
2812
+ async function processOwned(owner, slot) {
2813
+ const { run, claim, lease } = owner;
2814
+ const { clock, limits } = run.config;
2815
+ const deadline = lease.dispatchedAt + limits.preHandoffTimeoutMs;
2816
+ let budget;
2817
+ try {
2818
+ budget = createChildBudgetUntil(clock, run.budget, deadline);
2819
+ const host = createChildBudgetUntil(clock, budget, deadline, AbortSignal.any([run.noLaunch, owner.lost]));
2820
+ const stopRenewal = new AbortController();
2821
+ const renewal = owner.renewWhile(budget, stopRenewal.signal);
2822
+ let preflight;
2823
+ try {
2824
+ preflight = await prepareAttempt(
2825
+ run.config,
2826
+ claim,
2827
+ {
2828
+ ...host,
2829
+ check() {
2830
+ host.check();
2831
+ owner.checkLease();
2832
+ }
2833
+ },
2834
+ slot
2835
+ );
2836
+ } finally {
2837
+ stopRenewal.abort();
2838
+ host.close();
2839
+ await renewal;
2840
+ }
2841
+ if ("result" in preflight) return { result: preflight.result, providerInvoked: false };
2842
+ const mark = await owner.mark(budget);
2843
+ if (mark) {
2844
+ const result = await launch(run, owner, mark, preflight.submit, budget);
2845
+ return {
2846
+ result: result ?? unsubmitted("launch_window_closed"),
2847
+ providerInvoked: result !== void 0
2848
+ };
2849
+ }
2850
+ } catch (error) {
2851
+ return { result: stoppedPreflight(error), providerInvoked: false };
2852
+ } finally {
2853
+ budget?.close();
2854
+ }
2855
+ return { providerInvoked: false };
2856
+ }
2857
+ async function processClaim(run, claim, times, slot) {
2858
+ const owner = new AttemptOwner(run, claim, times);
2859
+ const { result, providerInvoked } = await processOwned(owner, slot);
2860
+ const commit = await finishAttempt(run, owner, providerInvoked, owner.lost.aborted ? void 0 : result);
2861
+ return Object.freeze({
2862
+ operation: "claim",
2863
+ jobId: claim.fence.jobId,
2864
+ attemptId: claim.fence.attemptId,
2865
+ providerInvoked,
2866
+ ...commit ? { status: commit.disposition, reason: commit.reason } : { status: "unconfirmed" }
2867
+ });
2868
+ }
2869
+
2870
+ // src/internal/worker-run.ts
2871
+ var WorkerRun = class {
2872
+ constructor(config, budget) {
2873
+ this.config = config;
2874
+ this.budget = budget;
2875
+ }
2876
+ config;
2877
+ budget;
2878
+ #noLaunch = new AbortController();
2879
+ #persistenceFailures = 0;
2880
+ get noLaunch() {
2881
+ return this.#noLaunch.signal;
2882
+ }
2883
+ get persistenceFailures() {
2884
+ return this.#persistenceFailures;
2885
+ }
2886
+ canLaunch() {
2887
+ return this.budget.remainingMs() >= 1 && !this.noLaunch.aborted;
2888
+ }
2889
+ checkLaunch() {
2890
+ this.budget.check();
2891
+ if (this.noLaunch.aborted) invalid("aborted");
2892
+ }
2893
+ callStore(budget, operation) {
2894
+ const { clock, limits } = this.config;
2895
+ let invoked = false;
2896
+ return runStoreCall(clock, budget, {
2897
+ ...operation,
2898
+ maxMs: Math.min(operation.maxMs ?? limits.storeTimeoutMs, limits.storeTimeoutMs),
2899
+ beforeInvoke: () => {
2900
+ if (operation.authorize) this.checkLaunch();
2901
+ operation.beforeInvoke?.();
2902
+ },
2903
+ invoke: (call, dispatchedAt) => {
2904
+ invoked = true;
2905
+ return operation.invoke(call, dispatchedAt);
2906
+ },
2907
+ onError: () => {
2908
+ if (!invoked) return;
2909
+ this.#persistenceFailures++;
2910
+ this.#noLaunch.abort();
2911
+ }
2912
+ });
2913
+ }
2914
+ };
2915
+ var statuses = {
2916
+ retry_scheduled: "retryScheduled",
2917
+ accepted: "accepted",
2918
+ partially_accepted: "partiallyAccepted",
2919
+ validated: "validated",
2920
+ rejected: "rejected",
2921
+ unknown: "unknown",
2922
+ failed: "failed",
2923
+ expired: "expired",
2924
+ cancelled: "cancelled",
2925
+ unconfirmed: "unconfirmed"
2926
+ };
2927
+ function runReport(stop, items, persistenceFailures) {
2928
+ const counts = {
2929
+ claimed: 0,
2930
+ recovered: 0,
2931
+ expiredInSweep: 0,
2932
+ providerCalls: 0,
2933
+ submitted: 0,
2934
+ retryScheduled: 0,
2935
+ accepted: 0,
2936
+ partiallyAccepted: 0,
2937
+ validated: 0,
2938
+ rejected: 0,
2939
+ unknown: 0,
2940
+ failed: 0,
2941
+ expired: 0,
2942
+ cancelled: 0,
2943
+ unconfirmed: 0,
2944
+ persistenceFailures
2945
+ };
2946
+ for (const item of items) {
2947
+ if (item.operation === "claim") counts.claimed++;
2948
+ else if (item.operation === "recover") counts.recovered++;
2949
+ else counts.expiredInSweep++;
2950
+ counts[statuses[item.status]]++;
2951
+ if (item.providerInvoked) counts.providerCalls++;
2952
+ }
2953
+ counts.submitted = counts.accepted + counts.partiallyAccepted;
2954
+ return Object.freeze({ stop, items: Object.freeze(items), counts: Object.freeze(counts) });
2955
+ }
2956
+
2957
+ // src/worker.ts
2958
+ async function sweep(run, limit, items, invoke, read, entry) {
2959
+ for (let i = 0; i < limit && run.canLaunch(); i++) {
2960
+ try {
2961
+ const next = await run.callStore(run.budget, {
2962
+ effect: "mutation",
2963
+ authorize: true,
2964
+ invoke,
2965
+ accept: (value) => readStoreNext(value, read)
2966
+ });
2967
+ if (next.status !== "applied") return next.status === "contended";
2968
+ items.push(Object.freeze(entry(next.value)));
2969
+ } catch {
2970
+ break;
2971
+ }
2972
+ }
2973
+ return false;
2974
+ }
2975
+ function claimNext(run) {
2976
+ const { clock, scope, store, limits } = run.config;
2977
+ const request = Object.freeze({
2978
+ attemptId: (0, import_node_crypto4.randomUUID)(),
2979
+ token: (0, import_node_crypto4.randomBytes)(16).toString("base64url"),
2980
+ leaseMs: limits.leaseMs
2981
+ });
2982
+ let dispatchedAt;
2983
+ return run.callStore(run.budget, {
2984
+ effect: "mutation",
2985
+ authorize: true,
2986
+ maxMs: limits.preHandoffTimeoutMs,
2987
+ invoke(call, start) {
2988
+ dispatchedAt = start;
2989
+ return store.claimNext(scope, request, call);
2990
+ },
2991
+ accept: (value) => readStoreNext(value, (raw) => {
2992
+ const claim = readClaimed(raw, scope, request);
2993
+ return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
2994
+ })
2995
+ });
2996
+ }
2997
+ async function drainClaims(run, options, items, slots) {
2998
+ const tasks = [];
2999
+ let active = 0;
3000
+ let settled;
3001
+ let failed = false;
3002
+ let stop = "idle";
3003
+ try {
3004
+ while (run.canLaunch() && !failed) {
3005
+ if (tasks.length === options.limit) {
3006
+ stop = "limit";
3007
+ break;
3008
+ }
3009
+ if (active === options.concurrency || slots.size >= run.config.limits.maxConcurrency) {
3010
+ if (!active) {
3011
+ stop = "callback_capacity";
3012
+ break;
3013
+ }
3014
+ await new Promise((resolve) => {
3015
+ settled = resolve;
3016
+ });
3017
+ continue;
3018
+ }
3019
+ const slot = new CallbackSlot(() => slots.delete(slot));
3020
+ slots.add(slot);
3021
+ let next;
3022
+ try {
3023
+ next = await claimNext(run);
3024
+ } catch {
3025
+ slot.close();
3026
+ break;
3027
+ }
3028
+ if (next.status !== "applied") {
3029
+ slot.close();
3030
+ stop = next.status === "contended" ? "contended" : "idle";
3031
+ break;
3032
+ }
3033
+ const { claim } = next.value;
3034
+ const index = items.length;
3035
+ items.push(
3036
+ Object.freeze({
3037
+ operation: "claim",
3038
+ jobId: claim.fence.jobId,
3039
+ attemptId: claim.fence.attemptId,
3040
+ providerInvoked: false,
3041
+ status: "unconfirmed"
3042
+ })
3043
+ );
3044
+ active++;
3045
+ tasks.push(
3046
+ processClaim(run, claim, next.value, slot).then(
3047
+ (entry) => {
3048
+ items[index] = entry;
3049
+ },
3050
+ () => {
3051
+ failed = true;
3052
+ }
3053
+ ).finally(() => {
3054
+ slot.close();
3055
+ active--;
3056
+ const wake = settled;
3057
+ settled = void 0;
3058
+ wake?.();
3059
+ })
3060
+ );
3061
+ }
3062
+ } finally {
3063
+ await Promise.all(tasks);
3064
+ }
3065
+ if (failed) invalid("invalid_config");
3066
+ return stop;
3067
+ }
3068
+ async function runQueue(run, options, slots, shutdown) {
3069
+ const items = [];
3070
+ const { scope, store } = run.config;
3071
+ const contended = await sweep(
3072
+ run,
3073
+ options.maintenanceLimit,
3074
+ items,
3075
+ (call) => store.recoverNext(scope, call),
3076
+ readRecovery,
3077
+ (commit) => ({
3078
+ operation: "recover",
3079
+ jobId: commit.jobId,
3080
+ attemptId: commit.attemptId,
3081
+ status: commit.disposition,
3082
+ reason: commit.reason,
3083
+ providerInvoked: false
3084
+ })
3085
+ ) || await sweep(
3086
+ run,
3087
+ options.maintenanceLimit,
3088
+ items,
3089
+ (call) => store.expireNext(scope, call),
3090
+ (value) => readQueuedExpiry(value, scope),
3091
+ (job) => ({
3092
+ operation: "expire",
3093
+ jobId: job.jobId,
3094
+ status: "expired",
3095
+ reason: "expired",
3096
+ providerInvoked: false
3097
+ })
3098
+ );
3099
+ const queueStop = contended ? "contended" : await drainClaims(run, options, items, slots);
3100
+ const timeLeft = run.budget.remainingMs();
3101
+ let stop;
3102
+ if (shutdown.aborted) stop = "shutdown";
3103
+ else if (options.signal?.aborted) stop = "aborted";
3104
+ else if (allowedErrorCode(run.budget.signal.reason, ["deadline"])) stop = "deadline";
3105
+ else if (run.persistenceFailures) stop = "store_error";
3106
+ else if (run.budget.signal.aborted) return invalid("invalid_config");
3107
+ else if (queueStop !== "contended" && slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
3108
+ else if (queueStop === "idle" && timeLeft < 1)
3109
+ stop = "deadline";
3110
+ else stop = queueStop;
3111
+ return runReport(stop, items, run.persistenceFailures);
3112
+ }
3113
+ function createEmailWorker(options) {
3114
+ const config = readWorkerConfig(options);
3115
+ const { clock, scope, limits } = config;
3116
+ const shutdown = new AbortController();
3117
+ const slots = /* @__PURE__ */ new Set();
3118
+ let active;
3119
+ const worker = {
3120
+ scope,
3121
+ async run(options2 = {}) {
3122
+ if (shutdown.signal.aborted) invalid("closed");
3123
+ if (active) invalid("busy");
3124
+ const settings = readRunOptions(options2, limits);
3125
+ const done = new AbortController();
3126
+ active = done;
3127
+ try {
3128
+ const signal = settings.signal ? AbortSignal.any([settings.signal, shutdown.signal]) : shutdown.signal;
3129
+ const budget = createBudget(clock, settings.timeoutMs, signal);
3130
+ try {
3131
+ return await runQueue(new WorkerRun(config, budget), settings, slots, shutdown.signal);
3132
+ } finally {
3133
+ budget.close();
3134
+ }
3135
+ } finally {
3136
+ active = void 0;
3137
+ done.abort();
3138
+ }
3139
+ },
3140
+ async shutdown(options2 = {}) {
3141
+ const { timeoutMs } = readShutdownOptions(options2);
3142
+ const done = active;
3143
+ let end;
3144
+ try {
3145
+ if (done) end = monotonicNow(clock) + timeoutMs;
3146
+ } finally {
3147
+ shutdown.abort();
3148
+ }
3149
+ if (done && end !== void 0) {
3150
+ const wait = createBudgetUntil(clock, end, done.signal);
3151
+ try {
3152
+ await waitForAbort(wait.signal);
3153
+ } finally {
3154
+ wait.close();
3155
+ }
3156
+ }
3157
+ return Object.freeze({
3158
+ status: active ? "deadline" : "stopped",
3159
+ activeRun: active !== void 0,
3160
+ pendingCallbacks: [...slots].reduce((sum, slot) => sum + slot.pending, 0)
3161
+ });
3162
+ }
3163
+ };
3164
+ return Object.freeze(worker);
3165
+ }
3166
+
3167
+ // src/batch.ts
3168
+ var import_node_util9 = require("util");
3169
+ var STOP_ERRORS2 = ["aborted", "deadline"];
3170
+ var ADMISSION_ERRORS = [
3171
+ ...STOP_ERRORS2,
3172
+ ...STORE_PERSISTENCE_ERRORS,
3173
+ "invalid_config",
3174
+ "invalid_command",
3175
+ "invalid_input",
3176
+ "invalid_data",
3177
+ "invalid_snapshot",
3178
+ "preparation_failed",
3179
+ "template_not_found",
3180
+ "template_source",
3181
+ "template_render",
3182
+ "provider_mismatch",
3183
+ "expired",
3184
+ "idempotency_conflict",
3185
+ "busy",
3186
+ "closed"
3187
+ ];
3188
+ function boundScope(port) {
3189
+ return scopeToken(readPortMember(port, "scope"), "invalid_config");
3190
+ }
3191
+ function readBatch(scope, input) {
3192
+ const code = "invalid_command";
3193
+ const raw = readRecord(input, ["batchId", "items"], [], code);
3194
+ const batchId = identifier(raw.batchId, code);
3195
+ const seen = /* @__PURE__ */ new Set();
3196
+ const items = readArray(raw.items, MAX_BATCH_ITEMS, code, (entry) => {
3197
+ const item = readRecord(entry, ["itemId", "command"], [], code);
3198
+ const itemId = identifier(item.itemId, code);
3199
+ if (seen.has(itemId)) invalid(code);
3200
+ seen.add(itemId);
3201
+ const command = readRecord(item.command, ["templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
3202
+ return { itemId, parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }) };
3203
+ });
3204
+ if (!items.length) invalid(code);
3205
+ return { batchId, items };
3206
+ }
3207
+ function stopReason(budget) {
3208
+ if (budget.remainingMs() > 0) return;
3209
+ return allowedErrorCode(budget.signal.reason, STOP_ERRORS2) ?? invalid("invalid_config");
3210
+ }
3211
+ function readAdmissionResult(input, identity) {
3212
+ const code = "write_unconfirmed";
3213
+ const { status, job: raw } = readRecord(input, ["status", "job"], [], code);
3214
+ if (status !== "enqueued" && status !== "replayed") invalid(code);
3215
+ const job = readJobSummary(identity.scope, raw);
3216
+ if (!matchesAdmissionJob(job, identity, status)) invalid(code);
3217
+ return { status, job };
3218
+ }
3219
+ function createEmailBatchService(options) {
3220
+ return createEmailBatchServiceWithClock(options, systemEmailClock);
3221
+ }
3222
+ function createEmailBatchServiceWithClock(options, clock) {
3223
+ const { service, worker } = readRecord(options, ["service", "worker"], [], "invalid_config");
3224
+ const scope = boundScope(service);
3225
+ if (scope !== boundScope(worker)) invalid("invalid_config");
3226
+ const run = bindMethod(worker, "run");
3227
+ const enqueue = bindMethod(service, "enqueue");
3228
+ const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
3229
+ if (boundScope(service) !== scope) invalid("invalid_config");
3230
+ const bounds = CALL_BUDGETS.admissionOrAdmin;
3231
+ const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
3232
+ budget.check();
3233
+ let raw;
3234
+ try {
3235
+ const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
3236
+ raw = import_node_util9.types.isPromise(pending) ? await pending : pending;
3237
+ } catch (error) {
3238
+ if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
3239
+ invalid("deadline");
3240
+ }
3241
+ throw error;
3242
+ }
3243
+ try {
3244
+ return readAdmissionResult(raw, identity);
3245
+ } catch {
3246
+ return invalid("write_unconfirmed");
3247
+ }
3248
+ });
3249
+ const batch = {
3250
+ async enqueueBatch(input, call = {}) {
3251
+ const { signal, timeoutMs } = readCallOptions(call, CALL_BUDGETS.batchOrRun);
3252
+ const budget = createBudget(clock, timeoutMs, signal);
3253
+ try {
3254
+ const { batchId, items: commands } = readBatch(scope, input);
3255
+ const items = [];
3256
+ const counts = { enqueued: 0, replayed: 0, failed: 0, notStarted: 0, persistenceFailures: 0 };
3257
+ for (const { itemId, parsed } of commands) {
3258
+ if (stopReason(budget)) {
3259
+ counts.notStarted++;
3260
+ items.push(Object.freeze({ itemId, status: "not_started" }));
3261
+ continue;
3262
+ }
3263
+ try {
3264
+ const result = await admit(parsed, budget);
3265
+ counts[result.status]++;
3266
+ items.push(Object.freeze({ itemId, status: result.status, job: result.job }));
3267
+ } catch (error) {
3268
+ const code = allowedErrorCode(error, ADMISSION_ERRORS) ?? "write_unconfirmed";
3269
+ counts.failed++;
3270
+ if (STORE_PERSISTENCE_ERRORS.some((candidate) => candidate === code)) counts.persistenceFailures++;
3271
+ items.push(Object.freeze({ itemId, status: "failed", code }));
3272
+ }
3273
+ }
3274
+ return Object.freeze({ batchId, items: Object.freeze(items), counts: Object.freeze(counts) });
3275
+ } finally {
3276
+ budget.close();
3277
+ }
3278
+ },
3279
+ async run(options2) {
3280
+ if (boundScope(worker) !== scope) invalid("invalid_config");
3281
+ return run(options2);
3282
+ }
3283
+ };
3284
+ return Object.freeze(batch);
3285
+ }
3286
+
3287
+ // src/admin.ts
3288
+ var CONFIG3 = "invalid_config";
3289
+ var STORED4 = "store_incompatible";
3290
+ var STOP_CODES = ["aborted", "deadline", CONFIG3];
3291
+ var RESOLUTION_REJECTIONS = ["not_found", "resolution_conflict", "expired"];
3292
+ var CLEANUP_COUNTERS = {
3293
+ payload_pruned: "payloadsPruned",
3294
+ retirement_started: "retirementsStarted",
3295
+ purged: "jobsPurged"
3296
+ };
3297
+ function createEmailAdmin(options) {
3298
+ return createEmailAdminWithClock(options, systemEmailClock);
3299
+ }
3300
+ function createEmailAdminWithClock(options, clock) {
3301
+ const { scope: input, store, onActivity: callback } = readRecord(options, ["scope", "store"], ["onActivity"], CONFIG3);
3302
+ const scope = scopeToken(input, CONFIG3);
3303
+ const findJob = bindMethod(store, "findJob");
3304
+ const cancel = bindMethod(store, "cancel");
3305
+ const resolveUnknown = bindMethod(store, "resolveUnknown");
3306
+ const listActivities = bindMethod(store, "listActivities");
3307
+ const reserve = bindMethod(store, "reserveProjection");
3308
+ const put = bindMethod(store, "putActivity");
3309
+ const ack = bindMethod(store, "ackProjection");
3310
+ const cleanupNext = bindMethod(store, "cleanupNext");
3311
+ const onActivity = callback === void 0 ? void 0 : requireCallback(callback);
3312
+ let observers = 0;
3313
+ function observe(activity, counts) {
3314
+ if (!onActivity) return;
3315
+ if (observers >= MAX_OBSERVER_PENDING) {
3316
+ counts.observerSkipped++;
3317
+ return;
3318
+ }
3319
+ observers++;
3320
+ counts.observerStarted++;
3321
+ const slot = new CallbackSlot(() => observers--);
3322
+ try {
3323
+ const pending = pendingCallback(onActivity(activity));
3324
+ if (pending) slot.hold(pending);
3325
+ } catch {
3326
+ } finally {
3327
+ slot.close();
3328
+ }
3329
+ }
3330
+ function readJob(jobId, value) {
3331
+ const job = readJobSummary(scope, value);
3332
+ if (job.jobId !== jobId) invalid(STORED4);
3333
+ return job;
3334
+ }
3335
+ function callStore(budget, operation) {
3336
+ return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS });
3337
+ }
3338
+ function write(budget, invoke, accept) {
3339
+ return callStore(budget, { effect: "mutation", invoke, accept });
3340
+ }
3341
+ async function inOperation(options2, run) {
3342
+ const { timeoutMs, signal: source } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
3343
+ const signal = source && AbortSignal.any([source]);
3344
+ const budget = createBudget(clock, timeoutMs, signal);
3345
+ try {
3346
+ return await run(budget, signal);
3347
+ } finally {
3348
+ budget.close();
3349
+ }
3350
+ }
3351
+ async function maintain(options2, step) {
3352
+ const { limit: input2, ...call } = readRecord(options2, [], ["limit", "signal", "timeoutMs"], CONFIG3);
3353
+ const limit = boundedOption(input2, ADMIN_MAINTENANCE_LIMIT);
3354
+ return inOperation(call, async (budget, signal) => {
3355
+ let stop = "limit";
3356
+ for (let i = 0; i < limit; i++) {
3357
+ try {
3358
+ const next = await step(budget);
3359
+ if (!next) continue;
3360
+ stop = next;
3361
+ } catch (error) {
3362
+ const code = allowedErrorCode(error, STOP_CODES);
3363
+ if (code === CONFIG3) invalid(code);
3364
+ stop = code ?? "store_error";
3365
+ }
3366
+ break;
3367
+ }
3368
+ const persistenceFailures = Number(stop === "store_error");
3369
+ budget.remainingMs();
3370
+ const interrupted = allowedErrorCode(budget.signal.reason, STOP_CODES);
3371
+ if (interrupted === CONFIG3) invalid(interrupted);
3372
+ if (signal?.aborted) stop = "aborted";
3373
+ else if (interrupted) stop = interrupted;
3374
+ return { stop, persistenceFailures };
3375
+ });
3376
+ }
3377
+ const admin = {
3378
+ scope,
3379
+ getJob(jobId, options2 = {}) {
3380
+ return inOperation(options2, (budget) => {
3381
+ const id = readStoreId(jobId);
3382
+ return callStore(budget, {
3383
+ effect: "read",
3384
+ invoke: (call) => findJob(scope, id, call),
3385
+ accept: (value) => value === null ? null : readJob(id, value)
3386
+ });
3387
+ });
3388
+ },
3389
+ cancel(jobId, options2 = {}) {
3390
+ return inOperation(options2, (budget) => {
3391
+ const id = readStoreId(jobId);
3392
+ return write(
3393
+ budget,
3394
+ (call) => cancel(scope, id, call),
3395
+ (value) => {
3396
+ const raw = readRecord(value, ["status"], ["job"], STORED4);
3397
+ const { status } = raw;
3398
+ if (status === "not_found" && !Object.hasOwn(raw, "job")) return Object.freeze({ status });
3399
+ if (status !== "cancelled" && status !== "too_late") invalid(STORED4);
3400
+ const job = readJob(id, raw.job);
3401
+ if (status === "cancelled" !== (job.state === "terminal" && job.disposition === "cancelled")) {
3402
+ invalid(STORED4);
3403
+ }
3404
+ return Object.freeze({ status, job });
3405
+ }
3406
+ );
3407
+ });
3408
+ },
3409
+ resolveUnknown(command, options2 = {}) {
3410
+ return inOperation(options2, (budget) => {
3411
+ const request = readResolution(command);
3412
+ return callStore(budget, {
3413
+ effect: "mutation",
3414
+ definite: RESOLUTION_REJECTIONS,
3415
+ invoke: (call) => resolveUnknown(scope, request, call),
3416
+ accept(value) {
3417
+ const { status, job: raw } = readRecord(value, ["status", "job"], [], STORED4);
3418
+ const job = readJob(request.jobId, raw);
3419
+ const decision = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
3420
+ if (decision?.action !== request.action || status !== "resolved" && status !== "replayed") {
3421
+ invalid(STORED4);
3422
+ }
3423
+ if (status === "resolved" && (job.unknownOpen || job.latestAttempt?.attemptId !== request.attemptId || job.latestAttempt.outcome !== "unknown" || job.updatedAt !== decision.at || (decision.action === "redrive" ? job.state !== "queued" || job.nextAt !== decision.at : job.state !== "terminal" || job.disposition !== "unknown"))) {
3424
+ invalid(STORED4);
3425
+ }
3426
+ return Object.freeze({ status, job });
3427
+ }
3428
+ });
3429
+ });
3430
+ },
3431
+ listActivities(query = {}, options2 = {}) {
3432
+ return inOperation(options2, (budget) => {
3433
+ const criteria = readActivityCriteria(scope, query);
3434
+ const request = activityQuery(criteria);
3435
+ return callStore(budget, {
3436
+ effect: "read",
3437
+ invoke: (call) => listActivities(scope, request, call),
3438
+ accept: (value) => readActivityPage(criteria, value)
3439
+ });
3440
+ });
3441
+ },
3442
+ async reconcile(options2 = {}) {
3443
+ const counts = { reserved: 0, acknowledged: 0, permitsExpired: 0, observerStarted: 0, observerSkipped: 0 };
3444
+ const report = await maintain(options2, async (budget) => {
3445
+ const next = await write(
3446
+ budget,
3447
+ (call) => reserve(scope, call),
3448
+ (value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2))
3449
+ );
3450
+ if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
3451
+ counts.reserved++;
3452
+ const permit = next.value;
3453
+ const present = await write(
3454
+ budget,
3455
+ (call) => put(scope, permit, call),
3456
+ (value) => readStatus(value, ["present", "permit_expired"])
3457
+ );
3458
+ if (present === "permit_expired") {
3459
+ counts.permitsExpired++;
3460
+ return;
3461
+ }
3462
+ const confirmed = await write(
3463
+ budget,
3464
+ (call) => ack(scope, permit, call),
3465
+ (value) => readStatus(value, ["acknowledged", "already_acknowledged", "stale"])
3466
+ );
3467
+ if (confirmed === "stale") return "contended";
3468
+ counts.acknowledged++;
3469
+ if (confirmed === "acknowledged" && budget.remainingMs() > 0) observe(permit.activity, counts);
3470
+ });
3471
+ return Object.freeze({ ...report, ...counts });
3472
+ },
3473
+ async cleanup(options2 = {}) {
3474
+ const counts = { payloadsPruned: 0, retirementsStarted: 0, jobsPurged: 0 };
3475
+ const report = await maintain(options2, async (budget) => {
3476
+ const next = await write(
3477
+ budget,
3478
+ (call) => cleanupNext(scope, call),
3479
+ (value) => readStoreNext(value, (step) => readStatus(step, ["payload_pruned", "retirement_started", "purged"]))
3480
+ );
3481
+ if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
3482
+ counts[CLEANUP_COUNTERS[next.value]]++;
3483
+ });
3484
+ return Object.freeze({ ...report, ...counts });
3485
+ }
3486
+ };
3487
+ return Object.freeze(admin);
3488
+ }
3489
+ function readStatus(value, allowed) {
3490
+ return allowed.find((status) => status === value) ?? invalid(STORED4);
3491
+ }
3492
+
3493
+ // src/stores/memory.ts
3494
+ var import_node_crypto5 = require("crypto");
3495
+
3496
+ // src/internal/job-record.ts
3497
+ var STORED5 = "store_incompatible";
3498
+ function leasePhase(lease) {
3499
+ return lease.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
3500
+ }
3501
+ function terminalState(disposition, terminalReason, now) {
3502
+ return Object.freeze({
3503
+ state: "terminal",
3504
+ disposition,
3505
+ terminalReason,
3506
+ terminalAt: now,
3507
+ ...disposition === "unknown" ? {} : { settledAt: now }
3508
+ });
3509
+ }
3510
+ function hasRedrive(job) {
3511
+ return job.resolutions.some(({ action }) => action === "redrive");
3512
+ }
3513
+ function pendingAttempt(job) {
3514
+ return job.attempts.find(({ projectionAckAt }) => projectionAckAt === void 0);
3515
+ }
3516
+ function retirementAt(job) {
3517
+ if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
3518
+ const { settledAt } = job.state;
3519
+ const payload = timeAfter(settledAt, job.retention.payloadMs);
3520
+ const history = timeAfter(settledAt, job.retention.historyMs);
3521
+ const identity = timeAfter(settledAt, job.retention.idempotencyMs);
3522
+ const drain = job.projectionPermitUntil === void 0 ? 0 : timeAfter(job.projectionPermitUntil, PROJECTION_DRAIN_MS);
3523
+ if (payload === void 0 || history === void 0 || identity === void 0 || drain === void 0) return;
3524
+ return Math.max(payload, history, identity, drain);
3525
+ }
3526
+ function cleanupAt(job) {
3527
+ if (job.retiring) return job.updatedAt;
3528
+ if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
3529
+ if (job.snapshot) {
3530
+ const payloadAt = timeAfter(job.state.settledAt, job.retention.payloadMs);
3531
+ if (payloadAt === void 0) return;
3532
+ return Math.max(payloadAt, job.attempts.at(-1)?.projectionAckAt ?? 0);
3533
+ }
3534
+ const retireAt = retirementAt(job);
3535
+ return retireAt === void 0 ? void 0 : Math.max(retireAt, job.updatedAt);
3536
+ }
3537
+ function jobSelectors(job) {
3538
+ const { state } = job;
3539
+ const pendingAt = pendingAttempt(job)?.commit.finishedAt;
3540
+ const nextCleanupAt = cleanupAt(job);
3541
+ return {
3542
+ state: state.state,
3543
+ ...state.state === "queued" ? { nextAt: state.nextAt, queuedExpiresAt: job.expiresAt } : {},
3544
+ ...state.state === "leased" ? { leaseEndsAt: state.lease.leaseEndsAt } : {},
3545
+ ...pendingAt === void 0 ? {} : { pendingAt },
3546
+ ...nextCleanupAt === void 0 ? {} : { nextCleanupAt }
3547
+ };
3548
+ }
3549
+ function jobSummary(job) {
3550
+ const { state } = job;
3551
+ let summaryState;
3552
+ if (state.state === "terminal") {
3553
+ const { disposition, terminalReason, terminalAt } = state;
3554
+ summaryState = { state: "terminal", disposition, terminalReason, terminalAt };
3555
+ } else if (state.state === "leased") {
3556
+ summaryState = { state: "leased", phase: leasePhase(state.lease) };
3557
+ } else {
3558
+ summaryState = { state: "queued", nextAt: state.nextAt };
3559
+ }
3560
+ const latest = job.attempts.at(-1)?.commit;
3561
+ return Object.freeze({
3562
+ version: EMAIL_FORMAT_VERSION,
3563
+ scope: job.scope,
3564
+ jobId: job.jobId,
3565
+ key: Object.freeze({ ...job.key }),
3566
+ provider: Object.freeze({ ...job.provider }),
3567
+ template: Object.freeze({ ...job.template }),
3568
+ correlation: validateCorrelation(job.correlation, STORED5),
3569
+ scheduleAt: job.scheduleAt,
3570
+ createdAt: job.createdAt,
3571
+ updatedAt: job.updatedAt,
3572
+ expiresAt: job.expiresAt,
3573
+ priority: job.priority,
3574
+ attemptCount: job.attempts.length + Number(state.state === "leased"),
3575
+ ...latest ? {
3576
+ latestAttempt: Object.freeze({
3577
+ attemptId: latest.attemptId,
3578
+ outcome: latest.result.outcome,
3579
+ reason: latest.result.reason
3580
+ })
3581
+ } : {},
3582
+ unknownOpen: state.state === "terminal" && state.disposition === "unknown" && state.settledAt === void 0,
3583
+ resolutions: Object.freeze(job.resolutions.map((entry) => Object.freeze({ ...entry }))),
3584
+ ...summaryState
3585
+ });
3586
+ }
3587
+ function copyCommit(commit) {
3588
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5) });
3589
+ }
3590
+ function readStoredSnapshot(job, input) {
3591
+ let validated;
3592
+ try {
3593
+ validated = validateSnapshot(input);
3594
+ } catch {
3595
+ return invalid(STORED5);
3596
+ }
3597
+ const { snapshot, snapshotHash } = validated;
3598
+ const metadata = (value, counts) => canonicalJson([value.provider, value.template, value.correlation, counts], 4096, STORED5).encoded;
3599
+ 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)) {
3600
+ invalid(STORED5);
3601
+ }
3602
+ return snapshot;
3603
+ }
3604
+
3605
+ // src/internal/job-transitions.ts
3606
+ function guard(job, { now }, before) {
3607
+ if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
3608
+ invalid("store_unavailable");
3609
+ }
3610
+ return {
3611
+ scope: job.scope,
3612
+ jobId: job.jobId,
3613
+ revision: job.revision,
3614
+ state: job.state,
3615
+ ...job.retiring ? { retiring: true } : {},
3616
+ atOrAfter: now,
3617
+ ...before === void 0 ? {} : { before }
3618
+ };
3619
+ }
3620
+ function replace(job, time, patch, value, before, pendingAck) {
3621
+ const expect = guard(job, time, before);
3622
+ const next = Object.freeze({ ...patch, updatedAt: time.now, revision: time.revision });
3623
+ return {
3624
+ value: value(next),
3625
+ write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
3626
+ };
3627
+ }
3628
+ function newJob(admission, time) {
3629
+ const { command, jobId, retry, retention, admissionKey } = admission;
3630
+ const { scope, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
3631
+ const now = unixMs(time.now, "store_unavailable");
3632
+ if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
3633
+ const nextAt = Math.max(now, scheduleAt ?? now);
3634
+ if (nextAt >= snapshot.expiresAt) invalid("expired");
3635
+ return Object.freeze({
3636
+ version: EMAIL_FORMAT_VERSION,
3637
+ scope,
3638
+ jobId,
3639
+ key,
3640
+ admissionKey,
3641
+ fingerprint,
3642
+ snapshotHash,
3643
+ snapshot,
3644
+ retry,
3645
+ retention,
3646
+ provider: snapshot.provider,
3647
+ template: snapshot.template,
3648
+ correlation: snapshot.correlation,
3649
+ recipientCounts: recipientCounts(snapshot.envelope),
3650
+ scheduleAt,
3651
+ createdAt: now,
3652
+ updatedAt: now,
3653
+ expiresAt: snapshot.expiresAt,
3654
+ priority: snapshot.priority,
3655
+ revision: time.revision,
3656
+ state: Object.freeze({ state: "queued", nextAt }),
3657
+ attempts: Object.freeze([]),
3658
+ resolutions: Object.freeze([])
3659
+ });
3660
+ }
3661
+ function endOfGrant(now, leaseMs) {
3662
+ return timeAfter(now, leaseMs) ?? invalid("store_unavailable");
3663
+ }
3664
+ function withLease(job, lease) {
3665
+ return { ...job, state: Object.freeze({ state: "leased", lease: Object.freeze(lease) }) };
3666
+ }
3667
+ function liveLease(job, fence, phase, now) {
3668
+ if (job.jobId !== fence.jobId || job.state.state !== "leased") return;
3669
+ const { lease } = job.state;
3670
+ if (lease.attemptId !== fence.attemptId || lease.token !== fence.token || leasePhase(lease) !== phase || now >= lease.leaseEndsAt) {
3671
+ return;
3672
+ }
3673
+ return lease;
3674
+ }
3675
+ function claimJob(job, claim, time) {
3676
+ const { now } = time;
3677
+ if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
3678
+ const manual = hasRedrive(job);
3679
+ const ordinal = job.attempts.length + 1;
3680
+ if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
3681
+ if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
3682
+ const snapshot = readStoredSnapshot(job, job.snapshot);
3683
+ const lease = Object.freeze({
3684
+ attemptId: claim.attemptId,
3685
+ token: claim.token,
3686
+ startedAt: now,
3687
+ grantedAt: now,
3688
+ leaseEndsAt: endOfGrant(now, claim.leaseMs)
3689
+ });
3690
+ return replace(
3691
+ job,
3692
+ time,
3693
+ withLease(job, lease),
3694
+ (next) => Object.freeze({
3695
+ job: jobSummary(next),
3696
+ snapshot,
3697
+ fence: Object.freeze({ jobId: job.jobId, attemptId: lease.attemptId, token: lease.token }),
3698
+ lease: Object.freeze({ grantedAt: lease.grantedAt, leaseEndsAt: lease.leaseEndsAt }),
3699
+ ordinal,
3700
+ manual
3701
+ }),
3702
+ Math.min(job.expiresAt, lease.leaseEndsAt)
3703
+ );
3704
+ }
3705
+ function renewJob(job, fence, leaseMs, time) {
3706
+ const lease = liveLease(job, fence, "pre_handoff", time.now);
3707
+ if (!lease || time.now >= job.expiresAt) return null;
3708
+ const grant = Object.freeze({
3709
+ grantedAt: time.now,
3710
+ // A renewal never shortens a still-live grant, even if the caller requests a smaller duration.
3711
+ leaseEndsAt: Math.max(lease.leaseEndsAt, endOfGrant(time.now, leaseMs))
3712
+ });
3713
+ return replace(
3714
+ job,
3715
+ time,
3716
+ withLease(job, { ...lease, ...grant }),
3717
+ () => grant,
3718
+ Math.min(job.expiresAt, lease.leaseEndsAt)
3719
+ );
3720
+ }
3721
+ function markJob(job, fence, leaseMs, time) {
3722
+ const lease = liveLease(job, fence, "pre_handoff", time.now);
3723
+ if (!lease || time.now >= job.expiresAt) return null;
3724
+ const grant = Object.freeze({
3725
+ grantedAt: time.now,
3726
+ handoffAt: time.now,
3727
+ leaseEndsAt: endOfGrant(time.now, leaseMs)
3728
+ });
3729
+ return replace(
3730
+ job,
3731
+ time,
3732
+ withLease(job, {
3733
+ ...lease,
3734
+ grantedAt: grant.grantedAt,
3735
+ handedOffAt: grant.handoffAt,
3736
+ leaseEndsAt: grant.leaseEndsAt
3737
+ }),
3738
+ () => grant,
3739
+ Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
3740
+ );
3741
+ }
3742
+ function finalize(job, lease, operationId, result, time, owner) {
3743
+ const { now } = time;
3744
+ const { attemptId, startedAt, handedOffAt } = lease;
3745
+ const ordinal = job.attempts.length + 1;
3746
+ const effect = attemptEffect(result, attemptId, ordinal, hasRedrive(job), job.retry, job.expiresAt, now);
3747
+ const commit = Object.freeze({
3748
+ jobId: job.jobId,
3749
+ attemptId,
3750
+ ordinal,
3751
+ operationId,
3752
+ startedAt,
3753
+ ...handedOffAt === void 0 ? {} : { handedOffAt },
3754
+ finishedAt: now,
3755
+ result,
3756
+ ...effect
3757
+ });
3758
+ const entry = Object.freeze({
3759
+ commit,
3760
+ digest: activityDigest(activityFor(job, commit)),
3761
+ ...owner ? { ownerDigest: sha256(lease.token) } : {}
3762
+ });
3763
+ const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
3764
+ let before = owner ? lease.leaseEndsAt : void 0;
3765
+ if (result.reason === "cancelled" || result.retry === "safe_transient" && effect.disposition !== "expired") {
3766
+ before = Math.min(before ?? job.expiresAt, job.expiresAt);
3767
+ }
3768
+ return replace(
3769
+ job,
3770
+ time,
3771
+ { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
3772
+ () => copyCommit(commit),
3773
+ before
3774
+ );
3775
+ }
3776
+ function finishJob(job, request, time) {
3777
+ const { fence, phase, operationId, result } = request;
3778
+ if (job.jobId !== fence.jobId) return null;
3779
+ assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
3780
+ const previous = job.attempts.find(({ commit }) => commit.attemptId === fence.attemptId);
3781
+ if (previous) {
3782
+ const { commit } = previous;
3783
+ const previousPhase = commit.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
3784
+ if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
3785
+ return null;
3786
+ }
3787
+ if (hashJson(result, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
3788
+ invalid("invalid_command");
3789
+ }
3790
+ return { value: copyCommit(commit) };
3791
+ }
3792
+ const lease = liveLease(job, fence, phase, time.now);
3793
+ if (!lease) return null;
3794
+ if (result.reason === "expired" && time.now < job.expiresAt) invalid("invalid_command");
3795
+ assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
3796
+ return finalize(job, lease, operationId, result, time, true);
3797
+ }
3798
+ function recoverJob(job, operationId, time) {
3799
+ if (job.state.state !== "leased" || time.now < job.state.lease.leaseEndsAt) return null;
3800
+ const { lease } = job.state;
3801
+ const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
3802
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false);
3803
+ }
3804
+ function expireJob(job, time) {
3805
+ if (job.state.state !== "queued" || time.now < job.expiresAt) return null;
3806
+ return replace(job, time, { ...job, state: terminalState("expired", "expired", time.now) }, jobSummary);
3807
+ }
3808
+ function cancelJob(job, operationId, time) {
3809
+ const { state } = job;
3810
+ if (state.state === "terminal") {
3811
+ return {
3812
+ value: Object.freeze({
3813
+ status: state.disposition === "cancelled" ? "cancelled" : "too_late",
3814
+ job: jobSummary(job)
3815
+ })
3816
+ };
3817
+ }
3818
+ if (time.now >= job.expiresAt || state.state === "leased" && state.lease.handedOffAt !== void 0) {
3819
+ return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
3820
+ }
3821
+ if (state.state === "leased") {
3822
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false);
3823
+ const { write } = decision;
3824
+ if (write?.kind !== "replace") invalid("store_incompatible");
3825
+ return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
3826
+ }
3827
+ return replace(
3828
+ job,
3829
+ time,
3830
+ { ...job, state: terminalState("cancelled", "cancelled", time.now) },
3831
+ (next) => Object.freeze({ status: "cancelled", job: jobSummary(next) }),
3832
+ job.expiresAt
3833
+ );
3834
+ }
3835
+ function resolveJob(job, request, time) {
3836
+ if (job.jobId !== request.jobId) invalid("not_found");
3837
+ const replay = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
3838
+ if (replay) {
3839
+ if (replay.action !== request.action) invalid("resolution_conflict");
3840
+ return { value: Object.freeze({ status: "replayed", job: jobSummary(job) }) };
3841
+ }
3842
+ const { state } = job;
3843
+ if (state.state !== "terminal" || state.disposition !== "unknown" || state.settledAt !== void 0 || job.attempts.at(-1)?.commit.attemptId !== request.attemptId) {
3844
+ invalid("resolution_conflict");
3845
+ }
3846
+ const redrive = request.action === "redrive";
3847
+ if (redrive) {
3848
+ if (hasRedrive(job) || !job.snapshot) invalid("resolution_conflict");
3849
+ if (time.now >= job.expiresAt) invalid("expired");
3850
+ }
3851
+ const resolutions = Object.freeze([
3852
+ ...job.resolutions,
3853
+ Object.freeze({ attemptId: request.attemptId, action: request.action, at: time.now })
3854
+ ]);
3855
+ const nextState = redrive ? Object.freeze({ state: "queued", nextAt: time.now }) : Object.freeze({ ...state, settledAt: time.now });
3856
+ return replace(
3857
+ job,
3858
+ time,
3859
+ { ...job, resolutions, state: nextState },
3860
+ (next) => Object.freeze({ status: "resolved", job: jobSummary(next) }),
3861
+ redrive ? job.expiresAt : void 0
3862
+ );
3863
+ }
3864
+ function replaceAttempt(job, previous, entry) {
3865
+ return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
3866
+ }
3867
+ function reserveJobProjection(job, time) {
3868
+ const entry = pendingAttempt(job);
3869
+ if (job.retiring || !entry || entry.commit.finishedAt > time.now) return null;
3870
+ const permitUntil = timeAfter(time.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
3871
+ const activity = activityFor(job, entry.commit);
3872
+ const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
3873
+ const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
3874
+ return replace(
3875
+ job,
3876
+ time,
3877
+ { ...job, attempts, projectionPermitUntil: Math.max(job.projectionPermitUntil ?? 0, permitUntil) },
3878
+ () => permit,
3879
+ permitUntil
3880
+ );
3881
+ }
3882
+ function matchingProjection(job, permit) {
3883
+ const { scope, jobId, attemptId } = permit.activity;
3884
+ if (!job || job.scope !== scope || job.jobId !== jobId) return;
3885
+ return job.attempts.find(
3886
+ (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
3887
+ );
3888
+ }
3889
+ function assertMatchingActivity(stored, permit) {
3890
+ const { activity } = permit;
3891
+ if (stored.activity.scope !== activity.scope || stored.activity.jobId !== activity.jobId || stored.activity.attemptId !== activity.attemptId || stored.digest !== permit.digest) {
3892
+ invalid("store_incompatible");
3893
+ }
3894
+ }
3895
+ function decideActivityPut(job, permit, existing, now) {
3896
+ if (existing) assertMatchingActivity(existing, permit);
3897
+ if (!existing && now >= permit.permitUntil) return "permit_expired";
3898
+ const entry = matchingProjection(job, permit);
3899
+ if (!entry) invalid("invalid_command");
3900
+ if (existing) return "present";
3901
+ if (entry.projectionAckAt !== void 0 || job?.retiring) invalid("store_incompatible");
3902
+ if (now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
3903
+ return "insert";
3904
+ }
3905
+ function acknowledgeJobProjection(job, permit, proof, time) {
3906
+ const entry = matchingProjection(job, permit);
3907
+ if (!entry) return { value: "stale" };
3908
+ if (proof) assertMatchingActivity(proof, permit);
3909
+ if (entry.projectionAckAt !== void 0) return { value: "already_acknowledged" };
3910
+ if (!proof || job.retiring) return { value: "stale" };
3911
+ if (time.now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
3912
+ const attempts = replaceAttempt(job, entry, { ...entry, projectionAckAt: time.now });
3913
+ return replace(job, time, { ...job, attempts }, () => "acknowledged", void 0, {
3914
+ attemptId: entry.commit.attemptId,
3915
+ digest: entry.digest
3916
+ });
3917
+ }
3918
+ function cleanupJob(job, time) {
3919
+ const due = jobSelectors(job).nextCleanupAt;
3920
+ if (due === void 0 || due > time.now) return null;
3921
+ if (job.retiring) {
3922
+ return {
3923
+ write: {
3924
+ kind: "purge",
3925
+ guard: guard(job, time),
3926
+ attemptIds: Object.freeze(job.attempts.map(({ commit }) => commit.attemptId))
3927
+ },
3928
+ value: "purged"
3929
+ };
3930
+ }
3931
+ if (job.snapshot) {
3932
+ const pruned = { ...job };
3933
+ delete pruned.snapshot;
3934
+ return replace(job, time, pruned, () => "payload_pruned");
3935
+ }
3936
+ return replace(job, time, { ...job, retiring: true }, () => "retirement_started");
3937
+ }
3938
+
3939
+ // src/stores/memory.ts
3940
+ var dueKeys = ["nextAt", "queuedExpiresAt", "leaseEndsAt", "pendingAt", "nextCleanupAt"];
3941
+ function emptyScope() {
3942
+ return {
3943
+ jobs: /* @__PURE__ */ new Map(),
3944
+ identities: /* @__PURE__ */ new Map(),
3945
+ due: { nextAt: [], queuedExpiresAt: [], leaseEndsAt: [], pendingAt: [], nextCleanupAt: [] },
3946
+ activities: [],
3947
+ byJob: /* @__PURE__ */ new Map()
3948
+ };
3949
+ }
3950
+ function lowerBound(ordered, test) {
3951
+ let lo = 0;
3952
+ let hi = ordered.length;
3953
+ while (lo < hi) {
3954
+ const mid = Math.floor((lo + hi) / 2);
3955
+ if (test(ordered[mid])) hi = mid;
3956
+ else lo = mid + 1;
3957
+ }
3958
+ return lo;
3959
+ }
3960
+ function compareDue(a, b) {
3961
+ return a.at - b.at || b.priority - a.priority || compareAscii(a.jobId, b.jobId);
3962
+ }
3963
+ function reindex(rows, previous, next) {
3964
+ const oldKeys = previous && jobSelectors(previous);
3965
+ const newKeys = next && jobSelectors(next);
3966
+ for (const key of dueKeys) {
3967
+ const oldAt = oldKeys?.[key];
3968
+ const newAt = newKeys?.[key];
3969
+ if (oldAt === newAt) continue;
3970
+ const index = rows.due[key];
3971
+ if (previous && oldAt !== void 0) {
3972
+ const entry = { at: oldAt, jobId: previous.jobId, priority: key === "nextAt" ? previous.priority : 0 };
3973
+ index.splice(
3974
+ lowerBound(index, (candidate) => compareDue(candidate, entry) >= 0),
3975
+ 1
3976
+ );
3977
+ }
3978
+ if (next && newAt !== void 0) {
3979
+ const entry = { at: newAt, jobId: next.jobId, priority: key === "nextAt" ? next.priority : 0 };
3980
+ index.splice(
3981
+ lowerBound(index, (candidate) => compareDue(candidate, entry) >= 0),
3982
+ 0,
3983
+ entry
3984
+ );
3985
+ }
3986
+ }
3987
+ }
3988
+ function putRow(rows, stored) {
3989
+ const { jobId, attemptId } = stored.activity;
3990
+ let job = rows.byJob.get(jobId);
3991
+ if (!job) {
3992
+ job = { byId: /* @__PURE__ */ new Map(), ordered: [] };
3993
+ rows.byJob.set(jobId, job);
3994
+ }
3995
+ job.byId.set(attemptId, stored);
3996
+ const index = (candidate) => compareActivity(candidate.activity, stored.activity) >= 0;
3997
+ job.ordered.splice(lowerBound(job.ordered, index), 0, stored);
3998
+ rows.activities.splice(lowerBound(rows.activities, index), 0, stored);
3999
+ }
4000
+ function removeActivities(rows, jobId, attemptIds) {
4001
+ const job = rows.byJob.get(jobId);
4002
+ if (!job) return;
4003
+ for (const attemptId of attemptIds) {
4004
+ const activity = job.byId.get(attemptId)?.activity;
4005
+ if (!activity) continue;
4006
+ const i = lowerBound(rows.activities, (candidate) => compareActivity(candidate.activity, activity) >= 0);
4007
+ rows.activities.splice(i, 1);
4008
+ }
4009
+ rows.byJob.delete(jobId);
4010
+ }
4011
+ var TIME_MISS = /* @__PURE__ */ Symbol("time_miss");
4012
+ var NONE = Object.freeze({ status: "none" });
4013
+ var CONTENDED = Object.freeze({ status: "contended" });
4014
+ function createMemoryEmailStore(options = {}) {
4015
+ const config = readRecord(options, [], ["clock", "maxJobs"], "invalid_config");
4016
+ const clock = readClock(config.clock);
4017
+ const maxJobs = boundedOption(config.maxJobs, MEMORY_MAX_JOBS);
4018
+ const scopes = /* @__PURE__ */ new Map();
4019
+ let count = 0;
4020
+ let active = false;
4021
+ let lastWall = 0;
4022
+ function wallNow() {
4023
+ let now;
4024
+ try {
4025
+ now = unixMs(clock.now(), "store_unavailable");
4026
+ } catch {
4027
+ return invalid("store_unavailable");
4028
+ }
4029
+ if (now < lastWall) invalid("store_unavailable");
4030
+ lastWall = now;
4031
+ return now;
4032
+ }
4033
+ function elapsedClock() {
4034
+ try {
4035
+ const now = clock.monotonicNow();
4036
+ if (Number.isFinite(now)) return now;
4037
+ } catch {
4038
+ invalid("store_unavailable");
4039
+ }
4040
+ return invalid("store_unavailable");
4041
+ }
4042
+ function atomic(call, run) {
4043
+ if (active) invalid("busy");
4044
+ active = true;
4045
+ try {
4046
+ const signal = call.signal;
4047
+ if (signal && Reflect.get(AbortSignal.prototype, "aborted", signal)) invalid("aborted");
4048
+ const start = elapsedClock();
4049
+ const check = () => {
4050
+ const elapsed = elapsedClock() - start;
4051
+ if (signal && Reflect.get(AbortSignal.prototype, "aborted", signal)) invalid("aborted");
4052
+ if (elapsed < 0) invalid("store_unavailable");
4053
+ if (elapsed >= call.timeoutMs) invalid("deadline");
4054
+ };
4055
+ check();
4056
+ return run(check);
4057
+ } finally {
4058
+ active = false;
4059
+ }
4060
+ }
4061
+ function read(call, worker, get) {
4062
+ return atomic(readStoreCall(call, worker), (check) => {
4063
+ const value = get();
4064
+ check();
4065
+ return value;
4066
+ });
4067
+ }
4068
+ function apply(rows, row, plan, check) {
4069
+ check();
4070
+ if (!plan) return null;
4071
+ const { write } = plan;
4072
+ if (write) {
4073
+ const now = wallNow();
4074
+ check();
4075
+ if (now < write.guard.atOrAfter || write.guard.before !== void 0 && now >= write.guard.before)
4076
+ return TIME_MISS;
4077
+ if (write.kind === "replace") {
4078
+ reindex(rows, row, write.next);
4079
+ rows.jobs.set(row.jobId, write.next);
4080
+ } else {
4081
+ removeActivities(rows, row.jobId, write.attemptIds);
4082
+ reindex(rows, row, void 0);
4083
+ rows.jobs.delete(row.jobId);
4084
+ rows.identities.delete(row.admissionKey);
4085
+ count--;
4086
+ if (rows.jobs.size === 0) scopes.delete(row.scope);
4087
+ }
4088
+ }
4089
+ return plan.value;
4090
+ }
4091
+ function point(scope, jobId, check, decide) {
4092
+ const rows = scopes.get(scopeToken(scope));
4093
+ const row = rows?.jobs.get(jobId);
4094
+ if (!rows || !row) {
4095
+ check();
4096
+ return null;
4097
+ }
4098
+ for (let i = 0; i < MAX_STORE_CAS_SUBMISSIONS; i++) {
4099
+ const value = apply(rows, row, decide(row, { now: wallNow(), revision: (0, import_node_crypto5.randomUUID)() }), check);
4100
+ if (value !== TIME_MISS) return value;
4101
+ }
4102
+ return invalid("busy");
4103
+ }
4104
+ function next(scope, key, check, decide) {
4105
+ const rows = scopes.get(scopeToken(scope));
4106
+ let now = wallNow();
4107
+ let misses = 0;
4108
+ if (rows) {
4109
+ const index = rows.due[key];
4110
+ for (let i = 0; i < MAX_STORE_CANDIDATES && i < index.length; i++) {
4111
+ const candidate = index[i];
4112
+ if (candidate.at > now) break;
4113
+ const row = rows.jobs.get(candidate.jobId);
4114
+ for (; ; ) {
4115
+ const value = apply(rows, row, decide(row, { now, revision: (0, import_node_crypto5.randomUUID)() }), check);
4116
+ if (value === null) break;
4117
+ if (value !== TIME_MISS) return Object.freeze({ status: "applied", value });
4118
+ if (++misses === MAX_STORE_CAS_SUBMISSIONS) return CONTENDED;
4119
+ now = wallNow();
4120
+ }
4121
+ }
4122
+ }
4123
+ check();
4124
+ return misses ? CONTENDED : NONE;
4125
+ }
4126
+ const store = {
4127
+ async ready(options2 = {}) {
4128
+ const call = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
4129
+ atomic({ ...call, timeoutMs: Math.min(call.timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) }, (check) => {
4130
+ wallNow();
4131
+ check();
4132
+ });
4133
+ },
4134
+ async findAdmission(scope, key, call) {
4135
+ return read(call, false, () => {
4136
+ const rows = scopes.get(scopeToken(scope));
4137
+ const encoded = encodeAdmissionKey(validateAdmissionKey(key));
4138
+ const id = rows?.identities.get(encoded);
4139
+ const row = id && rows?.jobs.get(id);
4140
+ return row ? Object.freeze({ job: jobSummary(row), fingerprint: row.fingerprint }) : null;
4141
+ });
4142
+ },
4143
+ async insert(scope, admission, call) {
4144
+ return atomic(readStoreCall(call), (check) => {
4145
+ const parsed = readStoreAdmission(scope, admission);
4146
+ const rows = scopes.get(parsed.command.scope);
4147
+ if (rows?.identities.has(parsed.admissionKey)) {
4148
+ check();
4149
+ return Object.freeze({ status: "duplicate" });
4150
+ }
4151
+ if (rows?.jobs.has(parsed.jobId)) invalid("invalid_command");
4152
+ const row = newJob(parsed, { now: wallNow(), revision: (0, import_node_crypto5.randomUUID)() });
4153
+ if (count >= maxJobs) invalid("store_capacity");
4154
+ const result = Object.freeze({ status: "inserted", job: jobSummary(row) });
4155
+ check();
4156
+ const target = rows ?? emptyScope();
4157
+ target.identities.set(row.admissionKey, row.jobId);
4158
+ target.jobs.set(row.jobId, row);
4159
+ reindex(target, void 0, row);
4160
+ if (!rows) scopes.set(row.scope, target);
4161
+ count++;
4162
+ return result;
4163
+ });
4164
+ },
4165
+ async findJob(scope, jobId, call) {
4166
+ return read(call, false, () => {
4167
+ const rows = scopes.get(scopeToken(scope));
4168
+ const id = readStoreId(jobId);
4169
+ const job = rows?.jobs.get(id);
4170
+ return job ? jobSummary(job) : null;
4171
+ });
4172
+ },
4173
+ async findAttempt(scope, jobId, attemptId, call) {
4174
+ return read(call, true, () => {
4175
+ const rows = scopes.get(scopeToken(scope));
4176
+ const job = readStoreId(jobId);
4177
+ const id = readStoreId(attemptId);
4178
+ const entry = rows?.jobs.get(job)?.attempts.find(({ commit }) => commit.attemptId === id);
4179
+ return entry ? copyCommit(entry.commit) : null;
4180
+ });
4181
+ },
4182
+ async claimNext(scope, claim, call) {
4183
+ return atomic(readStoreCall(call, true), (check) => {
4184
+ const safe = readClaim(claim);
4185
+ return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time));
4186
+ });
4187
+ },
4188
+ async renew(scope, fence, leaseMs, call) {
4189
+ return atomic(readStoreCall(call, true), (check) => {
4190
+ const safe = readFence(fence);
4191
+ const duration = readLeaseMs(leaseMs);
4192
+ return point(scope, safe.jobId, check, (row, time) => renewJob(row, safe, duration, time));
4193
+ });
4194
+ },
4195
+ async markHandoff(scope, fence, leaseMs, call) {
4196
+ return atomic(readStoreCall(call, true), (check) => {
4197
+ const safe = readFence(fence);
4198
+ const duration = readLeaseMs(leaseMs);
4199
+ return point(scope, safe.jobId, check, (row, time) => markJob(row, safe, duration, time));
4200
+ });
4201
+ },
4202
+ async finish(scope, finish, call) {
4203
+ return atomic(readStoreCall(call, true), (check) => {
4204
+ const safe = readFinish(finish);
4205
+ return point(scope, safe.fence.jobId, check, (row, time) => finishJob(row, safe, time));
4206
+ });
4207
+ },
4208
+ async recoverNext(scope, call) {
4209
+ return atomic(readStoreCall(call, true), (check) => {
4210
+ const operationId = (0, import_node_crypto5.randomUUID)();
4211
+ return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time));
4212
+ });
4213
+ },
4214
+ async expireNext(scope, call) {
4215
+ return atomic(readStoreCall(call, true), (check) => next(scope, "queuedExpiresAt", check, expireJob));
4216
+ },
4217
+ async cancel(scope, jobId, call) {
4218
+ return atomic(readStoreCall(call), (check) => {
4219
+ const operationId = (0, import_node_crypto5.randomUUID)();
4220
+ return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time)) ?? Object.freeze({ status: "not_found" });
4221
+ });
4222
+ },
4223
+ async resolveUnknown(scope, command, call) {
4224
+ return atomic(readStoreCall(call), (check) => {
4225
+ const safe = readResolution(command);
4226
+ return point(scope, safe.jobId, check, (row, time) => resolveJob(row, safe, time)) ?? invalid("not_found");
4227
+ });
4228
+ },
4229
+ async reserveProjection(scope, call) {
4230
+ return atomic(readStoreCall(call), (check) => next(scope, "pendingAt", check, reserveJobProjection));
4231
+ },
4232
+ async putActivity(scope, permit, call) {
4233
+ return atomic(readStoreCall(call), (check) => {
4234
+ const safe = readProjectionPermit(scopeToken(scope), permit);
4235
+ const rows = scopes.get(scope);
4236
+ const { jobId, attemptId } = safe.activity;
4237
+ const existing = rows?.byJob.get(jobId)?.byId.get(attemptId);
4238
+ const decision = decideActivityPut(rows?.jobs.get(jobId), safe, existing, wallNow());
4239
+ check();
4240
+ if (decision !== "insert") return decision;
4241
+ if (!rows) invalid("store_incompatible");
4242
+ const now = wallNow();
4243
+ check();
4244
+ if (now >= safe.permitUntil) return "permit_expired";
4245
+ putRow(rows, Object.freeze({ activity: safe.activity, digest: safe.digest }));
4246
+ return "present";
4247
+ });
4248
+ },
4249
+ async ackProjection(scope, permit, call) {
4250
+ return atomic(readStoreCall(call), (check) => {
4251
+ const safe = readProjectionPermit(scopeToken(scope), permit);
4252
+ const { jobId, attemptId } = safe.activity;
4253
+ const proof = scopes.get(scope)?.byJob.get(jobId)?.byId.get(attemptId);
4254
+ return point(scope, jobId, check, (row, time) => acknowledgeJobProjection(row, safe, proof, time)) ?? "stale";
4255
+ });
4256
+ },
4257
+ async listActivities(scope, query, call) {
4258
+ return read(call, false, () => {
4259
+ const criteria = readActivityCriteria(scopeToken(scope), query);
4260
+ const rows = scopes.get(scope);
4261
+ const { jobId, before, from, after, limit } = criteria;
4262
+ const index = (jobId === null ? rows?.activities : rows?.byJob.get(jobId)?.ordered) ?? [];
4263
+ const start = Math.max(
4264
+ before === null ? 0 : lowerBound(index, ({ activity }) => activity.finishedAt < before),
4265
+ after === void 0 ? 0 : lowerBound(index, ({ activity }) => compareActivity(activity, after) > 0)
4266
+ );
4267
+ const end = from === null ? index.length : lowerBound(index, ({ activity }) => activity.finishedAt < from);
4268
+ const selected = index.slice(start, Math.min(end, start + limit + 1)).map(({ activity }) => activity);
4269
+ return activityPage(criteria, selected);
4270
+ });
4271
+ },
4272
+ async cleanupNext(scope, call) {
4273
+ return atomic(readStoreCall(call), (check) => next(scope, "nextCleanupAt", check, cleanupJob));
4274
+ }
4275
+ };
4276
+ return Object.freeze(store);
4277
+ }
4278
+ // Annotate the CommonJS export names for ESM import in node:
4279
+ 0 && (module.exports = {
4280
+ EmailError,
4281
+ createEmailAdmin,
4282
+ createEmailBatchService,
4283
+ createEmailService,
4284
+ createEmailTemplateRegistry,
4285
+ createEmailWorker,
4286
+ createMemoryEmailStore,
4287
+ defineLocalTemplate,
4288
+ defineSendGridTemplate
4289
+ });