delivrie-cli 0.1.0 → 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 +1 -1
- package/README.md +2 -1
- package/bin/delivrie.js +1 -1
- package/dist/api.js +58 -0
- package/dist/args.js +47 -0
- package/dist/cli.js +697 -0
- package/dist/config.js +38 -0
- package/dist/format.js +42 -0
- package/dist/version.js +1 -0
- package/package.json +12 -5
- package/src/api.js +0 -50
- package/src/args.js +0 -30
- package/src/cli.js +0 -485
- package/src/config.js +0 -28
- package/src/format.js +0 -36
- package/src/version.js +0 -1
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
|
+
}
|