@mailstest/playwright 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +365 -2
- package/dist/client-BkgYBSna.d.ts +415 -0
- package/dist/client-Bq5lAfzY.js +651 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +1 -0
- package/dist/fixtures.d.ts +144 -0
- package/dist/fixtures.js +152 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +202 -0
- package/package.json +79 -3
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// src/extract.ts
|
|
3
|
+
/** A bare URL in a text part, up to whitespace, `<`, `>` or a quote. */
|
|
4
|
+
const TEXT_URL = /https?:\/\/[^\s<>"']+/gi;
|
|
5
|
+
/**
|
|
6
|
+
* Sentence punctuation a URL at the end of a sentence collects; a closing
|
|
7
|
+
* bracket only ends the URL when the URL does not open one itself. One linear
|
|
8
|
+
* pass: each bracket kind's surplus of closers is counted once, then the end
|
|
9
|
+
* walks back.
|
|
10
|
+
*/
|
|
11
|
+
function trimTrailing(url) {
|
|
12
|
+
const surplus = {
|
|
13
|
+
")": 0,
|
|
14
|
+
"]": 0,
|
|
15
|
+
"}": 0
|
|
16
|
+
};
|
|
17
|
+
for (const ch of url) if (ch === ")" || ch === "]" || ch === "}") surplus[ch]++;
|
|
18
|
+
else if (ch === "(") surplus[")"]--;
|
|
19
|
+
else if (ch === "[") surplus["]"]--;
|
|
20
|
+
else if (ch === "{") surplus["}"]--;
|
|
21
|
+
let end = url.length;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const last = url[end - 1];
|
|
24
|
+
if (last === void 0) break;
|
|
25
|
+
if (".,;:!?".includes(last)) end--;
|
|
26
|
+
else if ((last === ")" || last === "]" || last === "}") && surplus[last] > 0) {
|
|
27
|
+
surplus[last]--;
|
|
28
|
+
end--;
|
|
29
|
+
} else break;
|
|
30
|
+
}
|
|
31
|
+
return url.slice(0, end);
|
|
32
|
+
}
|
|
33
|
+
const NAMED = {
|
|
34
|
+
amp: "&",
|
|
35
|
+
lt: "<",
|
|
36
|
+
gt: ">",
|
|
37
|
+
quot: "\"",
|
|
38
|
+
apos: "'",
|
|
39
|
+
nbsp: "\xA0"
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Decodes numeric references and the five XML entities plus `nbsp`.
|
|
43
|
+
* shortcut: no table of the other HTML named entities, so `©` stays as
|
|
44
|
+
* written; a token or a code never sits behind one, upgrade to a full table if
|
|
45
|
+
* that changes.
|
|
46
|
+
*/
|
|
47
|
+
function decodeEntities(s) {
|
|
48
|
+
return s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (m, dec, hex, name) => {
|
|
49
|
+
if (name) return NAMED[name.toLowerCase()] ?? m;
|
|
50
|
+
const cp = dec !== void 0 ? Number(dec) : Number.parseInt(hex, 16);
|
|
51
|
+
return cp > 0 && cp <= 1114111 && !(cp >= 55296 && cp <= 57343) ? String.fromCodePoint(cp) : m;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/** Elements whose content is never text and never holds a link. */
|
|
55
|
+
const RAW_TEXT = /* @__PURE__ */ new Set([
|
|
56
|
+
"script",
|
|
57
|
+
"style",
|
|
58
|
+
"title",
|
|
59
|
+
"textarea"
|
|
60
|
+
]);
|
|
61
|
+
const TAG = /<!--[\s\S]*?(?:-->|$)|<(\/?)([a-zA-Z][^\s/>]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>?/g;
|
|
62
|
+
const ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g;
|
|
63
|
+
/** Walks the markup's tags in order; raw-text elements are skipped whole. */
|
|
64
|
+
function* tags(html) {
|
|
65
|
+
TAG.lastIndex = 0;
|
|
66
|
+
for (let m = TAG.exec(html); m; m = TAG.exec(html)) {
|
|
67
|
+
if (m[2] === void 0) continue;
|
|
68
|
+
const name = m[2].toLowerCase();
|
|
69
|
+
yield {
|
|
70
|
+
closing: m[1] === "/",
|
|
71
|
+
name,
|
|
72
|
+
attributes: m[3] ?? "",
|
|
73
|
+
start: m.index,
|
|
74
|
+
end: TAG.lastIndex
|
|
75
|
+
};
|
|
76
|
+
if (m[1] !== "/" && RAW_TEXT.has(name)) {
|
|
77
|
+
const close = new RegExp(`</${name}[\\s/>]`, "i");
|
|
78
|
+
const at = html.slice(TAG.lastIndex).search(close);
|
|
79
|
+
TAG.lastIndex = at === -1 ? html.length : TAG.lastIndex + at;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function hrefOf(attributes) {
|
|
84
|
+
ATTRIBUTE.lastIndex = 0;
|
|
85
|
+
for (let a = ATTRIBUTE.exec(attributes); a; a = ATTRIBUTE.exec(attributes)) if (a[1]?.toLowerCase() === "href") return decodeEntities(a[2] ?? a[3] ?? a[4] ?? "");
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The links of the message's own parts, as written: HTML anchors (`a`, `area`
|
|
89
|
+
* with an `href`) in document order, then the text part's URLs, each distinct
|
|
90
|
+
* value once at its first occurrence. Comments, script, style, title and
|
|
91
|
+
* textarea hold none.
|
|
92
|
+
*/
|
|
93
|
+
function extractLinks(message) {
|
|
94
|
+
const seen = /* @__PURE__ */ new Set();
|
|
95
|
+
const links = [];
|
|
96
|
+
const add = (url, source) => {
|
|
97
|
+
if (seen.has(url)) return;
|
|
98
|
+
seen.add(url);
|
|
99
|
+
links.push({
|
|
100
|
+
url,
|
|
101
|
+
source
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
if (message.html) for (const tag of tags(message.html)) {
|
|
105
|
+
if (tag.closing || tag.name !== "a" && tag.name !== "area") continue;
|
|
106
|
+
const href = hrefOf(tag.attributes);
|
|
107
|
+
if (href !== void 0) add(href, "html");
|
|
108
|
+
}
|
|
109
|
+
for (const m of (message.text ?? "").matchAll(TEXT_URL)) add(trimTrailing(m[0]), "text");
|
|
110
|
+
return links;
|
|
111
|
+
}
|
|
112
|
+
const BLOCK = /^(?:address|article|aside|blockquote|br|caption|center|dd|details|div|dl|dt|fieldset|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|td|th|tr|ul)$/;
|
|
113
|
+
/** The text a reader sees: no comments, script, style or tags (an attribute is never text), entities decoded, a line break at each block. */
|
|
114
|
+
function visibleText(html) {
|
|
115
|
+
let out = "";
|
|
116
|
+
let at = 0;
|
|
117
|
+
for (const tag of tags(html)) {
|
|
118
|
+
out += html.slice(at, tag.start);
|
|
119
|
+
at = tag.end;
|
|
120
|
+
if (BLOCK.test(tag.name)) out += "\n";
|
|
121
|
+
if (!tag.closing && RAW_TEXT.has(tag.name)) {
|
|
122
|
+
const close = new RegExp(`</${tag.name}[\\s/>]`, "i");
|
|
123
|
+
const skip = html.slice(at).search(close);
|
|
124
|
+
at = skip === -1 ? html.length : at + skip;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
out += html.slice(at);
|
|
128
|
+
return decodeEntities(out.replace(/<!--[\s\S]*?(?:-->|$)/g, ""));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The codes a pattern finds in the subject, then the text part, then the HTML
|
|
132
|
+
* part's visible text. `pattern` is a string or a `RegExp`, matched globally
|
|
133
|
+
* with JavaScript's engine. A value is the first capturing group when it took
|
|
134
|
+
* part, else the whole match; empty values are skipped; each value once.
|
|
135
|
+
*/
|
|
136
|
+
function extractCodes(message, pattern) {
|
|
137
|
+
const re = typeof pattern === "string" ? new RegExp(pattern, "g") : new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`);
|
|
138
|
+
const seen = /* @__PURE__ */ new Set();
|
|
139
|
+
const codes = [];
|
|
140
|
+
const scan = (haystack, source) => {
|
|
141
|
+
for (const m of (haystack ?? "").matchAll(re)) {
|
|
142
|
+
const value = m[1] ?? m[0];
|
|
143
|
+
if (!value || seen.has(value)) continue;
|
|
144
|
+
seen.add(value);
|
|
145
|
+
codes.push({
|
|
146
|
+
value,
|
|
147
|
+
source
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
scan(message.subject, "subject");
|
|
152
|
+
scan(message.text, "text");
|
|
153
|
+
scan(message.html ? visibleText(message.html) : null, "html");
|
|
154
|
+
return codes;
|
|
155
|
+
}
|
|
156
|
+
// src/schemas.ts
|
|
157
|
+
/** The limits an inbox's plan sets: the ring it keeps, the days a message lives, the inboxes the workspace may hold and the largest message it accepts. */
|
|
158
|
+
const inboxLimits = z.object({
|
|
159
|
+
ring: z.number().int(),
|
|
160
|
+
retentionDays: z.number().int(),
|
|
161
|
+
inboxes: z.number().int(),
|
|
162
|
+
maxMessageBytes: z.number().int()
|
|
163
|
+
});
|
|
164
|
+
/** An inbox's identity; no password lives here. */
|
|
165
|
+
const inboxSummary = z.object({
|
|
166
|
+
id: z.string(),
|
|
167
|
+
name: z.string(),
|
|
168
|
+
username: z.string()
|
|
169
|
+
});
|
|
170
|
+
/** One row of the inbox list: the identity, the mail it holds, whether capture is frozen, and its limits. */
|
|
171
|
+
const inboxListItem = inboxSummary.extend({
|
|
172
|
+
emailCount: z.number().int(),
|
|
173
|
+
lastEmailAt: z.string().nullable(),
|
|
174
|
+
frozen: z.boolean(),
|
|
175
|
+
limits: inboxLimits
|
|
176
|
+
});
|
|
177
|
+
/** The workspace's inboxes, with the plan's limits on their own for a workspace that has none. */
|
|
178
|
+
const listInboxesResponse = z.object({
|
|
179
|
+
inboxes: z.array(inboxListItem),
|
|
180
|
+
limits: inboxLimits
|
|
181
|
+
});
|
|
182
|
+
/** When the inbox stops; null for a durable inbox. */
|
|
183
|
+
const inboxStopsAt = z.string().datetime().nullable();
|
|
184
|
+
/** An inbox's SMTP credential as a create answers it: the password once, or null on a replay of the same idempotency key. */
|
|
185
|
+
const credentialRevealResponse = z.discriminatedUnion("replayed", [inboxSummary.extend({
|
|
186
|
+
password: z.string(),
|
|
187
|
+
replayed: z.literal(false),
|
|
188
|
+
expiresAt: inboxStopsAt
|
|
189
|
+
}), inboxSummary.extend({
|
|
190
|
+
password: z.null(),
|
|
191
|
+
replayed: z.literal(true),
|
|
192
|
+
expiresAt: inboxStopsAt
|
|
193
|
+
})]);
|
|
194
|
+
/** An inbox delete's receipt. */
|
|
195
|
+
const deleteInboxResponse = z.object({ deleted: z.literal(true) });
|
|
196
|
+
/** A clear's receipt: how many messages it removed. */
|
|
197
|
+
const clearMessagesResponse = z.object({
|
|
198
|
+
cleared: z.literal(true),
|
|
199
|
+
count: z.number().int().nonnegative()
|
|
200
|
+
});
|
|
201
|
+
/** A message delete's receipt. */
|
|
202
|
+
const deleteMessageResponse = deleteInboxResponse;
|
|
203
|
+
/** A pin or unpin's answer: the message and its resulting state. */
|
|
204
|
+
const setPinnedResponse = z.object({
|
|
205
|
+
id: z.string(),
|
|
206
|
+
pinned: z.boolean()
|
|
207
|
+
});
|
|
208
|
+
/** One captured message as a list row; `deliveredTo` holds the envelope recipients, a Bcc'd address included. */
|
|
209
|
+
const messageSummary = z.object({
|
|
210
|
+
id: z.string(),
|
|
211
|
+
senderName: z.string().nullable(),
|
|
212
|
+
senderAddress: z.string().nullable(),
|
|
213
|
+
subject: z.string().nullable(),
|
|
214
|
+
sizeBytes: z.number().int(),
|
|
215
|
+
parseFailed: z.boolean(),
|
|
216
|
+
createdAt: z.string(),
|
|
217
|
+
expiresAt: z.string(),
|
|
218
|
+
pinned: z.boolean(),
|
|
219
|
+
deliveredTo: z.array(z.string())
|
|
220
|
+
});
|
|
221
|
+
/** One page of an inbox's messages, newest first; `nextCursor` is null once none remains. */
|
|
222
|
+
const listMessagesResponse = z.object({
|
|
223
|
+
messages: z.array(messageSummary),
|
|
224
|
+
nextCursor: z.string().nullable()
|
|
225
|
+
});
|
|
226
|
+
/** One header as received. */
|
|
227
|
+
const messageHeader = z.object({
|
|
228
|
+
name: z.string(),
|
|
229
|
+
value: z.string()
|
|
230
|
+
});
|
|
231
|
+
/** One attachment's manifest entry, never its bytes. */
|
|
232
|
+
const messageAttachment = z.object({
|
|
233
|
+
index: z.number().int(),
|
|
234
|
+
filename: z.string().nullable(),
|
|
235
|
+
contentType: z.string(),
|
|
236
|
+
disposition: z.enum(["inline", "attachment"]),
|
|
237
|
+
sizeBytes: z.number().int(),
|
|
238
|
+
cid: z.string().nullable()
|
|
239
|
+
});
|
|
240
|
+
/** One message decoded once at capture: its parts, headers and attachment manifest. */
|
|
241
|
+
const messageDetailResponse = z.object({
|
|
242
|
+
id: z.string(),
|
|
243
|
+
senderName: z.string().nullable(),
|
|
244
|
+
senderAddress: z.string().nullable(),
|
|
245
|
+
subject: z.string().nullable(),
|
|
246
|
+
recipients: z.object({
|
|
247
|
+
to: z.array(z.string()),
|
|
248
|
+
cc: z.array(z.string())
|
|
249
|
+
}),
|
|
250
|
+
deliveredTo: z.array(z.string()),
|
|
251
|
+
date: z.string().nullable(),
|
|
252
|
+
messageId: z.string().nullable(),
|
|
253
|
+
sizeBytes: z.number().int(),
|
|
254
|
+
parseFailed: z.boolean(),
|
|
255
|
+
expiresAt: z.string(),
|
|
256
|
+
pinned: z.boolean(),
|
|
257
|
+
text: z.string().nullable(),
|
|
258
|
+
html: z.string().nullable(),
|
|
259
|
+
headers: z.array(messageHeader),
|
|
260
|
+
attachments: z.array(messageAttachment)
|
|
261
|
+
});
|
|
262
|
+
/** A wait's outcome: the message that arrived, or the structured timeout; never both, never neither. */
|
|
263
|
+
const waitForEmailResponse = z.object({
|
|
264
|
+
timedOut: z.boolean(),
|
|
265
|
+
message: messageSummary.nullable()
|
|
266
|
+
}).superRefine((value, ctx) => {
|
|
267
|
+
if (value.timedOut === (value.message !== null)) ctx.addIssue({
|
|
268
|
+
code: "custom",
|
|
269
|
+
message: "exactly one outcome: an arrived message (timedOut=false) or a timeout (timedOut=true, message=null)"
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
/** What every key reveal names; never key material. */
|
|
273
|
+
const apiKeyIdentity = {
|
|
274
|
+
id: z.string(),
|
|
275
|
+
name: z.string(),
|
|
276
|
+
fragment: z.string(),
|
|
277
|
+
expiresAt: z.string().nullable()
|
|
278
|
+
};
|
|
279
|
+
/** A run key as a mint answers it: the key once, or null on a replay of the same idempotency key. */
|
|
280
|
+
const apiKeyRevealResponse = z.discriminatedUnion("replayed", [z.object({
|
|
281
|
+
...apiKeyIdentity,
|
|
282
|
+
key: z.string(),
|
|
283
|
+
replayed: z.literal(false)
|
|
284
|
+
}), z.object({
|
|
285
|
+
...apiKeyIdentity,
|
|
286
|
+
key: z.null(),
|
|
287
|
+
replayed: z.literal(true)
|
|
288
|
+
})]);
|
|
289
|
+
/** A run key revoke's receipt. */
|
|
290
|
+
const revokeApiKeyResponse = z.object({ revoked: z.literal(true) });
|
|
291
|
+
// src/scope.ts
|
|
292
|
+
const fixtureHandles = /* @__PURE__ */ new WeakSet();
|
|
293
|
+
function markFixtureHandle(handle) {
|
|
294
|
+
fixtureHandles.add(handle);
|
|
295
|
+
}
|
|
296
|
+
function isFixtureHandle(handle) {
|
|
297
|
+
return fixtureHandles.has(handle);
|
|
298
|
+
}
|
|
299
|
+
// src/wait.ts
|
|
300
|
+
const REQUEST_CEILING_SECONDS = 55;
|
|
301
|
+
/**
|
|
302
|
+
* The shortest follow-up leg worth issuing after a leg that answered "nothing
|
|
303
|
+
* yet". A server leg's window opens when the request ARRIVES, so it answers a
|
|
304
|
+
* round trip before the caller's own deadline, leaving a leftover of a few
|
|
305
|
+
* milliseconds. A leg that short cannot clear the server's entry gate (its
|
|
306
|
+
* reads are bounded by the leg itself) and answers 503 instead of a result —
|
|
307
|
+
* so a leftover below this is spent as the deadline, and the leg that just
|
|
308
|
+
* answered is the chain's answer. The first leg is always issued, whatever
|
|
309
|
+
* the budget. One second is the server's own Retry-After granularity.
|
|
310
|
+
*/
|
|
311
|
+
const MIN_FOLLOW_UP_LEG_MS = 1e3;
|
|
312
|
+
const MAX_PAUSE_MS = 8e3;
|
|
313
|
+
/**
|
|
314
|
+
* A leg cut on its way: a gateway's 502/503/504, or status 0, every transport
|
|
315
|
+
* failure `request()` produces (a fetch reject, a failed body read, the leg's
|
|
316
|
+
* own abort). A wait only reads, so the same leg sent again answers what the
|
|
317
|
+
* lost one would have, or a newer state of the same inbox. Every other
|
|
318
|
+
* refusal (400, 401, 404, 409, 429, 500, a 2xx whose body is not JSON, a
|
|
319
|
+
* non-API error) is decisive.
|
|
320
|
+
*/
|
|
321
|
+
function isCut(err) {
|
|
322
|
+
return err instanceof MailstestApiError && [
|
|
323
|
+
0,
|
|
324
|
+
502,
|
|
325
|
+
503,
|
|
326
|
+
504
|
|
327
|
+
].includes(err.status);
|
|
328
|
+
}
|
|
329
|
+
async function chainWait(request, opts) {
|
|
330
|
+
const now = opts.now ?? Date.now;
|
|
331
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
332
|
+
const deadline = now() + opts.timeoutMs;
|
|
333
|
+
let followUp = false;
|
|
334
|
+
let pauseMs = MIN_FOLLOW_UP_LEG_MS;
|
|
335
|
+
let cut;
|
|
336
|
+
for (;;) {
|
|
337
|
+
const remainingMs = deadline - now();
|
|
338
|
+
if (remainingMs <= 0 || followUp && remainingMs < MIN_FOLLOW_UP_LEG_MS) {
|
|
339
|
+
if (cut !== void 0) throw cut;
|
|
340
|
+
return {
|
|
341
|
+
timedOut: true,
|
|
342
|
+
message: null
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
followUp = true;
|
|
346
|
+
const timeoutSeconds = Math.min(REQUEST_CEILING_SECONDS, remainingMs / 1e3);
|
|
347
|
+
let result;
|
|
348
|
+
try {
|
|
349
|
+
result = await request({
|
|
350
|
+
timeoutSeconds,
|
|
351
|
+
since: opts.since
|
|
352
|
+
});
|
|
353
|
+
} catch (err) {
|
|
354
|
+
if (!isCut(err) || deadline - now() < pauseMs + MIN_FOLLOW_UP_LEG_MS) throw err;
|
|
355
|
+
cut = err;
|
|
356
|
+
await sleep(pauseMs);
|
|
357
|
+
pauseMs = Math.min(pauseMs * 2, MAX_PAUSE_MS);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (!result.timedOut) return result;
|
|
361
|
+
cut = void 0;
|
|
362
|
+
pauseMs = MIN_FOLLOW_UP_LEG_MS;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
// src/client.ts
|
|
366
|
+
const USER_AGENT = `mailstest-playwright/0.1.0 node/${process.versions.node.split(".")[0]}`;
|
|
367
|
+
function redactSecret(text, secret) {
|
|
368
|
+
if (!secret) return text;
|
|
369
|
+
return text.split(secret).join("[redacted]");
|
|
370
|
+
}
|
|
371
|
+
var MailstestApiError = class extends Error {
|
|
372
|
+
status;
|
|
373
|
+
body;
|
|
374
|
+
/** The request's URL, already redacted of this client's own key — kept so a caller holding a second secret can rebuild a fully redacted copy. */
|
|
375
|
+
url;
|
|
376
|
+
constructor(status, body, url) {
|
|
377
|
+
super(`mailstest API request failed with ${status} for ${url}`);
|
|
378
|
+
this.name = "MailstestApiError";
|
|
379
|
+
this.status = status;
|
|
380
|
+
this.body = body;
|
|
381
|
+
this.url = url;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
/**
|
|
385
|
+
* Raised when a read scoped to one address meets a message that was not
|
|
386
|
+
* delivered to it, and when the run fixture's inbox is asked for mail it does
|
|
387
|
+
* not scope. The server filters by `to`; this is the client refusing to trust
|
|
388
|
+
* the filter alone, so a server that ignored `to` (an older build) cannot hand
|
|
389
|
+
* a test another test's mail. It names the address, never a secret.
|
|
390
|
+
*/
|
|
391
|
+
var MailstestScopeError = class extends Error {
|
|
392
|
+
constructor(message) {
|
|
393
|
+
super(message);
|
|
394
|
+
this.name = "MailstestScopeError";
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
function assertDeliveredTo(to, messages) {
|
|
398
|
+
const want = to.toLowerCase();
|
|
399
|
+
for (const m of messages) if (!m.deliveredTo.some((a) => a.toLowerCase() === want)) throw new MailstestScopeError(`mailstest: a read scoped to to=${to} returned message ${m.id}, which was not delivered to ${to}`);
|
|
400
|
+
}
|
|
401
|
+
function buildV1Url(baseUrl, segments, query) {
|
|
402
|
+
const path = segments.map(encodeURIComponent).join("/");
|
|
403
|
+
const qs = query && Object.keys(query).length > 0 ? `?${new URLSearchParams(query)}` : "";
|
|
404
|
+
return `${baseUrl.replace(/\/$/, "")}/v1/${path}${qs}`;
|
|
405
|
+
}
|
|
406
|
+
function parseFilename(header) {
|
|
407
|
+
if (!header) return null;
|
|
408
|
+
const ext = /filename\*=UTF-8''([^;]+)/i.exec(header);
|
|
409
|
+
if (ext?.[1]) try {
|
|
410
|
+
return decodeURIComponent(ext[1]);
|
|
411
|
+
} catch {}
|
|
412
|
+
return /filename="([^"]*)"/.exec(header)?.[1] ?? null;
|
|
413
|
+
}
|
|
414
|
+
function createClient(options) {
|
|
415
|
+
const { baseUrl, apiKey, fetchImpl = fetch } = options;
|
|
416
|
+
const secrets = [apiKey];
|
|
417
|
+
const protect = (secret) => {
|
|
418
|
+
if (secret && !secrets.includes(secret)) secrets.push(secret);
|
|
419
|
+
};
|
|
420
|
+
const scrub = (text) => secrets.reduce((acc, secret) => redactSecret(acc, secret), text);
|
|
421
|
+
async function request(segments, method = "GET", query, jsonOrAbortAfterMs, callerSignal) {
|
|
422
|
+
const abortAfterMs = typeof jsonOrAbortAfterMs === "number" ? jsonOrAbortAfterMs : void 0;
|
|
423
|
+
const json = typeof jsonOrAbortAfterMs === "object" ? jsonOrAbortAfterMs : void 0;
|
|
424
|
+
const url = buildV1Url(baseUrl, segments, query);
|
|
425
|
+
const controller = abortAfterMs === void 0 ? void 0 : new AbortController();
|
|
426
|
+
const timer = controller === void 0 ? void 0 : setTimeout(() => controller.abort(), abortAfterMs);
|
|
427
|
+
const signal = controller?.signal ?? callerSignal;
|
|
428
|
+
try {
|
|
429
|
+
const res = await fetchImpl(url, {
|
|
430
|
+
method,
|
|
431
|
+
headers: json === void 0 ? {
|
|
432
|
+
authorization: `Bearer ${apiKey}`,
|
|
433
|
+
"user-agent": USER_AGENT
|
|
434
|
+
} : {
|
|
435
|
+
authorization: `Bearer ${apiKey}`,
|
|
436
|
+
"content-type": "application/json",
|
|
437
|
+
"user-agent": USER_AGENT
|
|
438
|
+
},
|
|
439
|
+
body: json === void 0 ? void 0 : JSON.stringify(json),
|
|
440
|
+
signal
|
|
441
|
+
});
|
|
442
|
+
if (controller !== void 0) {
|
|
443
|
+
const text = await res.text();
|
|
444
|
+
if (!res.ok) throw new MailstestApiError(res.status, scrub(text), scrub(url));
|
|
445
|
+
try {
|
|
446
|
+
return JSON.parse(text);
|
|
447
|
+
} catch (err) {
|
|
448
|
+
throw new MailstestApiError(res.status, scrub(String(err)), scrub(url));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (!res.ok) throw new MailstestApiError(res.status, scrub(await res.text()), scrub(url));
|
|
452
|
+
return res;
|
|
453
|
+
} catch (err) {
|
|
454
|
+
if (err instanceof MailstestApiError) throw err;
|
|
455
|
+
if (controller?.signal.aborted) throw new MailstestApiError(0, "wait request timed out in transport", scrub(url));
|
|
456
|
+
throw new MailstestApiError(0, scrub(String(err)), scrub(url));
|
|
457
|
+
} finally {
|
|
458
|
+
clearTimeout(timer);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async function readBody(url, read) {
|
|
462
|
+
try {
|
|
463
|
+
return await read();
|
|
464
|
+
} catch (err) {
|
|
465
|
+
if (err instanceof MailstestApiError) throw err;
|
|
466
|
+
throw new MailstestApiError(0, scrub(String(err)), scrub(url));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
async function requestRaw(segments) {
|
|
470
|
+
const res = await request(segments);
|
|
471
|
+
const bytes = await readBody(buildV1Url(baseUrl, segments), () => res.arrayBuffer());
|
|
472
|
+
return {
|
|
473
|
+
bytes: new Uint8Array(bytes),
|
|
474
|
+
filename: parseFilename(res.headers.get("content-disposition"))
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function makeInboxHandle(inboxId) {
|
|
478
|
+
const messagesSegments = [
|
|
479
|
+
"inboxes",
|
|
480
|
+
inboxId,
|
|
481
|
+
"messages"
|
|
482
|
+
];
|
|
483
|
+
async function getMessage(messageId, options = {}) {
|
|
484
|
+
const segments = [...messagesSegments, messageId];
|
|
485
|
+
const res = await request(segments, "GET", void 0, void 0, options.signal);
|
|
486
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
487
|
+
return messageDetailResponse.parse(body);
|
|
488
|
+
}
|
|
489
|
+
async function page(to, options = {}) {
|
|
490
|
+
const query = {};
|
|
491
|
+
if (to !== void 0) query.to = to;
|
|
492
|
+
if (options.cursor !== void 0) query.cursor = options.cursor;
|
|
493
|
+
const res = await request(messagesSegments, "GET", query, void 0, options.signal);
|
|
494
|
+
const body = await readBody(buildV1Url(baseUrl, messagesSegments), () => res.json());
|
|
495
|
+
const parsed = listMessagesResponse.parse(body);
|
|
496
|
+
if (to !== void 0) assertDeliveredTo(to, parsed.messages);
|
|
497
|
+
return parsed;
|
|
498
|
+
}
|
|
499
|
+
async function all(to, signal) {
|
|
500
|
+
const out = [];
|
|
501
|
+
let cursor;
|
|
502
|
+
for (;;) {
|
|
503
|
+
const p = await page(to, {
|
|
504
|
+
cursor,
|
|
505
|
+
signal
|
|
506
|
+
});
|
|
507
|
+
out.push(...p.messages);
|
|
508
|
+
if (p.nextCursor === null) return out;
|
|
509
|
+
cursor = p.nextCursor;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function wait(to, { timeout = 3e4, since } = {}) {
|
|
513
|
+
return chainWait(async ({ timeoutSeconds, since: cursor }) => {
|
|
514
|
+
const query = { timeoutSeconds: String(timeoutSeconds) };
|
|
515
|
+
if (to !== void 0) query.to = to;
|
|
516
|
+
if (cursor !== void 0) query.since = cursor;
|
|
517
|
+
const body = await request([...messagesSegments, "wait"], "GET", query, timeoutSeconds * 1e3 + 1e4);
|
|
518
|
+
const parsed = waitForEmailResponse.parse(body);
|
|
519
|
+
if (to !== void 0 && parsed.message !== null) assertDeliveredTo(to, [parsed.message]);
|
|
520
|
+
return parsed;
|
|
521
|
+
}, {
|
|
522
|
+
timeoutMs: timeout,
|
|
523
|
+
since
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
async function clearMessages(to, signal) {
|
|
527
|
+
const res = await request(messagesSegments, "DELETE", to === void 0 ? { all: "true" } : { to }, void 0, signal);
|
|
528
|
+
const body = await readBody(buildV1Url(baseUrl, messagesSegments), () => res.json());
|
|
529
|
+
return clearMessagesResponse.parse(body);
|
|
530
|
+
}
|
|
531
|
+
function refuseIfFixture(verb) {
|
|
532
|
+
if (isFixtureHandle(handle)) throw new MailstestScopeError(`mailstest: ${verb} on the run fixture's inbox would reach other tests' mail — name \`to\` with inbox.recipient(address).${verb}`);
|
|
533
|
+
}
|
|
534
|
+
const handle = {
|
|
535
|
+
id: inboxId,
|
|
536
|
+
recipient(address) {
|
|
537
|
+
return {
|
|
538
|
+
inboxId,
|
|
539
|
+
address,
|
|
540
|
+
dashboardUrl: `${baseUrl.replace(/\/$/, "")}/inboxes/${encodeURIComponent(inboxId)}?to=${encodeURIComponent(address)}`,
|
|
541
|
+
listMessagesPage: (options) => page(address, options),
|
|
542
|
+
listMessages: (options = {}) => all(address, options.signal),
|
|
543
|
+
waitForEmail: (options) => wait(address, options),
|
|
544
|
+
clear: (options = {}) => clearMessages(address, options.signal)
|
|
545
|
+
};
|
|
546
|
+
},
|
|
547
|
+
async listMessagesPage(options = {}) {
|
|
548
|
+
refuseIfFixture("listMessagesPage");
|
|
549
|
+
return page(void 0, options);
|
|
550
|
+
},
|
|
551
|
+
async listMessages(options = {}) {
|
|
552
|
+
refuseIfFixture("listMessages");
|
|
553
|
+
return all(void 0, options.signal);
|
|
554
|
+
},
|
|
555
|
+
getMessage,
|
|
556
|
+
async getLinks(messageId, options = {}) {
|
|
557
|
+
return { links: extractLinks(await getMessage(messageId, options)) };
|
|
558
|
+
},
|
|
559
|
+
async getCodes(messageId, pattern, options = {}) {
|
|
560
|
+
return { codes: extractCodes(await getMessage(messageId, options), pattern) };
|
|
561
|
+
},
|
|
562
|
+
async getRaw(messageId) {
|
|
563
|
+
return requestRaw([
|
|
564
|
+
...messagesSegments,
|
|
565
|
+
messageId,
|
|
566
|
+
"raw"
|
|
567
|
+
]);
|
|
568
|
+
},
|
|
569
|
+
async clear() {
|
|
570
|
+
refuseIfFixture("clear");
|
|
571
|
+
return clearMessages(void 0);
|
|
572
|
+
},
|
|
573
|
+
async deleteMessage(messageId) {
|
|
574
|
+
const segments = [...messagesSegments, messageId];
|
|
575
|
+
const res = await request(segments, "DELETE");
|
|
576
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
577
|
+
deleteMessageResponse.parse(body);
|
|
578
|
+
},
|
|
579
|
+
async setPinned(messageId, pinned) {
|
|
580
|
+
const segments = [...messagesSegments, messageId];
|
|
581
|
+
const res = await request(segments, "PATCH", void 0, { pinned });
|
|
582
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
583
|
+
return setPinnedResponse.parse(body);
|
|
584
|
+
},
|
|
585
|
+
async waitForEmail(options) {
|
|
586
|
+
refuseIfFixture("waitForEmail");
|
|
587
|
+
return wait(void 0, options);
|
|
588
|
+
},
|
|
589
|
+
redactSecrets(text) {
|
|
590
|
+
return scrub(text);
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
return handle;
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
async listInboxes() {
|
|
597
|
+
const segments = ["inboxes"];
|
|
598
|
+
const res = await request(segments);
|
|
599
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
600
|
+
return listInboxesResponse.parse(body).inboxes;
|
|
601
|
+
},
|
|
602
|
+
createInbox: (async ({ name, expiresIn, maxUses, idempotencyKey, signal }) => {
|
|
603
|
+
const segments = ["inboxes"];
|
|
604
|
+
const payload = { name };
|
|
605
|
+
if (expiresIn !== void 0) payload.expiresIn = expiresIn;
|
|
606
|
+
if (maxUses !== void 0) payload.maxUses = maxUses;
|
|
607
|
+
if (idempotencyKey !== void 0) payload.idempotencyKey = idempotencyKey;
|
|
608
|
+
const res = await request(segments, "POST", void 0, payload, signal);
|
|
609
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
610
|
+
const reveal = credentialRevealResponse.parse(body);
|
|
611
|
+
if (reveal.password !== null) protect(reveal.password);
|
|
612
|
+
if (idempotencyKey === void 0 && reveal.replayed) throw new Error("mailstest: the create answered a replay for a request that declared no idempotency key");
|
|
613
|
+
return reveal;
|
|
614
|
+
}),
|
|
615
|
+
async deleteInbox(inboxId, { confirmName, signal }) {
|
|
616
|
+
const segments = ["inboxes", inboxId];
|
|
617
|
+
const res = await request(segments, "DELETE", void 0, { confirmName }, signal);
|
|
618
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
619
|
+
deleteInboxResponse.parse(body);
|
|
620
|
+
},
|
|
621
|
+
mintRunKey: (async ({ name, expiresIn, idempotencyKey, signal }) => {
|
|
622
|
+
const segments = ["keys"];
|
|
623
|
+
const res = await request(segments, "POST", void 0, idempotencyKey === void 0 ? {
|
|
624
|
+
name,
|
|
625
|
+
expiresIn
|
|
626
|
+
} : {
|
|
627
|
+
name,
|
|
628
|
+
expiresIn,
|
|
629
|
+
idempotencyKey
|
|
630
|
+
}, signal);
|
|
631
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
632
|
+
const reveal = apiKeyRevealResponse.parse(body);
|
|
633
|
+
if (reveal.key !== null) protect(reveal.key);
|
|
634
|
+
if (idempotencyKey === void 0 && reveal.replayed) throw new Error("mailstest: the mint answered a replay for a request that declared no idempotency key");
|
|
635
|
+
return reveal;
|
|
636
|
+
}),
|
|
637
|
+
async revokeRunKey(keyId, { signal } = {}) {
|
|
638
|
+
const segments = ["keys", keyId];
|
|
639
|
+
const res = await request(segments, "DELETE", void 0, void 0, signal);
|
|
640
|
+
const body = await readBody(buildV1Url(baseUrl, segments), () => res.json());
|
|
641
|
+
return revokeApiKeyResponse.parse(body);
|
|
642
|
+
},
|
|
643
|
+
inbox(inboxId) {
|
|
644
|
+
return makeInboxHandle(inboxId);
|
|
645
|
+
},
|
|
646
|
+
protectSecret(secret) {
|
|
647
|
+
protect(secret);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
export { parseFilename as a, markFixtureHandle as c, createClient as i, extractCodes as l, MailstestScopeError as n, redactSecret as o, buildV1Url as r, isFixtureHandle as s, MailstestApiError as t, extractLinks as u };
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { _ as buildV1Url, a as InboxIssuance, b as redactSecret, c as MailstestClient, d as MessageCodes, f as MessageDetail, g as WaitResult, h as RecipientHandle, i as InboxHandle, l as MailstestClientOptions, m as MessageSummary, n as ApiKeyReveal, o as InboxSummary, p as MessageLinks, r as InboxCredentials, s as MailstestApiError, t as ApiKeyIssuance, u as MailstestScopeError, v as createClient, y as parseFilename } from "./client-BkgYBSna.js";
|
|
2
|
+
export { ApiKeyIssuance, ApiKeyReveal, InboxCredentials, InboxHandle, InboxIssuance, InboxSummary, MailstestApiError, MailstestClient, MailstestClientOptions, MailstestScopeError, MessageCodes, MessageDetail, MessageLinks, MessageSummary, RecipientHandle, WaitResult, buildV1Url, createClient, parseFilename, redactSecret };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as MailstestApiError, n as MailstestScopeError, r as buildV1Url, i as createClient, a as parseFilename, o as redactSecret } from "./client-Bq5lAfzY.js";
|