@noisybrood/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ import { CLASSIFICATION_STATES, TONE_TITLES, } from "./brood/api/src/index.js";
2
+ import { API_PAGE_MAX, API_STRETCH_DAYS, PORTRAIT_DAYS } from "./brood/figures/index.js";
3
+ import { call } from "./client.js";
4
+ import { clean, Refusal } from "./io.js";
5
+ import { day, dim, json, more, rows, state } from "./out.js";
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ /**
8
+ * A lookup by name reads every page, so a match on a later one is never
9
+ * missed. This bounds it against an answer that never ends; reaching it is
10
+ * said, never taken as "none".
11
+ */
12
+ const LOOKUP_PAGES = 100;
13
+ const tooMany = (name) => new Refusal(`Brood read ${LOOKUP_PAGES} pages looking for ${clean(name)} and stopped. Name it by its id.`);
14
+ /** Refuses options a command was given that it takes only in its other form. */
15
+ const without = (options, names, form) => {
16
+ const given = names.find((n) => options[n] !== undefined);
17
+ if (given)
18
+ throw new Refusal(`--${given} does not apply to ${form}.`);
19
+ };
20
+ const owner = (o) => (o.owner === undefined ? {} : { owner: o.owner });
21
+ const page = (o) => ({
22
+ ...(o.limit === undefined ? {} : { limit: o.limit }),
23
+ ...(o.cursor === undefined ? {} : { cursor: o.cursor }),
24
+ });
25
+ const stretch = (o) => ({
26
+ ...(o.since === undefined ? {} : { since: o.since }),
27
+ ...(o.until === undefined ? {} : { until: o.until }),
28
+ });
29
+ const same = (a, b) => a !== null && a.toLowerCase() === b.toLowerCase();
30
+ /** The answer, or for `--json` the answer as given, after its mailboxes' state. */
31
+ function shown(io, style, envelope, print) {
32
+ if (style.json)
33
+ return json(io, envelope);
34
+ state(io, style, envelope);
35
+ print(envelope.data);
36
+ more(io, style, envelope);
37
+ }
38
+ const one = (args, what) => {
39
+ const [arg, ...rest] = args;
40
+ if (arg === undefined || rest.length)
41
+ throw new Refusal(`Name one ${what}.`);
42
+ return arg;
43
+ };
44
+ const none = (args) => {
45
+ if (args.length)
46
+ throw new Refusal(`It takes no ${args.length === 1 ? "argument" : "arguments"}: ${clean(args.join(" "))}.`);
47
+ };
48
+ /**
49
+ * A sender's id: given as one, or found over a stretch by its root domain,
50
+ * or by its address under a root many unrelated people share. Such a root
51
+ * is listed one address at a time, each row naming the shared root, so a
52
+ * row with an address is matched by its address alone: matched by its
53
+ * root, one person's mail would be shown as the whole root's. And it is
54
+ * read by its address too, so the read does not widen to the root either.
55
+ */
56
+ async function senderOf(io, options, name, over) {
57
+ if (UUID.test(name))
58
+ return { sender: name, scope: "domain" };
59
+ let cursor;
60
+ let whole = true;
61
+ for (let n = 0; n < LOOKUP_PAGES; n++) {
62
+ const answer = await call(io, "list_senders", {
63
+ ...owner(options),
64
+ ...over,
65
+ limit: API_PAGE_MAX,
66
+ ...(cursor ? { cursor } : {}),
67
+ });
68
+ const found = answer.data.senders.find((s) => s.sender_written.address === null
69
+ ? same(s.sender_written.root, name)
70
+ : same(s.sender_written.address, name));
71
+ if (found)
72
+ return {
73
+ sender: found.id,
74
+ scope: found.sender_written.address === null ? "domain" : "address",
75
+ };
76
+ whole &&= answer.complete;
77
+ if (!answer.next)
78
+ throw new Refusal(`Brood has no mail from ${clean(name)} from ${over.since}${over.until ? ` to ${over.until}` : ""}${whole ? "" : ", though it has not read every mailbox whole, so the mail may be there"}. Name a sender who wrote to you by its root domain, such as example.com, or under a shared one such as gmail.com, by its address.`);
79
+ cursor = answer.next;
80
+ }
81
+ throw tooMany(name);
82
+ }
83
+ /** The first day of the `days` ending `until`, or today, as YYYY-MM-DD in UTC. */
84
+ function daysBack(io, days, until) {
85
+ const end = until === undefined ? io.now() : Date.parse(`${until}T00:00:00Z`);
86
+ if (Number.isNaN(end) ||
87
+ (until !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(until)))
88
+ throw new Refusal("--until is a day, as YYYY-MM-DD.");
89
+ return new Date(end - (days - 1) * 86_400_000).toISOString().slice(0, 10);
90
+ }
91
+ /** The classifications covering a sender, by its id, or by what one covers or its path. */
92
+ async function classificationsOf(io, options, name) {
93
+ if (UUID.test(name)) {
94
+ const one = await call(io, "get_classification", {
95
+ ...owner(options),
96
+ id: name,
97
+ });
98
+ return [one.data];
99
+ }
100
+ const found = [];
101
+ let cursor;
102
+ for (let n = 0; n < LOOKUP_PAGES; n++) {
103
+ const answer = await call(io, "list_classifications", {
104
+ ...owner(options),
105
+ limit: API_PAGE_MAX,
106
+ ...(cursor ? { cursor } : {}),
107
+ });
108
+ found.push(...answer.data.classifications.filter((c) => same(c.sender_written.subject, name) ||
109
+ same(c.sender_written.path, name)));
110
+ if (!answer.next)
111
+ return found;
112
+ cursor = answer.next;
113
+ }
114
+ throw tooMany(name);
115
+ }
116
+ /** One classification to act on: the one found, or the choice put back to the person. */
117
+ async function chosen(io, style, options, name, verb) {
118
+ const all = await classificationsOf(io, options, name);
119
+ const found = verb === "unhush"
120
+ ? all.filter((c) => c.state === "active" || c.state === "quieted")
121
+ : all;
122
+ const [only, ...others] = found;
123
+ if (!only)
124
+ throw new Refusal(verb === "hush"
125
+ ? `Brood has proposed nothing for ${clean(name)}.`
126
+ : `Nothing is filed for ${clean(name)}.`);
127
+ if (!others.length)
128
+ return only.id;
129
+ io.err(`Several classifications cover ${clean(name)}:`);
130
+ rows(io, found.map((c) => [c.sender_written.path, c.state, dim(style, c.id)]), io.err);
131
+ throw new Refusal(`Run brood ${verb} with the id of the one you mean.`);
132
+ }
133
+ const accounts = async (io, style, options, args) => {
134
+ none(args);
135
+ const answer = await call(io, "list_accounts", owner(options));
136
+ shown(io, style, answer, (data) => {
137
+ if (!data.accounts.length)
138
+ return io.out("No mailbox is connected.");
139
+ const phase = new Map(answer.accounts.map((a) => [a.id, a.sync.phase]));
140
+ rows(io, data.accounts.map((a) => [
141
+ a.address,
142
+ a.connected ? (phase.get(a.id) ?? "") : "disconnected",
143
+ dim(style, a.id),
144
+ ]));
145
+ });
146
+ };
147
+ const week = async (io, style, options, args) => {
148
+ none(args);
149
+ const answer = await call(io, "summarise_week", {
150
+ ...owner(options),
151
+ ...(options.week === undefined ? {} : { week: options.week }),
152
+ });
153
+ shown(io, style, answer, (w) => {
154
+ io.out(`The week of ${w.monday} to ${w.sunday}.`);
155
+ io.out(TONE_TITLES[w.tone]);
156
+ const section = (title, lines, empty) => {
157
+ io.out("");
158
+ io.out("· · ·");
159
+ io.out("");
160
+ io.out(title);
161
+ if (!lines.length)
162
+ return io.out(` ${empty}`);
163
+ rows(io, lines.map((l) => ["", ...l]));
164
+ };
165
+ section("Wrote most", w.loudest.map((s) => [
166
+ s.sender_written.customer ?? s.sender_written.root,
167
+ dim(style, s.tags.join(", ")),
168
+ ]), "No one wrote.");
169
+ section("Wrote for the first time", w.first_wrote.map((s) => [s.sender_written.root]), "No one new.");
170
+ section("Proposed", w.proposed.map((c) => [c.sender_written.path]), "Nothing.");
171
+ section("Quieted", w.quieted.map((c) => [c.sender_written.path]), "Nothing.");
172
+ });
173
+ };
174
+ const senders = async (io, style, options, args) => {
175
+ if (args.length) {
176
+ without(options, ["since", "until", "limit", "cursor"], "brood senders <name>");
177
+ // Over the days its portrait covers, so a sender with mail in it is found.
178
+ const found = await senderOf(io, options, one(args, "sender"), {
179
+ since: daysBack(io, PORTRAIT_DAYS),
180
+ });
181
+ const answer = await call(io, "get_sender", {
182
+ ...owner(options),
183
+ ...found,
184
+ });
185
+ return shown(io, style, answer, (s) => printSender(io, style, s));
186
+ }
187
+ const answer = await call(io, "list_senders", {
188
+ ...owner(options),
189
+ ...page(options),
190
+ ...stretch(options),
191
+ });
192
+ shown(io, style, answer, (data) => {
193
+ io.err(dim(style, `${data.counted_from} to ${data.counted_to}, counted by the ${data.resolution === "day" ? "day" : "whole month"}.`));
194
+ if (!data.senders.length)
195
+ return io.out("No one wrote in that stretch.");
196
+ rows(io, data.senders.map((s) => [
197
+ s.sender_written.address ?? s.sender_written.root,
198
+ String(s.messages),
199
+ `last ${day(s.last)}`,
200
+ ]));
201
+ });
202
+ };
203
+ function printSender(io, style, s) {
204
+ const w = s.sender_written;
205
+ io.out(s.scope === "address" ? w.address : (w.customer ?? w.root));
206
+ io.out(`${s.messages} messages in the last ${PORTRAIT_DAYS} days${s.mailing ? ", mostly mailings" : ""}.`);
207
+ io.out(s.written_to ? "You have written to it." : "You have not written to it.");
208
+ if (s.first_wrote)
209
+ io.out(`First wrote ${day(s.first_wrote)}.`);
210
+ if (s.classifications.length) {
211
+ io.out("");
212
+ io.out("Classifications");
213
+ rows(io, s.classifications.map((c) => [
214
+ "",
215
+ c.sender_written.path,
216
+ c.state,
217
+ dim(style, c.id),
218
+ ]));
219
+ }
220
+ if (s.addresses.length) {
221
+ io.out("");
222
+ io.out("Addresses");
223
+ rows(io, s.addresses.map((a) => [
224
+ "",
225
+ a.sender_written.address,
226
+ String(a.messages),
227
+ a.never_quiet ? "never quiet" : a.kept_out ? "kept out" : "",
228
+ ]));
229
+ if (s.more_addresses)
230
+ io.out(dim(style, " and more."));
231
+ }
232
+ }
233
+ const events = async (io, style, options, args) => {
234
+ none(args);
235
+ // Over the stretch asked for, so a sender who wrote in it is found.
236
+ const found = options.sender === undefined
237
+ ? undefined
238
+ : await senderOf(io, options, options.sender, {
239
+ since: options.since ?? daysBack(io, API_STRETCH_DAYS, options.until),
240
+ ...(options.until === undefined ? {} : { until: options.until }),
241
+ });
242
+ const answer = await call(io, "list_events", {
243
+ ...owner(options),
244
+ ...page(options),
245
+ ...stretch(options),
246
+ ...(found ?? {}),
247
+ });
248
+ shown(io, style, answer, (data) => {
249
+ io.err(dim(style, `Reaching back to ${day(data.retained_from)}.`));
250
+ if (!data.events.length)
251
+ return io.out("No messages in that stretch.");
252
+ rows(io, data.events.map((e) => [
253
+ e.at.slice(0, 16).replace("T", " "),
254
+ e.direction === "inbound" ? "from" : "to",
255
+ e.sender_written.address,
256
+ dim(style, [e.reply && "reply", e.mailing && "mailing"]
257
+ .filter(Boolean)
258
+ .join(", ")),
259
+ ]));
260
+ });
261
+ };
262
+ const quiet = async (io, style, options, args) => {
263
+ none(args);
264
+ const answer = await call(io, "list_quiet_senders", {
265
+ ...owner(options),
266
+ ...page(options),
267
+ });
268
+ shown(io, style, answer, (data) => {
269
+ io.err(dim(style, `Silent for ${data.silence_days} days or more, after writing most months.`));
270
+ if (!data.quiet.length)
271
+ return io.out("No regular sender has gone silent.");
272
+ rows(io, data.quiet.map((s) => [
273
+ s.sender_written.address ?? s.sender_written.root,
274
+ `last heard ${day(s.last_heard)}`,
275
+ ]));
276
+ });
277
+ };
278
+ const classifications = async (io, style, options, args) => {
279
+ const path = args.length ? one(args, "path") : undefined;
280
+ const wanted = options.state === undefined
281
+ ? undefined
282
+ : CLASSIFICATION_STATES.find((s) => s === options.state);
283
+ if (options.state !== undefined && !wanted)
284
+ throw new Refusal(`--state is one of ${CLASSIFICATION_STATES.join(", ")}.`);
285
+ const answer = await call(io, "list_classifications", {
286
+ ...owner(options),
287
+ ...page(options),
288
+ ...(path ? { path } : {}),
289
+ ...(wanted ? { state: wanted } : {}),
290
+ });
291
+ shown(io, style, answer, (data) => {
292
+ if (!data.classifications.length)
293
+ return io.out("No classifications.");
294
+ rows(io, data.classifications.map((c) => [
295
+ c.sender_written.path,
296
+ c.state,
297
+ c.reason ?? "",
298
+ dim(style, c.id),
299
+ ]));
300
+ });
301
+ };
302
+ const classification = async (io, style, options, args) => {
303
+ const id = one(args, "classification, by its id");
304
+ const answer = await call(io, "get_classification", {
305
+ ...owner(options),
306
+ id,
307
+ });
308
+ shown(io, style, answer, (c) => {
309
+ io.out(c.sender_written.path);
310
+ io.out(`${c.state}${c.reason ? `, for ${c.reason}` : ""}. Covers ${c.subject_kind === "domain" ? "everything from" : "the one address"} ${c.sender_written.subject}.`);
311
+ io.out(`Proposed ${day(c.proposed_at)}${c.decided_at ? `, decided ${day(c.decided_at)}${c.decided_by === "user" ? " by you" : " by Brood"}` : ""}.`);
312
+ if (c.mailboxes.length) {
313
+ io.out("");
314
+ io.out("Filed in");
315
+ rows(io, c.mailboxes.map((m) => [
316
+ "",
317
+ m.mailbox,
318
+ `since ${day(m.installed_at)}`,
319
+ m.stranded ? "left behind" : "",
320
+ ]));
321
+ }
322
+ });
323
+ };
324
+ function printRule(io, style, r) {
325
+ const w = r.sender_written;
326
+ rows(io, [
327
+ [
328
+ w.path ?? "",
329
+ `${w.from.kind === "domain" ? "everything from" : "the address"} ${w.from.value}`,
330
+ ],
331
+ [
332
+ "",
333
+ `in ${r.mailbox}, since ${day(r.installed_at)}${r.stranded ? ", left behind" : ""}`,
334
+ ],
335
+ ...(w.exclude.length ? [["", `leaves out ${w.exclude.join(", ")}`]] : []),
336
+ ...(w.exclude_cc.length
337
+ ? [["", `leaves out, when copied, ${w.exclude_cc.join(", ")}`]]
338
+ : []),
339
+ ["", dim(style, r.id)],
340
+ ]);
341
+ }
342
+ const rules = async (io, style, options, args) => {
343
+ if (args.length) {
344
+ without(options, ["classification", "limit", "cursor"], "brood rules <id>");
345
+ const answer = await call(io, "get_rule", {
346
+ ...owner(options),
347
+ id: one(args, "rule, by its id"),
348
+ });
349
+ return shown(io, style, answer, (r) => printRule(io, style, r));
350
+ }
351
+ const answer = await call(io, "list_rules", {
352
+ ...owner(options),
353
+ ...page(options),
354
+ ...(options.classification === undefined
355
+ ? {}
356
+ : { classification: options.classification }),
357
+ });
358
+ shown(io, style, answer, (data) => {
359
+ if (!data.rules.length)
360
+ return io.out("Brood has installed no filters.");
361
+ rows(io, data.rules.map((r) => [
362
+ r.sender_written.path ?? "",
363
+ r.mailbox,
364
+ r.stranded ? "left behind" : "",
365
+ dim(style, r.id),
366
+ ]));
367
+ });
368
+ };
369
+ const hush = async (io, style, options, args) => {
370
+ const name = one(args, "sender, by its root domain or address, or a classification by its id");
371
+ const id = await chosen(io, style, options, name, "hush");
372
+ const answer = await call(io, "hush", {
373
+ ...owner(options),
374
+ classification: id,
375
+ });
376
+ shown(io, style, answer, (h) => {
377
+ io.out(h.already
378
+ ? `${clean(name)} was filed already.`
379
+ : `Filed ${clean(name)} out of your inbox.`);
380
+ if (h.failed.length)
381
+ io.out(`Brood could not install its filter in ${h.failed.length === 1 ? "one mailbox" : `${h.failed.length} mailboxes`}: ${h.failed.join(", ")}.`);
382
+ });
383
+ };
384
+ const unhush = async (io, style, options, args) => {
385
+ const name = one(args, "sender, by its root domain or address, or a classification by its id");
386
+ const id = await chosen(io, style, options, name, "unhush");
387
+ const answer = await call(io, "unhush", {
388
+ ...owner(options),
389
+ classification: id,
390
+ });
391
+ shown(io, style, answer, (u) => {
392
+ if (u.outcome === "not_filed")
393
+ return io.out(`Nothing to undo: ${clean(name)} is not filed.`);
394
+ io.out(u.handed_back
395
+ ? "Your own filter is back as it was, and your mail stays where it is."
396
+ : "Undone. Its mail is coming back to your inbox, the first of it now and the rest within the hour.");
397
+ });
398
+ };
399
+ /** Each command, and the options it takes, so one it does not is refused rather than ignored. */
400
+ export const COMMANDS = {
401
+ accounts: { run: accounts, takes: [] },
402
+ week: { run: week, takes: ["week"] },
403
+ senders: { run: senders, takes: ["since", "until", "limit", "cursor"] },
404
+ events: {
405
+ run: events,
406
+ takes: ["since", "until", "limit", "cursor", "sender"],
407
+ },
408
+ quiet: { run: quiet, takes: ["limit", "cursor"] },
409
+ classifications: {
410
+ run: classifications,
411
+ takes: ["state", "limit", "cursor"],
412
+ },
413
+ classification: { run: classification, takes: [] },
414
+ rules: { run: rules, takes: ["classification", "limit", "cursor"] },
415
+ hush: { run: hush, takes: [] },
416
+ unhush: { run: unhush, takes: [] },
417
+ };
package/dist/io.js ADDED
@@ -0,0 +1,50 @@
1
+ /** A refusal said to the person in a sentence, with nothing else printed. */
2
+ export class Refusal extends Error {
3
+ }
4
+ /** The session is over at Clerk, and its file is gone. */
5
+ export class SessionEnded extends Refusal {
6
+ }
7
+ /** Brood refused the call, with the status it answered. */
8
+ export class Refused extends Refusal {
9
+ code;
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ export const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+ // Built from code points: Prettier writes a `\u` escape in a pattern
17
+ // literal as the character itself, which leaves invisible characters in
18
+ // the source, and a line separator breaks the literal (voice.md).
19
+ const UNSAFE = new RegExp(`[${[
20
+ [0x00, 0x1f],
21
+ [0x7f, 0x9f],
22
+ [0x061c],
23
+ [0x200b],
24
+ [0x200e, 0x200f],
25
+ [0x2028, 0x202e],
26
+ [0x2060],
27
+ [0x2066, 0x2069],
28
+ [0xfeff],
29
+ ]
30
+ .map((range) => range.map((c) => `\\u${c.toString(16).padStart(4, "0")}`).join("-"))
31
+ .join("")}]`, "gu");
32
+ /**
33
+ * Text from outside brood, made safe to print. A sender writes its own
34
+ * address, name and domain (DD21 §8), and a control character or a
35
+ * direction override in one would let it rewrite the terminal or disguise
36
+ * what is shown, so every one is removed: the C0 and C1 controls, every
37
+ * direction mark and override, the line and paragraph separators, and the
38
+ * zero-width space, word joiner and byte order mark, which can make two
39
+ * names look alike. The zero-width joiner and non-joiner stay, since some
40
+ * scripts need them to spell a name.
41
+ */
42
+ export const clean = (text) => text.replace(UNSAFE, "");
43
+ /** Every string in a value from outside, cleaned, so nothing printed from it can be missed. */
44
+ export const cleaned = (value) => typeof value === "string"
45
+ ? clean(value)
46
+ : Array.isArray(value)
47
+ ? value.map(cleaned)
48
+ : typeof value === "object" && value !== null
49
+ ? Object.fromEntries(Object.entries(value).map(([k, v]) => [clean(k), cleaned(v)]))
50
+ : value;
package/dist/main.js ADDED
@@ -0,0 +1,193 @@
1
+ import { parseArgs } from "node:util";
2
+ import { call } from "./client.js";
3
+ import { COMMANDS } from "./commands.js";
4
+ import { Refused, Refusal, SessionEnded } from "./io.js";
5
+ import { colorOn, styleOf } from "./out.js";
6
+ import { login } from "./sign-in.js";
7
+ import { readCredentials, removeCredentials } from "./store.js";
8
+ import { VERSION } from "./version.js";
9
+ import { depthOf, wrenIn } from "./wren.js";
10
+ /**
11
+ * `brood`, the command line over Brood's index (DD10): it answers questions
12
+ * about a mailbox without opening one, and changes it only by `hush` and
13
+ * `unhush`. Bare `brood` prints this help, never a report (DD10 §3), so it is
14
+ * never a status glanced at, under the wren.
15
+ */
16
+ const HELP = `brood answers questions about your mailbox from Brood's index. It never reads a message.
17
+
18
+ Observing
19
+ brood week one finished week, beside the week before
20
+ brood senders who wrote, most first
21
+ brood senders <domain|address> one sender
22
+ brood events [--sender <name>] messages that arrived or were sent, newest first
23
+ brood quiet senders that have gone silent
24
+
25
+ Structure
26
+ brood classifications [<path>] what Brood has decided, and its state
27
+ brood classification <id> one, with the reason for its state
28
+ brood rules [<id>] the filters Brood installed
29
+
30
+ Suppression, the two that change your mailbox
31
+ brood hush <domain|address|id> file what Brood proposed for a sender
32
+ brood unhush <domain|address|id> undo the filing
33
+
34
+ Accounts and session
35
+ brood accounts your mailboxes, and whether Brood can read them
36
+ brood login [--read-only] sign in, by a code you approve in a browser
37
+ brood logout end this session
38
+ brood version
39
+
40
+ Options
41
+ --json the answer as the API gives it
42
+ --since, --until a stretch of whole days, as YYYY-MM-DD in UTC
43
+ --limit <n> how many to show
44
+ --cursor <next> carry on a listing from where it stopped
45
+ --state <state> classifications in one state
46
+ --week <monday> brood week for an earlier week
47
+ --classification <id> brood rules for one classification
48
+ --owner <user id> the index of someone who granted you access
49
+ --no-color no dimming, as NO_COLOR also asks`;
50
+ async function logout(io) {
51
+ if (!(await readCredentials(io.env)))
52
+ return io.err("Not signed in.");
53
+ try {
54
+ await call(io, "end_session", (held) => ({
55
+ refresh_token: held.refresh_token,
56
+ }));
57
+ }
58
+ catch (error) {
59
+ // Forgotten only when nothing is left to end: a session Clerk has ended,
60
+ // or a program Brood refuses as revoked, whose file would otherwise leave
61
+ // login refusing too. Anything else, Brood unreachable or failing, or
62
+ // refusing a token just renewed, may leave the session live at Clerk,
63
+ // so the file stays and logging out again can end it.
64
+ const over = error instanceof SessionEnded ||
65
+ (error instanceof Refused && error.code === "credential_revoked");
66
+ if (!over)
67
+ throw error;
68
+ }
69
+ await removeCredentials(io.env);
70
+ io.err("Signed out. This session can no longer be renewed.");
71
+ }
72
+ const OPTION_NAMES = [
73
+ "since",
74
+ "until",
75
+ "limit",
76
+ "cursor",
77
+ "state",
78
+ "week",
79
+ "sender",
80
+ "classification",
81
+ ];
82
+ /** Runs one command line, and answers its exit status. */
83
+ export async function run(io, argv) {
84
+ try {
85
+ const { values, positionals } = parseArgs({
86
+ args: argv,
87
+ allowPositionals: true,
88
+ options: {
89
+ json: { type: "boolean", default: false },
90
+ "no-color": { type: "boolean", default: false },
91
+ "read-only": { type: "boolean", default: false },
92
+ help: { type: "boolean", short: "h", default: false },
93
+ since: { type: "string" },
94
+ until: { type: "string" },
95
+ limit: { type: "string" },
96
+ cursor: { type: "string" },
97
+ state: { type: "string" },
98
+ week: { type: "string" },
99
+ sender: { type: "string" },
100
+ classification: { type: "string" },
101
+ owner: { type: "string" },
102
+ },
103
+ });
104
+ const [command, ...args] = positionals;
105
+ const empty = Object.entries(values).find(([, v]) => v === "");
106
+ if (empty)
107
+ throw new Refusal(`--${empty[0]} needs a value.`);
108
+ // An option a command does not take is refused, never ignored: a flag
109
+ // with nothing behind it looks like a filter that was applied (DD10 §3).
110
+ const takes = (names, readOnly = false) => {
111
+ const given = OPTION_NAMES.find((n) => values[n] !== undefined && !names.includes(n));
112
+ if (given)
113
+ throw new Refusal(`--${given} does not apply to brood ${command}.`);
114
+ if (values["read-only"] && !readOnly)
115
+ throw new Refusal(`--read-only applies to brood login alone.`);
116
+ };
117
+ // The session commands read no index, so neither whose nor how to print.
118
+ const session = (colors = false) => {
119
+ if (args.length)
120
+ throw new Refusal(`brood ${command} takes no arguments.`);
121
+ const given = ["owner", "json"].find((n) => n === "json" ? values.json : values.owner !== undefined);
122
+ if (given)
123
+ throw new Refusal(`--${given} does not apply to brood ${command}.`);
124
+ if (values["no-color"] && !colors)
125
+ throw new Refusal(`--no-color does not apply to brood ${command}.`);
126
+ };
127
+ if (command === undefined || command === "help" || values.help) {
128
+ const color = colorOn(io, values["no-color"]);
129
+ for (const line of wrenIn(color ? depthOf(io.env) : "none"))
130
+ io.out(line);
131
+ io.out("");
132
+ io.out(HELP);
133
+ return 0;
134
+ }
135
+ if (command === "version") {
136
+ takes([]);
137
+ session();
138
+ io.out(VERSION);
139
+ return 0;
140
+ }
141
+ if (command === "login") {
142
+ takes([], true);
143
+ session(true);
144
+ await login(io, values["read-only"], values["no-color"]);
145
+ return 0;
146
+ }
147
+ if (command === "logout") {
148
+ takes([]);
149
+ session();
150
+ await logout(io);
151
+ return 0;
152
+ }
153
+ const runs = Object.hasOwn(COMMANDS, command)
154
+ ? COMMANDS[command]
155
+ : undefined;
156
+ if (!runs)
157
+ throw new Refusal(`brood has no command ${command}. Run brood help.`);
158
+ takes(runs.takes);
159
+ const limit = values.limit === undefined ? undefined : Number(values.limit);
160
+ if (limit !== undefined && !Number.isInteger(limit))
161
+ throw new Refusal("--limit is a whole number.");
162
+ const options = {
163
+ ...(values.owner === undefined ? {} : { owner: values.owner }),
164
+ ...(values.since === undefined ? {} : { since: values.since }),
165
+ ...(values.until === undefined ? {} : { until: values.until }),
166
+ ...(limit === undefined ? {} : { limit }),
167
+ ...(values.cursor === undefined ? {} : { cursor: values.cursor }),
168
+ ...(values.state === undefined ? {} : { state: values.state }),
169
+ ...(values.week === undefined ? {} : { week: values.week }),
170
+ ...(values.sender === undefined ? {} : { sender: values.sender }),
171
+ ...(values.classification === undefined
172
+ ? {}
173
+ : { classification: values.classification }),
174
+ };
175
+ await runs.run(io, styleOf(io, { json: values.json, noColor: values["no-color"] }), options, args);
176
+ return 0;
177
+ }
178
+ catch (error) {
179
+ if (error instanceof Refusal) {
180
+ io.err(error.message);
181
+ return 1;
182
+ }
183
+ // parseArgs refuses an option it does not know, or one missing its value.
184
+ if (error instanceof TypeError &&
185
+ "code" in error &&
186
+ typeof error.code === "string" &&
187
+ error.code.startsWith("ERR_PARSE_ARGS")) {
188
+ io.err(`${error.message}. Run brood help.`);
189
+ return 1;
190
+ }
191
+ throw error;
192
+ }
193
+ }