delivrie-cli 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Surce Inc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # Delivrie CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send email and manage your [Delivrie](https://delivrie.io) account from the terminal: domains, API keys, webhooks,
4
+ templates, contacts, suppressions and logs. No dependencies; needs Node.js 18 or later.
5
+
6
+ ```sh
7
+ npm install -g delivrie-cli # or run any command with npx delivrie-cli
8
+ delivrie login # paste an API key from https://delivrie.io/api-keys
9
+ delivrie send -f "Acme <hi@acme.com>" -t ada@example.com -s "Hello" --text "It works"
10
+ ```
11
+
12
+ ## Commands
13
+
14
+ | Command | What it does |
15
+ | --- | --- |
16
+ | `delivrie login` / `logout` / `whoami` | Save, remove or check the API key |
17
+ | `delivrie usage` | Plan, emails sent this month and today |
18
+ | `delivrie send` | Send an email: HTML, text, a template, attachments, tags, headers, scheduling |
19
+ | `delivrie emails list\|get\|cancel\|reschedule` | Recent emails, one email's events, change a scheduled email |
20
+ | `delivrie domains list\|add\|get\|verify\|delete` | Add a domain, see its DNS records, check DNS |
21
+ | `delivrie keys list\|create\|delete` | API keys (`--sending` for a sending-only key) |
22
+ | `delivrie webhooks list\|create\|test\|deliveries` | Endpoints, test events, delivery attempts |
23
+ | `delivrie templates import <file.html>` | Upload an HTML template as written; `--publish` to make it live |
24
+ | `delivrie templates list\|get\|create\|update\|publish\|delete` | Templates by id or alias |
25
+ | `delivrie contacts list\|add\|get\|delete` | Contacts by id or email |
26
+ | `delivrie suppressions list\|add\|remove` | Addresses Delivrie won't send to |
27
+ | `delivrie logs list\|get` | API request logs |
28
+
29
+ Run `delivrie <command> --help` for options. Add `--json` to any command for the raw API response, which makes the
30
+ CLI easy to script:
31
+
32
+ ```sh
33
+ id=$(delivrie send -f hi@acme.com -t ada@example.com -s Hi --text Hi -q)
34
+ delivrie emails get "$id" --json | jq .last_event
35
+ cat welcome.html | delivrie send -f hi@acme.com -t ada@example.com -s Welcome --html-file -
36
+ delivrie send -t ada@example.com --template welcome --var name=Ada
37
+ ```
38
+
39
+ ## Keys and settings
40
+
41
+ `delivrie login` saves the key in `~/.config/delivrie/config.json` (readable only by you). In CI, set
42
+ `DELIVRIE_API_KEY` instead; it always wins over the saved key. `--api-key` overrides both for one command.
43
+ `DELIVRIE_BASE_URL` or `--base-url` points the CLI at another API address.
44
+
45
+ Sends always carry an idempotency key, so a retried send never goes out twice; pass `--idempotency-key` to choose it.
46
+ Deleting asks for confirmation; `--yes` skips the question in scripts.
47
+
48
+ Exit codes: `0` success, `1` the API returned an error, `2` the command was used wrongly.
49
+
50
+ Docs: https://delivrie.io/docs/cli
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../dist/cli.js";
3
+
4
+ const major = Number(process.versions.node.split(".")[0]);
5
+ if (major < 18) { process.stderr.write("The Delivrie CLI needs Node.js 18 or later.\n"); process.exit(1); }
6
+ run(process.argv.slice(2)).then((code) => { process.exitCode = code; });
package/dist/api.js ADDED
@@ -0,0 +1,58 @@
1
+ // A small API client for the CLI: bearer key, JSON in and out, retries for rate limits and server errors.
2
+ // Sends (POST/PATCH) are only retried with an idempotency key, so a retry never sends an email twice.
3
+ import { VERSION } from "./version.js";
4
+ export class ApiError extends Error {
5
+ constructor(status, name, message) {
6
+ super(message);
7
+ this.status = status;
8
+ this.code = name;
9
+ }
10
+ }
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
+ export function createClient({ key, baseUrl, timeout = 30000, maxRetries = 2, fetchImpl = globalThis.fetch }) {
13
+ const base = baseUrl.replace(/\/+$/, "");
14
+ async function request(method, path, body, { query, idempotencyKey } = {}) {
15
+ let url = base + path;
16
+ if (query) {
17
+ const q = Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== "").map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
18
+ if (q)
19
+ url += (url.includes("?") ? "&" : "?") + q;
20
+ }
21
+ const headers = { authorization: `Bearer ${key}`, accept: "application/json", "user-agent": `delivrie-cli/${VERSION}` };
22
+ if (body !== undefined)
23
+ headers["content-type"] = "application/json";
24
+ if (idempotencyKey)
25
+ headers["idempotency-key"] = idempotencyKey;
26
+ const retryable = method === "GET" || method === "DELETE" || !!idempotencyKey;
27
+ for (let attempt = 0;; attempt++) {
28
+ let res;
29
+ try {
30
+ res = await fetchImpl(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeout) });
31
+ }
32
+ catch (e) {
33
+ if (retryable && attempt < maxRetries) {
34
+ await sleep(500 * 2 ** attempt);
35
+ continue;
36
+ }
37
+ const timedOut = e?.name === "TimeoutError" || e?.name === "AbortError";
38
+ throw new ApiError(0, timedOut ? "timeout" : "network_error", timedOut ? `No response from ${base} within ${timeout / 1000}s` : `Couldn't reach ${base} (${e?.cause?.code || e?.message || "network error"})`);
39
+ }
40
+ const text = await res.text();
41
+ let json = null;
42
+ try {
43
+ json = text ? JSON.parse(text) : null;
44
+ }
45
+ catch { /* not JSON */ }
46
+ if (res.ok)
47
+ return json;
48
+ const name = (json && json.name) || (res.status === 401 ? "invalid_api_key" : res.status === 404 ? "not_found" : res.status === 429 ? "rate_limit_exceeded" : "application_error");
49
+ if ((res.status === 429 || res.status >= 500) && retryable && attempt < maxRetries) {
50
+ const after = Number(res.headers.get("retry-after"));
51
+ await sleep(Number.isFinite(after) && after > 0 ? Math.min(after, 30) * 1000 : 500 * 2 ** attempt);
52
+ continue;
53
+ }
54
+ throw new ApiError(res.status, name, (json && json.message) || text.slice(0, 300) || `Request failed with status ${res.status}`);
55
+ }
56
+ }
57
+ return { request, baseUrl: base };
58
+ }
package/dist/args.js ADDED
@@ -0,0 +1,47 @@
1
+ export function parseArgs(argv, { booleans = [], repeatable = [], aliases = {} } = {}) {
2
+ const flags = {}, positionals = [];
3
+ const set = (k, v) => {
4
+ k = aliases[k] || k;
5
+ if (repeatable.includes(k))
6
+ (flags[k] ||= []).push(v);
7
+ else
8
+ flags[k] = v;
9
+ };
10
+ for (let i = 0; i < argv.length; i++) {
11
+ const a = argv[i];
12
+ if (a === "--") {
13
+ positionals.push(...argv.slice(i + 1));
14
+ break;
15
+ }
16
+ if (a.startsWith("--") || (a.startsWith("-") && a.length === 2 && !/^-\d/.test(a))) {
17
+ let k = a.replace(/^--?/, ""), v;
18
+ const eq = k.indexOf("=");
19
+ if (eq >= 0) {
20
+ v = k.slice(eq + 1);
21
+ k = k.slice(0, eq);
22
+ }
23
+ if (k.startsWith("no-") && booleans.includes(aliases[k.slice(3)] || k.slice(3))) {
24
+ set(k.slice(3), false);
25
+ continue;
26
+ }
27
+ const name = aliases[k] || k;
28
+ if (booleans.includes(name)) {
29
+ set(k, v === undefined ? true : !/^(false|0|no)$/i.test(v));
30
+ continue;
31
+ }
32
+ if (v === undefined) {
33
+ const next = argv[i + 1];
34
+ if (next === undefined || (next.startsWith("--") && next.length > 2))
35
+ throw new UsageError(`--${name} needs a value`);
36
+ v = next;
37
+ i++;
38
+ }
39
+ set(k, v);
40
+ }
41
+ else
42
+ positionals.push(a);
43
+ }
44
+ return { flags, positionals };
45
+ }
46
+ export class UsageError extends Error {
47
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,697 @@
1
+ // The Delivrie CLI. `run(argv, io)` returns an exit code; io carries stdout/stderr/stdin/env/fetch so tests can drive it.
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { parseArgs, UsageError } from "./args.js";
6
+ import { createClient, ApiError } from "./api.js";
7
+ import { readConfig, writeConfig, clearConfig, configPath } from "./config.js";
8
+ import { makeOut, when, list } from "./format.js";
9
+ import { VERSION } from "./version.js";
10
+ const DEFAULT_BASE = "https://delivrie.io/api";
11
+ const BOOLEANS = ["json", "yes", "help", "version", "sending", "received", "quiet", "publish"];
12
+ const REPEATABLE = ["to", "cc", "bcc", "reply-to", "attach", "tag", "header", "var", "events"];
13
+ const ALIASES = { h: "help", v: "version", y: "yes", q: "quiet", f: "from", t: "to", s: "subject", n: "limit" };
14
+ const HELP = {
15
+ main: `Delivrie CLI ${VERSION}
16
+
17
+ Usage: delivrie <command> [options]
18
+
19
+ Account
20
+ login Save an API key (or set DELIVRIE_API_KEY)
21
+ logout Forget the saved key
22
+ whoami Show which key and account the CLI is using
23
+ usage Plan, emails sent this month and today
24
+
25
+ Sending
26
+ send Send an email (see delivrie send --help)
27
+ emails list|get|cancel|reschedule
28
+
29
+ Setup
30
+ domains list|add|get|verify|delete
31
+ keys list|create|delete
32
+ webhooks list|create|test|deliveries
33
+ templates list|get|import|create|update|publish|delete
34
+
35
+ Audience and logs
36
+ contacts list|add|get|delete
37
+ suppressions list|add|remove
38
+ logs list|get
39
+
40
+ Options for every command
41
+ --json Print the raw JSON response
42
+ --api-key <key> Use this key instead of the saved one
43
+ --base-url <url> API address (default ${DEFAULT_BASE})
44
+ -h, --help Help for a command
45
+ -v, --version Print the version
46
+
47
+ Docs: https://delivrie.io/docs/cli`,
48
+ login: `Usage: delivrie login [--api-key <key>]
49
+
50
+ Saves an API key to ${"~/.config/delivrie/config.json"} (readable only by you). Without --api-key it asks for it.
51
+ Create a key at https://delivrie.io/api-keys. In CI, set DELIVRIE_API_KEY instead of logging in.`,
52
+ send: `Usage: delivrie send --from <sender> --to <address> --subject <text> (--html <html> | --text <text> | --template <id>)
53
+
54
+ -f, --from <sender> "Acme <hi@acme.com>" on a verified domain
55
+ -t, --to <address> Repeat or comma-separate for several (up to 50)
56
+ --cc, --bcc <address> Repeatable
57
+ --reply-to <address> Repeatable
58
+ -s, --subject <text>
59
+ --html <html> HTML body
60
+ --html-file <path> HTML body from a file ("-" reads stdin)
61
+ --text <text> Plain-text body (made from the HTML when left out)
62
+ --text-file <path> Plain-text body from a file ("-" reads stdin)
63
+ --template <id|alias> Send a published template
64
+ --var key=value Template variable, repeatable
65
+ --attach <path> Attach a file, repeatable
66
+ --tag name=value Repeatable
67
+ --header Name:value Custom header, repeatable
68
+ --schedule <when> ISO time or "in 1 hour", "tomorrow at 9am" (UTC)
69
+ --idempotency-key <k> Retrying with the same key never sends twice (one is made for you if left out)
70
+ -q, --quiet Print only the email id
71
+
72
+ Examples
73
+ delivrie send -f "Acme <hi@acme.com>" -t ada@example.com -s "Hello" --text "It works"
74
+ cat welcome.html | delivrie send -f hi@acme.com -t ada@example.com -s Welcome --html-file -
75
+ delivrie send -t ada@example.com --template welcome --var name=Ada`,
76
+ emails: `Usage:
77
+ delivrie emails list [--limit 20] [--offset 0] [--received]
78
+ delivrie emails get <id>
79
+ delivrie emails cancel <id> Cancel a scheduled email
80
+ delivrie emails reschedule <id> --at <when> Move a scheduled email`,
81
+ domains: `Usage:
82
+ delivrie domains list
83
+ delivrie domains add <name> [--region eu-west-1] [--return-path send]
84
+ delivrie domains get <id|name> Shows the DNS records to add
85
+ delivrie domains verify <id|name> Check DNS now
86
+ delivrie domains delete <id|name> [--yes]`,
87
+ keys: `Usage:
88
+ delivrie keys list
89
+ delivrie keys create <name> [--sending] [--domain <id|name>] The key is shown once
90
+ delivrie keys delete <id> [--yes]`,
91
+ webhooks: `Usage:
92
+ delivrie webhooks list
93
+ delivrie webhooks create <https-url> --events email.delivered,email.bounced ("*" for all)
94
+ delivrie webhooks test <id>
95
+ delivrie webhooks deliveries <id>`,
96
+ templates: `Usage:
97
+ delivrie templates list
98
+ delivrie templates get <id|alias>
99
+ delivrie templates import <file.html|-> [--name <name>] [--alias <alias>] [--subject <text>] [--from <sender>] [--publish]
100
+ delivrie templates create --name <name> [--html-file <file|->] [--alias <alias>] [--subject <text>] [--from <sender>]
101
+ delivrie templates update <id|alias> [--html-file <file|->] [--name ..] [--alias ..] [--subject ..] [--from ..]
102
+ delivrie templates publish <id|alias>
103
+ delivrie templates delete <id|alias> [--yes]
104
+
105
+ import keeps your HTML exactly as written. The name comes from the file (or its <title>), the alias from the file name,
106
+ and every {{variable}} in it is listed on the template. Changes stay a draft until you publish.
107
+ delivrie templates import emails/order-shipped.html --publish
108
+ cat welcome.html | delivrie templates import - --name Welcome --alias welcome`,
109
+ contacts: `Usage:
110
+ delivrie contacts list [--limit 50] [--offset 0]
111
+ delivrie contacts add <email> [--first-name Ada] [--last-name Lovelace]
112
+ delivrie contacts get <id|email>
113
+ delivrie contacts delete <id|email> [--yes]`,
114
+ suppressions: `Usage:
115
+ delivrie suppressions list
116
+ delivrie suppressions add <email> [<email>...]
117
+ delivrie suppressions remove <email>`,
118
+ logs: `Usage:
119
+ delivrie logs list [--limit 20] [--offset 0]
120
+ delivrie logs get <id>`,
121
+ };
122
+ /** Runs one command and resolves with its exit code. */
123
+ export async function run(argv, io = {}) {
124
+ const stdout = io.stdout || process.stdout, stderr = io.stderr || process.stderr, env = io.env || process.env;
125
+ const out = makeOut(stdout, env), err = makeOut(stderr, env);
126
+ const print = (s = "") => stdout.write(s + "\n");
127
+ const fail = (msg, code = 1) => { stderr.write(err.red("Error: ") + msg + "\n"); return code; };
128
+ let flags, pos;
129
+ try {
130
+ ({ flags, positionals: pos } = parseArgs(argv, { booleans: BOOLEANS, repeatable: REPEATABLE, aliases: ALIASES }));
131
+ }
132
+ catch (e) {
133
+ return fail(e.message, 2);
134
+ }
135
+ const [cmd, sub, ...rest] = pos;
136
+ if (flags.version) {
137
+ print(VERSION);
138
+ return 0;
139
+ }
140
+ if (!cmd || cmd === "help") {
141
+ print(HELP[sub] || HELP.main);
142
+ return 0;
143
+ }
144
+ if (flags.help) {
145
+ print(HELP[cmd] || HELP.main);
146
+ return 0;
147
+ }
148
+ const cfg = readConfig(env);
149
+ const baseUrl = flags["base-url"] || env.DELIVRIE_BASE_URL || cfg.base_url || DEFAULT_BASE;
150
+ const keyFrom = flags["api-key"] ? "--api-key" : env.DELIVRIE_API_KEY ? "DELIVRIE_API_KEY" : cfg.api_key ? configPath(env) : null;
151
+ const key = flags["api-key"] || env.DELIVRIE_API_KEY || cfg.api_key;
152
+ const client = (k = key) => createClient({ key: k, baseUrl, fetchImpl: io.fetch || globalThis.fetch });
153
+ const need = () => { if (!key)
154
+ throw new UsageError("No API key. Run `delivrie login`, or set DELIVRIE_API_KEY. Create one at https://delivrie.io/api-keys"); return client(); };
155
+ const json = (v) => print(JSON.stringify(v, null, 2));
156
+ const show = (v, human) => (flags.json ? json(v) : human(v));
157
+ const listOf = (r) => (Array.isArray(r?.data) ? r.data : Array.isArray(r) ? r : []);
158
+ const empty = (what) => print(out.dim(`No ${what} yet.`));
159
+ const confirm = async (q) => {
160
+ if (flags.yes)
161
+ return true;
162
+ const stdin = io.stdin || process.stdin;
163
+ if (!stdin.isTTY)
164
+ throw new UsageError(`${q} Add --yes to confirm.`);
165
+ stderr.write(`${q} [y/N] `);
166
+ const ans = await readLine(stdin);
167
+ return /^y(es)?$/i.test(ans.trim());
168
+ };
169
+ const resolveDomain = async (api, ref) => {
170
+ if (!ref)
171
+ throw new UsageError("Give a domain id or name");
172
+ if (!ref.includes("."))
173
+ return ref;
174
+ const d = listOf(await api.request("GET", "/domains")).find((x) => x.name === ref.toLowerCase());
175
+ if (!d)
176
+ throw new ApiError(404, "not_found", `No domain named ${ref} on this account`);
177
+ return d.id;
178
+ };
179
+ try {
180
+ switch (cmd) {
181
+ // ------------------------------------------------------------ account
182
+ case "login": {
183
+ let k = flags["api-key"];
184
+ if (!k) {
185
+ const stdin = io.stdin || process.stdin;
186
+ if (!stdin.isTTY)
187
+ k = (await readAll(stdin)).trim();
188
+ else {
189
+ stderr.write("API key (from https://delivrie.io/api-keys): ");
190
+ k = (await readLine(stdin, { hidden: true })).trim();
191
+ stderr.write("\n");
192
+ }
193
+ }
194
+ if (!/^dlv_[A-Za-z0-9_-]{8,}$/.test(k || ""))
195
+ return fail("That doesn't look like a Delivrie API key (they start with dlv_).");
196
+ const who = await checkKey(client(k));
197
+ if (who.permission === "invalid")
198
+ return fail("Delivrie didn't accept that key. Check it, or create a new one at https://delivrie.io/api-keys");
199
+ const file = writeConfig({ ...cfg, api_key: k, ...(flags["base-url"] ? { base_url: flags["base-url"] } : {}) }, env);
200
+ if (flags.json)
201
+ return json({ saved: file, permission: who.permission }), 0;
202
+ print(out.green("✓") + ` Logged in with a ${who.permission === "sending" ? "sending-only" : "full-access"} key. Saved to ${file}`);
203
+ if (who.permission === "sending")
204
+ print(out.dim(" Sending-only keys can send email but can't list or change domains, keys or webhooks."));
205
+ return 0;
206
+ }
207
+ case "logout": {
208
+ const had = clearConfig(env);
209
+ print(had ? "Logged out. The saved key was removed." : "No saved key to remove.");
210
+ if (env.DELIVRIE_API_KEY)
211
+ print(out.dim("DELIVRIE_API_KEY is still set in this shell."));
212
+ return 0;
213
+ }
214
+ case "whoami": {
215
+ if (!key)
216
+ return fail("Not logged in. Run `delivrie login`, or set DELIVRIE_API_KEY.");
217
+ const who = await checkKey(client());
218
+ if (flags.json)
219
+ return json({ key_prefix: key.slice(0, 10), source: keyFrom, base_url: baseUrl, ...who }), 0;
220
+ if (who.permission === "invalid")
221
+ return fail("The key in use was rejected. Run `delivrie login` with a new one.");
222
+ print(`${out.bold("Key")} ${key.slice(0, 10)}… (${who.permission === "sending" ? "sending only" : "full access"})`);
223
+ print(`${out.bold("From")} ${keyFrom}`);
224
+ print(`${out.bold("API")} ${baseUrl}`);
225
+ if (who.usage)
226
+ print(`${out.bold("Plan")} ${who.usage.plan} · ${fmtUsage(who.usage)}`);
227
+ return 0;
228
+ }
229
+ case "usage": {
230
+ const u = await need().request("GET", "/usage");
231
+ return show(u, () => {
232
+ print(`${out.bold("Plan")} ${u.plan}${u.marketing_plan && u.marketing_plan !== "free" ? ` (marketing: ${u.marketing_plan})` : ""}`);
233
+ print(`${out.bold("This month")} ${fmtUsage(u)}`);
234
+ print(`${out.bold("Today")} ${num(u.emails_today)}${u.daily_limit ? ` of ${num(u.daily_limit)}` : ""}`);
235
+ if (u.credits_emails)
236
+ print(`${out.bold("Credits")} ${num(u.credits_emails)} emails`);
237
+ }), 0;
238
+ }
239
+ // ------------------------------------------------------------ sending
240
+ case "send": {
241
+ const api = need();
242
+ const stdin = io.stdin || process.stdin;
243
+ const read = async (p) => (p === "-" ? readAll(stdin) : fs.readFileSync(p, "utf8"));
244
+ const splitList = (v) => (v || []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean);
245
+ const to = splitList(flags.to).concat(sub && sub.includes("@") ? [sub] : []);
246
+ if (!to.length)
247
+ throw new UsageError("Add at least one --to address");
248
+ const body = { to };
249
+ if (flags.from)
250
+ body.from = flags.from;
251
+ if (flags.subject)
252
+ body.subject = flags.subject;
253
+ if (flags.html !== undefined)
254
+ body.html = flags.html;
255
+ if (flags["html-file"])
256
+ body.html = await read(flags["html-file"]);
257
+ if (flags.text !== undefined)
258
+ body.text = flags.text;
259
+ if (flags["text-file"])
260
+ body.text = await read(flags["text-file"]);
261
+ if (flags.cc)
262
+ body.cc = splitList(flags.cc);
263
+ if (flags.bcc)
264
+ body.bcc = splitList(flags.bcc);
265
+ if (flags["reply-to"])
266
+ body.reply_to = splitList(flags["reply-to"]);
267
+ if (flags.template)
268
+ body.template = { id: flags.template, ...(flags.var ? { variables: pairs(flags.var, "=", "--var") } : {}) };
269
+ if (flags.tag)
270
+ body.tags = Object.entries(pairs(flags.tag, "=", "--tag")).map(([name, value]) => ({ name, value }));
271
+ if (flags.header)
272
+ body.headers = pairs(flags.header, ":", "--header");
273
+ if (flags.schedule)
274
+ body.scheduled_at = flags.schedule;
275
+ if (flags.attach)
276
+ body.attachments = flags.attach.map((p) => ({ filename: path.basename(p), content: fs.readFileSync(p).toString("base64") }));
277
+ if (!body.template && body.html === undefined && body.text === undefined)
278
+ throw new UsageError("Add a body: --html, --html-file, --text, --text-file or --template");
279
+ if (!body.template && !body.subject)
280
+ throw new UsageError("Add a --subject");
281
+ const r = await api.request("POST", "/emails", body, { idempotencyKey: flags["idempotency-key"] || randomUUID() });
282
+ if (flags.json)
283
+ return json(r), 0;
284
+ if (flags.quiet)
285
+ return print(r.id), 0;
286
+ print(out.green("✓") + ` ${body.scheduled_at ? "Scheduled" : "Sent"} ${out.bold(r.id)} to ${to.join(", ")}`);
287
+ print(out.dim(` Track it: delivrie emails get ${r.id}`));
288
+ return 0;
289
+ }
290
+ case "emails": {
291
+ const api = need();
292
+ if (sub === "list" || !sub) {
293
+ const r = await api.request("GET", flags.received ? "/emails/received" : "/emails", undefined, { query: { limit: flags.limit || 20, offset: flags.offset } });
294
+ return show(r, () => {
295
+ const rows = listOf(r);
296
+ if (!rows.length)
297
+ return empty(flags.received ? "received emails" : "emails");
298
+ print(out.table(rows, [
299
+ { label: "ID", get: (e) => e.id },
300
+ { label: "STATUS", get: (e) => out.statusColor(e.last_event || e.status || (flags.received ? "received" : "")) },
301
+ { label: flags.received ? "FROM" : "TO", get: (e) => trunc(flags.received ? e.from : list(e.to), 32) },
302
+ { label: "SUBJECT", get: (e) => trunc(e.subject, 40) },
303
+ { label: "WHEN", get: (e) => when(e.scheduled_at && /scheduled/.test(e.last_event || e.status) ? e.scheduled_at : e.created_at) },
304
+ ]));
305
+ }), 0;
306
+ }
307
+ const id = need1(rest[0], "email id");
308
+ if (sub === "get") {
309
+ const e = await api.request("GET", `/emails/${enc(id)}`);
310
+ return show(e, () => {
311
+ print(`${out.bold(e.subject || "(no subject)")} ${out.statusColor(e.last_event)}`);
312
+ print(`${out.dim("ID")} ${e.id}`);
313
+ print(`${out.dim("From")} ${e.from}`);
314
+ print(`${out.dim("To")} ${list(e.to)}`);
315
+ if (e.cc?.length)
316
+ print(`${out.dim("Cc")} ${list(e.cc)}`);
317
+ print(`${out.dim("Created")} ${when(e.created_at)}`);
318
+ if (e.scheduled_at)
319
+ print(`${out.dim("Sends")} ${e.scheduled_at}`);
320
+ if (e.error)
321
+ print(`${out.dim("Error")} ${out.red(e.error)}`);
322
+ if (e.events?.length) {
323
+ print("");
324
+ print(out.dim("Events"));
325
+ for (const ev of e.events)
326
+ print(` ${when(ev.created_at).padEnd(17)} ${out.statusColor(ev.type.replace(/^email\./, ""))}`);
327
+ }
328
+ }), 0;
329
+ }
330
+ if (sub === "cancel") {
331
+ const r = await api.request("POST", `/emails/${enc(id)}/cancel`);
332
+ return show(r, () => print(out.green("✓") + ` Canceled ${id}`)), 0;
333
+ }
334
+ if (sub === "reschedule") {
335
+ if (!flags.at)
336
+ throw new UsageError("Add --at <when>, like --at \"in 2 hours\" or an ISO time");
337
+ const r = await api.request("PATCH", `/emails/${enc(id)}`, { scheduled_at: flags.at });
338
+ return show(r, () => print(out.green("✓") + ` ${id} now sends ${flags.at}`)), 0;
339
+ }
340
+ throw new UsageError(`Unknown: emails ${sub}. Try delivrie emails --help`);
341
+ }
342
+ // ------------------------------------------------------------ setup
343
+ case "domains": {
344
+ const api = need();
345
+ if (sub === "list" || !sub) {
346
+ const r = await api.request("GET", "/domains");
347
+ return show(r, () => {
348
+ const rows = listOf(r);
349
+ if (!rows.length)
350
+ return empty("domains") || print(out.dim("Add one: delivrie domains add example.com"));
351
+ print(out.table(rows, [{ label: "ID", get: (d) => d.id }, { label: "NAME", get: (d) => d.name }, { label: "STATUS", get: (d) => out.statusColor(d.status) }, { label: "REGION", get: (d) => d.region_label || d.region }, { label: "ADDED", get: (d) => when(d.created_at) }]));
352
+ }), 0;
353
+ }
354
+ if (sub === "add") {
355
+ const name = need1(rest[0], "domain name");
356
+ const d = await api.request("POST", "/domains", { name, ...(flags.region ? { region: flags.region } : {}), ...(flags["return-path"] ? { return_path: flags["return-path"] } : {}) });
357
+ return show(d, () => { print(out.green("✓") + ` Added ${out.bold(d.name)} (${d.id}). Add these DNS records, then run: delivrie domains verify ${d.name}`); print(""); printRecords(d); }), 0;
358
+ }
359
+ const id = await resolveDomain(api, rest[0]);
360
+ if (sub === "get") {
361
+ const d = await api.request("GET", `/domains/${enc(id)}`);
362
+ return show(d, () => { print(`${out.bold(d.name)} ${out.statusColor(d.status)} ${out.dim(d.id)}`); print(""); printRecords(d); }), 0;
363
+ }
364
+ if (sub === "verify") {
365
+ const d = await api.request("POST", `/domains/${enc(id)}/verify`);
366
+ return show(d, () => { print(`${out.bold(d.name)}: ${out.statusColor(d.status)}`); if (d.status !== "verified") {
367
+ print("");
368
+ printRecords(d);
369
+ print("");
370
+ print(out.dim("DNS changes can take a few minutes to show up. Run verify again later."));
371
+ } }), 0;
372
+ }
373
+ if (sub === "delete") {
374
+ if (!(await confirm(`Delete ${rest[0]}? Emails can't be sent from it afterwards.`)))
375
+ return print("Kept it."), 0;
376
+ const r = await api.request("DELETE", `/domains/${enc(id)}`);
377
+ return show(r, () => print(out.green("✓") + ` Deleted ${rest[0]}`)), 0;
378
+ }
379
+ throw new UsageError(`Unknown: domains ${sub}. Try delivrie domains --help`);
380
+ }
381
+ case "keys": {
382
+ const api = need();
383
+ if (sub === "list" || !sub) {
384
+ const r = await api.request("GET", "/api-keys");
385
+ return show(r, () => {
386
+ const rows = listOf(r);
387
+ if (!rows.length)
388
+ return empty("API keys");
389
+ print(out.table(rows, [{ label: "ID", get: (k) => k.id }, { label: "NAME", get: (k) => k.name }, { label: "KEY", get: (k) => (k.prefix || "") + "…" }, { label: "ACCESS", get: (k) => k.permission }, { label: "LAST USED", get: (k) => (k.last_used_at ? when(k.last_used_at) : out.dim("never")) }]));
390
+ }), 0;
391
+ }
392
+ if (sub === "create") {
393
+ const name = need1(rest[0], "key name");
394
+ const body = { name, permission: flags.sending ? "sending_access" : "full_access" };
395
+ if (flags.domain)
396
+ body.domain_id = await resolveDomain(api, flags.domain);
397
+ const r = await api.request("POST", "/api-keys", body);
398
+ return show(r, () => { print(out.green("✓") + ` Created ${out.bold(name)} (${r.id}). Copy it now, it's only shown once:`); print(""); print(" " + out.bold(r.token)); print(""); }), 0;
399
+ }
400
+ if (sub === "delete") {
401
+ const id = need1(rest[0], "key id");
402
+ if (!(await confirm(`Delete key ${id}? Anything using it stops working.`)))
403
+ return print("Kept it."), 0;
404
+ const r = await api.request("DELETE", `/api-keys/${enc(id)}`);
405
+ return show(r, () => print(out.green("✓") + ` Deleted ${id}`)), 0;
406
+ }
407
+ throw new UsageError(`Unknown: keys ${sub}. Try delivrie keys --help`);
408
+ }
409
+ case "webhooks": {
410
+ const api = need();
411
+ if (sub === "list" || !sub) {
412
+ const r = await api.request("GET", "/webhooks");
413
+ return show(r, () => {
414
+ const rows = listOf(r);
415
+ if (!rows.length)
416
+ return empty("webhooks");
417
+ print(out.table(rows, [{ label: "ID", get: (w) => w.id }, { label: "ENDPOINT", get: (w) => trunc(w.endpoint, 44) }, { label: "EVENTS", get: (w) => trunc(list(w.events), 40) }, { label: "STATUS", get: (w) => out.statusColor(w.status) }]));
418
+ }), 0;
419
+ }
420
+ if (sub === "create") {
421
+ const endpoint = need1(rest[0], "endpoint URL");
422
+ const events = (flags.events || []).flatMap((e) => e.split(",")).map((e) => e.trim()).filter(Boolean);
423
+ if (!events.length)
424
+ throw new UsageError("Add --events, like --events email.delivered,email.bounced (or \"*\" for all)");
425
+ const r = await api.request("POST", "/webhooks", { endpoint, events });
426
+ return show(r, () => { print(out.green("✓") + ` Created ${r.id}. Its signing secret (shown once):`); print(""); print(" " + out.bold(r.signing_secret)); print(""); print(out.dim(" Verify requests with it: https://delivrie.io/docs/webhooks")); }), 0;
427
+ }
428
+ const id = need1(rest[0], "webhook id");
429
+ if (sub === "test") {
430
+ const r = await api.request("POST", `/webhooks/${enc(id)}/test`);
431
+ return show(r, () => print(out.green("✓") + ` Sent a test event to ${id}${r?.status_code ? ` (endpoint answered ${r.status_code})` : ""}`)), 0;
432
+ }
433
+ if (sub === "deliveries") {
434
+ const r = await api.request("GET", `/webhooks/${enc(id)}/events`);
435
+ return show(r, () => {
436
+ const rows = listOf(r);
437
+ if (!rows.length)
438
+ return empty("deliveries");
439
+ print(out.table(rows, [{ label: "ID", get: (d) => d.id }, { label: "EVENT", get: (d) => d.event_type }, { label: "RESULT", get: (d) => (d.delivered ? out.green("delivered") : out.red("failing")) }, { label: "HTTP", get: (d) => d.status_code ?? "" }, { label: "TRIES", get: (d) => d.attempts }, { label: "WHEN", get: (d) => when(d.created_at) }]));
440
+ }), 0;
441
+ }
442
+ throw new UsageError(`Unknown: webhooks ${sub}. Try delivrie webhooks --help`);
443
+ }
444
+ case "templates": {
445
+ const api = need();
446
+ if (sub === "list" || !sub) {
447
+ const r = await api.request("GET", "/templates");
448
+ return show(r, () => {
449
+ const rows = listOf(r);
450
+ if (!rows.length)
451
+ return empty("templates");
452
+ print(out.table(rows, [{ label: "ID", get: (t) => t.id }, { label: "NAME", get: (t) => trunc(t.name, 36) }, { label: "ALIAS", get: (t) => t.alias || "" }, { label: "STATUS", get: (t) => out.statusColor(t.status) }, { label: "UPDATED", get: (t) => when(t.updated_at) }]));
453
+ }), 0;
454
+ }
455
+ const stdin = io.stdin || process.stdin;
456
+ const readHtml = async (p) => (p === "-" ? readAll(stdin) : fs.readFileSync(p, "utf8"));
457
+ const varsIn = (html) => [...new Set([...html.matchAll(/\{\{\{?\s*([a-zA-Z_]\w*)/g)].map((m) => m[1]))];
458
+ const fields = (body) => { for (const k of ["name", "alias", "subject", "from"])
459
+ if (typeof flags[k] === "string")
460
+ body[k] = flags[k]; return body; };
461
+ if (sub === "import" || sub === "create") {
462
+ const file = sub === "import" ? need1(rest[0], "HTML file (or - to read stdin)") : flags["html-file"];
463
+ if (sub === "create" && !flags.name)
464
+ throw new UsageError("Give the template a --name");
465
+ const html = file ? await readHtml(file) : undefined;
466
+ if (sub === "import" && !html?.trim())
467
+ throw new UsageError("That file is empty");
468
+ const base = file && file !== "-" ? path.basename(file).replace(/\.html?$/i, "") : "";
469
+ const title = html?.match(/<title>([^<]+)<\/title>/i)?.[1]?.trim();
470
+ const body = { name: title || base.replace(/[-_]+/g, " ").replace(/^./, (c) => c.toUpperCase()) || "Imported template" };
471
+ if (base)
472
+ body.alias = base.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
473
+ if (title)
474
+ body.subject = title;
475
+ if (html !== undefined) {
476
+ body.html = html;
477
+ body.variables = varsIn(html).map((name) => ({ name, type: "string" }));
478
+ }
479
+ fields(body);
480
+ const t = await api.request("POST", "/templates", body);
481
+ let pub = null;
482
+ if (flags.publish)
483
+ pub = await api.request("POST", `/templates/${enc(t.id)}/publish`);
484
+ const kb = html ? Math.max(1, Math.round(Buffer.byteLength(html) / 1024)) : 0;
485
+ const warn = [];
486
+ if (html && /<link\b[^>]*rel=["']?stylesheet/i.test(html))
487
+ warn.push("It links an external stylesheet. Gmail and Outlook ignore those, so move the styles inline.");
488
+ if (kb > 102)
489
+ warn.push(`It's ${kb} KB. Gmail cuts emails off at 102 KB.`);
490
+ return show({ ...t, ...(pub ? { published_version: pub.version } : {}), variables: body.variables?.map((v) => v.name) || [] }, () => {
491
+ print(out.green("✓") + ` ${sub === "import" ? "Imported" : "Created"} ${out.bold(body.name)} ${out.dim(t.id)}`);
492
+ if (body.alias)
493
+ print(`${out.dim("Alias")} ${body.alias}`);
494
+ if (body.variables?.length)
495
+ print(`${out.dim("Variables")} ${body.variables.map((v) => v.name).join(", ")}`);
496
+ for (const w of warn)
497
+ print(out.yellow("!") + " " + w);
498
+ print(pub ? `${out.green("✓")} Published v${pub.version}. Send it with --template ${body.alias || t.id}` : out.dim(`Draft. Publish with: delivrie templates publish ${body.alias || t.id}`));
499
+ }), 0;
500
+ }
501
+ const id = need1(rest[0], "template id or alias");
502
+ if (sub === "update") {
503
+ const body = fields({});
504
+ if (flags["html-file"]) {
505
+ body.html = await readHtml(flags["html-file"]);
506
+ body.variables = varsIn(body.html).map((name) => ({ name, type: "string" }));
507
+ }
508
+ if (!Object.keys(body).length)
509
+ throw new UsageError("Nothing to change. Pass --html-file, --name, --alias, --subject or --from");
510
+ const t = await api.request("GET", `/templates/${enc(id)}`);
511
+ const r = await api.request("PATCH", `/templates/${enc(t.id)}`, body);
512
+ return show(r, () => { print(out.green("✓") + ` Updated ${t.name}`); if (r.note)
513
+ print(out.dim(r.note)); }), 0;
514
+ }
515
+ if (sub === "delete") {
516
+ if (!(await confirm(`Delete template ${id}? API calls that use it will fail.`)))
517
+ return print("Kept it."), 0;
518
+ const t = await api.request("GET", `/templates/${enc(id)}`);
519
+ const r = await api.request("DELETE", `/templates/${enc(t.id)}`);
520
+ return show(r, () => print(out.green("✓") + ` Deleted ${t.name}`)), 0;
521
+ }
522
+ if (sub === "get") {
523
+ const t = await api.request("GET", `/templates/${enc(id)}`);
524
+ return show(t, () => { print(`${out.bold(t.name)} ${out.statusColor(t.status)} ${out.dim(t.id)}`); if (t.alias)
525
+ print(`${out.dim("Alias")} ${t.alias}`); if (t.subject)
526
+ print(`${out.dim("Subject")} ${t.subject}`); if (t.from)
527
+ print(`${out.dim("From")} ${t.from}`); if (t.variables?.length)
528
+ print(`${out.dim("Variables")} ${t.variables.map((v) => v.name || v.key).join(", ")}`); if (typeof t.content?.raw === "string")
529
+ print(`${out.dim("Format")} HTML, sent as written`); }), 0;
530
+ }
531
+ if (sub === "publish") {
532
+ const t = await api.request("POST", `/templates/${enc(id)}/publish`);
533
+ return show(t, () => print(out.green("✓") + ` Published ${t.name || id}`)), 0;
534
+ }
535
+ throw new UsageError(`Unknown: templates ${sub}. Try delivrie templates --help`);
536
+ }
537
+ // ------------------------------------------------------------ audience, logs
538
+ case "contacts": {
539
+ const api = need();
540
+ if (sub === "list" || !sub) {
541
+ const r = await api.request("GET", "/contacts", undefined, { query: { limit: flags.limit || 50, offset: flags.offset } });
542
+ return show(r, () => {
543
+ const rows = listOf(r);
544
+ if (!rows.length)
545
+ return empty("contacts");
546
+ print(out.table(rows, [{ label: "EMAIL", get: (c) => c.email }, { label: "NAME", get: (c) => [c.first_name, c.last_name].filter(Boolean).join(" ") }, { label: "SUBSCRIBED", get: (c) => (c.unsubscribed ? out.red("no") : out.green("yes")) }, { label: "ADDED", get: (c) => when(c.created_at) }]));
547
+ }), 0;
548
+ }
549
+ const ref = need1(rest[0], "contact email or id");
550
+ if (sub === "add") {
551
+ const r = await api.request("POST", "/contacts", { email: ref, ...(flags["first-name"] ? { first_name: flags["first-name"] } : {}), ...(flags["last-name"] ? { last_name: flags["last-name"] } : {}) });
552
+ return show(r, () => print(out.green("✓") + ` Added ${ref} (${r.id})`)), 0;
553
+ }
554
+ if (sub === "get") {
555
+ const c = await api.request("GET", `/contacts/${enc(ref)}`);
556
+ return show(c, () => { print(`${out.bold(c.email)} ${c.unsubscribed ? out.red("unsubscribed") : out.green("subscribed")}`); const name = [c.first_name, c.last_name].filter(Boolean).join(" "); if (name)
557
+ print(`${out.dim("Name")} ${name}`); print(`${out.dim("ID")} ${c.id}`); print(`${out.dim("Added")} ${when(c.created_at)}`); for (const [k, v] of Object.entries(c.properties || {}))
558
+ print(`${out.dim(k.padEnd(8))} ${v}`); }), 0;
559
+ }
560
+ if (sub === "delete") {
561
+ if (!(await confirm(`Delete contact ${ref}?`)))
562
+ return print("Kept it."), 0;
563
+ const r = await api.request("DELETE", `/contacts/${enc(ref)}`);
564
+ return show(r, () => print(out.green("✓") + ` Deleted ${ref}`)), 0;
565
+ }
566
+ throw new UsageError(`Unknown: contacts ${sub}. Try delivrie contacts --help`);
567
+ }
568
+ case "suppressions": {
569
+ const api = need();
570
+ if (sub === "list" || !sub) {
571
+ const r = await api.request("GET", "/suppressions");
572
+ return show(r, () => {
573
+ const rows = listOf(r);
574
+ if (!rows.length)
575
+ return empty("suppressed addresses");
576
+ print(out.table(rows, [{ label: "EMAIL", get: (s) => s.email }, { label: "REASON", get: (s) => s.reason }, { label: "SINCE", get: (s) => when(s.created_at) }]));
577
+ }), 0;
578
+ }
579
+ if (sub === "add") {
580
+ const emails = rest.flatMap((e) => e.split(",")).map((e) => e.trim()).filter(Boolean);
581
+ if (!emails.length)
582
+ throw new UsageError("Give one or more email addresses");
583
+ const r = await api.request("POST", "/suppressions", emails.length === 1 ? { email: emails[0] } : { emails });
584
+ return show(r, () => print(out.green("✓") + ` Suppressed ${emails.join(", ")}. Delivrie won't send to ${emails.length === 1 ? "it" : "them"}.`)), 0;
585
+ }
586
+ if (sub === "remove") {
587
+ const e = need1(rest[0], "email address");
588
+ const r = await api.request("DELETE", `/suppressions/${enc(e)}`);
589
+ return show(r, () => print(out.green("✓") + ` ${e} can receive email again`)), 0;
590
+ }
591
+ throw new UsageError(`Unknown: suppressions ${sub}. Try delivrie suppressions --help`);
592
+ }
593
+ case "logs": {
594
+ const api = need();
595
+ if (sub === "list" || !sub) {
596
+ const r = await api.request("GET", "/logs", undefined, { query: { limit: flags.limit || 20, offset: flags.offset } });
597
+ return show(r, () => {
598
+ const rows = listOf(r);
599
+ if (!rows.length)
600
+ return empty("API requests");
601
+ print(out.table(rows, [{ label: "ID", get: (l) => l.id }, { label: "REQUEST", get: (l) => `${l.method} ${l.endpoint}` }, { label: "STATUS", get: (l) => (l.status >= 400 ? out.red(l.status) : out.green(l.status)) }, { label: "CLIENT", get: (l) => trunc(l.user_agent, 24) }, { label: "WHEN", get: (l) => when(l.created_at) }]));
602
+ }), 0;
603
+ }
604
+ if (sub === "get") {
605
+ const l = await api.request("GET", `/logs/${enc(need1(rest[0], "log id"))}`);
606
+ return json(l), 0;
607
+ }
608
+ throw new UsageError(`Unknown: logs ${sub}. Try delivrie logs --help`);
609
+ }
610
+ default:
611
+ return fail(`Unknown command "${cmd}". Run delivrie --help to see them all.`, 2);
612
+ }
613
+ }
614
+ catch (e) {
615
+ if (e instanceof UsageError)
616
+ return fail(e.message, 2);
617
+ if (e instanceof ApiError) {
618
+ if (flags.json) {
619
+ stdout.write(JSON.stringify({ error: { statusCode: e.status, name: e.code, message: e.message } }, null, 2) + "\n");
620
+ return 1;
621
+ }
622
+ const hint = e.status === 401 ? " Run `delivrie login` with a valid key." : e.code === "restricted_api_key" ? " This needs a full-access key." : "";
623
+ return fail(`${e.message}${hint}`);
624
+ }
625
+ if (e?.code === "ENOENT")
626
+ return fail(`File not found: ${e.path}`);
627
+ return fail(e?.message || String(e));
628
+ }
629
+ function printRecords(d) {
630
+ const recs = d.records || [];
631
+ if (!recs.length)
632
+ return;
633
+ print(out.table(recs, [{ label: "TYPE", get: (r) => r.type }, { label: "NAME", get: (r) => r.name }, { label: "VALUE", get: (r) => (r.priority != null ? `${r.priority} ` : "") + r.value }, { label: "STATUS", get: (r) => out.statusColor(r.status) }]));
634
+ }
635
+ }
636
+ // A sending-only key gets 403 from /usage; a bad key gets 401.
637
+ async function checkKey(api) {
638
+ try {
639
+ const usage = await api.request("GET", "/usage");
640
+ return { permission: "full", usage };
641
+ }
642
+ catch (e) {
643
+ if (e instanceof ApiError && e.status === 403)
644
+ return { permission: "sending" };
645
+ if (e instanceof ApiError && e.status === 401)
646
+ return { permission: "invalid" };
647
+ throw e;
648
+ }
649
+ }
650
+ const enc = encodeURIComponent;
651
+ const num = (n) => Number(n || 0).toLocaleString("en-US");
652
+ const trunc = (v, n) => { const s = String(v ?? ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; };
653
+ const fmtUsage = (u) => `${num(u.emails_this_month)}${u.monthly_allowance ? ` of ${num(u.monthly_allowance)}` : ""} emails this month`;
654
+ function need1(v, what) { if (!v)
655
+ throw new UsageError(`Give the ${what}`); return v; }
656
+ function pairs(items, sep, flag) {
657
+ const o = {};
658
+ for (const it of items) {
659
+ const i = it.indexOf(sep);
660
+ if (i < 1)
661
+ throw new UsageError(`${flag} expects name${sep}value, got "${it}"`);
662
+ o[it.slice(0, i).trim()] = it.slice(i + 1).trim();
663
+ }
664
+ return o;
665
+ }
666
+ function readAll(stream) {
667
+ return new Promise((resolve, reject) => { let s = ""; stream.setEncoding?.("utf8"); stream.on("data", (c) => (s += c)); stream.on("end", () => resolve(s)); stream.on("error", reject); });
668
+ }
669
+ function readLine(stream, { hidden = false } = {}) {
670
+ return new Promise((resolve) => {
671
+ let s = "";
672
+ const raw = hidden && typeof stream.setRawMode === "function";
673
+ if (raw)
674
+ stream.setRawMode(true);
675
+ stream.resume();
676
+ stream.setEncoding?.("utf8");
677
+ const onData = (chunk) => {
678
+ for (const ch of String(chunk)) {
679
+ if (ch === "\r" || ch === "\n") {
680
+ done();
681
+ return;
682
+ }
683
+ if (ch === "\u0003") {
684
+ done();
685
+ process.exit(130);
686
+ }
687
+ if (ch === "\u007f")
688
+ s = s.slice(0, -1);
689
+ else
690
+ s += ch;
691
+ }
692
+ };
693
+ const done = () => { stream.off("data", onData); if (raw)
694
+ stream.setRawMode(false); stream.pause(); resolve(s); };
695
+ stream.on("data", onData);
696
+ });
697
+ }
package/dist/config.js ADDED
@@ -0,0 +1,38 @@
1
+ // Where `delivrie login` keeps the API key: ~/.config/delivrie/config.json (or $XDG_CONFIG_HOME, or %APPDATA% on
2
+ // Windows), readable only by you. DELIVRIE_API_KEY always wins over the saved key.
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ export function configPath(env = process.env) {
7
+ const dir = env.DELIVRIE_CONFIG_DIR
8
+ || (process.platform === "win32" && env.APPDATA ? path.join(env.APPDATA, "delivrie")
9
+ : path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "delivrie"));
10
+ return path.join(dir, "config.json");
11
+ }
12
+ export function readConfig(env = process.env) {
13
+ try {
14
+ return JSON.parse(fs.readFileSync(configPath(env), "utf8")) || {};
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ export function writeConfig(cfg, env = process.env) {
21
+ const file = configPath(env);
22
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
23
+ fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
24
+ try {
25
+ fs.chmodSync(file, 0o600);
26
+ }
27
+ catch { /* Windows */ }
28
+ return file;
29
+ }
30
+ export function clearConfig(env = process.env) {
31
+ try {
32
+ fs.unlinkSync(configPath(env));
33
+ return true;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
package/dist/format.js ADDED
@@ -0,0 +1,42 @@
1
+ export function makeOut(stream = process.stdout, env = process.env) {
2
+ const color = !!stream.isTTY && !env.NO_COLOR && env.TERM !== "dumb";
3
+ const c = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : String(s));
4
+ const st = { bold: c(1), dim: c(2), red: c(31), green: c(32), yellow: c(33), cyan: c(36) };
5
+ const visible = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, "");
6
+ function table(rows, cols) {
7
+ if (!rows.length)
8
+ return "";
9
+ const head = cols.map((k) => st.dim(k.label));
10
+ const body = rows.map((r) => cols.map((k) => String(k.get(r) ?? "")));
11
+ const widths = cols.map((k, i) => Math.max(visible(head[i]).length, ...body.map((row) => visible(row[i]).length)));
12
+ const line = (cells) => cells.map((v, i) => (i === cells.length - 1 ? v : v + " ".repeat(widths[i] - visible(v).length))).join(" ");
13
+ return [line(head), ...body.map(line)].join("\n");
14
+ }
15
+ const statusColor = (s) => {
16
+ const v = String(s || "");
17
+ if (/^(delivered|verified|sent|enabled|opened|clicked|published|full)$/.test(v))
18
+ return st.green(v);
19
+ if (/^(bounced|failed|complained|disabled|canceled)$/.test(v))
20
+ return st.red(v);
21
+ if (/^(pending|queued|scheduled|sending|delivery_delayed|not_started|temporary_failure|draft)$/.test(v))
22
+ return st.yellow(v);
23
+ return v;
24
+ };
25
+ return { ...st, color, table, statusColor };
26
+ }
27
+ export function when(iso) {
28
+ if (!iso)
29
+ return "";
30
+ const d = new Date(iso);
31
+ if (Number.isNaN(d.getTime()))
32
+ return String(iso);
33
+ const s = (Date.now() - d.getTime()) / 1000;
34
+ if (s >= 0 && s < 60)
35
+ return "just now";
36
+ if (s >= 0 && s < 3600)
37
+ return `${Math.floor(s / 60)} min ago`;
38
+ if (s >= 0 && s < 86400)
39
+ return `${Math.floor(s / 3600)} h ago`;
40
+ return d.toISOString().slice(0, 16).replace("T", " ");
41
+ }
42
+ export const list = (v) => (Array.isArray(v) ? v.join(", ") : (v ?? ""));
@@ -0,0 +1 @@
1
+ export const VERSION = "0.2.0";
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "delivrie-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The Delivrie command-line tool: send email, check deliveries, and manage domains, API keys, webhooks and templates from your terminal.",
5
+ "keywords": [
6
+ "delivrie",
7
+ "email",
8
+ "cli",
9
+ "email-api",
10
+ "transactional-email",
11
+ "resend-alternative"
12
+ ],
13
+ "homepage": "https://delivrie.io/docs/cli",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/bysurce/delivrie.git",
17
+ "directory": "sdk/cli"
18
+ },
19
+ "bugs": {
20
+ "url": "https://delivrie.io/support"
21
+ },
22
+ "license": "MIT",
23
+ "author": "Surce Inc <support@delivrie.io>",
24
+ "type": "module",
25
+ "bin": {
26
+ "delivrie": "bin/delivrie.js"
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "engines": {
35
+ "node": ">=18"
36
+ },
37
+ "scripts": {
38
+ "build": "node scripts/build.mjs",
39
+ "pretest": "npm run build",
40
+ "test": "node --test test/cli.test.js",
41
+ "prepublishOnly": "npm test"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "26.6.3",
45
+ "typescript": "6.0.3"
46
+ }
47
+ }