waba-devtools 0.0.0-stage → 0.1.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,397 @@
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 { assertSafeIdentity, normalizeTemplate, templateKey } from './normalize.js';
6
+
7
+ /**
8
+ * CSV columns: our key → accepted header names (compared case-insensitively, trimmed). Other
9
+ * columns are ignored.
10
+ */
11
+ export const CSV_COLUMNS = {
12
+ name: ['template name'],
13
+ category: ['category'],
14
+ language: ['language'],
15
+ body: ['body', 'meta template'],
16
+ examples: ['body examples', 'examples'],
17
+ header: ['header'],
18
+ headerExample: ['header example'],
19
+ footer: ['footer'],
20
+ quickReplies: ['quick replies'],
21
+ urlButton: ['url button'],
22
+ urlExample: ['url example'],
23
+ callButton: ['call button'],
24
+ };
25
+
26
+ const REQUIRED_COLUMNS = ['name', 'category', 'body', 'language'];
27
+ const BUTTON_COLUMNS = new Map([
28
+ ['quickReplies', 'QUICK_REPLY'],
29
+ ['urlButton', 'URL'],
30
+ ['callButton', 'PHONE_NUMBER'],
31
+ ]);
32
+ const VARIABLE = /\{\{\s*([^{}]*?)\s*\}\}/g;
33
+
34
+ /**
35
+ * @typedef {object} CsvRowError
36
+ * @property {number} row - Line number in the sheet (header = 1).
37
+ * @property {string} message
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} CsvResult
42
+ * @property {import('./normalize.js').Template[]} templates - One template per good row.
43
+ * @property {CsvRowError[]} errors
44
+ * @property {string[]} parts - Template parts the sheet defines (BODY always; HEADER, FOOTER,
45
+ * BUTTON:<type> per button column it has).
46
+ * @property {CsvCleanup} [cleanup] - What was cleaned up while reading the file.
47
+ */
48
+
49
+ /**
50
+ * @typedef {object} CsvCleanup
51
+ * @property {number} removedColumns - Empty columns removed on the right (no header, no values).
52
+ * @property {number} removedRecords - Empty rows removed at the bottom.
53
+ * @property {number} skippedRecords - Empty rows skipped in between.
54
+ */
55
+
56
+ /**
57
+ * Parser options, the same as sfmc-dataloader uses for its CSV imports: strict width and quoting,
58
+ * BOM removal, empty rows skipped, empty right-padding columns and bottom rows removed.
59
+ */
60
+ const PARSER_OPTIONS = {
61
+ bom: true,
62
+ strict: true,
63
+ strictQuotes: true,
64
+ skipEmptyLines: true,
65
+ sanitizeRightPadding: true,
66
+ sanitizeBottom: true,
67
+ mapHeaders: ({ header }) => header.trim().toLowerCase(),
68
+ outputByteOffset: true,
69
+ };
70
+
71
+ /**
72
+ * Line ending of the file, taken from the end of the header line: `\r` for old Mac exports,
73
+ * otherwise `\n` (the parser handles `\r\n` with it).
74
+ *
75
+ * @param {string} file
76
+ * @returns {Promise.<string>}
77
+ */
78
+ async function detectNewline(file) {
79
+ const handle = await open(file);
80
+ try {
81
+ const { buffer, bytesRead } = await handle.read({ buffer: Buffer.alloc(64 * 1024) });
82
+ const text = buffer.subarray(0, bytesRead).toString('latin1');
83
+ const end = text.search(/[\r\n]/);
84
+ return end !== -1 && text[end] === '\r' && text[end + 1] !== '\n' ? '\r' : '\n';
85
+ } finally {
86
+ await handle.close();
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Row number in the sheet of every record in the file, by byte offset. Counts every record,
92
+ * also the empty ones that are skipped while parsing.
93
+ *
94
+ * @param {string} file
95
+ * @param {string} newline - From `detectNewline`, so both passes split records the same way.
96
+ * @returns {Promise.<Map.<number, number>>} Byte offset to row number.
97
+ */
98
+ async function recordOffsets(file, newline) {
99
+ const rowNumbers = new Map();
100
+ const parser = createReadStream(file).pipe(
101
+ csv({ bom: true, headers: false, skipEmptyLines: false, outputByteOffset: true, newline }),
102
+ );
103
+ for await (const { byteOffset } of parser) {
104
+ rowNumbers.set(byteOffset, rowNumbers.size + 1);
105
+ }
106
+ return rowNumbers;
107
+ }
108
+
109
+ /**
110
+ * Reads a Google Sheets (or other) CSV export into body-only templates.
111
+ *
112
+ * @param {string} file - CSV path.
113
+ * @returns {Promise.<CsvResult>}
114
+ */
115
+ export async function readCsvTemplates(file) {
116
+ const rows = [];
117
+ const rowNumbers = [];
118
+ let validation;
119
+ try {
120
+ const newline = await detectNewline(file);
121
+ validation = await validateFile(file, { ...PARSER_OPTIONS, newline });
122
+ const offsets = await recordOffsets(file, newline);
123
+ for await (const { row, byteOffset } of replayFiles(validation)) {
124
+ rows.push(row);
125
+ const rowNumber = offsets.get(byteOffset);
126
+ if (rowNumber === undefined) {
127
+ throw new Error(`no row number for the record at byte ${byteOffset}`);
128
+ }
129
+ rowNumbers.push(rowNumber);
130
+ }
131
+ } catch (ex) {
132
+ throw new UsageError(`Could not read CSV ${file}: ${ex.message}`);
133
+ }
134
+ if (!validation.headers || validation.headers.length === 0) {
135
+ throw new UsageError(`CSV ${file} has no header row.`);
136
+ }
137
+ const { removedColumns, removedRecords, skippedRecords } = validation.cleanup;
138
+ return {
139
+ ...templatesFromRows(rows, rowNumbers),
140
+ cleanup: { removedColumns, removedRecords, skippedRecords },
141
+ };
142
+ }
143
+
144
+ /**
145
+ * @param {Object.<string, string>[]} rows - Parsed rows keyed by lower-case header.
146
+ * @param {number[]} [rowNumbers] - Row number in the sheet per row (default: header = 1, no gaps).
147
+ * @returns {CsvResult}
148
+ */
149
+ export function templatesFromRows(rows, rowNumbers = rows.map((_, index) => index + 2)) {
150
+ const columns = resolveColumns(rows.length > 0 ? Object.keys(rows[0]) : []);
151
+ if (rows.length > 0) {
152
+ const missing = REQUIRED_COLUMNS.filter((key) => !columns.has(key));
153
+ if (missing.length > 0) {
154
+ const names = missing
155
+ .map((key) => CSV_COLUMNS[key].map((alias) => `"${alias}"`).join(' or '))
156
+ .join(', ');
157
+ throw new UsageError(`CSV is missing the column(s) ${names}.`);
158
+ }
159
+ }
160
+ const templates = [];
161
+ const errors = [];
162
+ const seen = new Map();
163
+ for (const [index, row] of rows.entries()) {
164
+ const line = rowNumbers[index];
165
+ try {
166
+ const template = templateFromRow(row, columns);
167
+ const key = templateKey(template);
168
+ if (seen.has(key)) {
169
+ throw new Error(
170
+ `duplicate of row ${seen.get(key)} (${template.name}, ${template.language})`,
171
+ );
172
+ }
173
+ seen.set(key, line);
174
+ templates.push(template);
175
+ } catch (ex) {
176
+ errors.push({ row: line, message: ex.message });
177
+ }
178
+ }
179
+ return { templates, errors, parts: partsOf(columns) };
180
+ }
181
+
182
+ /**
183
+ * Which of our columns the sheet has, mapped to the sheet's (lower-case) header.
184
+ *
185
+ * @param {string[]} headers
186
+ * @returns {Map.<string, string>} Column key to header.
187
+ */
188
+ function resolveColumns(headers) {
189
+ const present = new Set(headers);
190
+ const columns = new Map();
191
+ for (const [key, aliases] of Object.entries(CSV_COLUMNS)) {
192
+ const header = aliases.find((alias) => present.has(alias));
193
+ if (header) {
194
+ columns.set(key, header);
195
+ }
196
+ }
197
+ return columns;
198
+ }
199
+
200
+ /**
201
+ * The template parts the sheet defines. A part without a column stays as it is in the target.
202
+ *
203
+ * @param {Map.<string, string>} columns
204
+ * @returns {string[]}
205
+ */
206
+ function partsOf(columns) {
207
+ const parts = ['BODY'];
208
+ if (columns.has('header')) {
209
+ parts.push('HEADER');
210
+ }
211
+ if (columns.has('footer')) {
212
+ parts.push('FOOTER');
213
+ }
214
+ for (const [key, type] of BUTTON_COLUMNS) {
215
+ if (columns.has(key)) {
216
+ parts.push(`BUTTON:${type}`);
217
+ }
218
+ }
219
+ return parts;
220
+ }
221
+
222
+ /**
223
+ * The numbered variables of a text: their count, or an error for named ones.
224
+ *
225
+ * @param {string} text
226
+ * @returns {number} Highest variable number (0 = none).
227
+ */
228
+ function variableCount(text) {
229
+ let count = 0;
230
+ for (const [, variable] of text.matchAll(VARIABLE)) {
231
+ if (!/^\d+$/.test(variable)) {
232
+ throw new Error(
233
+ `only numbered variables like {{1}} are supported, found {{${variable}}}`,
234
+ );
235
+ }
236
+ count = Math.max(count, Number(variable));
237
+ }
238
+ return count;
239
+ }
240
+
241
+ /**
242
+ * Splits `label|value` cells (URL and call buttons).
243
+ *
244
+ * @param {string} cell
245
+ * @param {string} column - For the error message.
246
+ * @returns {[string, string]}
247
+ */
248
+ function splitPair(cell, column) {
249
+ const separator = cell.indexOf('|');
250
+ const label = separator === -1 ? '' : cell.slice(0, separator).trim();
251
+ const value = separator === -1 ? '' : cell.slice(separator + 1).trim();
252
+ if (!label || !value) {
253
+ throw new Error(`${column}: write label|value, e.g. "Track|https://example.com/{{1}}"`);
254
+ }
255
+ return [label, value];
256
+ }
257
+
258
+ /**
259
+ * @param {(key: string) => string} value
260
+ * @returns {object|undefined} BODY component.
261
+ */
262
+ function bodyComponent(value) {
263
+ const text = value('body');
264
+ const count = variableCount(text);
265
+ const body = { type: 'BODY', text };
266
+ if (count > 0) {
267
+ const examples = value('examples')
268
+ .split('|')
269
+ .map((example) => example.trim());
270
+ const missingExample = examples.slice(0, count).includes('');
271
+ if (missingExample || examples.length < count) {
272
+ throw new Error(
273
+ `text uses ${count} variable(s) but the Examples column has ` +
274
+ `${examples.slice(0, count).filter((example) => example !== '').length} ` +
275
+ `non-empty value(s) for them; give one per variable, separated by |`,
276
+ );
277
+ }
278
+ body.example = { body_text: [examples.slice(0, count)] };
279
+ }
280
+ return body;
281
+ }
282
+
283
+ /**
284
+ * @param {(key: string) => string} value
285
+ * @returns {object|undefined} HEADER component (text only), or none for an empty cell.
286
+ */
287
+ function headerComponent(value) {
288
+ const text = value('header');
289
+ if (!text) {
290
+ return;
291
+ }
292
+ const count = variableCount(text);
293
+ if (count > 1 || (count === 1 && !text.includes('{{1}}'))) {
294
+ throw new Error('Header: at most one variable, written {{1}}');
295
+ }
296
+ const header = { type: 'HEADER', format: 'TEXT', text };
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
+ }
302
+ header.example = { header_text: [example] };
303
+ }
304
+ return header;
305
+ }
306
+
307
+ /**
308
+ * @param {(key: string) => string} value
309
+ * @returns {object|undefined} FOOTER component, or none for an empty cell.
310
+ */
311
+ function footerComponent(value) {
312
+ const text = value('footer');
313
+ if (!text) {
314
+ return;
315
+ }
316
+ if (text.includes('{{')) {
317
+ throw new Error('Footer: variables are not allowed');
318
+ }
319
+ return { type: 'FOOTER', text };
320
+ }
321
+
322
+ /**
323
+ * @param {(key: string) => string} value
324
+ * @returns {object|undefined} BUTTONS component, or none when all button cells are empty.
325
+ */
326
+ function buttonsComponent(value) {
327
+ const buttons = value('quickReplies')
328
+ .split('|')
329
+ .map((label) => label.trim())
330
+ .filter(Boolean)
331
+ .map((text) => ({ type: 'QUICK_REPLY', text }));
332
+ if (value('urlButton')) {
333
+ const [text, url] = splitPair(value('urlButton'), 'URL button');
334
+ if (!/^https?:\/\//.test(url)) {
335
+ throw new Error('URL button: the URL must start with https:// or http://');
336
+ }
337
+ const count = variableCount(url);
338
+ const button = { type: 'URL', text, url };
339
+ if (count > 0) {
340
+ if (count > 1 || !url.endsWith('{{1}}')) {
341
+ throw new Error('URL button: only one variable, {{1}} at the very end of the URL');
342
+ }
343
+ const example = value('urlExample');
344
+ if (!example) {
345
+ throw new Error('URL button has {{1}}: fill in the URL example column');
346
+ }
347
+ button.example = [url.replace('{{1}}', () => example)];
348
+ }
349
+ buttons.push(button);
350
+ }
351
+ if (value('callButton')) {
352
+ const [text, phone] = splitPair(value('callButton'), 'Call button');
353
+ const phoneNumber = phone.replaceAll(/[\s()-]/g, '');
354
+ if (!/^\+\d{6,15}$/.test(phoneNumber)) {
355
+ throw new Error('Call button: phone number with country code, e.g. +15550100');
356
+ }
357
+ buttons.push({ type: 'PHONE_NUMBER', text, phone_number: phoneNumber });
358
+ }
359
+ return buttons.length > 0 ? { type: 'BUTTONS', buttons } : undefined;
360
+ }
361
+
362
+ /**
363
+ * @param {Object.<string, string>} row
364
+ * @param {Map.<string, string>} columns - From `resolveColumns`.
365
+ * @returns {import('./normalize.js').Template}
366
+ */
367
+ function templateFromRow(row, columns) {
368
+ const value = (key) =>
369
+ columns.has(key)
370
+ ? String(row[columns.get(key)] ?? '')
371
+ .replaceAll(/\r\n?/g, '\n')
372
+ .trim()
373
+ : '';
374
+ const name = value('name');
375
+ const language = value('language');
376
+ const category = value('category');
377
+ if (!name || !language || !category || !value('body')) {
378
+ throw new Error('template name, language, category and body text are all required');
379
+ }
380
+ assertSafeIdentity({ name, language });
381
+ if (category.toUpperCase() === 'AUTHENTICATION') {
382
+ throw new Error('authentication (OTP) templates are not supported yet');
383
+ }
384
+ const components = [
385
+ headerComponent(value),
386
+ bodyComponent(value),
387
+ footerComponent(value),
388
+ buttonsComponent(value),
389
+ ].filter(Boolean);
390
+ return normalizeTemplate({
391
+ name,
392
+ language,
393
+ category,
394
+ parameter_format: 'POSITIONAL',
395
+ components,
396
+ });
397
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Error for wrong command-line usage or an invalid project setup (exit code 2).
3
+ */
4
+ export class UsageError extends Error {
5
+ /**
6
+ * @param {string} message - What is wrong and how to fix it.
7
+ * @param {string} [code] - Stable machine-readable reason (e.g. `BUSINESS_ID_REQUIRED`), so callers
8
+ * such as the desktop app can show their own wording.
9
+ */
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.name = 'UsageError';
13
+ if (code) {
14
+ this.code = code;
15
+ }
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Error returned by Meta's Graph API. Carries Meta's own codes and messages, never the token.
21
+ */
22
+ export class GraphError extends Error {
23
+ /**
24
+ * @param {object} details
25
+ * @param {number} details.httpStatus - HTTP status of the response.
26
+ * @param {string} details.message - Meta's error message.
27
+ * @param {number} [details.code] - Meta's error code.
28
+ * @param {number} [details.subcode] - Meta's error subcode.
29
+ * @param {string} [details.userTitle] - Meta's `error_user_title`.
30
+ * @param {string} [details.userMessage] - Meta's `error_user_msg`.
31
+ * @param {string} [details.traceId] - Meta's `fbtrace_id`.
32
+ */
33
+ constructor({ httpStatus, message, code, subcode, userTitle, userMessage, traceId }) {
34
+ super(message);
35
+ this.name = 'GraphError';
36
+ this.httpStatus = httpStatus;
37
+ this.code = code;
38
+ this.subcode = subcode;
39
+ this.userTitle = userTitle;
40
+ this.userMessage = userMessage;
41
+ this.traceId = traceId;
42
+ }
43
+
44
+ /**
45
+ * One-line description with Meta's codes, for reports.
46
+ *
47
+ * @returns {string}
48
+ */
49
+ describe() {
50
+ const codes = [this.code, this.subcode].filter((value) => value !== undefined).join('/');
51
+ const detail = this.userMessage ? ` — ${this.userMessage}` : '';
52
+ return `${codes ? `(#${codes}) ` : ''}${this.message}${detail}`;
53
+ }
54
+ }
package/lib/files.js ADDED
@@ -0,0 +1,112 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { parseJson } from './config.js';
5
+ import { UsageError } from './errors.js';
6
+ import { assertSafeIdentity, normalizeTemplate, templateKey } from './normalize.js';
7
+
8
+ /**
9
+ * Path of a template file: `<directory>/<name>/<language>.json`.
10
+ *
11
+ * @param {string} directory - Templates folder.
12
+ * @param {{name: string, language: string}} template
13
+ * @returns {string}
14
+ */
15
+ export function templatePath(directory, template) {
16
+ assertSafeIdentity(template);
17
+ return path.join(directory, template.name, `${template.language}.json`);
18
+ }
19
+
20
+ /**
21
+ * Stable file content: sorted keys, 4-space indent, LF, final newline.
22
+ *
23
+ * @param {object} template - Normalized template.
24
+ * @returns {string}
25
+ */
26
+ export function serializeTemplate(template) {
27
+ return `${JSON.stringify(template, undefined, 4)}\n`;
28
+ }
29
+
30
+ /**
31
+ * Reads one template file, or `undefined` when it does not exist.
32
+ *
33
+ * @param {string} directory
34
+ * @param {{name: string, language: string}} identity
35
+ * @returns {Promise.<import('./normalize.js').Template | undefined>}
36
+ */
37
+ export async function readTemplateFile(directory, identity) {
38
+ const file = templatePath(directory, identity);
39
+ return existsSync(file)
40
+ ? normalizeTemplate(parseJson(await readFile(file, 'utf8')))
41
+ : undefined;
42
+ }
43
+
44
+ /**
45
+ * Writes a template file.
46
+ *
47
+ * @param {string} directory
48
+ * @param {import('./normalize.js').Template} template - Normalized template.
49
+ * @returns {Promise.<'created' | 'updated' | 'unchanged'>}
50
+ */
51
+ export async function writeTemplateFile(directory, template) {
52
+ const file = templatePath(directory, template);
53
+ const content = serializeTemplate(template);
54
+ let previous;
55
+ if (existsSync(file)) {
56
+ previous = await readFile(file, 'utf8');
57
+ if (previous === content) {
58
+ return 'unchanged';
59
+ }
60
+ }
61
+ await mkdir(path.dirname(file), { recursive: true });
62
+ await writeFile(file, content, 'utf8');
63
+ return previous === undefined ? 'created' : 'updated';
64
+ }
65
+
66
+ /**
67
+ * Reads all templates below `directory`. File and folder names must match the content.
68
+ *
69
+ * @param {string} directory
70
+ * @returns {Promise.<import('./normalize.js').Template[]>}
71
+ */
72
+ export async function readTemplateDirectory(directory) {
73
+ if (!existsSync(directory)) {
74
+ throw new UsageError(
75
+ `Templates folder ${directory} does not exist. Run "waba retrieve" first.`,
76
+ );
77
+ }
78
+ const templates = [];
79
+ const folders = await readdir(directory, { withFileTypes: true });
80
+ for (const folder of folders) {
81
+ if (!folder.isDirectory()) {
82
+ continue;
83
+ }
84
+ const folderPath = path.join(directory, folder.name);
85
+ const files = await readdir(folderPath, { withFileTypes: true });
86
+ for (const file of files) {
87
+ if (!file.isFile() || !file.name.endsWith('.json')) {
88
+ continue;
89
+ }
90
+ const relative = `${folder.name}/${file.name}`;
91
+ let parsed;
92
+ try {
93
+ parsed = parseJson(await readFile(path.join(folderPath, file.name), 'utf8'));
94
+ } catch (ex) {
95
+ throw new UsageError(`${relative} is not valid JSON: ${ex.message}`);
96
+ }
97
+ const template = normalizeTemplate(parsed);
98
+ if (
99
+ template.name !== folder.name ||
100
+ `${template.language}.json` !== file.name ||
101
+ !template.category
102
+ ) {
103
+ throw new UsageError(
104
+ `${relative} must contain name "${folder.name}", the language of its file ` +
105
+ `name and a category.`,
106
+ );
107
+ }
108
+ templates.push(template);
109
+ }
110
+ }
111
+ return templates.toSorted((a, b) => templateKey(a).localeCompare(templateKey(b)));
112
+ }