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/csv.js ADDED
@@ -0,0 +1,778 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import csv, { replayFiles, validateFile } from '@joern.berkefeld/csv-parser';
4
+ import { UsageError } from './errors.js';
5
+ import {
6
+ assertSafeIdentity,
7
+ comparableContent,
8
+ normalizeTemplate,
9
+ templateKey,
10
+ unsupportedReason,
11
+ } from './normalize.js';
12
+
13
+ /**
14
+ * CSV columns: our key → accepted header names (compared case-insensitively, trimmed). Other
15
+ * columns are ignored.
16
+ */
17
+ export const CSV_COLUMNS = {
18
+ name: ['template name'],
19
+ category: ['category'],
20
+ language: ['language'],
21
+ body: ['body', 'meta template'],
22
+ examples: ['body examples', 'examples'],
23
+ header: ['header'],
24
+ headerExample: ['header example'],
25
+ footer: ['footer'],
26
+ quickReplies: ['quick replies'],
27
+ urlButton: ['url button'],
28
+ urlExample: ['url example'],
29
+ callButton: ['call button'],
30
+ };
31
+
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
+ ]);
41
+ const BUTTON_COLUMNS = new Map([
42
+ ['quickReplies', 'QUICK_REPLY'],
43
+ ['urlButton', 'URL'],
44
+ ['callButton', 'PHONE_NUMBER'],
45
+ ]);
46
+ const VARIABLE = /\{\{\s*([^{}]*?)\s*\}\}/g;
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
+
54
+ /**
55
+ * @typedef {object} CsvRowError
56
+ * @property {number} row - Line number in the sheet (header = 1).
57
+ * @property {string} message
58
+ */
59
+
60
+ /**
61
+ * @typedef {object} CsvResult
62
+ * @property {import('./normalize.js').Template[]} templates - One template per good row.
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, …).
67
+ * @property {string[]} parts - Template parts the sheet defines (BODY always; HEADER, FOOTER,
68
+ * BUTTON:<type> per button column it has).
69
+ * @property {CsvCleanup} [cleanup] - What was cleaned up while reading the file.
70
+ */
71
+
72
+ /**
73
+ * @typedef {object} CsvCleanup
74
+ * @property {number} removedColumns - Empty columns removed on the right (no header, no values).
75
+ * @property {number} removedRecords - Empty rows removed at the bottom.
76
+ * @property {number} skippedRecords - Empty rows skipped in between.
77
+ */
78
+
79
+ /**
80
+ * Parser options, the same as sfmc-dataloader uses for its CSV imports: strict width and quoting,
81
+ * BOM removal, empty rows skipped, empty right-padding columns and bottom rows removed.
82
+ */
83
+ const PARSER_OPTIONS = {
84
+ bom: true,
85
+ strict: true,
86
+ strictQuotes: true,
87
+ skipEmptyLines: true,
88
+ sanitizeRightPadding: true,
89
+ sanitizeBottom: true,
90
+ mapHeaders: ({ header }) => header.trim().toLowerCase(),
91
+ outputByteOffset: true,
92
+ };
93
+
94
+ /**
95
+ * Line ending of the file, taken from the end of the header line: `\r` for old Mac exports,
96
+ * otherwise `\n` (the parser handles `\r\n` with it).
97
+ *
98
+ * @param {string} file
99
+ * @returns {Promise.<string>}
100
+ */
101
+ async function detectNewline(file) {
102
+ const handle = await open(file);
103
+ try {
104
+ const { buffer, bytesRead } = await handle.read({ buffer: Buffer.alloc(64 * 1024) });
105
+ const text = buffer.subarray(0, bytesRead).toString('latin1');
106
+ const end = text.search(/[\r\n]/);
107
+ return end !== -1 && text[end] === '\r' && text[end + 1] !== '\n' ? '\r' : '\n';
108
+ } finally {
109
+ await handle.close();
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Row number in the sheet of every record in the file, by byte offset. Counts every record,
115
+ * also the empty ones that are skipped while parsing.
116
+ *
117
+ * @param {string} file
118
+ * @param {string} newline - From `detectNewline`, so both passes split records the same way.
119
+ * @returns {Promise.<Map.<number, number>>} Byte offset to row number.
120
+ */
121
+ async function recordOffsets(file, newline) {
122
+ const rowNumbers = new Map();
123
+ const parser = createReadStream(file).pipe(
124
+ csv({ bom: true, headers: false, skipEmptyLines: false, outputByteOffset: true, newline }),
125
+ );
126
+ for await (const { byteOffset } of parser) {
127
+ rowNumbers.set(byteOffset, rowNumbers.size + 1);
128
+ }
129
+ return rowNumbers;
130
+ }
131
+
132
+ /**
133
+ * Reads a Google Sheets (or other) CSV export into body-only templates.
134
+ *
135
+ * @param {string} file - CSV path.
136
+ * @returns {Promise.<CsvResult>}
137
+ */
138
+ export async function readCsvTemplates(file) {
139
+ const rows = [];
140
+ const rowNumbers = [];
141
+ let validation;
142
+ try {
143
+ const newline = await detectNewline(file);
144
+ validation = await validateFile(file, { ...PARSER_OPTIONS, newline });
145
+ const offsets = await recordOffsets(file, newline);
146
+ for await (const { row, byteOffset } of replayFiles(validation)) {
147
+ rows.push(row);
148
+ const rowNumber = offsets.get(byteOffset);
149
+ if (rowNumber === undefined) {
150
+ throw new Error(`no row number for the record at byte ${byteOffset}`);
151
+ }
152
+ rowNumbers.push(rowNumber);
153
+ }
154
+ } catch (ex) {
155
+ throw new UsageError(`Could not read CSV ${file}: ${ex.message}`);
156
+ }
157
+ if (!validation.headers || validation.headers.length === 0) {
158
+ throw new UsageError(`CSV ${file} has no header row.`);
159
+ }
160
+ const { removedColumns, removedRecords, skippedRecords } = validation.cleanup;
161
+ return {
162
+ ...templatesFromRows(rows, rowNumbers),
163
+ cleanup: { removedColumns, removedRecords, skippedRecords },
164
+ };
165
+ }
166
+
167
+ /**
168
+ * @param {Object.<string, string>[]} rows - Parsed rows keyed by lower-case header.
169
+ * @param {number[]} [rowNumbers] - Row number in the sheet per row (default: header = 1, no gaps).
170
+ * @returns {CsvResult}
171
+ */
172
+ export function templatesFromRows(rows, rowNumbers = rows.map((_, index) => index + 2)) {
173
+ const columns = resolveColumns(rows.length > 0 ? Object.keys(rows[0]) : []);
174
+ if (rows.length > 0) {
175
+ const missing = [
176
+ ...REQUIRED_COLUMNS,
177
+ ...[...EXAMPLE_COLUMNS].filter(([key]) => columns.has(key)).map(([, key]) => key),
178
+ ].filter((key) => !columns.has(key));
179
+ if (missing.length > 0) {
180
+ const names = missing
181
+ .map((key) => CSV_COLUMNS[key].map((alias) => `"${alias}"`).join(' or '))
182
+ .join(', ');
183
+ throw new UsageError(`CSV is missing the column(s) ${names}.`);
184
+ }
185
+ }
186
+ const templates = [];
187
+ const errors = [];
188
+ const warnings = [];
189
+ const seen = new Map();
190
+ for (const [index, row] of rows.entries()) {
191
+ const line = rowNumbers[index];
192
+ try {
193
+ const { template, warnings: rowWarnings } = templateFromRow(row, columns);
194
+ warnings.push(...rowWarnings.map((message) => ({ row: line, message })));
195
+ const key = templateKey(template);
196
+ if (seen.has(key)) {
197
+ throw new Error(
198
+ `duplicate of row ${seen.get(key)} (${template.name}, ${template.language})`,
199
+ );
200
+ }
201
+ seen.set(key, line);
202
+ templates.push(template);
203
+ } catch (ex) {
204
+ errors.push({ row: line, message: ex.message });
205
+ }
206
+ }
207
+ return { templates, errors, warnings, parts: partsOf(columns) };
208
+ }
209
+
210
+ /**
211
+ * Which of our columns the sheet has, mapped to the sheet's (lower-case) header.
212
+ *
213
+ * @param {string[]} headers
214
+ * @returns {Map.<string, string>} Column key to header.
215
+ */
216
+ function resolveColumns(headers) {
217
+ const present = new Set(headers);
218
+ const columns = new Map();
219
+ for (const [key, aliases] of Object.entries(CSV_COLUMNS)) {
220
+ const header = aliases.find((alias) => present.has(alias));
221
+ if (header) {
222
+ columns.set(key, header);
223
+ }
224
+ }
225
+ return columns;
226
+ }
227
+
228
+ /**
229
+ * The template parts the sheet defines. A part without a column stays as it is in the target.
230
+ *
231
+ * @param {Map.<string, string>} columns
232
+ * @returns {string[]}
233
+ */
234
+ function partsOf(columns) {
235
+ const parts = ['BODY'];
236
+ if (columns.has('header')) {
237
+ parts.push('HEADER');
238
+ }
239
+ if (columns.has('footer')) {
240
+ parts.push('FOOTER');
241
+ }
242
+ for (const [key, type] of BUTTON_COLUMNS) {
243
+ if (columns.has(key)) {
244
+ parts.push(`BUTTON:${type}`);
245
+ }
246
+ }
247
+ return parts;
248
+ }
249
+
250
+ /**
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).
262
+ *
263
+ * @param {string} text
264
+ * @returns {number}
265
+ */
266
+ function variableCount(text) {
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);
335
+ }
336
+ }
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] ?? '');
377
+ }
378
+
379
+ /**
380
+ * Splits `label|value` cells (URL and call buttons).
381
+ *
382
+ * @param {string} cell
383
+ * @param {string} column - For the error message.
384
+ * @returns {[string, string]}
385
+ */
386
+ function splitPair(cell, column) {
387
+ const separator = cell.indexOf('|');
388
+ const label = separator === -1 ? '' : cell.slice(0, separator).trim();
389
+ const value = separator === -1 ? '' : cell.slice(separator + 1).trim();
390
+ if (!label || !value) {
391
+ throw new Error(`${column}: write label|value, e.g. "Track|https://example.com/{{1}}"`);
392
+ }
393
+ return [label, value];
394
+ }
395
+
396
+ /**
397
+ * @param {(key: string) => string} value
398
+ * @param {'POSITIONAL'|'NAMED'} format
399
+ * @param {RowNotes} notes
400
+ * @returns {object|undefined} BODY component.
401
+ */
402
+ function bodyComponent(value, format, notes) {
403
+ const text = value('body');
404
+ const body = { type: 'BODY', text };
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
+ };
416
+ }
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] };
423
+ }
424
+ return body;
425
+ }
426
+
427
+ /**
428
+ * @param {(key: string) => string} value
429
+ * @param {'POSITIONAL'|'NAMED'} format
430
+ * @param {RowNotes} notes
431
+ * @returns {object|undefined} HEADER component (text only), or none for an empty cell.
432
+ */
433
+ function headerComponent(value, format, notes) {
434
+ const text = value('header');
435
+ const example = value('headerExample');
436
+ if (!text) {
437
+ if (example) {
438
+ notes.warnings.push('Header example: the row has no header, the example is ignored');
439
+ }
440
+ return;
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
+ }
459
+ const count = variableCount(text);
460
+ if (count > 1 || (count === 1 && !text.includes('{{1}}'))) {
461
+ throw new Error('Header: at most one variable, written {{1}}');
462
+ }
463
+ if (count === 1 && example) {
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');
469
+ }
470
+ return header;
471
+ }
472
+
473
+ /**
474
+ * @param {(key: string) => string} value
475
+ * @returns {object|undefined} FOOTER component, or none for an empty cell.
476
+ */
477
+ function footerComponent(value) {
478
+ const text = value('footer');
479
+ if (!text) {
480
+ return;
481
+ }
482
+ if (text.includes('{{')) {
483
+ throw new Error('Footer: variables are not allowed');
484
+ }
485
+ return { type: 'FOOTER', text };
486
+ }
487
+
488
+ /**
489
+ * @param {(key: string) => string} value
490
+ * @param {RowNotes} notes
491
+ * @returns {object|undefined} BUTTONS component, or none when all button cells are empty.
492
+ */
493
+ function buttonsComponent(value, notes) {
494
+ const buttons = value('quickReplies')
495
+ .split('|')
496
+ .map((label) => label.trim())
497
+ .filter(Boolean)
498
+ .map((text) => ({ type: 'QUICK_REPLY', text }));
499
+ const example = value('urlExample');
500
+ if (value('urlButton')) {
501
+ const [text, url] = splitPair(value('urlButton'), 'URL button');
502
+ if (!/^https?:\/\//.test(url)) {
503
+ throw new Error('URL button: the URL must start with https:// or http://');
504
+ }
505
+ const variables = variablesOf(url);
506
+ const button = { type: 'URL', text, url };
507
+ if (variables.length > 0) {
508
+ if (variables.length > 1 || variables[0] !== '1' || !url.endsWith('{{1}}')) {
509
+ throw new Error('URL button: only one variable, {{1}} at the very end of the URL');
510
+ }
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');
515
+ }
516
+ } else if (example) {
517
+ notes.warnings.push('URL example: the URL has no variable, the example is ignored');
518
+ }
519
+ buttons.push(button);
520
+ } else if (example) {
521
+ notes.warnings.push('URL example: the row has no URL button, the example is ignored');
522
+ }
523
+ if (value('callButton')) {
524
+ const [text, phone] = splitPair(value('callButton'), 'Call button');
525
+ const phoneNumber = phone.replaceAll(/[\s()-]/g, '');
526
+ if (!/^\+\d{6,15}$/.test(phoneNumber)) {
527
+ throw new Error('Call button: phone number with country code, e.g. +15550100');
528
+ }
529
+ buttons.push({ type: 'PHONE_NUMBER', text, phone_number: phoneNumber });
530
+ }
531
+ return buttons.length > 0 ? { type: 'BUTTONS', buttons } : undefined;
532
+ }
533
+
534
+ /**
535
+ * @param {Object.<string, string>} row
536
+ * @param {Map.<string, string>} columns - From `resolveColumns`.
537
+ * @returns {{template: import('./normalize.js').Template, warnings: string[]}}
538
+ */
539
+ function templateFromRow(row, columns) {
540
+ const value = (key) =>
541
+ columns.has(key)
542
+ ? String(row[columns.get(key)] ?? '')
543
+ .replaceAll(/\r\n?/g, '\n')
544
+ .trim()
545
+ : '';
546
+ const name = value('name');
547
+ const language = value('language');
548
+ const category = value('category');
549
+ if (!name || !language || !category || !value('body')) {
550
+ throw new Error('template name, language, category and body text are all required');
551
+ }
552
+ assertSafeIdentity({ name, language });
553
+ if (category.toUpperCase() === 'AUTHENTICATION') {
554
+ throw new Error('authentication (OTP) templates are not supported yet');
555
+ }
556
+ const format = parameterFormatOf([value('body'), value('header')]);
557
+ /**
558
+ @type {RowNotes}
559
+ */
560
+ const notes = { errors: [], warnings: [] };
561
+ const components = [
562
+ headerComponent(value, format, notes),
563
+ bodyComponent(value, format, notes),
564
+ footerComponent(value),
565
+ buttonsComponent(value, notes),
566
+ ].filter(Boolean);
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 ?? '',
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 };
778
+ }