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.
package/lib/report.js ADDED
@@ -0,0 +1,328 @@
1
+ import { DEFAULT_LIMIT_PERCENT, USAGE_WARN_PERCENT } from './budget.js';
2
+
3
+ /**
4
+ * Human-readable report lines. `--json` prints the report object instead.
5
+ *
6
+ * @param {object} report - Result of a command.
7
+ * @returns {string[]}
8
+ */
9
+ export function formatReport(report) {
10
+ switch (report.command) {
11
+ case 'retrieve': {
12
+ return [
13
+ `Retrieved ${report.files.length} template(s) from ${report.stage} (WABA ${report.wabaId}):`,
14
+ ...report.files.map((file) => ` ${file.result.padEnd(9)} ${file.path}`),
15
+ ];
16
+ }
17
+ case 'import': {
18
+ return [
19
+ `Imported ${report.files.length} row(s) from ${report.csv}:`,
20
+ ...cleanupLines(report.csvCleanup),
21
+ ...report.files.map((file) => ` ${file.result.padEnd(9)} ${file.path}`),
22
+ ...rowErrorLines(report.rowErrors, report.rowWarnings),
23
+ ];
24
+ }
25
+ case 'deploy': {
26
+ return deployLines(report);
27
+ }
28
+ case 'list': {
29
+ return report.wabas.flatMap((waba) => [
30
+ `${waba.stage} — WABA ${waba.wabaId}:`,
31
+ ...usageLines(waba.usage),
32
+ ...(waba.error
33
+ ? [` FAILED ${waba.error}`]
34
+ : [
35
+ ...waba.templates.map(
36
+ (template) =>
37
+ ` ${template.name} (${template.language}) ${template.category} [${template.status}]`,
38
+ ),
39
+ ` = ${waba.templates.length} template(s)`,
40
+ ]),
41
+ ]);
42
+ }
43
+ case 'discover': {
44
+ const { tokenInfo } = report;
45
+ const tokenLines = tokenInfo
46
+ ? [
47
+ ` Token: ${tokenInfo.type ?? 'unknown type'}, ${
48
+ tokenInfo.expiresAt ? `expires ${tokenInfo.expiresAt}` : 'never expires'
49
+ }`,
50
+ ...(tokenInfo.type === 'USER'
51
+ ? [
52
+ ' Warning: a user token stops working within hours. Use a system-user ' +
53
+ 'token (README: Access tokens).',
54
+ ]
55
+ : []),
56
+ ]
57
+ : [];
58
+ return [
59
+ ...tokenLines,
60
+ ...report.wabas.map((waba) =>
61
+ waba.error
62
+ ? ` FAILED WABA ${waba.wabaId}: ${waba.error}`
63
+ : ` WABA ${waba.wabaId} ${waba.name ?? ''} ${waba.phoneNumbers
64
+ .map((phone) => `${phone.displayPhoneNumber} (${phone.verifiedName})`)
65
+ .join(', ')}`,
66
+ ),
67
+ ];
68
+ }
69
+ case 'backup': {
70
+ return report.sets.map((set) =>
71
+ set.error
72
+ ? ` FAILED ${set.stage} WABA ${set.wabaId}: ${set.error}`
73
+ : ` OK ${set.stage} WABA ${set.wabaId} → ${set.backup} (${set.templateCount} templates)`,
74
+ );
75
+ }
76
+ case 'compare': {
77
+ return compareLines(report);
78
+ }
79
+ case 'check': {
80
+ return report.entries.flatMap((entry) =>
81
+ entry.ok
82
+ ? [
83
+ ` OK ${entry.stage} WABA ${entry.wabaId} (${entry.wabaName ?? 'no name'})`,
84
+ ...(entry.warnings ?? []).map(
85
+ (warning) => ` WARN ${warning.message}`,
86
+ ),
87
+ ]
88
+ : ` FAILED ${entry.stage} WABA ${entry.wabaId}: ${entry.error}`,
89
+ );
90
+ }
91
+ default: {
92
+ return [JSON.stringify(report)];
93
+ }
94
+ }
95
+ }
96
+
97
+ /**
98
+ * @param {{wabaId: string, stage?: string, createdAt: string, phase?: string}} info
99
+ * @returns {string}
100
+ */
101
+ function setLine(info) {
102
+ if (info.phase === 'live') {
103
+ return `WABA ${info.wabaId} (${info.stage ?? '-'}) right now`;
104
+ }
105
+ const phase = info.phase ? ` ${info.phase}` : '';
106
+ return `WABA ${info.wabaId} (${info.stage ?? '-'}) backup ${info.createdAt}${phase}`;
107
+ }
108
+
109
+ /**
110
+ * @param {{name: string, language: string}} template
111
+ * @returns {string}
112
+ */
113
+ function itemLine(template) {
114
+ return ` ${template.name} (${template.language})`;
115
+ }
116
+
117
+ /**
118
+ * Compare report: the two sets, then added / removed / changed with field details.
119
+ *
120
+ * @param {object} report
121
+ * @returns {string[]}
122
+ */
123
+ function compareLines(report) {
124
+ const lines = [`Before: ${setLine(report.before)}`, `After: ${setLine(report.after)}`];
125
+ if (!report.sameWaba) {
126
+ lines.push('Note: before and after are different WABAs.');
127
+ }
128
+ lines.push(
129
+ `Added (${report.added.length}):`,
130
+ ...report.added.map((template) => itemLine(template)),
131
+ `Removed (${report.removed.length}):`,
132
+ ...report.removed.map((template) => itemLine(template)),
133
+ `Changed (${report.changed.length}):`,
134
+ );
135
+ for (const template of report.changed) {
136
+ lines.push(itemLine(template));
137
+ for (const change of template.changes) {
138
+ lines.push(
139
+ ` ${change.field}:`,
140
+ ` before: ${change.before ?? '—'}`,
141
+ ` after: ${change.after ?? '—'}`,
142
+ );
143
+ }
144
+ }
145
+ lines.push(`Unchanged: ${report.unchanged}`);
146
+ return lines;
147
+ }
148
+
149
+ /**
150
+ * One line about the CSV cleanup, when anything was cleaned up.
151
+ *
152
+ * @param {import('./csv.js').CsvCleanup} [cleanup]
153
+ * @returns {string[]}
154
+ */
155
+ function cleanupLines(cleanup) {
156
+ if (
157
+ !cleanup ||
158
+ cleanup.removedColumns + cleanup.removedRecords + cleanup.skippedRecords === 0
159
+ ) {
160
+ return [];
161
+ }
162
+ const rows = cleanup.removedRecords + cleanup.skippedRecords;
163
+ return [
164
+ ` CSV cleanup: removed ${cleanup.removedColumns} empty column(s) on the right and ${rows} empty row(s).`,
165
+ ];
166
+ }
167
+
168
+ /**
169
+ * @param {{row: number, message: string}[]} [rowErrors] - Rows left out.
170
+ * @param {{row: number, message: string}[]} [rowWarnings] - Rows read, something ignored.
171
+ * @param {boolean} [isStopped] - deploy --stop-on-error stopped because of them.
172
+ * @returns {string[]}
173
+ */
174
+ function rowErrorLines(rowErrors = [], rowWarnings = [], isStopped = false) {
175
+ return [
176
+ ...(rowErrors.length > 0
177
+ ? [
178
+ `CSV rows with errors, ${isStopped ? 'so nothing is sent' : 'left out'} (${rowErrors.length}):`,
179
+ ...rowErrors.map((error) => ` row ${error.row}: ${error.message}`),
180
+ ]
181
+ : []),
182
+ ...(rowWarnings.length > 0
183
+ ? [
184
+ `CSV rows with warnings (${rowWarnings.length}):`,
185
+ ...rowWarnings.map((warning) => ` row ${warning.row}: ${warning.message}`),
186
+ ]
187
+ : []),
188
+ ];
189
+ }
190
+
191
+ /**
192
+ * @param {object} report - Deploy report.
193
+ * @returns {string[]}
194
+ */
195
+ function deployLines(report) {
196
+ const lines = [];
197
+ const from =
198
+ report.source.type === 'waba'
199
+ ? `${report.source.stage} (WABA ${report.source.wabaId})`
200
+ : (report.source.csv ?? report.source.dir);
201
+ lines.push(
202
+ `${report.dryRun ? 'Dry run — nothing is sent. ' : ''}Source: ${from}`,
203
+ ...cleanupLines(report.source.cleanup),
204
+ );
205
+ for (const target of report.targets) {
206
+ lines.push(`${target.stage} — WABA ${target.wabaId}:`);
207
+ if (target.error) {
208
+ lines.push(` FAILED ${target.error}`);
209
+ continue;
210
+ }
211
+ for (const [label, value] of [
212
+ ['backup before', target.backup],
213
+ ['backup after', target.backupAfter],
214
+ ['WARNING', target.backupAfterError],
215
+ ]) {
216
+ if (value) {
217
+ lines.push(` ${label}: ${value}`);
218
+ }
219
+ }
220
+ lines.push(...usageLines(target.usage, target.budget?.limitPercent));
221
+ if (target.budget) {
222
+ const { limitPercent, limit, usedLastHour, left, schedule = [] } = target.budget;
223
+ lines.push(
224
+ ` hourly budget (${limitPercent} %): ${usedLastHour} of ${limit} creates in the last hour, ${left} left`,
225
+ );
226
+ if (schedule.length > 1) {
227
+ lines.push(` schedule: ${scheduleText(schedule)}`);
228
+ }
229
+ }
230
+ if (target.throttled) {
231
+ lines.push(
232
+ ` STOPPED Meta throttles this WABA; the rest is deferred until ${target.throttled.retryAfter}`,
233
+ );
234
+ }
235
+ for (const action of target.actions) {
236
+ const status = action.status ? ` [${action.status}]` : '';
237
+ const after = action.statusAfter ? ` → ${action.statusAfter}` : '';
238
+ const retry = action.retryAfter ? ` until ${action.retryAfter}` : '';
239
+ const result = action.result ? ` ${action.result}${after}${retry}` : '';
240
+ const detail =
241
+ action.error ??
242
+ (action.deferredReason === 'budget' ? 'hourly create limit used up' : action.note);
243
+ lines.push(
244
+ ` ${action.action.padEnd(9)} ${action.name} (${action.language})${status}${result}` +
245
+ (detail ? ` — ${detail}` : ''),
246
+ );
247
+ }
248
+ const counts = {};
249
+ for (const action of target.actions) {
250
+ counts[action.action] = (counts[action.action] ?? 0) + 1;
251
+ }
252
+ const summary = Object.entries(counts)
253
+ .map(([action, count]) => `${count} ${action}`)
254
+ .join(', ');
255
+ lines.push(` = ${summary || 'nothing to do'}`);
256
+ }
257
+ lines.push(...rowErrorLines(report.rowErrors, report.rowWarnings, report.stoppedByRowErrors));
258
+ const retry = nextRetry(report);
259
+ if (retry) {
260
+ lines.push(
261
+ `Deferred templates: run the same command again after ${clockTime(retry)} (${retry}) — ` +
262
+ 'only what is still missing or different is sent.',
263
+ );
264
+ }
265
+ return lines;
266
+ }
267
+
268
+ /**
269
+ * Earliest time a deferred template of a deploy report can be sent, or `undefined`.
270
+ *
271
+ * @param {object} report - Deploy report.
272
+ * @returns {string|undefined} ISO time.
273
+ */
274
+ export function nextRetry(report) {
275
+ const times = (report.targets ?? [])
276
+ .flatMap((target) => target.actions ?? [])
277
+ .filter((action) => action.result === 'deferred' && action.retryAfter)
278
+ .map((action) => action.retryAfter)
279
+ .toSorted((a, b) => Date.parse(a) - Date.parse(b));
280
+ return times[0];
281
+ }
282
+
283
+ /**
284
+ * Local `HH:MM` of an ISO time.
285
+ *
286
+ * @param {string} iso
287
+ * @returns {string}
288
+ */
289
+ function clockTime(iso) {
290
+ const date = new Date(iso);
291
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
292
+ }
293
+
294
+ /**
295
+ * E.g. `3 batches: 100 now, 100 at 15:05, 50 at 16:05` (the first batch is "now").
296
+ *
297
+ * @param {{at: string, count: number}[]} schedule
298
+ * @returns {string}
299
+ */
300
+ function scheduleText(schedule) {
301
+ const parts = schedule.map(
302
+ (batch, index) => `${batch.count} ${index === 0 ? 'now' : `at ${clockTime(batch.at)}`}`,
303
+ );
304
+ return `${schedule.length} batches: ${parts.join(', ')}`;
305
+ }
306
+
307
+ /**
308
+ * Meta's API usage for a WABA, with a warning from `USAGE_WARN_PERCENT` (or the limit, when lower) on.
309
+ *
310
+ * @param {import('./graph.js').UsageInfo} [usage]
311
+ * @param {number} [limitPercent] - Where `deploy` stops writing.
312
+ * @returns {string[]}
313
+ */
314
+ function usageLines(usage, limitPercent = DEFAULT_LIMIT_PERCENT) {
315
+ if (!usage) {
316
+ return [];
317
+ }
318
+ const peak = Math.max(usage.callCount, usage.totalCputime, usage.totalTime);
319
+ const text =
320
+ `Meta API usage this hour: calls ${usage.callCount} %, CPU ${usage.totalCputime} %, ` +
321
+ `time ${usage.totalTime} %` +
322
+ (usage.regainAccessMinutes > 0 ? `, throttled for ${usage.regainAccessMinutes} min` : '');
323
+ const isHigh =
324
+ peak >= Math.min(USAGE_WARN_PERCENT, limitPercent) || usage.regainAccessMinutes > 0;
325
+ return [
326
+ ` ${isHigh ? 'WARNING ' : ''}${text}${isHigh ? ` — waba stops writing at ${limitPercent} %` : ''}`,
327
+ ];
328
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
- "name": "waba-devtools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "waba-devtools",
3
+ "version": "0.2.0",
4
+ "description": "WABA DevTools (waba) — retrieve, import from CSV and deploy WhatsApp Business message templates across WABAs and pipeline stages",
5
+ "author": "Jörn Berkefeld <joern.berkefeld@gmail.com>",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/JoernBerkefeld/waba-devtools.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/JoernBerkefeld/waba-devtools/issues"
13
+ },
14
+ "homepage": "https://github.com/JoernBerkefeld/waba-devtools#readme",
15
+ "keywords": [
16
+ "whatsapp",
17
+ "waba",
18
+ "whatsapp-business",
19
+ "message-templates",
20
+ "meta",
21
+ "graph-api",
22
+ "devops",
23
+ "cli"
24
+ ],
25
+ "type": "module",
26
+ "bin": {
27
+ "waba": "./bin/waba.js"
28
+ },
29
+ "main": "./lib/index.js",
30
+ "exports": {
31
+ ".": "./lib/index.js"
32
+ },
33
+ "files": ["bin", "lib", "README.md", "LICENSE"],
34
+ "scripts": {
35
+ "test": "node --test test/*.test.js",
36
+ "lint": "eslint .",
37
+ "lint:fix": "eslint --fix .",
38
+ "format": "prettier --write .",
39
+ "format:check": "prettier --check .",
40
+ "verify:own-dependencies-latest": "node scripts/verify-own-dependencies-latest.mjs",
41
+ "preversion": "npm run verify:own-dependencies-latest",
42
+ "prepare": "husky || true"
43
+ },
44
+ "engines": {
45
+ "node": "^22.22.2 || >=24.15.0"
46
+ },
47
+ "lint-staged": {
48
+ "*.{js,mjs,cjs}": ["eslint --fix"]
49
+ },
50
+ "dependencies": {
51
+ "@joern.berkefeld/csv-parser": "^5.0.0"
52
+ },
53
+ "devDependencies": {
54
+ "@eslint/js": "^10.0.1",
55
+ "eslint": "^10.15.0",
56
+ "eslint-config-prettier": "^10.1.8",
57
+ "eslint-plugin-jsdoc": "^65.5.0",
58
+ "eslint-plugin-prettier": "^5.5.7",
59
+ "eslint-plugin-unicorn": "^80.0.0",
60
+ "globals": "^17.14.0",
61
+ "husky": "^9.1.7",
62
+ "lint-staged": "^17.6.1",
63
+ "prettier": "^3.10.1"
64
+ }
65
+ }