@billionsend/cli 0.4.0 → 0.5.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.
Files changed (3) hide show
  1. package/README.md +23 -18
  2. package/dist/index.js +233 -25
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -14,16 +14,16 @@ Node 18 or newer; no dependencies.
14
14
 
15
15
  ## What moves
16
16
 
17
- | Resource | How |
18
- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
- | Contacts | Upserted by email through the batch endpoint; `unsubscribed` and topic opt-outs are preserved, never re-subscribed. Resend's `unsubscribed` is global, so it lands as BillionSend's team-wide `unsubscribed: true`; no per-domain unsubscribe is created. Topic subscriptions and properties follow in two per-contact passes that run after everything else, so the account is sendable before they finish. The batch endpoint answers created, updated or skipped but never whether a matched contact changed, so the summary reports those as `matched existing`, not as updated or unchanged. |
20
- | Segments, topics, properties | Matched by name / name / key: created when missing, updated when different, left alone when equal. Segment memberships follow the contacts. BillionSend property keys ignore case, Resend's do not: when Resend has both `plan` and `PLAN`, only the first is created, the other is listed as a manual note, and the report counts the contacts whose value for it was not written. A key that differs only in case from one already on BillionSend is the same property, and values are written under the spelling it has. |
21
- | Templates | Name, alias, subject, html, text, default from, reply-to and variables (up to 50 reply-to addresses and 50 variables; what does not fit is listed as a manual note). |
22
- | Webhooks | Endpoint and events. Signing secrets are copied so receivers keep verifying (`--fresh-webhook-secrets` mints new ones, shown once). Events BillionSend also emits carry over (`email.*`, `contact.created`, `contact.updated`, `contact.deleted`, `contact.topics.updated`, `suppression.added`, `suppression.removed`, `domain.created`, `domain.updated`, `domain.deleted`, `topic.created`, `topic.updated`, `topic.deleted` and `inbox.*`); the rest are dropped per webhook and listed. `email.scheduled`, `email.failed` and `email.suppressed` carry over only to an instance that emits them (its `GET /openapi.json` lists them). An older one refuses those webhooks with a 422: migrate to it with `npx @billionsend/cli@0.2.3`, which drops the three along with `suppression.added` and `suppression.removed` and lists all five; add those two back to the webhook afterwards, in the dashboard or with `PATCH /webhooks/{id}`. |
23
- | Suppressions | Bounces, complaints and manual entries, with their origin. |
24
- | Domains | Created with return path and tracking settings, in the one SES region your BillionSend instance serves (BillionSend Cloud: `us-east-2`) — the Resend region does not carry over. The return path is always set explicitly and is never the label the domain has on Resend (`send` unless Resend names another): BillionSend gets `bounce`, or `bounces` when Resend's is already `bounce`, so the bounce MX record on Resend's side is not touched and both providers run in parallel until cutover; the plan and the report state both labels. BillionSend fixes the label at creation (changing it later means deleting the domain and creating it again). A domain that already exists on BillionSend is left as it is. DNS records must be added again (DKIM keys are per provider); the report prints a copy-ready table. Both providers can stay verified side by side. Resend has no unsubscribe subdomain or page, so those are left unset. |
25
- | Broadcasts | Drafts and scheduled ones import as drafts; sent ones are skipped unless `--include-sent`. |
26
- | API keys | Not recreated (the source only exposes names); the report lists them as a to-do. |
17
+ | Resource | How |
18
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | Contacts | Upserted by email through the batch endpoint; `unsubscribed` and topic opt-outs are preserved, never re-subscribed. Resend's `unsubscribed` is global, so it lands as BillionSend's team-wide `unsubscribed: true`; no per-domain unsubscribe is created. Topic subscriptions and properties follow in two per-contact passes that run after everything else, so the account is sendable before they finish. The batch endpoint answers created, updated or skipped but never whether a matched contact changed, so the summary reports those as `matched existing`, not as updated or unchanged. |
20
+ | Segments, topics, properties | Matched by name / name / key: created when missing, updated when different, left alone when equal. Segment memberships follow the contacts. BillionSend property keys ignore case, Resend's do not: when Resend has both `plan` and `PLAN`, only the first is created, the other is listed as a manual note, and the report counts the contacts whose value for it was not written. A key that differs only in case from one already on BillionSend is the same property, and values are written under the spelling it has. |
21
+ | Templates | Name, alias, subject, html, text, default from, reply-to and variables (up to 50 reply-to addresses and 50 variables; what does not fit is listed as a manual note). |
22
+ | Webhooks | Endpoint and events. Signing secrets are copied so receivers keep verifying (`--fresh-webhook-secrets` mints new ones, shown once). Events BillionSend also emits carry over (`email.*`, `contact.created`, `contact.updated`, `contact.deleted`, `contact.topics.updated`, `suppression.added`, `suppression.removed`, `domain.created`, `domain.updated`, `domain.deleted`, `topic.created`, `topic.updated`, `topic.deleted` and `inbox.*`); the rest are dropped per webhook and listed. |
23
+ | Suppressions | Bounces, complaints and manual entries, with their origin. |
24
+ | Domains | Created with return path and tracking settings, in the SES region BillionSend serves (`us-east-2`) — the Resend region does not carry over. The return path is always set explicitly and is never the label the domain has on Resend (`send` unless Resend names another): BillionSend gets `bounce`, or `bounces` when Resend's is already `bounce`, so the bounce MX record on Resend's side is not touched and both providers run in parallel until cutover; the plan and the report state both labels. BillionSend fixes the label at creation (changing it later means deleting the domain and creating it again). A domain that already exists on BillionSend is left as it is. DNS records must be added again (DKIM keys are per provider); the report prints a copy-ready table. Both providers can stay verified side by side. Resend has no unsubscribe subdomain or page, so those are left unset. |
25
+ | Broadcasts | Drafts and scheduled ones import as drafts; sent ones are skipped unless `--include-sent`. |
26
+ | API keys | Not recreated (the source only exposes names); the report lists them as a to-do. |
27
27
 
28
28
  Audiences (deprecated in Resend) are skipped — segments cover them.
29
29
 
@@ -43,21 +43,26 @@ billionsend broadcasts send --from "Leo <leo@mail.example.com>" --subject "Black
43
43
  billionsend broadcasts send --from "Leo <leo@mail.example.com>" --subject "Black Friday" \
44
44
  --html-file black-friday.html --segment Customers --topic Newsletter --wait
45
45
 
46
+ billionsend broadcasts list # newest first, with ids
46
47
  billionsend broadcasts get <id>
48
+ billionsend broadcasts recipients <id> --type opened --all > opened.csv # or --format json
49
+ billionsend segments create --name "Black Friday last call"
50
+ billionsend segments get "Black Friday last call" # its contact count
51
+ billionsend contacts import --file buyers.csv --segment "Black Friday last call"
47
52
  billionsend emails send --from "Leo <leo@mail.example.com>" --to you@example.com --subject "Hi" --text-file hi.txt --yes
48
53
  ```
49
54
 
50
- `--test` puts the test addresses in a segment named "CLI test recipients" that holds exactly them (contacts that do not exist yet are created; an existing contact's name, topics and unsubscribe state are left as they are) and sends the broadcast there with `[TEST]` before the subject, so a test goes through the real broadcast path: merge tags such as `{{{FIRST_NAME|there}}}` are filled per recipient and the unsubscribe link is the recipient's own. Without a terminal, sending needs `--yes`. `--wait` follows the broadcast until it is sent, failed or canceled; a small broadcast reads as sent within about five minutes of its last email. `billionsend broadcasts --help` lists every option.
55
+ `--test` puts the test addresses in a segment named "CLI test recipients" that holds exactly them (contacts that do not exist yet are created; an existing contact's name, topics and unsubscribe state are left as they are) and sends the broadcast there with `[TEST]` before the subject, so a test goes through the real broadcast path: merge tags such as `{{{FIRST_NAME|there}}}` are filled per recipient and the unsubscribe link is the recipient's own. Without a terminal, sending needs `--yes`. `--wait` follows the broadcast until it is sent, failed or canceled, for 30 minutes unless `--wait-timeout <minutes>` says otherwise; a small broadcast reads as sent within about five minutes of its last email, and a first send to contacts the team never mailed is released in steps over about an hour, so give that one `--wait-timeout 90` or more. `contacts import` uploads a CSV (a header row with an email column, at most 20 MiB), follows the import to its end and prints the counts; contacts who unsubscribed stay unsubscribed, and it exits 3 when some rows failed. Contacts the team already has are updated from the file and join `--segment` (a column the file lacks keeps its value); `--on-conflict skip` leaves them out entirely, segment included. By default a contact who got 8 or more of your broadcasts and automation emails with no open or click for 120 days gets a short "still want these?" email instead of the broadcast (only where the sending domain tracks opens or clicks); `--no-dormant-check` sends the content to everyone, and `--include-dormant` also reaches contacts who never answered that email. `broadcasts list` shows each broadcast's id, time, status and name, newest first. `broadcasts recipients` lists who was sent, delivered, opened, clicked, bounced, complained, unsubscribed or suppressed, as CSV or JSON, one page of 100 or every page with `--all`. `billionsend broadcasts --help` lists every option.
51
56
 
52
57
  ## Environment
53
58
 
54
- | Variable | Meaning |
55
- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
56
- | `RESEND_API_KEY` | Source key (full access; the tool only ever reads). Alternatives: `--from-key-stdin`, or a masked prompt in a terminal. |
57
- | `BILLIONSEND_API_KEY` | BillionSend key (full access). Alternatives: `--to-key-stdin`, or a masked prompt. |
58
- | `BILLIONSEND_BASE_URL` | BillionSend API URL. Same as `--to-url`. Unset, the target is BillionSend Cloud (`https://api.billionsend.com`), like the SDKs. |
59
- | `NO_COLOR` | Disables ANSI colors. |
60
- | `DO_NOT_TRACK` | Honored as a no-op: the tool sends no telemetry, never phones home and never checks for updates. |
59
+ | Variable | Meaning |
60
+ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------- |
61
+ | `RESEND_API_KEY` | Source key (full access; the tool only ever reads). Alternatives: `--from-key-stdin`, or a masked prompt in a terminal. |
62
+ | `BILLIONSEND_API_KEY` | BillionSend key (full access). Alternatives: `--to-key-stdin`, or a masked prompt. |
63
+ | `BILLIONSEND_BASE_URL` | BillionSend API URL. Same as `--to-url`. Unset, the target is `https://api.billionsend.com`, like the SDKs. |
64
+ | `NO_COLOR` | Disables ANSI colors. |
65
+ | `DO_NOT_TRACK` | Honored as a no-op: the tool sends no telemetry, never phones home and never checks for updates. |
61
66
 
62
67
  ## Flags
63
68
 
package/dist/index.js CHANGED
@@ -279,7 +279,8 @@ function createHttp(options) {
279
279
  authorization: `Bearer ${options.token}`,
280
280
  "user-agent": options.userAgent,
281
281
  accept: "application/json",
282
- ...body === void 0 ? {} : { "content-type": "application/json" },
282
+ // A FormData body sets its own multipart content type, boundary included.
283
+ ...body === void 0 || body instanceof FormData ? {} : { "content-type": "application/json" },
283
284
  ...extraHeaders
284
285
  };
285
286
  for (const [header, value] of Object.entries(headers)) {
@@ -292,7 +293,7 @@ function createHttp(options) {
292
293
  const init = {
293
294
  method,
294
295
  headers,
295
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
296
+ ...body === void 0 ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }
296
297
  };
297
298
  const repeatable = idempotent || REPEATABLE_METHODS.has(method);
298
299
  let rateLimited = 0;
@@ -2122,7 +2123,7 @@ function describePlanDiff(saved, current) {
2122
2123
  import { parseArgs as parseArgs2 } from "node:util";
2123
2124
 
2124
2125
  // src/meta.ts
2125
- var VERSION = true ? "0.4.0" : "0.0.0-dev";
2126
+ var VERSION = true ? "0.5.0" : "0.0.0-dev";
2126
2127
  var REPO_URL = "https://github.com/billionsend/billionsend-cli";
2127
2128
  var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
2128
2129
  var CLOUD_API_URL = "https://api.billionsend.com";
@@ -2146,8 +2147,8 @@ var RESOURCES = [
2146
2147
  ];
2147
2148
 
2148
2149
  // src/send.ts
2149
- import { readFileSync } from "node:fs";
2150
- import { resolve } from "node:path";
2150
+ import { readFileSync, statSync } from "node:fs";
2151
+ import { basename, resolve } from "node:path";
2151
2152
  import { parseArgs } from "node:util";
2152
2153
 
2153
2154
  // src/log.ts
@@ -2175,21 +2176,39 @@ function createLogger({
2175
2176
  }
2176
2177
 
2177
2178
  // src/send.ts
2178
- var SEND_COMMANDS = ["broadcasts", "emails"];
2179
+ var SEND_COMMANDS = ["broadcasts", "emails", "segments", "contacts"];
2179
2180
  var TEST_SEGMENT_NAME = "CLI test recipients";
2180
2181
  var SEND_RPS = 5;
2181
2182
  var WAIT_POLL_MS = 5e3;
2182
- var WAIT_LIMIT_MS = 30 * 6e4;
2183
+ var DEFAULT_WAIT_MINUTES = 30;
2184
+ var MAX_WAIT_MINUTES = 24 * 60;
2185
+ var IMPORT_POLL_MS = 2e3;
2186
+ var IMPORT_MAX_BYTES = 20 * 1024 * 1024;
2187
+ var RECIPIENT_TYPES = [
2188
+ "sent",
2189
+ "delivered",
2190
+ "opened",
2191
+ "clicked",
2192
+ "bounced",
2193
+ "complained",
2194
+ "unsubscribed",
2195
+ "suppressed"
2196
+ ];
2183
2197
  var SYSTEM_CLOCK = {
2184
2198
  now: () => Date.now(),
2185
2199
  sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms))
2186
2200
  };
2187
2201
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["sent", "failed", "canceled", "cancelled"]);
2188
- var sendHelpText = () => `Sending
2202
+ var sendHelpText = () => `Sending and the account
2189
2203
  billionsend broadcasts send --from <addr> --subject <s> --html-file <f> --segment <name|id> [options]
2190
2204
  billionsend broadcasts send ... --test <email> [--test <email>] the same broadcast, to these addresses only
2205
+ billionsend broadcasts list [--limit <n>] [--all] newest first, with each broadcast's id
2191
2206
  billionsend broadcasts get <id>
2207
+ billionsend broadcasts recipients <id> --type <type> [--all] [--format csv|json]
2192
2208
  billionsend emails send --from <addr> --to <email> --subject <s> (--html-file <f> | --text-file <f>) [options]
2209
+ billionsend segments create --name <name>
2210
+ billionsend segments get <name|id>
2211
+ billionsend contacts import --file <contacts.csv> [--segment <name|id>] [--on-conflict upsert|skip]
2193
2212
 
2194
2213
  Sending options
2195
2214
  --from <address> sender, "Name <user@your-domain>"; the domain must be verified on BillionSend
@@ -2202,11 +2221,26 @@ Sending options
2202
2221
  --preview-text <text> broadcasts: inbox preview line
2203
2222
  --reply-to <address> repeatable
2204
2223
  --to <email> emails: repeatable
2224
+ --no-dormant-check broadcasts: send the content to every contact. By default a contact who got 8 or more
2225
+ of your broadcasts and automation emails with no open or click for 120 days gets a short
2226
+ "still want these?" email instead (only where the domain tracks opens or clicks)
2227
+ --include-dormant broadcasts: also send to contacts marked dormant (they never answered that email)
2205
2228
  --test <email> broadcasts: send to these addresses instead of the segment (repeatable or comma-separated).
2206
2229
  They are put in a segment named "${TEST_SEGMENT_NAME}" holding exactly them, so the test
2207
2230
  goes through the real broadcast path: names and unsubscribe links are each recipient's own
2208
- --wait broadcasts: follow the broadcast until it is sent, failed or canceled (30 min at most)
2231
+ --wait broadcasts: follow the broadcast until it is sent, failed or canceled
2232
+ --wait-timeout <minutes> how long --wait and contacts import follow before giving up (default ${DEFAULT_WAIT_MINUTES}).
2233
+ A first send to new contacts is released in steps over about an hour: give it 90 or more
2209
2234
  --idempotency-key <key> emails: a retry with the same key sends once
2235
+ --type <type> recipients: ${RECIPIENT_TYPES.join(", ")}
2236
+ --all recipients, list: every page (default: one page)
2237
+ --limit <n> list: how many per page, 1-100 (default 20)
2238
+ --format csv|json recipients: output format (default csv; --json is the same as --format json)
2239
+ --file <path> contacts import: a CSV with a header row and an email column, at most 20 MiB;
2240
+ contacts who unsubscribed stay unsubscribed
2241
+ --on-conflict upsert|skip contacts import: update contacts the team already has from the file and add them to
2242
+ --segment (default; a column the file lacks keeps its value), or skip them entirely,
2243
+ segment included
2210
2244
  --key-stdin read the BillionSend API key from stdin instead of BILLIONSEND_API_KEY
2211
2245
  -y, --yes send without asking; required when stdin is not a terminal
2212
2246
  --json JSON on stdout
@@ -2226,6 +2260,15 @@ var OPTIONS = {
2226
2260
  to: { type: "string", multiple: true },
2227
2261
  test: { type: "string", multiple: true },
2228
2262
  wait: { type: "boolean" },
2263
+ "no-dormant-check": { type: "boolean" },
2264
+ "include-dormant": { type: "boolean" },
2265
+ limit: { type: "string" },
2266
+ "wait-timeout": { type: "string" },
2267
+ type: { type: "string" },
2268
+ all: { type: "boolean" },
2269
+ format: { type: "string" },
2270
+ file: { type: "string" },
2271
+ "on-conflict": { type: "string" },
2229
2272
  "idempotency-key": { type: "string" },
2230
2273
  "key-stdin": { type: "boolean" },
2231
2274
  "to-url": { type: "string" },
@@ -2346,8 +2389,18 @@ async function confirm(io, values, question) {
2346
2389
  }
2347
2390
  }
2348
2391
  var describe = (b) => `status ${b.status}${b.sent_count === null ? "" : ` \xB7 sent ${b.sent_count}`}${b.failure_reason ? ` \xB7 ${b.failure_reason}` : ""}`;
2349
- async function waitFor(http, id, say, clock) {
2350
- const deadline = clock.now() + WAIT_LIMIT_MS;
2392
+ function waitMinutes(values) {
2393
+ const raw = values["wait-timeout"];
2394
+ if (raw === void 0) return DEFAULT_WAIT_MINUTES;
2395
+ const minutes = Number(raw);
2396
+ if (!(minutes > 0 && minutes <= MAX_WAIT_MINUTES))
2397
+ throw new UsageError(
2398
+ `--wait-timeout takes minutes, more than 0 and at most ${MAX_WAIT_MINUTES}.`
2399
+ );
2400
+ return minutes;
2401
+ }
2402
+ async function waitFor(http, id, say, clock, minutes) {
2403
+ const deadline = clock.now() + minutes * 6e4;
2351
2404
  let last = "";
2352
2405
  for (; ; ) {
2353
2406
  const { body } = await http.get(route`/broadcasts/${id}`);
@@ -2363,6 +2416,7 @@ async function broadcastsSend(io, http, values, clock) {
2363
2416
  const from = required(values, "from");
2364
2417
  const subject = required(values, "subject");
2365
2418
  const body = readBody(io, values);
2419
+ const minutes = waitMinutes(values);
2366
2420
  const test = splitAddresses(values.test);
2367
2421
  const segmentRef = values.segment;
2368
2422
  if (test.length === 0 && !segmentRef)
@@ -2401,6 +2455,8 @@ async function broadcastsSend(io, http, values, clock) {
2401
2455
  ...topic ? { topic_id: topic.id } : {},
2402
2456
  ...values["reply-to"]?.length ? { reply_to: values["reply-to"] } : {},
2403
2457
  ...values["preview-text"] ? { preview_text: values["preview-text"] } : {},
2458
+ ...values["no-dormant-check"] ? { dormant_check: false } : {},
2459
+ ...values["include-dormant"] ? { include_dormant: true } : {},
2404
2460
  ...body,
2405
2461
  send: true
2406
2462
  },
@@ -2411,19 +2467,18 @@ async function broadcastsSend(io, http, values, clock) {
2411
2467
  let result;
2412
2468
  let gaveUp = false;
2413
2469
  if (values.wait) {
2414
- const waited = await waitFor(http, id, say, clock);
2470
+ const waited = await waitFor(http, id, say, clock, minutes);
2415
2471
  result = waited.broadcast;
2416
2472
  gaveUp = !waited.ended;
2417
2473
  if (gaveUp)
2418
2474
  say(
2419
- `Still ${result.status} after 30 minutes; follow it with: billionsend broadcasts get ${id}`
2475
+ `Still ${result.status} after ${minutes} minutes; follow it with: billionsend broadcasts get ${id}`
2420
2476
  );
2421
2477
  } else {
2422
2478
  result = (await http.get(route`/broadcasts/${id}`)).body;
2423
2479
  say(` ${describe(result)}`);
2424
2480
  }
2425
- if (values.json)
2426
- io.stdout.write(`${JSON.stringify(result)}
2481
+ if (values.json) io.stdout.write(`${JSON.stringify(result)}
2427
2482
  `);
2428
2483
  return result.status === "failed" || gaveUp ? 1 : 0;
2429
2484
  }
@@ -2465,6 +2520,149 @@ async function emailsSend(io, http, values) {
2465
2520
  `);
2466
2521
  return 0;
2467
2522
  }
2523
+ async function broadcastsList(io, http, values) {
2524
+ const limit = values.limit === void 0 ? 20 : Number(values.limit);
2525
+ if (!(Number.isInteger(limit) && limit >= 1 && limit <= 100))
2526
+ throw new UsageError("--limit takes a whole number from 1 to 100.");
2527
+ const path2 = "/broadcasts";
2528
+ const rows = [];
2529
+ const guard = cursorGuard(path2);
2530
+ let after;
2531
+ let more = false;
2532
+ for (; ; ) {
2533
+ const { body } = await http.get(path2, { query: { limit, after } });
2534
+ const page = pageItems(path2, body, after);
2535
+ guard(page, after);
2536
+ rows.push(...page);
2537
+ more = body.has_more === true;
2538
+ if (!more || !values.all) break;
2539
+ after = nextCursor(path2, page, after);
2540
+ }
2541
+ if (values.json) io.stdout.write(`${JSON.stringify(rows)}
2542
+ `);
2543
+ else
2544
+ for (const b of rows)
2545
+ io.stdout.write(
2546
+ `${b.id} \xB7 ${b.created_at.slice(0, 16).replace("T", " ")} \xB7 ${describe(b)}${b.name ? ` \xB7 ${b.name}` : ""}
2547
+ `
2548
+ );
2549
+ if (more) io.stderr.write("More broadcasts remain; pass --all for every page.\n");
2550
+ return 0;
2551
+ }
2552
+ async function segmentsCreate(io, http, values) {
2553
+ const name = values.name?.trim();
2554
+ if (!name) throw new UsageError("--name is required.");
2555
+ const { body } = await http.post("/segments", { name }, { idempotent: false });
2556
+ if (values.json) io.stdout.write(`${JSON.stringify(body)}
2557
+ `);
2558
+ else io.stdout.write(`Segment ${body.id} created (${body.name}).
2559
+ `);
2560
+ return 0;
2561
+ }
2562
+ async function segmentsGet(io, http, values, ref) {
2563
+ if (!ref) throw new UsageError("Usage: billionsend segments get <name|id>");
2564
+ const segment = await resolveNamed(http, "/segments", "segment", ref);
2565
+ const { body } = await http.get(route`/segments/${segment.id}`);
2566
+ if (values.json) io.stdout.write(`${JSON.stringify(body)}
2567
+ `);
2568
+ else io.stdout.write(`${body.name} \xB7 ${body.id} \xB7 ${body.contact_count} contacts
2569
+ `);
2570
+ return 0;
2571
+ }
2572
+ async function contactsImport(io, http, values, clock) {
2573
+ const path2 = values.file;
2574
+ if (!path2) throw new UsageError("--file is required.");
2575
+ const onConflict = values["on-conflict"];
2576
+ if (onConflict !== void 0 && onConflict !== "upsert" && onConflict !== "skip")
2577
+ throw new UsageError("--on-conflict takes upsert or skip.");
2578
+ const minutes = waitMinutes(values);
2579
+ const full = resolve(io.cwd, path2);
2580
+ let csv;
2581
+ try {
2582
+ if (statSync(full).size > IMPORT_MAX_BYTES)
2583
+ throw new UsageError(`${path2} is larger than 20 MiB, the most one import takes.`);
2584
+ csv = readFileSync(full);
2585
+ } catch (error) {
2586
+ if (error instanceof UsageError) throw error;
2587
+ throw new UsageError(`Cannot read --file ${path2}`);
2588
+ }
2589
+ const segment = values.segment ? await resolveNamed(http, "/segments", "segment", values.segment) : null;
2590
+ const form = new FormData();
2591
+ form.set("file", new Blob([csv], { type: "text/csv" }), basename(full));
2592
+ if (segment) form.set("segments", JSON.stringify([{ id: segment.id }]));
2593
+ if (onConflict) form.set("on_conflict", onConflict);
2594
+ const say = (line) => (values.json ? io.stderr : io.stdout).write(`${line}
2595
+ `);
2596
+ const { body: started } = await http.post("/contacts/imports", form, {
2597
+ idempotent: false
2598
+ });
2599
+ say(`Import ${started.id} started${segment ? ` into segment ${segment.name}` : ""}.`);
2600
+ const deadline = clock.now() + minutes * 6e4;
2601
+ let job;
2602
+ for (; ; ) {
2603
+ job = (await http.get(route`/contacts/imports/${started.id}`)).body;
2604
+ if (job.status === "completed" || job.status === "failed" || clock.now() >= deadline) break;
2605
+ await clock.sleep(IMPORT_POLL_MS);
2606
+ }
2607
+ const { total, created, updated, skipped, failed } = job.counts;
2608
+ say(
2609
+ ` status ${job.status} \xB7 ${total} rows \xB7 ${created} created \xB7 ${updated} updated \xB7 ${skipped} skipped \xB7 ${failed} failed`
2610
+ );
2611
+ if (values.json) io.stdout.write(`${JSON.stringify(job)}
2612
+ `);
2613
+ if (job.status === "completed") return failed > 0 ? 3 : 0;
2614
+ if (job.status !== "failed") say(`Still ${job.status} after ${minutes} minutes.`);
2615
+ return 1;
2616
+ }
2617
+ var csvField = (value) => /[",\r\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
2618
+ function recipientsCsv(rows) {
2619
+ const lines = ["email,contact_id,email_id,count,clicked_links,bounce_type"];
2620
+ for (const r of rows) {
2621
+ lines.push(
2622
+ [
2623
+ r.email,
2624
+ r.contact_id ?? "",
2625
+ r.id,
2626
+ r.count === void 0 ? "" : String(r.count),
2627
+ (r.clicked_links ?? []).map((l) => `${l.url} (${l.clicks})`).join("; "),
2628
+ r.bounce_type ?? ""
2629
+ ].map(csvField).join(",")
2630
+ );
2631
+ }
2632
+ return `${lines.join("\n")}
2633
+ `;
2634
+ }
2635
+ async function broadcastsRecipients(io, http, values, id) {
2636
+ if (!id) throw new UsageError("Usage: billionsend broadcasts recipients <id> --type <type>");
2637
+ const type = values.type;
2638
+ if (!type || !RECIPIENT_TYPES.includes(type))
2639
+ throw new UsageError(`--type is one of: ${RECIPIENT_TYPES.join(", ")}`);
2640
+ const format = values.json ? "json" : values.format ?? "csv";
2641
+ if (format !== "csv" && format !== "json") throw new UsageError("--format takes csv or json.");
2642
+ const path2 = route`/broadcasts/${id}/recipients`;
2643
+ const rows = [];
2644
+ const guard = cursorGuard(path2);
2645
+ let after;
2646
+ let more = false;
2647
+ for (; ; ) {
2648
+ const { body } = await http.get(path2, {
2649
+ query: { type, limit: 100, after }
2650
+ });
2651
+ const page = pageItems(path2, body, after);
2652
+ guard(page, after);
2653
+ rows.push(...page);
2654
+ more = body.has_more === true;
2655
+ if (!more || !values.all) break;
2656
+ after = nextCursor(path2, page, after);
2657
+ }
2658
+ io.stdout.write(format === "json" ? `${JSON.stringify(rows)}
2659
+ ` : recipientsCsv(rows));
2660
+ io.stderr.write(
2661
+ `${rows.length} ${type} recipient${rows.length === 1 ? "" : "s"}${more ? "; more remain, pass --all for every page" : ""}.
2662
+ `
2663
+ );
2664
+ return 0;
2665
+ }
2468
2666
  async function readKey(io, values) {
2469
2667
  if (values["key-stdin"]) {
2470
2668
  const rl = lineReader(io.stdin, io.stderr);
@@ -2481,6 +2679,17 @@ async function readKey(io, values) {
2481
2679
  if (!key) throw new UsageError("Set BILLIONSEND_API_KEY or pass --key-stdin.");
2482
2680
  return key;
2483
2681
  }
2682
+ var COMMANDS = {
2683
+ "broadcasts send": ({ io, http, values, clock }) => broadcastsSend(io, http, values, clock),
2684
+ "broadcasts get": ({ io, http, values, id }) => broadcastsGet(io, http, values, id),
2685
+ "broadcasts list": ({ io, http, values }) => broadcastsList(io, http, values),
2686
+ "broadcasts recipients": ({ io, http, values, id }) => broadcastsRecipients(io, http, values, id),
2687
+ "emails send": ({ io, http, values }) => emailsSend(io, http, values),
2688
+ "segments create": ({ io, http, values }) => segmentsCreate(io, http, values),
2689
+ "segments get": ({ io, http, values, id }) => segmentsGet(io, http, values, id),
2690
+ "contacts import": ({ io, http, values, clock }) => contactsImport(io, http, values, clock)
2691
+ };
2692
+ var TAKES_ID = /* @__PURE__ */ new Set(["broadcasts get", "broadcasts recipients", "segments get"]);
2484
2693
  async function runSend(argv, ioIn = {}, clock = SYSTEM_CLOCK) {
2485
2694
  const io = {
2486
2695
  stdout: ioIn.stdout ?? process.stdout,
@@ -2503,9 +2712,10 @@ async function runSend(argv, ioIn = {}, clock = SYSTEM_CLOCK) {
2503
2712
  io.stdout.write(sendHelpText());
2504
2713
  return values.help ? 0 : 1;
2505
2714
  }
2506
- const known = command === "broadcasts" && (sub === "send" || sub === "get") || command === "emails" && sub === "send";
2507
- if (!known) throw new UsageError(`Unknown command: ${command} ${sub}`);
2508
- if (rest.length > 0 || id !== void 0 && sub !== "get")
2715
+ const name = `${command} ${sub}`;
2716
+ const run = COMMANDS[name];
2717
+ if (!run) throw new UsageError(`Unknown command: ${name}`);
2718
+ if (rest.length > 0 || id !== void 0 && !TAKES_ID.has(name))
2509
2719
  throw new UsageError(`Unexpected argument: ${[id, ...rest].filter(Boolean).join(" ")}`);
2510
2720
  const token = await readKey(io, values);
2511
2721
  const baseUrl = stripTrailingSlashes(
@@ -2520,9 +2730,7 @@ async function runSend(argv, ioIn = {}, clock = SYSTEM_CLOCK) {
2520
2730
  name: "BillionSend",
2521
2731
  fetch: io.fetch
2522
2732
  });
2523
- if (command === "emails") return await emailsSend(io, http, values);
2524
- if (sub === "get") return await broadcastsGet(io, http, values, id);
2525
- return await broadcastsSend(io, http, values, clock);
2733
+ return await run({ io, http, values, id, clock });
2526
2734
  } catch (error) {
2527
2735
  if (error instanceof UsageError || error instanceof AuthError || error instanceof ApiError) {
2528
2736
  log.error(error.message);
@@ -3300,7 +3508,7 @@ import {
3300
3508
  unlinkSync,
3301
3509
  writeFileSync
3302
3510
  } from "node:fs";
3303
- import { basename, dirname, join } from "node:path";
3511
+ import { basename as basename2, dirname, join } from "node:path";
3304
3512
  var STATE_DIR = ".billionsend";
3305
3513
  function migratePaths(cwd = process.cwd()) {
3306
3514
  const dir = join(cwd, STATE_DIR);
@@ -3314,7 +3522,7 @@ function migratePaths(cwd = process.cwd()) {
3314
3522
  function writePrivate(path2, content) {
3315
3523
  const dir = dirname(path2);
3316
3524
  mkdirSync(dir, { recursive: true, mode: 448 });
3317
- if (basename(dir) === STATE_DIR && lstatSync(dir).isSymbolicLink()) {
3525
+ if (basename2(dir) === STATE_DIR && lstatSync(dir).isSymbolicLink()) {
3318
3526
  throw new Error(`${dir} is a symbolic link; remove it and run again.`);
3319
3527
  }
3320
3528
  const tmp = `${path2}.tmp`;
@@ -5163,7 +5371,7 @@ function createContext(config, io = {}) {
5163
5371
  }
5164
5372
 
5165
5373
  // src/index.ts
5166
- var COMMANDS = { migrate, plan, apply, status, rollback };
5374
+ var COMMANDS2 = { migrate, plan, apply, status, rollback };
5167
5375
  async function main(argv = process.argv.slice(2), io = {}) {
5168
5376
  if (SEND_COMMANDS.includes(argv[0] ?? "")) return runSend(argv, io);
5169
5377
  const stdout = io.stdout ?? process.stdout;
@@ -5189,7 +5397,7 @@ async function main(argv = process.argv.slice(2), io = {}) {
5189
5397
  const ctx = createContext(config, io);
5190
5398
  for (const warning of config.warnings) ctx.log.warn(warning);
5191
5399
  try {
5192
- return await COMMANDS[config.command](ctx);
5400
+ return await COMMANDS2[config.command](ctx);
5193
5401
  } catch (error) {
5194
5402
  ctx.progress.clear();
5195
5403
  ctx.log.error(error instanceof Error ? error.message : String(error));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@billionsend/cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Migrate an email account to BillionSend: contacts, segments, topics, templates, webhooks, domains and suppressions — read from the source provider, written to your BillionSend account, re-run safe",
5
5
  "license": "MIT",
6
6
  "type": "module",