@mailpier/inbox 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.
@@ -0,0 +1,321 @@
1
+ // src/testing/fakeServer.ts
2
+ import { createServer } from "http";
3
+ import { randomBytes, randomUUID } from "crypto";
4
+ var MAX_TAKE = 100;
5
+ var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
+ async function startFakeMailPier(options = {}) {
7
+ const apiKey = options.apiKey ?? "mpi_test_key";
8
+ const account = options.account ?? "demo";
9
+ const environment = options.environment ?? "qa";
10
+ const domains = (options.domains ?? ["mailpier.io"]).map((d) => d.toLowerCase());
11
+ const zoneFor = (d) => `${environment}.${account}.${d}`;
12
+ const zones = domains.map(zoneFor);
13
+ const zone = zones[0];
14
+ let seq = 0;
15
+ let store = [];
16
+ let failures = [];
17
+ const waiters = /* @__PURE__ */ new Set();
18
+ const requests = [];
19
+ const inEnv = (address) => {
20
+ const a = address.trim().toLowerCase();
21
+ return zones.some((z) => a.endsWith(`@${z}`) || a.endsWith(`.${z}`));
22
+ };
23
+ function deliver(mail) {
24
+ const recipients = (Array.isArray(mail.to) ? mail.to : [mail.to]).map((t) => t.trim()).filter(Boolean);
25
+ if (recipients.length === 0) throw new Error("deliver needs at least one recipient.");
26
+ const id = randomUUID();
27
+ const attachments = (mail.attachments ?? []).map((a) => ({
28
+ fileName: a.fileName,
29
+ contentType: a.contentType ?? "application/octet-stream",
30
+ bytes: typeof a.content === "string" ? Buffer.from(a.content, "utf8") : Buffer.from(a.content)
31
+ }));
32
+ const raw = buildEml(id, mail, recipients, attachments);
33
+ store.push({
34
+ seq: ++seq,
35
+ id,
36
+ received: (mail.receivedUtc ?? /* @__PURE__ */ new Date()).getTime(),
37
+ mail,
38
+ to: recipients,
39
+ links: mail.links ?? findLinks(mail.html, mail.text),
40
+ codes: mail.codes ?? findCodes(mail.subject, mail.text),
41
+ attachments,
42
+ raw
43
+ });
44
+ for (const w of [...waiters]) w();
45
+ return id;
46
+ }
47
+ const summary = (s) => clean({
48
+ id: s.id,
49
+ receivedUtc: new Date(s.received).toISOString(),
50
+ from: s.mail.from ?? "sender@example.com",
51
+ to: s.to.filter(inEnv),
52
+ subject: s.mail.subject,
53
+ sizeBytes: s.raw.length,
54
+ hasAttachments: s.attachments.length > 0
55
+ });
56
+ const detail = (s) => clean({
57
+ ...summary(s),
58
+ text: s.mail.text,
59
+ html: s.mail.html,
60
+ headers: clean({
61
+ from: clean({ name: s.mail.fromName, address: s.mail.from ?? "sender@example.com" }),
62
+ to: s.to.map((a) => ({ address: a })),
63
+ cc: [],
64
+ subject: s.mail.subject,
65
+ date: new Date(s.received).toISOString(),
66
+ messageId: `<${s.id}@fake.mailpier.test>`
67
+ }),
68
+ links: s.links.map((l) => clean({ href: l.href, text: l.text })),
69
+ codes: s.codes,
70
+ attachments: s.attachments.map((a, index) => ({ index, fileName: a.fileName, contentType: a.contentType, size: a.bytes.length })),
71
+ auth: { spf: "pass", dkim: "pass", dmarc: "pass" },
72
+ spam: { score: 0.1, verdict: "ham" }
73
+ });
74
+ function matches(f) {
75
+ let afterSeq = 0;
76
+ if (f.since !== void 0 && f.afterId) afterSeq = store.find((s) => s.id === f.afterId)?.seq ?? 0;
77
+ return store.filter((s) => s.to.some(inEnv) && (!f.to || s.to.some((t) => t.toLowerCase() === f.to.toLowerCase())) && (!f.subject || (s.mail.subject ?? "").toLowerCase().includes(f.subject.toLowerCase())) && (f.since === void 0 || s.received >= f.since) && s.seq > afterSeq);
78
+ }
79
+ const server = createServer((req, res) => {
80
+ handle(req, res).catch((err) => {
81
+ if (!res.headersSent) send(res, 500, { error: `Fake server error: ${String(err)}` });
82
+ else res.end();
83
+ });
84
+ });
85
+ async function handle(req, res) {
86
+ const u = new URL(req.url ?? "/", "http://fake");
87
+ const method = req.method ?? "GET";
88
+ requests.push({ method, url: u.pathname + u.search, authorization: req.headers.authorization });
89
+ res.setHeader("Cache-Control", "no-store");
90
+ if (u.pathname === "/_fake/deliver" && method === "POST") {
91
+ const body = await readJson(req);
92
+ if (!body || typeof body !== "object") return send(res, 400, { error: "JSON body required." });
93
+ return send(res, 201, { id: deliver(body) });
94
+ }
95
+ if (!u.pathname.startsWith("/v1/")) return send(res, 404, { error: "Not found." });
96
+ if ((req.headers.authorization ?? "") !== `Bearer ${apiKey}`) {
97
+ res.setHeader("WWW-Authenticate", "Bearer");
98
+ return send(res, 401, { error: "Missing, unknown or revoked API key. Send Authorization: Bearer mpi_..." });
99
+ }
100
+ const f = failures[0];
101
+ if (f) {
102
+ if ((f.times ?? 1) <= 1) failures.shift();
103
+ else f.times = (f.times ?? 1) - 1;
104
+ if (f.retryAfter !== void 0) res.setHeader("Retry-After", String(f.retryAfter));
105
+ return send(res, f.status, { error: f.error ?? (f.status === 429 ? "Too many requests. Slow down and retry after the Retry-After seconds." : "The service is not available right now. Retry in a moment.") });
106
+ }
107
+ const q = u.searchParams;
108
+ const to = q.get("to")?.trim() || void 0;
109
+ if (to && !inEnv(to) && u.pathname.startsWith("/v1/messages")) {
110
+ return send(res, 400, { error: `${to} is not an address of environment ${environment} (${zones.map((z) => `*@${z}`).join(", ")}).` });
111
+ }
112
+ const sinceText = q.get("since");
113
+ let since;
114
+ if (sinceText) {
115
+ since = Date.parse(sinceText);
116
+ if (Number.isNaN(since)) return send(res, 400, { error: "since must be an ISO 8601 date/time." });
117
+ }
118
+ const filter = { to, subject: q.get("subject") ?? void 0, since, afterId: q.get("afterId") ?? void 0 };
119
+ const parts = u.pathname.split("/").filter(Boolean);
120
+ if (u.pathname === "/v1/me" && method === "GET") {
121
+ return send(res, 200, {
122
+ account: { slug: account, name: "Demo", plan: "Team", status: "Active", monthlyQuota: 1e4, apiRequestsPerMinute: 600 },
123
+ environment: { name: environment, displayName: environment.toUpperCase(), retentionMinutes: 720, retentionHours: 12, isMain: environment === "main" },
124
+ domains,
125
+ addressPattern: `anything@${zone}`,
126
+ fullOriginalPattern: `jane.doe@example.com.${zone}`,
127
+ usage: { month: (/* @__PURE__ */ new Date()).toISOString().slice(0, 7), messages: store.length, quota: 1e4 },
128
+ key: { name: "test", prefix: apiKey.slice(0, 12) }
129
+ });
130
+ }
131
+ if (u.pathname === "/v1/addresses" && method === "POST") {
132
+ const body = await readJson(req, true);
133
+ if (body === "invalid") return send(res, 400, { error: "The body must be a JSON object, or empty." });
134
+ const prefix = body?.prefix?.trim();
135
+ if (prefix && !/^[a-z0-9-]{1,30}$/.test(prefix)) {
136
+ return send(res, 400, { error: "prefix may only hold a-z, 0-9 and '-' (at most 30 characters)." });
137
+ }
138
+ const domain = body?.domain?.trim().toLowerCase() || domains[0];
139
+ if (!domains.includes(domain)) return send(res, 400, { error: `domain must be one of: ${domains.join(", ")}.` });
140
+ const local = (prefix ? `${prefix}-` : "") + randomLocal();
141
+ return send(res, 201, { address: `${local}@${zoneFor(domain)}`, domain, account, environment, workspace: environment });
142
+ }
143
+ if (u.pathname === "/v1/messages" && method === "GET") {
144
+ const take = clamp(int(q.get("take"), 50), 1, MAX_TAKE);
145
+ const skip = clamp(int(q.get("skip"), 0), 0, 1e4);
146
+ const items = matches(filter).sort((a, b) => b.received - a.received || b.seq - a.seq).slice(skip, skip + take).map(summary);
147
+ return send(res, 200, { items, skip, take });
148
+ }
149
+ if (u.pathname === "/v1/messages/wait" && method === "GET") {
150
+ const seconds = clamp(int(q.get("timeoutSeconds"), 30), 1, 120);
151
+ const first = () => matches(filter).sort((a, b) => a.received - b.received || a.seq - b.seq)[0];
152
+ const found = first() ?? await new Promise((resolve) => {
153
+ const done = (s) => {
154
+ clearTimeout(timer);
155
+ waiters.delete(check);
156
+ res.off("close", gone);
157
+ resolve(s);
158
+ };
159
+ const check = () => {
160
+ const s = first();
161
+ if (s) done(s);
162
+ };
163
+ const gone = () => done(void 0);
164
+ const timer = setTimeout(() => done(void 0), seconds * 1e3);
165
+ waiters.add(check);
166
+ res.on("close", gone);
167
+ });
168
+ if (!found) {
169
+ res.statusCode = 204;
170
+ return res.end();
171
+ }
172
+ return send(res, 200, detail(found));
173
+ }
174
+ if (u.pathname === "/v1/messages" && method === "DELETE") {
175
+ if (!to) return send(res, 400, { error: "to (one of this environment's addresses) is required." });
176
+ const gone = matches({ to });
177
+ store = store.filter((s) => !gone.includes(s));
178
+ return send(res, 200, { deleted: gone.length, skippedShared: 0 });
179
+ }
180
+ if (parts[0] === "v1" && parts[1] === "messages" && parts[2] && GUID.test(parts[2])) {
181
+ const s = store.find((m) => m.id.toLowerCase() === parts[2].toLowerCase() && m.to.some(inEnv));
182
+ const notFound = () => send(res, 404, { error: "No such message in this environment." });
183
+ if (parts.length === 3 && method === "GET") return s ? send(res, 200, detail(s)) : notFound();
184
+ if (parts.length === 3 && method === "DELETE") {
185
+ if (!s) return notFound();
186
+ store = store.filter((m) => m !== s);
187
+ res.statusCode = 204;
188
+ return res.end();
189
+ }
190
+ if (parts.length === 4 && parts[3] === "raw" && method === "GET") {
191
+ if (!s) return notFound();
192
+ res.writeHead(200, { "Content-Type": "message/rfc822", "Content-Disposition": `attachment; filename="${s.id}.eml"` });
193
+ return res.end(s.raw);
194
+ }
195
+ if (parts.length === 5 && parts[3] === "attachments" && /^\d+$/.test(parts[4]) && method === "GET") {
196
+ const a = s?.attachments[Number(parts[4])];
197
+ if (!a) return notFound();
198
+ res.writeHead(200, { "Content-Type": a.contentType, "Content-Disposition": `attachment; filename="${a.fileName}"` });
199
+ return res.end(a.bytes);
200
+ }
201
+ }
202
+ return send(res, 404, { error: "Not found." });
203
+ }
204
+ await new Promise((resolve, reject) => {
205
+ server.once("error", reject);
206
+ server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
207
+ });
208
+ const port = server.address().port;
209
+ return {
210
+ url: `http://127.0.0.1:${port}`,
211
+ apiKey,
212
+ zone,
213
+ requests,
214
+ deliver,
215
+ failNext: (f) => {
216
+ failures.push({ ...f });
217
+ },
218
+ count: () => store.length,
219
+ reset: () => {
220
+ store = [];
221
+ failures = [];
222
+ requests.length = 0;
223
+ },
224
+ close: () => new Promise((resolve) => {
225
+ for (const w of [...waiters]) w();
226
+ server.closeAllConnections?.();
227
+ server.close(() => resolve());
228
+ })
229
+ };
230
+ }
231
+ function send(res, status, body) {
232
+ const text = JSON.stringify(body);
233
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(text) });
234
+ res.end(text);
235
+ }
236
+ async function readJson(req, optional = false) {
237
+ const chunks = [];
238
+ for await (const c of req) chunks.push(c);
239
+ const text = Buffer.concat(chunks).toString("utf8");
240
+ if (!text.trim()) return void 0;
241
+ try {
242
+ const v = JSON.parse(text);
243
+ return v && typeof v === "object" && !Array.isArray(v) ? v : optional ? "invalid" : void 0;
244
+ } catch {
245
+ return optional ? "invalid" : void 0;
246
+ }
247
+ }
248
+ function clean(o) {
249
+ for (const k of Object.keys(o)) if (o[k] === void 0 || o[k] === null) delete o[k];
250
+ return o;
251
+ }
252
+ var int = (v, d) => {
253
+ const n = Number.parseInt(v ?? "", 10);
254
+ return Number.isFinite(n) ? n : d;
255
+ };
256
+ var clamp = (n, lo, hi) => Math.min(Math.max(n, lo), hi);
257
+ function randomLocal() {
258
+ const abc = "abcdefghijklmnopqrstuvwxyz0123456789";
259
+ return [...randomBytes(10)].map((b) => abc[b % abc.length]).join("");
260
+ }
261
+ function findLinks(html, text) {
262
+ const out = [];
263
+ const seen = /* @__PURE__ */ new Set();
264
+ if (html) {
265
+ for (const m of html.matchAll(/<a\s[^>]*href\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)) {
266
+ const href = m[1].replace(/&amp;/g, "&");
267
+ if (!/^https?:/i.test(href) || seen.has(href)) continue;
268
+ seen.add(href);
269
+ const t = m[2].replace(/<[^>]+>/g, "").trim();
270
+ out.push(t ? { href, text: t } : { href });
271
+ }
272
+ }
273
+ for (const m of (text ?? "").matchAll(/https?:\/\/[^\s<>"')]+/gi)) {
274
+ const href = m[0].replace(/[.,;:!?]+$/, "");
275
+ if (!seen.has(href)) {
276
+ seen.add(href);
277
+ out.push({ href });
278
+ }
279
+ }
280
+ return out;
281
+ }
282
+ function findCodes(subject, text) {
283
+ const out = [];
284
+ for (const m of `${subject ?? ""}
285
+ ${text ?? ""}`.matchAll(/(?<![\w\/.-])\d{4,8}(?!\w|[.\/-]\d)/g)) if (!out.includes(m[0])) out.push(m[0]);
286
+ return out;
287
+ }
288
+ function buildEml(id, mail, to, atts) {
289
+ const boundary = `=_fake_${id}`;
290
+ const lines = [
291
+ `From: ${mail.fromName ? `"${mail.fromName}" ` : ""}<${mail.from ?? "sender@example.com"}>`,
292
+ `To: ${to.join(", ")}`,
293
+ `Subject: ${mail.subject ?? ""}`,
294
+ `Message-ID: <${id}@fake.mailpier.test>`,
295
+ "MIME-Version: 1.0",
296
+ `Content-Type: multipart/mixed; boundary="${boundary}"`,
297
+ "",
298
+ `--${boundary}`,
299
+ "Content-Type: text/plain; charset=utf-8",
300
+ "",
301
+ mail.text ?? ""
302
+ ];
303
+ if (mail.html) lines.push(`--${boundary}`, "Content-Type: text/html; charset=utf-8", "", mail.html);
304
+ for (const a of atts) {
305
+ lines.push(
306
+ `--${boundary}`,
307
+ `Content-Type: ${a.contentType}; name="${a.fileName}"`,
308
+ "Content-Transfer-Encoding: base64",
309
+ `Content-Disposition: attachment; filename="${a.fileName}"`,
310
+ "",
311
+ a.bytes.toString("base64")
312
+ );
313
+ }
314
+ lines.push(`--${boundary}--`, "");
315
+ return Buffer.from(lines.join("\r\n"), "utf8");
316
+ }
317
+ export {
318
+ findCodes,
319
+ findLinks,
320
+ startFakeMailPier
321
+ };
package/package.json CHANGED
@@ -1,6 +1,109 @@
1
1
  {
2
2
  "name": "@mailpier/inbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MailPier Inbox client for Node.js tests: a fresh email address per test, wait for the mail, read its code and links. Playwright fixture and Cypress commands included.",
5
+ "license": "MIT",
6
+ "author": "Solutions Group Unlimited",
7
+ "homepage": "https://mailpier.io",
8
+ "keywords": [
9
+ "email",
10
+ "testing",
11
+ "inbox",
12
+ "otp",
13
+ "playwright",
14
+ "cypress",
15
+ "e2e",
16
+ "mailpier"
17
+ ],
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "sideEffects": [
23
+ "./dist/cypress/commands.*"
24
+ ],
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md"
30
+ ],
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "import": {
37
+ "types": "./dist/index.d.ts",
38
+ "default": "./dist/index.js"
39
+ },
40
+ "require": {
41
+ "types": "./dist/index.d.cts",
42
+ "default": "./dist/index.cjs"
43
+ }
44
+ },
45
+ "./testing": {
46
+ "import": {
47
+ "types": "./dist/testing/index.d.ts",
48
+ "default": "./dist/testing/index.js"
49
+ },
50
+ "require": {
51
+ "types": "./dist/testing/index.d.cts",
52
+ "default": "./dist/testing/index.cjs"
53
+ }
54
+ },
55
+ "./playwright": {
56
+ "import": {
57
+ "types": "./dist/playwright.d.ts",
58
+ "default": "./dist/playwright.js"
59
+ },
60
+ "require": {
61
+ "types": "./dist/playwright.d.cts",
62
+ "default": "./dist/playwright.cjs"
63
+ }
64
+ },
65
+ "./cypress": {
66
+ "import": {
67
+ "types": "./dist/cypress/index.d.ts",
68
+ "default": "./dist/cypress/index.js"
69
+ },
70
+ "require": {
71
+ "types": "./dist/cypress/index.d.cts",
72
+ "default": "./dist/cypress/index.cjs"
73
+ }
74
+ },
75
+ "./cypress/commands": {
76
+ "import": {
77
+ "types": "./dist/cypress/commands.d.ts",
78
+ "default": "./dist/cypress/commands.js"
79
+ },
80
+ "require": {
81
+ "types": "./dist/cypress/commands.d.cts",
82
+ "default": "./dist/cypress/commands.cjs"
83
+ }
84
+ },
85
+ "./package.json": "./package.json"
86
+ },
87
+ "scripts": {
88
+ "build": "tsup",
89
+ "typecheck": "tsc --noEmit",
90
+ "test": "vitest run",
91
+ "test:e2e": "playwright test --config playwright/playwright.config.ts",
92
+ "example": "node examples/quickstart.mjs"
93
+ },
94
+ "peerDependencies": {
95
+ "@playwright/test": ">=1.40"
96
+ },
97
+ "peerDependenciesMeta": {
98
+ "@playwright/test": {
99
+ "optional": true
100
+ }
101
+ },
102
+ "devDependencies": {
103
+ "@playwright/test": "^1.65.0",
104
+ "@types/node": "^26.6.6",
105
+ "tsup": "^9.0.0",
106
+ "typescript": "~5.9.3",
107
+ "vitest": "^5.1.0"
108
+ }
109
+ }