apimend 0.0.0-stage → 0.1.1
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/README.md +13 -2
- package/dist/index.js +511 -0
- package/package.json +26 -4
package/README.md
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Apimend CLI (`apimend`)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official CLI for [Apimend Mail](https://www.apimend.com): sandbox sends, Development Inbox, two-way agent inboxes & threads, real-time SSE event tailing, Email Debugger diagnostics, Pre-release QA CI gates, DNS checks, and template pull/push.
|
|
4
|
+
|
|
5
|
+
## Quickstart
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx apimend login --api-key am_test_...
|
|
9
|
+
npx apimend send --from hi@acme.dev --to ada@example.com --subject "Welcome" --text "Hi Ada"
|
|
10
|
+
npx apimend events tail --sandbox
|
|
11
|
+
npx apimend qa --email-id em_123 --fail-below 90 --json
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
See [apimend.com/topics/cli](https://www.apimend.com/topics/cli) for full documentation.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
export function parseCliArgs(argv) {
|
|
8
|
+
const positionals = [];
|
|
9
|
+
const flags = {};
|
|
10
|
+
for (let i = 0; i < argv.length; i++) {
|
|
11
|
+
const arg = argv[i];
|
|
12
|
+
if (!arg.startsWith("--")) {
|
|
13
|
+
positionals.push(arg);
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
const eqIdx = arg.indexOf("=");
|
|
17
|
+
if (eqIdx !== -1) {
|
|
18
|
+
flags[arg.slice(2, eqIdx)] = arg.slice(eqIdx + 1);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const key = arg.slice(2);
|
|
22
|
+
const next = argv[i + 1];
|
|
23
|
+
if (next !== undefined && !next.startsWith("--")) {
|
|
24
|
+
flags[key] = next;
|
|
25
|
+
i++;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
flags[key] = true;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return { positionals, flags };
|
|
32
|
+
}
|
|
33
|
+
async function readStoredConfig(configPath) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(await readFile(configPath, "utf8"));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return {};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function writeStoredConfig(configPath, data) {
|
|
42
|
+
await mkdir(dirname(configPath), { recursive: true });
|
|
43
|
+
await writeFile(configPath, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
44
|
+
}
|
|
45
|
+
async function apiRequest(opts, method, path, body, idempotent = false) {
|
|
46
|
+
const canRetry = method === "GET" || idempotent;
|
|
47
|
+
const maxAttempts = canRetry ? 3 : 1;
|
|
48
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
49
|
+
try {
|
|
50
|
+
const res = await opts.fetcher(`${opts.baseUrl}${path}`, {
|
|
51
|
+
method,
|
|
52
|
+
headers: {
|
|
53
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
54
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
55
|
+
},
|
|
56
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
57
|
+
});
|
|
58
|
+
const text = await res.text();
|
|
59
|
+
let parsed = {};
|
|
60
|
+
try {
|
|
61
|
+
parsed = text ? JSON.parse(text) : {};
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
parsed = { raw: text };
|
|
65
|
+
}
|
|
66
|
+
if (res.ok)
|
|
67
|
+
return parsed;
|
|
68
|
+
if (attempt + 1 < maxAttempts && [429, 500, 502, 503, 504].includes(res.status)) {
|
|
69
|
+
const retryAfter = Number(res.headers.get("retry-after") || "0");
|
|
70
|
+
const delayMs = retryAfter > 0 ? Math.min(retryAfter * 1000, 5000) : 200 * 2 ** attempt;
|
|
71
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
throw new Error(parsed?.error || `HTTP ${res.status}`);
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
if (attempt + 1 < maxAttempts && err instanceof TypeError) {
|
|
78
|
+
await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export async function runCli(argv, ctx = {}) {
|
|
86
|
+
const { positionals, flags } = parseCliArgs(argv);
|
|
87
|
+
const out = ctx.stdout ?? ((s) => console.log(s));
|
|
88
|
+
const errOut = ctx.stderr ?? ((s) => console.error(s));
|
|
89
|
+
const jsonMode = flags.json === true;
|
|
90
|
+
const configPath = ctx.configPath ?? join(homedir(), ".apimend", "config.json");
|
|
91
|
+
const cmd = positionals[0];
|
|
92
|
+
const sub = positionals[1];
|
|
93
|
+
if (!cmd || cmd === "help" || flags.help) {
|
|
94
|
+
out([
|
|
95
|
+
"Apimend CLI — Transactional email, Remote MCP & two-way agent inboxes",
|
|
96
|
+
"",
|
|
97
|
+
"Auth & Setup:",
|
|
98
|
+
" login Save API key and base URL to ~/.apimend/config.json",
|
|
99
|
+
" whoami Show current workspace, plan, and monthly usage",
|
|
100
|
+
" mcp setup Print one-command Remote MCP setup (claude | cursor | codex)",
|
|
101
|
+
"",
|
|
102
|
+
"Sending, Sandbox & Diagnostics:",
|
|
103
|
+
" send Send to Customer Sandbox (default) or live (--live --confirm-live)",
|
|
104
|
+
" emails List or inspect emails (`list`, `get <id>`)",
|
|
105
|
+
" inbox Manage Development Inbox (`list`, `clear`)",
|
|
106
|
+
" diagnose Run read-only Email Debugger (`diagnose <emailId>`)",
|
|
107
|
+
" qa Run Pre-release Email QA (supports `--fail-below <score>` for CI)",
|
|
108
|
+
" events tail Stream live/sandbox SSE events (`--types`, `--sandbox`, `--oneshot`)",
|
|
109
|
+
"",
|
|
110
|
+
"Agent Inboxes & Threads:",
|
|
111
|
+
" inboxes Manage two-way inboxes (`create`, `list`, `state <id> <status>`)",
|
|
112
|
+
" threads Inspect or reply to threads (`list`, `get <id>`, `reply <id>`, `state`)",
|
|
113
|
+
"",
|
|
114
|
+
"Infrastructure & Templates:",
|
|
115
|
+
" domains List or add sending domains (`list`, `add <domain>`)",
|
|
116
|
+
" dns check Verify domain ownership & DKIM (`dns check <domain>`)",
|
|
117
|
+
" webhooks List or test webhooks (`list`, `test <id>`)",
|
|
118
|
+
" suppressions Manage suppressions (`list`, `add <email>`, `remove <email>`)",
|
|
119
|
+
" approvals List held emails pending owner approval (`list`)",
|
|
120
|
+
" analytics Show workspace analytics & usage",
|
|
121
|
+
" templates List, pull, or push templates (`list`, `pull`, `push`)",
|
|
122
|
+
"",
|
|
123
|
+
"Global flags: --json, --api-key <key>, --base-url <url>",
|
|
124
|
+
].join("\n"));
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
const stored = await readStoredConfig(configPath);
|
|
128
|
+
const baseUrl = (typeof flags["base-url"] === "string"
|
|
129
|
+
? flags["base-url"]
|
|
130
|
+
: ctx.baseUrl ?? process.env.APIMEND_BASE_URL ?? stored.baseUrl ?? "https://app.apimend.com").replace(/\/$/, "");
|
|
131
|
+
const print = (data, human) => {
|
|
132
|
+
out(jsonMode ? JSON.stringify(data, null, 2) : human);
|
|
133
|
+
};
|
|
134
|
+
if (cmd === "login") {
|
|
135
|
+
const keyArg = typeof flags["api-key"] === "string" ? flags["api-key"].trim() : "";
|
|
136
|
+
if (!keyArg) {
|
|
137
|
+
errOut("Usage: apimend login --api-key <am_live_... or am_test_...> [--base-url <url>]");
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
await writeStoredConfig(configPath, { apiKey: keyArg, baseUrl });
|
|
141
|
+
print({ ok: true, baseUrl, configPath }, `Saved Apimend credentials to ${configPath} (${baseUrl})`);
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
144
|
+
if (cmd === "mcp" && sub === "setup") {
|
|
145
|
+
const target = positionals[2] ?? "all";
|
|
146
|
+
const endpoint = `${baseUrl}/mcp`;
|
|
147
|
+
const setup = {
|
|
148
|
+
endpoint,
|
|
149
|
+
claudeCode: `claude mcp add --transport http apimend ${endpoint}`,
|
|
150
|
+
codex: `codex mcp add apimend --url ${endpoint}`,
|
|
151
|
+
cursor: { mcpServers: { apimend: { url: endpoint } } },
|
|
152
|
+
};
|
|
153
|
+
if (jsonMode) {
|
|
154
|
+
out(JSON.stringify(setup, null, 2));
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
if (target === "claude")
|
|
158
|
+
out(setup.claudeCode);
|
|
159
|
+
else if (target === "codex")
|
|
160
|
+
out(setup.codex);
|
|
161
|
+
else if (target === "cursor")
|
|
162
|
+
out(JSON.stringify(setup.cursor, null, 2));
|
|
163
|
+
else {
|
|
164
|
+
out(`Remote MCP endpoint: ${endpoint}\n\nClaude Code:\n ${setup.claudeCode}\n\nCodex:\n ${setup.codex}\n\nCursor (.cursor/mcp.json):\n${JSON.stringify(setup.cursor, null, 2)}`);
|
|
165
|
+
}
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
const apiKey = (typeof flags["api-key"] === "string"
|
|
169
|
+
? flags["api-key"]
|
|
170
|
+
: ctx.apiKey ?? process.env.APIMEND_API_KEY ?? stored.apiKey ?? "").trim();
|
|
171
|
+
const fetcher = ctx.fetcher ?? fetch;
|
|
172
|
+
if (!apiKey) {
|
|
173
|
+
errOut("Missing API key. Run `apimend login --api-key <key>`, set APIMEND_API_KEY, or pass --api-key.");
|
|
174
|
+
return 1;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
if (cmd === "whoami") {
|
|
178
|
+
let me = null;
|
|
179
|
+
let stats = null;
|
|
180
|
+
try {
|
|
181
|
+
me = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/auth/me");
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
me = null;
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
stats = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/stats");
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
stats = null;
|
|
191
|
+
}
|
|
192
|
+
const keyMode = apiKey.startsWith("am_test_") ? "test" : "live";
|
|
193
|
+
const payload = { account: me?.account ?? null, keyMode, baseUrl, stats };
|
|
194
|
+
print(payload, stats
|
|
195
|
+
? `${me?.account?.name ?? "Workspace"} (${me?.account?.plan ?? keyMode}) — ${stats.usedThisMonth ?? 0}/${stats.monthlyLimit ?? 0} sent this month`
|
|
196
|
+
: `Authenticated (${keyMode} key) at ${baseUrl}`);
|
|
197
|
+
return 0;
|
|
198
|
+
}
|
|
199
|
+
if (cmd === "send") {
|
|
200
|
+
const from = String(flags.from ?? "");
|
|
201
|
+
const to = String(flags.to ?? "");
|
|
202
|
+
const subject = typeof flags.subject === "string" ? flags.subject : undefined;
|
|
203
|
+
const text = typeof flags.text === "string" ? flags.text : undefined;
|
|
204
|
+
const html = typeof flags.html === "string" ? flags.html : undefined;
|
|
205
|
+
const template = typeof flags.template === "string" ? flags.template : undefined;
|
|
206
|
+
const stream = typeof flags.stream === "string" ? flags.stream : undefined;
|
|
207
|
+
const templateData = typeof flags.data === "string" ? JSON.parse(flags.data) : undefined;
|
|
208
|
+
const isLive = flags.live === true;
|
|
209
|
+
const confirmLive = flags["confirm-live"] === true;
|
|
210
|
+
if (isLive && !confirmLive) {
|
|
211
|
+
throw new Error("Live sending requires both --live and --confirm-live. Omit --live to capture in Customer Sandbox.");
|
|
212
|
+
}
|
|
213
|
+
if (!from || !to || (!subject && !template)) {
|
|
214
|
+
throw new Error("--from, --to, and either --subject or --template are required.");
|
|
215
|
+
}
|
|
216
|
+
const idempotencyKey = typeof flags["idempotency-key"] === "string" ? flags["idempotency-key"] : `cli_${randomUUID()}`;
|
|
217
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/send", {
|
|
218
|
+
from,
|
|
219
|
+
to,
|
|
220
|
+
...(subject ? { subject } : {}),
|
|
221
|
+
...(text ? { text } : {}),
|
|
222
|
+
...(html ? { html } : {}),
|
|
223
|
+
...(template ? { template } : {}),
|
|
224
|
+
...(templateData ? { templateData } : {}),
|
|
225
|
+
...(stream ? { stream } : {}),
|
|
226
|
+
idempotencyKey,
|
|
227
|
+
sandbox: !isLive,
|
|
228
|
+
}, true);
|
|
229
|
+
print(res, `Queued ${res.id} (${res.status}, ${isLive ? "live" : "sandbox"})`);
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
232
|
+
if (cmd === "emails") {
|
|
233
|
+
if (sub === "get") {
|
|
234
|
+
const emailId = positionals[2];
|
|
235
|
+
if (!emailId)
|
|
236
|
+
throw new Error("Email ID is required.");
|
|
237
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/emails/${encodeURIComponent(emailId)}`);
|
|
238
|
+
print(res, `${res.id} [${res.status}] ${res.from} -> ${res.to?.join(",")} "${res.subject}"`);
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
const limit = Number(flags.limit) || 25;
|
|
242
|
+
const sandbox = flags.sandbox === true ? "&sandbox=true" : "";
|
|
243
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/emails?limit=${limit}${sandbox}`);
|
|
244
|
+
const rows = (res.data ?? []);
|
|
245
|
+
print(res, rows.length ? rows.map((r) => `${r.id} ${r.status} ${r.to?.join(",")} "${r.subject}"`).join("\n") : "No emails found.");
|
|
246
|
+
return 0;
|
|
247
|
+
}
|
|
248
|
+
if (cmd === "inbox") {
|
|
249
|
+
if (sub === "clear") {
|
|
250
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "DELETE", "/v1/sandbox/emails");
|
|
251
|
+
print(res, `Cleared ${res.cleared ?? 0} sandbox emails.`);
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
const limit = Number(flags.limit) || 25;
|
|
255
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/sandbox/emails?limit=${limit}`);
|
|
256
|
+
const rows = (res.data ?? []);
|
|
257
|
+
print(res, rows.length ? rows.map((r) => `${r.id} ${r.status} ${r.to?.join(",")} "${r.subject}"`).join("\n") : "Sandbox inbox is empty.");
|
|
258
|
+
return 0;
|
|
259
|
+
}
|
|
260
|
+
if (cmd === "inboxes") {
|
|
261
|
+
if (sub === "create") {
|
|
262
|
+
const mode = typeof flags.mode === "string" ? flags.mode : "managed";
|
|
263
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/inboxes", {
|
|
264
|
+
mode,
|
|
265
|
+
...(typeof flags.slug === "string" ? { slug: flags.slug } : {}),
|
|
266
|
+
...(typeof flags.address === "string" ? { address: flags.address } : {}),
|
|
267
|
+
...(typeof flags.label === "string" ? { label: flags.label } : {}),
|
|
268
|
+
});
|
|
269
|
+
print(res, `Created inbox ${res.id}: ${res.address} (${res.status})`);
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
272
|
+
if (sub === "state") {
|
|
273
|
+
const inboxId = positionals[2];
|
|
274
|
+
const status = positionals[3];
|
|
275
|
+
if (!inboxId || !status)
|
|
276
|
+
throw new Error("Usage: apimend inboxes state <inboxId> <open|waiting|resolved|escalated>");
|
|
277
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "PATCH", `/v1/inboxes/${encodeURIComponent(inboxId)}`, { status });
|
|
278
|
+
print(res, `Inbox ${res.id} -> ${res.status}`);
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
const status = typeof flags.status === "string" ? `?status=${encodeURIComponent(flags.status)}` : "";
|
|
282
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/inboxes${status}`);
|
|
283
|
+
const rows = (res.data ?? []);
|
|
284
|
+
print(res, rows.length ? rows.map((r) => `${r.id} ${r.status} ${r.address}`).join("\n") : "No inboxes found.");
|
|
285
|
+
return 0;
|
|
286
|
+
}
|
|
287
|
+
if (cmd === "threads") {
|
|
288
|
+
if (sub === "list" || !sub) {
|
|
289
|
+
const qs = new URLSearchParams();
|
|
290
|
+
if (typeof flags["inbox-id"] === "string")
|
|
291
|
+
qs.set("inboxId", flags["inbox-id"]);
|
|
292
|
+
if (typeof flags.status === "string")
|
|
293
|
+
qs.set("status", flags.status);
|
|
294
|
+
const query = qs.toString() ? `?${qs.toString()}` : "";
|
|
295
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/threads${query}`);
|
|
296
|
+
const rows = (res.data ?? []);
|
|
297
|
+
print(res, rows.length ? rows.map((t) => `${t.id} ${t.status} (${t.messageCount}) "${t.subject}"`).join("\n") : "No threads found.");
|
|
298
|
+
return 0;
|
|
299
|
+
}
|
|
300
|
+
if (sub === "get") {
|
|
301
|
+
const threadId = positionals[2];
|
|
302
|
+
if (!threadId)
|
|
303
|
+
throw new Error("Thread ID is required.");
|
|
304
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/threads/${encodeURIComponent(threadId)}`);
|
|
305
|
+
print(res, `Thread ${res.id} [${res.status}] "${res.subject}" (${res.messageCount} messages)`);
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
if (sub === "state") {
|
|
309
|
+
const threadId = positionals[2];
|
|
310
|
+
const status = positionals[3];
|
|
311
|
+
if (!threadId || !status)
|
|
312
|
+
throw new Error("Usage: apimend threads state <threadId> <open|waiting|resolved|escalated>");
|
|
313
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "PATCH", `/v1/threads/${encodeURIComponent(threadId)}`, { status });
|
|
314
|
+
print(res, `Thread ${res.id} -> ${res.status}`);
|
|
315
|
+
return 0;
|
|
316
|
+
}
|
|
317
|
+
if (sub === "reply") {
|
|
318
|
+
const threadId = positionals[2];
|
|
319
|
+
const text = typeof flags.text === "string" ? flags.text : undefined;
|
|
320
|
+
if (!threadId || !text)
|
|
321
|
+
throw new Error("Usage: apimend threads reply <threadId> --text '...'");
|
|
322
|
+
const idempotencyKey = typeof flags["idempotency-key"] === "string" ? flags["idempotency-key"] : `cli_reply_${randomUUID()}`;
|
|
323
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", `/v1/threads/${encodeURIComponent(threadId)}/reply`, { text, idempotencyKey, ...(typeof flags.status === "string" ? { statusAfterReply: flags.status } : {}) }, true);
|
|
324
|
+
print(res, `Replied on thread ${res.threadId} -> ${res.id} (${res.status})`);
|
|
325
|
+
return 0;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (cmd === "events" && sub === "tail") {
|
|
329
|
+
const qs = new URLSearchParams();
|
|
330
|
+
if (typeof flags.types === "string")
|
|
331
|
+
qs.set("types", flags.types);
|
|
332
|
+
if (flags.sandbox === true)
|
|
333
|
+
qs.set("sandbox", "true");
|
|
334
|
+
if (flags.oneshot === true)
|
|
335
|
+
qs.set("oneshot", "true");
|
|
336
|
+
const res = await fetcher(`${baseUrl}/v1/events/stream?${qs.toString()}`, {
|
|
337
|
+
headers: { Authorization: `Bearer ${apiKey}`, Accept: "text/event-stream" },
|
|
338
|
+
});
|
|
339
|
+
if (!res.ok || !res.body)
|
|
340
|
+
throw new Error(`Stream failed (HTTP ${res.status})`);
|
|
341
|
+
const reader = res.body.getReader();
|
|
342
|
+
const decoder = new TextDecoder();
|
|
343
|
+
let buf = "";
|
|
344
|
+
while (true) {
|
|
345
|
+
const { done, value } = await reader.read();
|
|
346
|
+
if (done)
|
|
347
|
+
break;
|
|
348
|
+
buf += decoder.decode(value, { stream: true });
|
|
349
|
+
const blocks = buf.split("\n\n");
|
|
350
|
+
buf = blocks.pop() ?? "";
|
|
351
|
+
for (const block of blocks) {
|
|
352
|
+
if (!block.trim() || block.startsWith(":"))
|
|
353
|
+
continue;
|
|
354
|
+
const eventLine = block.split("\n").find((l) => l.startsWith("event:"))?.slice(6).trim() ?? "message";
|
|
355
|
+
const dataLine = block.split("\n").find((l) => l.startsWith("data:"))?.slice(5).trim() ?? "{}";
|
|
356
|
+
if (jsonMode)
|
|
357
|
+
out(JSON.stringify({ event: eventLine, data: JSON.parse(dataLine) }));
|
|
358
|
+
else
|
|
359
|
+
out(`[${eventLine}] ${dataLine}`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return 0;
|
|
363
|
+
}
|
|
364
|
+
if (cmd === "diagnose") {
|
|
365
|
+
const emailId = positionals[1];
|
|
366
|
+
if (!emailId)
|
|
367
|
+
throw new Error("Email ID is required.");
|
|
368
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/emails/${encodeURIComponent(emailId)}/diagnostics`);
|
|
369
|
+
print(res, `${res.status}: ${res.summary}`);
|
|
370
|
+
return 0;
|
|
371
|
+
}
|
|
372
|
+
if (cmd === "qa") {
|
|
373
|
+
const emailId = typeof flags["email-id"] === "string" ? flags["email-id"] : undefined;
|
|
374
|
+
const failBelow = flags["fail-below"] !== undefined ? Number(flags["fail-below"]) : undefined;
|
|
375
|
+
const res = emailId
|
|
376
|
+
? await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/emails/${encodeURIComponent(emailId)}/qa`)
|
|
377
|
+
: await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/qa/check", {
|
|
378
|
+
...(typeof flags.subject === "string" ? { subject: flags.subject } : {}),
|
|
379
|
+
...(typeof flags.text === "string" ? { text: flags.text } : {}),
|
|
380
|
+
...(typeof flags.html === "string" ? { html: flags.html } : {}),
|
|
381
|
+
});
|
|
382
|
+
print(res, `QA Score: ${res.score}/100 (${res.status})`);
|
|
383
|
+
if (failBelow !== undefined && Number(res.score) < failBelow) {
|
|
384
|
+
errOut(`QA score ${res.score} is below threshold ${failBelow}`);
|
|
385
|
+
return 1;
|
|
386
|
+
}
|
|
387
|
+
return 0;
|
|
388
|
+
}
|
|
389
|
+
if (cmd === "domains") {
|
|
390
|
+
if (sub === "add") {
|
|
391
|
+
const domain = positionals[2]?.trim().toLowerCase();
|
|
392
|
+
if (!domain)
|
|
393
|
+
throw new Error("Usage: apimend domains add <domain>");
|
|
394
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/domains", { domain });
|
|
395
|
+
print(res, `Added domain ${res.domain} (verified=${Boolean(res.verified)})`);
|
|
396
|
+
return 0;
|
|
397
|
+
}
|
|
398
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/domains");
|
|
399
|
+
const rows = (res.data ?? []);
|
|
400
|
+
print(res, rows.length ? rows.map((d) => `${d.domain} verified=${Boolean(d.verified)}`).join("\n") : "No domains configured.");
|
|
401
|
+
return 0;
|
|
402
|
+
}
|
|
403
|
+
if (cmd === "dns" && sub === "check") {
|
|
404
|
+
const domainName = positionals[2]?.trim().toLowerCase();
|
|
405
|
+
if (!domainName)
|
|
406
|
+
throw new Error("Domain name is required.");
|
|
407
|
+
const verified = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", `/v1/domains/${encodeURIComponent(domainName)}/verify`, {});
|
|
408
|
+
print(verified, `${domainName}: verified=${Boolean(verified.verified)}`);
|
|
409
|
+
return 0;
|
|
410
|
+
}
|
|
411
|
+
if (cmd === "webhooks") {
|
|
412
|
+
if (sub === "test") {
|
|
413
|
+
const webhookId = positionals[2];
|
|
414
|
+
if (!webhookId)
|
|
415
|
+
throw new Error("Usage: apimend webhooks test <webhookId>");
|
|
416
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/test-webhook", { endpointId: webhookId });
|
|
417
|
+
print(res, `Webhook test queued: ${JSON.stringify(res)}`);
|
|
418
|
+
return 0;
|
|
419
|
+
}
|
|
420
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/webhooks");
|
|
421
|
+
const rows = (res.data ?? []);
|
|
422
|
+
print(res, rows.length ? rows.map((w) => `${w.id} ${w.active ? "active" : "paused"} ${w.url}`).join("\n") : "No webhooks configured.");
|
|
423
|
+
return 0;
|
|
424
|
+
}
|
|
425
|
+
if (cmd === "suppressions") {
|
|
426
|
+
if (sub === "add") {
|
|
427
|
+
const email = positionals[2];
|
|
428
|
+
if (!email)
|
|
429
|
+
throw new Error("Usage: apimend suppressions add <email>");
|
|
430
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/suppressions", { email, reason: String(flags.reason ?? "manual") });
|
|
431
|
+
print(res, `Suppressed ${email}`);
|
|
432
|
+
return 0;
|
|
433
|
+
}
|
|
434
|
+
if (sub === "remove") {
|
|
435
|
+
const email = positionals[2];
|
|
436
|
+
if (!email)
|
|
437
|
+
throw new Error("Usage: apimend suppressions remove <email>");
|
|
438
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "DELETE", `/v1/suppressions/${encodeURIComponent(email)}`);
|
|
439
|
+
print(res, `Removed suppression for ${email}`);
|
|
440
|
+
return 0;
|
|
441
|
+
}
|
|
442
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/suppressions");
|
|
443
|
+
const rows = (res.data ?? []);
|
|
444
|
+
print(res, rows.length ? rows.map((s) => `${s.email} (${s.reason})`).join("\n") : "No suppressions.");
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
if (cmd === "approvals") {
|
|
448
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/approvals");
|
|
449
|
+
const rows = (res.data ?? []);
|
|
450
|
+
print(res, rows.length ? rows.map((a) => `${a.id} ${a.to?.join(",")} "${a.subject}"`).join("\n") : "No emails pending approval.");
|
|
451
|
+
return 0;
|
|
452
|
+
}
|
|
453
|
+
if (cmd === "analytics") {
|
|
454
|
+
const days = Number(flags.days) || 7;
|
|
455
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", `/v1/analytics?days=${days}`);
|
|
456
|
+
print(res, `Analytics (${days}d): ${JSON.stringify(res.totals ?? res)}`);
|
|
457
|
+
return 0;
|
|
458
|
+
}
|
|
459
|
+
if (cmd === "templates") {
|
|
460
|
+
const dir = typeof flags.dir === "string" ? flags.dir : "./apimend-templates";
|
|
461
|
+
if (sub === "list") {
|
|
462
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/templates");
|
|
463
|
+
const items = (res.data ?? []);
|
|
464
|
+
print(res, items.length ? items.map((t) => `${t.id} ${t.name} "${t.subject}"`).join("\n") : "No templates.");
|
|
465
|
+
return 0;
|
|
466
|
+
}
|
|
467
|
+
if (sub === "pull") {
|
|
468
|
+
const res = await apiRequest({ apiKey, baseUrl, fetcher }, "GET", "/v1/templates");
|
|
469
|
+
const items = (res.data ?? []);
|
|
470
|
+
await mkdir(dir, { recursive: true });
|
|
471
|
+
for (const tpl of items) {
|
|
472
|
+
const slug = String(tpl.name || tpl.id).replace(/[^a-z0-9._-]+/gi, "-").toLowerCase();
|
|
473
|
+
await writeFile(join(dir, `${slug}.json`), JSON.stringify({ id: tpl.id, name: tpl.name, subject: tpl.subject, html: tpl.html, text: tpl.text }, null, 2));
|
|
474
|
+
}
|
|
475
|
+
print({ count: items.length, dir }, `Pulled ${items.length} templates to ${dir}`);
|
|
476
|
+
return 0;
|
|
477
|
+
}
|
|
478
|
+
if (sub === "push") {
|
|
479
|
+
const files = (await readdir(dir)).filter((f) => f.endsWith(".json"));
|
|
480
|
+
let pushed = 0;
|
|
481
|
+
for (const file of files) {
|
|
482
|
+
const raw = JSON.parse(await readFile(join(dir, file), "utf8"));
|
|
483
|
+
if (raw.id) {
|
|
484
|
+
await apiRequest({ apiKey, baseUrl, fetcher }, "PATCH", `/v1/templates/${encodeURIComponent(raw.id)}`, {
|
|
485
|
+
name: raw.name,
|
|
486
|
+
subject: raw.subject,
|
|
487
|
+
html: raw.html,
|
|
488
|
+
...(raw.text ? { text: raw.text } : {}),
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
await apiRequest({ apiKey, baseUrl, fetcher }, "POST", "/v1/templates", raw);
|
|
493
|
+
}
|
|
494
|
+
pushed++;
|
|
495
|
+
}
|
|
496
|
+
print({ pushed, dir }, `Pushed ${pushed} templates from ${dir}`);
|
|
497
|
+
return 0;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
throw new Error(`Unknown command: ${positionals.join(" ")}`);
|
|
501
|
+
}
|
|
502
|
+
catch (err) {
|
|
503
|
+
errOut(err instanceof Error ? err.message : String(err));
|
|
504
|
+
return 1;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
508
|
+
runCli(process.argv.slice(2)).then((code) => {
|
|
509
|
+
process.exitCode = code;
|
|
510
|
+
});
|
|
511
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apimend",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Official CLI for Apimend Mail: sandbox sends, inbox & thread management, SSE event tailing, diagnostics, QA, DNS checks, and template sync.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"apimend": "dist/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://www.apimend.com/topics/cli",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/CoderSufiyan/apimend.git",
|
|
17
|
+
"directory": "mail/cli"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc",
|
|
21
|
+
"prepack": "npm run build",
|
|
22
|
+
"test": "node --import tsx --test index.test.ts"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT"
|
|
28
|
+
}
|