@web-ts-toolkit/email-service 0.0.0-stage → 0.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +584 -2
- package/index.d.mts +214 -0
- package/index.d.ts +214 -0
- package/index.js +4522 -0
- package/index.mjs +4477 -0
- package/mongoose.d.mts +27 -0
- package/mongoose.d.ts +27 -0
- package/mongoose.js +3311 -0
- package/mongoose.mjs +3286 -0
- package/package.json +89 -4
- package/provider-DC_av0SQ.d.mts +199 -0
- package/provider-DC_av0SQ.d.ts +199 -0
- package/sendgrid.d.mts +18 -0
- package/sendgrid.d.ts +18 -0
- package/sendgrid.js +1521 -0
- package/sendgrid.mjs +1494 -0
- package/smtp.d.mts +30 -0
- package/smtp.d.ts +30 -0
- package/smtp.js +1549 -0
- package/smtp.mjs +1512 -0
- package/store-Bi5iZ910.d.ts +360 -0
- package/store-DlABKTjt.d.mts +360 -0
package/sendgrid.mjs
ADDED
|
@@ -0,0 +1,1494 @@
|
|
|
1
|
+
// src/constants.ts
|
|
2
|
+
var KiB = 1024;
|
|
3
|
+
var MiB = 1024 * KiB;
|
|
4
|
+
var DAY_MS = 864e5;
|
|
5
|
+
function bounded(defaultValue, min, max) {
|
|
6
|
+
return Object.freeze({ default: defaultValue, min, max });
|
|
7
|
+
}
|
|
8
|
+
var EMAIL_FORMAT_VERSION = 1;
|
|
9
|
+
var MAX_UNIX_MS = 253402300799999;
|
|
10
|
+
var CLOCK_MARGIN_MS = 1e3;
|
|
11
|
+
var MAX_EXPIRY_MS = 30 * DAY_MS;
|
|
12
|
+
var MESSAGE_LIMITS = Object.freeze({
|
|
13
|
+
scopeBytes: 64,
|
|
14
|
+
identifierBytes: 128,
|
|
15
|
+
jsonDepth: 12,
|
|
16
|
+
jsonValues: 2048,
|
|
17
|
+
jsonKeyBytes: 128,
|
|
18
|
+
intentBytes: 16 * KiB,
|
|
19
|
+
dataBytes: 64 * KiB,
|
|
20
|
+
snapshotBytes: MiB,
|
|
21
|
+
recipients: 50,
|
|
22
|
+
addressBytes: 254,
|
|
23
|
+
localPartBytes: 64,
|
|
24
|
+
displayNameBytes: 128,
|
|
25
|
+
subjectBytes: 512,
|
|
26
|
+
templateSourceBytes: 256 * KiB,
|
|
27
|
+
htmlBytes: 512 * KiB,
|
|
28
|
+
textBytes: 256 * KiB,
|
|
29
|
+
correlationEntries: 8,
|
|
30
|
+
correlationKeyBytes: 32,
|
|
31
|
+
correlationValueBytes: 96,
|
|
32
|
+
attachments: 5,
|
|
33
|
+
filenameBytes: 128,
|
|
34
|
+
contentTypeBytes: 127,
|
|
35
|
+
attachmentBytes: 2 * MiB,
|
|
36
|
+
totalAttachmentBytes: 5 * MiB
|
|
37
|
+
});
|
|
38
|
+
var PRIORITY = bounded(0, 0, 9);
|
|
39
|
+
var TEMPLATE_CACHE_ENTRIES = bounded(32, 0, 128);
|
|
40
|
+
var TEMPLATE_MAX_PENDING = bounded(8, 1, 32);
|
|
41
|
+
var CALL_BUDGETS = Object.freeze({
|
|
42
|
+
prepare: bounded(5e3, 50, 3e4),
|
|
43
|
+
admissionOrAdmin: bounded(1e4, 50, 6e4),
|
|
44
|
+
batchOrRun: bounded(3e4, 50, 12e4),
|
|
45
|
+
shutdown: bounded(15e3, 50, 6e4)
|
|
46
|
+
});
|
|
47
|
+
var DEFAULT_RETRY_POLICY = Object.freeze({
|
|
48
|
+
maxAttempts: 3,
|
|
49
|
+
baseDelayMs: 1e3,
|
|
50
|
+
maxDelayMs: 6e4
|
|
51
|
+
});
|
|
52
|
+
var RETRY_POLICY_BOUNDS = Object.freeze({
|
|
53
|
+
maxAttempts: bounded(DEFAULT_RETRY_POLICY.maxAttempts, 1, 10),
|
|
54
|
+
baseDelayMs: bounded(DEFAULT_RETRY_POLICY.baseDelayMs, 100, 6e4),
|
|
55
|
+
// Also require maxDelayMs >= the configured baseDelayMs.
|
|
56
|
+
maxDelayMs: bounded(DEFAULT_RETRY_POLICY.maxDelayMs, 100, 36e5)
|
|
57
|
+
});
|
|
58
|
+
var MAX_MANUAL_ATTEMPTS = 1;
|
|
59
|
+
var MAX_ATTEMPT_LEDGER = RETRY_POLICY_BOUNDS.maxAttempts.max + MAX_MANUAL_ATTEMPTS;
|
|
60
|
+
var MAX_RATE_DEFERRAL_MS = 30 * DAY_MS;
|
|
61
|
+
var DEFAULT_RETENTION_POLICY = Object.freeze({
|
|
62
|
+
payloadMs: 7 * DAY_MS,
|
|
63
|
+
historyMs: 30 * DAY_MS,
|
|
64
|
+
idempotencyMs: 30 * DAY_MS
|
|
65
|
+
});
|
|
66
|
+
var RETENTION_POLICY_BOUNDS = Object.freeze({
|
|
67
|
+
payloadMs: bounded(DEFAULT_RETENTION_POLICY.payloadMs, 0, 30 * DAY_MS),
|
|
68
|
+
historyMs: bounded(DEFAULT_RETENTION_POLICY.historyMs, DAY_MS, 90 * DAY_MS),
|
|
69
|
+
idempotencyMs: bounded(DEFAULT_RETENTION_POLICY.idempotencyMs, DAY_MS, 90 * DAY_MS)
|
|
70
|
+
});
|
|
71
|
+
var DEFAULT_WORKER_LIMITS = Object.freeze({
|
|
72
|
+
maxConcurrency: 4,
|
|
73
|
+
storeTimeoutMs: 5e3,
|
|
74
|
+
leaseMs: 6e4,
|
|
75
|
+
preHandoffTimeoutMs: 8e3,
|
|
76
|
+
attachmentTimeoutMs: 5e3,
|
|
77
|
+
rateTimeoutMs: 500,
|
|
78
|
+
providerTimeoutMs: 15e3,
|
|
79
|
+
finalizeGraceMs: 1e4
|
|
80
|
+
});
|
|
81
|
+
var WORKER_LIMIT_BOUNDS = Object.freeze({
|
|
82
|
+
maxConcurrency: bounded(DEFAULT_WORKER_LIMITS.maxConcurrency, 1, 16),
|
|
83
|
+
storeTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.storeTimeoutMs, 50, 3e4),
|
|
84
|
+
leaseMs: bounded(DEFAULT_WORKER_LIMITS.leaseMs, 5e3, 3e5),
|
|
85
|
+
preHandoffTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.preHandoffTimeoutMs, 50, 6e4),
|
|
86
|
+
attachmentTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.attachmentTimeoutMs, 50, 3e4),
|
|
87
|
+
rateTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.rateTimeoutMs, 10, 5e3),
|
|
88
|
+
providerTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.providerTimeoutMs, 50, 6e4),
|
|
89
|
+
finalizeGraceMs: bounded(DEFAULT_WORKER_LIMITS.finalizeGraceMs, 100, 3e4)
|
|
90
|
+
});
|
|
91
|
+
var RUN_CLAIM_LIMIT = bounded(20, 1, 100);
|
|
92
|
+
var RUN_MAINTENANCE_LIMIT = bounded(10, 0, 100);
|
|
93
|
+
var ACTIVITY_PAGE_LIMIT = bounded(25, 1, 100);
|
|
94
|
+
var ADMIN_MAINTENANCE_LIMIT = bounded(20, 1, 100);
|
|
95
|
+
var PROJECTION_DRAIN_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max + CLOCK_MARGIN_MS;
|
|
96
|
+
var MEMORY_MAX_JOBS = bounded(256, 1, 4096);
|
|
97
|
+
var MONGOOSE_DEFAULT_NAMES = Object.freeze({
|
|
98
|
+
jobsCollection: "email_jobs",
|
|
99
|
+
activitiesCollection: "email_activities",
|
|
100
|
+
jobsModelName: "EmailJobV1",
|
|
101
|
+
activitiesModelName: "EmailActivityV1"
|
|
102
|
+
});
|
|
103
|
+
var SMTP_DEFAULT_PORTS = Object.freeze({ implicit: 465, starttls: 587 });
|
|
104
|
+
var SENDGRID_DEFAULT_MODE = "live";
|
|
105
|
+
var SENDGRID_REQUEST_MAX_BYTES = 8 * MiB;
|
|
106
|
+
var SENDGRID_RESPONSE_MAX_BYTES = 64 * KiB;
|
|
107
|
+
|
|
108
|
+
// src/internal/canonical-json.ts
|
|
109
|
+
import { createHash } from "crypto";
|
|
110
|
+
|
|
111
|
+
// src/internal/validation.ts
|
|
112
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
113
|
+
import { types } from "util";
|
|
114
|
+
|
|
115
|
+
// src/errors.ts
|
|
116
|
+
var messages = Object.freeze({
|
|
117
|
+
invalid_config: "Invalid email service configuration.",
|
|
118
|
+
invalid_command: "Invalid email command.",
|
|
119
|
+
invalid_input: "Invalid template input.",
|
|
120
|
+
invalid_data: "Invalid prepared template data.",
|
|
121
|
+
invalid_snapshot: "Invalid prepared email snapshot.",
|
|
122
|
+
preparation_failed: "Email preparation failed.",
|
|
123
|
+
template_not_found: "Email template not found.",
|
|
124
|
+
template_source: "Email template source could not be loaded.",
|
|
125
|
+
template_render: "Email template could not be rendered.",
|
|
126
|
+
provider_mismatch: "Email provider does not match the template or snapshot.",
|
|
127
|
+
expired: "Email has expired.",
|
|
128
|
+
idempotency_conflict: "Email admission key was used with different intent.",
|
|
129
|
+
not_found: "Email job not found.",
|
|
130
|
+
resolution_conflict: "Unknown attempt cannot be resolved with this action.",
|
|
131
|
+
store_capacity: "Email store is at capacity.",
|
|
132
|
+
store_unavailable: "Email store is unavailable.",
|
|
133
|
+
store_incompatible: "Email store does not meet the required guarantees.",
|
|
134
|
+
write_unconfirmed: "Email store write not confirmed; it may have committed.",
|
|
135
|
+
invalid_cursor: "Invalid email activity cursor.",
|
|
136
|
+
aborted: "Email operation was aborted.",
|
|
137
|
+
deadline: "Email operation deadline elapsed.",
|
|
138
|
+
busy: "Email service has no available capacity for this operation.",
|
|
139
|
+
closed: "Email service is closed."
|
|
140
|
+
});
|
|
141
|
+
var EmailError = class extends Error {
|
|
142
|
+
/** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
|
|
143
|
+
code;
|
|
144
|
+
constructor(code) {
|
|
145
|
+
const safeCode = typeof code === "string" && Object.hasOwn(messages, code) ? code : "invalid_config";
|
|
146
|
+
super(messages[safeCode]);
|
|
147
|
+
this.name = "EmailError";
|
|
148
|
+
this.code = safeCode;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/internal/validation.ts
|
|
153
|
+
function invalid(code) {
|
|
154
|
+
throw new EmailError(code);
|
|
155
|
+
}
|
|
156
|
+
function dataObject(value, code) {
|
|
157
|
+
if (typeof value !== "object" || value === null || types.isProxy(value)) invalid(code);
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
160
|
+
function isArray(value, code) {
|
|
161
|
+
return Array.isArray(dataObject(value, code));
|
|
162
|
+
}
|
|
163
|
+
function plainKeys(value, maxKeys, code) {
|
|
164
|
+
const object = dataObject(value, code);
|
|
165
|
+
const proto = Object.getPrototypeOf(object);
|
|
166
|
+
if (Array.isArray(object) || proto !== null && proto !== Object.prototype) invalid(code);
|
|
167
|
+
const keys = Reflect.ownKeys(object);
|
|
168
|
+
if (keys.length > maxKeys || keys.some((key) => typeof key !== "string")) invalid(code);
|
|
169
|
+
return keys;
|
|
170
|
+
}
|
|
171
|
+
function ownData(value, key, code) {
|
|
172
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
173
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) invalid(code);
|
|
174
|
+
return descriptor.value;
|
|
175
|
+
}
|
|
176
|
+
function readRecord(value, required, optional, code) {
|
|
177
|
+
const keys = plainKeys(value, required.length + optional.length, code);
|
|
178
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
179
|
+
for (const key of keys) {
|
|
180
|
+
if (!required.includes(key) && !optional.includes(key)) invalid(code);
|
|
181
|
+
copy[key] = ownData(value, key, code);
|
|
182
|
+
}
|
|
183
|
+
for (const key of required) {
|
|
184
|
+
if (!Object.hasOwn(copy, key)) invalid(code);
|
|
185
|
+
}
|
|
186
|
+
return copy;
|
|
187
|
+
}
|
|
188
|
+
function denseArrayLength(value, maxLength, code) {
|
|
189
|
+
const object = dataObject(value, code);
|
|
190
|
+
if (!Array.isArray(object) || Object.getPrototypeOf(object) !== Array.prototype) invalid(code);
|
|
191
|
+
const { length } = object;
|
|
192
|
+
if (length > maxLength || Reflect.ownKeys(object).length !== length + 1) invalid(code);
|
|
193
|
+
return length;
|
|
194
|
+
}
|
|
195
|
+
function readArray(value, maxLength, code, read) {
|
|
196
|
+
const length = denseArrayLength(value, maxLength, code);
|
|
197
|
+
const copy = [];
|
|
198
|
+
for (let i = 0; i < length; i++) copy.push(read(ownData(value, String(i), code)));
|
|
199
|
+
return Object.freeze(copy);
|
|
200
|
+
}
|
|
201
|
+
function integer(value, min, max, code) {
|
|
202
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) invalid(code);
|
|
203
|
+
return value === 0 ? 0 : value;
|
|
204
|
+
}
|
|
205
|
+
function boundedOption(value, bounds, code = "invalid_config") {
|
|
206
|
+
return value === void 0 ? bounds.default : integer(value, bounds.min, bounds.max, code);
|
|
207
|
+
}
|
|
208
|
+
function unixMs(value, code) {
|
|
209
|
+
return integer(value, 0, MAX_UNIX_MS, code);
|
|
210
|
+
}
|
|
211
|
+
function utf8Length(value, maxBytes, code) {
|
|
212
|
+
if (value.length > maxBytes || /[\uD800-\uDFFF]/u.test(value)) invalid(code);
|
|
213
|
+
const bytes = Buffer2.byteLength(value, "utf8");
|
|
214
|
+
if (bytes > maxBytes) invalid(code);
|
|
215
|
+
return bytes;
|
|
216
|
+
}
|
|
217
|
+
function utf8String(value, maxBytes, code) {
|
|
218
|
+
if (typeof value !== "string") invalid(code);
|
|
219
|
+
utf8Length(value, maxBytes, code);
|
|
220
|
+
return value;
|
|
221
|
+
}
|
|
222
|
+
function headerString(value, maxBytes, code) {
|
|
223
|
+
const text = utf8String(value, maxBytes, code);
|
|
224
|
+
for (let i = 0; i < text.length; i++) {
|
|
225
|
+
const ch = text.charCodeAt(i);
|
|
226
|
+
if (ch < 32 || ch === 127) invalid(code);
|
|
227
|
+
}
|
|
228
|
+
return text;
|
|
229
|
+
}
|
|
230
|
+
function opaqueToken(value, maxBytes, code) {
|
|
231
|
+
if (typeof value !== "string" || value.length > maxBytes || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
232
|
+
invalid(code);
|
|
233
|
+
}
|
|
234
|
+
return value;
|
|
235
|
+
}
|
|
236
|
+
function identifier(value, code) {
|
|
237
|
+
return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
|
|
238
|
+
}
|
|
239
|
+
function uuidV4(value, code) {
|
|
240
|
+
if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
|
|
241
|
+
invalid(code);
|
|
242
|
+
}
|
|
243
|
+
return value;
|
|
244
|
+
}
|
|
245
|
+
function hashToken(value, code) {
|
|
246
|
+
if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
|
|
247
|
+
return value;
|
|
248
|
+
}
|
|
249
|
+
function jsonKey(key, code) {
|
|
250
|
+
utf8Length(key, MESSAGE_LIMITS.jsonKeyBytes, code);
|
|
251
|
+
if (key === "__proto__" || key === "prototype" || key === "constructor" || key.includes(".") || key.includes("$") || key.includes("\0")) {
|
|
252
|
+
invalid(code);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/internal/canonical-json.ts
|
|
257
|
+
var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
|
|
258
|
+
function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
|
|
259
|
+
let bytesLeft = maxBytes;
|
|
260
|
+
let valuesLeft = limits2.values;
|
|
261
|
+
const chunks = [];
|
|
262
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
263
|
+
function append(text, bytes = text.length) {
|
|
264
|
+
if (bytes > bytesLeft) invalid(code);
|
|
265
|
+
bytesLeft -= bytes;
|
|
266
|
+
chunks.push(text);
|
|
267
|
+
}
|
|
268
|
+
function appendString(text) {
|
|
269
|
+
let bytes = 2 + utf8Length(text, bytesLeft - 2, code);
|
|
270
|
+
for (let i = 0; i < text.length; i++) {
|
|
271
|
+
const ch = text.charCodeAt(i);
|
|
272
|
+
if (ch === 34 || ch === 92 || ch === 8 || ch === 9 || ch === 10 || ch === 12 || ch === 13) bytes++;
|
|
273
|
+
else if (ch < 32) bytes += 5;
|
|
274
|
+
if (bytes > bytesLeft) invalid(code);
|
|
275
|
+
}
|
|
276
|
+
append(JSON.stringify(text), bytes);
|
|
277
|
+
}
|
|
278
|
+
function visit(value2, depth) {
|
|
279
|
+
if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
|
|
280
|
+
switch (typeof value2) {
|
|
281
|
+
case "string":
|
|
282
|
+
appendString(value2);
|
|
283
|
+
return value2;
|
|
284
|
+
case "number":
|
|
285
|
+
if (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2)) invalid(code);
|
|
286
|
+
append(JSON.stringify(value2));
|
|
287
|
+
return value2 === 0 ? 0 : value2;
|
|
288
|
+
case "boolean":
|
|
289
|
+
append(value2 ? "true" : "false");
|
|
290
|
+
return value2;
|
|
291
|
+
case "object":
|
|
292
|
+
if (value2 === null) {
|
|
293
|
+
append("null");
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
break;
|
|
297
|
+
default:
|
|
298
|
+
invalid(code);
|
|
299
|
+
}
|
|
300
|
+
if (ancestors.has(value2)) invalid(code);
|
|
301
|
+
ancestors.add(value2);
|
|
302
|
+
try {
|
|
303
|
+
const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
|
|
304
|
+
if (isArray(value2, code)) {
|
|
305
|
+
const length = denseArrayLength(value2, maxChildren, code);
|
|
306
|
+
if (length && 2 * length + 1 > bytesLeft) invalid(code);
|
|
307
|
+
const copy2 = [];
|
|
308
|
+
append("[");
|
|
309
|
+
for (let i = 0; i < length; i++) {
|
|
310
|
+
if (i) append(",");
|
|
311
|
+
copy2.push(visit(ownData(value2, String(i), code), depth + 1));
|
|
312
|
+
}
|
|
313
|
+
append("]");
|
|
314
|
+
return Object.freeze(copy2);
|
|
315
|
+
}
|
|
316
|
+
const keys = plainKeys(value2, maxChildren, code);
|
|
317
|
+
if (keys.length && 5 * keys.length + 1 > bytesLeft) invalid(code);
|
|
318
|
+
for (const key of keys) jsonKey(key, code);
|
|
319
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
320
|
+
append("{");
|
|
321
|
+
for (const [index, key] of keys.sort().entries()) {
|
|
322
|
+
if (index) append(",");
|
|
323
|
+
appendString(key);
|
|
324
|
+
append(":");
|
|
325
|
+
copy[key] = visit(ownData(value2, key, code), depth + 1);
|
|
326
|
+
}
|
|
327
|
+
append("}");
|
|
328
|
+
return Object.freeze(copy);
|
|
329
|
+
} finally {
|
|
330
|
+
ancestors.delete(value2);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const value = visit(input, 0);
|
|
334
|
+
return { value, encoded: chunks.join("") };
|
|
335
|
+
}
|
|
336
|
+
function copyJsonObject(input, maxBytes, code) {
|
|
337
|
+
if (typeof input !== "object" || input === null || isArray(input, code)) invalid(code);
|
|
338
|
+
return canonicalJson(input, maxBytes, code).value;
|
|
339
|
+
}
|
|
340
|
+
function sha256(input) {
|
|
341
|
+
return createHash("sha256").update(input).digest("hex");
|
|
342
|
+
}
|
|
343
|
+
function encodeEvidence(input, code, capacity) {
|
|
344
|
+
return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/internal/smtp-capacity.ts
|
|
348
|
+
var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
|
|
349
|
+
var MAX_RECIPIENTS = 1e3;
|
|
350
|
+
var KIB = 1024;
|
|
351
|
+
var limits = Object.freeze({
|
|
352
|
+
snapshotBytes: 2 * KIB * KIB,
|
|
353
|
+
snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
|
|
354
|
+
evidenceBytes: 64 * KIB,
|
|
355
|
+
evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
|
|
356
|
+
jobBsonBytes: 4 * KIB * KIB,
|
|
357
|
+
activityBsonBytes: 128 * KIB,
|
|
358
|
+
registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
|
|
359
|
+
registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
|
|
360
|
+
servicePending: 4,
|
|
361
|
+
workerProfiles: 16,
|
|
362
|
+
workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
|
|
363
|
+
runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
|
|
364
|
+
runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
|
|
365
|
+
adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
|
|
366
|
+
page: Object.freeze({ min: 1, default: 8, max: 16 }),
|
|
367
|
+
memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
|
|
368
|
+
mongoInFlight: 4,
|
|
369
|
+
dueCandidates: 4
|
|
370
|
+
});
|
|
371
|
+
function readBinding(input, code) {
|
|
372
|
+
const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
|
|
373
|
+
if (format !== "smtp-v2") invalid(code);
|
|
374
|
+
return Object.freeze({
|
|
375
|
+
format,
|
|
376
|
+
namespace: uuidV4(namespace, code),
|
|
377
|
+
maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
function capacityTag(capacity) {
|
|
381
|
+
return capacity ? { smtpCapacity: capacity.binding } : {};
|
|
382
|
+
}
|
|
383
|
+
function recipientLimit(capacity) {
|
|
384
|
+
return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
|
|
385
|
+
}
|
|
386
|
+
function matchesBinding(input, capacity, code) {
|
|
387
|
+
const binding = readBinding(input, code);
|
|
388
|
+
if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
|
|
389
|
+
invalid(code);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
function assertCapacityTag(raw, capacity, code) {
|
|
393
|
+
const tagged = Object.hasOwn(raw, "smtpCapacity");
|
|
394
|
+
if (capacity) {
|
|
395
|
+
if (!tagged) invalid(code);
|
|
396
|
+
matchesBinding(raw.smtpCapacity, capacity, code);
|
|
397
|
+
} else if (tagged) {
|
|
398
|
+
invalid(code);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function assertCapacityProvider(provider, capacity, code) {
|
|
402
|
+
if (capacity && provider.kind !== "smtp") invalid(code);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/internal/attempt-codecs.ts
|
|
406
|
+
var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
|
|
407
|
+
var providerStages = [...smtpStages, "http"];
|
|
408
|
+
var evidence = Object.freeze({
|
|
409
|
+
smtp_accepted: ["accepted", "never", ["data"], "smtp"],
|
|
410
|
+
smtp_partial: ["partially_accepted", "never", ["data"], "smtp"],
|
|
411
|
+
smtp_transient_reply: ["rejected", "safe_transient", smtpStages, "smtp"],
|
|
412
|
+
smtp_permanent_reply: ["rejected", "never", smtpStages, "smtp"],
|
|
413
|
+
sendgrid_accepted: ["accepted", "never", ["http"], "sendgrid"],
|
|
414
|
+
sendgrid_validated: ["validated", "never", ["http"], "sendgrid"],
|
|
415
|
+
sendgrid_throttled: ["rejected", "safe_transient", ["http"], "sendgrid"],
|
|
416
|
+
sendgrid_rejected: ["rejected", "never", ["http"], "sendgrid"],
|
|
417
|
+
not_transmitted: ["unsubmitted", "safe_transient", providerStages, "provider"],
|
|
418
|
+
provider_configuration: ["unsubmitted", "never", providerStages, "provider"],
|
|
419
|
+
transport_uncertain: ["unknown", "never", providerStages, "provider"],
|
|
420
|
+
provider_timeout: ["unknown", "never", providerStages, "provider"],
|
|
421
|
+
provider_aborted: ["unknown", "never", providerStages, "provider"],
|
|
422
|
+
attachment_unavailable: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
423
|
+
attachment_timeout: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
424
|
+
attachment_invalid: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
425
|
+
attachment_resolver_error: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
426
|
+
rate_deferred: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
427
|
+
rate_timeout: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
428
|
+
rate_error: ["unsubmitted", "never", ["rate_limit"], "pre"],
|
|
429
|
+
profile_unavailable: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
430
|
+
provider_preflight_error: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
431
|
+
pre_handoff_timeout: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
432
|
+
worker_stopped: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
433
|
+
pre_handoff_lease_expired: ["unsubmitted", "safe_transient", ["pre_handoff"], "recovery"],
|
|
434
|
+
launch_window_closed: ["unsubmitted", "safe_transient", ["pre_handoff"], "launch"],
|
|
435
|
+
post_handoff_lease_expired: ["unknown", "never", ["pre_handoff"], "recovery"],
|
|
436
|
+
expired: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
437
|
+
cancelled: ["unsubmitted", "never", ["pre_handoff"], "cancel"]
|
|
438
|
+
});
|
|
439
|
+
function readAttemptReason(value, code) {
|
|
440
|
+
if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
|
|
441
|
+
return value;
|
|
442
|
+
}
|
|
443
|
+
var recipientGroups = ["to", "cc", "bcc"];
|
|
444
|
+
function recipientCounts(envelope) {
|
|
445
|
+
return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
|
|
446
|
+
}
|
|
447
|
+
function smtpMessageId(attemptId) {
|
|
448
|
+
return `<${attemptId}@email.invalid>`;
|
|
449
|
+
}
|
|
450
|
+
function readHint(input, reason, code) {
|
|
451
|
+
if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
|
|
452
|
+
const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
|
|
453
|
+
const hasDelay = Object.hasOwn(raw, "delayMs");
|
|
454
|
+
const hasFloor = Object.hasOwn(raw, "notBefore");
|
|
455
|
+
if (!hasDelay && (!hasFloor || reason === "rate_deferred")) invalid(code);
|
|
456
|
+
return Object.freeze({
|
|
457
|
+
...hasDelay ? {
|
|
458
|
+
delayMs: reason === "rate_deferred" ? integer(raw.delayMs, 1, MAX_RATE_DEFERRAL_MS, code) : integer(raw.delayMs, 0, Number.MAX_SAFE_INTEGER, code)
|
|
459
|
+
} : {},
|
|
460
|
+
...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
|
|
464
|
+
const raw = readRecord(
|
|
465
|
+
input,
|
|
466
|
+
["outcome", "retry", "stage", "reason"],
|
|
467
|
+
["retryHint", "recipients", "messageId", "providerMessageId"],
|
|
468
|
+
code
|
|
469
|
+
);
|
|
470
|
+
const reason = readAttemptReason(raw.reason, code);
|
|
471
|
+
const [outcome, retry, stages, origin] = evidence[reason];
|
|
472
|
+
const stage = stages.find((value) => value === raw.stage);
|
|
473
|
+
if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
|
|
474
|
+
if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
|
|
475
|
+
const hasHint = Object.hasOwn(raw, "retryHint");
|
|
476
|
+
if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
|
|
477
|
+
const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
|
|
478
|
+
const hasRecipients = Object.hasOwn(raw, "recipients");
|
|
479
|
+
if (smtpSuccess && !hasRecipients) invalid(code);
|
|
480
|
+
let recipients;
|
|
481
|
+
if (hasRecipients) {
|
|
482
|
+
if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
|
|
483
|
+
const seen = /* @__PURE__ */ new Set();
|
|
484
|
+
const limit = recipientLimit(capacity);
|
|
485
|
+
let previous = -1;
|
|
486
|
+
recipients = readArray(raw.recipients, limit, code, (value) => {
|
|
487
|
+
const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
|
|
488
|
+
if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
|
|
489
|
+
if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
|
|
490
|
+
const index = integer(rawIndex, 0, limit - 1, code);
|
|
491
|
+
if (capacity) {
|
|
492
|
+
const position = recipientGroups.indexOf(group) * limit + index;
|
|
493
|
+
if (position <= previous) invalid(code);
|
|
494
|
+
previous = position;
|
|
495
|
+
} else {
|
|
496
|
+
const key = `${group}:${index}`;
|
|
497
|
+
if (seen.has(key)) invalid(code);
|
|
498
|
+
seen.add(key);
|
|
499
|
+
}
|
|
500
|
+
return Object.freeze({ group, index, status });
|
|
501
|
+
});
|
|
502
|
+
const accepted = recipients.filter(({ status }) => status === "accepted").length;
|
|
503
|
+
if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
|
|
504
|
+
invalid(code);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const hasMessageId = Object.hasOwn(raw, "messageId");
|
|
508
|
+
const { messageId, providerMessageId } = raw;
|
|
509
|
+
if (hasMessageId && (!smtpSuccess || typeof messageId !== "string" || messageId.length !== 52)) invalid(code);
|
|
510
|
+
const hasProviderId = Object.hasOwn(raw, "providerMessageId");
|
|
511
|
+
if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
|
|
512
|
+
invalid(code);
|
|
513
|
+
}
|
|
514
|
+
const result = Object.freeze({
|
|
515
|
+
outcome,
|
|
516
|
+
retry,
|
|
517
|
+
stage,
|
|
518
|
+
reason,
|
|
519
|
+
...hasHint ? { retryHint: readHint(raw.retryHint, reason, code) } : {},
|
|
520
|
+
...recipients === void 0 ? {} : { recipients },
|
|
521
|
+
...typeof messageId === "string" ? { messageId } : {},
|
|
522
|
+
...typeof providerMessageId === "string" ? { providerMessageId } : {}
|
|
523
|
+
});
|
|
524
|
+
if (capacity && !projected) encodeEvidence(result, code, capacity);
|
|
525
|
+
return result;
|
|
526
|
+
}
|
|
527
|
+
function assertEvidenceContext(result, provider, attemptId, counts, code) {
|
|
528
|
+
const { reason, stage, recipients, messageId } = result;
|
|
529
|
+
const origin = evidence[reason][3];
|
|
530
|
+
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)) {
|
|
531
|
+
invalid(code);
|
|
532
|
+
}
|
|
533
|
+
if (recipients) {
|
|
534
|
+
if (provider.kind !== "smtp") invalid(code);
|
|
535
|
+
if (counts) {
|
|
536
|
+
if (recipients.some(({ group, index }) => index >= counts[group])) invalid(code);
|
|
537
|
+
const needsPartition = reason === "smtp_accepted" || reason === "smtp_partial" || stage === "envelope" && (reason === "smtp_transient_reply" || reason === "smtp_permanent_reply");
|
|
538
|
+
if (needsPartition && recipients.length !== counts.to + counts.cc + counts.bcc) invalid(code);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
function readProviderResult(input, provider, attemptId, envelope, capacity) {
|
|
543
|
+
const code = "invalid_command";
|
|
544
|
+
const result = readAttemptResult(input, code, false, capacity);
|
|
545
|
+
const origin = evidence[result.reason][3];
|
|
546
|
+
if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
|
|
547
|
+
assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
|
|
548
|
+
return result;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// src/internal/budget.ts
|
|
552
|
+
import { addAbortListener } from "events";
|
|
553
|
+
import { performance } from "perf_hooks";
|
|
554
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
555
|
+
import { types as types2 } from "util";
|
|
556
|
+
var systemEmailClock = Object.freeze({
|
|
557
|
+
now: Date.now,
|
|
558
|
+
monotonicNow: () => performance.now(),
|
|
559
|
+
sleep: (ms, signal) => sleep(ms, void 0, { signal })
|
|
560
|
+
});
|
|
561
|
+
function readCallOptions(input, bounds) {
|
|
562
|
+
const code = "invalid_config";
|
|
563
|
+
const { signal, timeoutMs } = readRecord(input, [], ["signal", "timeoutMs"], code);
|
|
564
|
+
const timeout = boundedOption(timeoutMs, bounds, code);
|
|
565
|
+
if (signal === void 0) return { timeoutMs: timeout };
|
|
566
|
+
try {
|
|
567
|
+
if (!types2.isProxy(signal) && signal instanceof AbortSignal && typeof Reflect.get(AbortSignal.prototype, "aborted", signal) === "boolean") {
|
|
568
|
+
return { signal, timeoutMs: timeout };
|
|
569
|
+
}
|
|
570
|
+
} catch {
|
|
571
|
+
invalid(code);
|
|
572
|
+
}
|
|
573
|
+
return invalid(code);
|
|
574
|
+
}
|
|
575
|
+
function monotonicNow(clock) {
|
|
576
|
+
try {
|
|
577
|
+
const now = clock.monotonicNow();
|
|
578
|
+
if (Number.isFinite(now)) return now;
|
|
579
|
+
} catch {
|
|
580
|
+
invalid("invalid_config");
|
|
581
|
+
}
|
|
582
|
+
return invalid("invalid_config");
|
|
583
|
+
}
|
|
584
|
+
function createBudget(clock, timeoutMs, external) {
|
|
585
|
+
return createBudgetUntil(clock, monotonicNow(clock) + timeoutMs, external);
|
|
586
|
+
}
|
|
587
|
+
function createBudgetUntil(clock, end, external) {
|
|
588
|
+
const operation = new AbortController();
|
|
589
|
+
const timer = new AbortController();
|
|
590
|
+
let externalListener;
|
|
591
|
+
let closed = false;
|
|
592
|
+
let reason;
|
|
593
|
+
function close() {
|
|
594
|
+
if (closed) return;
|
|
595
|
+
closed = true;
|
|
596
|
+
externalListener?.[Symbol.dispose]();
|
|
597
|
+
timer.abort();
|
|
598
|
+
}
|
|
599
|
+
function stop(code) {
|
|
600
|
+
if (closed) return;
|
|
601
|
+
reason = code;
|
|
602
|
+
close();
|
|
603
|
+
operation.abort(new EmailError(code));
|
|
604
|
+
}
|
|
605
|
+
function remainingMs() {
|
|
606
|
+
if (closed) return 0;
|
|
607
|
+
if (external?.aborted) {
|
|
608
|
+
stop("aborted");
|
|
609
|
+
} else {
|
|
610
|
+
try {
|
|
611
|
+
const remaining = end - monotonicNow(clock);
|
|
612
|
+
if (remaining > 0) return remaining;
|
|
613
|
+
stop("deadline");
|
|
614
|
+
} catch {
|
|
615
|
+
stop("invalid_config");
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return 0;
|
|
619
|
+
}
|
|
620
|
+
function arm(remaining) {
|
|
621
|
+
void Promise.resolve(clock.sleep(Math.ceil(remaining), timer.signal)).then(
|
|
622
|
+
() => {
|
|
623
|
+
try {
|
|
624
|
+
const left = remainingMs();
|
|
625
|
+
if (left <= 0) return;
|
|
626
|
+
if (left >= remaining) stop("invalid_config");
|
|
627
|
+
else arm(left);
|
|
628
|
+
} catch {
|
|
629
|
+
stop("invalid_config");
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
() => stop("invalid_config")
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
try {
|
|
636
|
+
if (external && !external.aborted) externalListener = addAbortListener(external, () => stop("aborted"));
|
|
637
|
+
const remaining = remainingMs();
|
|
638
|
+
if (remaining > 0) arm(remaining);
|
|
639
|
+
} catch {
|
|
640
|
+
stop("invalid_config");
|
|
641
|
+
}
|
|
642
|
+
return {
|
|
643
|
+
signal: operation.signal,
|
|
644
|
+
deadline: end,
|
|
645
|
+
remainingMs,
|
|
646
|
+
check() {
|
|
647
|
+
remainingMs();
|
|
648
|
+
if (reason) invalid(reason);
|
|
649
|
+
if (closed) invalid("aborted");
|
|
650
|
+
},
|
|
651
|
+
close
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// src/internal/message-codecs.ts
|
|
656
|
+
import { isIP } from "net";
|
|
657
|
+
import { types as types3 } from "util";
|
|
658
|
+
var L = MESSAGE_LIMITS;
|
|
659
|
+
var SNAPSHOT = "invalid_snapshot";
|
|
660
|
+
var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
|
|
661
|
+
var DNS_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
662
|
+
var MIME_TYPE = /^[-a-z0-9!#$%&'*+.^_`{|}~]+\/[-a-z0-9!#$%&'*+.^_`{|}~]+$/;
|
|
663
|
+
function validateProviderRef(input, code = SNAPSHOT) {
|
|
664
|
+
const { kind, key, mode } = readRecord(input, ["kind", "key", "mode"], [], code);
|
|
665
|
+
const profile = identifier(key, code);
|
|
666
|
+
if (kind === "smtp" && mode === "live") return Object.freeze({ kind, key: profile, mode });
|
|
667
|
+
if (kind === "sendgrid" && (mode === "live" || mode === "sandbox")) {
|
|
668
|
+
return Object.freeze({ kind, key: profile, mode });
|
|
669
|
+
}
|
|
670
|
+
return invalid(code);
|
|
671
|
+
}
|
|
672
|
+
function validateTemplateIdentity(input, code = SNAPSHOT) {
|
|
673
|
+
const { key, revision } = readRecord(input, ["key", "revision"], [], code);
|
|
674
|
+
return Object.freeze({ key: identifier(key, code), revision: identifier(revision, code) });
|
|
675
|
+
}
|
|
676
|
+
function sendGridTemplateId(input, code = SNAPSHOT) {
|
|
677
|
+
if (typeof input !== "string" || input.length !== 34 || !/^d-[0-9a-fA-F]{32}$/.test(input)) invalid(code);
|
|
678
|
+
return input;
|
|
679
|
+
}
|
|
680
|
+
function validateMailbox(input, code = SNAPSHOT) {
|
|
681
|
+
const mailbox2 = readRecord(input, ["address"], ["name"], code);
|
|
682
|
+
const address = headerString(mailbox2.address, L.addressBytes, code);
|
|
683
|
+
const at = address.indexOf("@");
|
|
684
|
+
const local = address.slice(0, at);
|
|
685
|
+
const domain = address.slice(at + 1);
|
|
686
|
+
if (at < 1 || at > L.localPartBytes || !DOT_ATOM.test(local) || !domain.split(".").every((label) => DNS_LABEL.test(label)) || isIP(domain) !== 0) {
|
|
687
|
+
invalid(code);
|
|
688
|
+
}
|
|
689
|
+
return Object.freeze({
|
|
690
|
+
address,
|
|
691
|
+
...Object.hasOwn(mailbox2, "name") ? { name: headerString(mailbox2.name, L.displayNameBytes, code) } : {}
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
|
|
695
|
+
const limit = recipientLimit(capacity);
|
|
696
|
+
const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
|
|
697
|
+
const seen = /* @__PURE__ */ new Set();
|
|
698
|
+
const recipient = (raw) => {
|
|
699
|
+
const mailbox2 = validateMailbox(raw, code);
|
|
700
|
+
const address = mailbox2.address.toLowerCase();
|
|
701
|
+
if (seen.has(address)) invalid(code);
|
|
702
|
+
seen.add(address);
|
|
703
|
+
return mailbox2;
|
|
704
|
+
};
|
|
705
|
+
const from = validateMailbox(envelope.from, code);
|
|
706
|
+
const to = readArray(envelope.to, limit, code, recipient);
|
|
707
|
+
const cc = readArray(envelope.cc, limit - to.length, code, recipient);
|
|
708
|
+
const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
|
|
709
|
+
if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
|
|
710
|
+
return Object.freeze({
|
|
711
|
+
from,
|
|
712
|
+
to,
|
|
713
|
+
cc,
|
|
714
|
+
bcc,
|
|
715
|
+
...Object.hasOwn(envelope, "replyTo") ? { replyTo: validateMailbox(envelope.replyTo, code) } : {}
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
function validateCorrelation(input, code = SNAPSHOT) {
|
|
719
|
+
const keys = plainKeys(input, L.correlationEntries, code);
|
|
720
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
721
|
+
for (const key of keys) {
|
|
722
|
+
jsonKey(key, code);
|
|
723
|
+
opaqueToken(key, L.correlationKeyBytes, code);
|
|
724
|
+
copy[key] = opaqueToken(ownData(input, key, code), L.correlationValueBytes, code);
|
|
725
|
+
}
|
|
726
|
+
return Object.freeze(copy);
|
|
727
|
+
}
|
|
728
|
+
function validateAttachmentRef(input, code = SNAPSHOT) {
|
|
729
|
+
const ref = readRecord(
|
|
730
|
+
input,
|
|
731
|
+
["resolverKey", "id", "version", "filename", "contentType", "byteLength", "sha256"],
|
|
732
|
+
[],
|
|
733
|
+
code
|
|
734
|
+
);
|
|
735
|
+
const filename = headerString(ref.filename, L.filenameBytes, code);
|
|
736
|
+
if (!filename || filename === "." || filename === ".." || /[/\\:]/.test(filename)) invalid(code);
|
|
737
|
+
const contentType = headerString(ref.contentType, L.contentTypeBytes, code);
|
|
738
|
+
if (!MIME_TYPE.test(contentType)) invalid(code);
|
|
739
|
+
return Object.freeze({
|
|
740
|
+
resolverKey: identifier(ref.resolverKey, code),
|
|
741
|
+
id: identifier(ref.id, code),
|
|
742
|
+
version: identifier(ref.version, code),
|
|
743
|
+
filename,
|
|
744
|
+
contentType,
|
|
745
|
+
byteLength: integer(ref.byteLength, 1, L.attachmentBytes, code),
|
|
746
|
+
sha256: hashToken(ref.sha256, code)
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
function validateAttachmentRefs(input, code = SNAPSHOT) {
|
|
750
|
+
let total = 0;
|
|
751
|
+
return readArray(input, L.attachments, code, (raw) => {
|
|
752
|
+
const ref = validateAttachmentRef(raw, code);
|
|
753
|
+
total += ref.byteLength;
|
|
754
|
+
if (total > L.totalAttachmentBytes) invalid(code);
|
|
755
|
+
return ref;
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
function copyAttachmentBytes(ref, input, code = SNAPSHOT) {
|
|
759
|
+
if (!types3.isUint8Array(input)) invalid(code);
|
|
760
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
761
|
+
const buffer = Reflect.get(typedArrayPrototype, "buffer", input);
|
|
762
|
+
const offset = Reflect.get(typedArrayPrototype, "byteOffset", input);
|
|
763
|
+
const length = Reflect.get(typedArrayPrototype, "byteLength", input);
|
|
764
|
+
if (types3.isSharedArrayBuffer(buffer) || length !== ref.byteLength || length < 1 || length > L.attachmentBytes) {
|
|
765
|
+
invalid(code);
|
|
766
|
+
}
|
|
767
|
+
const bytes = new Uint8Array(new Uint8Array(buffer, offset, length));
|
|
768
|
+
if (sha256(bytes) !== ref.sha256) invalid(code);
|
|
769
|
+
return bytes;
|
|
770
|
+
}
|
|
771
|
+
function validateSubject(input, code = SNAPSHOT) {
|
|
772
|
+
const subject = headerString(input, L.subjectBytes, code);
|
|
773
|
+
if (!subject.trim()) invalid(code);
|
|
774
|
+
return subject;
|
|
775
|
+
}
|
|
776
|
+
function smtpParts(subject, html, text, code) {
|
|
777
|
+
if (!html && !text) invalid(code);
|
|
778
|
+
return Object.freeze({ subject, ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } });
|
|
779
|
+
}
|
|
780
|
+
function validateSmtpContent(input, code = SNAPSHOT) {
|
|
781
|
+
const content = readRecord(input, ["subject"], ["html", "text"], code);
|
|
782
|
+
return smtpParts(
|
|
783
|
+
validateSubject(content.subject, code),
|
|
784
|
+
Object.hasOwn(content, "html") ? utf8String(content.html, L.htmlBytes, code) : void 0,
|
|
785
|
+
Object.hasOwn(content, "text") ? utf8String(content.text, L.textBytes, code) : void 0,
|
|
786
|
+
code
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
|
|
790
|
+
const expiresAt = unixMs(input, code);
|
|
791
|
+
if (expiresAt <= preparedAt || expiresAt - preparedAt > MAX_EXPIRY_MS || scheduleAt !== null && scheduleAt >= expiresAt) {
|
|
792
|
+
invalid(code);
|
|
793
|
+
}
|
|
794
|
+
return expiresAt;
|
|
795
|
+
}
|
|
796
|
+
function hashSnapshot(snapshot, capacity) {
|
|
797
|
+
return sha256(
|
|
798
|
+
canonicalJson(
|
|
799
|
+
snapshot,
|
|
800
|
+
capacity?.limits.snapshotBytes ?? L.snapshotBytes,
|
|
801
|
+
SNAPSHOT,
|
|
802
|
+
capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
|
|
803
|
+
).encoded
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
function readSnapshot(input, capacity) {
|
|
807
|
+
const dto = readRecord(
|
|
808
|
+
input,
|
|
809
|
+
[
|
|
810
|
+
"version",
|
|
811
|
+
"kind",
|
|
812
|
+
"provider",
|
|
813
|
+
"template",
|
|
814
|
+
"envelope",
|
|
815
|
+
"preparedAt",
|
|
816
|
+
"expiresAt",
|
|
817
|
+
"priority",
|
|
818
|
+
"attachments",
|
|
819
|
+
"correlation"
|
|
820
|
+
],
|
|
821
|
+
["subject", "html", "text", "templateId", "data", "smtpCapacity"],
|
|
822
|
+
SNAPSHOT
|
|
823
|
+
);
|
|
824
|
+
if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
|
|
825
|
+
assertCapacityTag(dto, capacity, SNAPSHOT);
|
|
826
|
+
const provider = validateProviderRef(dto.provider);
|
|
827
|
+
if (provider.kind !== dto.kind) invalid("provider_mismatch");
|
|
828
|
+
assertCapacityProvider(provider, capacity, "provider_mismatch");
|
|
829
|
+
const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
|
|
830
|
+
const common = {
|
|
831
|
+
version: EMAIL_FORMAT_VERSION,
|
|
832
|
+
template: validateTemplateIdentity(dto.template),
|
|
833
|
+
envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
|
|
834
|
+
preparedAt,
|
|
835
|
+
expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
|
|
836
|
+
priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
|
|
837
|
+
attachments: validateAttachmentRefs(dto.attachments),
|
|
838
|
+
correlation: validateCorrelation(dto.correlation)
|
|
839
|
+
};
|
|
840
|
+
if (provider.kind === "smtp") {
|
|
841
|
+
if (Object.hasOwn(dto, "templateId") || Object.hasOwn(dto, "data")) invalid(SNAPSHOT);
|
|
842
|
+
const content = validateSmtpContent({
|
|
843
|
+
subject: dto.subject,
|
|
844
|
+
...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
|
|
845
|
+
...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
|
|
846
|
+
});
|
|
847
|
+
return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
|
|
848
|
+
}
|
|
849
|
+
if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
|
|
850
|
+
return Object.freeze({
|
|
851
|
+
...common,
|
|
852
|
+
kind: provider.kind,
|
|
853
|
+
provider,
|
|
854
|
+
templateId: sendGridTemplateId(dto.templateId),
|
|
855
|
+
data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
function validateSnapshot(input, capacity) {
|
|
859
|
+
const snapshot = readSnapshot(input, capacity);
|
|
860
|
+
return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// src/internal/store-codecs.ts
|
|
864
|
+
var REQUEST = "invalid_command";
|
|
865
|
+
var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
|
|
866
|
+
function readStoreId(value, code = REQUEST) {
|
|
867
|
+
return uuidV4(value, code);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// src/internal/provider-preparation.ts
|
|
871
|
+
function sameRef(a, b) {
|
|
872
|
+
return a.resolverKey === b.resolverKey && a.id === b.id && a.version === b.version && a.filename === b.filename && a.contentType === b.contentType && a.byteLength === b.byteLength && a.sha256 === b.sha256;
|
|
873
|
+
}
|
|
874
|
+
function readProviderSubmission(input, ref, capacity) {
|
|
875
|
+
const code = "invalid_snapshot";
|
|
876
|
+
const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
|
|
877
|
+
const jobId = readStoreId(raw.jobId, code);
|
|
878
|
+
const attemptId = readStoreId(raw.attemptId, code);
|
|
879
|
+
const { snapshot } = validateSnapshot(raw.snapshot, capacity);
|
|
880
|
+
if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
|
|
881
|
+
invalid("provider_mismatch");
|
|
882
|
+
}
|
|
883
|
+
const length = denseArrayLength(raw.attachments, MESSAGE_LIMITS.attachments, code);
|
|
884
|
+
if (length !== snapshot.attachments.length) invalid(code);
|
|
885
|
+
const attachments = snapshot.attachments.map((expected, index) => {
|
|
886
|
+
const resolved = readRecord(ownData(raw.attachments, String(index), code), ["ref", "bytes"], [], code);
|
|
887
|
+
if (!sameRef(expected, validateAttachmentRef(resolved.ref, code))) invalid(code);
|
|
888
|
+
return Object.freeze({ ref: expected, bytes: copyAttachmentBytes(expected, resolved.bytes, code) });
|
|
889
|
+
});
|
|
890
|
+
return Object.freeze({
|
|
891
|
+
jobId,
|
|
892
|
+
attemptId,
|
|
893
|
+
snapshot,
|
|
894
|
+
attachments: Object.freeze(attachments)
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
function readProviderCall(input) {
|
|
898
|
+
const code = "invalid_config";
|
|
899
|
+
const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
|
|
900
|
+
const bounds = { ...WORKER_LIMIT_BOUNDS.providerTimeoutMs, min: 1 };
|
|
901
|
+
const timeoutMs = integer(raw.timeoutMs, bounds.min, bounds.max, code);
|
|
902
|
+
const { signal } = readCallOptions(raw, bounds);
|
|
903
|
+
if (!signal) invalid(code);
|
|
904
|
+
return { timeoutMs, signal };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// src/providers/sendgrid/submit.ts
|
|
908
|
+
import { Resolver } from "dns";
|
|
909
|
+
import { addAbortListener as addAbortListener2 } from "events";
|
|
910
|
+
import { request as httpsRequest } from "https";
|
|
911
|
+
import { isIP as isIP2 } from "net";
|
|
912
|
+
import { checkServerIdentity, connect as connectTls } from "tls";
|
|
913
|
+
|
|
914
|
+
// src/providers/sendgrid/retry-hint.ts
|
|
915
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
916
|
+
var WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
917
|
+
var DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
918
|
+
var SECONDS = /^\d+$/;
|
|
919
|
+
var IMF = /^(?<weekday>[A-Z][a-z]{2}), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/;
|
|
920
|
+
var RFC850 = /^(?<weekday>[A-Z][a-z]+), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) GMT$/;
|
|
921
|
+
var ASCTIME = /^(?<weekday>[A-Z][a-z]{2}) (?<month>[A-Z][a-z]{2}) (?<day> \d|\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}) (?<year>\d{4})$/;
|
|
922
|
+
function secondsMs(value) {
|
|
923
|
+
const seconds = Number(value);
|
|
924
|
+
return seconds > Math.floor(MAX_UNIX_MS / 1e3) ? MAX_UNIX_MS : seconds * 1e3;
|
|
925
|
+
}
|
|
926
|
+
function httpDate(value, now) {
|
|
927
|
+
const parts = IMF.exec(value)?.groups ?? RFC850.exec(value)?.groups ?? ASCTIME.exec(value)?.groups;
|
|
928
|
+
if (!parts) return;
|
|
929
|
+
const { weekday, day, month, year, hour, minute, second } = parts;
|
|
930
|
+
const old = year?.length === 2;
|
|
931
|
+
const m = MONTHS.indexOf(month ?? "");
|
|
932
|
+
const week = (old ? DAYS : WEEKDAYS).indexOf(weekday ?? "");
|
|
933
|
+
const d = Number(day);
|
|
934
|
+
const h = Number(hour);
|
|
935
|
+
const min = Number(minute);
|
|
936
|
+
const sec = Number(second);
|
|
937
|
+
if (m < 0 || week < 0 || d < 1 || d > 31 || h > 23 || min > 59 || sec > 59 && (sec !== 60 || h !== 23 || min !== 59)) {
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
941
|
+
const leapSecondMs = sec === 60 ? 1e3 : 0;
|
|
942
|
+
date.setUTCHours(h, min, Math.min(sec, 59));
|
|
943
|
+
let y = Number(year);
|
|
944
|
+
if (old) {
|
|
945
|
+
const latest = new Date(now);
|
|
946
|
+
const latestYear = latest.getUTCFullYear() + 50;
|
|
947
|
+
latest.setUTCFullYear(latestYear);
|
|
948
|
+
y += Math.floor(latestYear / 100) * 100;
|
|
949
|
+
if (date.setUTCFullYear(y, m, d) + leapSecondMs > latest.getTime()) y -= 100;
|
|
950
|
+
}
|
|
951
|
+
date.setUTCFullYear(y, m, d);
|
|
952
|
+
if (date.getUTCMonth() !== m || date.getUTCDate() !== d || date.getUTCDay() !== week) return;
|
|
953
|
+
return Math.max(0, Math.min(MAX_UNIX_MS, date.getTime() + leapSecondMs));
|
|
954
|
+
}
|
|
955
|
+
function retryHint(after, reset, now) {
|
|
956
|
+
const delayMs = after !== void 0 && SECONDS.test(after) ? secondsMs(after) : void 0;
|
|
957
|
+
const date = after !== void 0 && delayMs === void 0 ? httpDate(after, now) : void 0;
|
|
958
|
+
const resetMs = reset !== void 0 && SECONDS.test(reset) ? secondsMs(reset) : void 0;
|
|
959
|
+
if (delayMs === void 0 && date === void 0 && resetMs === void 0) return;
|
|
960
|
+
return {
|
|
961
|
+
...delayMs === void 0 ? {} : { delayMs },
|
|
962
|
+
...date === void 0 && resetMs === void 0 ? {} : { notBefore: Math.max(date ?? 0, resetMs ?? 0) }
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/providers/sendgrid/response.ts
|
|
967
|
+
var STATUS_PREFIX = "HTTP/1.";
|
|
968
|
+
var TOKEN_PUNCTUATION = "!#$%&'*+-.^_`|~";
|
|
969
|
+
var IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/;
|
|
970
|
+
var REJECTIONS = /* @__PURE__ */ new Set([400, 401, 403, 404, 405, 413]);
|
|
971
|
+
var METADATA = /* @__PURE__ */ new Set([
|
|
972
|
+
"connection",
|
|
973
|
+
"content-length",
|
|
974
|
+
"content-encoding",
|
|
975
|
+
"content-type",
|
|
976
|
+
"transfer-encoding",
|
|
977
|
+
"trailer",
|
|
978
|
+
"upgrade",
|
|
979
|
+
"retry-after",
|
|
980
|
+
"x-ratelimit-reset",
|
|
981
|
+
"x-message-id"
|
|
982
|
+
]);
|
|
983
|
+
function isTokenByte(byte) {
|
|
984
|
+
return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || TOKEN_PUNCTUATION.includes(String.fromCharCode(byte));
|
|
985
|
+
}
|
|
986
|
+
function trimOws(value) {
|
|
987
|
+
const space = (index) => value[index] === " " || value[index] === " ";
|
|
988
|
+
let start = 0;
|
|
989
|
+
let end = value.length;
|
|
990
|
+
while (start < end && space(start)) start++;
|
|
991
|
+
while (end > start && space(end - 1)) end--;
|
|
992
|
+
return value.slice(start, end);
|
|
993
|
+
}
|
|
994
|
+
var ResponseWire = class {
|
|
995
|
+
size = 0;
|
|
996
|
+
headBytes = 0;
|
|
997
|
+
statusCode = 0;
|
|
998
|
+
httpVersion = "";
|
|
999
|
+
#lineBytes = 0;
|
|
1000
|
+
#statusLine = true;
|
|
1001
|
+
#colon = false;
|
|
1002
|
+
#cr = false;
|
|
1003
|
+
push(chunk) {
|
|
1004
|
+
const start = this.size;
|
|
1005
|
+
this.size += chunk.byteLength;
|
|
1006
|
+
if (this.size > SENDGRID_RESPONSE_MAX_BYTES) return false;
|
|
1007
|
+
if (this.headBytes) return true;
|
|
1008
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1009
|
+
const byte = chunk[i];
|
|
1010
|
+
if (this.#cr) {
|
|
1011
|
+
if (byte !== 10) return false;
|
|
1012
|
+
if (this.#statusLine) {
|
|
1013
|
+
if (this.#lineBytes < 13) return false;
|
|
1014
|
+
this.#statusLine = false;
|
|
1015
|
+
} else if (!this.#lineBytes) {
|
|
1016
|
+
this.headBytes = start + i + 1;
|
|
1017
|
+
return true;
|
|
1018
|
+
} else if (!this.#colon) return false;
|
|
1019
|
+
this.#cr = false;
|
|
1020
|
+
this.#colon = false;
|
|
1021
|
+
this.#lineBytes = 0;
|
|
1022
|
+
} else if (byte === 13) {
|
|
1023
|
+
this.#cr = true;
|
|
1024
|
+
} else {
|
|
1025
|
+
if (byte < 32 && byte !== 9 || byte === 127) return false;
|
|
1026
|
+
const pos = this.#lineBytes++;
|
|
1027
|
+
if (this.#statusLine) {
|
|
1028
|
+
if (!this.#statusByte(pos, byte)) return false;
|
|
1029
|
+
} else if (!this.#colon) {
|
|
1030
|
+
if (byte === 58 && pos > 0) this.#colon = true;
|
|
1031
|
+
else if (!isTokenByte(byte)) return false;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
return true;
|
|
1036
|
+
}
|
|
1037
|
+
#statusByte(pos, byte) {
|
|
1038
|
+
if (pos < STATUS_PREFIX.length) return byte === STATUS_PREFIX.charCodeAt(pos);
|
|
1039
|
+
if (pos === 7) {
|
|
1040
|
+
if (byte !== 48 && byte !== 49) return false;
|
|
1041
|
+
this.httpVersion = byte === 48 ? "1.0" : "1.1";
|
|
1042
|
+
}
|
|
1043
|
+
if (pos === 8 || pos === 12) return byte === 32;
|
|
1044
|
+
if (pos >= 9 && pos <= 11) {
|
|
1045
|
+
if (byte < (pos === 9 ? 49 : 48) || byte > (pos === 9 ? 53 : 57)) return false;
|
|
1046
|
+
this.statusCode = this.statusCode * 10 + byte - 48;
|
|
1047
|
+
}
|
|
1048
|
+
return true;
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
var ChunkFraming = class {
|
|
1052
|
+
#phase = "size";
|
|
1053
|
+
#size = 0;
|
|
1054
|
+
#digits = 0;
|
|
1055
|
+
get complete() {
|
|
1056
|
+
return this.#phase === "done";
|
|
1057
|
+
}
|
|
1058
|
+
push(chunk, offset) {
|
|
1059
|
+
while (offset < chunk.length) {
|
|
1060
|
+
if (this.#phase === "data") {
|
|
1061
|
+
const length = Math.min(this.#size, chunk.length - offset);
|
|
1062
|
+
offset += length;
|
|
1063
|
+
this.#size -= length;
|
|
1064
|
+
if (!this.#size) this.#phase = "dataCr";
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
const byte = chunk[offset++];
|
|
1068
|
+
switch (this.#phase) {
|
|
1069
|
+
case "size": {
|
|
1070
|
+
if (byte === 13 && this.#digits) {
|
|
1071
|
+
this.#phase = "sizeLf";
|
|
1072
|
+
} else {
|
|
1073
|
+
const digit = byte >= 48 && byte <= 57 ? byte - 48 : (byte | 32) - 87;
|
|
1074
|
+
if ((byte < 48 || byte > 57) && ((byte | 32) < 97 || (byte | 32) > 102)) return false;
|
|
1075
|
+
this.#size = this.#size * 16 + digit;
|
|
1076
|
+
if (this.#size > SENDGRID_RESPONSE_MAX_BYTES) return false;
|
|
1077
|
+
this.#digits++;
|
|
1078
|
+
}
|
|
1079
|
+
break;
|
|
1080
|
+
}
|
|
1081
|
+
case "sizeLf":
|
|
1082
|
+
if (byte !== 10) return false;
|
|
1083
|
+
this.#digits = 0;
|
|
1084
|
+
this.#phase = this.#size ? "data" : "endCr";
|
|
1085
|
+
break;
|
|
1086
|
+
case "dataCr":
|
|
1087
|
+
if (byte !== 13) return false;
|
|
1088
|
+
this.#phase = "dataLf";
|
|
1089
|
+
break;
|
|
1090
|
+
case "dataLf":
|
|
1091
|
+
if (byte !== 10) return false;
|
|
1092
|
+
this.#phase = "size";
|
|
1093
|
+
break;
|
|
1094
|
+
case "endCr":
|
|
1095
|
+
if (byte !== 13) return false;
|
|
1096
|
+
this.#phase = "endLf";
|
|
1097
|
+
break;
|
|
1098
|
+
case "endLf":
|
|
1099
|
+
if (byte !== 10) return false;
|
|
1100
|
+
this.#phase = "done";
|
|
1101
|
+
break;
|
|
1102
|
+
case "done":
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
return true;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
function readResponseHead(response, wire, mode, apiKey, now) {
|
|
1110
|
+
const { rawHeaders, httpVersion, statusCode } = response;
|
|
1111
|
+
if (!wire.headBytes || statusCode !== wire.statusCode || httpVersion !== wire.httpVersion || rawHeaders.length % 2) {
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1115
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
1116
|
+
const name = rawHeaders[i].toLowerCase();
|
|
1117
|
+
if (!METADATA.has(name)) continue;
|
|
1118
|
+
fields.set(name, fields.has(name) ? null : trimOws(rawHeaders[i + 1]));
|
|
1119
|
+
}
|
|
1120
|
+
const length = fields.get("content-length");
|
|
1121
|
+
const transfer = fields.get("transfer-encoding");
|
|
1122
|
+
const encoding = fields.get("content-encoding");
|
|
1123
|
+
if (encoding !== void 0 && encoding?.toLowerCase() !== "identity" || fields.get("connection") === null || fields.get("content-type") === null || fields.has("trailer") || fields.has("upgrade")) {
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
let framing;
|
|
1127
|
+
if (transfer !== void 0) {
|
|
1128
|
+
if (transfer?.toLowerCase() !== "chunked" || length !== void 0 || httpVersion !== "1.1") return;
|
|
1129
|
+
framing = "chunked";
|
|
1130
|
+
} else {
|
|
1131
|
+
if (typeof length !== "string" || !/^\d+$/.test(length)) return;
|
|
1132
|
+
framing = Number(length);
|
|
1133
|
+
if (framing > SENDGRID_RESPONSE_MAX_BYTES - wire.headBytes) return;
|
|
1134
|
+
}
|
|
1135
|
+
const stage = "http";
|
|
1136
|
+
let result;
|
|
1137
|
+
if (statusCode === 202 && mode === "live") {
|
|
1138
|
+
const id = fields.get("x-message-id");
|
|
1139
|
+
result = {
|
|
1140
|
+
outcome: "accepted",
|
|
1141
|
+
retry: "never",
|
|
1142
|
+
stage,
|
|
1143
|
+
reason: "sendgrid_accepted",
|
|
1144
|
+
// An opaque provider ID is optional; do not expose an echoed credential, even with a prefix/suffix.
|
|
1145
|
+
...id && IDENTIFIER.test(id) && !id.includes(apiKey) ? { providerMessageId: id } : {}
|
|
1146
|
+
};
|
|
1147
|
+
} else if (statusCode === 200 && mode === "sandbox") {
|
|
1148
|
+
result = { outcome: "validated", retry: "never", stage, reason: "sendgrid_validated" };
|
|
1149
|
+
} else if (statusCode === 429) {
|
|
1150
|
+
const after = fields.get("retry-after");
|
|
1151
|
+
const reset = fields.get("x-ratelimit-reset");
|
|
1152
|
+
if (after === null || reset === null) return;
|
|
1153
|
+
const hint = retryHint(after, reset, now);
|
|
1154
|
+
result = {
|
|
1155
|
+
outcome: "rejected",
|
|
1156
|
+
retry: "safe_transient",
|
|
1157
|
+
stage,
|
|
1158
|
+
reason: "sendgrid_throttled",
|
|
1159
|
+
...hint ? { retryHint: hint } : {}
|
|
1160
|
+
};
|
|
1161
|
+
} else if (REJECTIONS.has(statusCode)) {
|
|
1162
|
+
result = { outcome: "rejected", retry: "never", stage, reason: "sendgrid_rejected" };
|
|
1163
|
+
} else {
|
|
1164
|
+
result = { outcome: "unknown", retry: "never", stage, reason: "transport_uncertain" };
|
|
1165
|
+
}
|
|
1166
|
+
return { framing, result };
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// src/providers/sendgrid/submit.ts
|
|
1170
|
+
var SENDGRID_HOST = "api.sendgrid.com";
|
|
1171
|
+
var PORT = 443;
|
|
1172
|
+
var PATH = "/v3/mail/send";
|
|
1173
|
+
var nodeIo = Object.freeze({
|
|
1174
|
+
resolver: (timeout) => new Resolver({ timeout, tries: 1 }),
|
|
1175
|
+
connect: connectTls,
|
|
1176
|
+
request: httpsRequest
|
|
1177
|
+
});
|
|
1178
|
+
var transient = /* @__PURE__ */ new Set([
|
|
1179
|
+
"EAI_AGAIN",
|
|
1180
|
+
"ECONNABORTED",
|
|
1181
|
+
"ECONNREFUSED",
|
|
1182
|
+
"ECONNRESET",
|
|
1183
|
+
"EHOSTUNREACH",
|
|
1184
|
+
"ENETDOWN",
|
|
1185
|
+
"ENETUNREACH",
|
|
1186
|
+
"EPIPE",
|
|
1187
|
+
"EREFUSED",
|
|
1188
|
+
"ESERVFAIL",
|
|
1189
|
+
"ETIMEOUT",
|
|
1190
|
+
"ETIMEDOUT"
|
|
1191
|
+
]);
|
|
1192
|
+
var tlsConfiguration = /* @__PURE__ */ new Set([
|
|
1193
|
+
"CERT_HAS_EXPIRED",
|
|
1194
|
+
"CERT_NOT_YET_VALID",
|
|
1195
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
1196
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
1197
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
1198
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
1199
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
1200
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
1201
|
+
"ERR_SSL_UNSUPPORTED_PROTOCOL",
|
|
1202
|
+
"ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION"
|
|
1203
|
+
]);
|
|
1204
|
+
function submitSendGrid(mode, apiKey, body, call, io = nodeIo) {
|
|
1205
|
+
const clock = io.clock ?? systemEmailClock;
|
|
1206
|
+
const budget = createBudget(clock, call.timeoutMs, call.signal);
|
|
1207
|
+
return new Promise((resolve) => {
|
|
1208
|
+
const wire = new ResponseWire();
|
|
1209
|
+
let stage = "connect";
|
|
1210
|
+
let settled = false;
|
|
1211
|
+
let dns;
|
|
1212
|
+
let socket;
|
|
1213
|
+
let socketClosed = false;
|
|
1214
|
+
let request;
|
|
1215
|
+
let response;
|
|
1216
|
+
let payload = body;
|
|
1217
|
+
let chunks;
|
|
1218
|
+
const listener = addAbortListener2(budget.signal, stopped);
|
|
1219
|
+
function finish(result) {
|
|
1220
|
+
if (settled) return;
|
|
1221
|
+
settled = true;
|
|
1222
|
+
listener[Symbol.dispose]();
|
|
1223
|
+
budget.close();
|
|
1224
|
+
const pendingDns = dns;
|
|
1225
|
+
dns = void 0;
|
|
1226
|
+
pendingDns?.cancel();
|
|
1227
|
+
payload = void 0;
|
|
1228
|
+
socket?.off("data", onWire);
|
|
1229
|
+
socket?.off("data", onChunkFrame);
|
|
1230
|
+
response?.destroy();
|
|
1231
|
+
request?.destroy();
|
|
1232
|
+
socket?.destroy();
|
|
1233
|
+
queueMicrotask(() => {
|
|
1234
|
+
if (!socket || socketClosed) resolve(result);
|
|
1235
|
+
else socket.once("close", () => resolve(result));
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
function fail(reason = "transport_uncertain") {
|
|
1239
|
+
if (reason === "not_transmitted") finish({ outcome: "unsubmitted", retry: "safe_transient", stage, reason });
|
|
1240
|
+
else if (reason === "provider_configuration") finish({ outcome: "unsubmitted", retry: "never", stage, reason });
|
|
1241
|
+
else finish({ outcome: "unknown", retry: "never", stage, reason });
|
|
1242
|
+
}
|
|
1243
|
+
function stopped() {
|
|
1244
|
+
const code = budget.signal.reason?.code;
|
|
1245
|
+
fail(code === "deadline" ? "provider_timeout" : code === "aborted" ? "provider_aborted" : "transport_uncertain");
|
|
1246
|
+
}
|
|
1247
|
+
function live() {
|
|
1248
|
+
if (settled) return false;
|
|
1249
|
+
try {
|
|
1250
|
+
budget.check();
|
|
1251
|
+
return true;
|
|
1252
|
+
} catch {
|
|
1253
|
+
stopped();
|
|
1254
|
+
return false;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
function lost() {
|
|
1258
|
+
if (live()) fail();
|
|
1259
|
+
}
|
|
1260
|
+
function socketError(error) {
|
|
1261
|
+
if (!live()) return;
|
|
1262
|
+
const code = error.code ?? "";
|
|
1263
|
+
if (stage === "http") return fail();
|
|
1264
|
+
if (tlsConfiguration.has(code)) {
|
|
1265
|
+
stage = "tls";
|
|
1266
|
+
fail("provider_configuration");
|
|
1267
|
+
} else fail(transient.has(code) ? "not_transmitted" : "transport_uncertain");
|
|
1268
|
+
}
|
|
1269
|
+
function onWire(chunk) {
|
|
1270
|
+
if (live() && !wire.push(chunk)) fail();
|
|
1271
|
+
}
|
|
1272
|
+
function onChunkFrame(chunk) {
|
|
1273
|
+
if (live() && chunks && !chunks.push(chunk, Math.max(0, wire.headBytes - (wire.size - chunk.length)))) fail();
|
|
1274
|
+
}
|
|
1275
|
+
function onResponse(incoming) {
|
|
1276
|
+
incoming.on("error", lost);
|
|
1277
|
+
if (!live() || response) {
|
|
1278
|
+
incoming.destroy();
|
|
1279
|
+
return lost();
|
|
1280
|
+
}
|
|
1281
|
+
response = incoming;
|
|
1282
|
+
incoming.once("aborted", lost);
|
|
1283
|
+
incoming.once("close", lost);
|
|
1284
|
+
const head = readResponseHead(incoming, wire, mode, apiKey, clock.now());
|
|
1285
|
+
if (!head) return fail();
|
|
1286
|
+
if (head.framing === "chunked") chunks = new ChunkFraming();
|
|
1287
|
+
let bytes = 0;
|
|
1288
|
+
incoming.on("data", (chunk) => {
|
|
1289
|
+
if (!live()) return;
|
|
1290
|
+
bytes += chunk.byteLength;
|
|
1291
|
+
if (bytes > SENDGRID_RESPONSE_MAX_BYTES || head.framing !== "chunked" && bytes > head.framing) fail();
|
|
1292
|
+
});
|
|
1293
|
+
incoming.once("end", () => {
|
|
1294
|
+
if (!live()) return;
|
|
1295
|
+
if (!incoming.complete || incoming.rawTrailers.length || (head.framing === "chunked" ? !chunks?.complete : bytes !== head.framing || wire.size !== wire.headBytes + bytes) || (head.result.outcome === "accepted" || head.result.outcome === "validated") && !request?.writableFinished) {
|
|
1296
|
+
return fail();
|
|
1297
|
+
}
|
|
1298
|
+
finish(head.result);
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
function post(secured) {
|
|
1302
|
+
if (!live()) return;
|
|
1303
|
+
if (!secured.authorized || secured.alpnProtocol && secured.alpnProtocol !== "http/1.1") {
|
|
1304
|
+
return fail("provider_configuration");
|
|
1305
|
+
}
|
|
1306
|
+
stage = "http";
|
|
1307
|
+
try {
|
|
1308
|
+
const req = io.request({
|
|
1309
|
+
protocol: "https:",
|
|
1310
|
+
hostname: SENDGRID_HOST,
|
|
1311
|
+
port: PORT,
|
|
1312
|
+
method: "POST",
|
|
1313
|
+
path: PATH,
|
|
1314
|
+
// No agent (including the global one), proxy, implicit dial, session cache or connection sharing.
|
|
1315
|
+
createConnection: () => secured,
|
|
1316
|
+
insecureHTTPParser: false,
|
|
1317
|
+
maxHeaderSize: SENDGRID_RESPONSE_MAX_BYTES,
|
|
1318
|
+
headers: {
|
|
1319
|
+
Host: SENDGRID_HOST,
|
|
1320
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1321
|
+
"Content-Type": "application/json",
|
|
1322
|
+
"Content-Length": payload.length,
|
|
1323
|
+
"Accept-Encoding": "identity",
|
|
1324
|
+
Connection: "close"
|
|
1325
|
+
}
|
|
1326
|
+
});
|
|
1327
|
+
request = req;
|
|
1328
|
+
req.maxHeadersCount = 0;
|
|
1329
|
+
req.on("error", lost);
|
|
1330
|
+
req.once("close", lost);
|
|
1331
|
+
req.on("response", onResponse);
|
|
1332
|
+
req.on("information", lost);
|
|
1333
|
+
req.on("upgrade", (incoming, wireSocket) => {
|
|
1334
|
+
incoming.on("error", lost);
|
|
1335
|
+
incoming.destroy();
|
|
1336
|
+
wireSocket.destroy();
|
|
1337
|
+
lost();
|
|
1338
|
+
});
|
|
1339
|
+
req.once("socket", (assigned) => {
|
|
1340
|
+
if (!live() || assigned !== secured || assigned.destroyed) {
|
|
1341
|
+
assigned.destroy();
|
|
1342
|
+
return lost();
|
|
1343
|
+
}
|
|
1344
|
+
assigned.prependListener("data", onWire);
|
|
1345
|
+
assigned.on("data", onChunkFrame);
|
|
1346
|
+
if (!live()) return;
|
|
1347
|
+
try {
|
|
1348
|
+
const bytes = payload;
|
|
1349
|
+
payload = void 0;
|
|
1350
|
+
req.end(bytes);
|
|
1351
|
+
} catch {
|
|
1352
|
+
lost();
|
|
1353
|
+
}
|
|
1354
|
+
});
|
|
1355
|
+
if (!live()) req.destroy();
|
|
1356
|
+
} catch {
|
|
1357
|
+
lost();
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
function dial(address) {
|
|
1361
|
+
if (!live()) return;
|
|
1362
|
+
try {
|
|
1363
|
+
const secured = io.connect({
|
|
1364
|
+
host: address,
|
|
1365
|
+
port: PORT,
|
|
1366
|
+
servername: SENDGRID_HOST,
|
|
1367
|
+
checkServerIdentity: (_hostname, cert) => checkServerIdentity(SENDGRID_HOST, cert),
|
|
1368
|
+
rejectUnauthorized: true,
|
|
1369
|
+
minVersion: "TLSv1.2",
|
|
1370
|
+
ALPNProtocols: ["http/1.1"],
|
|
1371
|
+
autoSelectFamily: false
|
|
1372
|
+
});
|
|
1373
|
+
socket = secured;
|
|
1374
|
+
secured.on("error", socketError);
|
|
1375
|
+
secured.once("close", () => {
|
|
1376
|
+
socketClosed = true;
|
|
1377
|
+
lost();
|
|
1378
|
+
});
|
|
1379
|
+
secured.once("connect", () => {
|
|
1380
|
+
if (stage === "connect" && live()) stage = "tls";
|
|
1381
|
+
});
|
|
1382
|
+
secured.once("secureConnect", () => {
|
|
1383
|
+
if (!live() || secured.destroyed) return lost();
|
|
1384
|
+
stage = "tls";
|
|
1385
|
+
post(secured);
|
|
1386
|
+
});
|
|
1387
|
+
if (!live()) secured.destroy();
|
|
1388
|
+
} catch {
|
|
1389
|
+
lost();
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
if (!live()) return;
|
|
1393
|
+
try {
|
|
1394
|
+
const remaining = Math.ceil(budget.remainingMs());
|
|
1395
|
+
if (!remaining) return;
|
|
1396
|
+
const resolver = io.resolver(remaining);
|
|
1397
|
+
if (!live()) return resolver.cancel();
|
|
1398
|
+
dns = resolver;
|
|
1399
|
+
const errors = [];
|
|
1400
|
+
const resolved = (error, addresses) => {
|
|
1401
|
+
if (dns !== resolver || !live()) return;
|
|
1402
|
+
const address = !error && addresses.find((value) => isIP2(value) !== 0);
|
|
1403
|
+
if (address) {
|
|
1404
|
+
dns = void 0;
|
|
1405
|
+
resolver.cancel();
|
|
1406
|
+
dial(address);
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
errors.push(error?.code ?? "");
|
|
1410
|
+
if (errors.length !== 2) return;
|
|
1411
|
+
if (errors.some((code) => transient.has(code))) fail("not_transmitted");
|
|
1412
|
+
else if (errors.every((code) => code === "ENODATA" || code === "ENOTFOUND")) fail("provider_configuration");
|
|
1413
|
+
else fail();
|
|
1414
|
+
};
|
|
1415
|
+
resolver.resolve4(SENDGRID_HOST, resolved);
|
|
1416
|
+
if (dns === resolver && live()) resolver.resolve6(SENDGRID_HOST, resolved);
|
|
1417
|
+
} catch {
|
|
1418
|
+
lost();
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// src/providers/sendgrid/profile.ts
|
|
1424
|
+
function mailbox({ address, name }) {
|
|
1425
|
+
return { email: address, ...name === void 0 ? {} : { name } };
|
|
1426
|
+
}
|
|
1427
|
+
function encode({ snapshot, attachments }) {
|
|
1428
|
+
const { envelope, templateId, data, provider } = snapshot;
|
|
1429
|
+
const { from, replyTo, to, cc, bcc } = envelope;
|
|
1430
|
+
const payload = JSON.stringify({
|
|
1431
|
+
personalizations: [
|
|
1432
|
+
{
|
|
1433
|
+
to: to.map(mailbox),
|
|
1434
|
+
...cc.length ? { cc: cc.map(mailbox) } : {},
|
|
1435
|
+
...bcc.length ? { bcc: bcc.map(mailbox) } : {},
|
|
1436
|
+
dynamic_template_data: data
|
|
1437
|
+
}
|
|
1438
|
+
],
|
|
1439
|
+
from: mailbox(from),
|
|
1440
|
+
...replyTo ? { reply_to: mailbox(replyTo) } : {},
|
|
1441
|
+
template_id: templateId,
|
|
1442
|
+
...provider.mode === "sandbox" ? { mail_settings: { sandbox_mode: { enable: true } } } : {},
|
|
1443
|
+
...attachments.length ? {
|
|
1444
|
+
attachments: attachments.map(({ ref, bytes }) => ({
|
|
1445
|
+
content: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"),
|
|
1446
|
+
filename: ref.filename,
|
|
1447
|
+
type: ref.contentType,
|
|
1448
|
+
disposition: "attachment"
|
|
1449
|
+
}))
|
|
1450
|
+
} : {}
|
|
1451
|
+
});
|
|
1452
|
+
if (Buffer.byteLength(payload) > SENDGRID_REQUEST_MAX_BYTES) invalid("invalid_snapshot");
|
|
1453
|
+
return Buffer.from(payload);
|
|
1454
|
+
}
|
|
1455
|
+
function createSendGridProfile(options, io) {
|
|
1456
|
+
const code = "invalid_config";
|
|
1457
|
+
const raw = readRecord(options, ["key", "apiKey"], ["mode"], code);
|
|
1458
|
+
const mode = Object.hasOwn(raw, "mode") ? raw.mode : SENDGRID_DEFAULT_MODE;
|
|
1459
|
+
if (mode !== "live" && mode !== "sandbox") invalid(code);
|
|
1460
|
+
const key = identifier(raw.key, code);
|
|
1461
|
+
const apiKey = headerString(raw.apiKey, 1024, code);
|
|
1462
|
+
if (!/^[A-Za-z0-9._~+/-]+=*$/.test(apiKey)) invalid(code);
|
|
1463
|
+
const ref = Object.freeze({ kind: "sendgrid", key, mode });
|
|
1464
|
+
const provider = {
|
|
1465
|
+
ref,
|
|
1466
|
+
prepare(input) {
|
|
1467
|
+
const prepared = readProviderSubmission(input, ref);
|
|
1468
|
+
const {
|
|
1469
|
+
attemptId,
|
|
1470
|
+
snapshot: { envelope }
|
|
1471
|
+
} = prepared;
|
|
1472
|
+
let body = encode(prepared);
|
|
1473
|
+
return Object.freeze({
|
|
1474
|
+
async submit(context) {
|
|
1475
|
+
if (!body) invalid("closed");
|
|
1476
|
+
const call = readProviderCall(context);
|
|
1477
|
+
const payload = body;
|
|
1478
|
+
body = void 0;
|
|
1479
|
+
const result = await submitSendGrid(mode, apiKey, payload, call, io);
|
|
1480
|
+
return readProviderResult(result, ref, attemptId, envelope);
|
|
1481
|
+
}
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
};
|
|
1485
|
+
return Object.freeze(provider);
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// src/sendgrid.ts
|
|
1489
|
+
function createSendGridProvider(options) {
|
|
1490
|
+
return createSendGridProfile(options);
|
|
1491
|
+
}
|
|
1492
|
+
export {
|
|
1493
|
+
createSendGridProvider
|
|
1494
|
+
};
|