@billionsend/cli 0.0.0-stage → 0.2.5

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/index.js +4251 -0
  4. package/package.json +46 -4
package/dist/index.js ADDED
@@ -0,0 +1,4251 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { realpathSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ // src/commands/apply.ts
8
+ import { readFileSync as readFileSync2 } from "node:fs";
9
+
10
+ // src/plan.ts
11
+ import { createHash } from "node:crypto";
12
+
13
+ // src/utils.ts
14
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
+ var numberFormat = new Intl.NumberFormat("en-US");
16
+ var formatNumber = (n) => numberFormat.format(n);
17
+ function chunk(items, size) {
18
+ const out = [];
19
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
20
+ return out;
21
+ }
22
+ function formatDuration(seconds2) {
23
+ if (seconds2 < 60) return `${Math.max(1, Math.round(seconds2))} s`;
24
+ return `about ${Math.round(seconds2 / 60)} min`;
25
+ }
26
+ function canonicalJson(value) {
27
+ return JSON.stringify(
28
+ value,
29
+ (_key, v) => v !== null && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(
30
+ Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)
31
+ ) : v
32
+ );
33
+ }
34
+ function senderDomain(from) {
35
+ const address = /<([^<>]+)>\s*$/.exec(from)?.[1] ?? from;
36
+ const at = address.lastIndexOf("@");
37
+ if (at === -1) return null;
38
+ const domain = address.slice(at + 1).trim().toLowerCase();
39
+ return domain === "" ? null : domain;
40
+ }
41
+ var capitalize = (s) => `${s[0]?.toUpperCase() ?? ""}${s.slice(1)}`;
42
+ var pluralize = (n, noun, plural = `${noun}s`) => `${formatNumber(n)} ${n === 1 ? noun : plural}`;
43
+ var retryableStatus = (status2) => status2 !== 400 && status2 !== 409 && status2 !== 422;
44
+ var CONTROL_RE = (
45
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the control bytes are the target
46
+ /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[\x00-\x08\x0b-\x1f\x7f]/g
47
+ );
48
+ var stripControl = (s) => s.replace(CONTROL_RE, "");
49
+ var stripControlDeep = (value) => JSON.parse(
50
+ JSON.stringify(value, (_key, v) => typeof v === "string" ? stripControl(v) : v)
51
+ );
52
+ function truncate(s, width) {
53
+ const chars = [...s];
54
+ if (chars.length <= width) return s;
55
+ return `${chars.slice(0, Math.max(0, width - 1)).join("")}\u2026`;
56
+ }
57
+ async function forEachConcurrent(items, limit, fn) {
58
+ let next = 0;
59
+ let stopped = false;
60
+ const worker = async () => {
61
+ while (!stopped && next < items.length) {
62
+ const item = items[next++];
63
+ try {
64
+ await fn(item);
65
+ } catch (error) {
66
+ stopped = true;
67
+ throw error;
68
+ }
69
+ }
70
+ };
71
+ const workers = Math.max(1, Math.min(limit, items.length));
72
+ await Promise.all(Array.from({ length: workers }, worker));
73
+ }
74
+ function stripTrailingSlashes(s) {
75
+ let end = s.length;
76
+ while (end > 0 && s[end - 1] === "/") end--;
77
+ return s.slice(0, end);
78
+ }
79
+
80
+ // src/http.ts
81
+ var AuthError = class extends Error {
82
+ status;
83
+ constructor(side, status2) {
84
+ super(`${side} rejected the API key (${status2})`);
85
+ this.name = "AuthError";
86
+ this.status = status2;
87
+ }
88
+ };
89
+ var ApiError = class extends Error {
90
+ status;
91
+ body;
92
+ constructor(status2, name, message, body = null) {
93
+ super(message);
94
+ this.name = name;
95
+ this.status = status2;
96
+ this.body = body;
97
+ }
98
+ };
99
+ var PaginationError = class extends Error {
100
+ constructor(path2, after, reason) {
101
+ super(`${path2}: ${reason} (cursor after=${after ?? "none"})`);
102
+ this.name = "PaginationError";
103
+ }
104
+ };
105
+ var MAX_PAGES = 1e5;
106
+ function pageItems(path2, body, after) {
107
+ const data = typeof body === "object" && body !== null ? body.data : void 0;
108
+ if (!Array.isArray(data))
109
+ throw new PaginationError(path2, after, "the list page has no data array");
110
+ return data;
111
+ }
112
+ function nextCursor(path2, page, after) {
113
+ const last = page.at(-1);
114
+ const id = typeof last === "object" && last !== null ? last.id : void 0;
115
+ if (typeof id !== "string" || id === "") {
116
+ throw new PaginationError(
117
+ path2,
118
+ after,
119
+ "the last item of the list page has no id to continue from"
120
+ );
121
+ }
122
+ return id;
123
+ }
124
+ function cursorGuard(path2, maxPages = MAX_PAGES) {
125
+ const seen = /* @__PURE__ */ new Set();
126
+ let pages = 0;
127
+ return (page, after) => {
128
+ pages += 1;
129
+ if (pages > maxPages) {
130
+ throw new PaginationError(path2, after, `more than ${maxPages} pages walked`);
131
+ }
132
+ if (after !== void 0 && page.length > 0 && page[page.length - 1]?.id === after) {
133
+ throw new PaginationError(
134
+ path2,
135
+ after,
136
+ "the page ends at the cursor it was asked to start after; the API ignored `after`"
137
+ );
138
+ }
139
+ if (page.length > 0 && page.every((row) => seen.has(row.id))) {
140
+ throw new PaginationError(path2, after, "the page holds only ids already listed");
141
+ }
142
+ for (const row of page) seen.add(row.id);
143
+ };
144
+ }
145
+ var MAX_WAIT_MS = 12e4;
146
+ var REMAINING_RESERVE = 2;
147
+ var clampWait = (ms) => Math.min(MAX_WAIT_MS, Math.max(0, ms));
148
+ function headerNumber(headers, name) {
149
+ const raw = headers.get(name);
150
+ if (raw === null) return null;
151
+ const value = Number(raw);
152
+ return Number.isFinite(value) ? value : null;
153
+ }
154
+ function retryAfterMs(headers, now = Date.now()) {
155
+ const retryAfter = headers.get("retry-after");
156
+ if (retryAfter !== null) {
157
+ const seconds2 = Number(retryAfter);
158
+ if (Number.isFinite(seconds2)) return clampWait(seconds2 * 1e3);
159
+ const date = Date.parse(retryAfter);
160
+ if (Number.isFinite(date)) return clampWait(date - now);
161
+ }
162
+ const reset = headerNumber(headers, "ratelimit-reset");
163
+ return reset === null ? null : clampWait(reset * 1e3);
164
+ }
165
+ async function parseBody(response) {
166
+ const text = await response.text();
167
+ if (text === "") return null;
168
+ try {
169
+ return JSON.parse(text);
170
+ } catch {
171
+ return text;
172
+ }
173
+ }
174
+ var seconds = (ms) => `${Math.round(ms / 100) / 10}s`;
175
+ function networkReason(error) {
176
+ const message = error instanceof Error ? error.message : String(error);
177
+ const cause = error.cause;
178
+ if (cause === null || cause === void 0) return message;
179
+ let detail = null;
180
+ if (typeof cause.code === "string") {
181
+ const where = typeof cause.address === "string" ? ` ${cause.address}${cause.port === void 0 ? "" : `:${String(cause.port)}`}` : "";
182
+ detail = `${cause.code}${where}`;
183
+ } else if (typeof cause.message === "string") {
184
+ detail = cause.message;
185
+ }
186
+ return detail === null ? message : `${message} (${detail})`;
187
+ }
188
+ var isPlanLimit = (body) => body?.name === "plan_limit_reached";
189
+ function createHttp(options) {
190
+ const {
191
+ name,
192
+ log,
193
+ maxAttempts = 5,
194
+ rateLimitAttempts = 8,
195
+ timeoutMs = 3e4,
196
+ fetch: fetchFn = globalThis.fetch
197
+ } = options;
198
+ const base = stripTrailingSlashes(options.baseUrl);
199
+ let targetRps = options.rps;
200
+ let rps = targetRps;
201
+ let rampedAt = 0;
202
+ let nextSlot = 0;
203
+ let holdUntil = 0;
204
+ let rateLimit = null;
205
+ const currentRps = (now) => {
206
+ if (rps < targetRps) {
207
+ const steps = Math.floor((now - rampedAt) / 1e3);
208
+ if (steps > 0) {
209
+ rps = Math.min(targetRps, rps + steps);
210
+ rampedAt += steps * 1e3;
211
+ }
212
+ }
213
+ return rps;
214
+ };
215
+ const acquire = async () => {
216
+ const now = Date.now();
217
+ const at = Math.max(now, nextSlot, holdUntil);
218
+ nextSlot = at + 1e3 / currentRps(now);
219
+ if (at > now) await sleep(at - now);
220
+ };
221
+ const readRateHeaders = (headers) => {
222
+ const limit = headerNumber(headers, "ratelimit-limit");
223
+ if (limit !== null && limit > 0) rateLimit = limit;
224
+ const remaining = headerNumber(headers, "ratelimit-remaining");
225
+ const reset = headerNumber(headers, "ratelimit-reset");
226
+ if (remaining !== null && reset !== null && remaining <= REMAINING_RESERVE) {
227
+ holdUntil = Math.max(holdUntil, Date.now() + clampWait(reset * 1e3));
228
+ }
229
+ };
230
+ async function request(method, path2, body, { query, headers: extraHeaders } = {}) {
231
+ if (options.readOnly === true && method !== "GET") {
232
+ throw new Error(`${name} is read-only for this tool; refusing ${method} ${path2}`);
233
+ }
234
+ const url = new URL(base + (path2.startsWith("/") ? path2 : `/${path2}`));
235
+ for (const [key, value] of Object.entries(query ?? {})) {
236
+ if (value !== void 0) url.searchParams.set(key, String(value));
237
+ }
238
+ const label = `${method} ${url.pathname}${url.search}`;
239
+ const headers = {
240
+ authorization: `Bearer ${options.token}`,
241
+ "user-agent": options.userAgent,
242
+ accept: "application/json",
243
+ ...body === void 0 ? {} : { "content-type": "application/json" },
244
+ ...extraHeaders
245
+ };
246
+ const init = {
247
+ method,
248
+ headers,
249
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
250
+ };
251
+ let rateLimited = 0;
252
+ let failures = 0;
253
+ for (; ; ) {
254
+ await acquire();
255
+ const started = Date.now();
256
+ let response;
257
+ try {
258
+ response = await fetchFn(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
259
+ } catch (error) {
260
+ const reason = networkReason(error);
261
+ failures += 1;
262
+ if (failures >= maxAttempts) {
263
+ const hint = name === "BillionSend" ? "check --to-url / BILLIONSEND_BASE_URL" : `check your network to ${url.host}`;
264
+ throw new ApiError(
265
+ 0,
266
+ "network_error",
267
+ `${name}: ${label} failed ${failures} times \u2014 ${reason}; ${hint}`
268
+ );
269
+ }
270
+ const wait = 1e3 * 2 ** (failures - 1);
271
+ log.warn(`retry ${failures + 1}/${maxAttempts} in ${seconds(wait)} \u2014 ${name} ${reason}`);
272
+ await sleep(wait);
273
+ continue;
274
+ }
275
+ log.debug(`${label} \u2192 ${response.status} (${Date.now() - started} ms)`);
276
+ readRateHeaders(response.headers);
277
+ const parsed = await parseBody(response);
278
+ const { status: status2 } = response;
279
+ if (status2 === 401 || status2 === 403 && !isPlanLimit(parsed)) {
280
+ throw new AuthError(name, status2);
281
+ }
282
+ if (status2 === 429) {
283
+ rateLimited += 1;
284
+ if (rateLimited >= rateLimitAttempts) {
285
+ throw new ApiError(
286
+ 429,
287
+ "rate_limit_exceeded",
288
+ `${name} kept rate limiting ${label} after ${rateLimited} attempts`,
289
+ parsed
290
+ );
291
+ }
292
+ const wait = retryAfterMs(response.headers) ?? 2e3;
293
+ rps = Math.max(1, rps / 2);
294
+ rampedAt = Date.now();
295
+ log.warn(
296
+ `retry ${rateLimited + 1}/${rateLimitAttempts} in ${seconds(wait)} \u2014 ${name} 429 \xB7 slowing to ${Math.round(rps * 10) / 10} req/s`
297
+ );
298
+ await sleep(wait);
299
+ continue;
300
+ }
301
+ if (status2 >= 500) {
302
+ failures += 1;
303
+ if (failures >= maxAttempts) {
304
+ throw new ApiError(
305
+ status2,
306
+ "server_error",
307
+ `${name} answered ${status2} to ${label} ${failures} times`,
308
+ parsed
309
+ );
310
+ }
311
+ const wait = 1e3 * 2 ** (failures - 1);
312
+ log.warn(`retry ${failures + 1}/${maxAttempts} in ${seconds(wait)} \u2014 ${name} ${status2}`);
313
+ await sleep(wait);
314
+ continue;
315
+ }
316
+ if (status2 >= 400) {
317
+ const error = parsed ?? {};
318
+ throw new ApiError(
319
+ status2,
320
+ typeof error.name === "string" ? error.name : "http_error",
321
+ typeof error.message === "string" ? `${name}: ${error.message} (${status2} on ${label})` : `${name} answered ${status2} to ${label}`,
322
+ parsed
323
+ );
324
+ }
325
+ return { status: status2, body: parsed, headers: response.headers };
326
+ }
327
+ }
328
+ return {
329
+ get rateLimit() {
330
+ return rateLimit;
331
+ },
332
+ setRps(next) {
333
+ rps = rps >= targetRps ? next : Math.min(rps, next);
334
+ targetRps = next;
335
+ },
336
+ get: (path2, options2) => request("GET", path2, void 0, options2),
337
+ post: (path2, body, options2) => request("POST", path2, body, options2),
338
+ patch: (path2, body, options2) => request("PATCH", path2, body, options2),
339
+ delete: (path2, options2) => request("DELETE", path2, void 0, options2)
340
+ };
341
+ }
342
+
343
+ // src/providers/resend.ts
344
+ var RESEND_BASE_URL = "https://api.resend.com";
345
+ var RESEND_BASE_URL_ENV = "BILLIONSEND_CLI_RESEND_URL";
346
+ var resendBaseUrl = (env = process.env) => {
347
+ const override = env[RESEND_BASE_URL_ENV];
348
+ return override === void 0 || override === "" ? RESEND_BASE_URL : override;
349
+ };
350
+ var PAGE = 100;
351
+ var METRICS_WINDOW_DAYS = 30;
352
+ var ENRICH_CONCURRENCY = 3;
353
+ var path = (...parts) => `/${parts.map(encodeURIComponent).join("/")}`;
354
+ function customReturnPath(records) {
355
+ const spf = records.find((record) => record.record === "SPF" && record.name !== void 0);
356
+ const label = spf?.name?.split(".")[0];
357
+ return label === void 0 || label === "" || label === "send" ? null : label;
358
+ }
359
+ function toDomain(wire) {
360
+ const records = wire.records ?? [];
361
+ return {
362
+ name: wire.name,
363
+ region: wire.region ?? "us-east-1",
364
+ openTracking: wire.open_tracking === true,
365
+ clickTracking: wire.click_tracking === true,
366
+ trackingSubdomain: wire.tracking_subdomain ?? null,
367
+ customReturnPath: customReturnPath(records),
368
+ records: records.map(
369
+ (record) => ({
370
+ record: record.record ?? "",
371
+ name: record.name ?? "",
372
+ type: record.type ?? "",
373
+ value: record.value ?? "",
374
+ ttl: record.ttl,
375
+ priority: record.priority,
376
+ status: record.status
377
+ })
378
+ ),
379
+ status: wire.status ?? "unknown"
380
+ };
381
+ }
382
+ function toContact(wire) {
383
+ return {
384
+ id: wire.id,
385
+ email: wire.email,
386
+ firstName: wire.first_name ?? null,
387
+ lastName: wire.last_name ?? null,
388
+ unsubscribed: wire.unsubscribed === true,
389
+ createdAt: wire.created_at ?? ""
390
+ };
391
+ }
392
+ function toBroadcast(wire) {
393
+ return {
394
+ id: wire.id,
395
+ name: wire.name ?? "",
396
+ from: wire.from ?? "",
397
+ subject: wire.subject ?? "",
398
+ replyTo: wire.reply_to ?? null,
399
+ previewText: wire.preview_text ?? null,
400
+ html: wire.html ?? null,
401
+ text: wire.text ?? null,
402
+ status: wire.status ?? "draft",
403
+ segmentId: wire.segment_id ?? null,
404
+ topicId: wire.topic_id ?? null,
405
+ scheduledAt: wire.scheduled_at ?? null
406
+ };
407
+ }
408
+ function toVariable(wire) {
409
+ const fallback = wire.fallback_value;
410
+ return {
411
+ key: wire.key,
412
+ type: wire.type,
413
+ fallbackValue: fallback === void 0 || fallback === null || typeof fallback === "string" ? fallback : typeof fallback === "number" ? fallback : JSON.stringify(fallback)
414
+ };
415
+ }
416
+ function toTemplate(wire) {
417
+ return {
418
+ id: wire.id,
419
+ name: wire.name,
420
+ alias: wire.alias ?? null,
421
+ from: wire.from ?? null,
422
+ subject: wire.subject ?? null,
423
+ replyTo: wire.reply_to ?? null,
424
+ html: wire.html ?? null,
425
+ text: wire.text ?? null,
426
+ variables: (wire.variables ?? []).map(toVariable)
427
+ };
428
+ }
429
+ function toProperties(raw) {
430
+ const properties = {};
431
+ for (const [key, wire] of Object.entries(raw ?? {})) {
432
+ const value = typeof wire === "object" && wire !== null && "value" in wire ? wire.value : wire;
433
+ if (typeof value === "string" || typeof value === "number") properties[key] = value;
434
+ else if (typeof value === "boolean") properties[key] = String(value);
435
+ }
436
+ return properties;
437
+ }
438
+ var emptySnapshot = () => ({
439
+ provider: "resend",
440
+ takenAt: (/* @__PURE__ */ new Date()).toISOString(),
441
+ domains: [],
442
+ apiKeys: [],
443
+ properties: [],
444
+ topics: [],
445
+ segments: [],
446
+ contacts: [],
447
+ broadcasts: [],
448
+ templates: [],
449
+ webhooks: [],
450
+ suppressions: [],
451
+ metrics: { emailsLast30Days: null },
452
+ enriched: false
453
+ });
454
+ function createResendSource(http, log) {
455
+ let requests = 0;
456
+ const get = (route, options) => {
457
+ requests += 1;
458
+ return http.get(route, options);
459
+ };
460
+ async function listAll(route, query = {}, label, onProgress) {
461
+ const items = [];
462
+ let after;
463
+ const guard = cursorGuard(route);
464
+ for (; ; ) {
465
+ const { body } = await get(route, { query: { ...query, limit: PAGE, after } });
466
+ const data = pageItems(route, body, after);
467
+ guard(data, after);
468
+ items.push(...data);
469
+ const hasMore = body.has_more ?? data.length === PAGE;
470
+ if (!hasMore || data.length === 0) break;
471
+ after = nextCursor(route, data, after);
472
+ if (label !== void 0) onProgress?.({ label, n: items.length, done: false });
473
+ }
474
+ if (label !== void 0) {
475
+ onProgress?.({ label, n: items.length, total: items.length, done: true });
476
+ }
477
+ return items;
478
+ }
479
+ async function listWithDetails(route, label, onProgress, detail, keep = () => true) {
480
+ const list = (await listAll(route)).filter(keep);
481
+ const out = [];
482
+ for (const item of list) {
483
+ out.push(await detail(item));
484
+ onProgress?.({ label, n: out.length, total: list.length, done: false });
485
+ }
486
+ onProgress?.({ label, n: out.length, total: list.length, done: true });
487
+ return out;
488
+ }
489
+ return {
490
+ get requests() {
491
+ return requests;
492
+ },
493
+ async probe() {
494
+ const { body } = await get("/domains", { query: { limit: 1 } });
495
+ const first = body.data?.[0];
496
+ return first === void 0 ? { ok: true } : { ok: true, teamHint: first.name };
497
+ },
498
+ async readShallow({ include, includeSent = false, onProgress }) {
499
+ const snapshot = emptySnapshot();
500
+ if (include.has("domains")) {
501
+ snapshot.domains = await listWithDetails(
502
+ "/domains",
503
+ "Domains",
504
+ onProgress,
505
+ async (item) => toDomain((await get(path("domains", item.id))).body),
506
+ (item) => item.shared !== true
507
+ );
508
+ }
509
+ if (include.has("properties") || include.has("enrichment")) {
510
+ const list = await listAll(
511
+ "/contact-properties",
512
+ {},
513
+ "Contact properties",
514
+ onProgress
515
+ );
516
+ snapshot.properties = list.map((property) => ({
517
+ key: property.key,
518
+ type: property.type === "number" ? "number" : "string",
519
+ fallbackValue: property.fallback_value
520
+ }));
521
+ }
522
+ if (include.has("topics") || include.has("enrichment")) {
523
+ const list = await listAll("/topics", {}, "Topics", onProgress);
524
+ snapshot.topics = list.map((topic) => ({
525
+ id: topic.id,
526
+ name: topic.name,
527
+ description: topic.description ?? null,
528
+ defaultSubscription: topic.default_subscription ?? "opt_in",
529
+ visibility: topic.visibility
530
+ }));
531
+ }
532
+ if (include.has("segments")) {
533
+ snapshot.segments = await listWithDetails(
534
+ "/segments",
535
+ "Segments",
536
+ onProgress,
537
+ async (item) => {
538
+ const { body } = await get(path("segments", item.id));
539
+ const members = await listAll(`/segments/${item.id}/contacts`, {});
540
+ return {
541
+ id: item.id,
542
+ name: body.name ?? item.name,
543
+ filter: body.filter ?? null,
544
+ memberEmails: members.map((member) => member.email)
545
+ };
546
+ }
547
+ );
548
+ }
549
+ if (include.has("contacts") || include.has("enrichment")) {
550
+ const list = await listAll("/contacts", {}, "Contacts", onProgress);
551
+ snapshot.contacts = list.map(toContact);
552
+ }
553
+ if (include.has("broadcasts")) {
554
+ snapshot.broadcasts = await listWithDetails(
555
+ "/broadcasts",
556
+ "Broadcasts",
557
+ onProgress,
558
+ async (item) => item.status === "sent" && !includeSent ? toBroadcast(item) : toBroadcast((await get(path("broadcasts", item.id))).body)
559
+ );
560
+ }
561
+ if (include.has("templates")) {
562
+ snapshot.templates = await listWithDetails(
563
+ "/templates",
564
+ "Templates",
565
+ onProgress,
566
+ async (item) => toTemplate((await get(path("templates", item.id))).body)
567
+ );
568
+ }
569
+ if (include.has("webhooks")) {
570
+ snapshot.webhooks = await listWithDetails(
571
+ "/webhooks",
572
+ "Webhooks",
573
+ onProgress,
574
+ async (item) => {
575
+ const { body } = await get(path("webhooks", item.id));
576
+ return {
577
+ id: item.id,
578
+ endpoint: body.endpoint ?? item.endpoint,
579
+ events: body.events ?? item.events ?? [],
580
+ status: body.status ?? item.status ?? "enabled",
581
+ signingSecret: body.signing_secret ?? null
582
+ };
583
+ }
584
+ );
585
+ }
586
+ if (include.has("suppressions")) {
587
+ const list = await listAll(
588
+ "/suppressions",
589
+ {},
590
+ "Suppressions",
591
+ onProgress
592
+ );
593
+ snapshot.suppressions = list.map((row) => ({
594
+ email: row.email,
595
+ origin: row.origin ?? "manual",
596
+ createdAt: row.created_at ?? ""
597
+ }));
598
+ }
599
+ if (include.has("api-keys")) {
600
+ const list = await listAll("/api-keys", {}, "API keys", onProgress);
601
+ snapshot.apiKeys = list.map((key) => ({ name: key.name, createdAt: key.created_at }));
602
+ }
603
+ return snapshot;
604
+ },
605
+ async enrichContacts(snapshot, { alreadyDone, onProgress, onContact, facets, concurrency = ENRICH_CONCURRENCY }) {
606
+ const wants = (facet) => facets === void 0 || facets.includes(facet);
607
+ const wantProperties = wants("properties") && snapshot.properties.length > 0;
608
+ const wantTopics = wants("topics") && snapshot.topics.length > 0;
609
+ const total = snapshot.contacts.length;
610
+ const label = "Enrichment";
611
+ if (wantProperties || wantTopics) {
612
+ const pending = snapshot.contacts.flatMap(
613
+ (contact, index) => alreadyDone?.has(contact.id) === true ? [] : [{ contact, index }]
614
+ );
615
+ let completed = total - pending.length;
616
+ let deliver = Promise.resolve();
617
+ await forEachConcurrent(pending, concurrency, async ({ contact, index }) => {
618
+ const enriched = { ...contact };
619
+ if (wantProperties) {
620
+ const { body } = await get(path("contacts", contact.id));
621
+ enriched.properties = toProperties(body.properties);
622
+ }
623
+ if (wantTopics) {
624
+ const topics = await listAll(path("contacts", contact.id, "topics"));
625
+ enriched.topics = topics.map((topic) => ({
626
+ id: topic.id,
627
+ subscription: topic.subscription ?? "opt_in"
628
+ }));
629
+ }
630
+ snapshot.contacts[index] = enriched;
631
+ deliver = deliver.then(() => onContact(enriched));
632
+ await deliver;
633
+ completed += 1;
634
+ onProgress?.({ label, n: completed, total, done: false });
635
+ });
636
+ }
637
+ onProgress?.({ label, n: total, total, done: true });
638
+ snapshot.enriched = true;
639
+ return snapshot;
640
+ },
641
+ async readMetrics() {
642
+ const end = /* @__PURE__ */ new Date();
643
+ const start = new Date(end.getTime() - METRICS_WINDOW_DAYS * 864e5);
644
+ try {
645
+ const { body } = await get("/emails/metrics", {
646
+ query: {
647
+ start_date: start.toISOString(),
648
+ end_date: end.toISOString(),
649
+ metrics: "sent"
650
+ }
651
+ });
652
+ const sent = body.totals?.sent;
653
+ return { emailsLast30Days: typeof sent === "number" ? sent : null };
654
+ } catch (error) {
655
+ log.debug(`metrics unavailable: ${error instanceof Error ? error.message : String(error)}`);
656
+ return { emailsLast30Days: null };
657
+ }
658
+ }
659
+ };
660
+ }
661
+ var pagesOf = (count) => Math.max(1, Math.ceil(count / PAGE));
662
+ function estimateSourceRequests(snapshot) {
663
+ const s = snapshot;
664
+ 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);
665
+ const facets = (s.properties.length > 0 ? 1 : 0) + (s.topics.length > 0 ? 1 : 0);
666
+ return { spent, enrichment: s.contacts.length * facets };
667
+ }
668
+
669
+ // src/providers/index.ts
670
+ var providers = {
671
+ resend: { id: "resend", label: "Resend", baseUrl: resendBaseUrl, create: createResendSource }
672
+ };
673
+
674
+ // src/tty-ui.ts
675
+ import { createInterface, emitKeypressEvents } from "node:readline";
676
+ var TERMINAL_TOKEN_RE = /\x1b\[[?\d;]*[@-~]|\x1b[^[]|[\s\S]/gu;
677
+ function cursorTracker(columns) {
678
+ let row = 0;
679
+ let col = 0;
680
+ let pending = false;
681
+ return {
682
+ row: () => row,
683
+ reset() {
684
+ row = 0;
685
+ col = 0;
686
+ pending = false;
687
+ },
688
+ feed(text) {
689
+ const width = columns();
690
+ for (const [token] of text.matchAll(TERMINAL_TOKEN_RE)) {
691
+ if (token === "\r" || token === "\n") {
692
+ if (token === "\n") row++;
693
+ col = 0;
694
+ pending = false;
695
+ } else if (token.startsWith("\x1B[")) {
696
+ const n = Number.parseInt(token.slice(2), 10) || 1;
697
+ const op = token.at(-1);
698
+ if (op === "A") row -= n;
699
+ else if (op === "B") row += n;
700
+ else if (op === "C") col = Math.min(width - 1, col + n);
701
+ else if (op === "D") col = Math.max(0, col - n);
702
+ else if (op === "G") col = Math.min(width - 1, n - 1);
703
+ else continue;
704
+ pending = false;
705
+ } else if (token >= " ") {
706
+ if (pending) {
707
+ row++;
708
+ col = 0;
709
+ pending = false;
710
+ }
711
+ if (col === width - 1) pending = true;
712
+ else col++;
713
+ }
714
+ }
715
+ }
716
+ };
717
+ }
718
+ function lineReader(input = process.stdin, output = process.stdout) {
719
+ const tty = output.isTTY === true;
720
+ const cursor = cursorTracker(() => output.columns ?? 80);
721
+ const tracked = new Proxy(output, {
722
+ get(target, key) {
723
+ if (key === "write") {
724
+ return (chunk2) => {
725
+ cursor.feed(String(chunk2));
726
+ return target.write(chunk2);
727
+ };
728
+ }
729
+ const value = Reflect.get(target, key);
730
+ return typeof value === "function" ? value.bind(target) : value;
731
+ }
732
+ });
733
+ const terminal = input.isTTY === true && tty;
734
+ const rl = createInterface({ input, output: tracked, terminal, historySize: 0 });
735
+ const queue = [];
736
+ let waiting;
737
+ let ended = false;
738
+ const endRow = () => {
739
+ if (tty) tracked.write("\n");
740
+ };
741
+ rl.on("line", (line) => {
742
+ if (!terminal && input.isRaw === true) return;
743
+ if (waiting) {
744
+ const resolve = waiting;
745
+ waiting = void 0;
746
+ if (!terminal) endRow();
747
+ resolve(line);
748
+ } else {
749
+ queue.push(line);
750
+ }
751
+ });
752
+ rl.on("close", () => {
753
+ ended = true;
754
+ if (waiting) {
755
+ const resolve = waiting;
756
+ waiting = void 0;
757
+ endRow();
758
+ resolve("");
759
+ }
760
+ });
761
+ rl.on("SIGINT", () => {
762
+ waiting = void 0;
763
+ rl.close();
764
+ output.write("\n");
765
+ process.exit(130);
766
+ });
767
+ return {
768
+ question(prompt) {
769
+ cursor.reset();
770
+ if (ended) {
771
+ tracked.write(prompt);
772
+ } else {
773
+ rl.setPrompt(prompt);
774
+ rl.prompt();
775
+ }
776
+ const line = queue.shift() ?? (ended ? "" : void 0);
777
+ if (line !== void 0) {
778
+ endRow();
779
+ return Promise.resolve(line);
780
+ }
781
+ return new Promise((resolve) => {
782
+ waiting = resolve;
783
+ });
784
+ },
785
+ take() {
786
+ return terminal ? queue.shift() : void 0;
787
+ },
788
+ rows() {
789
+ return cursor.row();
790
+ },
791
+ close() {
792
+ rl.close();
793
+ }
794
+ };
795
+ }
796
+ var isInteractive = () => process.stdin.isTTY === true && process.stdout.isTTY === true;
797
+ var secretPromptMode = (stdinTty, stdoutTty) => ({
798
+ masked: stdinTty,
799
+ toStderr: stdinTty && !stdoutTty
800
+ });
801
+ var answerLine = (label, answer) => `${label}${label.endsWith("?") ? " \u2014 " : ": "}${answer}`;
802
+ var visibleLength = (s) => [...stripControl(s)].length;
803
+ var rowsFor = (lines, columns) => lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(visibleLength(line) / columns)), 0);
804
+ var FULL_ART = [
805
+ "\u2593\u2593\u2584 \u2584\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588 \u2588\u2588 \u2588\u2588\u2588\u2588 \u2584\u2588\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2584 \u2588\u2588 \u2584\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2584 \u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2584 ",
806
+ "\u2593\u2593\u2580\u2584\u2580\u2588\u2588\u2591 \u2588\u2588\u2591\u2591\u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591\u2591\u2588\u2588\u2591\u2591\u2591\u2588\u2588\u2591\u2588\u2588\u2580\u2584 \u2588\u2588\u2591\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2580\u2584 \u2588\u2588\u2591\u2588\u2588\u2591\u2591\u2588\u2588\u2591",
807
+ "\u2593\u2593\u2591\u2580\u2591\u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591\u2588\u2588\u2591\u2580\u2584\u2588\u2588\u2591\u2580\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588\u2588 \u2588\u2588\u2591\u2580\u2584\u2588\u2588\u2591\u2588\u2588\u2591 \u2588\u2588\u2591",
808
+ "\u2593\u2593\u2591 \u2591\u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591 \u2588\u2588\u2591\u2588\u2588\u2591 \u2580\u2588\u2588\u2591 \u2591\u2591\u2591\u2588\u2588\u2591\u2588\u2588\u2591\u2591\u2591 \u2588\u2588\u2591 \u2580\u2588\u2588\u2591\u2588\u2588\u2591 \u2588\u2588\u2591",
809
+ "\u2593\u2593\u2591 \u2588\u2588\u2591\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2591\u2588\u2588\u2591 \u2588\u2588\u2591\u2588\u2588\u2588\u2588\u2588\u2580\u2591\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2591 \u2588\u2588\u2591\u2588\u2588\u2588\u2588\u2588\u2580\u2591",
810
+ " \u2591\u2591 \u2591\u2591 \u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591 \u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591 \u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591"
811
+ ];
812
+ var COMPACT_ART = [
813
+ "\u2593\u2584 \u2584\u2588 \u2588 \u2588 \u2588 \u2588 \u2584\u2580\u2580\u2584 \u2588\u2584 \u2588 \u2588\u2580\u2580 \u2588\u2580\u2580 \u2588\u2584 \u2588 \u2588\u2580\u2584",
814
+ "\u2593 \u2580 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2580\u2588 \u2580\u2580\u2588 \u2588\u2580\u2580 \u2588 \u2580\u2588 \u2588 \u2588",
815
+ "\u2593 \u2588 \u2588 \u2588\u2584\u2584 \u2588\u2584\u2584 \u2588 \u2580\u2584\u2584\u2580 \u2588 \u2588 \u2584\u2584\u2588 \u2588\u2584\u2584 \u2588 \u2588 \u2588\u2584\u2580"
816
+ ];
817
+ function pickBannerTier(columns, isTTY) {
818
+ if (!isTTY || columns < 48) return "plain";
819
+ return columns >= 80 ? "full" : "compact";
820
+ }
821
+ function bannerLines(tier = "full") {
822
+ return tier === "full" ? FULL_ART : COMPACT_ART;
823
+ }
824
+ function banner(tier = "full") {
825
+ return bannerLines(tier);
826
+ }
827
+ async function selectPrompt(rl, {
828
+ label,
829
+ options,
830
+ initial,
831
+ rail = false
832
+ }) {
833
+ const fallback = initial ?? options[0]?.value ?? "";
834
+ if (!isInteractive()) {
835
+ const answer = (await rl.question(`${label} [${fallback}]: `)).trim();
836
+ return answer || fallback;
837
+ }
838
+ return selectTty(label, options, fallback, rail);
839
+ }
840
+ var isEnter = (key) => key.name === "return" || key.name === "enter";
841
+ function readKeys(onKey, erase, stdout = process.stdout) {
842
+ const { stdin } = process;
843
+ emitKeypressEvents(stdin);
844
+ const parked = stdin.rawListeners("keypress");
845
+ stdin.removeAllListeners("keypress");
846
+ const wasRaw = stdin.isRaw === true;
847
+ stdin.setRawMode(true);
848
+ stdin.resume();
849
+ return new Promise((resolve) => {
850
+ const done = (value) => {
851
+ stdin.removeListener("keypress", listener);
852
+ process.removeListener("SIGINT", onSigint);
853
+ for (const l of parked) stdin.on("keypress", l);
854
+ if (!wasRaw) stdin.setRawMode(false);
855
+ erase();
856
+ stdout.write("\x1B[?25h");
857
+ if (value === void 0) {
858
+ stdin.setRawMode(false);
859
+ stdout.write("\n");
860
+ process.exit(130);
861
+ }
862
+ resolve(value);
863
+ };
864
+ const onSigint = () => done(void 0);
865
+ process.once("SIGINT", onSigint);
866
+ const listener = (str, key = {}) => {
867
+ if (key.ctrl === true && key.name === "c") done(void 0);
868
+ else {
869
+ const value = onKey(str, key);
870
+ if (value !== void 0) done(value);
871
+ }
872
+ };
873
+ stdin.on("keypress", listener);
874
+ });
875
+ }
876
+ var eraseRows = (height) => {
877
+ process.stdout.write(`\x1B[${height}A\x1B[J`);
878
+ };
879
+ var terminalColumns = () => process.stdout.columns ?? 80;
880
+ function optionRow(prefix, { label, hint }, selected, columns) {
881
+ const text = truncate(`${label}${hint ? ` (${hint})` : ""}`, columns - 1 - visibleLength(prefix));
882
+ const head = text.slice(0, label.length);
883
+ const tail = text.slice(label.length);
884
+ return `${(selected ? bone : dim)(`${prefix}${head}`)}${tail ? dim(tail) : ""}`;
885
+ }
886
+ function railOptionRow({ label, hint }, selected, columns) {
887
+ const text = truncate(`${label}${hint ? ` ${hint}` : ""}`, columns - 6);
888
+ const head = text.slice(0, label.length);
889
+ const tail = text.slice(label.length);
890
+ return `${dim("\u2502")} ${selected ? info("\u25CF") : dim("\u25CB")} ${selected ? bone(head) : dim(head)}${dim(tail)}`;
891
+ }
892
+ async function selectTty(label, options, initial, rail = false) {
893
+ const { stdout } = process;
894
+ let index = Math.max(
895
+ 0,
896
+ options.findIndex((o) => o.value === initial)
897
+ );
898
+ let height = 0;
899
+ const render = (first) => {
900
+ if (!first) eraseRows(height);
901
+ const columns = terminalColumns();
902
+ const lines = rail ? [
903
+ `${info("\u25C6")} ${bold(label)}`,
904
+ ...options.map((o, i) => railOptionRow(o, i === index, columns)),
905
+ dim("\u2502")
906
+ ] : [
907
+ label,
908
+ ...options.map((o, i) => optionRow(i === index ? "\u276F " : " ", o, i === index, columns))
909
+ ];
910
+ height = rowsFor(lines, columns);
911
+ stdout.write(`${lines.join("\n")}
912
+ `);
913
+ };
914
+ stdout.write("\x1B[?25l");
915
+ render(true);
916
+ const value = await readKeys(
917
+ (_, key) => {
918
+ if (key.name === "up") {
919
+ index = (index + options.length - 1) % options.length;
920
+ render(false);
921
+ } else if (key.name === "down") {
922
+ index = (index + 1) % options.length;
923
+ render(false);
924
+ } else if (isEnter(key)) {
925
+ return options[index]?.value ?? initial;
926
+ }
927
+ return void 0;
928
+ },
929
+ () => eraseRows(height)
930
+ );
931
+ const chosen = options.find((o) => o.value === value)?.label ?? value;
932
+ stdout.write(
933
+ rail ? `${dim("\u25C7")} ${label}
934
+ ${dim("\u2502")} ${dim(chosen)}
935
+ ${dim("\u2502")}
936
+ ` : `${answerLine(label, chosen)}
937
+ `
938
+ );
939
+ return value;
940
+ }
941
+ async function multiSelectPrompt(rl, { label, options }) {
942
+ const defaults = options.filter((o) => o.checked === true).map((o) => o.value);
943
+ if (!isInteractive()) {
944
+ const answer = (await rl.question(`${label} [${defaults.join(",")}]: `)).trim();
945
+ if (answer === "") return defaults;
946
+ const typed = new Set(answer.split(",").map((v) => v.trim()));
947
+ return options.filter((o) => typed.has(o.value)).map((o) => o.value);
948
+ }
949
+ return multiSelectTty(label, options);
950
+ }
951
+ async function multiSelectTty(label, options) {
952
+ const { stdout } = process;
953
+ const checked = options.map((o) => o.checked === true);
954
+ let index = 0;
955
+ let height = 0;
956
+ const render = (first) => {
957
+ if (!first) eraseRows(height);
958
+ const columns = terminalColumns();
959
+ const lines = [
960
+ `${label} ${dim("space toggles \xB7 a toggles all \xB7 enter confirms")}`,
961
+ ...options.map(
962
+ (o, i) => optionRow(
963
+ `${i === index ? "\u276F" : " "} ${checked[i] ? "[x]" : "[ ]"} `,
964
+ o,
965
+ i === index,
966
+ columns
967
+ )
968
+ )
969
+ ];
970
+ height = rowsFor(lines, columns);
971
+ stdout.write(`${lines.join("\n")}
972
+ `);
973
+ };
974
+ stdout.write("\x1B[?25l");
975
+ render(true);
976
+ const values = await readKeys(
977
+ (str, key) => {
978
+ if (key.name === "up") {
979
+ index = (index + options.length - 1) % options.length;
980
+ } else if (key.name === "down") {
981
+ index = (index + 1) % options.length;
982
+ } else if (key.name === "space") {
983
+ checked[index] = !checked[index];
984
+ } else if (str === "a") {
985
+ const all = checked.every(Boolean);
986
+ checked.fill(!all);
987
+ } else if (isEnter(key)) {
988
+ return options.filter((_, i) => checked[i]).map((o) => o.value);
989
+ } else {
990
+ return void 0;
991
+ }
992
+ render(false);
993
+ return void 0;
994
+ },
995
+ () => eraseRows(height)
996
+ );
997
+ const labels = options.filter((o) => values.includes(o.value)).map((o) => o.label);
998
+ stdout.write(
999
+ labels.length > 0 ? `${label}
1000
+ ${labels.map((l) => wrapIndent(l, { indent: " " })).join("\n")}
1001
+ ` : `${answerLine(label, "none")}
1002
+ `
1003
+ );
1004
+ return values;
1005
+ }
1006
+ function maskSecret(secret) {
1007
+ return secret.length >= 12 ? `${secret.slice(0, 3)}****\u2026${secret.slice(-4)}` : "****";
1008
+ }
1009
+ async function secretPrompt(rl, { label, rail = false }) {
1010
+ const mode2 = secretPromptMode(process.stdin.isTTY === true, process.stdout.isTTY === true);
1011
+ if (!mode2.masked) return (await rl.question(`${label}: `)).trim();
1012
+ const stdout = mode2.toStderr ? process.stderr : process.stdout;
1013
+ const ahead = rl.take?.();
1014
+ let secret;
1015
+ if (ahead !== void 0) {
1016
+ secret = ahead.trim();
1017
+ } else {
1018
+ stdout.write(rail ? `${dim("\u2502")} ` : `${label}: `);
1019
+ let value = "";
1020
+ secret = await readKeys(
1021
+ (str, key) => {
1022
+ if (isEnter(key)) return value.trim();
1023
+ if (key.name === "backspace" || key.name === "delete") value = value.slice(0, -1);
1024
+ else if (str !== void 0 && key.ctrl !== true && str >= " ") value += str;
1025
+ return void 0;
1026
+ },
1027
+ () => stdout.write("\r\x1B[2K"),
1028
+ stdout
1029
+ );
1030
+ }
1031
+ stdout.write(
1032
+ rail ? `${dim("\u2502")} ${dim(maskSecret(secret))}
1033
+ ${dim("\u2502")}
1034
+ ` : `${label}: ${dim(maskSecret(secret))}
1035
+ `
1036
+ );
1037
+ return secret;
1038
+ }
1039
+ async function confirmPrompt(rl, { label, initial = false }) {
1040
+ const answer = (await rl.question(`${label} ${initial ? "(Y/n)" : "(y/N)"} `)).trim().toLowerCase();
1041
+ if (answer === "") return initial;
1042
+ return answer === "y" || answer === "yes";
1043
+ }
1044
+
1045
+ // src/theme.ts
1046
+ var COLOR_MODES = ["auto", "always", "never"];
1047
+ var mode = "auto";
1048
+ var streamTty;
1049
+ function setColorMode(next, tty) {
1050
+ mode = next;
1051
+ streamTty = tty;
1052
+ }
1053
+ function colorEnabled() {
1054
+ if (mode !== "auto") return mode === "always";
1055
+ const force = process.env.FORCE_COLOR;
1056
+ if (force !== void 0 && force !== "" && force !== "0") return true;
1057
+ return (streamTty ?? process.stdout.isTTY === true) && process.env.NO_COLOR === void 0;
1058
+ }
1059
+ var sgr = (on, off) => (s) => colorEnabled() ? `\x1B[${on}m${s}\x1B[${off}m` : s;
1060
+ var ok = sgr("32", "39");
1061
+ var warn = sgr("33", "39");
1062
+ var err = sgr("31", "39");
1063
+ var info = sgr("36", "39");
1064
+ var note = sgr("35", "39");
1065
+ var dim = sgr("2", "22");
1066
+ var bold = sgr("1", "22");
1067
+ var accent = sgr("1;97", "22;39");
1068
+ var bone = sgr("97", "39");
1069
+ var badge = sgr("7", "27");
1070
+ var SYM = {
1071
+ ok: "\u2713",
1072
+ err: "\u2717",
1073
+ live: "\u27F3",
1074
+ note: "!",
1075
+ create: "+",
1076
+ update: "~",
1077
+ same: "=",
1078
+ manual: "!",
1079
+ skip: "\u2212"
1080
+ };
1081
+ var layoutWidth = () => Math.min(process.stdout.columns ?? 80, 100);
1082
+ function wrapIndent(text, {
1083
+ width = layoutWidth(),
1084
+ indent = "",
1085
+ hanging = indent
1086
+ } = {}) {
1087
+ const lines = [];
1088
+ let line = indent;
1089
+ let empty = true;
1090
+ for (const word of text.split(/\s+/).filter((w) => w !== "")) {
1091
+ if (!empty && visibleLength(line) + 1 + visibleLength(word) > width) {
1092
+ lines.push(line);
1093
+ line = hanging;
1094
+ empty = true;
1095
+ }
1096
+ line += empty ? word : ` ${word}`;
1097
+ empty = false;
1098
+ }
1099
+ lines.push(line);
1100
+ return lines.join("\n");
1101
+ }
1102
+ var heading = (title) => `${bold(title)}
1103
+ ${dim("\u2500".repeat(layoutWidth()))}`;
1104
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1105
+ var shortId = (id) => UUID_RE.test(id) ? `${id.slice(0, 8)}\u2026` : id;
1106
+ var VALUE_WIDTH = 7;
1107
+ function column(rows, valueWidth = VALUE_WIDTH) {
1108
+ const width = Math.max(0, ...rows.map(([label]) => visibleLength(label)));
1109
+ return rows.map(
1110
+ ([label, value]) => `${label}${" ".repeat(width - visibleLength(label))} ${" ".repeat(Math.max(0, valueWidth - visibleLength(value)))}${value}`
1111
+ );
1112
+ }
1113
+
1114
+ // src/translate.ts
1115
+ var TARGET_WEBHOOK_EVENTS = [
1116
+ "email.scheduled",
1117
+ "email.sent",
1118
+ "email.delivered",
1119
+ "email.delivery_delayed",
1120
+ "email.bounced",
1121
+ "email.complained",
1122
+ "email.failed",
1123
+ "email.suppressed",
1124
+ "email.opened",
1125
+ "email.clicked",
1126
+ "email.received",
1127
+ "contact.created",
1128
+ "contact.updated",
1129
+ "contact.deleted",
1130
+ "suppression.added",
1131
+ "suppression.removed",
1132
+ "inbox.created",
1133
+ "inbox.updated",
1134
+ "inbox.deleted",
1135
+ "inbox.thread.created",
1136
+ "inbox.thread.folder.updated",
1137
+ "inbox.thread.labels.updated",
1138
+ "inbox.email.received",
1139
+ "inbox.email.sent",
1140
+ "inbox.draft.created",
1141
+ "inbox.draft.updated",
1142
+ "inbox.draft.sent",
1143
+ "inbox.draft.deleted"
1144
+ ];
1145
+ var TARGET_ALL_EVENTS = TARGET_WEBHOOK_EVENTS.filter(
1146
+ (event) => !event.startsWith("inbox.")
1147
+ );
1148
+ var MERGE_NAME_RE = /^[A-Za-z0-9_]+$/;
1149
+ var TRIPLE_BRACE_RE = /\{\{\{([\s\S]*?)\}\}\}/g;
1150
+ var MERGE_ALIASES = {
1151
+ "contact.first_name": "FIRST_NAME",
1152
+ "contact.last_name": "LAST_NAME",
1153
+ "contact.email": "EMAIL",
1154
+ unsubscribe_url: "UNSUBSCRIBE_URL",
1155
+ UNSUBSCRIBE_URL: "UNSUBSCRIBE_URL",
1156
+ RESEND_UNSUBSCRIBE_URL: "RESEND_UNSUBSCRIBE_URL"
1157
+ };
1158
+ function translateMergeTags(html) {
1159
+ const untranslated = /* @__PURE__ */ new Set();
1160
+ const out = html.replace(TRIPLE_BRACE_RE, (token, inner) => {
1161
+ const pipe = inner.indexOf("|");
1162
+ const rawName = (pipe === -1 ? inner : inner.slice(0, pipe)).trim();
1163
+ const fallback = pipe === -1 ? null : inner.slice(pipe + 1);
1164
+ const name = MERGE_ALIASES[rawName] ?? (rawName.startsWith("contact.") ? rawName.slice(8) : rawName);
1165
+ if (!MERGE_NAME_RE.test(name) || fallback !== null && /[{}]/.test(fallback)) {
1166
+ untranslated.add(token);
1167
+ return token;
1168
+ }
1169
+ return `{{{${name}${fallback === null ? "" : `|${fallback}`}}}}`;
1170
+ });
1171
+ return { html: out, untranslated: [...untranslated] };
1172
+ }
1173
+ var MATCH_ALIASES = {
1174
+ all: "all",
1175
+ and: "all",
1176
+ any: "any",
1177
+ or: "any"
1178
+ };
1179
+ var TEXT_OP_ALIASES = {
1180
+ equals: "equals",
1181
+ eq: "equals",
1182
+ is: "equals",
1183
+ "=": "equals",
1184
+ not_equals: "not_equals",
1185
+ neq: "not_equals",
1186
+ is_not: "not_equals",
1187
+ "!=": "not_equals",
1188
+ contains: "contains",
1189
+ starts_with: "starts_with",
1190
+ ends_with: "ends_with",
1191
+ is_set: "is_set",
1192
+ exists: "is_set",
1193
+ is_not_empty: "is_set",
1194
+ is_not_set: "is_not_set",
1195
+ not_exists: "is_not_set",
1196
+ is_empty: "is_not_set"
1197
+ };
1198
+ var DATE_OP_ALIASES = {
1199
+ before: "before",
1200
+ lt: "before",
1201
+ less_than: "before",
1202
+ after: "after",
1203
+ gt: "after",
1204
+ greater_than: "after"
1205
+ };
1206
+ var BUILTIN_TEXT_FIELDS = /* @__PURE__ */ new Set(["email", "first_name", "last_name"]);
1207
+ var PROPERTY_PREFIX_RE = /^(?:propert(?:y|ies)[.:]|contact\.)(.+)$/;
1208
+ var asRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
1209
+ var scalarString = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : null;
1210
+ function translateCondition(raw) {
1211
+ const c = asRecord(raw);
1212
+ if (!c || typeof c.field !== "string") return "condition without a field";
1213
+ const opRaw = c.op ?? c.operator;
1214
+ if (typeof opRaw !== "string") return `condition on "${c.field}" without an operator`;
1215
+ const op = opRaw.toLowerCase();
1216
+ const value = scalarString(c.value);
1217
+ const property = PROPERTY_PREFIX_RE.exec(c.field)?.[1];
1218
+ const field = property ? `property:${property}` : c.field;
1219
+ if (property || BUILTIN_TEXT_FIELDS.has(field)) {
1220
+ const mapped = TEXT_OP_ALIASES[op];
1221
+ if (!mapped) return `operator "${opRaw}" on "${c.field}"`;
1222
+ const presence = mapped === "is_set" || mapped === "is_not_set";
1223
+ if (!presence && value === null) return `operator "${opRaw}" on "${c.field}" needs a value`;
1224
+ return { field, op: mapped, value: presence ? null : value };
1225
+ }
1226
+ if (field === "unsubscribed") {
1227
+ const truthy = value === "true" || value === "1";
1228
+ const falsy = value === "false" || value === "0";
1229
+ if (op === "is_true" || (op === "equals" || op === "eq" || op === "is") && truthy)
1230
+ return { field, op: "is_true", value: null };
1231
+ if (op === "is_false" || (op === "equals" || op === "eq" || op === "is") && falsy)
1232
+ return { field, op: "is_false", value: null };
1233
+ return `operator "${opRaw}" on "unsubscribed"`;
1234
+ }
1235
+ if (field === "created_at") {
1236
+ const mapped = DATE_OP_ALIASES[op];
1237
+ if (!mapped) return `operator "${opRaw}" on "created_at"`;
1238
+ if (value === null || Number.isNaN(Date.parse(value)))
1239
+ return `operator "${opRaw}" on "created_at" needs an ISO date`;
1240
+ return { field, op: mapped, value };
1241
+ }
1242
+ return `field "${c.field}"`;
1243
+ }
1244
+ function translateSegmentFilter(filter) {
1245
+ const f = asRecord(filter);
1246
+ if (!f) return { filter: null, reason: "filter is not an object" };
1247
+ const matchRaw = f.match ?? f.operator ?? f.logic ?? f.combinator ?? "all";
1248
+ const match = typeof matchRaw === "string" ? MATCH_ALIASES[matchRaw.toLowerCase()] : void 0;
1249
+ if (!match) return { filter: null, reason: `unknown match mode "${String(matchRaw)}"` };
1250
+ const rawConditions = f.conditions ?? f.filters ?? f.rules;
1251
+ if (!Array.isArray(rawConditions)) return { filter: null, reason: "filter has no conditions" };
1252
+ const conditions = [];
1253
+ for (const raw of rawConditions) {
1254
+ const result = translateCondition(raw);
1255
+ if (typeof result === "string") return { filter: null, reason: `unsupported ${result}` };
1256
+ conditions.push(result);
1257
+ }
1258
+ return { filter: { match, conditions }, reason: null };
1259
+ }
1260
+ function translateWebhookEvents(events) {
1261
+ const kept = /* @__PURE__ */ new Set();
1262
+ const dropped = /* @__PURE__ */ new Set();
1263
+ for (const event of events) {
1264
+ if (TARGET_WEBHOOK_EVENTS.includes(event)) {
1265
+ kept.add(event);
1266
+ } else {
1267
+ dropped.add(event);
1268
+ }
1269
+ }
1270
+ return { events: [...kept], dropped: [...dropped] };
1271
+ }
1272
+ function returnPathLabel(domain) {
1273
+ if (domain.customReturnPath) return domain.customReturnPath;
1274
+ const spf = domain.records.find((r) => r.record === "SPF");
1275
+ if (!spf) return null;
1276
+ let name = spf.name.toLowerCase();
1277
+ if (name.endsWith(`.${domain.name.toLowerCase()}`)) name = name.slice(0, -domain.name.length - 1);
1278
+ const label = name.split(".")[0] ?? "";
1279
+ return label === "" || label === domain.name.toLowerCase() ? null : label;
1280
+ }
1281
+ function domainCreateInput(domain) {
1282
+ const tracking = {
1283
+ open_tracking: domain.openTracking,
1284
+ click_tracking: domain.clickTracking,
1285
+ ...domain.trackingSubdomain ? { tracking_subdomain: domain.trackingSubdomain } : {}
1286
+ };
1287
+ const label = returnPathLabel(domain);
1288
+ const input = {
1289
+ name: domain.name,
1290
+ ...label && label !== "send" ? { custom_return_path: label } : {}
1291
+ };
1292
+ return { input, tracking };
1293
+ }
1294
+ var listTokens = (tokens) => tokens.join(", ");
1295
+ function templateCreateInput(t) {
1296
+ const notes = [];
1297
+ if (t.from) notes.push(`from ${t.from} is not stored on templates; pass it when sending`);
1298
+ if (t.replyTo?.length)
1299
+ notes.push(`reply_to ${t.replyTo.join(", ")} is not stored on templates; pass it when sending`);
1300
+ if (t.variables.length > 0)
1301
+ notes.push(
1302
+ `variables ${t.variables.map((v) => v.key).join(", ")} are not stored; merge fields resolve from contact properties`
1303
+ );
1304
+ if (!t.html) return { input: null, notes, reason: "template has no html body" };
1305
+ const html = translateMergeTags(t.html);
1306
+ const subject = t.subject ? translateMergeTags(t.subject) : null;
1307
+ const text = t.text ? translateMergeTags(t.text) : null;
1308
+ const untranslated = [
1309
+ .../* @__PURE__ */ new Set([
1310
+ ...html.untranslated,
1311
+ ...subject?.untranslated ?? [],
1312
+ ...text?.untranslated ?? []
1313
+ ])
1314
+ ];
1315
+ if (untranslated.length > 0) notes.push(`merge tags left as-is: ${listTokens(untranslated)}`);
1316
+ const input = {
1317
+ name: t.name,
1318
+ ...t.alias ? { alias: t.alias } : {},
1319
+ ...subject ? { subject: subject.html } : {},
1320
+ html: html.html,
1321
+ ...text ? { text: text.html } : {}
1322
+ };
1323
+ return { input, notes, reason: null };
1324
+ }
1325
+ function broadcastCreateInput(b, ids) {
1326
+ const notes = [];
1327
+ if (b.status === "sent") notes.push("already sent on Resend; imported as a draft");
1328
+ else if (b.status === "scheduled" || b.scheduledAt)
1329
+ notes.push(
1330
+ `scheduled on Resend${b.scheduledAt ? ` for ${b.scheduledAt}` : ""}; imported as a draft \u2014 schedule it again`
1331
+ );
1332
+ else if (b.status !== "draft") notes.push(`status ${b.status} on Resend; imported as a draft`);
1333
+ if (!b.html && !b.text) return { input: null, notes, reason: "broadcast has no body" };
1334
+ const html = b.html ? translateMergeTags(b.html) : null;
1335
+ const text = b.text ? translateMergeTags(b.text) : null;
1336
+ const subject = translateMergeTags(b.subject);
1337
+ const untranslated = [
1338
+ .../* @__PURE__ */ new Set([
1339
+ ...html?.untranslated ?? [],
1340
+ ...text?.untranslated ?? [],
1341
+ ...subject.untranslated
1342
+ ])
1343
+ ];
1344
+ if (untranslated.length > 0) notes.push(`merge tags left as-is: ${listTokens(untranslated)}`);
1345
+ const input = {
1346
+ name: b.name,
1347
+ from: b.from,
1348
+ subject: subject.html,
1349
+ ...html ? { html: html.html } : {},
1350
+ ...text ? { text: text.html } : {},
1351
+ ...b.replyTo?.length ? { reply_to: b.replyTo } : {},
1352
+ ...b.previewText ? { preview_text: b.previewText } : {},
1353
+ ...ids.segmentId ? { segment_id: ids.segmentId } : {},
1354
+ ...ids.topicId ? { topic_id: ids.topicId } : {}
1355
+ };
1356
+ return { input, notes, reason: null };
1357
+ }
1358
+
1359
+ // src/plan.ts
1360
+ var PLAN_VERSION = 1;
1361
+ var BATCH_SIZE = 1e3;
1362
+ var RESOURCE_ORDER = [
1363
+ "properties",
1364
+ "topics",
1365
+ "segments",
1366
+ "domains",
1367
+ "webhooks",
1368
+ "templates",
1369
+ "contacts",
1370
+ "broadcasts",
1371
+ "suppressions",
1372
+ "enrichment",
1373
+ "api-keys"
1374
+ ];
1375
+ function changedFields(pairs) {
1376
+ return pairs.filter(([, a, b]) => canonicalJson(a) !== canonicalJson(b)).map(([name]) => name);
1377
+ }
1378
+ var sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
1379
+ function buildPlan({
1380
+ snapshot,
1381
+ target,
1382
+ options
1383
+ }) {
1384
+ const items = [];
1385
+ const warnings = [];
1386
+ const add = (resource, action, key, init = {}) => {
1387
+ items.push({ resource, action, key, ...init });
1388
+ };
1389
+ const manual = (resource, key, detail) => add(resource, "manual", key, { detail });
1390
+ const has = (resource) => options.include.has(resource);
1391
+ if (has("properties")) {
1392
+ for (const p of snapshot.properties) {
1393
+ const existing = target.properties.find((t) => t.key === p.key);
1394
+ if (!existing) {
1395
+ const payload = {
1396
+ key: p.key,
1397
+ type: p.type,
1398
+ ...p.fallbackValue !== void 0 ? { fallback_value: p.fallbackValue } : {}
1399
+ };
1400
+ add("properties", "create", p.key, { payload, detail: p.type });
1401
+ } else if (existing.type !== p.type) {
1402
+ manual(
1403
+ "properties",
1404
+ p.key,
1405
+ `type differs: ${p.type} on Resend, ${existing.type} here \u2014 a property's type cannot change`
1406
+ );
1407
+ } else {
1408
+ add("properties", "unchanged", p.key, { targetId: existing.id });
1409
+ }
1410
+ }
1411
+ }
1412
+ if (has("topics")) {
1413
+ for (const t of snapshot.topics) {
1414
+ const existing = target.topics.find((x) => x.name === t.name);
1415
+ if (!existing) {
1416
+ const payload = {
1417
+ name: t.name,
1418
+ ...t.description ? { description: t.description } : {},
1419
+ default_subscription: t.defaultSubscription,
1420
+ ...t.visibility ? { visibility: t.visibility } : {}
1421
+ };
1422
+ add("topics", "create", t.name, { payload, detail: t.defaultSubscription });
1423
+ continue;
1424
+ }
1425
+ if (existing.defaultSubscription !== t.defaultSubscription) {
1426
+ manual(
1427
+ "topics",
1428
+ t.name,
1429
+ `default_subscription differs: ${t.defaultSubscription} on Resend, ${existing.defaultSubscription} here \u2014 it is fixed at creation`
1430
+ );
1431
+ }
1432
+ const changed = changedFields([
1433
+ ["description", t.description ?? "", existing.description ?? ""]
1434
+ ]);
1435
+ if (changed.length > 0) {
1436
+ add("topics", "update", t.name, {
1437
+ targetId: existing.id,
1438
+ detail: changed.join(", "),
1439
+ payload: { description: t.description ?? "" }
1440
+ });
1441
+ } else {
1442
+ add("topics", "unchanged", t.name, { targetId: existing.id });
1443
+ }
1444
+ }
1445
+ }
1446
+ if (has("segments")) {
1447
+ for (const s of snapshot.segments) {
1448
+ const translated = s.filter === null ? null : translateSegmentFilter(s.filter);
1449
+ const existing = target.segments.find((x) => x.name === s.name);
1450
+ const filter = translated?.filter ?? null;
1451
+ if (!existing) {
1452
+ const payload = { name: s.name, ...filter ? { filter } : {} };
1453
+ add("segments", "create", s.name, {
1454
+ payload,
1455
+ detail: `${filter ? "filter, " : ""}${pluralize(s.memberEmails.length, "member")}`
1456
+ });
1457
+ } else if (filter && canonicalJson(filter) !== canonicalJson(existing.filter)) {
1458
+ add("segments", "update", s.name, {
1459
+ targetId: existing.id,
1460
+ detail: "filter",
1461
+ payload: { filter }
1462
+ });
1463
+ } else {
1464
+ add("segments", "unchanged", s.name, { targetId: existing.id });
1465
+ }
1466
+ if (translated?.reason) {
1467
+ manual(
1468
+ "segments",
1469
+ s.name,
1470
+ `filter not translated (${translated.reason}); ${pluralize(s.memberEmails.length, "member")} still imported`
1471
+ );
1472
+ }
1473
+ }
1474
+ }
1475
+ if (has("domains")) {
1476
+ let creates = 0;
1477
+ for (const d of snapshot.domains) {
1478
+ const existing = target.domains.find((x) => x.name === d.name);
1479
+ if (existing) {
1480
+ add("domains", "unchanged", d.name, { targetId: existing.id });
1481
+ if (existing.status !== "verified") {
1482
+ manual("domains", d.name, `add ${pluralize(existing.records.length, "DNS record")}`);
1483
+ }
1484
+ continue;
1485
+ }
1486
+ const { input, tracking } = domainCreateInput(d);
1487
+ creates += 1;
1488
+ const payload = { create: input, tracking };
1489
+ add("domains", "create", d.name, { payload });
1490
+ manual("domains", d.name, DNS_AFTER_APPLY);
1491
+ }
1492
+ const limit = target.usage.limits.domains;
1493
+ if (limit !== null && creates > 0 && target.domains.length + creates > limit) {
1494
+ warnings.push(
1495
+ `${pluralize(creates, "domain")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${limit} (${target.domains.length} already there)`
1496
+ );
1497
+ }
1498
+ }
1499
+ if (has("webhooks")) {
1500
+ for (const w of snapshot.webhooks) {
1501
+ const { events, dropped } = translateWebhookEvents(w.events);
1502
+ const droppedNote = () => {
1503
+ if (dropped.length > 0)
1504
+ manual("webhooks", w.endpoint, `events not delivered here: ${dropped.join(", ")}`);
1505
+ };
1506
+ if (events.length === 0) {
1507
+ manual("webhooks", w.endpoint, "none of its events exist here; not created");
1508
+ droppedNote();
1509
+ continue;
1510
+ }
1511
+ const existing = target.webhooks.find((x) => x.endpoint === w.endpoint);
1512
+ if (!existing) {
1513
+ const payload = {
1514
+ endpoint: w.endpoint,
1515
+ events,
1516
+ sourceId: w.id,
1517
+ signingSecret: options.freshWebhookSecrets || !w.signingSecret ? "fresh" : "copy"
1518
+ };
1519
+ add("webhooks", "create", w.endpoint, {
1520
+ payload,
1521
+ detail: `${pluralize(events.length, "event")}, ${payload.signingSecret === "copy" ? "secret copied" : "fresh secret"}`
1522
+ });
1523
+ droppedNote();
1524
+ continue;
1525
+ }
1526
+ const update = webhookUpdate(existing, events, w.status);
1527
+ if (update) {
1528
+ add("webhooks", "update", w.endpoint, {
1529
+ targetId: existing.id,
1530
+ detail: Object.keys(update).join(", "),
1531
+ payload: update
1532
+ });
1533
+ } else {
1534
+ add("webhooks", "unchanged", w.endpoint, { targetId: existing.id });
1535
+ }
1536
+ droppedNote();
1537
+ }
1538
+ }
1539
+ if (has("templates")) {
1540
+ for (const t of snapshot.templates) {
1541
+ const { input, notes, reason } = templateCreateInput(t);
1542
+ const label = t.alias ?? t.name;
1543
+ const existing = (t.alias ? target.templates.find((x) => x.alias === t.alias) : void 0) ?? target.templates.find((x) => x.name === t.name);
1544
+ if (!input) {
1545
+ manual("templates", label, reason ?? "cannot be created");
1546
+ } else if (!existing) {
1547
+ add("templates", "create", label, {
1548
+ payload: input,
1549
+ ...t.alias ? { detail: t.name } : {}
1550
+ });
1551
+ } else {
1552
+ const desired = {
1553
+ name: input.name,
1554
+ alias: t.alias,
1555
+ subject: input.subject ?? null,
1556
+ html: input.html,
1557
+ text: input.text ?? null
1558
+ };
1559
+ const current = {
1560
+ name: existing.name,
1561
+ alias: existing.alias,
1562
+ subject: existing.subject ?? null,
1563
+ html: existing.html ?? null,
1564
+ text: existing.text ?? null
1565
+ };
1566
+ const changed = changedFields(
1567
+ Object.keys(desired).map((field) => [field, desired[field], current[field]])
1568
+ );
1569
+ if (changed.length > 0) {
1570
+ add("templates", "update", label, {
1571
+ targetId: existing.id,
1572
+ detail: changed.join(", "),
1573
+ payload: Object.fromEntries(changed.map((field) => [field, desired[field]]))
1574
+ });
1575
+ } else {
1576
+ add("templates", "unchanged", label, { targetId: existing.id });
1577
+ }
1578
+ }
1579
+ for (const note2 of notes) manual("templates", label, note2);
1580
+ }
1581
+ }
1582
+ const contactCount = has("contacts") ? snapshot.contacts.length : 0;
1583
+ if (contactCount > 0) {
1584
+ const memberships = has("segments") ? snapshot.segments.reduce((n, s) => n + s.memberEmails.length, 0) : 0;
1585
+ add("contacts", "create", "contacts", {
1586
+ count: contactCount,
1587
+ detail: `batch upsert, ${pluralize(memberships, "segment membership")}`
1588
+ });
1589
+ const limit = target.usage.limits.contacts;
1590
+ if (limit !== null && contactCount > limit) {
1591
+ warnings.push(
1592
+ `${pluralize(contactCount, "contact")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${formatNumber(limit)}`
1593
+ );
1594
+ }
1595
+ }
1596
+ const facets = [
1597
+ ...snapshot.topics.length > 0 ? ["topic subscriptions"] : [],
1598
+ ...snapshot.properties.length > 0 ? ["properties"] : []
1599
+ ];
1600
+ const enrichCount = snapshot.contacts.length;
1601
+ const enrichment = has("enrichment") && enrichCount > 0 && (contactCount > 0 || target.hasContacts === true) && !snapshot.enriched && facets.length > 0;
1602
+ if (enrichment) {
1603
+ add("enrichment", "update", "contacts", {
1604
+ count: enrichCount,
1605
+ detail: `${facets.join(", then ")}, read per contact`
1606
+ });
1607
+ if (!has("topics") && snapshot.topics.length > 0) {
1608
+ warnings.push(
1609
+ "topics are excluded, so the topic-subscriptions pass has nothing to write and is skipped"
1610
+ );
1611
+ }
1612
+ if (!has("properties") && snapshot.properties.length > 0) {
1613
+ warnings.push(
1614
+ "contact properties are excluded, so the properties pass has nothing to write and is skipped"
1615
+ );
1616
+ }
1617
+ }
1618
+ if (has("broadcasts")) {
1619
+ for (const b of snapshot.broadcasts) {
1620
+ if (b.status === "sent" && !options.includeSent) {
1621
+ add("broadcasts", "skip", b.name, {
1622
+ detail: "already sent; --include-sent imports sent broadcasts as drafts"
1623
+ });
1624
+ continue;
1625
+ }
1626
+ const existing = target.broadcasts.find((x) => x.name === b.name && x.status === "draft");
1627
+ if (existing) {
1628
+ add("broadcasts", "unchanged", b.name, {
1629
+ targetId: existing.id,
1630
+ detail: "matched by name; the draft's body is not compared"
1631
+ });
1632
+ continue;
1633
+ }
1634
+ const domain = senderDomain(b.from);
1635
+ const verified = target.domains.some((d) => d.name === domain && d.status === "verified");
1636
+ const { input, notes, reason } = broadcastCreateInput(b, { segmentId: null, topicId: null });
1637
+ if (!input) {
1638
+ manual("broadcasts", b.name, reason ?? "cannot be created");
1639
+ continue;
1640
+ }
1641
+ if (!verified) {
1642
+ manual(
1643
+ "broadcasts",
1644
+ b.name,
1645
+ `from domain ${domain ?? b.from} is not verified here \u2014 re-run apply after DNS verification`
1646
+ );
1647
+ continue;
1648
+ }
1649
+ const payload = {
1650
+ input,
1651
+ segmentName: snapshot.segments.find((s) => s.id === b.segmentId)?.name ?? null,
1652
+ topicName: snapshot.topics.find((t) => t.id === b.topicId)?.name ?? null
1653
+ };
1654
+ add("broadcasts", "create", b.name, { payload, detail: "draft" });
1655
+ for (const note2 of notes) manual("broadcasts", b.name, note2);
1656
+ }
1657
+ }
1658
+ const suppressionCount = has("suppressions") ? snapshot.suppressions.length : 0;
1659
+ if (suppressionCount > 0) {
1660
+ add("suppressions", "create", "suppressions", {
1661
+ count: suppressionCount,
1662
+ detail: "batch add with origin"
1663
+ });
1664
+ }
1665
+ if (has("api-keys")) {
1666
+ for (const k of snapshot.apiKeys) {
1667
+ manual("api-keys", k.name, "create by hand; Resend exposes only the name");
1668
+ }
1669
+ }
1670
+ items.sort((a, b) => RESOURCE_ORDER.indexOf(a.resource) - RESOURCE_ORDER.indexOf(b.resource));
1671
+ const batches = (n) => Math.ceil(n / BATCH_SIZE);
1672
+ const rowWrites = items.filter(
1673
+ (i) => (i.action === "create" || i.action === "update") && i.count === void 0
1674
+ ).length;
1675
+ const writes = rowWrites + batches(contactCount) + batches(suppressionCount) + (enrichment ? facets.length * batches(enrichCount) : 0);
1676
+ const reads = enrichment ? estimateSourceRequests(snapshot).enrichment : 0;
1677
+ const requests = options.sourceRequestsSpent + reads + writes;
1678
+ const seconds2 = Math.ceil(reads / options.rps + writes / 10);
1679
+ return {
1680
+ version: 1,
1681
+ createdAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1682
+ source: snapshot.provider,
1683
+ target: {
1684
+ baseUrl: options.baseUrl,
1685
+ plan: target.usage.plan
1686
+ },
1687
+ rps: options.rps,
1688
+ items,
1689
+ estimate: { requests, seconds: seconds2 },
1690
+ warnings,
1691
+ ...summarize(items)
1692
+ };
1693
+ }
1694
+ function summarize(items) {
1695
+ const counts = {
1696
+ create: 0,
1697
+ update: 0,
1698
+ unchanged: 0,
1699
+ manual: 0,
1700
+ skip: 0
1701
+ };
1702
+ for (const item of items) counts[item.action] += 1;
1703
+ return {
1704
+ counts,
1705
+ manual: items.filter((i) => i.action === "manual").map((i) => ({ title: `${i.resource}/${i.key}`, detail: i.detail ?? "" }))
1706
+ };
1707
+ }
1708
+ var DNS_AFTER_APPLY = "add DNS records (shown after apply)";
1709
+ function capDomainCreates(plan2, allowed) {
1710
+ let kept = 0;
1711
+ const capped = /* @__PURE__ */ new Set();
1712
+ const items = plan2.items.flatMap((item) => {
1713
+ if (item.resource !== "domains") return [item];
1714
+ if (item.action === "create") {
1715
+ if (kept < allowed) {
1716
+ kept += 1;
1717
+ return [item];
1718
+ }
1719
+ capped.add(item.key);
1720
+ return [
1721
+ {
1722
+ resource: "domains",
1723
+ action: "manual",
1724
+ key: item.key,
1725
+ detail: "over the plan's domain limit; add by hand after upgrading"
1726
+ }
1727
+ ];
1728
+ }
1729
+ if (item.action === "manual" && item.detail === DNS_AFTER_APPLY && capped.has(item.key)) {
1730
+ return [];
1731
+ }
1732
+ return [item];
1733
+ });
1734
+ return { ...plan2, items, ...summarize(items) };
1735
+ }
1736
+ function webhookUpdate(existing, events, status2) {
1737
+ const update = {};
1738
+ if (!sameSet(existing.events, events)) update.events = events;
1739
+ if ((status2 === "enabled" || status2 === "disabled") && status2 !== existing.status)
1740
+ update.status = status2;
1741
+ return Object.keys(update).length > 0 ? update : null;
1742
+ }
1743
+ var COLLAPSE_AT = 3;
1744
+ function groupPlanItems(items) {
1745
+ const runKey = (i) => `${i.action}\0${i.detail ?? ""}`;
1746
+ const groups = [];
1747
+ for (const resource of RESOURCE_ORDER) {
1748
+ const own = items.filter((i) => i.resource === resource);
1749
+ if (own.length === 0) continue;
1750
+ const sizes = /* @__PURE__ */ new Map();
1751
+ for (const i of own) sizes.set(runKey(i), (sizes.get(runKey(i)) ?? 0) + 1);
1752
+ const folded = /* @__PURE__ */ new Set();
1753
+ const rows = [];
1754
+ for (const item of own) {
1755
+ const key = runKey(item);
1756
+ const writes = item.action === "create" || item.action === "update";
1757
+ if (writes || (sizes.get(key) ?? 0) < COLLAPSE_AT) {
1758
+ rows.push({ action: item.action, name: item.key, detail: item.detail });
1759
+ } else if (!folded.has(key)) {
1760
+ folded.add(key);
1761
+ const keys = own.filter((i) => runKey(i) === key).map((i) => i.key);
1762
+ rows.push({
1763
+ action: item.action,
1764
+ name: `${formatNumber(keys.length)} ${resource}`,
1765
+ detail: item.detail,
1766
+ keys
1767
+ });
1768
+ }
1769
+ }
1770
+ const count = own[0]?.count;
1771
+ groups.push({
1772
+ resource,
1773
+ label: count === void 0 ? resource : `${resource} (${formatNumber(count)})`,
1774
+ rows
1775
+ });
1776
+ }
1777
+ return groups;
1778
+ }
1779
+ var ACTION_STYLE = {
1780
+ create: [SYM.create, ok],
1781
+ update: [SYM.update, warn],
1782
+ unchanged: [SYM.same, dim],
1783
+ manual: [SYM.manual, note],
1784
+ skip: [SYM.skip, dim]
1785
+ };
1786
+ var ACTIONS = ["create", "update", "unchanged", "manual", "skip"];
1787
+ function renderRow(row) {
1788
+ const [symbol, paint] = ACTION_STYLE[row.action];
1789
+ const head = ` ${paint(symbol)} ${stripControl(row.name)}`;
1790
+ const lines = [
1791
+ row.detail === void 0 ? head : wrapIndent(dim(stripControl(row.detail)), { indent: `${head} `, hanging: " " })
1792
+ ];
1793
+ if (row.keys) lines.push(wrapIndent(dim(foldedKeysLine(row.keys)), { indent: " " }));
1794
+ return lines;
1795
+ }
1796
+ var foldedKeysLine = (keys) => `${keys.slice(0, 2).map(stripControl).join(", ")} \u2026 and ${formatNumber(keys.length - 2)} more`;
1797
+ function renderPlan(plan2) {
1798
+ const c = plan2.counts;
1799
+ const n = (count) => count > 0 ? bold(formatNumber(count)) : "0";
1800
+ const lines = [
1801
+ dim(ACTIONS.map((a) => `${ACTION_STYLE[a][0]} ${a}`).join(" ")),
1802
+ "",
1803
+ ...groupPlanItems(plan2.items).flatMap((g) => [g.label, ...g.rows.flatMap(renderRow)]),
1804
+ "",
1805
+ wrapIndent(
1806
+ `Plan: ${n(c.create)} to create, ${n(c.update)} to update, ${n(c.unchanged)} unchanged, ${n(c.manual)} manual${c.skip > 0 ? `, ${n(c.skip)} skipped` : ""}.`,
1807
+ { hanging: " " }
1808
+ ),
1809
+ ...plan2.warnings.map((w) => wrapIndent(warn(`warning: ${w}`), { hanging: " " })),
1810
+ wrapIndent(
1811
+ dim(
1812
+ `Estimate: ~${formatNumber(plan2.estimate.requests)} requests \xB7 ${formatDuration(plan2.estimate.seconds)} at ${plan2.rps} req/s`
1813
+ ),
1814
+ { hanging: " " }
1815
+ )
1816
+ ];
1817
+ return `${lines.join("\n")}
1818
+ `;
1819
+ }
1820
+ function planHash(plan2) {
1821
+ return createHash("sha256").update(canonicalJson(plan2.items)).digest("hex");
1822
+ }
1823
+ var serializePlan = (plan2) => `${JSON.stringify(plan2, null, 2)}
1824
+ `;
1825
+ function parsePlan(text) {
1826
+ let parsed;
1827
+ try {
1828
+ parsed = JSON.parse(text);
1829
+ } catch {
1830
+ throw new Error("plan file is not valid JSON");
1831
+ }
1832
+ const plan2 = parsed;
1833
+ if (!plan2 || typeof plan2 !== "object" || !Array.isArray(plan2.items)) {
1834
+ throw new Error("plan file is not a migration plan");
1835
+ }
1836
+ if (plan2.version !== PLAN_VERSION) {
1837
+ throw new Error(
1838
+ `plan file version ${String(plan2.version)} is not supported (expected ${PLAN_VERSION})`
1839
+ );
1840
+ }
1841
+ return plan2;
1842
+ }
1843
+
1844
+ // src/config.ts
1845
+ import { parseArgs } from "node:util";
1846
+
1847
+ // src/meta.ts
1848
+ var VERSION = true ? "0.2.5" : "0.0.0-dev";
1849
+ var REPO_URL = "https://github.com/billionsend/billionsend-cli";
1850
+ var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
1851
+ var CLOUD_API_URL = "https://api.billionsend.com";
1852
+ var CLOUD_BILLING_URL = "https://billionsend.com/settings/billing";
1853
+ var TRADEMARK_NOTICE = "Resend is a trademark of Plus Five Five, Inc. BillionSend is not affiliated with or endorsed by Resend.";
1854
+
1855
+ // src/model.ts
1856
+ var PROVIDERS = ["resend"];
1857
+ var RESOURCES = [
1858
+ "domains",
1859
+ "properties",
1860
+ "topics",
1861
+ "segments",
1862
+ "contacts",
1863
+ "enrichment",
1864
+ "broadcasts",
1865
+ "templates",
1866
+ "webhooks",
1867
+ "suppressions",
1868
+ "api-keys"
1869
+ ];
1870
+
1871
+ // src/config.ts
1872
+ var ConfigError = class extends Error {
1873
+ constructor(message) {
1874
+ super(message);
1875
+ this.name = "ConfigError";
1876
+ }
1877
+ };
1878
+ var DEFAULT_RPS = 8;
1879
+ var MAX_RPS = 10;
1880
+ var RPS_CEILING = 100;
1881
+ var RPS_HEADROOM = 2;
1882
+ var TARGET_KEY_ENV = "BILLIONSEND_API_KEY";
1883
+ var TARGET_URL_ENV = "BILLIONSEND_BASE_URL";
1884
+ var sourceKeyEnv = (provider) => `${provider.toUpperCase()}_API_KEY`;
1885
+ var OPTIONS = {
1886
+ from: { type: "string" },
1887
+ "from-key": { type: "string" },
1888
+ "from-key-stdin": { type: "boolean" },
1889
+ "to-url": { type: "string" },
1890
+ "to-key": { type: "string" },
1891
+ "to-key-stdin": { type: "boolean" },
1892
+ rps: { type: "string" },
1893
+ only: { type: "string" },
1894
+ skip: { type: "string" },
1895
+ "on-conflict": { type: "string" },
1896
+ yes: { type: "boolean", short: "y" },
1897
+ "non-interactive": { type: "boolean" },
1898
+ json: { type: "boolean" },
1899
+ out: { type: "string" },
1900
+ report: { type: "string" },
1901
+ color: { type: "string" },
1902
+ "no-color": { type: "boolean" },
1903
+ verbose: { type: "boolean", short: "v" },
1904
+ "fresh-webhook-secrets": { type: "boolean" },
1905
+ "include-sent": { type: "boolean" },
1906
+ fresh: { type: "boolean" },
1907
+ help: { type: "boolean", short: "h" },
1908
+ version: { type: "boolean", short: "V" }
1909
+ };
1910
+ var SUBCOMMANDS = ["plan", "apply", "status", "rollback"];
1911
+ var GRAMMAR = "billionsend migrate --from resend | migrate plan | migrate apply [plan.json] | migrate status | migrate rollback";
1912
+ function resourceList(flag, value) {
1913
+ if (value === void 0) return null;
1914
+ const names = value.split(",").map((name) => name.trim()).filter((name) => name !== "");
1915
+ for (const name of names) {
1916
+ if (!RESOURCES.includes(name)) {
1917
+ throw new ConfigError(
1918
+ `Unknown resource \`${name}\` in ${flag}. Known: ${RESOURCES.join(", ")}`
1919
+ );
1920
+ }
1921
+ }
1922
+ return names;
1923
+ }
1924
+ function keyInput(envName, env, stdinFlag, flagValue, flagName, warnings) {
1925
+ if (stdinFlag && flagValue !== void 0) {
1926
+ throw new ConfigError(`Pass either ${flagName} or ${flagName}-stdin, not both.`);
1927
+ }
1928
+ const fromEnv = env[envName];
1929
+ if (fromEnv !== void 0 && fromEnv !== "") return { source: "env", value: fromEnv };
1930
+ if (stdinFlag) return { source: "stdin", value: null };
1931
+ if (flagValue !== void 0) {
1932
+ warnings.push(
1933
+ `${flagName} is visible to other users in process lists; prefer ${envName} or ${flagName}-stdin.`
1934
+ );
1935
+ return { source: "flag", value: flagValue };
1936
+ }
1937
+ return { source: "prompt", value: null };
1938
+ }
1939
+ function apiUrl(value) {
1940
+ let url;
1941
+ try {
1942
+ url = new URL(value);
1943
+ } catch {
1944
+ throw new ConfigError(`Not a URL: ${value}. Expected e.g. ${CLOUD_API_URL}`);
1945
+ }
1946
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
1947
+ throw new ConfigError(`The BillionSend API URL must be http(s): ${value}`);
1948
+ }
1949
+ return stripTrailingSlashes(value);
1950
+ }
1951
+ function parseConfig(argv, env = process.env, stdinIsTTY = process.stdin.isTTY === true) {
1952
+ let values;
1953
+ let positionals;
1954
+ try {
1955
+ ({ values, positionals } = parseArgs({
1956
+ args: argv,
1957
+ options: OPTIONS,
1958
+ strict: true,
1959
+ allowPositionals: true
1960
+ }));
1961
+ } catch (error) {
1962
+ const reason = error.message.split(". ")[0] ?? "Bad arguments";
1963
+ throw new ConfigError(`${reason}. See billionsend --help`);
1964
+ }
1965
+ if (values.version === true) return minimal("version");
1966
+ if (values.help === true || positionals.length === 0) return minimal("help");
1967
+ const [top, sub, file, ...rest] = positionals;
1968
+ if (top !== "migrate") {
1969
+ throw new ConfigError(`Unknown command \`${top}\`. Usage: ${GRAMMAR}`);
1970
+ }
1971
+ if (sub !== void 0 && !SUBCOMMANDS.includes(sub)) {
1972
+ throw new ConfigError(`Unknown command \`migrate ${sub}\`. Usage: ${GRAMMAR}`);
1973
+ }
1974
+ const command = sub ?? "migrate";
1975
+ if (file !== void 0 && command !== "apply") {
1976
+ throw new ConfigError(`Unexpected argument \`${file}\`. Usage: ${GRAMMAR}`);
1977
+ }
1978
+ if (rest.length > 0) {
1979
+ throw new ConfigError(`Unexpected argument \`${rest[0]}\`. Usage: ${GRAMMAR}`);
1980
+ }
1981
+ const planFile = file ?? null;
1982
+ const warnings = [];
1983
+ const json = values.json === true;
1984
+ const nonInteractive = values["non-interactive"] === true || json || !stdinIsTTY;
1985
+ let from = null;
1986
+ if (values.from !== void 0) {
1987
+ if (!PROVIDERS.includes(values.from)) {
1988
+ throw new ConfigError(
1989
+ `Unknown provider \`${values.from}\`. Supported: ${PROVIDERS.join(", ")}`
1990
+ );
1991
+ }
1992
+ from = values.from;
1993
+ }
1994
+ const needsSource = command === "migrate" || command === "plan" || command === "apply";
1995
+ if (needsSource && from === null && planFile === null) {
1996
+ throw new ConfigError(
1997
+ `Missing --from <provider>. Only \`resend\` is supported: billionsend migrate${sub === void 0 ? "" : ` ${sub}`} --from resend`
1998
+ );
1999
+ }
2000
+ const fromKey = keyInput(
2001
+ sourceKeyEnv(from ?? "resend"),
2002
+ env,
2003
+ values["from-key-stdin"] === true,
2004
+ values["from-key"],
2005
+ "--from-key",
2006
+ warnings
2007
+ );
2008
+ const toKey = keyInput(
2009
+ TARGET_KEY_ENV,
2010
+ env,
2011
+ values["to-key-stdin"] === true,
2012
+ values["to-key"],
2013
+ "--to-key",
2014
+ warnings
2015
+ );
2016
+ const toUrlRaw = values["to-url"] ?? env[TARGET_URL_ENV];
2017
+ const toUrl = toUrlRaw === void 0 || toUrlRaw === "" ? CLOUD_API_URL : apiUrl(toUrlRaw);
2018
+ const needsTarget = needsSource || command === "rollback";
2019
+ if (nonInteractive && needsTarget) {
2020
+ if (needsSource && fromKey.source === "prompt") {
2021
+ throw new ConfigError(
2022
+ `Missing ${providers[from ?? "resend"].label} API key. Set ${sourceKeyEnv(from ?? "resend")} or pass --from-key-stdin (non-interactive mode never prompts).`
2023
+ );
2024
+ }
2025
+ if (toKey.source === "prompt") {
2026
+ throw new ConfigError(
2027
+ `Missing BillionSend API key. Set ${TARGET_KEY_ENV} or pass --to-key-stdin (non-interactive mode never prompts).`
2028
+ );
2029
+ }
2030
+ if (command !== "plan" && values.yes !== true) {
2031
+ throw new ConfigError(
2032
+ "migrate/apply/rollback need --yes in non-interactive mode (or run `migrate plan` to only read)."
2033
+ );
2034
+ }
2035
+ }
2036
+ let rps = DEFAULT_RPS;
2037
+ const rpsGiven = values.rps !== void 0;
2038
+ if (values.rps !== void 0) {
2039
+ rps = Number(values.rps);
2040
+ if (!Number.isInteger(rps) || rps < 1 || rps > RPS_CEILING) {
2041
+ throw new ConfigError(
2042
+ `--rps must be a whole number between 1 and ${RPS_CEILING} (got ${values.rps}).`
2043
+ );
2044
+ }
2045
+ }
2046
+ const onConflict = values["on-conflict"] ?? "upsert";
2047
+ if (onConflict !== "upsert" && onConflict !== "skip" && onConflict !== "error") {
2048
+ throw new ConfigError(`--on-conflict must be upsert, skip or error (got ${onConflict}).`);
2049
+ }
2050
+ if (values.out !== void 0 && command !== "plan") {
2051
+ throw new ConfigError("--out only applies to `migrate plan`.");
2052
+ }
2053
+ const color = values.color ?? (values["no-color"] === true ? "never" : "auto");
2054
+ if (!COLOR_MODES.includes(color)) {
2055
+ throw new ConfigError(`--color must be auto, always or never (got ${color}).`);
2056
+ }
2057
+ if (values["no-color"] === true && color !== "never") {
2058
+ throw new ConfigError("Pass either --color or --no-color, not both.");
2059
+ }
2060
+ return {
2061
+ command,
2062
+ planFile,
2063
+ from,
2064
+ fromKey,
2065
+ toKey,
2066
+ toUrl,
2067
+ rps,
2068
+ rpsGiven,
2069
+ only: resourceList("--only", values.only),
2070
+ skip: resourceList("--skip", values.skip) ?? [],
2071
+ onConflict,
2072
+ yes: values.yes === true,
2073
+ nonInteractive,
2074
+ json,
2075
+ out: values.out ?? null,
2076
+ report: values.report ?? null,
2077
+ color,
2078
+ verbose: values.verbose === true,
2079
+ freshWebhookSecrets: values["fresh-webhook-secrets"] === true,
2080
+ includeSent: values["include-sent"] === true,
2081
+ fresh: values.fresh === true,
2082
+ warnings
2083
+ };
2084
+ }
2085
+ function minimal(command) {
2086
+ return {
2087
+ command,
2088
+ planFile: null,
2089
+ from: null,
2090
+ fromKey: { source: "prompt", value: null },
2091
+ toKey: { source: "prompt", value: null },
2092
+ toUrl: CLOUD_API_URL,
2093
+ rps: DEFAULT_RPS,
2094
+ rpsGiven: false,
2095
+ only: null,
2096
+ skip: [],
2097
+ onConflict: "upsert",
2098
+ yes: false,
2099
+ nonInteractive: true,
2100
+ json: false,
2101
+ out: null,
2102
+ report: null,
2103
+ color: "auto",
2104
+ verbose: false,
2105
+ freshWebhookSecrets: false,
2106
+ includeSent: false,
2107
+ fresh: false,
2108
+ warnings: []
2109
+ };
2110
+ }
2111
+ function helpText() {
2112
+ return `billionsend ${VERSION} \u2014 move an email account to BillionSend
2113
+
2114
+ Usage
2115
+ billionsend migrate --from resend connect, choose resources, plan, confirm, apply, summary
2116
+ billionsend migrate plan --from resend [--out plan.json] read-only; exit 0 nothing to do, 2 changes, 1 error
2117
+ billionsend migrate apply [plan.json] [--yes] apply a saved plan, or plan and apply in one go
2118
+ billionsend migrate status what the last run created and what is left
2119
+ billionsend migrate rollback [--yes] delete only what this tool created
2120
+ billionsend --help | --version
2121
+
2122
+ Options
2123
+ --from <provider> source provider; only \`resend\` exists
2124
+ --from-key-stdin read the source API key from stdin (first line)
2125
+ --from-key <key> source API key as an argument (visible in process lists; prefer the env var)
2126
+ --to-url <url> BillionSend API URL (default ${CLOUD_API_URL})
2127
+ --to-key-stdin read the BillionSend API key from stdin (second line when both stdin flags are set)
2128
+ --to-key <key> BillionSend API key as an argument (same caveat)
2129
+ --rps <n> requests per second against the source (default ${DEFAULT_RPS}). Resend's team limit is ${MAX_RPS}, shared
2130
+ with your production sending; the CLI prints the limit it detects and warns above it.
2131
+ Go past ${MAX_RPS} only after Resend raised your limit (up to ${RPS_CEILING})
2132
+ --only <a,b> migrate only these resources
2133
+ --skip <a,b> skip these resources; \`enrichment\` is the per-contact properties/topics pass
2134
+ --on-conflict <mode> contacts that already exist on the target: upsert (default), skip, error
2135
+ --include-sent import sent broadcasts as drafts (skipped by default)
2136
+ --fresh-webhook-secrets mint new webhook signing secrets instead of copying them (shown once in the report)
2137
+ --fresh ignore resume progress; keeps what earlier runs created so rollback still works
2138
+ --out <file> \`migrate plan\`: write the plan as JSON
2139
+ --report <file> also write the Markdown report to this path
2140
+ -y, --yes skip confirmations
2141
+ --non-interactive never prompt; a missing input is exit 1 (automatic when stdin is not a terminal, and with --json)
2142
+ --json JSON on stdout, progress on stderr
2143
+ -v, --verbose log every request: GET /contacts?limit=100 \u2192 200 (143 ms)
2144
+ --color <mode> auto (default: colors on a terminal, none when piped or NO_COLOR is set), always, never
2145
+ --no-color same as --color never
2146
+ -h, --help this text
2147
+ -V, --version print the version
2148
+
2149
+ Resources
2150
+ ${RESOURCES.join(", ")}
2151
+
2152
+ Environment
2153
+ RESEND_API_KEY source API key (full access; the tool only reads from Resend)
2154
+ ${TARGET_KEY_ENV} BillionSend API key (full access)
2155
+ ${TARGET_URL_ENV} BillionSend API URL, same as --to-url
2156
+ NO_COLOR disable colors
2157
+ FORCE_COLOR colors even when piped, same as --color always
2158
+ DO_NOT_TRACK honored, as a no-op: this tool sends no telemetry, never phones home and never checks for updates
2159
+
2160
+ Files (mode 0600, never a key)
2161
+ .billionsend/migrate-state.json ids created, resume cursors, plan hash
2162
+ .billionsend/migrate-report.json the last run's report, also as migrate-report.md
2163
+
2164
+ Exit codes
2165
+ 0 ok \xB7 1 error \xB7 2 plan has changes (plan only) \xB7 3 partial, some items failed (details in the report)
2166
+
2167
+ ${TRADEMARK_NOTICE}
2168
+ `;
2169
+ }
2170
+
2171
+ // src/billionsend.ts
2172
+ var BATCH_MAX = 1e3;
2173
+ var PERMISSIVE = { headers: { "x-batch-validation": "permissive" } };
2174
+ function writeError(error) {
2175
+ if (!(error instanceof ApiError) || error.status < 400 || error.status >= 500) return null;
2176
+ const body = error.body;
2177
+ return {
2178
+ ok: false,
2179
+ status: error.status,
2180
+ name: error.name,
2181
+ message: typeof body?.message === "string" ? body.message : error.message
2182
+ };
2183
+ }
2184
+ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2185
+ let requests = 0;
2186
+ const api = {
2187
+ get: (path2, options) => {
2188
+ requests += 1;
2189
+ return http.get(path2, options);
2190
+ },
2191
+ post: (path2, body, options) => {
2192
+ requests += 1;
2193
+ return http.post(path2, body, options);
2194
+ },
2195
+ patch: (path2, body, options) => {
2196
+ requests += 1;
2197
+ return http.patch(path2, body, options);
2198
+ },
2199
+ delete: (path2, options) => {
2200
+ requests += 1;
2201
+ return http.delete(path2, options);
2202
+ }
2203
+ };
2204
+ async function write(run) {
2205
+ try {
2206
+ return { ok: true, ...await run() };
2207
+ } catch (error) {
2208
+ const failed = writeError(error);
2209
+ if (failed) return failed;
2210
+ throw error;
2211
+ }
2212
+ }
2213
+ const id = async (response) => ({
2214
+ id: (await response).body.id
2215
+ });
2216
+ const withRecords = async (response) => {
2217
+ const { body } = await response;
2218
+ return { id: body.id, records: body.records };
2219
+ };
2220
+ async function listAll(path2, { paged = true } = {}) {
2221
+ const rows = [];
2222
+ let after;
2223
+ const guard = cursorGuard(path2);
2224
+ for (; ; ) {
2225
+ const { body } = await api.get(
2226
+ path2,
2227
+ paged ? { query: { limit: 100, after } } : {}
2228
+ );
2229
+ const data = pageItems(path2, body, after);
2230
+ guard(data, after);
2231
+ rows.push(...data);
2232
+ if (!paged || body.has_more !== true || data.length === 0) {
2233
+ return rows.sort(
2234
+ (a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)
2235
+ );
2236
+ }
2237
+ after = nextCursor(path2, data, after);
2238
+ }
2239
+ }
2240
+ async function probe() {
2241
+ let body;
2242
+ try {
2243
+ ({ body } = await api.get("/usage"));
2244
+ } catch (error) {
2245
+ if (error instanceof AuthError) {
2246
+ error.message = error.status === 403 ? `BillionSend rejected the API key (403): it is a sending-only key. Migration needs a full-access key (bs_\u2026) for your BillionSend instance in ${TARGET_KEY_ENV}.` : `BillionSend rejected the API key (401). Check ${TARGET_KEY_ENV}: it must be a full-access key (bs_\u2026) of your BillionSend instance.`;
2247
+ }
2248
+ if (error instanceof ApiError && error.status === 404) {
2249
+ throw new Error(
2250
+ `BillionSend at ${baseUrl} has no GET /usage: either ${baseUrl} is not the API URL of your instance (check --to-url / ${TARGET_URL_ENV}) or the instance predates CLI ${VERSION}; upgrade it.`
2251
+ );
2252
+ }
2253
+ throw error;
2254
+ }
2255
+ const period = body.period ?? null;
2256
+ return {
2257
+ plan: body.plan,
2258
+ limits: {
2259
+ emailsPerDay: body.limits.emails_per_day,
2260
+ emailsPerMonth: body.limits.emails_per_month ?? null,
2261
+ domains: body.limits.domains,
2262
+ contacts: body.limits.contacts ?? null
2263
+ },
2264
+ today: { emailsSent: body.today.emails_sent },
2265
+ period: period && {
2266
+ emailsSent: period.emails_sent,
2267
+ included: period.included,
2268
+ overageEnabled: period.overage_enabled,
2269
+ startsAt: period.starts_at,
2270
+ endsAt: period.ends_at
2271
+ },
2272
+ appUrl: body.app_url
2273
+ };
2274
+ }
2275
+ async function readState() {
2276
+ const usage = await probe();
2277
+ const [
2278
+ domainRows,
2279
+ properties,
2280
+ topics,
2281
+ segments,
2282
+ webhooks,
2283
+ templateRows,
2284
+ broadcasts,
2285
+ firstContact
2286
+ ] = await Promise.all([
2287
+ listAll("/domains"),
2288
+ listAll("/contact-properties"),
2289
+ listAll("/topics", { paged: false }),
2290
+ listAll("/segments"),
2291
+ listAll("/webhooks"),
2292
+ listAll("/templates"),
2293
+ listAll("/broadcasts"),
2294
+ api.get("/contacts", { query: { limit: 1 } })
2295
+ ]);
2296
+ const domains = [];
2297
+ for (const { id: id2 } of domainRows.filter((row) => row.shared !== true)) {
2298
+ const { body } = await api.get(`/domains/${id2}`);
2299
+ domains.push({
2300
+ id: body.id,
2301
+ name: body.name,
2302
+ region: body.region,
2303
+ status: body.status,
2304
+ records: body.records
2305
+ });
2306
+ }
2307
+ const templates = [];
2308
+ for (const { id: id2 } of templateRows) {
2309
+ const { body } = await api.get(`/templates/${id2}`);
2310
+ templates.push({
2311
+ id: body.id,
2312
+ name: body.name,
2313
+ alias: body.alias,
2314
+ subject: body.subject,
2315
+ html: body.html,
2316
+ text: body.text
2317
+ });
2318
+ }
2319
+ return {
2320
+ usage,
2321
+ domains,
2322
+ hasContacts: firstContact.body.data.length > 0,
2323
+ properties: properties.map(({ id: id2, key, type }) => ({ id: id2, key, type })),
2324
+ topics: topics.map(
2325
+ (t) => ({
2326
+ id: t.id,
2327
+ name: t.name,
2328
+ description: t.description ?? null,
2329
+ defaultSubscription: t.default_subscription
2330
+ })
2331
+ ),
2332
+ segments: segments.map(({ id: id2, name, filter }) => ({ id: id2, name, filter })),
2333
+ // null on the wire means every event (dashboard-created endpoints); the plan diffs real sets.
2334
+ webhooks: webhooks.map(
2335
+ (w) => ({
2336
+ id: w.id,
2337
+ endpoint: w.endpoint,
2338
+ events: w.events ?? [...TARGET_ALL_EVENTS],
2339
+ status: w.status
2340
+ })
2341
+ ),
2342
+ templates,
2343
+ broadcasts: broadcasts.map(
2344
+ (b) => ({ id: b.id, name: b.name ?? "", status: b.status })
2345
+ )
2346
+ };
2347
+ }
2348
+ async function batchContacts(items, {
2349
+ onConflict,
2350
+ permissive = true
2351
+ }) {
2352
+ const out = {
2353
+ data: [],
2354
+ counts: { created: 0, updated: 0, skipped: 0, failed: 0 },
2355
+ errors: []
2356
+ };
2357
+ const chunks = chunk(items, BATCH_MAX);
2358
+ for (const [n, slice] of chunks.entries()) {
2359
+ const base = n * BATCH_MAX;
2360
+ if (chunks.length > 1)
2361
+ log.debug(`contacts batch ${n + 1}/${chunks.length} (${slice.length})`);
2362
+ const result = await write(async () => ({
2363
+ body: (await api.post(`/contacts/batch?on_conflict=${onConflict}`, slice, {
2364
+ ...permissive ? PERMISSIVE : {}
2365
+ })).body
2366
+ }));
2367
+ if (!result.ok) {
2368
+ log.warn(`contacts batch ${n + 1}/${chunks.length} failed: ${result.message}`);
2369
+ for (const i of slice.keys()) {
2370
+ out.errors.push({ index: base + i, statusCode: result.status, message: result.message });
2371
+ }
2372
+ out.counts.failed += slice.length;
2373
+ continue;
2374
+ }
2375
+ const { body } = result;
2376
+ for (const row of body.data) out.data.push({ ...row, index: base + row.index });
2377
+ for (const { index, statusCode, message } of body.errors ?? []) {
2378
+ out.errors.push({ index: base + index, statusCode, message });
2379
+ }
2380
+ for (const key of Object.keys(out.counts)) {
2381
+ out.counts[key] += body.counts[key];
2382
+ }
2383
+ }
2384
+ return out;
2385
+ }
2386
+ async function suppressionsBatch(path2, key, values, extra = {}) {
2387
+ const out = { ids: [], errors: [] };
2388
+ const chunks = chunk(values, BATCH_MAX);
2389
+ for (const [n, slice] of chunks.entries()) {
2390
+ const result = await write(async () => ({
2391
+ data: (await api.post(path2, { [key]: slice, ...extra })).body.data
2392
+ }));
2393
+ if (!result.ok) {
2394
+ log.warn(`${path2} ${n + 1}/${chunks.length} failed: ${result.message}`);
2395
+ for (const i of slice.keys()) {
2396
+ out.errors.push({
2397
+ index: n * BATCH_MAX + i,
2398
+ statusCode: result.status,
2399
+ message: result.message
2400
+ });
2401
+ }
2402
+ continue;
2403
+ }
2404
+ out.ids.push(...result.data.map((r) => r.id));
2405
+ }
2406
+ return out;
2407
+ }
2408
+ return {
2409
+ /** Requests issued so far, for the summary's "~2,140 requests" line. */
2410
+ get requests() {
2411
+ return requests;
2412
+ },
2413
+ probe,
2414
+ readState,
2415
+ createProperty: (input) => write(
2416
+ () => id(
2417
+ api.post("/contact-properties", {
2418
+ key: input.key,
2419
+ type: input.type,
2420
+ fallback_value: input.fallbackValue
2421
+ })
2422
+ )
2423
+ ),
2424
+ deleteProperty: (propertyId) => write(() => id(api.delete(`/contact-properties/${propertyId}`))),
2425
+ createTopic: (input) => write(
2426
+ () => id(
2427
+ api.post("/topics", {
2428
+ name: input.name,
2429
+ description: input.description ?? void 0,
2430
+ default_subscription: input.defaultSubscription,
2431
+ visibility: input.visibility
2432
+ })
2433
+ )
2434
+ ),
2435
+ updateTopic: (topicId, input) => write(
2436
+ () => id(
2437
+ api.patch(`/topics/${topicId}`, {
2438
+ name: input.name,
2439
+ description: input.description ?? void 0,
2440
+ visibility: input.visibility
2441
+ })
2442
+ )
2443
+ ),
2444
+ deleteTopic: (topicId) => write(() => id(api.delete(`/topics/${topicId}`))),
2445
+ createSegment: (input) => write(
2446
+ () => id(
2447
+ api.post("/segments", {
2448
+ name: input.name,
2449
+ ...input.filter != null ? { filter: input.filter } : {}
2450
+ })
2451
+ )
2452
+ ),
2453
+ /** `filter: null` clears the saved filter (manual membership only). */
2454
+ updateSegment: (segmentId, input) => write(
2455
+ () => id(
2456
+ api.patch(`/segments/${segmentId}`, {
2457
+ name: input.name,
2458
+ ...input.filter !== void 0 ? { filter: input.filter } : {}
2459
+ })
2460
+ )
2461
+ ),
2462
+ deleteSegment: (segmentId) => write(() => id(api.delete(`/segments/${segmentId}`))),
2463
+ createDomain: (input) => write(
2464
+ () => withRecords(
2465
+ api.post("/domains", {
2466
+ name: input.name,
2467
+ custom_return_path: input.customReturnPath ?? void 0
2468
+ })
2469
+ )
2470
+ ),
2471
+ updateDomainTracking: (domainId, input) => write(
2472
+ () => withRecords(
2473
+ api.patch(`/domains/${domainId}`, {
2474
+ open_tracking: input.openTracking,
2475
+ click_tracking: input.clickTracking,
2476
+ tracking_subdomain: input.trackingSubdomain
2477
+ })
2478
+ )
2479
+ ),
2480
+ deleteDomain: (domainId) => write(() => id(api.delete(`/domains/${domainId}`))),
2481
+ createWebhook: (input) => write(async () => {
2482
+ const { body } = await api.post("/webhooks", {
2483
+ endpoint: input.endpoint,
2484
+ events: input.events,
2485
+ signing_secret: input.signingSecret ?? void 0
2486
+ });
2487
+ return { id: body.id, signingSecret: body.signing_secret };
2488
+ }),
2489
+ updateWebhook: (webhookId, input) => write(() => id(api.patch(`/webhooks/${webhookId}`, input))),
2490
+ deleteWebhook: (webhookId) => write(() => id(api.delete(`/webhooks/${webhookId}`))),
2491
+ createTemplate: (input) => write(
2492
+ () => id(
2493
+ api.post("/templates", {
2494
+ name: input.name,
2495
+ alias: input.alias ?? void 0,
2496
+ subject: input.subject ?? void 0,
2497
+ html: input.html,
2498
+ text: input.text ?? void 0
2499
+ })
2500
+ )
2501
+ ),
2502
+ /** `idOrAlias`: the API resolves either. */
2503
+ updateTemplate: (idOrAlias, input) => write(() => id(api.patch(`/templates/${idOrAlias}`, input))),
2504
+ deleteTemplate: (idOrAlias) => write(() => id(api.delete(`/templates/${idOrAlias}`))),
2505
+ /** Always a draft; sending stays a deliberate act in the dashboard. */
2506
+ createBroadcast: (input) => write(
2507
+ () => id(
2508
+ api.post("/broadcasts", {
2509
+ name: input.name ?? void 0,
2510
+ from: input.from,
2511
+ subject: input.subject,
2512
+ html: input.html ?? void 0,
2513
+ text: input.text ?? void 0,
2514
+ reply_to: input.replyTo ?? void 0,
2515
+ preview_text: input.previewText ?? void 0,
2516
+ segment_id: input.segmentId ?? void 0,
2517
+ topic_id: input.topicId ?? void 0
2518
+ })
2519
+ )
2520
+ ),
2521
+ deleteBroadcast: (broadcastId) => write(() => id(api.delete(`/broadcasts/${broadcastId}`))),
2522
+ batchContacts,
2523
+ deleteContact: (contactId) => write(async () => ({
2524
+ id: (await api.delete(`/contacts/${contactId}`)).body.contact
2525
+ })),
2526
+ /** Prefer inline `segments` on batch items; this is one request per contact. */
2527
+ addContactsToSegment: async (segmentId, contactIds) => {
2528
+ const added = [];
2529
+ const errors = [];
2530
+ for (const contactId of contactIds) {
2531
+ const result = await write(
2532
+ () => id(api.post(`/contacts/${contactId}/segments/${segmentId}`))
2533
+ );
2534
+ if (result.ok) added.push(result.id);
2535
+ else errors.push({ id: contactId, message: result.message });
2536
+ }
2537
+ return { added, errors };
2538
+ },
2539
+ /** Every suppression id on the target; apply diffs against it so rollback deletes only rows it added. */
2540
+ listSuppressionIds: async () => (await listAll("/suppressions")).map((s) => s.id),
2541
+ addSuppressions: (emails, origin) => suppressionsBatch("/suppressions/batch/add", "emails", emails, { origin }),
2542
+ removeSuppressions: (ids) => suppressionsBatch("/suppressions/batch/remove", "ids", ids)
2543
+ };
2544
+ }
2545
+
2546
+ // src/paths.ts
2547
+ import {
2548
+ appendFileSync,
2549
+ chmodSync,
2550
+ existsSync,
2551
+ lstatSync,
2552
+ mkdirSync,
2553
+ readFileSync,
2554
+ renameSync,
2555
+ unlinkSync,
2556
+ writeFileSync
2557
+ } from "node:fs";
2558
+ import { basename, dirname, join } from "node:path";
2559
+ var STATE_DIR = ".billionsend";
2560
+ function migratePaths(cwd = process.cwd()) {
2561
+ const dir = join(cwd, STATE_DIR);
2562
+ return {
2563
+ dir,
2564
+ state: join(dir, "migrate-state.json"),
2565
+ reportJson: join(dir, "migrate-report.json"),
2566
+ reportMd: join(dir, "migrate-report.md")
2567
+ };
2568
+ }
2569
+ function writePrivate(path2, content) {
2570
+ const dir = dirname(path2);
2571
+ mkdirSync(dir, { recursive: true, mode: 448 });
2572
+ if (basename(dir) === STATE_DIR && lstatSync(dir).isSymbolicLink()) {
2573
+ throw new Error(`${dir} is a symbolic link; remove it and run again.`);
2574
+ }
2575
+ const tmp = `${path2}.tmp`;
2576
+ const options = { mode: 384, flag: "wx" };
2577
+ try {
2578
+ writeFileSync(tmp, content, options);
2579
+ } catch (error) {
2580
+ if (error.code !== "EEXIST") throw error;
2581
+ unlinkSync(tmp);
2582
+ writeFileSync(tmp, content, options);
2583
+ }
2584
+ chmodSync(tmp, 384);
2585
+ renameSync(tmp, path2);
2586
+ }
2587
+ function writePrivateJson(path2, value) {
2588
+ writePrivate(path2, `${JSON.stringify(value, null, 2)}
2589
+ `);
2590
+ }
2591
+ function readJson(path2) {
2592
+ if (!existsSync(path2)) return null;
2593
+ const content = readFileSync(path2, "utf8");
2594
+ try {
2595
+ return JSON.parse(content);
2596
+ } catch {
2597
+ throw new Error(`${path2} is not valid JSON; delete it or pass --fresh to start over.`);
2598
+ }
2599
+ }
2600
+ function ensureGitignored(cwd = process.cwd()) {
2601
+ const path2 = join(cwd, ".gitignore");
2602
+ if (!existsSync(path2)) return false;
2603
+ const content = readFileSync(path2, "utf8");
2604
+ const listed = content.split(/\r?\n/).some((line) => line.trim().replace(/^\/|\/$/g, "") === STATE_DIR);
2605
+ if (listed) return false;
2606
+ const separator = content === "" || content.endsWith("\n") ? "" : "\n";
2607
+ appendFileSync(path2, `${separator}${STATE_DIR}/
2608
+ `);
2609
+ return true;
2610
+ }
2611
+
2612
+ // src/progress.ts
2613
+ var isTty = (stream) => stream.isTTY === true;
2614
+ var longest = (labels) => Math.max(0, ...labels.map((l) => [...l].length));
2615
+ var DEFAULT_PAD = 20;
2616
+ var ZERO = /^0(\/0)?$/;
2617
+ var PACE_WINDOW_MS = 6e4;
2618
+ var PACE_MIN_ITEMS = 10;
2619
+ function createProgress({
2620
+ stream = process.stdout,
2621
+ tty = isTty(stream)
2622
+ } = {}) {
2623
+ let live = null;
2624
+ let pad = DEFAULT_PAD;
2625
+ let valueWidth = VALUE_WIDTH;
2626
+ const row = (mark, label, value) => value === "" ? `${mark} ${label}` : `${mark} ${column([[label.padEnd(pad), value]], valueWidth)[0]}`;
2627
+ const writeAbove = (text, to = stream) => {
2628
+ if (live !== null) stream.write("\r\x1B[2K");
2629
+ to.write(text);
2630
+ if (live !== null) stream.write(live);
2631
+ };
2632
+ const writeLine = (text) => writeAbove(`${text}
2633
+ `);
2634
+ return {
2635
+ line: writeLine,
2636
+ writeAbove,
2637
+ clear() {
2638
+ if (live !== null) stream.write("\r\x1B[2K");
2639
+ live = null;
2640
+ },
2641
+ section(labels, values = []) {
2642
+ pad = longest(labels);
2643
+ valueWidth = Math.max(VALUE_WIDTH, longest(values));
2644
+ },
2645
+ step(label) {
2646
+ let n = 0;
2647
+ let total;
2648
+ let milestone = 0;
2649
+ let finished = false;
2650
+ const counter = () => {
2651
+ if (n === 0 && total === void 0) return "";
2652
+ return `${formatNumber(n)}${total === void 0 ? "" : `/${formatNumber(total)}`}`;
2653
+ };
2654
+ const samples = [];
2655
+ const pace = () => {
2656
+ if (total === void 0 || n >= total) return "";
2657
+ const now = Date.now();
2658
+ samples.push({ at: now, n });
2659
+ while (samples.length > 1 && now - (samples[0]?.at ?? now) > PACE_WINDOW_MS)
2660
+ samples.shift();
2661
+ const first = samples[0];
2662
+ if (first === void 0 || n - first.n < PACE_MIN_ITEMS || now - first.at < 1e3) return "";
2663
+ const rate = (n - first.n) * 1e3 / (now - first.at);
2664
+ const perSecond = rate >= 10 ? String(Math.round(rate)) : rate.toFixed(1);
2665
+ const left = formatDuration((total - n) / rate).replace(/^about /, "");
2666
+ return dim(` \xB7 ${perSecond}/s \xB7 ~${left} left`);
2667
+ };
2668
+ const render = () => {
2669
+ live = `${row(info(SYM.live), label, counter())}${pace()}`;
2670
+ stream.write(`\r\x1B[2K${live}`);
2671
+ };
2672
+ const finish2 = (text) => {
2673
+ finished = true;
2674
+ if (live !== null) stream.write("\r\x1B[2K");
2675
+ live = null;
2676
+ stream.write(`${text}
2677
+ `);
2678
+ };
2679
+ if (tty) render();
2680
+ return {
2681
+ update(value, t) {
2682
+ if (finished) return;
2683
+ n = value;
2684
+ if (t !== void 0) total = t;
2685
+ if (tty) {
2686
+ render();
2687
+ } else if (Math.floor(n / 1e3) > milestone) {
2688
+ milestone = Math.floor(n / 1e3);
2689
+ stream.write(`${row(info(SYM.live), label, counter())}
2690
+ `);
2691
+ }
2692
+ },
2693
+ done(summary) {
2694
+ if (finished) return;
2695
+ const value = summary ?? counter();
2696
+ finish2(ZERO.test(value) ? dim(row(SYM.ok, label, value)) : row(ok(SYM.ok), label, value));
2697
+ },
2698
+ fail(message) {
2699
+ if (!finished) finish2(`${err(SYM.err)} ${label} \u2014 ${message}`);
2700
+ },
2701
+ note(text) {
2702
+ writeLine(`${note(SYM.note)} ${text}`);
2703
+ }
2704
+ };
2705
+ }
2706
+ };
2707
+ }
2708
+ async function countUp(rows, {
2709
+ stream = process.stdout,
2710
+ tty = isTty(stream),
2711
+ ms = 800
2712
+ } = {}) {
2713
+ if (rows.length === 0) return;
2714
+ const width = Math.max(...rows.map((row) => formatNumber(row.value).length));
2715
+ const frame = (t) => `${rows.map(
2716
+ (row) => `${bold(formatNumber(Math.round(row.value * t)).padStart(width))} ${row.label}`
2717
+ ).join("\n")}
2718
+ `;
2719
+ if (!tty) {
2720
+ stream.write(frame(1));
2721
+ return;
2722
+ }
2723
+ const frameMs = 1e3 / 30;
2724
+ const frames = Math.max(1, Math.round(ms / frameMs));
2725
+ for (let i = 1; i <= frames; i++) {
2726
+ const t = i / frames;
2727
+ if (i > 1) stream.write(`\x1B[${rows.length}A`);
2728
+ stream.write(frame(i === frames ? 1 : 1 - (1 - t) ** 3));
2729
+ if (i < frames) await sleep(frameMs);
2730
+ }
2731
+ }
2732
+
2733
+ // src/report.ts
2734
+ var TOP = {
2735
+ id: "scale",
2736
+ label: "Scale 3M",
2737
+ perMonth: 3e6,
2738
+ domains: null,
2739
+ contacts: null
2740
+ };
2741
+ var PLANS = [
2742
+ { id: "free", label: "Free", perMonth: 3e3, domains: 3, contacts: 1e3 },
2743
+ { id: "starter", label: "Starter", perMonth: 3e4, domains: 10, contacts: null },
2744
+ { id: "pro", label: "Pro 60K", perMonth: 6e4, domains: null, contacts: null },
2745
+ { id: "pro", label: "Pro 120K", perMonth: 12e4, domains: null, contacts: null },
2746
+ { id: "scale", label: "Scale 240K", perMonth: 24e4, domains: null, contacts: null },
2747
+ { id: "scale", label: "Scale 600K", perMonth: 6e5, domains: null, contacts: null },
2748
+ { id: "scale", label: "Scale 1.2M", perMonth: 12e5, domains: null, contacts: null },
2749
+ { id: "scale", label: "Scale 1.8M", perMonth: 18e5, domains: null, contacts: null },
2750
+ TOP
2751
+ ];
2752
+ var perMonthText = (n) => n === null ? "unlimited" : `${formatNumber(n)}/month`;
2753
+ var domainsText = (n) => n === null ? "unlimited domains" : pluralize(n, "domain");
2754
+ function buildOffer(usage, snapshot, domains, sourceLabel) {
2755
+ if (usage.plan === null) return null;
2756
+ const sent = snapshot.metrics.emailsLast30Days;
2757
+ const perDay = sent === null ? null : Math.ceil(sent / 30);
2758
+ const included = usage.limits.emailsPerMonth;
2759
+ const current = PLANS.find(
2760
+ (p) => p.id === usage.plan && (included === null || p.perMonth === included)
2761
+ ) ?? {
2762
+ id: usage.plan,
2763
+ label: capitalize(usage.plan),
2764
+ perMonth: included ?? (usage.limits.emailsPerDay === null ? null : usage.limits.emailsPerDay * 30),
2765
+ domains: usage.limits.domains,
2766
+ contacts: usage.limits.contacts
2767
+ };
2768
+ const url = usage.appUrl === null ? CLOUD_BILLING_URL : `${stripTrailingSlashes(usage.appUrl)}/settings/billing`;
2769
+ const short = [];
2770
+ const over = sent !== null && current.perMonth !== null && sent > current.perMonth;
2771
+ const volumeShort = over && !usage.period?.overageEnabled;
2772
+ if (volumeShort) short.push(`${current.label} allows ${perMonthText(current.perMonth)}`);
2773
+ if (current.domains !== null && domains > current.domains) {
2774
+ short.push(
2775
+ `${current.label} allows ${pluralize(current.domains, "domain")}, you have ${domains}`
2776
+ );
2777
+ }
2778
+ const contacts = snapshot.contacts.length;
2779
+ if (current.contacts !== null && contacts > current.contacts) {
2780
+ short.push(
2781
+ `${current.label} allows ${pluralize(current.contacts, "contact")}, you have ${formatNumber(contacts)}`
2782
+ );
2783
+ }
2784
+ if (short.length === 0 && sent === null) return null;
2785
+ const text = [];
2786
+ if (sent !== null) {
2787
+ text.push(
2788
+ `On ${sourceLabel} you sent ${formatNumber(sent)} emails in the last 30 days (~${formatNumber(perDay ?? 0)}/day).`
2789
+ );
2790
+ }
2791
+ let fits = current.id;
2792
+ if (short.length === 0) {
2793
+ text.push(
2794
+ over ? `${current.label} includes ${perMonthText(current.perMonth)}; the rest bills as overage.` : `${current.label} allows ${perMonthText(current.perMonth)}; that covers it.`
2795
+ );
2796
+ } else {
2797
+ const fit = PLANS.find(
2798
+ (p) => (p.perMonth === null || (sent ?? 0) <= p.perMonth) && (p.domains === null || domains <= p.domains) && (p.contacts === null || contacts <= p.contacts)
2799
+ );
2800
+ fits = fit?.id ?? TOP.id;
2801
+ const spec = (p) => `${p.label} (${perMonthText(p.perMonth)}, ${domainsText(p.domains)})`;
2802
+ text.push(
2803
+ `${short.join("; ")}; ${fit ? `${spec(fit)} fits.` : `${spec(TOP)} is the top rung; emails past it bill as overage.`} Upgrade: ${url}`
2804
+ );
2805
+ }
2806
+ return { emailsLast30Days: sent, perDay, domains, plan: current.id, fits, url, text };
2807
+ }
2808
+ function buildReport({
2809
+ plan: plan2,
2810
+ snapshot,
2811
+ outcome,
2812
+ usage,
2813
+ targetState,
2814
+ baseUrl,
2815
+ sourceLabel
2816
+ }) {
2817
+ const dns = Object.entries(outcome.domainRecords).map(([domain, records]) => ({
2818
+ domain,
2819
+ records
2820
+ }));
2821
+ for (const domain of targetState.domains) {
2822
+ if (domain.status === "verified" || domain.name in outcome.domainRecords) continue;
2823
+ if (!snapshot.domains.some((d) => d.name === domain.name)) continue;
2824
+ dns.push({ domain: domain.name, records: domain.records });
2825
+ }
2826
+ const apiKeys = plan2.items.filter((i) => i.resource === "api-keys").map((i) => i.key);
2827
+ const manual = plan2.manual.filter(
2828
+ (m) => !m.title.startsWith("api-keys/") && !m.detail.startsWith("add DNS records")
2829
+ );
2830
+ const failures = outcome.state.failures;
2831
+ const retryable = failures.filter((f) => retryableStatus(f.statusCode)).length;
2832
+ const refused = failures.length - retryable;
2833
+ const done = Object.entries(outcome.counts).filter(([, c]) => c !== void 0 && c.failed === 0 && c.created + c.updated + c.unchanged > 0).map(([resource]) => resource);
2834
+ const left = [
2835
+ ...dns.map((d) => `add DNS records for ${d.domain}`),
2836
+ `set ${plan2.source.toUpperCase()}_BASE_URL=${baseUrl} in your app`,
2837
+ ...apiKeys.length > 0 ? [`create API keys: ${apiKeys.join(", ")}`] : [],
2838
+ ...outcome.ids.length > 0 ? [`replace ${sourceLabel} topic and segment ids in your code (id map below)`] : [],
2839
+ ...manual.length > 0 ? [`review ${pluralize(manual.length, "manual note")}`] : [],
2840
+ ...retryable > 0 ? [`retry ${pluralize(retryable, "failed item")}`] : [],
2841
+ ...refused > 0 ? [`review ${pluralize(refused, "refused item")} (see Failed); re-running won't change that`] : []
2842
+ ];
2843
+ const domains = targetState.domains.length + (outcome.counts.domains?.created ?? 0);
2844
+ return {
2845
+ version: 1,
2846
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2847
+ source: plan2.source,
2848
+ sourceLabel,
2849
+ target: { baseUrl, plan: usage.plan },
2850
+ counts: outcome.counts,
2851
+ enrichment: outcome.enrichment,
2852
+ sourceReadOnly: true,
2853
+ freshWebhookSecrets: outcome.freshSecrets,
2854
+ checklist: { done, left },
2855
+ dns,
2856
+ apiKeys,
2857
+ ids: outcome.ids,
2858
+ manual,
2859
+ failures,
2860
+ offer: buildOffer(usage, snapshot, domains, sourceLabel),
2861
+ trademark: TRADEMARK_NOTICE
2862
+ };
2863
+ }
2864
+ function dnsCards(records) {
2865
+ return records.flatMap((r, i) => [
2866
+ ...i > 0 ? [""] : [],
2867
+ ` ${info(r.type)} ${r.name}${r.priority === void 0 ? "" : dim(` priority ${r.priority}`)}`,
2868
+ ` ${bold(r.value)}`
2869
+ ]);
2870
+ }
2871
+ function cutoverReadyLines(source, baseUrl, domainRecords) {
2872
+ const lines = [
2873
+ "",
2874
+ heading("Cutover ready"),
2875
+ "Everything but the per-contact enrichment is on BillionSend: transactional sending can move now.",
2876
+ "Topic opt-outs and properties land in the enrichment passes below; hold topic sends and broadcasts until they finish.",
2877
+ ` ${dim("[")} ${dim("]")} set ${source.toUpperCase()}_BASE_URL=${baseUrl} in your app`
2878
+ ];
2879
+ for (const [domain, records] of Object.entries(domainRecords)) {
2880
+ lines.push("", `DNS records for ${domain}:`, ...dnsCards(records));
2881
+ }
2882
+ return lines;
2883
+ }
2884
+ function idRows(ids) {
2885
+ return ids.flatMap((m) => [
2886
+ ` ${m.resource}/${m.name}`,
2887
+ ` ${dim(shortId(m.sourceId))} \u2192 ${bold(m.targetId)}`
2888
+ ]);
2889
+ }
2890
+ function manualRows(manual) {
2891
+ const items = manual.map(({ title, detail }) => {
2892
+ const slash = title.indexOf("/");
2893
+ return {
2894
+ resource: title.slice(0, slash),
2895
+ action: "manual",
2896
+ key: title.slice(slash + 1),
2897
+ detail
2898
+ };
2899
+ });
2900
+ return groupPlanItems(items).flatMap(
2901
+ (g) => g.rows.map((row) => ({
2902
+ title: row.keys === void 0 ? `${g.resource}/${row.name}` : row.name,
2903
+ detail: row.detail ?? "",
2904
+ names: row.keys
2905
+ }))
2906
+ );
2907
+ }
2908
+ var boldNumbers = (text) => text.split(" ").map((word) => word.includes("://") ? word : word.replace(/\d[\d,.]*\d|\d/g, bold)).join(" ");
2909
+ var ITEM = { indent: " ", hanging: " " };
2910
+ var COUNT_LABEL = { enrichment: "contacts enriched" };
2911
+ var orderedCounts = (counts) => RESOURCES.flatMap((resource) => {
2912
+ const c = counts[resource];
2913
+ return c === void 0 ? [] : [[resource, c]];
2914
+ });
2915
+ function countRows(counts, enrichment) {
2916
+ const rows = [];
2917
+ for (const [resource, c] of orderedCounts(counts)) {
2918
+ const name = COUNT_LABEL[resource];
2919
+ if (name !== void 0) {
2920
+ if (c.updated > 0) rows.push({ label: name, value: c.updated });
2921
+ if (resource === "enrichment" && enrichment !== void 0) {
2922
+ rows.push({ label: "with topic subscriptions", value: enrichment.withTopics });
2923
+ rows.push({ label: "with properties", value: enrichment.withProperties });
2924
+ }
2925
+ } else {
2926
+ if (c.created > 0) rows.push({ label: `${resource} created`, value: c.created });
2927
+ if (c.updated > 0) rows.push({ label: `${resource} updated`, value: c.updated });
2928
+ if (c.unchanged > 0) rows.push({ label: `${resource} unchanged`, value: c.unchanged });
2929
+ }
2930
+ if (c.failed > 0) rows.push({ label: `${resource} failed`, value: c.failed });
2931
+ }
2932
+ return rows;
2933
+ }
2934
+ var SYNC_HINT = (source) => `Run \`billionsend migrate --from ${source}\` again right before cutover to sync new contacts.`;
2935
+ async function printSummary(out, raw) {
2936
+ const report = stripControlDeep(raw);
2937
+ const line = (text, opts = ITEM) => {
2938
+ out.write(`${wrapIndent(text, opts)}
2939
+ `);
2940
+ };
2941
+ out.write(`
2942
+ ${heading("Done")}
2943
+
2944
+ `);
2945
+ await countUp(countRows(report.counts, report.enrichment), { stream: out });
2946
+ out.write(`
2947
+ ${dim(`${report.sourceLabel} was only read; nothing there was changed.`)}
2948
+ `);
2949
+ if (report.freshWebhookSecrets.length > 0) {
2950
+ out.write("\nWebhook signing secrets, shown once (they are not saved anywhere):\n");
2951
+ for (const { endpoint, secret } of report.freshWebhookSecrets) {
2952
+ out.write(` ${endpoint} ${bold(secret)}
2953
+ `);
2954
+ }
2955
+ }
2956
+ const { done, left } = report.checklist;
2957
+ out.write(`
2958
+ ${bold(String(done.length))} of ${done.length + left.length} steps done \u2014 left:
2959
+ `);
2960
+ for (const item of left)
2961
+ line(`${dim("[")} ${dim("]")} ${item}`, { indent: " ", hanging: " " });
2962
+ for (const { domain, records } of report.dns) {
2963
+ out.write(`
2964
+ DNS records for ${domain}:
2965
+ `);
2966
+ for (const card of dnsCards(records)) out.write(`${card}
2967
+ `);
2968
+ }
2969
+ if (report.ids.length > 0) {
2970
+ out.write(`
2971
+ Id map (${report.sourceLabel} \u2192 BillionSend; full pairs in migrate-report.md):
2972
+ `);
2973
+ for (const row of idRows(report.ids)) out.write(`${row}
2974
+ `);
2975
+ }
2976
+ if (report.manual.length > 0) {
2977
+ out.write("\nManual notes:\n");
2978
+ for (const { title, detail, names } of manualRows(report.manual)) {
2979
+ line(`${note(SYM.manual)} ${title} \u2014 ${detail}`);
2980
+ if (names !== void 0) line(dim(foldedKeysLine(names)), { indent: " " });
2981
+ }
2982
+ }
2983
+ if (report.failures.length > 0) {
2984
+ out.write("\nFailed:\n");
2985
+ for (const f of report.failures) line(`${err(SYM.err)} ${f.resource}/${f.key} \u2014 ${f.message}`);
2986
+ }
2987
+ out.write(`
2988
+ ${dim(wrapIndent(SYNC_HINT(report.source)))}
2989
+ `);
2990
+ if (report.offer !== null)
2991
+ out.write(`
2992
+ ${wrapIndent(boldNumbers(report.offer.text.join(" ")))}
2993
+ `);
2994
+ }
2995
+ function renderReportMd(raw) {
2996
+ const report = stripControlDeep(raw);
2997
+ const lines = [
2998
+ `# Migration report \u2014 ${report.sourceLabel} \u2192 BillionSend`,
2999
+ "",
3000
+ `Finished ${report.finishedAt} \xB7 target ${report.target.baseUrl}${report.target.plan === null ? "" : ` \xB7 plan ${capitalize(report.target.plan)}`}`,
3001
+ "",
3002
+ "## Numbers",
3003
+ "",
3004
+ "| Resource | Created | Updated | Unchanged | Skipped | Manual | Failed |",
3005
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: |",
3006
+ ...orderedCounts(report.counts).map(
3007
+ ([resource, c]) => `| ${resource} | ${c.created} | ${c.updated} | ${c.unchanged} | ${c.skipped} | ${c.manual} | ${c.failed} |`
3008
+ ),
3009
+ "",
3010
+ `${report.sourceLabel} was only read; nothing there was changed.`,
3011
+ "",
3012
+ "## Checklist",
3013
+ "",
3014
+ ...report.checklist.done.map((step) => `- [x] ${step}`),
3015
+ ...report.checklist.left.map((step) => `- [ ] ${step}`)
3016
+ ];
3017
+ for (const { domain, records } of report.dns) {
3018
+ lines.push(
3019
+ "",
3020
+ `### DNS records for ${domain}`,
3021
+ "",
3022
+ "| Type | Name | Priority | Value |",
3023
+ "| --- | --- | --- | --- |",
3024
+ ...records.map((r) => `| ${r.type} | ${r.name} | ${r.priority ?? ""} | \`${r.value}\` |`)
3025
+ );
3026
+ }
3027
+ if (report.apiKeys.length > 0) {
3028
+ lines.push("", "## API keys to create", "", ...report.apiKeys.map((name) => `- ${name}`));
3029
+ }
3030
+ if (report.ids.length > 0) {
3031
+ lines.push(
3032
+ "",
3033
+ "## Id map",
3034
+ "",
3035
+ `| Resource | Name | ${report.sourceLabel} id | BillionSend id |`,
3036
+ "| --- | --- | --- | --- |",
3037
+ ...report.ids.map(
3038
+ (m) => `| ${m.resource} | ${m.name} | \`${m.sourceId}\` | \`${m.targetId}\` |`
3039
+ )
3040
+ );
3041
+ }
3042
+ if (report.manual.length > 0) {
3043
+ lines.push(
3044
+ "",
3045
+ "## Manual notes",
3046
+ "",
3047
+ ...report.manual.map(({ title, detail }) => `- ${title} \u2014 ${detail}`)
3048
+ );
3049
+ }
3050
+ if (report.failures.length > 0) {
3051
+ lines.push(
3052
+ "",
3053
+ "## Failed",
3054
+ "",
3055
+ ...report.failures.map((f) => `- ${f.resource}/${f.key} \u2014 ${f.message}`)
3056
+ );
3057
+ }
3058
+ lines.push("", SYNC_HINT(report.source));
3059
+ if (report.offer !== null) lines.push("", ...report.offer.text);
3060
+ lines.push("", "---", "", report.trademark, "");
3061
+ return lines.join("\n");
3062
+ }
3063
+ function writeReport(paths, report, extraMd) {
3064
+ const stored = { ...report, freshWebhookSecrets: [] };
3065
+ writePrivateJson(paths.reportJson, stored);
3066
+ const md = renderReportMd(stored);
3067
+ writePrivate(paths.reportMd, md);
3068
+ if (extraMd !== null) writePrivate(extraMd, md);
3069
+ }
3070
+
3071
+ // src/apply.ts
3072
+ var ROLLBACK_ORDER = [
3073
+ "broadcasts",
3074
+ "templates",
3075
+ "webhooks",
3076
+ "contacts",
3077
+ "segments",
3078
+ "topics",
3079
+ "properties",
3080
+ "suppressions",
3081
+ "domains"
3082
+ ];
3083
+ var RESOURCE_LABEL = {
3084
+ properties: "Contact properties",
3085
+ topics: "Topics",
3086
+ segments: "Segments",
3087
+ domains: "Domains",
3088
+ webhooks: "Webhooks",
3089
+ templates: "Templates",
3090
+ contacts: "Contacts",
3091
+ enrichment: "Enrichment",
3092
+ broadcasts: "Broadcasts",
3093
+ suppressions: "Suppressions",
3094
+ "api-keys": "API keys"
3095
+ };
3096
+ var CUTOVER_RESOURCES = ["contacts", "domains", "suppressions"];
3097
+ var ENRICHMENT_LABEL = {
3098
+ topics: "Enrichment \xB7 topics",
3099
+ properties: "Enrichment \xB7 properties"
3100
+ };
3101
+ var emptyCounts = () => ({
3102
+ created: 0,
3103
+ updated: 0,
3104
+ unchanged: 0,
3105
+ skipped: 0,
3106
+ manual: 0,
3107
+ failed: 0
3108
+ });
3109
+ var finish = (step, failed, total) => {
3110
+ if (failed > 0) step.fail(`${formatNumber(failed)} of ${formatNumber(total)} failed`);
3111
+ else step.done();
3112
+ };
3113
+ function enrichmentItem(c, pass1Status, maps, facets = ["properties", "topics"]) {
3114
+ const properties = facets.includes("properties") ? Object.fromEntries(
3115
+ Object.entries(c.properties ?? {}).filter(([key]) => maps.propertyKeys.has(key))
3116
+ ) : {};
3117
+ const topics = facets.includes("topics") ? (c.topics ?? []).flatMap((t) => {
3118
+ const id = maps.topicBySource.get(t.id);
3119
+ if (id === void 0 || pass1Status === "updated" && t.subscription !== "opt_out")
3120
+ return [];
3121
+ return [{ id, subscription: t.subscription }];
3122
+ }) : [];
3123
+ return {
3124
+ email: c.email,
3125
+ ...Object.keys(properties).length > 0 ? { properties } : {},
3126
+ ...topics.length > 0 ? { topics } : {}
3127
+ };
3128
+ }
3129
+ async function applyPlan(input) {
3130
+ const { plan: plan2, snapshot, source, target, state, progress, log } = input;
3131
+ const counts = {};
3132
+ const tally = (resource) => {
3133
+ counts[resource] ??= emptyCounts();
3134
+ return counts[resource];
3135
+ };
3136
+ const created = (resource, id) => {
3137
+ state.created[resource] ??= [];
3138
+ state.created[resource].push(id);
3139
+ tally(resource).created += 1;
3140
+ };
3141
+ const failed = (resource, key, { message, statusCode }) => {
3142
+ state.failures.push({ resource, key, message, statusCode });
3143
+ tally(resource).failed += 1;
3144
+ log.warn(`${resource}/${key}: ${message}`);
3145
+ };
3146
+ const save = () => {
3147
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3148
+ input.save(state);
3149
+ };
3150
+ const outcome = {
3151
+ state,
3152
+ counts,
3153
+ freshSecrets: [],
3154
+ domainRecords: {},
3155
+ ids: [],
3156
+ enrichment: { withProperties: 0, withTopics: 0 }
3157
+ };
3158
+ const topicByName = /* @__PURE__ */ new Map();
3159
+ const topicBySource = /* @__PURE__ */ new Map();
3160
+ const segmentByName = /* @__PURE__ */ new Map();
3161
+ const segmentBySource = /* @__PURE__ */ new Map();
3162
+ const propertyKeys = /* @__PURE__ */ new Set();
3163
+ const registerTopic = (name, id) => {
3164
+ topicByName.set(name, id);
3165
+ const sourceTopic = snapshot.topics.find((t) => t.name === name);
3166
+ if (sourceTopic) topicBySource.set(sourceTopic.id, id);
3167
+ };
3168
+ const registerSegment = (name, id) => {
3169
+ segmentByName.set(name, id);
3170
+ const sourceSegment = snapshot.segments.find((s) => s.name === name);
3171
+ if (sourceSegment) segmentBySource.set(sourceSegment.id, id);
3172
+ };
3173
+ for (const item of plan2.items) {
3174
+ if (item.action === "unchanged") tally(item.resource).unchanged += 1;
3175
+ else if (item.action === "manual") tally(item.resource).manual += 1;
3176
+ else if (item.action === "skip") tally(item.resource).skipped += 1;
3177
+ if (item.targetId === void 0) continue;
3178
+ if (item.resource === "topics") registerTopic(item.key, item.targetId);
3179
+ else if (item.resource === "segments") registerSegment(item.key, item.targetId);
3180
+ else if (item.resource === "properties") propertyKeys.add(item.key);
3181
+ }
3182
+ async function runRows(resource, run) {
3183
+ const items = plan2.items.filter(
3184
+ (i) => i.resource === resource && (i.action === "create" || i.action === "update")
3185
+ );
3186
+ if (items.length === 0) return;
3187
+ const step = progress.step(RESOURCE_LABEL[resource]);
3188
+ let n = 0;
3189
+ let failures = 0;
3190
+ for (const item of items) {
3191
+ const result = await run(item);
3192
+ if (result.ok) {
3193
+ if (item.action === "create") created(resource, result.id);
3194
+ else tally(resource).updated += 1;
3195
+ } else {
3196
+ failed(resource, item.key, { message: result.message, statusCode: result.status });
3197
+ failures += 1;
3198
+ }
3199
+ step.update(++n, items.length);
3200
+ save();
3201
+ }
3202
+ finish(step, failures, items.length);
3203
+ }
3204
+ await runRows("properties", async (item) => {
3205
+ const p = item.payload;
3206
+ const result = await target.createProperty({
3207
+ key: p.key,
3208
+ type: p.type,
3209
+ fallbackValue: p.fallback_value
3210
+ });
3211
+ if (result.ok) propertyKeys.add(p.key);
3212
+ return result;
3213
+ });
3214
+ await runRows("topics", async (item) => {
3215
+ if (item.action === "update") {
3216
+ return target.updateTopic(item.targetId ?? "", item.payload);
3217
+ }
3218
+ const p = item.payload;
3219
+ const result = await target.createTopic({
3220
+ name: p.name,
3221
+ description: p.description,
3222
+ defaultSubscription: p.default_subscription,
3223
+ visibility: p.visibility
3224
+ });
3225
+ if (result.ok) registerTopic(p.name, result.id);
3226
+ return result;
3227
+ });
3228
+ await runRows("segments", async (item) => {
3229
+ if (item.action === "update") {
3230
+ return target.updateSegment(item.targetId ?? "", item.payload);
3231
+ }
3232
+ const p = item.payload;
3233
+ const result = await target.createSegment({ name: p.name, filter: p.filter });
3234
+ if (result.ok) registerSegment(p.name, result.id);
3235
+ return result;
3236
+ });
3237
+ await runRows("domains", async (item) => {
3238
+ const { create, tracking } = item.payload;
3239
+ const result = await target.createDomain({
3240
+ name: create.name,
3241
+ customReturnPath: create.custom_return_path
3242
+ });
3243
+ if (!result.ok) return result;
3244
+ outcome.domainRecords[create.name] = result.records;
3245
+ const patched = await target.updateDomainTracking(result.id, {
3246
+ openTracking: tracking.open_tracking,
3247
+ clickTracking: tracking.click_tracking,
3248
+ trackingSubdomain: tracking.tracking_subdomain
3249
+ });
3250
+ if (patched.ok) outcome.domainRecords[create.name] = patched.records;
3251
+ else
3252
+ failed("domains", create.name, {
3253
+ message: `created, but tracking settings failed: ${patched.message}`,
3254
+ statusCode: patched.status
3255
+ });
3256
+ return result;
3257
+ });
3258
+ await runRows("webhooks", async (item) => {
3259
+ if (item.action === "update") {
3260
+ return target.updateWebhook(
3261
+ item.targetId ?? "",
3262
+ item.payload
3263
+ );
3264
+ }
3265
+ const p = item.payload;
3266
+ const copied = p.signingSecret === "copy" ? snapshot.webhooks.find((w) => w.id === p.sourceId)?.signingSecret ?? null : null;
3267
+ const result = await target.createWebhook({
3268
+ endpoint: p.endpoint,
3269
+ events: p.events,
3270
+ signingSecret: copied
3271
+ });
3272
+ if (result.ok && copied === null) {
3273
+ outcome.freshSecrets.push({ endpoint: p.endpoint, secret: result.signingSecret });
3274
+ }
3275
+ return result;
3276
+ });
3277
+ await runRows(
3278
+ "templates",
3279
+ (item) => item.action === "update" ? target.updateTemplate(
3280
+ item.targetId ?? "",
3281
+ item.payload
3282
+ ) : target.createTemplate(item.payload)
3283
+ );
3284
+ const pass1 = /* @__PURE__ */ new Map();
3285
+ if (plan2.items.some((i) => i.resource === "contacts") && snapshot.contacts.length > 0) {
3286
+ const step = progress.step(RESOURCE_LABEL.contacts);
3287
+ const membership = /* @__PURE__ */ new Map();
3288
+ for (const segment of snapshot.segments) {
3289
+ const id = segmentBySource.get(segment.id);
3290
+ if (id === void 0) continue;
3291
+ for (const email of segment.memberEmails) {
3292
+ const key = email.toLowerCase();
3293
+ const list = membership.get(key) ?? [];
3294
+ list.push({ id });
3295
+ membership.set(key, list);
3296
+ }
3297
+ }
3298
+ const total = snapshot.contacts.length;
3299
+ const cursor = state.progress.contactsCursor ?? null;
3300
+ let done = cursor === null ? 0 : snapshot.contacts.findIndex((c) => c.id === cursor) + 1;
3301
+ if (done > 0) step.note(`resuming after ${formatNumber(done)} contacts done in an earlier run`);
3302
+ step.update(done, total);
3303
+ for (const slice of chunk(snapshot.contacts.slice(done), BATCH_MAX)) {
3304
+ const items = slice.map(
3305
+ (c) => ({
3306
+ email: c.email,
3307
+ first_name: c.firstName ?? void 0,
3308
+ last_name: c.lastName ?? void 0,
3309
+ unsubscribed: c.unsubscribed,
3310
+ segments: membership.get(c.email.toLowerCase())
3311
+ })
3312
+ );
3313
+ const out = await target.batchContacts(items, { onConflict: input.onConflict });
3314
+ for (const row of out.data) {
3315
+ const contact = slice[row.index];
3316
+ if (contact === void 0) continue;
3317
+ pass1.set(contact.email.toLowerCase(), row.status);
3318
+ if (row.status === "created") created("contacts", row.id);
3319
+ else tally("contacts")[row.status] += 1;
3320
+ }
3321
+ for (const error of out.errors) {
3322
+ const contact = slice[error.index];
3323
+ pass1.set(contact?.email.toLowerCase() ?? "", "failed");
3324
+ failed("contacts", contact?.email ?? `#${error.index}`, error);
3325
+ }
3326
+ done += slice.length;
3327
+ state.progress.contactsCursor = slice.at(-1)?.id ?? null;
3328
+ step.update(done, total);
3329
+ save();
3330
+ }
3331
+ state.progress.contactsCursor = null;
3332
+ save();
3333
+ finish(step, tally("contacts").failed, total);
3334
+ }
3335
+ await runRows("broadcasts", (item) => {
3336
+ const { input: b, segmentName, topicName } = item.payload;
3337
+ return target.createBroadcast({
3338
+ name: b.name,
3339
+ from: b.from,
3340
+ subject: b.subject,
3341
+ html: b.html,
3342
+ text: b.text,
3343
+ replyTo: b.reply_to,
3344
+ previewText: b.preview_text,
3345
+ segmentId: segmentName === null ? null : segmentByName.get(segmentName),
3346
+ topicId: topicName === null ? null : topicByName.get(topicName)
3347
+ });
3348
+ });
3349
+ if (plan2.items.some((i) => i.resource === "suppressions") && snapshot.suppressions.length > 0) {
3350
+ const step = progress.step(RESOURCE_LABEL.suppressions);
3351
+ const existing = new Set(await target.listSuppressionIds());
3352
+ const total = snapshot.suppressions.length;
3353
+ let done = 0;
3354
+ for (const origin of ["bounce", "complaint", "manual"]) {
3355
+ const rows = snapshot.suppressions.filter((s) => s.origin === origin);
3356
+ for (const slice of chunk(rows, BATCH_MAX)) {
3357
+ const out = await target.addSuppressions(
3358
+ slice.map((s) => s.email),
3359
+ origin
3360
+ );
3361
+ for (const id of out.ids) {
3362
+ if (existing.has(id)) {
3363
+ tally("suppressions").unchanged += 1;
3364
+ } else {
3365
+ existing.add(id);
3366
+ created("suppressions", id);
3367
+ }
3368
+ }
3369
+ for (const error of out.errors) {
3370
+ failed("suppressions", slice[error.index]?.email ?? `#${error.index}`, error);
3371
+ }
3372
+ done += slice.length;
3373
+ step.update(done, total);
3374
+ save();
3375
+ }
3376
+ }
3377
+ state.progress.suppressionsDone = true;
3378
+ save();
3379
+ finish(step, tally("suppressions").failed, total);
3380
+ }
3381
+ if (plan2.items.some((i) => i.resource === "enrichment")) {
3382
+ const synced = state.progress.enrichmentCompleted === true;
3383
+ const enrichedIds = /* @__PURE__ */ new Set();
3384
+ const failedIds = /* @__PURE__ */ new Set();
3385
+ const total = snapshot.contacts.length;
3386
+ const passes = [
3387
+ {
3388
+ facet: "topics",
3389
+ ledger: "topicsDone",
3390
+ wanted: snapshot.topics.length > 0 && topicBySource.size > 0,
3391
+ skipped: snapshot.topics.length === 0 ? "no topics on the source" : "topics not migrated"
3392
+ },
3393
+ {
3394
+ facet: "properties",
3395
+ ledger: "enrichmentDone",
3396
+ wanted: snapshot.properties.length > 0 && propertyKeys.size > 0,
3397
+ skipped: snapshot.properties.length === 0 ? "no contact properties on the source" : "contact properties not migrated"
3398
+ }
3399
+ ];
3400
+ if (passes.some((p) => p.wanted)) {
3401
+ const leftOut = CUTOVER_RESOURCES.filter((r) => input.include?.has(r) === false);
3402
+ const lines = leftOut.length === 0 ? cutoverReadyLines(plan2.source, plan2.target.baseUrl, outcome.domainRecords) : [
3403
+ "",
3404
+ dim(
3405
+ `Enrichment follows. This run left out ${leftOut.join(", ")}, so it is not a cutover; run without --only for the cutover-ready checklist.`
3406
+ )
3407
+ ];
3408
+ for (const line of lines) progress.line(line);
3409
+ progress.line("");
3410
+ }
3411
+ for (const pass of passes) {
3412
+ if (!pass.wanted) {
3413
+ progress.line(dim(`${ENRICHMENT_LABEL[pass.facet]}: skipped, ${pass.skipped}`));
3414
+ continue;
3415
+ }
3416
+ const step = progress.step(ENRICHMENT_LABEL[pass.facet]);
3417
+ const doneIds = new Set(state.progress[pass.ledger] ?? []);
3418
+ if (doneIds.size > 0) {
3419
+ step.note(
3420
+ `resuming: skipping ${pluralize(doneIds.size, "contact")} enriched in an earlier run`
3421
+ );
3422
+ }
3423
+ const failedBefore = failedIds.size;
3424
+ let processed = 0;
3425
+ let withValues = 0;
3426
+ let buffer = [];
3427
+ const flush = async () => {
3428
+ const sendable = buffer.filter(
3429
+ (b) => b.item.properties !== void 0 || b.item.topics !== void 0
3430
+ );
3431
+ const failedNow = /* @__PURE__ */ new Set();
3432
+ if (sendable.length > 0) {
3433
+ const out = await target.batchContacts(
3434
+ sendable.map((b) => b.item),
3435
+ { onConflict: "upsert" }
3436
+ );
3437
+ for (const error of out.errors) {
3438
+ const entry = sendable[error.index];
3439
+ if (entry !== void 0) {
3440
+ failedNow.add(entry.id);
3441
+ failedIds.add(entry.id);
3442
+ }
3443
+ failed("enrichment", entry?.item.email ?? `#${error.index}`, error);
3444
+ }
3445
+ for (const row of out.data) if (row.status === "created") created("contacts", row.id);
3446
+ withValues += sendable.length - failedNow.size;
3447
+ for (const b of sendable) if (!failedNow.has(b.id)) enrichedIds.add(b.id);
3448
+ }
3449
+ for (const b of buffer) if (!failedNow.has(b.id)) doneIds.add(b.id);
3450
+ tally("enrichment").updated = enrichedIds.size;
3451
+ tally("enrichment").failed = failedIds.size;
3452
+ state.progress[pass.ledger] = [...doneIds];
3453
+ buffer = [];
3454
+ save();
3455
+ };
3456
+ await source.enrichContacts(snapshot, {
3457
+ alreadyDone: doneIds,
3458
+ facets: [pass.facet],
3459
+ onProgress: (event) => step.update(event.n, event.total),
3460
+ onContact: async (contact) => {
3461
+ const status2 = pass1.get(contact.email.toLowerCase());
3462
+ if (status2 === "failed" || status2 === "skipped") return;
3463
+ processed += 1;
3464
+ const item = enrichmentItem(
3465
+ contact,
3466
+ status2 === "created" || !synced ? "created" : "updated",
3467
+ { propertyKeys, topicBySource },
3468
+ [pass.facet]
3469
+ );
3470
+ if (status2 === void 0) {
3471
+ item.unsubscribed = contact.unsubscribed;
3472
+ item.first_name = contact.firstName ?? void 0;
3473
+ item.last_name = contact.lastName ?? void 0;
3474
+ }
3475
+ buffer.push({ id: contact.id, item });
3476
+ if (buffer.length >= BATCH_MAX) await flush();
3477
+ }
3478
+ });
3479
+ await flush();
3480
+ const noun = pass.facet === "properties" ? "properties" : "topic subscriptions";
3481
+ if (pass.facet === "properties") outcome.enrichment.withProperties = withValues;
3482
+ else outcome.enrichment.withTopics = withValues;
3483
+ if (pass.facet === "properties" && processed > 0 && withValues === 0) {
3484
+ const message = "no contact carried a property value \u2014 check the source shape";
3485
+ step.note(warn(message));
3486
+ log.warn(message);
3487
+ }
3488
+ const failedInPass = failedIds.size - failedBefore;
3489
+ if (failedInPass > 0) {
3490
+ step.fail(`${formatNumber(failedInPass)} of ${formatNumber(total)} failed`);
3491
+ } else {
3492
+ step.done(`${formatNumber(total)} \xB7 ${formatNumber(withValues)} with ${noun}`);
3493
+ }
3494
+ }
3495
+ state.progress.enrichmentCompleted = true;
3496
+ if (tally("enrichment").failed === 0) {
3497
+ delete state.progress.enrichmentDone;
3498
+ delete state.progress.topicsDone;
3499
+ state.progress.contactsCursor = null;
3500
+ }
3501
+ save();
3502
+ }
3503
+ const mapping = (resource, rows, bySource) => rows.flatMap((row) => {
3504
+ const targetId = bySource.get(row.id);
3505
+ return targetId === void 0 ? [] : [{ resource, name: row.name, sourceId: row.id, targetId }];
3506
+ });
3507
+ outcome.ids = [
3508
+ ...mapping("topics", snapshot.topics, topicBySource),
3509
+ ...mapping("segments", snapshot.segments, segmentBySource)
3510
+ ];
3511
+ return outcome;
3512
+ }
3513
+
3514
+ // src/session.ts
3515
+ var TARGET_RPS = 10;
3516
+ function printHeader(ctx, text) {
3517
+ const { out } = ctx;
3518
+ const tier = pickBannerTier(out.columns ?? 0, out.isTTY === true);
3519
+ if (tier === "plain") {
3520
+ out.write(`${wrapIndent(`billionsend ${VERSION} \u2014 ${text}`, { hanging: " " })}
3521
+
3522
+ `);
3523
+ return;
3524
+ }
3525
+ for (const line of banner(tier)) out.write(`${line}
3526
+ `);
3527
+ out.write(`
3528
+ ${dim(wrapIndent(text))}
3529
+
3530
+ `);
3531
+ }
3532
+ async function resolveKey(ctx, input, { label, envName, flag }) {
3533
+ if (input.value !== null) return input.value;
3534
+ if (input.source === "stdin") {
3535
+ const line = (await ctx.rl.question("")).trim();
3536
+ if (line === "") throw new Error(`No ${label} arrived on stdin (${flag}-stdin).`);
3537
+ return line;
3538
+ }
3539
+ if (ctx.config.nonInteractive) {
3540
+ throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3541
+ }
3542
+ const key = await secretPrompt(ctx.rl, { label: `${label} (full access)` });
3543
+ if (key === "") throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3544
+ return key;
3545
+ }
3546
+ async function connectSource(ctx, id) {
3547
+ const provider = providers[id];
3548
+ const envName = sourceKeyEnv(id);
3549
+ const baseUrl = provider.baseUrl(ctx.env);
3550
+ if (new URL(baseUrl).host === new URL(ctx.config.toUrl).host) {
3551
+ throw new Error(
3552
+ `${provider.label} API URL ${baseUrl} is the BillionSend host; the ${provider.label} key would be sent there. Unset ${RESEND_BASE_URL_ENV}, or point ${TARGET_URL_ENV} / --to-url at your BillionSend instance.`
3553
+ );
3554
+ }
3555
+ const token = await resolveKey(ctx, ctx.config.fromKey, {
3556
+ label: `${provider.label} API key`,
3557
+ envName,
3558
+ flag: "--from-key"
3559
+ });
3560
+ const http = createHttp({
3561
+ baseUrl,
3562
+ token,
3563
+ userAgent: USER_AGENT,
3564
+ rps: ctx.config.rps,
3565
+ log: ctx.log,
3566
+ name: provider.label,
3567
+ readOnly: true,
3568
+ fetch: ctx.fetch
3569
+ });
3570
+ const source = provider.create(http, ctx.log);
3571
+ try {
3572
+ await source.probe();
3573
+ } catch (error) {
3574
+ if (error instanceof AuthError) {
3575
+ throw new Error(
3576
+ `${provider.label} rejected the API key (${error.status}). Check ${envName}: it must be a full-access key of the account to migrate.`
3577
+ );
3578
+ }
3579
+ throw error;
3580
+ }
3581
+ const limit = http.rateLimit;
3582
+ let rps = ctx.config.rps;
3583
+ if (!ctx.config.rpsGiven && limit !== null && limit > MAX_RPS) rps = limit - RPS_HEADROOM;
3584
+ if (rps !== ctx.config.rps) {
3585
+ http.setRps(rps);
3586
+ ctx.config.rps = rps;
3587
+ }
3588
+ if (limit !== null && rps > limit) {
3589
+ ctx.log.warn(
3590
+ `--rps ${rps} is above the ${provider.label} team limit of ${limit} req/s. The limit is shared with your production sending, so both sides will see 429s.`
3591
+ );
3592
+ } else if (limit === null && rps > MAX_RPS) {
3593
+ ctx.log.warn(
3594
+ `--rps ${rps} is above ${provider.label}'s default team limit of ${MAX_RPS} req/s and no limit header was seen. Go past ${MAX_RPS} only after ${provider.label} raised your limit.`
3595
+ );
3596
+ }
3597
+ const host = baseUrl === provider.baseUrl({}) ? "" : ` (${baseUrl})`;
3598
+ const rate = limit === null ? `${rps} req/s` : `limit ${limit} req/s, using ${rps}`;
3599
+ ctx.out.write(
3600
+ `${ok(SYM.ok)} ${provider.label} ${dim("\xB7")} connected${host} ${dim("\xB7")} ${rate}
3601
+ `
3602
+ );
3603
+ return { provider, source };
3604
+ }
3605
+ async function connectTarget(ctx) {
3606
+ const baseUrl = ctx.config.toUrl;
3607
+ const token = await resolveKey(ctx, ctx.config.toKey, {
3608
+ label: "BillionSend API key",
3609
+ envName: TARGET_KEY_ENV,
3610
+ flag: "--to-key"
3611
+ });
3612
+ const http = createHttp({
3613
+ baseUrl,
3614
+ token,
3615
+ userAgent: USER_AGENT,
3616
+ rps: TARGET_RPS,
3617
+ log: ctx.log,
3618
+ name: "BillionSend",
3619
+ fetch: ctx.fetch
3620
+ });
3621
+ const target = createBillionSendTarget(http, ctx.log, baseUrl);
3622
+ const usage = await target.probe();
3623
+ ctx.out.write(
3624
+ `${ok(SYM.ok)} BillionSend Cloud ${dim("\xB7")} plan ${capitalize(usage.plan ?? "unknown")}
3625
+ `
3626
+ );
3627
+ return { target, usage, baseUrl };
3628
+ }
3629
+ function bridgeProgress(progress) {
3630
+ let current = null;
3631
+ return (event) => {
3632
+ if (current === null || current.label !== event.label) {
3633
+ current = { label: event.label, step: progress.step(event.label) };
3634
+ }
3635
+ current.step.update(event.n, event.total);
3636
+ if (event.done) {
3637
+ current.step.done(formatNumber(event.n));
3638
+ current = null;
3639
+ }
3640
+ };
3641
+ }
3642
+ function includeSet(config) {
3643
+ const set = new Set(config.only ?? RESOURCES);
3644
+ for (const resource of config.skip) set.delete(resource);
3645
+ return set;
3646
+ }
3647
+
3648
+ // src/commands/migrate.ts
3649
+ function pickerOption(resource, snapshot, includeSent) {
3650
+ const n = (count, noun) => count === 0 ? null : { label: `${noun} ${formatNumber(count)}` };
3651
+ switch (resource) {
3652
+ case "domains":
3653
+ return n(snapshot.domains.length, "Domains");
3654
+ case "properties":
3655
+ return n(snapshot.properties.length, "Contact properties");
3656
+ case "topics":
3657
+ return n(snapshot.topics.length, "Topics");
3658
+ case "segments":
3659
+ return n(snapshot.segments.length, "Segments");
3660
+ case "contacts":
3661
+ return n(snapshot.contacts.length, "Contacts");
3662
+ case "enrichment":
3663
+ return snapshot.contacts.length > 0 && (snapshot.properties.length > 0 || snapshot.topics.length > 0) ? {
3664
+ label: `Enrichment ${formatNumber(snapshot.contacts.length)}`,
3665
+ hint: "properties and topic subscriptions, read per contact"
3666
+ } : null;
3667
+ case "broadcasts": {
3668
+ const sent = snapshot.broadcasts.filter((b) => b.status === "sent").length;
3669
+ const drafts = snapshot.broadcasts.length - sent;
3670
+ if (snapshot.broadcasts.length === 0) return null;
3671
+ return {
3672
+ label: `Broadcasts ${pluralize(drafts, "draft")} \xB7 ${formatNumber(sent)} sent${includeSent || sent === 0 ? "" : " (not selected)"}`,
3673
+ ...sent > 0 && !includeSent ? { hint: "--include-sent imports sent broadcasts as drafts" } : {}
3674
+ };
3675
+ }
3676
+ case "templates":
3677
+ return n(snapshot.templates.length, "Templates");
3678
+ case "webhooks":
3679
+ return n(snapshot.webhooks.length, "Webhooks");
3680
+ case "suppressions":
3681
+ return n(snapshot.suppressions.length, "Suppressions");
3682
+ case "api-keys":
3683
+ return snapshot.apiKeys.length === 0 ? null : {
3684
+ label: `API keys ${formatNumber(snapshot.apiKeys.length)}`,
3685
+ hint: "names only, listed as a to-do"
3686
+ };
3687
+ }
3688
+ }
3689
+ async function pickResources(ctx, snapshot, include) {
3690
+ const options = RESOURCES.filter((r) => include.has(r)).flatMap((resource) => {
3691
+ const option = pickerOption(resource, snapshot, ctx.config.includeSent);
3692
+ return option === null ? [] : [{ value: resource, ...option, checked: true }];
3693
+ });
3694
+ if (options.length === 0) return /* @__PURE__ */ new Set();
3695
+ const values = await multiSelectPrompt(ctx.rl, { label: "Resources", options });
3696
+ return new Set(values);
3697
+ }
3698
+ async function resolveDomainLimit(ctx, plan2, target) {
3699
+ const limit = target.usage.limits.domains;
3700
+ const creates = plan2.items.filter((i) => i.resource === "domains" && i.action === "create");
3701
+ if (limit === null || creates.length === 0 || target.domains.length + creates.length <= limit) {
3702
+ return plan2;
3703
+ }
3704
+ const allowed = Math.max(0, limit - target.domains.length);
3705
+ const first = allowed === 0 ? "Skip the domains and list them as manual" : `Create the first ${pluralize(allowed, "domain")} and list the rest as manual`;
3706
+ let choice;
3707
+ if (ctx.config.command === "plan") {
3708
+ choice = "first";
3709
+ } else if (ctx.config.nonInteractive) {
3710
+ choice = "first";
3711
+ } else {
3712
+ choice = await selectPrompt(ctx.rl, {
3713
+ label: "Domain limit",
3714
+ options: [
3715
+ { value: "first", label: first },
3716
+ { value: "stop", label: "Stop" }
3717
+ ]
3718
+ });
3719
+ }
3720
+ if (choice !== "first") throw new Error("Stopped at the domain limit; nothing was applied.");
3721
+ ctx.out.write(
3722
+ `${formatNumber(allowed)} of ${formatNumber(creates.length)} domains will be created; the rest are listed as manual.
3723
+ `
3724
+ );
3725
+ return capDomainCreates(plan2, allowed);
3726
+ }
3727
+ async function prepare(ctx, providerId) {
3728
+ const { config, out } = ctx;
3729
+ const label = providers[providerId].label;
3730
+ printHeader(
3731
+ ctx,
3732
+ `Moves your ${label} account into BillionSend. Reads only; nothing on ${label} is changed.`
3733
+ );
3734
+ const { provider, source } = await connectSource(ctx, providerId);
3735
+ const { target, usage, baseUrl } = await connectTarget(ctx);
3736
+ const include = includeSet(config);
3737
+ out.write(`
3738
+ ${heading(`Reading ${label}`)}
3739
+ `);
3740
+ ctx.progress.section([...[...include].map((r) => RESOURCE_LABEL[r]), "BillionSend"]);
3741
+ const snapshot = await source.readShallow({
3742
+ include,
3743
+ includeSent: config.includeSent,
3744
+ onProgress: bridgeProgress(ctx.progress)
3745
+ });
3746
+ snapshot.metrics = await source.readMetrics();
3747
+ const step = ctx.progress.step("BillionSend");
3748
+ const targetState = await target.readState();
3749
+ step.done("current state read");
3750
+ const chosen = config.nonInteractive || config.only !== null || config.skip.length > 0 ? include : await pickResources(ctx, snapshot, include);
3751
+ let plan2 = buildPlan({
3752
+ snapshot,
3753
+ target: targetState,
3754
+ options: {
3755
+ include: chosen,
3756
+ includeSent: config.includeSent,
3757
+ freshWebhookSecrets: config.freshWebhookSecrets,
3758
+ rps: config.rps,
3759
+ sourceRequestsSpent: source.requests,
3760
+ baseUrl
3761
+ }
3762
+ });
3763
+ out.write(`
3764
+ ${heading("Plan")}
3765
+ `);
3766
+ out.write(renderPlan(plan2));
3767
+ plan2 = await resolveDomainLimit(ctx, plan2, targetState);
3768
+ return { provider, source, target, usage, baseUrl, snapshot, targetState, plan: plan2, include: chosen };
3769
+ }
3770
+ var hasChanges = (plan2) => plan2.counts.create + plan2.counts.update > 0;
3771
+ function newState(baseUrl, hash) {
3772
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3773
+ return {
3774
+ version: 1,
3775
+ startedAt: now,
3776
+ updatedAt: now,
3777
+ planHash: hash,
3778
+ target: { baseUrl },
3779
+ created: {},
3780
+ progress: {},
3781
+ failures: []
3782
+ };
3783
+ }
3784
+ function loadState(ctx, baseUrl, hash) {
3785
+ const paths = migratePaths(ctx.cwd);
3786
+ const existing = readJson(paths.state);
3787
+ if (existing === null) return newState(baseUrl, hash);
3788
+ if (existing.target.baseUrl !== baseUrl) {
3789
+ if (ctx.config.fresh) return newState(baseUrl, hash);
3790
+ throw new Error(
3791
+ `${paths.state} belongs to ${existing.target.baseUrl}; run from another directory or pass --fresh.`
3792
+ );
3793
+ }
3794
+ if (ctx.config.fresh) existing.progress = {};
3795
+ if (existing.planHash !== hash) existing.progress.contactsCursor = null;
3796
+ existing.planHash = hash;
3797
+ existing.failures = [];
3798
+ return existing;
3799
+ }
3800
+ function idleOutcome(plan2, state) {
3801
+ const counts = {};
3802
+ for (const item of plan2.items) {
3803
+ const c = counts[item.resource] ?? {
3804
+ created: 0,
3805
+ updated: 0,
3806
+ unchanged: 0,
3807
+ skipped: 0,
3808
+ manual: 0,
3809
+ failed: 0
3810
+ };
3811
+ counts[item.resource] = c;
3812
+ if (item.action === "unchanged") c.unchanged += 1;
3813
+ else if (item.action === "manual") c.manual += 1;
3814
+ else if (item.action === "skip") c.skipped += 1;
3815
+ }
3816
+ return {
3817
+ state,
3818
+ counts,
3819
+ freshSecrets: [],
3820
+ domainRecords: {},
3821
+ ids: [],
3822
+ enrichment: { withProperties: 0, withTopics: 0 }
3823
+ };
3824
+ }
3825
+ var runReport = (prepared, outcome) => buildReport({
3826
+ plan: prepared.plan,
3827
+ snapshot: prepared.snapshot,
3828
+ outcome,
3829
+ usage: prepared.usage,
3830
+ targetState: prepared.targetState,
3831
+ baseUrl: prepared.baseUrl,
3832
+ sourceLabel: prepared.provider.label
3833
+ });
3834
+ async function execute(ctx, prepared) {
3835
+ const { config, out } = ctx;
3836
+ const { plan: plan2 } = prepared;
3837
+ const hash = planHash(plan2);
3838
+ if (!hasChanges(plan2)) {
3839
+ out.write("Nothing to do.\n");
3840
+ if (config.json) {
3841
+ const idle = runReport(prepared, idleOutcome(plan2, newState(prepared.baseUrl, hash)));
3842
+ ctx.stdout.write(`${JSON.stringify(idle, null, 2)}
3843
+ `);
3844
+ }
3845
+ return 0;
3846
+ }
3847
+ if (!config.yes && !await confirmPrompt(ctx.rl, { label: "Apply this plan?" })) {
3848
+ out.write("Nothing applied.\n");
3849
+ return 0;
3850
+ }
3851
+ const paths = migratePaths(ctx.cwd);
3852
+ const state = loadState(ctx, prepared.baseUrl, hash);
3853
+ const save = (s) => writePrivateJson(paths.state, s);
3854
+ save(state);
3855
+ if (ensureGitignored(ctx.cwd)) out.write("Added .billionsend/ to .gitignore.\n");
3856
+ out.write(`
3857
+ ${heading("Applying")}
3858
+ `);
3859
+ const totals = /* @__PURE__ */ new Map();
3860
+ for (const i of plan2.items) {
3861
+ if (i.action === "create" || i.action === "update")
3862
+ totals.set(i.resource, (totals.get(i.resource) ?? 0) + (i.count ?? 1));
3863
+ }
3864
+ ctx.progress.section(
3865
+ [...totals.keys()].flatMap(
3866
+ (r) => r === "enrichment" ? Object.values(ENRICHMENT_LABEL) : [RESOURCE_LABEL[r]]
3867
+ ),
3868
+ [...totals.values()].map((n) => `${formatNumber(n)}/${formatNumber(n)}`)
3869
+ );
3870
+ const outcome = await applyPlan({
3871
+ plan: plan2,
3872
+ include: prepared.include,
3873
+ snapshot: prepared.snapshot,
3874
+ source: prepared.source,
3875
+ target: prepared.target,
3876
+ state,
3877
+ onConflict: config.onConflict,
3878
+ progress: ctx.progress,
3879
+ log: ctx.log,
3880
+ save
3881
+ });
3882
+ const report = runReport(prepared, outcome);
3883
+ writeReport(paths, report, config.report);
3884
+ if (config.json) {
3885
+ ctx.stdout.write(`${JSON.stringify(report, null, 2)}
3886
+ `);
3887
+ } else {
3888
+ await printSummary(out, report);
3889
+ }
3890
+ out.write(`
3891
+ Report: ${paths.reportMd} (and .json)
3892
+ `);
3893
+ return outcome.state.failures.length > 0 ? 3 : 0;
3894
+ }
3895
+ async function migrate(ctx) {
3896
+ const providerId = ctx.config.from ?? "resend";
3897
+ return execute(ctx, await prepare(ctx, providerId));
3898
+ }
3899
+
3900
+ // src/commands/apply.ts
3901
+ var MAX_PLAN_AGE_MS = 36e5;
3902
+ async function apply(ctx) {
3903
+ const { config, out } = ctx;
3904
+ if (config.planFile === null) return migrate(ctx);
3905
+ let text;
3906
+ try {
3907
+ text = readFileSync2(config.planFile, "utf8");
3908
+ } catch (error) {
3909
+ if (error.code !== "ENOENT") throw error;
3910
+ throw new Error(
3911
+ `plan file ${config.planFile} not found; run \`migrate plan --from ${config.from ?? "resend"} --out ${config.planFile}\` first`
3912
+ );
3913
+ }
3914
+ const saved = parsePlan(text);
3915
+ const ageMs = Date.now() - Date.parse(saved.createdAt);
3916
+ const stale = !(ageMs < MAX_PLAN_AGE_MS);
3917
+ if (stale && config.nonInteractive) {
3918
+ throw new Error(
3919
+ `${config.planFile} is ${formatDuration(ageMs / 1e3)} old. Re-run \`migrate plan --out\`, or apply without a file.`
3920
+ );
3921
+ }
3922
+ if (stale) {
3923
+ out.write(
3924
+ `${config.planFile} is ${formatDuration(ageMs / 1e3)} old; reading the source again to build a current plan.
3925
+ `
3926
+ );
3927
+ }
3928
+ const prepared = await prepare(ctx, config.from ?? saved.source);
3929
+ if (saved.target.baseUrl !== prepared.baseUrl) {
3930
+ throw new Error(
3931
+ `${config.planFile} was made for ${saved.target.baseUrl}; connected to ${prepared.baseUrl}.`
3932
+ );
3933
+ }
3934
+ const reasons = [];
3935
+ if (stale) reasons.push(`is ${formatDuration(ageMs / 1e3)} old`);
3936
+ if (planHash(saved) !== planHash(prepared.plan)) reasons.push("differs from the plan just built");
3937
+ if (reasons.length > 0) {
3938
+ const notice = `${config.planFile} ${reasons.join(" and ")}; the plan above is current.`;
3939
+ if (config.nonInteractive) {
3940
+ throw new Error(`${notice} Re-run \`migrate plan --out\`, or apply without a file.`);
3941
+ }
3942
+ out.write(`${notice}
3943
+ `);
3944
+ if (!await confirmPrompt(ctx.rl, { label: "Apply the current plan instead?" })) {
3945
+ out.write("Nothing applied.\n");
3946
+ return 0;
3947
+ }
3948
+ }
3949
+ return execute(ctx, prepared);
3950
+ }
3951
+
3952
+ // src/commands/plan.ts
3953
+ import { writeFileSync as writeFileSync2 } from "node:fs";
3954
+ async function plan(ctx) {
3955
+ const prepared = await prepare(ctx, ctx.config.from ?? "resend");
3956
+ const json = serializePlan(prepared.plan);
3957
+ if (ctx.config.out !== null) {
3958
+ writeFileSync2(ctx.config.out, json);
3959
+ ctx.out.write(`Plan written to ${ctx.config.out}
3960
+ `);
3961
+ }
3962
+ if (ctx.config.json) ctx.stdout.write(json);
3963
+ return hasChanges(prepared.plan) ? 2 : 0;
3964
+ }
3965
+
3966
+ // src/commands/rollback.ts
3967
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3968
+ var SAVE_EVERY = 100;
3969
+ var HEADER_TEXT = "Deletes what an earlier run created on your BillionSend instance; nothing on Resend is touched.";
3970
+ var DELETE = {
3971
+ broadcasts: (t, id) => t.deleteBroadcast(id),
3972
+ templates: (t, id) => t.deleteTemplate(id),
3973
+ webhooks: (t, id) => t.deleteWebhook(id),
3974
+ contacts: (t, id) => t.deleteContact(id),
3975
+ segments: (t, id) => t.deleteSegment(id),
3976
+ topics: (t, id) => t.deleteTopic(id),
3977
+ properties: (t, id) => t.deleteProperty(id),
3978
+ domains: (t, id) => t.deleteDomain(id)
3979
+ };
3980
+ async function rollback(ctx) {
3981
+ const { config, out } = ctx;
3982
+ const paths = migratePaths(ctx.cwd);
3983
+ const state = readJson(paths.state);
3984
+ const pending = ROLLBACK_ORDER.filter((r) => (state?.created[r]?.length ?? 0) > 0);
3985
+ const deleted = {};
3986
+ const emitJson = (failures) => {
3987
+ if (config.json) ctx.stdout.write(`${JSON.stringify({ deleted, failures })}
3988
+ `);
3989
+ };
3990
+ if (state === null || pending.length === 0) {
3991
+ out.write(`Nothing to roll back: no ids created by this tool in ${STATE_DIR}/.
3992
+ `);
3993
+ emitJson([]);
3994
+ return 0;
3995
+ }
3996
+ for (const resource of pending) {
3997
+ const bad = (state.created[resource] ?? []).filter((id) => !UUID.test(id)).length;
3998
+ if (bad > 0) {
3999
+ throw new Error(
4000
+ `${paths.state} lists ${pluralize(bad, "id")} under "${resource}" that are not BillionSend ids; the file was edited outside this tool. Fix or delete it, then run again.`
4001
+ );
4002
+ }
4003
+ }
4004
+ printHeader(ctx, HEADER_TEXT);
4005
+ const { target, baseUrl } = await connectTarget(ctx);
4006
+ if (state.target.baseUrl !== baseUrl) {
4007
+ throw new Error(`${paths.state} belongs to ${state.target.baseUrl}; connected to ${baseUrl}.`);
4008
+ }
4009
+ out.write("\nThis deletes only what this tool created; rows it merely updated stay:\n");
4010
+ let requests = 0;
4011
+ for (const resource of pending) {
4012
+ const ids = state.created[resource] ?? [];
4013
+ requests += resource === "suppressions" ? Math.ceil(ids.length / 1e3) : ids.length;
4014
+ out.write(
4015
+ ` ${bold(formatNumber(ids.length).padStart(8))} ${RESOURCE_LABEL[resource]}${resource === "contacts" ? " (one request each)" : ""}
4016
+ `
4017
+ );
4018
+ const rest = ids.length - 3;
4019
+ out.write(
4020
+ `${dim(` ${ids.slice(0, 3).join(", ")}${rest > 0 ? ` \u2026 and ${formatNumber(rest)} more` : ""}`)}
4021
+ `
4022
+ );
4023
+ }
4024
+ out.write(`${capitalize(formatDuration(requests / TARGET_RPS))} at ${TARGET_RPS} req/s.
4025
+
4026
+ `);
4027
+ if (!config.yes) {
4028
+ if (config.nonInteractive) throw new Error("Rollback needs --yes in non-interactive mode.");
4029
+ if (!await confirmPrompt(ctx.rl, { label: "Delete these from your BillionSend instance?" })) {
4030
+ out.write("Nothing deleted.\n");
4031
+ emitJson([]);
4032
+ return 0;
4033
+ }
4034
+ }
4035
+ state.failures = [];
4036
+ ctx.progress.section(
4037
+ pending.map((r) => RESOURCE_LABEL[r]),
4038
+ pending.map((r) => {
4039
+ const n = formatNumber(state.created[r]?.length ?? 0);
4040
+ return `${n}/${n}`;
4041
+ })
4042
+ );
4043
+ for (const resource of pending) {
4044
+ const ids = state.created[resource] ?? [];
4045
+ const remaining = new Set(ids);
4046
+ const save = () => {
4047
+ state.created[resource] = [...remaining];
4048
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4049
+ writePrivateJson(paths.state, state);
4050
+ };
4051
+ const step = ctx.progress.step(RESOURCE_LABEL[resource]);
4052
+ let failed = 0;
4053
+ if (resource === "suppressions") {
4054
+ const { ids: removed, errors } = await target.removeSuppressions(ids);
4055
+ const kept = /* @__PURE__ */ new Set();
4056
+ for (const error of errors) {
4057
+ kept.add(error.index);
4058
+ failed += 1;
4059
+ state.failures.push({ resource, key: ids[error.index] ?? "?", message: error.message });
4060
+ }
4061
+ for (const [i, id] of ids.entries()) if (!kept.has(i)) remaining.delete(id);
4062
+ step.update(removed.length, ids.length);
4063
+ } else {
4064
+ const del = DELETE[resource];
4065
+ for (const [n, id] of ids.entries()) {
4066
+ const result = del === void 0 ? null : await del(target, id);
4067
+ if (result === null) break;
4068
+ if (result.ok || result.status === 404) remaining.delete(id);
4069
+ else {
4070
+ failed += 1;
4071
+ state.failures.push({ resource, key: id, message: result.message });
4072
+ }
4073
+ step.update(n + 1, ids.length);
4074
+ if ((n + 1) % SAVE_EVERY === 0) save();
4075
+ }
4076
+ }
4077
+ deleted[resource] = ids.length - remaining.size;
4078
+ if (resource === "contacts") state.progress = {};
4079
+ save();
4080
+ if (failed > 0) step.fail(`${pluralize(failed, "delete")} failed`);
4081
+ else step.done();
4082
+ }
4083
+ emitJson(state.failures);
4084
+ if (state.failures.length > 0) {
4085
+ out.write(
4086
+ `
4087
+ ${pluralize(state.failures.length, "delete")} failed; the ids stay in ${paths.state}:
4088
+ `
4089
+ );
4090
+ for (const f of state.failures) {
4091
+ out.write(` ${err(SYM.err)} ${f.resource}/${f.key} \u2014 ${f.message}
4092
+ `);
4093
+ }
4094
+ return 3;
4095
+ }
4096
+ out.write("\nRolled back. Rows this tool only updated were left as they are.\n");
4097
+ return 0;
4098
+ }
4099
+
4100
+ // src/commands/status.ts
4101
+ async function status(ctx) {
4102
+ const paths = migratePaths(ctx.cwd);
4103
+ const state = readJson(paths.state);
4104
+ if (ctx.config.json) {
4105
+ ctx.stdout.write(`${JSON.stringify(state)}
4106
+ `);
4107
+ return 0;
4108
+ }
4109
+ const { out } = ctx;
4110
+ if (state === null) {
4111
+ out.write(`No migration state in ${STATE_DIR}/ \u2014 nothing has been applied from here.
4112
+ `);
4113
+ return 0;
4114
+ }
4115
+ const block = (rows) => {
4116
+ out.write(`${column(rows).join("\n")}
4117
+ `);
4118
+ };
4119
+ out.write(`${heading("State")}
4120
+ `);
4121
+ block([
4122
+ ["Target", state.target.baseUrl],
4123
+ ["Started", state.startedAt],
4124
+ ["Updated", state.updatedAt],
4125
+ ["Plan", state.planHash.slice(0, 12)]
4126
+ ]);
4127
+ out.write("\nCreated\n");
4128
+ const created = Object.entries(state.created).filter(([, ids]) => ids.length > 0);
4129
+ if (created.length === 0) out.write(" nothing\n");
4130
+ else
4131
+ block(
4132
+ created.map(([resource, ids]) => [
4133
+ ` ${RESOURCE_LABEL[resource] ?? resource}`,
4134
+ bold(formatNumber(ids.length))
4135
+ ])
4136
+ );
4137
+ const { contactsCursor, enrichmentDone } = state.progress;
4138
+ out.write("\nProgress\n");
4139
+ block([
4140
+ [" Contacts", contactsCursor ? `resumes after ${contactsCursor}` : "complete"],
4141
+ [
4142
+ " Enriched",
4143
+ enrichmentDone ? `resumes with ${formatNumber(enrichmentDone.length)} done` : "complete"
4144
+ ]
4145
+ ]);
4146
+ if (state.failures.length > 0) {
4147
+ out.write(`
4148
+ ${pluralize(state.failures.length, "failure")} in the last run
4149
+ `);
4150
+ for (const f of state.failures)
4151
+ out.write(` ${err(SYM.err)} ${stripControl(`${f.resource}/${f.key} \u2014 ${f.message}`)}
4152
+ `);
4153
+ }
4154
+ return 0;
4155
+ }
4156
+
4157
+ // src/log.ts
4158
+ var RANK = { error: 0, warn: 1, info: 2, debug: 3 };
4159
+ var TOKEN_RE = /\b(?:re|bs|whsec)_[A-Za-z0-9+/=_-]+/g;
4160
+ var AUTHORIZATION_RE = /(authorization["']?\s*[:=]\s*["']?)(?:bearer\s+)?[^\s"',}]+/gi;
4161
+ function redact(text) {
4162
+ return text.replace(AUTHORIZATION_RE, "$1***").replace(TOKEN_RE, "***");
4163
+ }
4164
+ function createLogger({
4165
+ level = "info",
4166
+ stream = process.stderr
4167
+ } = {}) {
4168
+ const write = (at, prefix, message) => {
4169
+ if (RANK[at] <= RANK[level]) stream.write(`${prefix}${stripControl(redact(message))}
4170
+ `);
4171
+ };
4172
+ return {
4173
+ level,
4174
+ error: (message) => write("error", `${err("error:")} `, message),
4175
+ warn: (message) => write("warn", `${warn("warning:")} `, message),
4176
+ info: (message) => write("info", "", message),
4177
+ debug: (message) => write("debug", "", message)
4178
+ };
4179
+ }
4180
+
4181
+ // src/context.ts
4182
+ function createContext(config, io = {}) {
4183
+ const stdout = io.stdout ?? process.stdout;
4184
+ const stderr = io.stderr ?? process.stderr;
4185
+ const out = config.json ? stderr : stdout;
4186
+ setColorMode(config.color, out.isTTY === true);
4187
+ const progress = createProgress({ stream: out });
4188
+ const logSink = out.isTTY === true ? { write: (chunk2) => progress.writeAbove(chunk2, stderr) } : stderr;
4189
+ return {
4190
+ config,
4191
+ log: createLogger({ level: config.verbose ? "debug" : "info", stream: logSink }),
4192
+ rl: lineReader(io.stdin ?? process.stdin, out),
4193
+ progress,
4194
+ out,
4195
+ stdout,
4196
+ env: io.env ?? process.env,
4197
+ fetch: io.fetch ?? globalThis.fetch,
4198
+ cwd: io.cwd ?? process.cwd()
4199
+ };
4200
+ }
4201
+
4202
+ // src/index.ts
4203
+ var COMMANDS = { migrate, plan, apply, status, rollback };
4204
+ async function main(argv = process.argv.slice(2), io = {}) {
4205
+ const stdout = io.stdout ?? process.stdout;
4206
+ const stderr = io.stderr ?? process.stderr;
4207
+ let config;
4208
+ try {
4209
+ config = parseConfig(argv, io.env ?? process.env, (io.stdin ?? process.stdin).isTTY === true);
4210
+ } catch (error) {
4211
+ if (!(error instanceof ConfigError)) throw error;
4212
+ stderr.write(`${error.message}
4213
+ `);
4214
+ return 1;
4215
+ }
4216
+ if (config.command === "help") {
4217
+ stdout.write(helpText());
4218
+ return 0;
4219
+ }
4220
+ if (config.command === "version") {
4221
+ stdout.write(`${VERSION}
4222
+ `);
4223
+ return 0;
4224
+ }
4225
+ const ctx = createContext(config, io);
4226
+ for (const warning of config.warnings) ctx.log.warn(warning);
4227
+ try {
4228
+ return await COMMANDS[config.command](ctx);
4229
+ } catch (error) {
4230
+ ctx.progress.clear();
4231
+ ctx.log.error(error instanceof Error ? error.message : String(error));
4232
+ return 1;
4233
+ } finally {
4234
+ ctx.rl.close();
4235
+ }
4236
+ }
4237
+ var invokedAsScript = () => {
4238
+ try {
4239
+ return process.argv[1] !== void 0 && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
4240
+ } catch {
4241
+ return false;
4242
+ }
4243
+ };
4244
+ if (invokedAsScript()) {
4245
+ main().then((code) => {
4246
+ process.exitCode = code;
4247
+ });
4248
+ }
4249
+ export {
4250
+ main
4251
+ };