waba-devtools 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,936 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {
5
+ DEFAULT_GRAPH_VERSION,
6
+ getStage,
7
+ pickSourceWaba,
8
+ pickTargetWabas,
9
+ resolveToken,
10
+ } from './config.js';
11
+ import {
12
+ batchTime,
13
+ DEFAULT_LIMIT_PERCENT,
14
+ DEFAULT_THROTTLE_MINUTES,
15
+ planBatches,
16
+ usageStopReason,
17
+ THROTTLED_CODE,
18
+ validateRecentWrites,
19
+ writeBudget,
20
+ writesPerHour,
21
+ } from './budget.js';
22
+ import { readCsvTemplates } from './csv.js';
23
+ import { GraphError, UsageError } from './errors.js';
24
+ import {
25
+ readTemplateDirectory,
26
+ readTemplateFile,
27
+ templatePath,
28
+ writeTemplateFile,
29
+ } from './files.js';
30
+ import { createGraphClient, SUMMARY_FIELDS } from './graph.js';
31
+ import {
32
+ comparableContent,
33
+ mergeParts,
34
+ normalizeTemplate,
35
+ sortKeys,
36
+ templateKey,
37
+ } from './normalize.js';
38
+ import { planDeploy } from './plan.js';
39
+
40
+ /**
41
+ * @typedef {object} CommonOptions
42
+ * @property {string} cwd - Project root.
43
+ * @property {import('./config.js').Config} config
44
+ * @property {NodeJS.ProcessEnv} [environment] - Environment with the tokens (default `process.env`).
45
+ * @property {typeof fetch} [fetchImpl] - Injected `fetch` (tests).
46
+ */
47
+
48
+ /**
49
+ * @param {import('./config.js').WabaEntry} entry
50
+ * @param {CommonOptions} options
51
+ * @returns {import('./graph.js').GraphClient}
52
+ */
53
+ function clientFor(entry, { config, environment = process.env, fetchImpl }) {
54
+ return createGraphClient({
55
+ token: resolveToken(entry, environment),
56
+ version: config.graphVersion,
57
+ fetchImpl,
58
+ });
59
+ }
60
+
61
+ /**
62
+ * `{usage}` with the highest `X-Business-Use-Case-Usage` values the client saw, or `{}` when Meta
63
+ * sent none (or there is no client).
64
+ *
65
+ * @param {import('./graph.js').GraphClient|undefined} client
66
+ * @returns {{usage?: import('./graph.js').UsageInfo}}
67
+ */
68
+ function usageOf(client) {
69
+ const usage = client?.usage();
70
+ return usage ? { usage } : {};
71
+ }
72
+
73
+ /**
74
+ * @param {unknown} ex
75
+ * @returns {string}
76
+ */
77
+ function describeError(ex) {
78
+ return ex instanceof GraphError ? ex.describe() : ex.message;
79
+ }
80
+
81
+ /**
82
+ * Keeps only the named templates; fails when a name is not in the list.
83
+ *
84
+ * @template T
85
+ * @param {T[]} items
86
+ * @param {(item: T) => string} nameOf
87
+ * @param {string[]} names
88
+ * @param {string} where - Used in the error message.
89
+ * @returns {T[]}
90
+ */
91
+ function selectByName(items, nameOf, names, where) {
92
+ if (names.length === 0) {
93
+ return items;
94
+ }
95
+ const available = new Set(items.map(nameOf));
96
+ const missing = names.filter((name) => !available.has(name));
97
+ if (missing.length > 0) {
98
+ throw new UsageError(`Not found in ${where}: ${missing.join(', ')}.`);
99
+ }
100
+ const wanted = new Set(names);
101
+ return items.filter((item) => wanted.has(nameOf(item)));
102
+ }
103
+
104
+ /**
105
+ * Writes the templates of one WABA into the templates folder.
106
+ *
107
+ * @param {CommonOptions & {from?: string, fromWaba?: string, names?: string[]}} options
108
+ * @returns {Promise.<object>} Report.
109
+ */
110
+ export async function retrieve(options) {
111
+ const { config, cwd, from, fromWaba, names = [] } = options;
112
+ const { stage, stages, entry } = pickSourceWaba(config, from, fromWaba);
113
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
114
+ const templates = selectByName(
115
+ live.map(normalizeTemplate),
116
+ (template) => template.name,
117
+ names,
118
+ `WABA ${entry.wabaId}`,
119
+ );
120
+ const files = [];
121
+ for (const template of templates) {
122
+ const result = await writeTemplateFile(config.templatesDir, template);
123
+ files.push({
124
+ name: template.name,
125
+ language: template.language,
126
+ result,
127
+ path: path.relative(cwd, templatePath(config.templatesDir, template)),
128
+ });
129
+ }
130
+ return { command: 'retrieve', stage, stages, wabaId: entry.wabaId, files, ok: true };
131
+ }
132
+
133
+ /**
134
+ * Writes CSV rows into template files. Only the body (and, for new files, the category) comes
135
+ * from the CSV; header, footer and buttons of existing files are kept.
136
+ *
137
+ * @param {CommonOptions & {csv: string}} options
138
+ * @returns {Promise.<object>} Report.
139
+ */
140
+ export async function importCsv({ config, cwd, csv }) {
141
+ const { templates, errors, warnings, cleanup, parts } = await readCsvTemplates(
142
+ path.resolve(cwd, csv),
143
+ );
144
+ const files = [];
145
+ for (const template of templates) {
146
+ const existing = await readTemplateFile(config.templatesDir, template);
147
+ const merged = existing ? mergeParts(existing, template, parts) : template;
148
+ const result = await writeTemplateFile(config.templatesDir, merged);
149
+ files.push({
150
+ name: template.name,
151
+ language: template.language,
152
+ result,
153
+ path: path.relative(cwd, templatePath(config.templatesDir, template)),
154
+ });
155
+ }
156
+ return {
157
+ command: 'import',
158
+ csv,
159
+ csvCleanup: cleanup,
160
+ files,
161
+ rowErrors: errors,
162
+ rowWarnings: warnings,
163
+ ok: errors.length === 0,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Loads what should be deployed: CSV rows, a live source WABA, or the templates folder.
169
+ *
170
+ * @param {CommonOptions & {from?: string, fromWaba?: string, csv?: string, sourceDir?: string}} options
171
+ * @returns {Promise.<{source: import('./plan.js').SourceTemplate[], description: object, rowErrors: object[]}>}
172
+ */
173
+ async function loadSource(options) {
174
+ const { config, cwd, from, fromWaba, csv } = options;
175
+ if (csv) {
176
+ const { templates, errors, warnings, cleanup, parts } = await readCsvTemplates(
177
+ path.resolve(cwd, csv),
178
+ );
179
+ return {
180
+ source: templates.map((template) => ({ template, parts })),
181
+ description: { type: 'csv', csv, cleanup },
182
+ rowErrors: errors,
183
+ rowWarnings: warnings,
184
+ };
185
+ }
186
+ if (from || fromWaba) {
187
+ const { stage, stages, entry } = pickSourceWaba(config, from, fromWaba);
188
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
189
+ return {
190
+ source: live.map((template) => ({ template: normalizeTemplate(template) })),
191
+ description: { type: 'waba', stage, stages, wabaId: entry.wabaId },
192
+ rowErrors: [],
193
+ };
194
+ }
195
+ const directory = options.sourceDir ?? config.templatesDir;
196
+ const templates = await readTemplateDirectory(directory);
197
+ return {
198
+ source: templates.map((template) => ({ template })),
199
+ description: { type: 'files', dir: path.relative(cwd, directory) || '.' },
200
+ rowErrors: [],
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Creates missing and updates changed templates in every WABA of the target stage.
206
+ *
207
+ * @param {CommonOptions & {
208
+ * to?: string, toWabas?: string[], from?: string, fromWaba?: string, csv?: string,
209
+ * names?: string[],
210
+ * dryRun?: boolean, prune?: boolean, yes?: boolean,
211
+ * onProgress?: (event: object) => void,
212
+ * expectedActions?: {wabaId: string, actions: {name: string, language: string, action: string}[]}[],
213
+ * backupDir?: string, backupBefore?: boolean, backupAfter?: boolean, sourceDir?: string,
214
+ * templateKeys?: string[] - only these templates, as `name::language` (e.g. a selection from a backup),
215
+ * limitPercent?: number - share of Meta's limits to use, 1–100 (default 80): creates per
216
+ * target WABA and hour = floor(100 × limitPercent / 100); writing stops when Meta's
217
+ * X-Business-Use-Case-Usage reports any percentage at or above it,
218
+ * recentWrites?: import('./budget.js').RecentWrite[] - creates and updates logged by the caller
219
+ * (creates count when younger than one hour and not visible in the live list; an update keeps
220
+ * that template's recent `last_updated_time` from counting),
221
+ * stopOnRowErrors?: boolean - with `csv`: when any row has an error, send nothing to any target
222
+ * (each target reports why); default false: rows with errors are left out, the others are sent
223
+ * }} options
224
+ * @returns {Promise.<object>} Report.
225
+ */
226
+ export async function deploy(options) {
227
+ const {
228
+ config,
229
+ to,
230
+ toWabas = [],
231
+ from,
232
+ fromWaba,
233
+ csv,
234
+ names = [],
235
+ dryRun = false,
236
+ prune = false,
237
+ yes = false,
238
+ onProgress,
239
+ expectedActions,
240
+ backupDir,
241
+ backupBefore = true,
242
+ backupAfter = false,
243
+ templateKeys,
244
+ limitPercent = DEFAULT_LIMIT_PERCENT,
245
+ recentWrites = [],
246
+ stopOnRowErrors = false,
247
+ } = options;
248
+ const maxWritesPerHour = writesPerHour(limitPercent);
249
+ validateRecentWrites(recentWrites);
250
+ if (backupDir && !backupBefore && !backupAfter) {
251
+ throw new UsageError(
252
+ 'A backup folder was given, but both before- and after-backups are off.',
253
+ );
254
+ }
255
+ if (backupAfter && !backupDir) {
256
+ throw new UsageError('--backup-after needs --backup <folder>.');
257
+ }
258
+ const sources = [csv, from || fromWaba, options.sourceDir].filter(Boolean);
259
+ if (sources.length > 1) {
260
+ throw new UsageError('Use only one source: --csv, --from/--from-waba or --from-dir.');
261
+ }
262
+ if (prune && (csv || templateKeys || names.length > 0)) {
263
+ throw new UsageError(
264
+ '--prune only works when deploying the full set (not with -m or --csv).',
265
+ );
266
+ }
267
+ const targets = pickTargetWabas(config, to, toWabas);
268
+ const loaded = await loadSource(options);
269
+ if (templateKeys?.length === 0) {
270
+ throw new UsageError('No templates selected — select at least one template.');
271
+ }
272
+ const byName = selectByName(loaded.source, (item) => item.template.name, names, 'the source');
273
+ const source = templateKeys
274
+ ? selectByName(byName, (item) => templateKey(item.template), templateKeys, 'the source')
275
+ : byName;
276
+ if (prune && source.length === 0) {
277
+ throw new UsageError(
278
+ 'The source has no templates; refusing --prune (it would delete all).',
279
+ );
280
+ }
281
+ const isFullSet = names.length === 0 && !templateKeys && !csv;
282
+ // With stopOnRowErrors, one bad CSV row blocks every target: nothing is sent at all.
283
+ const isStoppedByRowErrors = stopOnRowErrors === true && loaded.rowErrors.length > 0;
284
+ const results = [];
285
+ const createdAt = new Date().toISOString();
286
+ const backup = backupDir
287
+ ? { root: backupDir, runAt: createdAt, source: loaded.description }
288
+ : undefined;
289
+ for (const [targetIndex, { stage, stages, entry }] of targets.entries()) {
290
+ const target = { stage, stages, wabaId: entry.wabaId, actions: [] };
291
+ results.push(target);
292
+ let client;
293
+ let live;
294
+ try {
295
+ client = clientFor(entry, options);
296
+ live = await client.listTemplates(entry.wabaId);
297
+ } catch (ex) {
298
+ target.error = describeError(ex);
299
+ Object.assign(target, usageOf(client));
300
+ continue;
301
+ }
302
+ const liveById = new Map(live.map((template) => [template.id, template]));
303
+ const planned = planDeploy({ source, target: live, fullSet: isFullSet, prune }).map(
304
+ (action) => withFingerprint(action, liveById),
305
+ );
306
+ const hasChanged =
307
+ expectedActions !== undefined &&
308
+ !isSameSendSet(planned, expectedFor(expectedActions, entry.wabaId));
309
+ if (hasChanged) {
310
+ target.error = 'changed since preview — run the preview again';
311
+ } else if (isStoppedByRowErrors) {
312
+ target.error = `${loaded.rowErrors.length} CSV row(s) have errors — nothing is sent (stop on error)`;
313
+ }
314
+ const total = planned.filter((action) => SENDING.has(action.action)).length;
315
+ const now = Date.now();
316
+ const budget = writeBudget({
317
+ limit: maxWritesPerHour,
318
+ live,
319
+ recentWrites: recentWrites.filter((write) => write.wabaId === entry.wabaId),
320
+ now,
321
+ });
322
+ target.budget = {
323
+ limitPercent,
324
+ limit: budget.limit,
325
+ usedLastHour: budget.usedLastHour,
326
+ left: budget.left,
327
+ countedAt: budget.times.map((time) => new Date(time).toISOString()),
328
+ };
329
+ // Creates that the confirmed preview showed as deferred stay deferred.
330
+ const deferredInPreview = new Set(
331
+ (expectedActions === undefined ? [] : expectedFor(expectedActions, entry.wabaId))
332
+ .filter((action) => action.result === 'deferred')
333
+ .map((action) => actionKey(action)),
334
+ );
335
+ const isDeferredUpFront = (action) =>
336
+ COUNTED.has(action.action) && deferredInPreview.has(actionKey(action));
337
+ const counted = planned.filter((action) => COUNTED.has(action.action));
338
+ const willSend =
339
+ total > counted.length ||
340
+ Math.min(counted.filter((action) => !isDeferredUpFront(action)).length, budget.left) >
341
+ 0;
342
+ let isBlocked = hasChanged || isStoppedByRowErrors;
343
+ if (backup && backupBefore && !dryRun && !isBlocked && willSend) {
344
+ try {
345
+ target.backup = await backupTarget(backup, {
346
+ stage,
347
+ wabaId: entry.wabaId,
348
+ live,
349
+ phase: 'before',
350
+ });
351
+ } catch (ex) {
352
+ target.error = `backup failed, nothing sent: ${ex.message}`;
353
+ isBlocked = true;
354
+ }
355
+ }
356
+ target.budget.schedule = planBatches({
357
+ wanted: isBlocked ? 0 : counted.length,
358
+ limit: budget.limit,
359
+ countedAt: budget.times,
360
+ now,
361
+ });
362
+ let done = 0;
363
+ let sent = 0;
364
+ let left = budget.left;
365
+ const overBudget = [];
366
+ for (const plannedAction of planned) {
367
+ const { body, ...action } = plannedAction;
368
+ target.actions.push(action);
369
+ if (isBlocked || !SENDING.has(action.action)) {
370
+ continue;
371
+ }
372
+ const isCounted = COUNTED.has(action.action);
373
+ const usage = client.usage();
374
+ const stopReason = target.throttled ? undefined : usageStopReason(usage, limitPercent);
375
+ if (stopReason) {
376
+ const minutes = usage.regainAccessMinutes || DEFAULT_THROTTLE_MINUTES;
377
+ target.throttled = {
378
+ retryAfter: new Date(Date.now() + minutes * 60_000).toISOString(),
379
+ error: stopReason,
380
+ };
381
+ }
382
+ if (target.throttled) {
383
+ deferAction(action, 'throttled', target.throttled.retryAfter);
384
+ } else if (isCounted && (left <= 0 || isDeferredUpFront(action))) {
385
+ deferAction(action, 'budget');
386
+ overBudget.push(action);
387
+ } else {
388
+ if (isCounted) {
389
+ left--;
390
+ }
391
+ if (dryRun) {
392
+ continue;
393
+ }
394
+ if (!yes && action.action === 'delete') {
395
+ action.result = 'not run (add --yes)';
396
+ } else {
397
+ action.at = new Date().toISOString();
398
+ await sendAction(client, entry.wabaId, action, body);
399
+ if (action.result === 'done') {
400
+ sent++;
401
+ } else if (action.result === 'deferred') {
402
+ target.throttled = { retryAfter: action.retryAfter, error: action.error };
403
+ }
404
+ }
405
+ }
406
+ if (dryRun) {
407
+ continue;
408
+ }
409
+ done++;
410
+ onProgress?.({
411
+ wabaId: entry.wabaId,
412
+ targetIndex,
413
+ targetCount: targets.length,
414
+ name: action.name,
415
+ language: action.language,
416
+ action: action.action,
417
+ result: action.result,
418
+ done,
419
+ total,
420
+ });
421
+ }
422
+ const passed = budget.left - left;
423
+ for (const [index, action] of overBudget.entries()) {
424
+ action.retryAfter = batchTime(target.budget.schedule, passed + index);
425
+ }
426
+ Object.assign(target, usageOf(client));
427
+ if (backup && backupAfter && sent > 0) {
428
+ try {
429
+ target.backupAfter = await backupTarget(backup, {
430
+ stage,
431
+ wabaId: entry.wabaId,
432
+ live: await client.listTemplates(entry.wabaId),
433
+ phase: 'after',
434
+ });
435
+ } catch (ex) {
436
+ target.backupAfterError = `after-backup failed (changes were sent): ${describeError(ex)}`;
437
+ }
438
+ }
439
+ }
440
+ const isOk =
441
+ loaded.rowErrors.length === 0 &&
442
+ results.every(
443
+ (target) =>
444
+ !target.error &&
445
+ target.actions.every(
446
+ (action) =>
447
+ action.result !== 'failed' &&
448
+ action.result !== 'deferred' &&
449
+ action.action !== 'blocked',
450
+ ),
451
+ );
452
+ return {
453
+ command: 'deploy',
454
+ dryRun,
455
+ source: loaded.description,
456
+ rowErrors: loaded.rowErrors,
457
+ rowWarnings: loaded.rowWarnings ?? [],
458
+ ...(isStoppedByRowErrors && { stoppedByRowErrors: true }),
459
+ targets: results,
460
+ ok: isOk,
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Folder name of one backup set: the WABA ID, the UTC time of the deploy run (file-name safe) and
466
+ * whether it was taken before or after the changes,
467
+ * e.g. `444444444444444_2026-11-20T18-26-04-123Z_before`.
468
+ *
469
+ * @param {string} wabaId
470
+ * @param {string} runAt - ISO timestamp of the deploy run (same for the before and after set).
471
+ * @param {'before'|'after'|'manual'} phase
472
+ * @returns {string}
473
+ */
474
+ export function backupSetName(wabaId, runAt, phase) {
475
+ return `${wabaId}_${runAt.replaceAll(/[:.]/g, '-')}_${phase}`;
476
+ }
477
+
478
+ /**
479
+ * Writes one backup set: the full template set of one target WABA plus a manifest that lists the
480
+ * templates, so a backup can be browsed without reading every file. An existing set folder is never
481
+ * overwritten.
482
+ *
483
+ * @param {{root: string, runAt: string, source: object}} backup - Run state.
484
+ * @param {{stage: string, wabaId: string, live: object[], phase: 'before'|'after'|'manual'}} target
485
+ * @returns {Promise.<string>} Folder of the backup set.
486
+ */
487
+ async function backupTarget(backup, { stage, wabaId, live, phase }) {
488
+ const directory = path.join(backup.root, backupSetName(wabaId, backup.runAt, phase));
489
+ await mkdir(backup.root, { recursive: true });
490
+ try {
491
+ await mkdir(directory);
492
+ } catch (ex) {
493
+ throw ex.code === 'EEXIST' ? new Error(`backup set ${directory} already exists`) : ex;
494
+ }
495
+ const entries = live
496
+ .map((template) => ({ template: normalizeTemplate(template), status: template.status }))
497
+ .toSorted((a, b) => templateKey(a.template).localeCompare(templateKey(b.template)));
498
+ const templates = entries.map((item) => item.template);
499
+ for (const template of templates) {
500
+ await writeTemplateFile(directory, template);
501
+ }
502
+ const { version } = JSON.parse(
503
+ await readFile(new URL('../package.json', import.meta.url), 'utf8'),
504
+ );
505
+ const manifest = {
506
+ tool: 'waba-devtools',
507
+ version,
508
+ createdAt: new Date().toISOString(),
509
+ runAt: backup.runAt,
510
+ phase,
511
+ wabaId,
512
+ stage,
513
+ source: backup.source,
514
+ templates: entries.map(({ template, status }) => ({
515
+ name: template.name,
516
+ language: template.language,
517
+ category: template.category,
518
+ status,
519
+ })),
520
+ };
521
+ await writeFile(
522
+ path.join(directory, 'manifest.json'),
523
+ `${JSON.stringify(manifest, undefined, 4)}\n`,
524
+ );
525
+ return directory;
526
+ }
527
+
528
+ /**
529
+ * Actions that send something to Meta.
530
+ */
531
+ const SENDING = new Set(['create', 'update', 'delete']);
532
+
533
+ /**
534
+ * Actions that count against the hourly budget: Meta limits template creates per hour, not edits
535
+ * or deletes.
536
+ */
537
+ const COUNTED = new Set(['create']);
538
+
539
+ /**
540
+ * Marks a create, update or delete as not sent in this run.
541
+ *
542
+ * @param {object} action - Report entry, updated in place.
543
+ * @param {'budget'|'throttled'} reason - Hourly create budget used up, or Meta throttled the app.
544
+ * @param {string} [retryAfter] - ISO time it can be tried again (set after the loop for `budget`).
545
+ * @returns {void}
546
+ */
547
+ function deferAction(action, reason, retryAfter) {
548
+ action.result = 'deferred';
549
+ action.deferredReason = reason;
550
+ if (retryAfter) {
551
+ action.retryAfter = retryAfter;
552
+ }
553
+ }
554
+
555
+ /**
556
+ * The confirmed preview actions of one target WABA.
557
+ *
558
+ * @param {{wabaId: string, actions?: {name: string, language: string, action: string}[]}[]} expected
559
+ * @param {string} wabaId
560
+ * @returns {{name: string, language: string, action: string}[]}
561
+ */
562
+ function expectedFor(expected, wabaId) {
563
+ return expected.find((target) => target.wabaId === wabaId)?.actions ?? [];
564
+ }
565
+
566
+ /**
567
+ * True when both lists would send the same create/update/delete for the same templates.
568
+ *
569
+ * @param {{name: string, language: string, action: string}[]} planned
570
+ * @param {{name: string, language: string, action: string}[]} expected
571
+ * @returns {boolean}
572
+ */
573
+ function isSameSendSet(planned, expected) {
574
+ if (sendKey(planned) !== sendKey(expected)) {
575
+ return false;
576
+ }
577
+ const fingerprints = new Map(
578
+ expected
579
+ .filter((action) => SENDING.has(action.action))
580
+ .map((action) => [actionKey(action), action.fingerprint]),
581
+ );
582
+ // A preview without any fingerprints (older file) only binds what happens to which template.
583
+ // Once a preview has fingerprints, every sending action must match its own.
584
+ const hasFingerprints = fingerprints.values().some((value) => value !== undefined);
585
+ return planned
586
+ .filter((action) => SENDING.has(action.action))
587
+ .every(
588
+ (action) =>
589
+ !hasFingerprints || fingerprints.get(actionKey(action)) === action.fingerprint,
590
+ );
591
+ }
592
+
593
+ /**
594
+ * @param {{name: string, language: string, action: string}} action
595
+ * @returns {string}
596
+ */
597
+ function actionKey(action) {
598
+ return `${action.action}:${action.name}:${action.language}`;
599
+ }
600
+
601
+ /**
602
+ * Adds `fingerprint` to every create, update and delete: a short hash of the exact request body and,
603
+ * for updates and deletes, of the live template it replaces (ID, status, content). A confirmed preview
604
+ * then binds both what is sent and what it overwrites or deletes.
605
+ *
606
+ * @param {object} action - Planned action.
607
+ * @param {Map.<string, object>} liveById - Live templates of the target by ID.
608
+ * @returns {object}
609
+ */
610
+ function withFingerprint(action, liveById) {
611
+ if (!SENDING.has(action.action)) {
612
+ return action;
613
+ }
614
+ const current = action.templateId ? liveById.get(action.templateId) : undefined;
615
+ const bound = {
616
+ body: action.body ?? null,
617
+ live: current
618
+ ? {
619
+ id: current.id,
620
+ status: current.status,
621
+ content: comparableContent(normalizeTemplate(current)),
622
+ }
623
+ : null,
624
+ };
625
+ const fingerprint = createHash('sha256')
626
+ .update(JSON.stringify(sortKeys(bound)))
627
+ .digest('hex')
628
+ .slice(0, 16);
629
+ return { ...action, fingerprint };
630
+ }
631
+
632
+ /**
633
+ * @param {{name: string, language: string, action: string}[]} actions
634
+ * @returns {string} Sorted create/update/delete keys.
635
+ */
636
+ function sendKey(actions) {
637
+ return actions
638
+ .filter((action) => SENDING.has(action.action))
639
+ .map((action) => actionKey(action))
640
+ .toSorted((a, b) => a.localeCompare(b))
641
+ .join('\n');
642
+ }
643
+
644
+ /**
645
+ * Sends one planned action and records the result on it.
646
+ *
647
+ * @param {import('./graph.js').GraphClient} client
648
+ * @param {string} wabaId
649
+ * @param {object} action - Report entry, updated in place.
650
+ * @param {object} [body] - Request body from the plan.
651
+ * @returns {Promise.<void>}
652
+ */
653
+ async function sendAction(client, wabaId, action, body) {
654
+ try {
655
+ if (action.action === 'create') {
656
+ const response = await client.createTemplate(wabaId, body);
657
+ action.templateId = response.id;
658
+ action.statusAfter = response.status;
659
+ } else if (action.action === 'update') {
660
+ await client.updateTemplate(action.templateId, body);
661
+ } else {
662
+ await client.deleteTemplate(wabaId, action.name, action.templateId);
663
+ }
664
+ action.result = 'done';
665
+ } catch (ex) {
666
+ if (ex instanceof GraphError && ex.code === THROTTLED_CODE) {
667
+ const minutes = ex.regainAccessMinutes ?? DEFAULT_THROTTLE_MINUTES;
668
+ deferAction(action, 'throttled', new Date(Date.now() + minutes * 60_000).toISOString());
669
+ } else {
670
+ action.result = 'failed';
671
+ }
672
+ action.error = describeError(ex);
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Template overview per WABA (name, language, category, status) without components or files.
678
+ * Takes either a source (`from`/`fromWaba`) or targets (`to`/`toWabas`).
679
+ *
680
+ * @param {CommonOptions & {
681
+ * from?: string, fromWaba?: string, to?: string, toWabas?: string[]
682
+ * }} options
683
+ * @returns {Promise.<object>} Report.
684
+ */
685
+ export async function listTemplates(options) {
686
+ const { config, from, fromWaba, to, toWabas = [] } = options;
687
+ const isSource = Boolean(from || fromWaba);
688
+ if (isSource && (to || toWabas.length > 0)) {
689
+ throw new UsageError(
690
+ 'List either a source (--from/--from-waba) or targets (--to/--to-waba).',
691
+ );
692
+ }
693
+ const entries = isSource
694
+ ? [pickSourceWaba(config, from, fromWaba)]
695
+ : pickTargetWabas(config, to, toWabas);
696
+ const wabas = [];
697
+ for (const { stage, stages, entry } of entries) {
698
+ const result = { stage, stages, wabaId: entry.wabaId };
699
+ wabas.push(result);
700
+ let client;
701
+ try {
702
+ client = clientFor(entry, options);
703
+ const live = await client.listTemplates(entry.wabaId, SUMMARY_FIELDS);
704
+ result.templates = live
705
+ .map(({ name, language, category, status }) => ({
706
+ name,
707
+ language,
708
+ category,
709
+ status,
710
+ }))
711
+ .toSorted(
712
+ (a, b) => a.name.localeCompare(b.name) || a.language.localeCompare(b.language),
713
+ );
714
+ } catch (ex) {
715
+ result.error = describeError(ex);
716
+ }
717
+ Object.assign(result, usageOf(client));
718
+ }
719
+ return { command: 'list', wabas, ok: wabas.every((waba) => !waba.error) };
720
+ }
721
+
722
+ /**
723
+ * Token type and expiry from Meta's `debug_token` answer, for warnings about short-lived tokens.
724
+ *
725
+ * @param {{type?: string, expires_at?: number}} info
726
+ * @returns {{type: string|undefined, expiresAt: string|null}} `expiresAt` is `null` when the token
727
+ * never expires.
728
+ */
729
+ function describeTokenInfo(info) {
730
+ return {
731
+ type: info.type,
732
+ expiresAt: info.expires_at ? new Date(info.expires_at * 1000).toISOString() : null,
733
+ };
734
+ }
735
+
736
+ /**
737
+ * The WABAs an access token can manage, with their names and phone numbers. Read-only; needs no
738
+ * config, so it helps to write one.
739
+ *
740
+ * @param {object} options
741
+ * @param {string} options.token - Access token (never logged or returned).
742
+ * @param {string} [options.businessId] - Business portfolio to list the WABAs of, when Meta does not
743
+ * name them for the token.
744
+ * @param {string} [options.graphVersion]
745
+ * @param {typeof fetch} [options.fetchImpl]
746
+ * @returns {Promise.<object>} Report.
747
+ */
748
+ export async function discoverWabas({
749
+ token,
750
+ businessId,
751
+ graphVersion = DEFAULT_GRAPH_VERSION,
752
+ fetchImpl,
753
+ }) {
754
+ const client = createGraphClient({ token, version: graphVersion, fetchImpl });
755
+ let info;
756
+ try {
757
+ info = await client.debugToken();
758
+ } catch (ex) {
759
+ // A system user with only the "Test app" role may use its token but not describe it.
760
+ if (!(
761
+ ex instanceof GraphError &&
762
+ ex.code === 100 &&
763
+ /owner or developer/i.test(ex.message)
764
+ )) {
765
+ throw ex;
766
+ }
767
+ if (!businessId) {
768
+ throw new UsageError(
769
+ 'Meta does not describe this token: its system user needs the "Develop app" role on ' +
770
+ 'the app (Business settings → System users → Manage next to the app). Or give ' +
771
+ 'the business portfolio ID with --business <id>.',
772
+ 'TOKEN_INFO_REFUSED',
773
+ );
774
+ }
775
+ }
776
+ let ids = [];
777
+ if (info) {
778
+ if (info.is_valid === false) {
779
+ throw new UsageError(
780
+ 'Meta says this access token is not valid (expired or revoked).',
781
+ 'TOKEN_INVALID',
782
+ );
783
+ }
784
+ const scope = (info.granular_scopes ?? []).find(
785
+ (candidate) => candidate.scope === 'whatsapp_business_management',
786
+ );
787
+ if (!scope) {
788
+ throw new UsageError(
789
+ 'This access token has no whatsapp_business_management permission. Generate it again with that permission.',
790
+ 'TOKEN_MISSING_PERMISSION',
791
+ );
792
+ }
793
+ ids = scope.target_ids ?? [];
794
+ }
795
+ if (businessId && ids.length === 0) {
796
+ // Meta omits target_ids for tokens that reach everything (dashboard user tokens and
797
+ // system-user tokens alike); the portfolio's WABA lists work with business_management.
798
+ ids = (await client.listBusinessWabas(businessId)).map((waba) => waba.id);
799
+ }
800
+ if (ids.length === 0) {
801
+ throw new UsageError(
802
+ businessId
803
+ ? `Business portfolio ${businessId} has no WhatsApp accounts this token can see.`
804
+ : 'Meta did not list which WABAs this token can reach. Give the business portfolio ID ' +
805
+ 'with --business <id> (Business settings: the number after business_id= in the ' +
806
+ 'address bar), or add the WABA IDs to .wabadevrc.json by hand.',
807
+ businessId ? 'BUSINESS_HAS_NO_WABAS' : 'BUSINESS_ID_REQUIRED',
808
+ );
809
+ }
810
+ const wabas = [];
811
+ for (const wabaId of ids) {
812
+ const result = { wabaId };
813
+ wabas.push(result);
814
+ try {
815
+ result.name = (await client.getWaba(wabaId)).name;
816
+ result.phoneNumbers = (await client.listPhoneNumbers(wabaId)).map((phone) => ({
817
+ id: phone.id,
818
+ displayPhoneNumber: phone.display_phone_number,
819
+ verifiedName: phone.verified_name,
820
+ }));
821
+ } catch (ex) {
822
+ result.error = describeError(ex);
823
+ }
824
+ }
825
+ return {
826
+ command: 'discover',
827
+ ...(info && { tokenInfo: describeTokenInfo(info) }),
828
+ wabas,
829
+ ok: wabas.every((waba) => !waba.error),
830
+ };
831
+ }
832
+
833
+ /**
834
+ * Creates manual backups without deploying: one backup set `<wabaId>_<time>_manual` per WABA.
835
+ *
836
+ * @param {CommonOptions & {stage?: string, wabaIds?: string[], backupDir: string}} options
837
+ * @returns {Promise.<object>} Report.
838
+ */
839
+ export async function createBackup(options) {
840
+ const { config, stage, wabaIds = [], backupDir } = options;
841
+ if (!backupDir) {
842
+ throw new UsageError('Missing --backup <folder>.');
843
+ }
844
+ if (!stage && wabaIds.length === 0) {
845
+ throw new UsageError('Missing --stage or --waba.');
846
+ }
847
+ const backup = { root: backupDir, runAt: new Date().toISOString(), source: { type: 'manual' } };
848
+ const sets = [];
849
+ const targets = pickTargetWabas(config, stage, wabaIds, 'add --stage <stage>');
850
+ for (const { stage: stageName, stages, entry } of targets) {
851
+ const result = { stage: stageName, stages, wabaId: entry.wabaId };
852
+ sets.push(result);
853
+ try {
854
+ const live = await clientFor(entry, options).listTemplates(entry.wabaId);
855
+ result.backup = await backupTarget(backup, {
856
+ stage: stageName,
857
+ wabaId: entry.wabaId,
858
+ live,
859
+ phase: 'manual',
860
+ });
861
+ result.templateCount = live.length;
862
+ } catch (ex) {
863
+ result.error = describeError(ex);
864
+ }
865
+ }
866
+ return { command: 'backup', sets, ok: sets.every((set) => !set.error) };
867
+ }
868
+
869
+ /**
870
+ * Meta's error code on the WABA entity of `health_status` when it disabled the WABA.
871
+ */
872
+ const WABA_BANNED_CODE = 141_014;
873
+
874
+ /**
875
+ * Warning when Meta has disabled the WABA. Meta still answers reads then (and reports
876
+ * `status: ACTIVE`), so only `account_review_status` and the WABA's health errors show it.
877
+ * Errors every unverified test portfolio has (no payment method, no business verification) are
878
+ * not warnings: they only block sending messages, which waba never does.
879
+ *
880
+ * @param {object} waba - Graph answer with `account_review_status` and `health_status`.
881
+ * @returns {{code: string, message: string}[]}
882
+ */
883
+ function wabaWarnings(waba) {
884
+ const banned = (waba.health_status?.entities ?? [])
885
+ .filter((entity) => entity.entity_type === 'WABA')
886
+ .flatMap((entity) => entity.errors ?? [])
887
+ .find((error) => error.error_code === WABA_BANNED_CODE);
888
+ if (!banned && waba.account_review_status !== 'REJECTED') {
889
+ return [];
890
+ }
891
+ const review = waba.account_review_status
892
+ ? ` (account review: ${waba.account_review_status})`
893
+ : '';
894
+ return [
895
+ {
896
+ code: 'WABA_DISABLED',
897
+ message:
898
+ `Meta has disabled this WABA${review}. Templates can still be read. ` +
899
+ 'Details and appeal: Business Support Home (https://business.facebook.com/accountquality).',
900
+ },
901
+ ];
902
+ }
903
+
904
+ /**
905
+ * Read-only access check: token present, WABA reachable, templates listable, and whether Meta has
906
+ * disabled the WABA.
907
+ *
908
+ * @param {CommonOptions & {stage?: string}} options
909
+ * @returns {Promise.<object>} Report.
910
+ */
911
+ export async function check(options) {
912
+ const { config, stage } = options;
913
+ const stages = stage ? [stage] : Object.keys(config.stages);
914
+ const entries = [];
915
+ for (const name of stages) {
916
+ for (const entry of getStage(config, name)) {
917
+ const result = { stage: name, wabaId: entry.wabaId, tokenEnv: entry.tokenEnv };
918
+ entries.push(result);
919
+ try {
920
+ const client = clientFor(entry, options);
921
+ const waba = await client.getWaba(
922
+ entry.wabaId,
923
+ 'id,name,account_review_status,health_status',
924
+ );
925
+ result.wabaName = waba.name;
926
+ result.warnings = wabaWarnings(waba);
927
+ await client.probeTemplates(entry.wabaId);
928
+ result.ok = true;
929
+ } catch (ex) {
930
+ result.ok = false;
931
+ result.error = describeError(ex);
932
+ }
933
+ }
934
+ }
935
+ return { command: 'check', entries, ok: entries.every((entry) => entry.ok) };
936
+ }