@billionsend/cli 0.2.4 → 0.3.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 +19 -14
  2. package/dist/index.js +780 -205
  3. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -89,11 +89,18 @@ var AuthError = class extends Error {
89
89
  var ApiError = class extends Error {
90
90
  status;
91
91
  body;
92
- constructor(status2, name, message, body = null) {
92
+ /**
93
+ * The request was sent once and not again because it may have written something (a POST or
94
+ * PATCH that failed with a 5xx, a timeout or a lost connection). The caller records it as a
95
+ * failure; a re-run picks it up.
96
+ */
97
+ sentOnce;
98
+ constructor(status2, name, message, body = null, sentOnce = false) {
93
99
  super(message);
94
100
  this.name = name;
95
101
  this.status = status2;
96
102
  this.body = body;
103
+ this.sentOnce = sentOnce;
97
104
  }
98
105
  };
99
106
  var PaginationError = class extends Error {
@@ -103,6 +110,24 @@ var PaginationError = class extends Error {
103
110
  }
104
111
  };
105
112
  var MAX_PAGES = 1e5;
113
+ function pageItems(path2, body, after) {
114
+ const data = typeof body === "object" && body !== null ? body.data : void 0;
115
+ if (!Array.isArray(data))
116
+ throw new PaginationError(path2, after, "the list page has no data array");
117
+ return data;
118
+ }
119
+ function nextCursor(path2, page, after) {
120
+ const last = page.at(-1);
121
+ const id = typeof last === "object" && last !== null ? last.id : void 0;
122
+ if (typeof id !== "string" || id === "") {
123
+ throw new PaginationError(
124
+ path2,
125
+ after,
126
+ "the last item of the list page has no id to continue from"
127
+ );
128
+ }
129
+ return id;
130
+ }
106
131
  function cursorGuard(path2, maxPages = MAX_PAGES) {
107
132
  const seen = /* @__PURE__ */ new Set();
108
133
  let pages = 0;
@@ -111,7 +136,7 @@ function cursorGuard(path2, maxPages = MAX_PAGES) {
111
136
  if (pages > maxPages) {
112
137
  throw new PaginationError(path2, after, `more than ${maxPages} pages walked`);
113
138
  }
114
- if (page.length > 0 && page[page.length - 1]?.id === after) {
139
+ if (after !== void 0 && page.length > 0 && page[page.length - 1]?.id === after) {
115
140
  throw new PaginationError(
116
141
  path2,
117
142
  after,
@@ -124,7 +149,32 @@ function cursorGuard(path2, maxPages = MAX_PAGES) {
124
149
  for (const row of page) seen.add(row.id);
125
150
  };
126
151
  }
152
+ var route = (strings, ...values) => strings.reduce(
153
+ (out, text, i) => out + text + (i < values.length ? encodeURIComponent(values[i] ?? "") : ""),
154
+ ""
155
+ );
156
+ function badSegment(pathname) {
157
+ for (const segment of pathname.split("/").slice(1)) {
158
+ let decoded = segment;
159
+ try {
160
+ decoded = decodeURIComponent(segment);
161
+ } catch {
162
+ }
163
+ if (decoded === "" || decoded === "." || decoded === "..")
164
+ return decoded === "" ? "an empty one" : `\`${decoded}\``;
165
+ }
166
+ return null;
167
+ }
168
+ var HEADER_VALUE = /^[\t\x20-\x7e]*$/;
169
+ var RequestError = class extends Error {
170
+ constructor(message) {
171
+ super(message);
172
+ this.name = "invalid_request";
173
+ }
174
+ };
127
175
  var MAX_WAIT_MS = 12e4;
176
+ var MAX_RETRY_AFTER_MS = 6e4;
177
+ var REPEATABLE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE"]);
128
178
  var REMAINING_RESERVE = 2;
129
179
  var clampWait = (ms) => Math.min(MAX_WAIT_MS, Math.max(0, ms));
130
180
  function headerNumber(headers, name) {
@@ -209,11 +259,18 @@ function createHttp(options) {
209
259
  holdUntil = Math.max(holdUntil, Date.now() + clampWait(reset * 1e3));
210
260
  }
211
261
  };
212
- async function request(method, path2, body, { query, headers: extraHeaders } = {}) {
262
+ async function request(method, path2, body, { query, headers: extraHeaders, idempotent = false } = {}) {
213
263
  if (options.readOnly === true && method !== "GET") {
214
264
  throw new Error(`${name} is read-only for this tool; refusing ${method} ${path2}`);
215
265
  }
216
- const url = new URL(base + (path2.startsWith("/") ? path2 : `/${path2}`));
266
+ const rawPath = path2.startsWith("/") ? path2 : `/${path2}`;
267
+ const bad = badSegment(rawPath.split("?")[0] ?? rawPath);
268
+ if (bad !== null) {
269
+ throw new RequestError(
270
+ `${name}: ${method} ${rawPath.split("?")[0]} has ${bad} as a path segment; an id is missing or not an id`
271
+ );
272
+ }
273
+ const url = new URL(base + rawPath);
217
274
  for (const [key, value] of Object.entries(query ?? {})) {
218
275
  if (value !== void 0) url.searchParams.set(key, String(value));
219
276
  }
@@ -225,11 +282,19 @@ function createHttp(options) {
225
282
  ...body === void 0 ? {} : { "content-type": "application/json" },
226
283
  ...extraHeaders
227
284
  };
285
+ for (const [header, value] of Object.entries(headers)) {
286
+ if (!HEADER_VALUE.test(value)) {
287
+ throw new RequestError(
288
+ `${name}: the ${header} header holds a character a header cannot carry (only printable ASCII is allowed)${header === "authorization" ? "; check the API key for a stray line break or non-ASCII character" : ""}`
289
+ );
290
+ }
291
+ }
228
292
  const init = {
229
293
  method,
230
294
  headers,
231
295
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
232
296
  };
297
+ const repeatable = idempotent || REPEATABLE_METHODS.has(method);
233
298
  let rateLimited = 0;
234
299
  let failures = 0;
235
300
  for (; ; ) {
@@ -241,12 +306,14 @@ function createHttp(options) {
241
306
  } catch (error) {
242
307
  const reason = networkReason(error);
243
308
  failures += 1;
244
- if (failures >= maxAttempts) {
309
+ if (!repeatable || failures >= maxAttempts) {
245
310
  const hint = name === "BillionSend" ? "check --to-url / BILLIONSEND_BASE_URL" : `check your network to ${url.host}`;
246
311
  throw new ApiError(
247
312
  0,
248
313
  "network_error",
249
- `${name}: ${label} failed ${failures} times \u2014 ${reason}; ${hint}`
314
+ `${name}: ${label} failed ${failures} times \u2014 ${reason}; ${hint}`,
315
+ null,
316
+ !repeatable
250
317
  );
251
318
  }
252
319
  const wait = 1e3 * 2 ** (failures - 1);
@@ -272,6 +339,14 @@ function createHttp(options) {
272
339
  );
273
340
  }
274
341
  const wait = retryAfterMs(response.headers) ?? 2e3;
342
+ if (wait > MAX_RETRY_AFTER_MS) {
343
+ throw new ApiError(
344
+ 429,
345
+ "rate_limit_exceeded",
346
+ `${name} asks to wait ${Math.round(wait / 1e3)}s after rate limiting ${label}; not waiting more than ${MAX_RETRY_AFTER_MS / 1e3}s`,
347
+ parsed
348
+ );
349
+ }
275
350
  rps = Math.max(1, rps / 2);
276
351
  rampedAt = Date.now();
277
352
  log.warn(
@@ -282,12 +357,13 @@ function createHttp(options) {
282
357
  }
283
358
  if (status2 >= 500) {
284
359
  failures += 1;
285
- if (failures >= maxAttempts) {
360
+ if (!repeatable || failures >= maxAttempts) {
286
361
  throw new ApiError(
287
362
  status2,
288
363
  "server_error",
289
- `${name} answered ${status2} to ${label} ${failures} times`,
290
- parsed
364
+ `${name} answered ${status2} to ${label}${failures > 1 ? ` ${failures} times` : ""}${repeatable ? "" : "; it is not sent again, because it may have been written (run again to continue)"}`,
365
+ parsed,
366
+ !repeatable
291
367
  );
292
368
  }
293
369
  const wait = 1e3 * 2 ** (failures - 1);
@@ -431,27 +507,52 @@ var emptySnapshot = () => ({
431
507
  webhooks: [],
432
508
  suppressions: [],
433
509
  metrics: { emailsLast30Days: null },
434
- enriched: false
510
+ enriched: false,
511
+ segmentScope: null
435
512
  });
513
+ var SEGMENT_HINT_MAX = 30;
514
+ function selectSegments(all, selectors) {
515
+ const picked = [];
516
+ const missing = [];
517
+ for (const selector of selectors) {
518
+ const lower = selector.toLowerCase();
519
+ const matches = [
520
+ all.filter((s) => s.id === selector),
521
+ all.filter((s) => s.name === selector),
522
+ all.filter((s) => s.name.toLowerCase() === lower)
523
+ ].find((found) => found.length > 0);
524
+ if (matches === void 0) missing.push(selector);
525
+ else for (const match of matches) if (!picked.includes(match)) picked.push(match);
526
+ }
527
+ if (missing.length > 0) {
528
+ const shown = all.slice(0, SEGMENT_HINT_MAX).map((s) => ` ${s.name} (${s.id})`);
529
+ const more = all.length - shown.length;
530
+ throw new Error(
531
+ `No Resend segment named or with the id ${missing.map((m) => `\`${m}\``).join(", ")}. ${all.length === 0 ? "The account has no segments." : `Segments on the account:
532
+ ${shown.join("\n")}${more > 0 ? `
533
+ \u2026 and ${more} more` : ""}`}`
534
+ );
535
+ }
536
+ return picked;
537
+ }
436
538
  function createResendSource(http, log) {
437
539
  let requests = 0;
438
- const get = (route, options) => {
540
+ const get = (route2, options) => {
439
541
  requests += 1;
440
- return http.get(route, options);
542
+ return http.get(route2, options);
441
543
  };
442
- async function listAll(route, query = {}, label, onProgress) {
544
+ async function listAll(route2, query = {}, label, onProgress) {
443
545
  const items = [];
444
546
  let after;
445
- const guard = cursorGuard(route);
547
+ const guard = cursorGuard(route2);
446
548
  for (; ; ) {
447
- const { body } = await get(route, { query: { ...query, limit: PAGE, after } });
448
- const data = body.data ?? [];
549
+ const { body } = await get(route2, { query: { ...query, limit: PAGE, after } });
550
+ const data = pageItems(route2, body, after);
449
551
  guard(data, after);
450
552
  items.push(...data);
451
- const last = data[data.length - 1];
452
553
  const hasMore = body.has_more ?? data.length === PAGE;
453
- if (!hasMore || last === void 0) break;
454
- after = last.id;
554
+ if (!hasMore || data.length === 0) break;
555
+ after = nextCursor(route2, data, after);
455
556
  if (label !== void 0) onProgress?.({ label, n: items.length, done: false });
456
557
  }
457
558
  if (label !== void 0) {
@@ -459,8 +560,8 @@ function createResendSource(http, log) {
459
560
  }
460
561
  return items;
461
562
  }
462
- async function listWithDetails(route, label, onProgress, detail, keep = () => true) {
463
- const list = (await listAll(route)).filter(keep);
563
+ async function listWithDetails(route2, label, onProgress, detail, keep = () => true) {
564
+ const list = (await listAll(route2)).filter(keep);
464
565
  const out = [];
465
566
  for (const item of list) {
466
567
  out.push(await detail(item));
@@ -469,6 +570,23 @@ function createResendSource(http, log) {
469
570
  onProgress?.({ label, n: out.length, total: list.length, done: true });
470
571
  return out;
471
572
  }
573
+ async function readSegments(scope, onProgress, membersOf) {
574
+ const list = scope ?? await listAll("/segments");
575
+ const out = [];
576
+ for (const item of list) {
577
+ const { body } = await get(path("segments", item.id));
578
+ const members = await membersOf(item.id);
579
+ out.push({
580
+ id: item.id,
581
+ name: body.name ?? item.name,
582
+ filter: body.filter ?? null,
583
+ memberEmails: members.map((member) => member.email)
584
+ });
585
+ onProgress?.({ label: "Segments", n: out.length, total: list.length, done: false });
586
+ }
587
+ onProgress?.({ label: "Segments", n: out.length, total: list.length, done: true });
588
+ return out;
589
+ }
472
590
  return {
473
591
  get requests() {
474
592
  return requests;
@@ -478,8 +596,19 @@ function createResendSource(http, log) {
478
596
  const first = body.data?.[0];
479
597
  return first === void 0 ? { ok: true } : { ok: true, teamHint: first.name };
480
598
  },
481
- async readShallow({ include, includeSent = false, onProgress }) {
599
+ async readShallow({ include, includeSent = false, segments = [], onProgress }) {
482
600
  const snapshot = emptySnapshot();
601
+ const needsContacts = include.has("contacts") || include.has("enrichment");
602
+ const scope = segments.length === 0 ? null : selectSegments(await listAll("/segments"), segments);
603
+ if (scope !== null) snapshot.segmentScope = scope.map(({ id, name }) => ({ id, name }));
604
+ const memberLists = /* @__PURE__ */ new Map();
605
+ const membersOf = async (id) => {
606
+ const cached = memberLists.get(id);
607
+ if (cached !== void 0) return cached;
608
+ const members = await listAll(path("segments", id, "contacts"), {});
609
+ memberLists.set(id, members);
610
+ return members;
611
+ };
483
612
  if (include.has("domains")) {
484
613
  snapshot.domains = await listWithDetails(
485
614
  "/domains",
@@ -512,26 +641,30 @@ function createResendSource(http, log) {
512
641
  visibility: topic.visibility
513
642
  }));
514
643
  }
515
- if (include.has("segments")) {
516
- snapshot.segments = await listWithDetails(
517
- "/segments",
518
- "Segments",
519
- onProgress,
520
- async (item) => {
521
- const { body } = await get(path("segments", item.id));
522
- const members = await listAll(`/segments/${item.id}/contacts`, {});
523
- return {
524
- id: item.id,
525
- name: body.name ?? item.name,
526
- filter: body.filter ?? null,
527
- memberEmails: members.map((member) => member.email)
528
- };
529
- }
644
+ if (include.has("segments") || scope !== null && needsContacts) {
645
+ snapshot.segments = await readSegments(
646
+ scope,
647
+ include.has("segments") ? onProgress : void 0,
648
+ membersOf
530
649
  );
531
650
  }
532
- if (include.has("contacts") || include.has("enrichment")) {
533
- const list = await listAll("/contacts", {}, "Contacts", onProgress);
534
- snapshot.contacts = list.map(toContact);
651
+ if (needsContacts) {
652
+ if (scope === null) {
653
+ const list = await listAll("/contacts", {}, "Contacts", onProgress);
654
+ snapshot.contacts = list.map(toContact);
655
+ } else {
656
+ const seen = /* @__PURE__ */ new Set();
657
+ const members = [];
658
+ for (const segment of scope) {
659
+ for (const member of await membersOf(segment.id)) {
660
+ if (seen.has(member.id)) continue;
661
+ seen.add(member.id);
662
+ members.push(member);
663
+ }
664
+ }
665
+ onProgress?.({ label: "Contacts", n: members.length, total: members.length, done: true });
666
+ snapshot.contacts = members.map(toContact);
667
+ }
535
668
  }
536
669
  if (include.has("broadcasts")) {
537
670
  snapshot.broadcasts = await listWithDetails(
@@ -644,7 +777,7 @@ function createResendSource(http, log) {
644
777
  var pagesOf = (count) => Math.max(1, Math.ceil(count / PAGE));
645
778
  function estimateSourceRequests(snapshot) {
646
779
  const s = snapshot;
647
- const spent = pagesOf(s.domains.length) + s.domains.length + pagesOf(s.properties.length) + pagesOf(s.topics.length) + pagesOf(s.segments.length) + s.segments.reduce((sum, segment) => sum + 1 + pagesOf(segment.memberEmails.length), 0) + pagesOf(s.contacts.length) + pagesOf(s.broadcasts.length) + s.broadcasts.filter((b) => b.status !== "sent" || b.html !== null || b.text !== null).length + pagesOf(s.templates.length) + s.templates.length + pagesOf(s.webhooks.length) + s.webhooks.length + pagesOf(s.suppressions.length) + pagesOf(s.apiKeys.length);
780
+ const spent = pagesOf(s.domains.length) + s.domains.length + pagesOf(s.properties.length) + pagesOf(s.topics.length) + pagesOf(s.segments.length) + s.segments.reduce((sum, segment) => sum + 1 + pagesOf(segment.memberEmails.length), 0) + (s.segmentScope === null ? pagesOf(s.contacts.length) : 0) + pagesOf(s.broadcasts.length) + s.broadcasts.filter((b) => b.status !== "sent" || b.html !== null || b.text !== null).length + pagesOf(s.templates.length) + s.templates.length + pagesOf(s.webhooks.length) + s.webhooks.length + pagesOf(s.suppressions.length) + pagesOf(s.apiKeys.length);
648
781
  const facets = (s.properties.length > 0 ? 1 : 0) + (s.topics.length > 0 ? 1 : 0);
649
782
  return { spent, enrichment: s.contacts.length * facets };
650
783
  }
@@ -807,18 +940,13 @@ function bannerLines(tier = "full") {
807
940
  function banner(tier = "full") {
808
941
  return bannerLines(tier);
809
942
  }
810
- async function selectPrompt(rl, {
811
- label,
812
- options,
813
- initial,
814
- rail = false
815
- }) {
943
+ async function selectPrompt(rl, { label, options, initial }) {
816
944
  const fallback = initial ?? options[0]?.value ?? "";
817
945
  if (!isInteractive()) {
818
946
  const answer = (await rl.question(`${label} [${fallback}]: `)).trim();
819
947
  return answer || fallback;
820
948
  }
821
- return selectTty(label, options, fallback, rail);
949
+ return selectTty(label, options, fallback);
822
950
  }
823
951
  var isEnter = (key) => key.name === "return" || key.name === "enter";
824
952
  function readKeys(onKey, erase, stdout = process.stdout) {
@@ -866,13 +994,7 @@ function optionRow(prefix, { label, hint }, selected, columns) {
866
994
  const tail = text.slice(label.length);
867
995
  return `${(selected ? bone : dim)(`${prefix}${head}`)}${tail ? dim(tail) : ""}`;
868
996
  }
869
- function railOptionRow({ label, hint }, selected, columns) {
870
- const text = truncate(`${label}${hint ? ` ${hint}` : ""}`, columns - 6);
871
- const head = text.slice(0, label.length);
872
- const tail = text.slice(label.length);
873
- return `${dim("\u2502")} ${selected ? info("\u25CF") : dim("\u25CB")} ${selected ? bone(head) : dim(head)}${dim(tail)}`;
874
- }
875
- async function selectTty(label, options, initial, rail = false) {
997
+ async function selectTty(label, options, initial) {
876
998
  const { stdout } = process;
877
999
  let index = Math.max(
878
1000
  0,
@@ -882,11 +1004,7 @@ async function selectTty(label, options, initial, rail = false) {
882
1004
  const render = (first) => {
883
1005
  if (!first) eraseRows(height);
884
1006
  const columns = terminalColumns();
885
- const lines = rail ? [
886
- `${info("\u25C6")} ${bold(label)}`,
887
- ...options.map((o, i) => railOptionRow(o, i === index, columns)),
888
- dim("\u2502")
889
- ] : [
1007
+ const lines = [
890
1008
  label,
891
1009
  ...options.map((o, i) => optionRow(i === index ? "\u276F " : " ", o, i === index, columns))
892
1010
  ];
@@ -912,13 +1030,8 @@ async function selectTty(label, options, initial, rail = false) {
912
1030
  () => eraseRows(height)
913
1031
  );
914
1032
  const chosen = options.find((o) => o.value === value)?.label ?? value;
915
- stdout.write(
916
- rail ? `${dim("\u25C7")} ${label}
917
- ${dim("\u2502")} ${dim(chosen)}
918
- ${dim("\u2502")}
919
- ` : `${answerLine(label, chosen)}
920
- `
921
- );
1033
+ stdout.write(`${answerLine(label, chosen)}
1034
+ `);
922
1035
  return value;
923
1036
  }
924
1037
  async function multiSelectPrompt(rl, { label, options }) {
@@ -989,7 +1102,7 @@ ${labels.map((l) => wrapIndent(l, { indent: " " })).join("\n")}
989
1102
  function maskSecret(secret) {
990
1103
  return secret.length >= 12 ? `${secret.slice(0, 3)}****\u2026${secret.slice(-4)}` : "****";
991
1104
  }
992
- async function secretPrompt(rl, { label, rail = false }) {
1105
+ async function secretPrompt(rl, { label }) {
993
1106
  const mode2 = secretPromptMode(process.stdin.isTTY === true, process.stdout.isTTY === true);
994
1107
  if (!mode2.masked) return (await rl.question(`${label}: `)).trim();
995
1108
  const stdout = mode2.toStderr ? process.stderr : process.stdout;
@@ -998,7 +1111,7 @@ async function secretPrompt(rl, { label, rail = false }) {
998
1111
  if (ahead !== void 0) {
999
1112
  secret = ahead.trim();
1000
1113
  } else {
1001
- stdout.write(rail ? `${dim("\u2502")} ` : `${label}: `);
1114
+ stdout.write(`${label}: `);
1002
1115
  let value = "";
1003
1116
  secret = await readKeys(
1004
1117
  (str, key) => {
@@ -1011,12 +1124,8 @@ async function secretPrompt(rl, { label, rail = false }) {
1011
1124
  stdout
1012
1125
  );
1013
1126
  }
1014
- stdout.write(
1015
- rail ? `${dim("\u2502")} ${dim(maskSecret(secret))}
1016
- ${dim("\u2502")}
1017
- ` : `${label}: ${dim(maskSecret(secret))}
1018
- `
1019
- );
1127
+ stdout.write(`${label}: ${dim(maskSecret(secret))}
1128
+ `);
1020
1129
  return secret;
1021
1130
  }
1022
1131
  async function confirmPrompt(rl, { label, initial = false }) {
@@ -1062,11 +1171,20 @@ var SYM = {
1062
1171
  skip: "\u2212"
1063
1172
  };
1064
1173
  var layoutWidth = () => Math.min(process.stdout.columns ?? 80, 100);
1174
+ var KEEP = "\u241F";
1065
1175
  function wrapIndent(text, {
1066
1176
  width = layoutWidth(),
1067
1177
  indent = "",
1068
- hanging = indent
1178
+ hanging = indent,
1179
+ keep = []
1069
1180
  } = {}) {
1181
+ if (keep.length > 0) {
1182
+ let guarded = text;
1183
+ for (const token of keep) {
1184
+ if (/\s/.test(token)) guarded = guarded.split(token).join(token.replace(/\s+/g, KEEP));
1185
+ }
1186
+ return wrapIndent(guarded, { width, indent, hanging }).split(KEEP).join(" ");
1187
+ }
1070
1188
  const lines = [];
1071
1189
  let line = indent;
1072
1190
  let empty = true;
@@ -1110,13 +1228,22 @@ var TARGET_WEBHOOK_EVENTS = [
1110
1228
  "contact.created",
1111
1229
  "contact.updated",
1112
1230
  "contact.deleted",
1231
+ "contact.topics.updated",
1113
1232
  "suppression.added",
1114
1233
  "suppression.removed",
1234
+ "domain.created",
1235
+ "domain.updated",
1236
+ "domain.deleted",
1237
+ "topic.created",
1238
+ "topic.updated",
1239
+ "topic.deleted",
1115
1240
  "inbox.created",
1116
1241
  "inbox.updated",
1117
1242
  "inbox.deleted",
1118
1243
  "inbox.thread.created",
1119
1244
  "inbox.thread.folder.updated",
1245
+ "inbox.thread.assigned",
1246
+ "inbox.thread.unassigned",
1120
1247
  "inbox.thread.labels.updated",
1121
1248
  "inbox.email.received",
1122
1249
  "inbox.email.sent",
@@ -1274,16 +1401,45 @@ function domainCreateInput(domain) {
1274
1401
  };
1275
1402
  return { input, tracking };
1276
1403
  }
1404
+ var TEMPLATE_VARIABLES_MAX = 50;
1405
+ var TEMPLATE_VARIABLE_KEY_RE = /^[A-Za-z0-9_]{1,50}$/;
1406
+ var TEMPLATE_REPLY_TO_MAX = 50;
1277
1407
  var listTokens = (tokens) => tokens.join(", ");
1278
1408
  function templateCreateInput(t) {
1279
1409
  const notes = [];
1280
- if (t.from) notes.push(`from ${t.from} is not stored on templates; pass it when sending`);
1281
- if (t.replyTo?.length)
1282
- notes.push(`reply_to ${t.replyTo.join(", ")} is not stored on templates; pass it when sending`);
1283
- if (t.variables.length > 0)
1410
+ const replyTo = t.replyTo ?? [];
1411
+ if (replyTo.length > TEMPLATE_REPLY_TO_MAX) {
1412
+ notes.push(
1413
+ `reply_to has ${replyTo.length} addresses; a template stores ${TEMPLATE_REPLY_TO_MAX}, the first ${TEMPLATE_REPLY_TO_MAX} were kept`
1414
+ );
1415
+ }
1416
+ const keyOk = (key) => TEMPLATE_VARIABLE_KEY_RE.test(key);
1417
+ const typeOk = (type) => type === "string" || type === "number";
1418
+ const badKey = t.variables.filter((v) => !keyOk(v.key));
1419
+ const badType = t.variables.filter((v) => keyOk(v.key) && !typeOk(v.type));
1420
+ const usable = t.variables.filter((v) => keyOk(v.key) && typeOk(v.type));
1421
+ if (badKey.length > 0) {
1284
1422
  notes.push(
1285
- `variables ${t.variables.map((v) => v.key).join(", ")} are not stored; merge fields resolve from contact properties`
1423
+ `variables ${badKey.map((v) => v.key).join(", ")} not stored: a key is 1\u201350 letters, digits or underscores`
1286
1424
  );
1425
+ }
1426
+ if (badType.length > 0) {
1427
+ notes.push(
1428
+ `variables ${badType.map((v) => `${v.key} (${v.type})`).join(", ")} not stored: BillionSend variables are strings or numbers`
1429
+ );
1430
+ }
1431
+ const variables = usable.slice(0, TEMPLATE_VARIABLES_MAX).map(
1432
+ (v) => ({
1433
+ key: v.key,
1434
+ type: v.type === "number" ? "number" : "string",
1435
+ ...v.fallbackValue === void 0 ? {} : { fallback_value: v.fallbackValue }
1436
+ })
1437
+ );
1438
+ if (usable.length > TEMPLATE_VARIABLES_MAX) {
1439
+ notes.push(
1440
+ `${usable.length} variables; a template stores ${TEMPLATE_VARIABLES_MAX}, the first ${TEMPLATE_VARIABLES_MAX} were kept`
1441
+ );
1442
+ }
1287
1443
  if (!t.html) return { input: null, notes, reason: "template has no html body" };
1288
1444
  const html = translateMergeTags(t.html);
1289
1445
  const subject = t.subject ? translateMergeTags(t.subject) : null;
@@ -1299,9 +1455,12 @@ function templateCreateInput(t) {
1299
1455
  const input = {
1300
1456
  name: t.name,
1301
1457
  ...t.alias ? { alias: t.alias } : {},
1458
+ ...t.from ? { from: t.from } : {},
1459
+ ...replyTo.length > 0 ? { reply_to: replyTo.slice(0, TEMPLATE_REPLY_TO_MAX) } : {},
1302
1460
  ...subject ? { subject: subject.html } : {},
1303
1461
  html: html.html,
1304
- ...text ? { text: text.html } : {}
1462
+ ...text ? { text: text.html } : {},
1463
+ ...variables.length > 0 ? { variables } : {}
1305
1464
  };
1306
1465
  return { input, notes, reason: null };
1307
1466
  }
@@ -1340,7 +1499,7 @@ function broadcastCreateInput(b, ids) {
1340
1499
  }
1341
1500
 
1342
1501
  // src/plan.ts
1343
- var PLAN_VERSION = 1;
1502
+ var PLAN_VERSION = 2;
1344
1503
  var BATCH_SIZE = 1e3;
1345
1504
  var RESOURCE_ORDER = [
1346
1505
  "properties",
@@ -1355,6 +1514,11 @@ var RESOURCE_ORDER = [
1355
1514
  "enrichment",
1356
1515
  "api-keys"
1357
1516
  ];
1517
+ function contactDiffers(source, target) {
1518
+ if (source.unsubscribed && !target.unsubscribed) return true;
1519
+ if (source.firstName !== null && source.firstName !== target.firstName) return true;
1520
+ return source.lastName !== null && source.lastName !== target.lastName;
1521
+ }
1358
1522
  function changedFields(pairs) {
1359
1523
  return pairs.filter(([, a, b]) => canonicalJson(a) !== canonicalJson(b)).map(([name]) => name);
1360
1524
  }
@@ -1372,8 +1536,19 @@ function buildPlan({
1372
1536
  const manual = (resource, key, detail) => add(resource, "manual", key, { detail });
1373
1537
  const has = (resource) => options.include.has(resource);
1374
1538
  if (has("properties")) {
1539
+ const kept = /* @__PURE__ */ new Map();
1375
1540
  for (const p of snapshot.properties) {
1376
- const existing = target.properties.find((t) => t.key === p.key);
1541
+ const lower = p.key.toLowerCase();
1542
+ const first = kept.get(lower);
1543
+ if (first !== void 0) {
1544
+ add("properties", "manual", p.key, {
1545
+ detail: `differs from \`${first}\` only in case; BillionSend property keys ignore case, so only \`${first}\` is created and no value of \`${p.key}\` is written (the contacts that have one are counted after the enrichment pass)`,
1546
+ payload: { collidesWith: first }
1547
+ });
1548
+ continue;
1549
+ }
1550
+ kept.set(lower, p.key);
1551
+ const existing = target.properties.find((t) => t.key.toLowerCase() === lower);
1377
1552
  if (!existing) {
1378
1553
  const payload = {
1379
1554
  key: p.key,
@@ -1387,6 +1562,12 @@ function buildPlan({
1387
1562
  p.key,
1388
1563
  `type differs: ${p.type} on Resend, ${existing.type} here \u2014 a property's type cannot change`
1389
1564
  );
1565
+ } else if (existing.key !== p.key) {
1566
+ add("properties", "unchanged", p.key, {
1567
+ targetId: existing.id,
1568
+ detail: `already here as \`${existing.key}\` (keys ignore case)`,
1569
+ payload: { targetKey: existing.key }
1570
+ });
1390
1571
  } else {
1391
1572
  add("properties", "unchanged", p.key, { targetId: existing.id });
1392
1573
  }
@@ -1537,14 +1718,30 @@ function buildPlan({
1537
1718
  alias: t.alias,
1538
1719
  subject: input.subject ?? null,
1539
1720
  html: input.html,
1540
- text: input.text ?? null
1721
+ text: input.text ?? null,
1722
+ ...input.from === void 0 ? {} : { from: input.from },
1723
+ ...input.reply_to === void 0 ? {} : { reply_to: input.reply_to },
1724
+ ...input.variables === void 0 ? {} : {
1725
+ variables: input.variables.map((v) => ({
1726
+ key: v.key,
1727
+ type: v.type,
1728
+ fallback_value: v.fallback_value ?? null
1729
+ }))
1730
+ }
1541
1731
  };
1542
1732
  const current = {
1543
1733
  name: existing.name,
1544
1734
  alias: existing.alias,
1545
1735
  subject: existing.subject ?? null,
1546
1736
  html: existing.html ?? null,
1547
- text: existing.text ?? null
1737
+ text: existing.text ?? null,
1738
+ from: existing.from ?? null,
1739
+ reply_to: existing.replyTo ?? null,
1740
+ variables: (existing.variables ?? []).map((v) => ({
1741
+ key: v.key,
1742
+ type: v.type,
1743
+ fallback_value: v.fallback_value
1744
+ }))
1548
1745
  };
1549
1746
  const changed = changedFields(
1550
1747
  Object.keys(desired).map((field) => [field, desired[field], current[field]])
@@ -1565,14 +1762,62 @@ function buildPlan({
1565
1762
  const contactCount = has("contacts") ? snapshot.contacts.length : 0;
1566
1763
  if (contactCount > 0) {
1567
1764
  const memberships = has("segments") ? snapshot.segments.reduce((n, s) => n + s.memberEmails.length, 0) : 0;
1568
- add("contacts", "create", "contacts", {
1569
- count: contactCount,
1570
- detail: `batch upsert, ${pluralize(memberships, "segment membership")}`
1571
- });
1765
+ const members = /* @__PURE__ */ new Set();
1766
+ if (has("segments")) {
1767
+ for (const segment of snapshot.segments) {
1768
+ for (const email of segment.memberEmails) members.add(email.toLowerCase());
1769
+ }
1770
+ }
1771
+ const fresh = [];
1772
+ const matched = { changed: 0, same: 0 };
1773
+ for (const c of snapshot.contacts) {
1774
+ const there = target.contacts.get(c.email.toLowerCase());
1775
+ if (there === void 0) fresh.push(c);
1776
+ else if (contactDiffers(c, there) || members.has(c.email.toLowerCase())) matched.changed += 1;
1777
+ else matched.same += 1;
1778
+ }
1779
+ const existing = matched.changed + matched.same;
1780
+ const batchDetail = `batch upsert, ${pluralize(memberships, "segment membership")}`;
1781
+ if (fresh.length > 0 || existing === 0) {
1782
+ add("contacts", "create", "contacts", {
1783
+ count: fresh.length,
1784
+ detail: existing === 0 ? batchDetail : `${formatNumber(fresh.length)} not on BillionSend yet; batch upsert, ${pluralize(memberships, "segment membership")} across all ${formatNumber(contactCount)} contacts`
1785
+ });
1786
+ }
1787
+ if (existing > 0) {
1788
+ const there = (n, what) => `${formatNumber(n)} already on BillionSend (matched by address); ${what}`;
1789
+ if (options.onConflict === "skip") {
1790
+ add("contacts", "skip", "existing contacts", {
1791
+ count: existing,
1792
+ detail: there(existing, "--on-conflict skip leaves them as they are")
1793
+ });
1794
+ } else if (options.onConflict === "error") {
1795
+ add("contacts", "update", "existing contacts", {
1796
+ count: existing,
1797
+ detail: there(existing, "--on-conflict error refuses them, and the run exits 3")
1798
+ });
1799
+ } else {
1800
+ if (matched.changed > 0) {
1801
+ add("contacts", "update", "existing contacts", {
1802
+ count: matched.changed,
1803
+ detail: there(
1804
+ matched.changed,
1805
+ "the upsert makes sure each is in its segment and writes a name or opt-out flag that differs"
1806
+ )
1807
+ });
1808
+ }
1809
+ if (matched.same > 0) {
1810
+ add("contacts", "unchanged", "existing contacts", {
1811
+ count: matched.same,
1812
+ detail: there(matched.same, "names and opt-out flag are the same, in no segment")
1813
+ });
1814
+ }
1815
+ }
1816
+ }
1572
1817
  const limit = target.usage.limits.contacts;
1573
- if (limit !== null && contactCount > limit) {
1818
+ if (limit !== null && fresh.length > limit) {
1574
1819
  warnings.push(
1575
- `${pluralize(contactCount, "contact")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${formatNumber(limit)}`
1820
+ `${pluralize(fresh.length, "contact")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${formatNumber(limit)}`
1576
1821
  );
1577
1822
  }
1578
1823
  }
@@ -1600,6 +1845,10 @@ function buildPlan({
1600
1845
  }
1601
1846
  if (has("broadcasts")) {
1602
1847
  for (const b of snapshot.broadcasts) {
1848
+ if (snapshot.segmentScope !== null && b.segmentId !== null && !snapshot.segmentScope.some((s) => s.id === b.segmentId)) {
1849
+ add("broadcasts", "skip", b.name, { detail: "sent to a segment outside --segment" });
1850
+ continue;
1851
+ }
1603
1852
  if (b.status === "sent" && !options.includeSent) {
1604
1853
  add("broadcasts", "skip", b.name, {
1605
1854
  detail: "already sent; --include-sent imports sent broadcasts as drafts"
@@ -1655,18 +1904,28 @@ function buildPlan({
1655
1904
  const rowWrites = items.filter(
1656
1905
  (i) => (i.action === "create" || i.action === "update") && i.count === void 0
1657
1906
  ).length;
1658
- const writes = rowWrites + batches(contactCount) + batches(suppressionCount) + (enrichment ? facets.length * batches(enrichCount) : 0);
1659
- const reads = enrichment ? estimateSourceRequests(snapshot).enrichment : 0;
1660
- const requests = options.sourceRequestsSpent + reads + writes;
1907
+ const writes = rowWrites + // The lookup of the source's addresses on the target, then the upsert itself.
1908
+ batches(contactCount) * 2 + batches(suppressionCount) + (enrichment ? facets.length * batches(enrichCount) : 0);
1909
+ const reads = options.sourceRequestsSpent + (enrichment ? estimateSourceRequests(snapshot).enrichment : 0);
1910
+ const requests = reads + writes;
1661
1911
  const seconds2 = Math.ceil(reads / options.rps + writes / 10);
1662
1912
  return {
1663
- version: 1,
1913
+ version: 2,
1664
1914
  createdAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1665
1915
  source: snapshot.provider,
1666
1916
  target: {
1667
1917
  baseUrl: options.baseUrl,
1668
1918
  plan: target.usage.plan
1669
1919
  },
1920
+ options: {
1921
+ only: options.only,
1922
+ skip: options.skip,
1923
+ segment: options.segment,
1924
+ onConflict: options.onConflict,
1925
+ includeSent: options.includeSent,
1926
+ freshWebhookSecrets: options.freshWebhookSecrets
1927
+ },
1928
+ scope: snapshot.segmentScope === null ? null : { segments: snapshot.segmentScope },
1670
1929
  rps: options.rps,
1671
1930
  items,
1672
1931
  estimate: { requests, seconds: seconds2 },
@@ -1750,10 +2009,11 @@ function groupPlanItems(items) {
1750
2009
  });
1751
2010
  }
1752
2011
  }
1753
- const count = own[0]?.count;
2012
+ const counted = own.filter((i) => i.count !== void 0);
2013
+ const count = counted.reduce((n, i) => n + (i.count ?? 0), 0);
1754
2014
  groups.push({
1755
2015
  resource,
1756
- label: count === void 0 ? resource : `${resource} (${formatNumber(count)})`,
2016
+ label: counted.length === 0 ? resource : `${resource} (${formatNumber(count)})`,
1757
2017
  rows
1758
2018
  });
1759
2019
  }
@@ -1777,12 +2037,14 @@ function renderRow(row) {
1777
2037
  return lines;
1778
2038
  }
1779
2039
  var foldedKeysLine = (keys) => `${keys.slice(0, 2).map(stripControl).join(", ")} \u2026 and ${formatNumber(keys.length - 2)} more`;
2040
+ var scopeLine = (scope) => `Scope (--segment): only ${scope.segments.map((s) => s.name).join(", ")} and ${scope.segments.length === 1 ? "its" : "their"} members; contacts and the enrichment pass cover those contacts alone.`;
1780
2041
  function renderPlan(plan2) {
1781
2042
  const c = plan2.counts;
1782
2043
  const n = (count) => count > 0 ? bold(formatNumber(count)) : "0";
1783
2044
  const lines = [
1784
2045
  dim(ACTIONS.map((a) => `${ACTION_STYLE[a][0]} ${a}`).join(" ")),
1785
2046
  "",
2047
+ ...plan2.scope === null ? [] : [wrapIndent(dim(scopeLine(plan2.scope)), { hanging: " " }), ""],
1786
2048
  ...groupPlanItems(plan2.items).flatMap((g) => [g.label, ...g.rows.flatMap(renderRow)]),
1787
2049
  "",
1788
2050
  wrapIndent(
@@ -1821,14 +2083,38 @@ function parsePlan(text) {
1821
2083
  `plan file version ${String(plan2.version)} is not supported (expected ${PLAN_VERSION})`
1822
2084
  );
1823
2085
  }
2086
+ if (plan2.options === null || typeof plan2.options !== "object") {
2087
+ throw new Error("plan file is not a migration plan");
2088
+ }
1824
2089
  return plan2;
1825
2090
  }
2091
+ function describePlanDiff(saved, current) {
2092
+ const label = (i) => `${i.resource}/${i.key}`;
2093
+ const byLabel = (plan2) => new Map(plan2.items.map((i) => [label(i), i]));
2094
+ const before = byLabel(saved);
2095
+ const after = byLabel(current);
2096
+ const lines = [];
2097
+ for (const [name, a] of before) {
2098
+ const b = after.get(name);
2099
+ if (b === void 0) lines.push(`${name}: in the file, not in the current plan`);
2100
+ else if (canonicalJson(a) !== canonicalJson(b)) {
2101
+ const count = a.count !== b.count ? `, ${formatNumber(a.count ?? 0)} \u2192 ${formatNumber(b.count ?? 0)}` : "";
2102
+ lines.push(
2103
+ `${name}: ${a.action} \u2192 ${b.action}${a.action === b.action && count === "" ? " (details differ)" : count}`
2104
+ );
2105
+ }
2106
+ }
2107
+ for (const name of after.keys()) {
2108
+ if (!before.has(name)) lines.push(`${name}: not in the file, in the current plan`);
2109
+ }
2110
+ return lines;
2111
+ }
1826
2112
 
1827
2113
  // src/config.ts
1828
2114
  import { parseArgs } from "node:util";
1829
2115
 
1830
2116
  // src/meta.ts
1831
- var VERSION = true ? "0.2.4" : "0.0.0-dev";
2117
+ var VERSION = true ? "0.3.0" : "0.0.0-dev";
1832
2118
  var REPO_URL = "https://github.com/billionsend/billionsend-cli";
1833
2119
  var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
1834
2120
  var CLOUD_API_URL = "https://api.billionsend.com";
@@ -1852,6 +2138,14 @@ var RESOURCES = [
1852
2138
  ];
1853
2139
 
1854
2140
  // src/config.ts
2141
+ var PLAN_OPTIONS = [
2142
+ "only",
2143
+ "skip",
2144
+ "segment",
2145
+ "on-conflict",
2146
+ "include-sent",
2147
+ "fresh-webhook-secrets"
2148
+ ];
1855
2149
  var ConfigError = class extends Error {
1856
2150
  constructor(message) {
1857
2151
  super(message);
@@ -1875,6 +2169,7 @@ var OPTIONS = {
1875
2169
  rps: { type: "string" },
1876
2170
  only: { type: "string" },
1877
2171
  skip: { type: "string" },
2172
+ segment: { type: "string", multiple: true },
1878
2173
  "on-conflict": { type: "string" },
1879
2174
  yes: { type: "boolean", short: "y" },
1880
2175
  "non-interactive": { type: "boolean" },
@@ -1904,18 +2199,25 @@ function resourceList(flag, value) {
1904
2199
  }
1905
2200
  return names;
1906
2201
  }
2202
+ function segmentList(value) {
2203
+ const names = (value ?? []).flatMap((entry) => entry.split(",")).map((name) => name.trim());
2204
+ if (names.includes("")) {
2205
+ throw new ConfigError("--segment needs a segment name or id (an empty value was given).");
2206
+ }
2207
+ return [...new Set(names)];
2208
+ }
1907
2209
  function keyInput(envName, env, stdinFlag, flagValue, flagName, warnings) {
1908
2210
  if (stdinFlag && flagValue !== void 0) {
1909
2211
  throw new ConfigError(`Pass either ${flagName} or ${flagName}-stdin, not both.`);
1910
2212
  }
1911
- const fromEnv = env[envName];
2213
+ const fromEnv = env[envName]?.trim();
1912
2214
  if (fromEnv !== void 0 && fromEnv !== "") return { source: "env", value: fromEnv };
1913
2215
  if (stdinFlag) return { source: "stdin", value: null };
1914
2216
  if (flagValue !== void 0) {
1915
2217
  warnings.push(
1916
2218
  `${flagName} is visible to other users in process lists; prefer ${envName} or ${flagName}-stdin.`
1917
2219
  );
1918
- return { source: "flag", value: flagValue };
2220
+ return { source: "flag", value: flagValue.trim() };
1919
2221
  }
1920
2222
  return { source: "prompt", value: null };
1921
2223
  }
@@ -2051,6 +2353,8 @@ function parseConfig(argv, env = process.env, stdinIsTTY = process.stdin.isTTY =
2051
2353
  rpsGiven,
2052
2354
  only: resourceList("--only", values.only),
2053
2355
  skip: resourceList("--skip", values.skip) ?? [],
2356
+ segment: segmentList(values.segment),
2357
+ given: new Set(PLAN_OPTIONS.filter((name) => values[name] !== void 0)),
2054
2358
  onConflict,
2055
2359
  yes: values.yes === true,
2056
2360
  nonInteractive,
@@ -2077,6 +2381,8 @@ function minimal(command) {
2077
2381
  rpsGiven: false,
2078
2382
  only: null,
2079
2383
  skip: [],
2384
+ segment: [],
2385
+ given: /* @__PURE__ */ new Set(),
2080
2386
  onConflict: "upsert",
2081
2387
  yes: false,
2082
2388
  nonInteractive: true,
@@ -2097,7 +2403,7 @@ function helpText() {
2097
2403
  Usage
2098
2404
  billionsend migrate --from resend connect, choose resources, plan, confirm, apply, summary
2099
2405
  billionsend migrate plan --from resend [--out plan.json] read-only; exit 0 nothing to do, 2 changes, 1 error
2100
- billionsend migrate apply [plan.json] [--yes] apply a saved plan, or plan and apply in one go
2406
+ billionsend migrate apply [plan.json] [--yes] apply a saved plan (with the options it was made with), or plan and apply in one go
2101
2407
  billionsend migrate status what the last run created and what is left
2102
2408
  billionsend migrate rollback [--yes] delete only what this tool created
2103
2409
  billionsend --help | --version
@@ -2114,12 +2420,14 @@ Options
2114
2420
  Go past ${MAX_RPS} only after Resend raised your limit (up to ${RPS_CEILING})
2115
2421
  --only <a,b> migrate only these resources
2116
2422
  --skip <a,b> skip these resources; \`enrichment\` is the per-contact properties/topics pass
2423
+ --segment <name|id> only these Resend segments: the segments, their members and the members' enrichment.
2424
+ Repeat the flag or separate with commas; an unknown name or id exits 1 and lists the segments
2117
2425
  --on-conflict <mode> contacts that already exist on the target: upsert (default), skip, error
2118
2426
  --include-sent import sent broadcasts as drafts (skipped by default)
2119
2427
  --fresh-webhook-secrets mint new webhook signing secrets instead of copying them (shown once in the report)
2120
2428
  --fresh ignore resume progress; keeps what earlier runs created so rollback still works
2121
2429
  --out <file> \`migrate plan\`: write the plan as JSON
2122
- --report <file> also write the Markdown report to this path
2430
+ --report <file> also write the Markdown report to this path (\`migrate plan\`: the plan as Markdown)
2123
2431
  -y, --yes skip confirmations
2124
2432
  --non-interactive never prompt; a missing input is exit 1 (automatic when stdin is not a terminal, and with --json)
2125
2433
  --json JSON on stdout, progress on stderr
@@ -2152,16 +2460,18 @@ ${TRADEMARK_NOTICE}
2152
2460
  }
2153
2461
 
2154
2462
  // src/billionsend.ts
2463
+ var LOOKUP_EMAIL = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
2155
2464
  var BATCH_MAX = 1e3;
2156
2465
  var PERMISSIVE = { headers: { "x-batch-validation": "permissive" } };
2157
2466
  function writeError(error) {
2158
- if (!(error instanceof ApiError) || error.status < 400 || error.status >= 500) return null;
2467
+ if (!(error instanceof ApiError)) return null;
2468
+ if (!error.sentOnce && (error.status < 400 || error.status >= 500)) return null;
2159
2469
  const body = error.body;
2160
2470
  return {
2161
2471
  ok: false,
2162
2472
  status: error.status,
2163
2473
  name: error.name,
2164
- message: typeof body?.message === "string" ? body.message : error.message
2474
+ message: !error.sentOnce && typeof body?.message === "string" ? body.message : error.message
2165
2475
  };
2166
2476
  }
2167
2477
  function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
@@ -2193,8 +2503,8 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2193
2503
  throw error;
2194
2504
  }
2195
2505
  }
2196
- const id = async (response) => ({
2197
- id: (await response).body.id
2506
+ const id = async (response, known = "") => ({
2507
+ id: (await response).body?.id ?? known
2198
2508
  });
2199
2509
  const withRecords = async (response) => {
2200
2510
  const { body } = await response;
@@ -2209,15 +2519,15 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2209
2519
  path2,
2210
2520
  paged ? { query: { limit: 100, after } } : {}
2211
2521
  );
2212
- guard(body.data, after);
2213
- rows.push(...body.data);
2214
- const last = body.data.at(-1);
2215
- if (!paged || !body.has_more || !last) {
2522
+ const data = pageItems(path2, body, after);
2523
+ guard(data, after);
2524
+ rows.push(...data);
2525
+ if (!paged || body.has_more !== true || data.length === 0) {
2216
2526
  return rows.sort(
2217
2527
  (a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)
2218
2528
  );
2219
2529
  }
2220
- after = last.id;
2530
+ after = nextCursor(path2, data, after);
2221
2531
  }
2222
2532
  }
2223
2533
  async function probe() {
@@ -2235,24 +2545,15 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2235
2545
  }
2236
2546
  throw error;
2237
2547
  }
2238
- const period = body.period ?? null;
2239
2548
  return {
2240
2549
  plan: body.plan,
2241
2550
  limits: {
2242
- emailsPerDay: body.limits.emails_per_day,
2243
- emailsPerMonth: body.limits.emails_per_month ?? null,
2244
- domains: body.limits.domains,
2245
- contacts: body.limits.contacts ?? null
2246
- },
2247
- today: { emailsSent: body.today.emails_sent },
2248
- period: period && {
2249
- emailsSent: period.emails_sent,
2250
- included: period.included,
2251
- overageEnabled: period.overage_enabled,
2252
- startsAt: period.starts_at,
2253
- endsAt: period.ends_at
2551
+ emailsPerDay: body.emails.daily.limit,
2552
+ emailsPerMonth: body.emails.monthly.limit,
2553
+ domains: body.domains.limit,
2554
+ contacts: body.contacts.limit
2254
2555
  },
2255
- appUrl: body.app_url
2556
+ overageEnabled: body.emails.monthly.overage_enabled
2256
2557
  };
2257
2558
  }
2258
2559
  async function readState() {
@@ -2278,7 +2579,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2278
2579
  ]);
2279
2580
  const domains = [];
2280
2581
  for (const { id: id2 } of domainRows.filter((row) => row.shared !== true)) {
2281
- const { body } = await api.get(`/domains/${id2}`);
2582
+ const { body } = await api.get(route`/domains/${id2}`);
2282
2583
  domains.push({
2283
2584
  id: body.id,
2284
2585
  name: body.name,
@@ -2289,18 +2590,26 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2289
2590
  }
2290
2591
  const templates = [];
2291
2592
  for (const { id: id2 } of templateRows) {
2292
- const { body } = await api.get(`/templates/${id2}`);
2593
+ const { body } = await api.get(route`/templates/${id2}`);
2293
2594
  templates.push({
2294
2595
  id: body.id,
2295
2596
  name: body.name,
2296
2597
  alias: body.alias,
2598
+ from: body.from,
2599
+ replyTo: body.reply_to,
2297
2600
  subject: body.subject,
2298
2601
  html: body.html,
2299
- text: body.text
2602
+ text: body.text,
2603
+ variables: body.variables.map(({ key, type, fallback_value }) => ({
2604
+ key,
2605
+ type,
2606
+ fallback_value
2607
+ }))
2300
2608
  });
2301
2609
  }
2302
2610
  return {
2303
2611
  usage,
2612
+ contacts: /* @__PURE__ */ new Map(),
2304
2613
  domains,
2305
2614
  hasContacts: firstContact.body.data.length > 0,
2306
2615
  properties: properties.map(({ id: id2, key, type }) => ({ id: id2, key, type })),
@@ -2328,6 +2637,51 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2328
2637
  )
2329
2638
  };
2330
2639
  }
2640
+ async function lookupContacts(emails, include) {
2641
+ const rows = [];
2642
+ const ask = async (slice) => {
2643
+ try {
2644
+ const { body } = await api.post(
2645
+ "/contacts/batch/get",
2646
+ {
2647
+ contacts: slice.map((email) => ({ email })),
2648
+ ...include === null ? {} : { include: [include] }
2649
+ },
2650
+ // It only reads.
2651
+ { idempotent: true }
2652
+ );
2653
+ rows.push(...body.data);
2654
+ } catch (error) {
2655
+ if (!(error instanceof ApiError) || error.status !== 422) throw error;
2656
+ if (slice.length === 1) return;
2657
+ const half = Math.ceil(slice.length / 2);
2658
+ await ask(slice.slice(0, half));
2659
+ await ask(slice.slice(half));
2660
+ }
2661
+ };
2662
+ const askable = [...new Set(emails.filter((email) => LOOKUP_EMAIL.test(email)))];
2663
+ for (const slice of chunk(askable, BATCH_MAX)) await ask(slice);
2664
+ return rows;
2665
+ }
2666
+ async function findContacts(emails) {
2667
+ const found = /* @__PURE__ */ new Map();
2668
+ for (const row of await lookupContacts(emails, null)) {
2669
+ found.set(row.email.toLowerCase(), {
2670
+ firstName: row.first_name,
2671
+ lastName: row.last_name,
2672
+ unsubscribed: row.unsubscribed
2673
+ });
2674
+ }
2675
+ return found;
2676
+ }
2677
+ async function explicitOptOuts(emails) {
2678
+ const out = /* @__PURE__ */ new Map();
2679
+ for (const row of await lookupContacts(emails, "topics")) {
2680
+ const topics = (row.topics ?? []).filter((t) => t.explicit && t.subscription === "opt_out");
2681
+ if (topics.length > 0) out.set(row.email.toLowerCase(), new Set(topics.map((t) => t.id)));
2682
+ }
2683
+ return out;
2684
+ }
2331
2685
  async function batchContacts(items, {
2332
2686
  onConflict,
2333
2687
  permissive = true
@@ -2367,12 +2721,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2367
2721
  return out;
2368
2722
  }
2369
2723
  async function suppressionsBatch(path2, key, values, extra = {}) {
2370
- const out = { ids: [], errors: [] };
2724
+ const out = { ids: [], notRemoved: [], errors: [] };
2371
2725
  const chunks = chunk(values, BATCH_MAX);
2372
2726
  for (const [n, slice] of chunks.entries()) {
2373
- const result = await write(async () => ({
2374
- data: (await api.post(path2, { [key]: slice, ...extra })).body.data
2375
- }));
2727
+ const result = await write(async () => {
2728
+ const { body } = await api.post(path2, { [key]: slice, ...extra });
2729
+ return { data: body.data, notRemoved: body.not_removed ?? [] };
2730
+ });
2376
2731
  if (!result.ok) {
2377
2732
  log.warn(`${path2} ${n + 1}/${chunks.length} failed: ${result.message}`);
2378
2733
  for (const i of slice.keys()) {
@@ -2385,6 +2740,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2385
2740
  continue;
2386
2741
  }
2387
2742
  out.ids.push(...result.data.map((r) => r.id));
2743
+ out.notRemoved.push(...result.notRemoved);
2388
2744
  }
2389
2745
  return out;
2390
2746
  }
@@ -2404,7 +2760,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2404
2760
  })
2405
2761
  )
2406
2762
  ),
2407
- deleteProperty: (propertyId) => write(() => id(api.delete(`/contact-properties/${propertyId}`))),
2763
+ deleteProperty: (propertyId) => write(() => id(api.delete(route`/contact-properties/${propertyId}`), propertyId)),
2408
2764
  createTopic: (input) => write(
2409
2765
  () => id(
2410
2766
  api.post("/topics", {
@@ -2417,14 +2773,14 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2417
2773
  ),
2418
2774
  updateTopic: (topicId, input) => write(
2419
2775
  () => id(
2420
- api.patch(`/topics/${topicId}`, {
2776
+ api.patch(route`/topics/${topicId}`, {
2421
2777
  name: input.name,
2422
2778
  description: input.description ?? void 0,
2423
2779
  visibility: input.visibility
2424
2780
  })
2425
2781
  )
2426
2782
  ),
2427
- deleteTopic: (topicId) => write(() => id(api.delete(`/topics/${topicId}`))),
2783
+ deleteTopic: (topicId) => write(() => id(api.delete(route`/topics/${topicId}`), topicId)),
2428
2784
  createSegment: (input) => write(
2429
2785
  () => id(
2430
2786
  api.post("/segments", {
@@ -2436,13 +2792,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2436
2792
  /** `filter: null` clears the saved filter (manual membership only). */
2437
2793
  updateSegment: (segmentId, input) => write(
2438
2794
  () => id(
2439
- api.patch(`/segments/${segmentId}`, {
2795
+ api.patch(route`/segments/${segmentId}`, {
2440
2796
  name: input.name,
2441
2797
  ...input.filter !== void 0 ? { filter: input.filter } : {}
2442
2798
  })
2443
2799
  )
2444
2800
  ),
2445
- deleteSegment: (segmentId) => write(() => id(api.delete(`/segments/${segmentId}`))),
2801
+ deleteSegment: (segmentId) => write(() => id(api.delete(route`/segments/${segmentId}`), segmentId)),
2446
2802
  createDomain: (input) => write(
2447
2803
  () => withRecords(
2448
2804
  api.post("/domains", {
@@ -2453,14 +2809,14 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2453
2809
  ),
2454
2810
  updateDomainTracking: (domainId, input) => write(
2455
2811
  () => withRecords(
2456
- api.patch(`/domains/${domainId}`, {
2812
+ api.patch(route`/domains/${domainId}`, {
2457
2813
  open_tracking: input.openTracking,
2458
2814
  click_tracking: input.clickTracking,
2459
2815
  tracking_subdomain: input.trackingSubdomain
2460
2816
  })
2461
2817
  )
2462
2818
  ),
2463
- deleteDomain: (domainId) => write(() => id(api.delete(`/domains/${domainId}`))),
2819
+ deleteDomain: (domainId) => write(() => id(api.delete(route`/domains/${domainId}`), domainId)),
2464
2820
  createWebhook: (input) => write(async () => {
2465
2821
  const { body } = await api.post("/webhooks", {
2466
2822
  endpoint: input.endpoint,
@@ -2469,22 +2825,25 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2469
2825
  });
2470
2826
  return { id: body.id, signingSecret: body.signing_secret };
2471
2827
  }),
2472
- updateWebhook: (webhookId, input) => write(() => id(api.patch(`/webhooks/${webhookId}`, input))),
2473
- deleteWebhook: (webhookId) => write(() => id(api.delete(`/webhooks/${webhookId}`))),
2828
+ updateWebhook: (webhookId, input) => write(() => id(api.patch(route`/webhooks/${webhookId}`, input))),
2829
+ deleteWebhook: (webhookId) => write(() => id(api.delete(route`/webhooks/${webhookId}`), webhookId)),
2474
2830
  createTemplate: (input) => write(
2475
2831
  () => id(
2476
2832
  api.post("/templates", {
2477
2833
  name: input.name,
2478
2834
  alias: input.alias ?? void 0,
2835
+ from: input.from ?? void 0,
2836
+ reply_to: input.reply_to ?? void 0,
2479
2837
  subject: input.subject ?? void 0,
2480
2838
  html: input.html,
2481
- text: input.text ?? void 0
2839
+ text: input.text ?? void 0,
2840
+ variables: input.variables ?? void 0
2482
2841
  })
2483
2842
  )
2484
2843
  ),
2485
2844
  /** `idOrAlias`: the API resolves either. */
2486
- updateTemplate: (idOrAlias, input) => write(() => id(api.patch(`/templates/${idOrAlias}`, input))),
2487
- deleteTemplate: (idOrAlias) => write(() => id(api.delete(`/templates/${idOrAlias}`))),
2845
+ updateTemplate: (idOrAlias, input) => write(() => id(api.patch(route`/templates/${idOrAlias}`, input))),
2846
+ deleteTemplate: (idOrAlias) => write(() => id(api.delete(route`/templates/${idOrAlias}`), idOrAlias)),
2488
2847
  /** Always a draft; sending stays a deliberate act in the dashboard. */
2489
2848
  createBroadcast: (input) => write(
2490
2849
  () => id(
@@ -2501,10 +2860,12 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2501
2860
  })
2502
2861
  )
2503
2862
  ),
2504
- deleteBroadcast: (broadcastId) => write(() => id(api.delete(`/broadcasts/${broadcastId}`))),
2863
+ deleteBroadcast: (broadcastId) => write(() => id(api.delete(route`/broadcasts/${broadcastId}`), broadcastId)),
2864
+ findContacts,
2865
+ explicitOptOuts,
2505
2866
  batchContacts,
2506
2867
  deleteContact: (contactId) => write(async () => ({
2507
- id: (await api.delete(`/contacts/${contactId}`)).body.contact
2868
+ id: (await api.delete(route`/contacts/${contactId}`)).body?.contact ?? contactId
2508
2869
  })),
2509
2870
  /** Prefer inline `segments` on batch items; this is one request per contact. */
2510
2871
  addContactsToSegment: async (segmentId, contactIds) => {
@@ -2512,7 +2873,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2512
2873
  const errors = [];
2513
2874
  for (const contactId of contactIds) {
2514
2875
  const result = await write(
2515
- () => id(api.post(`/contacts/${contactId}/segments/${segmentId}`))
2876
+ () => id(api.post(route`/contacts/${contactId}/segments/${segmentId}`))
2516
2877
  );
2517
2878
  if (result.ok) added.push(result.id);
2518
2879
  else errors.push({ id: contactId, message: result.message });
@@ -2748,10 +3109,10 @@ function buildOffer(usage, snapshot, domains, sourceLabel) {
2748
3109
  domains: usage.limits.domains,
2749
3110
  contacts: usage.limits.contacts
2750
3111
  };
2751
- const url = usage.appUrl === null ? CLOUD_BILLING_URL : `${stripTrailingSlashes(usage.appUrl)}/settings/billing`;
3112
+ const url = CLOUD_BILLING_URL;
2752
3113
  const short = [];
2753
3114
  const over = sent !== null && current.perMonth !== null && sent > current.perMonth;
2754
- const volumeShort = over && !usage.period?.overageEnabled;
3115
+ const volumeShort = over && !usage.overageEnabled;
2755
3116
  if (volumeShort) short.push(`${current.label} allows ${perMonthText(current.perMonth)}`);
2756
3117
  if (current.domains !== null && domains > current.domains) {
2757
3118
  short.push(
@@ -2807,16 +3168,22 @@ function buildReport({
2807
3168
  dns.push({ domain: domain.name, records: domain.records });
2808
3169
  }
2809
3170
  const apiKeys = plan2.items.filter((i) => i.resource === "api-keys").map((i) => i.key);
2810
- const manual = plan2.manual.filter(
2811
- (m) => !m.title.startsWith("api-keys/") && !m.detail.startsWith("add DNS records")
2812
- );
3171
+ const manual = [
3172
+ ...plan2.manual.filter(
3173
+ (m) => !m.title.startsWith("api-keys/") && !m.detail.startsWith("add DNS records")
3174
+ ),
3175
+ ...outcome.enrichment.droppedProperties.filter((d) => d.contacts > 0).map((d) => ({
3176
+ title: `properties/${d.key}`,
3177
+ detail: `${pluralize(d.contacts, "contact")} had a value for it that was not written: BillionSend property keys ignore case and \`${d.collidesWith}\` is the same key`
3178
+ }))
3179
+ ];
2813
3180
  const failures = outcome.state.failures;
2814
3181
  const retryable = failures.filter((f) => retryableStatus(f.statusCode)).length;
2815
3182
  const refused = failures.length - retryable;
2816
3183
  const done = Object.entries(outcome.counts).filter(([, c]) => c !== void 0 && c.failed === 0 && c.created + c.updated + c.unchanged > 0).map(([resource]) => resource);
2817
3184
  const left = [
2818
3185
  ...dns.map((d) => `add DNS records for ${d.domain}`),
2819
- `set ${plan2.source.toUpperCase()}_BASE_URL=${baseUrl} in your app`,
3186
+ baseUrlStep(plan2.source, baseUrl),
2820
3187
  ...apiKeys.length > 0 ? [`create API keys: ${apiKeys.join(", ")}`] : [],
2821
3188
  ...outcome.ids.length > 0 ? [`replace ${sourceLabel} topic and segment ids in your code (id map below)`] : [],
2822
3189
  ...manual.length > 0 ? [`review ${pluralize(manual.length, "manual note")}`] : [],
@@ -2830,6 +3197,7 @@ function buildReport({
2830
3197
  source: plan2.source,
2831
3198
  sourceLabel,
2832
3199
  target: { baseUrl, plan: usage.plan },
3200
+ scope: plan2.scope,
2833
3201
  counts: outcome.counts,
2834
3202
  enrichment: outcome.enrichment,
2835
3203
  sourceReadOnly: true,
@@ -2844,6 +3212,11 @@ function buildReport({
2844
3212
  trademark: TRADEMARK_NOTICE
2845
3213
  };
2846
3214
  }
3215
+ function baseUrlStep(source, baseUrl) {
3216
+ const name = `${source.toUpperCase()}_BASE_URL`;
3217
+ const step = `set ${name}=${CLOUD_API_URL} in your app, so ${capitalize(source)} SDK calls go to BillionSend`;
3218
+ return baseUrl === CLOUD_API_URL ? step : `${step} (this run used ${baseUrl}; put that address there only if your app reaches BillionSend through it)`;
3219
+ }
2847
3220
  function dnsCards(records) {
2848
3221
  return records.flatMap((r, i) => [
2849
3222
  ...i > 0 ? [""] : [],
@@ -2857,7 +3230,10 @@ function cutoverReadyLines(source, baseUrl, domainRecords) {
2857
3230
  heading("Cutover ready"),
2858
3231
  "Everything but the per-contact enrichment is on BillionSend: transactional sending can move now.",
2859
3232
  "Topic opt-outs and properties land in the enrichment passes below; hold topic sends and broadcasts until they finish.",
2860
- ` ${dim("[")} ${dim("]")} set ${source.toUpperCase()}_BASE_URL=${baseUrl} in your app`
3233
+ wrapIndent(`${dim("[")} ${dim("]")} ${baseUrlStep(source, baseUrl)}`, {
3234
+ indent: " ",
3235
+ hanging: " "
3236
+ })
2861
3237
  ];
2862
3238
  for (const [domain, records] of Object.entries(domainRecords)) {
2863
3239
  lines.push("", `DNS records for ${domain}:`, ...dnsCards(records));
@@ -2904,10 +3280,13 @@ function countRows(counts, enrichment) {
2904
3280
  if (resource === "enrichment" && enrichment !== void 0) {
2905
3281
  rows.push({ label: "with topic subscriptions", value: enrichment.withTopics });
2906
3282
  rows.push({ label: "with properties", value: enrichment.withProperties });
3283
+ const dropped = (enrichment.droppedProperties ?? []).reduce((n, d) => n + d.contacts, 0);
3284
+ if (dropped > 0) rows.push({ label: "property values not written", value: dropped });
2907
3285
  }
2908
3286
  } else {
2909
3287
  if (c.created > 0) rows.push({ label: `${resource} created`, value: c.created });
2910
3288
  if (c.updated > 0) rows.push({ label: `${resource} updated`, value: c.updated });
3289
+ if (c.matched > 0) rows.push({ label: `${resource} matched existing`, value: c.matched });
2911
3290
  if (c.unchanged > 0) rows.push({ label: `${resource} unchanged`, value: c.unchanged });
2912
3291
  }
2913
3292
  if (c.failed > 0) rows.push({ label: `${resource} failed`, value: c.failed });
@@ -2928,6 +3307,8 @@ ${heading("Done")}
2928
3307
  await countUp(countRows(report.counts, report.enrichment), { stream: out });
2929
3308
  out.write(`
2930
3309
  ${dim(`${report.sourceLabel} was only read; nothing there was changed.`)}
3310
+ `);
3311
+ if (report.scope !== null) out.write(`${dim(wrapIndent(scopeLine(report.scope)))}
2931
3312
  `);
2932
3313
  if (report.freshWebhookSecrets.length > 0) {
2933
3314
  out.write("\nWebhook signing secrets, shown once (they are not saved anywhere):\n");
@@ -2965,7 +3346,10 @@ Id map (${report.sourceLabel} \u2192 BillionSend; full pairs in migrate-report.m
2965
3346
  }
2966
3347
  if (report.failures.length > 0) {
2967
3348
  out.write("\nFailed:\n");
2968
- for (const f of report.failures) line(`${err(SYM.err)} ${f.resource}/${f.key} \u2014 ${f.message}`);
3349
+ for (const f of report.failures) {
3350
+ const head = `${err(SYM.err)} ${f.resource}/${f.key}`;
3351
+ line(`${head} \u2014 ${f.message}`, { ...ITEM, keep: [head, f.key] });
3352
+ }
2969
3353
  }
2970
3354
  out.write(`
2971
3355
  ${dim(wrapIndent(SYNC_HINT(report.source)))}
@@ -2984,12 +3368,15 @@ function renderReportMd(raw) {
2984
3368
  "",
2985
3369
  "## Numbers",
2986
3370
  "",
2987
- "| Resource | Created | Updated | Unchanged | Skipped | Manual | Failed |",
2988
- "| --- | ---: | ---: | ---: | ---: | ---: | ---: |",
3371
+ "| Resource | Created | Updated | Matched existing | Unchanged | Skipped | Manual | Failed |",
3372
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
2989
3373
  ...orderedCounts(report.counts).map(
2990
- ([resource, c]) => `| ${resource} | ${c.created} | ${c.updated} | ${c.unchanged} | ${c.skipped} | ${c.manual} | ${c.failed} |`
3374
+ ([resource, c]) => `| ${resource} | ${c.created} | ${c.updated} | ${c.matched} | ${c.unchanged} | ${c.skipped} | ${c.manual} | ${c.failed} |`
2991
3375
  ),
2992
3376
  "",
3377
+ "Matched existing: contacts the batch endpoint found already in your account. It does not say whether a matched contact changed, so these are not counted as updated or unchanged.",
3378
+ "",
3379
+ ...report.scope === null ? [] : [scopeLine(report.scope), ""],
2993
3380
  `${report.sourceLabel} was only read; nothing there was changed.`,
2994
3381
  "",
2995
3382
  "## Checklist",
@@ -3050,6 +3437,47 @@ function writeReport(paths, report, extraMd) {
3050
3437
  writePrivate(paths.reportMd, md);
3051
3438
  if (extraMd !== null) writePrivate(extraMd, md);
3052
3439
  }
3440
+ function renderPlanMd(raw, sourceLabel) {
3441
+ const plan2 = stripControlDeep(raw);
3442
+ const rows = RESOURCES.flatMap((resource) => {
3443
+ const own = plan2.items.filter((i) => i.resource === resource);
3444
+ if (own.length === 0) return [];
3445
+ const n = (action) => own.filter((i) => i.action === action).reduce((sum, i) => sum + (i.count ?? 1), 0);
3446
+ return [
3447
+ `| ${resource} | ${n("create")} | ${n("update")} | ${n("unchanged")} | ${n("manual")} | ${n("skip")} |`
3448
+ ];
3449
+ });
3450
+ const lines = [
3451
+ `# Migration plan \u2014 ${sourceLabel} \u2192 BillionSend`,
3452
+ "",
3453
+ `Planned ${plan2.createdAt} \xB7 target ${plan2.target.baseUrl}${plan2.target.plan === null ? "" : ` \xB7 plan ${capitalize(plan2.target.plan)}`}`,
3454
+ "",
3455
+ "Nothing has been written: this is what `billionsend migrate apply` would do.",
3456
+ "",
3457
+ ...plan2.scope === null ? [] : [scopeLine(plan2.scope), ""],
3458
+ "## Plan",
3459
+ "",
3460
+ "| Resource | Create | Update | Unchanged | Manual | Skipped |",
3461
+ "| --- | ---: | ---: | ---: | ---: | ---: |",
3462
+ ...rows,
3463
+ "",
3464
+ `About ${formatNumber(plan2.estimate.requests)} requests (${formatDuration(plan2.estimate.seconds)} at ${plan2.rps} req/s).`
3465
+ ];
3466
+ if (plan2.warnings.length > 0) {
3467
+ lines.push("", "## Warnings", "", ...plan2.warnings.map((w) => `- ${w}`));
3468
+ }
3469
+ if (plan2.manual.length > 0) {
3470
+ lines.push(
3471
+ "",
3472
+ "## Manual notes",
3473
+ "",
3474
+ ...plan2.manual.map(({ title, detail }) => `- ${title} \u2014 ${detail}`)
3475
+ );
3476
+ }
3477
+ lines.push("", "---", "", TRADEMARK_NOTICE, "");
3478
+ return lines.join("\n");
3479
+ }
3480
+ var writePlanReport = (path2, plan2, sourceLabel) => writePrivate(path2, renderPlanMd(plan2, sourceLabel));
3053
3481
 
3054
3482
  // src/apply.ts
3055
3483
  var ROLLBACK_ORDER = [
@@ -3084,6 +3512,7 @@ var ENRICHMENT_LABEL = {
3084
3512
  var emptyCounts = () => ({
3085
3513
  created: 0,
3086
3514
  updated: 0,
3515
+ matched: 0,
3087
3516
  unchanged: 0,
3088
3517
  skipped: 0,
3089
3518
  manual: 0,
@@ -3093,15 +3522,20 @@ var finish = (step, failed, total) => {
3093
3522
  if (failed > 0) step.fail(`${formatNumber(failed)} of ${formatNumber(total)} failed`);
3094
3523
  else step.done();
3095
3524
  };
3096
- function enrichmentItem(c, pass1Status, maps, facets = ["properties", "topics"]) {
3525
+ function enrichmentItem(c, mode2, maps, facets = ["properties", "topics"]) {
3097
3526
  const properties = facets.includes("properties") ? Object.fromEntries(
3098
- Object.entries(c.properties ?? {}).filter(([key]) => maps.propertyKeys.has(key))
3527
+ Object.entries(c.properties ?? {}).flatMap(([key, value]) => {
3528
+ const targetKey = maps.propertyKeys.get(key);
3529
+ return targetKey === void 0 ? [] : [[targetKey, value]];
3530
+ })
3099
3531
  ) : {};
3100
3532
  const topics = facets.includes("topics") ? (c.topics ?? []).flatMap((t) => {
3101
3533
  const id = maps.topicBySource.get(t.id);
3102
- if (id === void 0 || pass1Status === "updated" && t.subscription !== "opt_out")
3103
- return [];
3104
- return [{ id, subscription: t.subscription }];
3534
+ if (id === void 0) return [];
3535
+ if (t.subscription === "opt_out" || mode2 === "created") {
3536
+ return [{ id, subscription: t.subscription }];
3537
+ }
3538
+ return mode2 === "pending" && maps.optOutByDefault?.has(t.id) === true ? [{ id, subscription: t.subscription }] : [];
3105
3539
  }) : [];
3106
3540
  return {
3107
3541
  email: c.email,
@@ -3124,10 +3558,12 @@ async function applyPlan(input) {
3124
3558
  const failed = (resource, key, { message, statusCode }) => {
3125
3559
  state.failures.push({ resource, key, message, statusCode });
3126
3560
  tally(resource).failed += 1;
3127
- log.warn(`${resource}/${key}: ${message}`);
3128
3561
  };
3562
+ const pending = new Set(state.progress.pendingEnrichment ?? []);
3129
3563
  const save = () => {
3130
3564
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3565
+ if (pending.size > 0) state.progress.pendingEnrichment = [...pending];
3566
+ else delete state.progress.pendingEnrichment;
3131
3567
  input.save(state);
3132
3568
  };
3133
3569
  const outcome = {
@@ -3136,13 +3572,14 @@ async function applyPlan(input) {
3136
3572
  freshSecrets: [],
3137
3573
  domainRecords: {},
3138
3574
  ids: [],
3139
- enrichment: { withProperties: 0, withTopics: 0 }
3575
+ enrichment: { withProperties: 0, withTopics: 0, droppedProperties: [] }
3140
3576
  };
3141
3577
  const topicByName = /* @__PURE__ */ new Map();
3142
3578
  const topicBySource = /* @__PURE__ */ new Map();
3143
3579
  const segmentByName = /* @__PURE__ */ new Map();
3144
3580
  const segmentBySource = /* @__PURE__ */ new Map();
3145
- const propertyKeys = /* @__PURE__ */ new Set();
3581
+ const propertyKeys = /* @__PURE__ */ new Map();
3582
+ const collidingKeys = /* @__PURE__ */ new Map();
3146
3583
  const registerTopic = (name, id) => {
3147
3584
  topicByName.set(name, id);
3148
3585
  const sourceTopic = snapshot.topics.find((t) => t.name === name);
@@ -3154,13 +3591,22 @@ async function applyPlan(input) {
3154
3591
  if (sourceSegment) segmentBySource.set(sourceSegment.id, id);
3155
3592
  };
3156
3593
  for (const item of plan2.items) {
3157
- if (item.action === "unchanged") tally(item.resource).unchanged += 1;
3158
- else if (item.action === "manual") tally(item.resource).manual += 1;
3159
- else if (item.action === "skip") tally(item.resource).skipped += 1;
3594
+ if (item.resource !== "contacts") {
3595
+ if (item.action === "unchanged") tally(item.resource).unchanged += 1;
3596
+ else if (item.action === "manual") tally(item.resource).manual += 1;
3597
+ else if (item.action === "skip") tally(item.resource).skipped += 1;
3598
+ }
3599
+ if (item.resource === "properties" && item.action === "manual") {
3600
+ const collidesWith = item.payload?.collidesWith;
3601
+ if (collidesWith !== void 0) collidingKeys.set(item.key, collidesWith);
3602
+ }
3160
3603
  if (item.targetId === void 0) continue;
3161
3604
  if (item.resource === "topics") registerTopic(item.key, item.targetId);
3162
3605
  else if (item.resource === "segments") registerSegment(item.key, item.targetId);
3163
- else if (item.resource === "properties") propertyKeys.add(item.key);
3606
+ else if (item.resource === "properties") {
3607
+ const targetKey = item.payload?.targetKey;
3608
+ propertyKeys.set(item.key, targetKey ?? item.key);
3609
+ }
3164
3610
  }
3165
3611
  async function runRows(resource, run) {
3166
3612
  const items = plan2.items.filter(
@@ -3191,7 +3637,7 @@ async function applyPlan(input) {
3191
3637
  type: p.type,
3192
3638
  fallbackValue: p.fallback_value
3193
3639
  });
3194
- if (result.ok) propertyKeys.add(p.key);
3640
+ if (result.ok) propertyKeys.set(p.key, p.key);
3195
3641
  return result;
3196
3642
  });
3197
3643
  await runRows("topics", async (item) => {
@@ -3298,8 +3744,11 @@ async function applyPlan(input) {
3298
3744
  const contact = slice[row.index];
3299
3745
  if (contact === void 0) continue;
3300
3746
  pass1.set(contact.email.toLowerCase(), row.status);
3301
- if (row.status === "created") created("contacts", row.id);
3302
- else tally("contacts")[row.status] += 1;
3747
+ if (row.status === "created") {
3748
+ created("contacts", row.id);
3749
+ pending.add(contact.email.toLowerCase());
3750
+ } else if (row.status === "updated") tally("contacts").matched += 1;
3751
+ else tally("contacts").skipped += 1;
3303
3752
  }
3304
3753
  for (const error of out.errors) {
3305
3754
  const contact = slice[error.index];
@@ -3366,6 +3815,10 @@ async function applyPlan(input) {
3366
3815
  const enrichedIds = /* @__PURE__ */ new Set();
3367
3816
  const failedIds = /* @__PURE__ */ new Set();
3368
3817
  const total = snapshot.contacts.length;
3818
+ const droppedContacts = /* @__PURE__ */ new Map();
3819
+ const optOutByDefault = new Set(
3820
+ snapshot.topics.filter((t) => t.defaultSubscription === "opt_out").map((t) => t.id)
3821
+ );
3369
3822
  const passes = [
3370
3823
  {
3371
3824
  facet: "topics",
@@ -3391,6 +3844,21 @@ async function applyPlan(input) {
3391
3844
  for (const line of lines) progress.line(line);
3392
3845
  progress.line("");
3393
3846
  }
3847
+ const keepTargetOptOuts = async (entries) => {
3848
+ const asking = entries.filter(
3849
+ (e) => !e.created && e.item.topics?.some((t) => t.subscription === "opt_in") === true
3850
+ );
3851
+ if (asking.length === 0) return;
3852
+ const optedOut = await target.explicitOptOuts(asking.map((e) => e.item.email));
3853
+ for (const e of asking) {
3854
+ const kept = optedOut.get(e.item.email.toLowerCase());
3855
+ if (kept !== void 0) {
3856
+ e.item.topics = e.item.topics?.filter(
3857
+ (t) => t.subscription !== "opt_in" || !kept.has(t.id)
3858
+ );
3859
+ }
3860
+ }
3861
+ };
3394
3862
  for (const pass of passes) {
3395
3863
  if (!pass.wanted) {
3396
3864
  progress.line(dim(`${ENRICHMENT_LABEL[pass.facet]}: skipped, ${pass.skipped}`));
@@ -3408,6 +3876,7 @@ async function applyPlan(input) {
3408
3876
  let withValues = 0;
3409
3877
  let buffer = [];
3410
3878
  const flush = async () => {
3879
+ if (pass.facet === "topics") await keepTargetOptOuts(buffer);
3411
3880
  const sendable = buffer.filter(
3412
3881
  (b) => b.item.properties !== void 0 || b.item.topics !== void 0
3413
3882
  );
@@ -3444,10 +3913,17 @@ async function applyPlan(input) {
3444
3913
  const status2 = pass1.get(contact.email.toLowerCase());
3445
3914
  if (status2 === "failed" || status2 === "skipped") return;
3446
3915
  processed += 1;
3916
+ if (pass.facet === "properties") {
3917
+ for (const [key, value] of Object.entries(contact.properties ?? {})) {
3918
+ if (collidingKeys.has(key) && String(value) !== "") {
3919
+ droppedContacts.set(key, (droppedContacts.get(key) ?? 0) + 1);
3920
+ }
3921
+ }
3922
+ }
3447
3923
  const item = enrichmentItem(
3448
3924
  contact,
3449
- status2 === "created" || !synced ? "created" : "updated",
3450
- { propertyKeys, topicBySource },
3925
+ status2 === "created" || !synced ? "created" : pending.has(contact.email.toLowerCase()) ? "pending" : "updated",
3926
+ { propertyKeys, topicBySource, optOutByDefault },
3451
3927
  [pass.facet]
3452
3928
  );
3453
3929
  if (status2 === void 0) {
@@ -3455,7 +3931,7 @@ async function applyPlan(input) {
3455
3931
  item.first_name = contact.firstName ?? void 0;
3456
3932
  item.last_name = contact.lastName ?? void 0;
3457
3933
  }
3458
- buffer.push({ id: contact.id, item });
3934
+ buffer.push({ id: contact.id, item, created: status2 === "created" });
3459
3935
  if (buffer.length >= BATCH_MAX) await flush();
3460
3936
  }
3461
3937
  });
@@ -3475,6 +3951,21 @@ async function applyPlan(input) {
3475
3951
  step.done(`${formatNumber(total)} \xB7 ${formatNumber(withValues)} with ${noun}`);
3476
3952
  }
3477
3953
  }
3954
+ outcome.enrichment.droppedProperties = [...collidingKeys].map(([key, collidesWith]) => ({
3955
+ key,
3956
+ collidesWith,
3957
+ contacts: droppedContacts.get(key) ?? 0
3958
+ }));
3959
+ if (snapshot.topics.length === 0) pending.clear();
3960
+ else if (passes.some((p) => p.facet === "topics" && p.wanted)) {
3961
+ for (const c of snapshot.contacts) {
3962
+ const email = c.email.toLowerCase();
3963
+ const status2 = pass1.get(email);
3964
+ if (status2 === "failed" || status2 === "skipped") continue;
3965
+ if (failedIds.has(c.id)) pending.add(email);
3966
+ else pending.delete(email);
3967
+ }
3968
+ }
3478
3969
  state.progress.enrichmentCompleted = true;
3479
3970
  if (tally("enrichment").failed === 0) {
3480
3971
  delete state.progress.enrichmentDone;
@@ -3519,10 +4010,7 @@ async function resolveKey(ctx, input, { label, envName, flag }) {
3519
4010
  if (line === "") throw new Error(`No ${label} arrived on stdin (${flag}-stdin).`);
3520
4011
  return line;
3521
4012
  }
3522
- if (ctx.config.nonInteractive) {
3523
- throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3524
- }
3525
- const key = await secretPrompt(ctx.rl, { label: `${label} (full access)` });
4013
+ const key = (await secretPrompt(ctx.rl, { label: `${label} (full access)` })).trim();
3526
4014
  if (key === "") throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3527
4015
  return key;
3528
4016
  }
@@ -3603,10 +4091,10 @@ async function connectTarget(ctx) {
3603
4091
  });
3604
4092
  const target = createBillionSendTarget(http, ctx.log, baseUrl);
3605
4093
  const usage = await target.probe();
3606
- ctx.out.write(
3607
- `${ok(SYM.ok)} BillionSend Cloud ${dim("\xB7")} plan ${capitalize(usage.plan ?? "unknown")}
3608
- `
3609
- );
4094
+ const where = baseUrl === CLOUD_API_URL ? "" : ` (${baseUrl})`;
4095
+ const plan2 = usage.plan === null ? "no plan limits" : `plan ${capitalize(usage.plan)}`;
4096
+ ctx.out.write(`${ok(SYM.ok)} BillionSend${where} ${dim("\xB7")} ${plan2}
4097
+ `);
3610
4098
  return { target, usage, baseUrl };
3611
4099
  }
3612
4100
  function bridgeProgress(progress) {
@@ -3707,7 +4195,7 @@ async function resolveDomainLimit(ctx, plan2, target) {
3707
4195
  );
3708
4196
  return capDomainCreates(plan2, allowed);
3709
4197
  }
3710
- async function prepare(ctx, providerId) {
4198
+ async function prepare(ctx, providerId, { pick = true } = {}) {
3711
4199
  const { config, out } = ctx;
3712
4200
  const label = providers[providerId].label;
3713
4201
  printHeader(
@@ -3724,18 +4212,30 @@ ${heading(`Reading ${label}`)}
3724
4212
  const snapshot = await source.readShallow({
3725
4213
  include,
3726
4214
  includeSent: config.includeSent,
4215
+ segments: config.segment,
3727
4216
  onProgress: bridgeProgress(ctx.progress)
3728
4217
  });
3729
4218
  snapshot.metrics = await source.readMetrics();
3730
4219
  const step = ctx.progress.step("BillionSend");
3731
- const targetState = await target.readState();
4220
+ let targetState = await target.readState();
4221
+ if (include.has("contacts") && snapshot.contacts.length > 0) {
4222
+ targetState = {
4223
+ ...targetState,
4224
+ contacts: await target.findContacts(snapshot.contacts.map((c) => c.email))
4225
+ };
4226
+ }
3732
4227
  step.done("current state read");
3733
- const chosen = config.nonInteractive || config.only !== null || config.skip.length > 0 ? include : await pickResources(ctx, snapshot, include);
4228
+ const chosen = !pick || config.nonInteractive || config.only !== null || config.skip.length > 0 ? include : await pickResources(ctx, snapshot, include);
3734
4229
  let plan2 = buildPlan({
3735
4230
  snapshot,
3736
4231
  target: targetState,
3737
4232
  options: {
3738
4233
  include: chosen,
4234
+ // What the picker left selected is recorded as `only`, so a plan file reproduces it.
4235
+ only: chosen.size === include.size ? config.only : RESOURCES.filter((r) => chosen.has(r)),
4236
+ skip: config.skip,
4237
+ segment: config.segment,
4238
+ onConflict: config.onConflict,
3739
4239
  includeSent: config.includeSent,
3740
4240
  freshWebhookSecrets: config.freshWebhookSecrets,
3741
4241
  rps: config.rps,
@@ -3786,15 +4286,17 @@ function idleOutcome(plan2, state) {
3786
4286
  const c = counts[item.resource] ?? {
3787
4287
  created: 0,
3788
4288
  updated: 0,
4289
+ matched: 0,
3789
4290
  unchanged: 0,
3790
4291
  skipped: 0,
3791
4292
  manual: 0,
3792
4293
  failed: 0
3793
4294
  };
3794
4295
  counts[item.resource] = c;
3795
- if (item.action === "unchanged") c.unchanged += 1;
3796
- else if (item.action === "manual") c.manual += 1;
3797
- else if (item.action === "skip") c.skipped += 1;
4296
+ const rows = item.count ?? 1;
4297
+ if (item.action === "unchanged") c.unchanged += rows;
4298
+ else if (item.action === "manual") c.manual += rows;
4299
+ else if (item.action === "skip") c.skipped += rows;
3798
4300
  }
3799
4301
  return {
3800
4302
  state,
@@ -3802,7 +4304,7 @@ function idleOutcome(plan2, state) {
3802
4304
  freshSecrets: [],
3803
4305
  domainRecords: {},
3804
4306
  ids: [],
3805
- enrichment: { withProperties: 0, withTopics: 0 }
4307
+ enrichment: { withProperties: 0, withTopics: 0, droppedProperties: [] }
3806
4308
  };
3807
4309
  }
3808
4310
  var runReport = (prepared, outcome) => buildReport({
@@ -3882,6 +4384,51 @@ async function migrate(ctx) {
3882
4384
 
3883
4385
  // src/commands/apply.ts
3884
4386
  var MAX_PLAN_AGE_MS = 36e5;
4387
+ var DIFF_SHOWN = 5;
4388
+ var sorted = (list) => [...list].sort();
4389
+ var show = (list) => list === null ? "(not set)" : list.length === 0 ? "(none)" : list.join(",");
4390
+ function followPlanOptions(config, file, recorded) {
4391
+ const conflicts = [];
4392
+ const conflict = (flag, given, wanted) => {
4393
+ conflicts.push(`${flag}: the command line has ${given}, the file has ${wanted}`);
4394
+ };
4395
+ const g = config.given;
4396
+ if (g.has("only") && canonicalJson(config.only && sorted(config.only)) !== canonicalJson(recorded.only && sorted(recorded.only))) {
4397
+ conflict("--only", show(config.only), show(recorded.only));
4398
+ }
4399
+ if (g.has("skip") && canonicalJson(sorted(config.skip)) !== canonicalJson(sorted(recorded.skip))) {
4400
+ conflict("--skip", show(config.skip), show(recorded.skip));
4401
+ }
4402
+ if (g.has("segment") && canonicalJson(sorted(config.segment)) !== canonicalJson(sorted(recorded.segment))) {
4403
+ conflict("--segment", show(config.segment), show(recorded.segment));
4404
+ }
4405
+ if (g.has("on-conflict") && config.onConflict !== recorded.onConflict) {
4406
+ conflict("--on-conflict", config.onConflict, recorded.onConflict);
4407
+ }
4408
+ if (g.has("include-sent") && config.includeSent !== recorded.includeSent) {
4409
+ conflict("--include-sent", String(config.includeSent), String(recorded.includeSent));
4410
+ }
4411
+ if (g.has("fresh-webhook-secrets") && config.freshWebhookSecrets !== recorded.freshWebhookSecrets) {
4412
+ conflict(
4413
+ "--fresh-webhook-secrets",
4414
+ String(config.freshWebhookSecrets),
4415
+ String(recorded.freshWebhookSecrets)
4416
+ );
4417
+ }
4418
+ if (conflicts.length > 0) {
4419
+ throw new Error(
4420
+ `${file} was made with other options than this command line asks for:
4421
+ ${conflicts.join("\n ")}
4422
+ Applying a file follows the options it was made with: leave these flags out, or run \`migrate plan --out ${file}\` again with the new ones.`
4423
+ );
4424
+ }
4425
+ config.only = recorded.only;
4426
+ config.skip = [...recorded.skip];
4427
+ config.segment = [...recorded.segment];
4428
+ config.onConflict = recorded.onConflict;
4429
+ config.includeSent = recorded.includeSent;
4430
+ config.freshWebhookSecrets = recorded.freshWebhookSecrets;
4431
+ }
3885
4432
  async function apply(ctx) {
3886
4433
  const { config, out } = ctx;
3887
4434
  if (config.planFile === null) return migrate(ctx);
@@ -3895,6 +4442,7 @@ async function apply(ctx) {
3895
4442
  );
3896
4443
  }
3897
4444
  const saved = parsePlan(text);
4445
+ followPlanOptions(config, config.planFile, saved.options);
3898
4446
  const ageMs = Date.now() - Date.parse(saved.createdAt);
3899
4447
  const stale = !(ageMs < MAX_PLAN_AGE_MS);
3900
4448
  if (stale && config.nonInteractive) {
@@ -3908,7 +4456,7 @@ async function apply(ctx) {
3908
4456
  `
3909
4457
  );
3910
4458
  }
3911
- const prepared = await prepare(ctx, config.from ?? saved.source);
4459
+ const prepared = await prepare(ctx, config.from ?? saved.source, { pick: false });
3912
4460
  if (saved.target.baseUrl !== prepared.baseUrl) {
3913
4461
  throw new Error(
3914
4462
  `${config.planFile} was made for ${saved.target.baseUrl}; connected to ${prepared.baseUrl}.`
@@ -3916,11 +4464,18 @@ async function apply(ctx) {
3916
4464
  }
3917
4465
  const reasons = [];
3918
4466
  if (stale) reasons.push(`is ${formatDuration(ageMs / 1e3)} old`);
3919
- if (planHash(saved) !== planHash(prepared.plan)) reasons.push("differs from the plan just built");
4467
+ const same = planHash(saved) === planHash(prepared.plan);
4468
+ const differing = same ? [] : describePlanDiff(saved, prepared.plan);
4469
+ if (!same) reasons.push("differs from the plan just built");
3920
4470
  if (reasons.length > 0) {
3921
- const notice = `${config.planFile} ${reasons.join(" and ")}; the plan above is current.`;
4471
+ const cause = differing.length === 0 ? "" : ` The options are the file's own, so the source or your BillionSend account changed since the file was made: ${differing.slice(0, DIFF_SHOWN).join(
4472
+ "; "
4473
+ )}${differing.length > DIFF_SHOWN ? `; \u2026 and ${differing.length - DIFF_SHOWN} more` : ""}.`;
4474
+ const notice = `${config.planFile} ${reasons.join(" and ")}; the plan above is current.${cause}`;
3922
4475
  if (config.nonInteractive) {
3923
- throw new Error(`${notice} Re-run \`migrate plan --out\`, or apply without a file.`);
4476
+ throw new Error(
4477
+ `${notice} Run \`migrate plan --out ${config.planFile}\` again to refresh the file, or apply without a file.`
4478
+ );
3924
4479
  }
3925
4480
  out.write(`${notice}
3926
4481
  `);
@@ -3940,6 +4495,11 @@ async function plan(ctx) {
3940
4495
  if (ctx.config.out !== null) {
3941
4496
  writeFileSync2(ctx.config.out, json);
3942
4497
  ctx.out.write(`Plan written to ${ctx.config.out}
4498
+ `);
4499
+ }
4500
+ if (ctx.config.report !== null) {
4501
+ writePlanReport(ctx.config.report, prepared.plan, prepared.provider.label);
4502
+ ctx.out.write(`Plan report written to ${ctx.config.report}
3943
4503
  `);
3944
4504
  }
3945
4505
  if (ctx.config.json) ctx.stdout.write(json);
@@ -3966,8 +4526,9 @@ async function rollback(ctx) {
3966
4526
  const state = readJson(paths.state);
3967
4527
  const pending = ROLLBACK_ORDER.filter((r) => (state?.created[r]?.length ?? 0) > 0);
3968
4528
  const deleted = {};
4529
+ const kept = {};
3969
4530
  const emitJson = (failures) => {
3970
- if (config.json) ctx.stdout.write(`${JSON.stringify({ deleted, failures })}
4531
+ if (config.json) ctx.stdout.write(`${JSON.stringify({ deleted, kept, failures })}
3971
4532
  `);
3972
4533
  };
3973
4534
  if (state === null || pending.length === 0) {
@@ -4008,7 +4569,6 @@ async function rollback(ctx) {
4008
4569
 
4009
4570
  `);
4010
4571
  if (!config.yes) {
4011
- if (config.nonInteractive) throw new Error("Rollback needs --yes in non-interactive mode.");
4012
4572
  if (!await confirmPrompt(ctx.rl, { label: "Delete these from your BillionSend instance?" })) {
4013
4573
  out.write("Nothing deleted.\n");
4014
4574
  emitJson([]);
@@ -4033,15 +4593,17 @@ async function rollback(ctx) {
4033
4593
  };
4034
4594
  const step = ctx.progress.step(RESOURCE_LABEL[resource]);
4035
4595
  let failed = 0;
4596
+ let permanent = 0;
4036
4597
  if (resource === "suppressions") {
4037
- const { ids: removed, errors } = await target.removeSuppressions(ids);
4038
- const kept = /* @__PURE__ */ new Set();
4598
+ const { ids: removed, notRemoved, errors } = await target.removeSuppressions(ids);
4599
+ permanent = notRemoved.length;
4600
+ const heldBack = /* @__PURE__ */ new Set();
4039
4601
  for (const error of errors) {
4040
- kept.add(error.index);
4602
+ heldBack.add(error.index);
4041
4603
  failed += 1;
4042
4604
  state.failures.push({ resource, key: ids[error.index] ?? "?", message: error.message });
4043
4605
  }
4044
- for (const [i, id] of ids.entries()) if (!kept.has(i)) remaining.delete(id);
4606
+ for (const [i, id] of ids.entries()) if (!heldBack.has(i)) remaining.delete(id);
4045
4607
  step.update(removed.length, ids.length);
4046
4608
  } else {
4047
4609
  const del = DELETE[resource];
@@ -4057,7 +4619,8 @@ async function rollback(ctx) {
4057
4619
  if ((n + 1) % SAVE_EVERY === 0) save();
4058
4620
  }
4059
4621
  }
4060
- deleted[resource] = ids.length - remaining.size;
4622
+ deleted[resource] = ids.length - remaining.size - permanent;
4623
+ if (permanent > 0) kept[resource] = permanent;
4061
4624
  if (resource === "contacts") state.progress = {};
4062
4625
  save();
4063
4626
  if (failed > 0) step.fail(`${pluralize(failed, "delete")} failed`);
@@ -4077,6 +4640,12 @@ ${pluralize(state.failures.length, "delete")} failed; the ids stay in ${paths.st
4077
4640
  return 3;
4078
4641
  }
4079
4642
  out.write("\nRolled back. Rows this tool only updated were left as they are.\n");
4643
+ if (kept.suppressions !== void 0) {
4644
+ out.write(
4645
+ `${pluralize(kept.suppressions, "suppression")} stay: a bounce or complaint entry is permanent and BillionSend does not remove it.
4646
+ `
4647
+ );
4648
+ }
4080
4649
  return 0;
4081
4650
  }
4082
4651
 
@@ -4117,14 +4686,20 @@ async function status(ctx) {
4117
4686
  bold(formatNumber(ids.length))
4118
4687
  ])
4119
4688
  );
4120
- const { contactsCursor, enrichmentDone } = state.progress;
4689
+ const { contactsCursor, enrichmentDone, pendingEnrichment } = state.progress;
4121
4690
  out.write("\nProgress\n");
4122
4691
  block([
4123
4692
  [" Contacts", contactsCursor ? `resumes after ${contactsCursor}` : "complete"],
4124
4693
  [
4125
4694
  " Enriched",
4126
4695
  enrichmentDone ? `resumes with ${formatNumber(enrichmentDone.length)} done` : "complete"
4127
- ]
4696
+ ],
4697
+ ...pendingEnrichment && pendingEnrichment.length > 0 ? [
4698
+ [
4699
+ " Waiting",
4700
+ `${pluralize(pendingEnrichment.length, "contact")} not enriched yet`
4701
+ ]
4702
+ ] : []
4128
4703
  ]);
4129
4704
  if (state.failures.length > 0) {
4130
4705
  out.write(`