waba-devtools 0.1.0 → 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/README.md +156 -43
- package/lib/budget.js +275 -0
- package/lib/cli.js +101 -5
- package/lib/commands.js +164 -18
- package/lib/compare.js +1 -1
- package/lib/csv.js +436 -55
- package/lib/errors.js +15 -1
- package/lib/graph.js +78 -1
- package/lib/index.js +8 -0
- package/lib/report.js +110 -11
- package/package.json +1 -1
package/lib/csv.js
CHANGED
|
@@ -2,7 +2,13 @@ import { createReadStream } from 'node:fs';
|
|
|
2
2
|
import { open } from 'node:fs/promises';
|
|
3
3
|
import csv, { replayFiles, validateFile } from '@joern.berkefeld/csv-parser';
|
|
4
4
|
import { UsageError } from './errors.js';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
assertSafeIdentity,
|
|
7
|
+
comparableContent,
|
|
8
|
+
normalizeTemplate,
|
|
9
|
+
templateKey,
|
|
10
|
+
unsupportedReason,
|
|
11
|
+
} from './normalize.js';
|
|
6
12
|
|
|
7
13
|
/**
|
|
8
14
|
* CSV columns: our key → accepted header names (compared case-insensitively, trimmed). Other
|
|
@@ -23,7 +29,15 @@ export const CSV_COLUMNS = {
|
|
|
23
29
|
callButton: ['call button'],
|
|
24
30
|
};
|
|
25
31
|
|
|
26
|
-
const REQUIRED_COLUMNS = ['name', 'category', 'body', 'language'];
|
|
32
|
+
const REQUIRED_COLUMNS = ['name', 'category', 'body', 'language', 'examples'];
|
|
33
|
+
/**
|
|
34
|
+
* Example columns a sheet needs when it has the column they belong to. Meta accepts templates
|
|
35
|
+
* without examples, but its UI then refuses to edit them until examples are given.
|
|
36
|
+
*/
|
|
37
|
+
const EXAMPLE_COLUMNS = new Map([
|
|
38
|
+
['header', 'headerExample'],
|
|
39
|
+
['urlButton', 'urlExample'],
|
|
40
|
+
]);
|
|
27
41
|
const BUTTON_COLUMNS = new Map([
|
|
28
42
|
['quickReplies', 'QUICK_REPLY'],
|
|
29
43
|
['urlButton', 'URL'],
|
|
@@ -31,6 +45,12 @@ const BUTTON_COLUMNS = new Map([
|
|
|
31
45
|
]);
|
|
32
46
|
const VARIABLE = /\{\{\s*([^{}]*?)\s*\}\}/g;
|
|
33
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Meta's rule for named variables: lower-case letters, digits and `_`, starting with a letter.
|
|
50
|
+
*/
|
|
51
|
+
const NAMED_VARIABLE = /^[a-z][a-z0-9_]*$/;
|
|
52
|
+
const NUMBERED_VARIABLE = /^\d+$/;
|
|
53
|
+
|
|
34
54
|
/**
|
|
35
55
|
* @typedef {object} CsvRowError
|
|
36
56
|
* @property {number} row - Line number in the sheet (header = 1).
|
|
@@ -40,7 +60,10 @@ const VARIABLE = /\{\{\s*([^{}]*?)\s*\}\}/g;
|
|
|
40
60
|
/**
|
|
41
61
|
* @typedef {object} CsvResult
|
|
42
62
|
* @property {import('./normalize.js').Template[]} templates - One template per good row.
|
|
43
|
-
* @property {CsvRowError[]} errors
|
|
63
|
+
* @property {CsvRowError[]} errors - Rows left out, e.g. a variable without an example (all
|
|
64
|
+
* problems of a row in one message).
|
|
65
|
+
* @property {CsvRowError[]} warnings - Rows read, with something ignored (an example for no
|
|
66
|
+
* variable, an unknown variable name, …).
|
|
44
67
|
* @property {string[]} parts - Template parts the sheet defines (BODY always; HEADER, FOOTER,
|
|
45
68
|
* BUTTON:<type> per button column it has).
|
|
46
69
|
* @property {CsvCleanup} [cleanup] - What was cleaned up while reading the file.
|
|
@@ -149,7 +172,10 @@ export async function readCsvTemplates(file) {
|
|
|
149
172
|
export function templatesFromRows(rows, rowNumbers = rows.map((_, index) => index + 2)) {
|
|
150
173
|
const columns = resolveColumns(rows.length > 0 ? Object.keys(rows[0]) : []);
|
|
151
174
|
if (rows.length > 0) {
|
|
152
|
-
const missing =
|
|
175
|
+
const missing = [
|
|
176
|
+
...REQUIRED_COLUMNS,
|
|
177
|
+
...[...EXAMPLE_COLUMNS].filter(([key]) => columns.has(key)).map(([, key]) => key),
|
|
178
|
+
].filter((key) => !columns.has(key));
|
|
153
179
|
if (missing.length > 0) {
|
|
154
180
|
const names = missing
|
|
155
181
|
.map((key) => CSV_COLUMNS[key].map((alias) => `"${alias}"`).join(' or '))
|
|
@@ -159,11 +185,13 @@ export function templatesFromRows(rows, rowNumbers = rows.map((_, index) => inde
|
|
|
159
185
|
}
|
|
160
186
|
const templates = [];
|
|
161
187
|
const errors = [];
|
|
188
|
+
const warnings = [];
|
|
162
189
|
const seen = new Map();
|
|
163
190
|
for (const [index, row] of rows.entries()) {
|
|
164
191
|
const line = rowNumbers[index];
|
|
165
192
|
try {
|
|
166
|
-
const template = templateFromRow(row, columns);
|
|
193
|
+
const { template, warnings: rowWarnings } = templateFromRow(row, columns);
|
|
194
|
+
warnings.push(...rowWarnings.map((message) => ({ row: line, message })));
|
|
167
195
|
const key = templateKey(template);
|
|
168
196
|
if (seen.has(key)) {
|
|
169
197
|
throw new Error(
|
|
@@ -176,7 +204,7 @@ export function templatesFromRows(rows, rowNumbers = rows.map((_, index) => inde
|
|
|
176
204
|
errors.push({ row: line, message: ex.message });
|
|
177
205
|
}
|
|
178
206
|
}
|
|
179
|
-
return { templates, errors, parts: partsOf(columns) };
|
|
207
|
+
return { templates, errors, warnings, parts: partsOf(columns) };
|
|
180
208
|
}
|
|
181
209
|
|
|
182
210
|
/**
|
|
@@ -220,22 +248,132 @@ function partsOf(columns) {
|
|
|
220
248
|
}
|
|
221
249
|
|
|
222
250
|
/**
|
|
223
|
-
* The
|
|
251
|
+
* The variables of a text, each once, in the order they first appear.
|
|
252
|
+
*
|
|
253
|
+
* @param {string} text
|
|
254
|
+
* @returns {string[]}
|
|
255
|
+
*/
|
|
256
|
+
function variablesOf(text) {
|
|
257
|
+
return [...new Set(text.matchAll(VARIABLE).map(([, variable]) => variable))];
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Highest variable number of a text with numbered variables (0 = none).
|
|
224
262
|
*
|
|
225
263
|
* @param {string} text
|
|
226
|
-
* @returns {number}
|
|
264
|
+
* @returns {number}
|
|
227
265
|
*/
|
|
228
266
|
function variableCount(text) {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
267
|
+
return Math.max(0, ...variablesOf(text).map(Number));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Variable format of a row, from the variables in its body and header: all numbered (`{{1}}`) →
|
|
272
|
+
* POSITIONAL, all named (`{{first_name}}`) → NAMED. No variables → POSITIONAL.
|
|
273
|
+
*
|
|
274
|
+
* @param {string[]} texts
|
|
275
|
+
* @returns {'POSITIONAL'|'NAMED'}
|
|
276
|
+
*/
|
|
277
|
+
function parameterFormatOf(texts) {
|
|
278
|
+
const variables = texts.flatMap((text) => variablesOf(text));
|
|
279
|
+
if (variables.every((variable) => NUMBERED_VARIABLE.test(variable))) {
|
|
280
|
+
return 'POSITIONAL';
|
|
281
|
+
}
|
|
282
|
+
if (variables.every((variable) => NAMED_VARIABLE.test(variable))) {
|
|
283
|
+
return 'NAMED';
|
|
284
|
+
}
|
|
285
|
+
throw new Error(
|
|
286
|
+
'variables must be all numbered like {{1}} or all named in lower case like {{first_name}} ' +
|
|
287
|
+
`(letters, digits, _), found ${variables.map((variable) => `{{${variable}}}`).join(', ')}`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Problems found in one row: errors leave the row out, warnings only inform.
|
|
293
|
+
*
|
|
294
|
+
* @typedef {object} RowNotes
|
|
295
|
+
* @property {string[]} errors
|
|
296
|
+
* @property {string[]} warnings
|
|
297
|
+
*/
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* @param {string[]} variables
|
|
301
|
+
* @returns {string}
|
|
302
|
+
*/
|
|
303
|
+
function variableList(variables) {
|
|
304
|
+
return variables.map((variable) => `{{${variable}}}`).join(', ');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Reads `name=value|other=value` examples for named variables (any order). A variable without an
|
|
309
|
+
* example is an error; an unknown name, a name given twice or an unreadable part only a warning.
|
|
310
|
+
*
|
|
311
|
+
* @param {string} cell
|
|
312
|
+
* @param {string[]} names - Variables of the text.
|
|
313
|
+
* @param {string} column - For the messages.
|
|
314
|
+
* @param {RowNotes} notes
|
|
315
|
+
* @returns {{param_name: string, example: string}[]} In the order of `names`.
|
|
316
|
+
*/
|
|
317
|
+
function namedExamples(cell, names, column, notes) {
|
|
318
|
+
const examples = new Map();
|
|
319
|
+
const parts = cell
|
|
320
|
+
.split('|')
|
|
321
|
+
.map((item) => item.trim())
|
|
322
|
+
.filter(Boolean);
|
|
323
|
+
for (const part of parts) {
|
|
324
|
+
const separator = part.indexOf('=');
|
|
325
|
+
const name = separator === -1 ? '' : part.slice(0, separator).trim();
|
|
326
|
+
const example = separator === -1 ? '' : part.slice(separator + 1).trim();
|
|
327
|
+
if (!name || !example) {
|
|
328
|
+
notes.warnings.push(`${column}: "${part}" is not name=value, ignored`);
|
|
329
|
+
} else if (!names.includes(name)) {
|
|
330
|
+
notes.warnings.push(`${column}: {{${name}}} is not in the text, ignored`);
|
|
331
|
+
} else if (examples.has(name)) {
|
|
332
|
+
notes.warnings.push(`${column}: ${name} is given twice, the first one is used`);
|
|
333
|
+
} else {
|
|
334
|
+
examples.set(name, example);
|
|
235
335
|
}
|
|
236
|
-
count = Math.max(count, Number(variable));
|
|
237
336
|
}
|
|
238
|
-
|
|
337
|
+
const missing = names.filter((name) => !examples.has(name));
|
|
338
|
+
if (missing.length > 0) {
|
|
339
|
+
notes.errors.push(
|
|
340
|
+
`${column}: no example for ${variableList(missing)} ` +
|
|
341
|
+
'(write name=value, separated by |, e.g. "first_name=Jane|order_id=A-1234")',
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
return names.map((name) => ({ param_name: name, example: examples.get(name) ?? '' }));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Reads `value|value` examples for numbered variables `{{1}}`…`{{count}}`, in that order. A
|
|
349
|
+
* variable without an example is an error; examples beyond `count` are only a warning.
|
|
350
|
+
*
|
|
351
|
+
* @param {string} cell
|
|
352
|
+
* @param {number} count - Highest variable number of the text (0 = none).
|
|
353
|
+
* @param {string} column - For the messages.
|
|
354
|
+
* @param {RowNotes} notes
|
|
355
|
+
* @returns {string[]} `count` examples.
|
|
356
|
+
*/
|
|
357
|
+
function numberedExamples(cell, count, column, notes) {
|
|
358
|
+
const examples = cell === '' ? [] : cell.split('|').map((example) => example.trim());
|
|
359
|
+
const missing = Array.from({ length: count }, (_, index) => index + 1).filter(
|
|
360
|
+
(number) => (examples.at(number - 1) ?? '') === '',
|
|
361
|
+
);
|
|
362
|
+
if (missing.length > 0) {
|
|
363
|
+
notes.errors.push(
|
|
364
|
+
`${column}: no example for ${variableList(missing.map(String))} ` +
|
|
365
|
+
'(one per variable in the order {{1}}, {{2}}, …, separated by |)',
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
const extra = examples.slice(count).filter(Boolean).length;
|
|
369
|
+
if (extra > 0) {
|
|
370
|
+
notes.warnings.push(
|
|
371
|
+
count === 0
|
|
372
|
+
? `${column}: the text has no variables, the example(s) are ignored`
|
|
373
|
+
: `${column}: ${extra} example(s) more than the text's ${count} variable(s), ignored`,
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
return Array.from({ length: count }, (_, index) => examples[index] ?? '');
|
|
239
377
|
}
|
|
240
378
|
|
|
241
379
|
/**
|
|
@@ -257,49 +395,77 @@ function splitPair(cell, column) {
|
|
|
257
395
|
|
|
258
396
|
/**
|
|
259
397
|
* @param {(key: string) => string} value
|
|
398
|
+
* @param {'POSITIONAL'|'NAMED'} format
|
|
399
|
+
* @param {RowNotes} notes
|
|
260
400
|
* @returns {object|undefined} BODY component.
|
|
261
401
|
*/
|
|
262
|
-
function bodyComponent(value) {
|
|
402
|
+
function bodyComponent(value, format, notes) {
|
|
263
403
|
const text = value('body');
|
|
264
|
-
const count = variableCount(text);
|
|
265
404
|
const body = { type: 'BODY', text };
|
|
266
|
-
if (
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
.
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
405
|
+
if (format === 'NAMED') {
|
|
406
|
+
const names = variablesOf(text);
|
|
407
|
+
if (names.length > 0) {
|
|
408
|
+
body.example = {
|
|
409
|
+
body_text_named_params: namedExamples(
|
|
410
|
+
value('examples'),
|
|
411
|
+
names,
|
|
412
|
+
'Body examples',
|
|
413
|
+
notes,
|
|
414
|
+
),
|
|
415
|
+
};
|
|
277
416
|
}
|
|
278
|
-
body
|
|
417
|
+
return body;
|
|
418
|
+
}
|
|
419
|
+
const count = variableCount(text);
|
|
420
|
+
const examples = numberedExamples(value('examples'), count, 'Body examples', notes);
|
|
421
|
+
if (count > 0) {
|
|
422
|
+
body.example = { body_text: [examples] };
|
|
279
423
|
}
|
|
280
424
|
return body;
|
|
281
425
|
}
|
|
282
426
|
|
|
283
427
|
/**
|
|
284
428
|
* @param {(key: string) => string} value
|
|
429
|
+
* @param {'POSITIONAL'|'NAMED'} format
|
|
430
|
+
* @param {RowNotes} notes
|
|
285
431
|
* @returns {object|undefined} HEADER component (text only), or none for an empty cell.
|
|
286
432
|
*/
|
|
287
|
-
function headerComponent(value) {
|
|
433
|
+
function headerComponent(value, format, notes) {
|
|
288
434
|
const text = value('header');
|
|
435
|
+
const example = value('headerExample');
|
|
289
436
|
if (!text) {
|
|
437
|
+
if (example) {
|
|
438
|
+
notes.warnings.push('Header example: the row has no header, the example is ignored');
|
|
439
|
+
}
|
|
290
440
|
return;
|
|
291
441
|
}
|
|
442
|
+
const header = { type: 'HEADER', format: 'TEXT', text };
|
|
443
|
+
if (format === 'NAMED') {
|
|
444
|
+
const names = variablesOf(text);
|
|
445
|
+
if (names.length > 1) {
|
|
446
|
+
throw new Error('Header: at most one variable');
|
|
447
|
+
}
|
|
448
|
+
if (names.length === 1) {
|
|
449
|
+
header.example = {
|
|
450
|
+
header_text_named_params: namedExamples(example, names, 'Header example', notes),
|
|
451
|
+
};
|
|
452
|
+
} else if (example) {
|
|
453
|
+
notes.warnings.push(
|
|
454
|
+
'Header example: the header has no variable, the example is ignored',
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
return header;
|
|
458
|
+
}
|
|
292
459
|
const count = variableCount(text);
|
|
293
460
|
if (count > 1 || (count === 1 && !text.includes('{{1}}'))) {
|
|
294
461
|
throw new Error('Header: at most one variable, written {{1}}');
|
|
295
462
|
}
|
|
296
|
-
|
|
297
|
-
if (count === 1) {
|
|
298
|
-
const example = value('headerExample');
|
|
299
|
-
if (!example) {
|
|
300
|
-
throw new Error('Header has {{1}}: fill in the Header example column');
|
|
301
|
-
}
|
|
463
|
+
if (count === 1 && example) {
|
|
302
464
|
header.example = { header_text: [example] };
|
|
465
|
+
} else if (count === 1) {
|
|
466
|
+
notes.errors.push('Header example: no example for {{1}}');
|
|
467
|
+
} else if (example) {
|
|
468
|
+
notes.warnings.push('Header example: the header has no variable, the example is ignored');
|
|
303
469
|
}
|
|
304
470
|
return header;
|
|
305
471
|
}
|
|
@@ -321,32 +487,38 @@ function footerComponent(value) {
|
|
|
321
487
|
|
|
322
488
|
/**
|
|
323
489
|
* @param {(key: string) => string} value
|
|
490
|
+
* @param {RowNotes} notes
|
|
324
491
|
* @returns {object|undefined} BUTTONS component, or none when all button cells are empty.
|
|
325
492
|
*/
|
|
326
|
-
function buttonsComponent(value) {
|
|
493
|
+
function buttonsComponent(value, notes) {
|
|
327
494
|
const buttons = value('quickReplies')
|
|
328
495
|
.split('|')
|
|
329
496
|
.map((label) => label.trim())
|
|
330
497
|
.filter(Boolean)
|
|
331
498
|
.map((text) => ({ type: 'QUICK_REPLY', text }));
|
|
499
|
+
const example = value('urlExample');
|
|
332
500
|
if (value('urlButton')) {
|
|
333
501
|
const [text, url] = splitPair(value('urlButton'), 'URL button');
|
|
334
502
|
if (!/^https?:\/\//.test(url)) {
|
|
335
503
|
throw new Error('URL button: the URL must start with https:// or http://');
|
|
336
504
|
}
|
|
337
|
-
const
|
|
505
|
+
const variables = variablesOf(url);
|
|
338
506
|
const button = { type: 'URL', text, url };
|
|
339
|
-
if (
|
|
340
|
-
if (
|
|
507
|
+
if (variables.length > 0) {
|
|
508
|
+
if (variables.length > 1 || variables[0] !== '1' || !url.endsWith('{{1}}')) {
|
|
341
509
|
throw new Error('URL button: only one variable, {{1}} at the very end of the URL');
|
|
342
510
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
511
|
+
if (example) {
|
|
512
|
+
button.example = [url.replace('{{1}}', () => example)];
|
|
513
|
+
} else {
|
|
514
|
+
notes.errors.push('URL example: no example for {{1}} of the URL button');
|
|
346
515
|
}
|
|
347
|
-
|
|
516
|
+
} else if (example) {
|
|
517
|
+
notes.warnings.push('URL example: the URL has no variable, the example is ignored');
|
|
348
518
|
}
|
|
349
519
|
buttons.push(button);
|
|
520
|
+
} else if (example) {
|
|
521
|
+
notes.warnings.push('URL example: the row has no URL button, the example is ignored');
|
|
350
522
|
}
|
|
351
523
|
if (value('callButton')) {
|
|
352
524
|
const [text, phone] = splitPair(value('callButton'), 'Call button');
|
|
@@ -362,7 +534,7 @@ function buttonsComponent(value) {
|
|
|
362
534
|
/**
|
|
363
535
|
* @param {Object.<string, string>} row
|
|
364
536
|
* @param {Map.<string, string>} columns - From `resolveColumns`.
|
|
365
|
-
* @returns {import('./normalize.js').Template}
|
|
537
|
+
* @returns {{template: import('./normalize.js').Template, warnings: string[]}}
|
|
366
538
|
*/
|
|
367
539
|
function templateFromRow(row, columns) {
|
|
368
540
|
const value = (key) =>
|
|
@@ -381,17 +553,226 @@ function templateFromRow(row, columns) {
|
|
|
381
553
|
if (category.toUpperCase() === 'AUTHENTICATION') {
|
|
382
554
|
throw new Error('authentication (OTP) templates are not supported yet');
|
|
383
555
|
}
|
|
556
|
+
const format = parameterFormatOf([value('body'), value('header')]);
|
|
557
|
+
/**
|
|
558
|
+
@type {RowNotes}
|
|
559
|
+
*/
|
|
560
|
+
const notes = { errors: [], warnings: [] };
|
|
384
561
|
const components = [
|
|
385
|
-
headerComponent(value),
|
|
386
|
-
bodyComponent(value),
|
|
562
|
+
headerComponent(value, format, notes),
|
|
563
|
+
bodyComponent(value, format, notes),
|
|
387
564
|
footerComponent(value),
|
|
388
|
-
buttonsComponent(value),
|
|
565
|
+
buttonsComponent(value, notes),
|
|
389
566
|
].filter(Boolean);
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
567
|
+
if (notes.errors.length > 0) {
|
|
568
|
+
throw new Error(notes.errors.join('; '));
|
|
569
|
+
}
|
|
570
|
+
return {
|
|
571
|
+
template: normalizeTemplate({
|
|
572
|
+
name,
|
|
573
|
+
language,
|
|
574
|
+
category,
|
|
575
|
+
parameter_format: format,
|
|
576
|
+
components,
|
|
577
|
+
}),
|
|
578
|
+
warnings: notes.warnings,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Header row written by `templatesToCsv`: every column the importer reads.
|
|
584
|
+
*/
|
|
585
|
+
const EXPORT_HEADERS = [
|
|
586
|
+
['name', 'Template name'],
|
|
587
|
+
['category', 'Category'],
|
|
588
|
+
['language', 'Language'],
|
|
589
|
+
['body', 'Body'],
|
|
590
|
+
['examples', 'Body examples'],
|
|
591
|
+
['header', 'Header'],
|
|
592
|
+
['headerExample', 'Header example'],
|
|
593
|
+
['footer', 'Footer'],
|
|
594
|
+
['quickReplies', 'Quick replies'],
|
|
595
|
+
['urlButton', 'URL button'],
|
|
596
|
+
['urlExample', 'URL example'],
|
|
597
|
+
['callButton', 'Call button'],
|
|
598
|
+
];
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* @param {{param_name: string, example: string}[]|undefined} parameters
|
|
602
|
+
* @returns {string} `name=value|other=value`.
|
|
603
|
+
*/
|
|
604
|
+
function namedCell(parameters) {
|
|
605
|
+
return (parameters ?? []).map((item) => `${item.param_name}=${item.example}`).join('|');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Cells of the buttons of a template (quick replies, one URL button, one call button).
|
|
610
|
+
*
|
|
611
|
+
* @param {object[]} buttons
|
|
612
|
+
* @param {Object.<string, string>} cells - Updated in place.
|
|
613
|
+
* @returns {void}
|
|
614
|
+
*/
|
|
615
|
+
function buttonCells(buttons, cells) {
|
|
616
|
+
const quickReplies = [];
|
|
617
|
+
for (const button of buttons) {
|
|
618
|
+
if (button.type === 'QUICK_REPLY') {
|
|
619
|
+
quickReplies.push(button.text);
|
|
620
|
+
} else if (button.type === 'URL' && !cells.urlButton) {
|
|
621
|
+
cells.urlButton = `${button.text}|${button.url}`;
|
|
622
|
+
if (String(button.url).endsWith('{{1}}')) {
|
|
623
|
+
const prefix = button.url.slice(0, -'{{1}}'.length);
|
|
624
|
+
const example = String(button.example?.[0] ?? '');
|
|
625
|
+
cells.urlExample = example.startsWith(prefix) ? example.slice(prefix.length) : '';
|
|
626
|
+
}
|
|
627
|
+
} else if (button.type === 'PHONE_NUMBER' && !cells.callButton) {
|
|
628
|
+
cells.callButton = `${button.text}|${button.phone_number}`;
|
|
629
|
+
} else {
|
|
630
|
+
throw new Error(
|
|
631
|
+
['URL', 'PHONE_NUMBER'].includes(button.type)
|
|
632
|
+
? `more than one ${button.type} button cannot be written to CSV`
|
|
633
|
+
: `${button.type} buttons cannot be written to CSV`,
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
cells.quickReplies = quickReplies.join('|');
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Fills the cells of one template component. Throws for what the columns cannot hold.
|
|
642
|
+
*
|
|
643
|
+
* @param {object} component
|
|
644
|
+
* @param {Object.<string, string>} cells - Updated in place.
|
|
645
|
+
* @param {boolean} isNamed - The template uses named variables.
|
|
646
|
+
* @returns {void}
|
|
647
|
+
*/
|
|
648
|
+
function componentCells(component, cells, isNamed) {
|
|
649
|
+
switch (component.type) {
|
|
650
|
+
case 'HEADER': {
|
|
651
|
+
if (component.format !== 'TEXT') {
|
|
652
|
+
throw new Error(`${component.format ?? 'this'} headers cannot be written to CSV`);
|
|
653
|
+
}
|
|
654
|
+
cells.header = component.text ?? '';
|
|
655
|
+
cells.headerExample = isNamed
|
|
656
|
+
? namedCell(component.example?.header_text_named_params)
|
|
657
|
+
: (component.example?.header_text?.[0] ?? '');
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
case 'BODY': {
|
|
661
|
+
cells.body = component.text ?? '';
|
|
662
|
+
cells.examples = isNamed
|
|
663
|
+
? namedCell(component.example?.body_text_named_params)
|
|
664
|
+
: (component.example?.body_text?.[0] ?? []).join('|');
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
case 'FOOTER': {
|
|
668
|
+
cells.footer = component.text ?? '';
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
case 'BUTTONS': {
|
|
672
|
+
buttonCells(component.buttons ?? [], cells);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
default: {
|
|
676
|
+
throw new Error(`${component.type} components cannot be written to CSV`);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* The CSV cells of one template, keyed like `CSV_COLUMNS`. Throws for what the columns cannot hold.
|
|
683
|
+
*
|
|
684
|
+
* @param {import('./normalize.js').Template} template - Normalized.
|
|
685
|
+
* @returns {Object.<string, string>}
|
|
686
|
+
*/
|
|
687
|
+
function cellsOf(template) {
|
|
688
|
+
const reason = unsupportedReason(template);
|
|
689
|
+
if (reason) {
|
|
690
|
+
throw new Error(reason);
|
|
691
|
+
}
|
|
692
|
+
const isNamed = template.parameter_format === 'NAMED';
|
|
693
|
+
const cells = Object.fromEntries(EXPORT_HEADERS.map(([key]) => [key, '']));
|
|
694
|
+
Object.assign(cells, {
|
|
695
|
+
name: template.name ?? '',
|
|
696
|
+
category: template.category ?? '',
|
|
697
|
+
language: template.language ?? '',
|
|
396
698
|
});
|
|
699
|
+
const components = template.components ?? [];
|
|
700
|
+
for (const component of components) {
|
|
701
|
+
componentCells(component, cells, isNamed);
|
|
702
|
+
}
|
|
703
|
+
return cells;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* True when the template read back from its CSV row is the same template. The variable format only
|
|
708
|
+
* counts when the template has variables (a row without variables always reads as POSITIONAL).
|
|
709
|
+
*
|
|
710
|
+
* @param {import('./normalize.js').Template} original
|
|
711
|
+
* @param {import('./normalize.js').Template} parsed
|
|
712
|
+
* @returns {boolean}
|
|
713
|
+
*/
|
|
714
|
+
function isSameTemplate(original, parsed) {
|
|
715
|
+
const hasVariables = JSON.stringify(original.components ?? []).includes('{{');
|
|
716
|
+
const content = (template) =>
|
|
717
|
+
comparableContent({
|
|
718
|
+
...template,
|
|
719
|
+
parameter_format: hasVariables ? template.parameter_format : undefined,
|
|
720
|
+
});
|
|
721
|
+
return (
|
|
722
|
+
templateKey(original) === templateKey(parsed) &&
|
|
723
|
+
original.category === parsed.category &&
|
|
724
|
+
content(original) === content(parsed)
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Quotes a CSV field when needed (RFC 4180).
|
|
730
|
+
*
|
|
731
|
+
* @param {string} field
|
|
732
|
+
* @returns {string}
|
|
733
|
+
*/
|
|
734
|
+
function csvField(field) {
|
|
735
|
+
return /[",\r\n]/.test(field) ? `"${field.replaceAll('"', '""')}"` : field;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Writes templates as CSV with the columns the importer reads (`import --csv` / `deploy --csv`), so
|
|
740
|
+
* the file can be edited in a spreadsheet and read back. Every exported row reads back as exactly the
|
|
741
|
+
* same template; templates the columns cannot hold are listed in `skipped` instead (media headers,
|
|
742
|
+
* carousels, authentication, other button types, more than one URL or call button, a `|` inside a
|
|
743
|
+
* label or example, missing examples, …).
|
|
744
|
+
*
|
|
745
|
+
* @param {object[]} templates - Templates from files, a backup set or the Graph API.
|
|
746
|
+
* @returns {{csv: string, skipped: {name: string, language: string, reason: string}[]}} `csv` has a
|
|
747
|
+
* header row and LF line endings, without a byte-order mark.
|
|
748
|
+
*/
|
|
749
|
+
export function templatesToCsv(templates) {
|
|
750
|
+
const columns = resolveColumns(EXPORT_HEADERS.map(([, header]) => header.toLowerCase()));
|
|
751
|
+
const lines = [EXPORT_HEADERS.map(([, header]) => csvField(header)).join(',')];
|
|
752
|
+
const skipped = [];
|
|
753
|
+
for (const raw of templates) {
|
|
754
|
+
const template = normalizeTemplate(raw);
|
|
755
|
+
try {
|
|
756
|
+
const cells = cellsOf(template);
|
|
757
|
+
const row = Object.fromEntries(
|
|
758
|
+
EXPORT_HEADERS.map(([key, header]) => [header.toLowerCase(), cells[key]]),
|
|
759
|
+
);
|
|
760
|
+
let parsed;
|
|
761
|
+
try {
|
|
762
|
+
({ template: parsed } = templateFromRow(row, columns));
|
|
763
|
+
} catch (ex) {
|
|
764
|
+
throw new Error(`it would not read back: ${ex.message}`, { cause: ex });
|
|
765
|
+
}
|
|
766
|
+
if (!isSameTemplate(template, parsed)) {
|
|
767
|
+
throw new Error(
|
|
768
|
+
'it would read back differently (e.g. a | inside a label or example, spaces ' +
|
|
769
|
+
'around a text, or buttons in another order)',
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
lines.push(EXPORT_HEADERS.map(([key]) => csvField(cells[key])).join(','));
|
|
773
|
+
} catch (ex) {
|
|
774
|
+
skipped.push({ name: template.name, language: template.language, reason: ex.message });
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
return { csv: `${lines.join('\n')}\n`, skipped };
|
|
397
778
|
}
|
package/lib/errors.js
CHANGED
|
@@ -29,8 +29,19 @@ export class GraphError extends Error {
|
|
|
29
29
|
* @param {string} [details.userTitle] - Meta's `error_user_title`.
|
|
30
30
|
* @param {string} [details.userMessage] - Meta's `error_user_msg`.
|
|
31
31
|
* @param {string} [details.traceId] - Meta's `fbtrace_id`.
|
|
32
|
+
* @param {number} [details.regainAccessMinutes] - Meta's `estimated_time_to_regain_access` from
|
|
33
|
+
* the `X-Business-Use-Case-Usage` header, when a throttled response carried it.
|
|
32
34
|
*/
|
|
33
|
-
constructor({
|
|
35
|
+
constructor({
|
|
36
|
+
httpStatus,
|
|
37
|
+
message,
|
|
38
|
+
code,
|
|
39
|
+
subcode,
|
|
40
|
+
userTitle,
|
|
41
|
+
userMessage,
|
|
42
|
+
traceId,
|
|
43
|
+
regainAccessMinutes,
|
|
44
|
+
}) {
|
|
34
45
|
super(message);
|
|
35
46
|
this.name = 'GraphError';
|
|
36
47
|
this.httpStatus = httpStatus;
|
|
@@ -39,6 +50,9 @@ export class GraphError extends Error {
|
|
|
39
50
|
this.userTitle = userTitle;
|
|
40
51
|
this.userMessage = userMessage;
|
|
41
52
|
this.traceId = traceId;
|
|
53
|
+
if (regainAccessMinutes !== undefined) {
|
|
54
|
+
this.regainAccessMinutes = regainAccessMinutes;
|
|
55
|
+
}
|
|
42
56
|
}
|
|
43
57
|
|
|
44
58
|
/**
|