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,278 @@
1
+ /**
2
+ * Statuses in which Meta accepts an edit of an existing template.
3
+ */
4
+ export const EDITABLE_STATUSES = new Set(['APPROVED', 'REJECTED', 'PAUSED']);
5
+
6
+ /**
7
+ * Note for Meta's sample templates, which Meta adds to new WABAs and refuses to edit or delete
8
+ * (error #100/2388094, checked 2026-11).
9
+ */
10
+ export const META_SAMPLE_NOTE =
11
+ "Meta's sample template — Meta does not allow editing or deleting it";
12
+
13
+ /**
14
+ * Whether a live template is one of Meta's sample templates (`hello_world`, `jaspers_market_*`).
15
+ *
16
+ * @param {{name: string}} template
17
+ * @returns {boolean}
18
+ */
19
+ export function isMetaSampleTemplate(template) {
20
+ return /^(?:hello_world|jaspers_market_\w+)$/.test(template.name);
21
+ }
22
+
23
+ const MEDIA_HEADER_FORMATS = new Set(['IMAGE', 'VIDEO', 'DOCUMENT']);
24
+ const SAFE_SEGMENT = /^[A-Za-z0-9_]+$/;
25
+
26
+ /**
27
+ * @typedef {object} Template
28
+ * @property {string} name
29
+ * @property {string} language
30
+ * @property {string} [category]
31
+ * @property {string} [parameter_format]
32
+ * @property {object[]} components
33
+ */
34
+
35
+ /**
36
+ * Returns a copy with object keys sorted at every level (stable files and comparisons).
37
+ *
38
+ * @param {any} value
39
+ * @returns {any}
40
+ */
41
+ export function sortKeys(value) {
42
+ if (Array.isArray(value)) {
43
+ return value.map(sortKeys);
44
+ }
45
+ if (value && typeof value === 'object') {
46
+ return Object.fromEntries(
47
+ Object.keys(value)
48
+ .toSorted((a, b) => a.localeCompare(b))
49
+ .map((key) => [key, sortKeys(value[key])]),
50
+ );
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /**
56
+ * Keeps only the fields that define a template and drops read-only ones (id, status, …).
57
+ * Files, CSV rows and live templates all pass through here before they are compared.
58
+ *
59
+ * @param {object} template - Template from a file, a CSV row or the Graph API.
60
+ * @returns {Template}
61
+ */
62
+ export function normalizeTemplate(template) {
63
+ const normalized = {
64
+ name: template.name,
65
+ language: template.language,
66
+ components: template.components ?? [],
67
+ };
68
+ if (template.category) {
69
+ normalized.category = String(template.category).toUpperCase();
70
+ }
71
+ if (template.parameter_format) {
72
+ normalized.parameter_format = String(template.parameter_format).toUpperCase();
73
+ }
74
+ return sortKeys(normalized);
75
+ }
76
+
77
+ /**
78
+ * @param {{name: string, language: string}} template
79
+ * @returns {string}
80
+ */
81
+ export function templateKey(template) {
82
+ return `${template.name}::${template.language}`;
83
+ }
84
+
85
+ /**
86
+ * Throws when a name or language could not safely be used as a file or folder name.
87
+ *
88
+ * @param {{name: string, language: string}} template
89
+ * @returns {void}
90
+ */
91
+ export function assertSafeIdentity(template) {
92
+ const fields = Object.entries({ name: template.name, language: template.language });
93
+ for (const [field, value] of fields) {
94
+ if (typeof value !== 'string' || !SAFE_SEGMENT.test(value)) {
95
+ throw new Error(
96
+ `Template ${field} "${value}" may only contain letters, digits and underscores.`,
97
+ );
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * The part of a template that deploy compares. Category is left out on purpose: Meta refuses
104
+ * category edits on approved templates and re-categorizes templates itself.
105
+ *
106
+ * @param {Template} template
107
+ * @returns {string}
108
+ */
109
+ export function comparableContent(template) {
110
+ return JSON.stringify(
111
+ sortKeys(
112
+ normalizeNewlines({
113
+ components: template.components ?? [],
114
+ parameter_format: template.parameter_format ?? 'POSITIONAL',
115
+ }),
116
+ ),
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Copy with `\r\n` and `\r` turned into `\n` in every string, so line endings never count as a change.
122
+ *
123
+ * @param {any} value
124
+ * @returns {any}
125
+ */
126
+ export function normalizeNewlines(value) {
127
+ if (typeof value === 'string') {
128
+ return value.replaceAll(/\r\n?/g, '\n');
129
+ }
130
+ if (Array.isArray(value)) {
131
+ return value.map(normalizeNewlines);
132
+ }
133
+ if (value && typeof value === 'object') {
134
+ return Object.fromEntries(
135
+ Object.entries(value).map(([key, item]) => [key, normalizeNewlines(item)]),
136
+ );
137
+ }
138
+ return value;
139
+ }
140
+
141
+ /**
142
+ * Why a template is out of scope for this version, or `undefined` when it is supported.
143
+ *
144
+ * @param {Template} template
145
+ * @returns {string|undefined}
146
+ */
147
+ export function unsupportedReason(template) {
148
+ if (template.category === 'AUTHENTICATION') {
149
+ return 'authentication (OTP) templates are not supported yet';
150
+ }
151
+ const components = template.components ?? [];
152
+ for (const component of components) {
153
+ const type = String(component.type ?? '').toUpperCase();
154
+ if (type === 'CAROUSEL') {
155
+ return 'carousel templates are not supported yet';
156
+ }
157
+ if (type === 'HEADER' && MEDIA_HEADER_FORMATS.has(String(component.format).toUpperCase())) {
158
+ return 'media headers (image, video, document) are not supported yet';
159
+ }
160
+ }
161
+ return;
162
+ }
163
+
164
+ /**
165
+ * Request body for creating a template.
166
+ *
167
+ * @param {Template} template
168
+ * @returns {object}
169
+ */
170
+ export function toCreateBody(template) {
171
+ return {
172
+ name: template.name,
173
+ language: template.language,
174
+ category: template.category,
175
+ components: template.components,
176
+ ...(template.parameter_format && { parameter_format: template.parameter_format }),
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Request body for editing a template. Category is never sent (see `comparableContent`).
182
+ *
183
+ * @param {Template} template
184
+ * @returns {object}
185
+ */
186
+ export function toUpdateBody(template) {
187
+ return {
188
+ components: template.components,
189
+ ...(template.parameter_format && { parameter_format: template.parameter_format }),
190
+ };
191
+ }
192
+
193
+ const COMPONENT_ORDER = ['HEADER', 'BODY', 'FOOTER', 'BUTTONS'];
194
+
195
+ /**
196
+ * Replaces the given component types of `base` with those of `source` (removing them when
197
+ * `source` has none) and keeps all other components. Used for CSV rows: the sheet defines only the
198
+ * parts it has columns for.
199
+ *
200
+ * @param {Template} base - Existing template (file or live).
201
+ * @param {Template} source - Template whose listed parts win.
202
+ * @param {string[]} parts - Component types from `source`, e.g. `['BODY', 'FOOTER']`; buttons per
203
+ * type as `BUTTON:QUICK_REPLY`, `BUTTON:URL`, `BUTTON:PHONE_NUMBER` (other button types are kept).
204
+ * @returns {Template}
205
+ */
206
+ export function mergeParts(base, source, parts) {
207
+ const owned = new Set(parts);
208
+ const ownedButtons = new Set(
209
+ parts.filter((part) => part.startsWith('BUTTON:')).map((part) => part.slice(7)),
210
+ );
211
+ const kept = (base.components ?? []).filter(
212
+ (component) => !owned.has(component.type) && component.type !== 'BUTTONS',
213
+ );
214
+ const taken = source.components.filter(
215
+ (component) => owned.has(component.type) && component.type !== 'BUTTONS',
216
+ );
217
+ const buttons = mergeButtons(
218
+ buttonsOf(base).filter((button) => !ownedButtons.has(button.type)),
219
+ buttonsOf(source).filter((button) => ownedButtons.has(button.type)),
220
+ );
221
+ const components = [
222
+ ...kept,
223
+ ...taken,
224
+ ...(buttons.length > 0 ? [{ type: 'BUTTONS', buttons }] : []),
225
+ ].toSorted((a, b) => componentRank(a) - componentRank(b));
226
+ return normalizeTemplate({
227
+ ...base,
228
+ components,
229
+ parameter_format: source.parameter_format ?? base.parameter_format,
230
+ });
231
+ }
232
+
233
+ /**
234
+ * Replaces the BODY of `base` with the BODY of `bodySource` and keeps header, footer and buttons.
235
+ *
236
+ * @param {Template} base - Existing template (file or live).
237
+ * @param {Template} bodySource - Template whose BODY wins.
238
+ * @returns {Template}
239
+ */
240
+ export function mergeBody(base, bodySource) {
241
+ return mergeParts(base, bodySource, ['BODY']);
242
+ }
243
+
244
+ /**
245
+ * @param {Template} template
246
+ * @returns {object[]} Its buttons (none without a BUTTONS component).
247
+ */
248
+ function buttonsOf(template) {
249
+ return (
250
+ (template.components ?? []).find((component) => component.type === 'BUTTONS')?.buttons ?? []
251
+ );
252
+ }
253
+
254
+ /**
255
+ * Kept and new buttons in one list; quick replies first, so they stay grouped as Meta requires.
256
+ *
257
+ * @param {object[]} kept
258
+ * @param {object[]} taken
259
+ * @returns {object[]}
260
+ */
261
+ function mergeButtons(kept, taken) {
262
+ const all = [...kept, ...taken];
263
+ return [
264
+ ...all.filter((button) => button.type === 'QUICK_REPLY'),
265
+ ...all.filter((button) => button.type !== 'QUICK_REPLY'),
266
+ ];
267
+ }
268
+
269
+ /**
270
+ * Position of a component (header, body, footer, buttons); unknown types go last.
271
+ *
272
+ * @param {{type: string}} component
273
+ * @returns {number}
274
+ */
275
+ function componentRank(component) {
276
+ const index = COMPONENT_ORDER.indexOf(component.type);
277
+ return index === -1 ? COMPONENT_ORDER.length : index;
278
+ }
package/lib/plan.js ADDED
@@ -0,0 +1,110 @@
1
+ import {
2
+ EDITABLE_STATUSES,
3
+ META_SAMPLE_NOTE,
4
+ comparableContent,
5
+ isMetaSampleTemplate,
6
+ mergeParts,
7
+ normalizeTemplate,
8
+ templateKey,
9
+ toCreateBody,
10
+ toUpdateBody,
11
+ unsupportedReason,
12
+ } from './normalize.js';
13
+
14
+ /**
15
+ * @typedef {object} SourceTemplate
16
+ * @property {import('./normalize.js').Template} template - Normalized template.
17
+ * @property {string[]} [parts] - CSV row: only these component types are authoritative.
18
+ */
19
+
20
+ /**
21
+ * @typedef {object} PlannedAction
22
+ * @property {'create'|'update'|'unchanged'|'blocked'|'skipped'|'extra'|'delete'} action
23
+ * @property {string} name
24
+ * @property {string} language
25
+ * @property {string} [status] - Live status in the target before deploying.
26
+ * @property {string} [templateId] - Live template ID in the target.
27
+ * @property {object} [body] - Request body for create/update.
28
+ * @property {string} [note] - Why blocked/skipped, or a category difference.
29
+ */
30
+
31
+ /**
32
+ * Decides what to do per template for one target WABA. Pure: no I/O.
33
+ *
34
+ * @param {object} input
35
+ * @param {SourceTemplate[]} input.source - What should be in the target.
36
+ * @param {object[]} input.target - Live templates of the target WABA (raw Graph objects).
37
+ * @param {boolean} [input.fullSet] - Source is the complete set, so target-only templates count
38
+ * as `extra` (and `delete` with prune).
39
+ * @param {boolean} [input.prune] - Turn `extra` into `delete`.
40
+ * @returns {PlannedAction[]}
41
+ */
42
+ export function planDeploy({ source, target, fullSet = false, prune = false }) {
43
+ const live = new Map(target.map((template) => [templateKey(template), template]));
44
+ const actions = [];
45
+ const sourceKeys = new Set();
46
+ for (const { template, parts } of source) {
47
+ const key = templateKey(template);
48
+ sourceKeys.add(key);
49
+ const base = { name: template.name, language: template.language };
50
+ const existing = live.get(key);
51
+ const reason =
52
+ unsupportedReason(template) ??
53
+ (existing ? unsupportedReason(normalizeTemplate(existing)) : undefined);
54
+ if (reason) {
55
+ actions.push({ ...base, action: 'skipped', note: reason, status: existing?.status });
56
+ continue;
57
+ }
58
+ if (!existing) {
59
+ actions.push({ ...base, action: 'create', body: toCreateBody(template) });
60
+ continue;
61
+ }
62
+ const current = normalizeTemplate(existing);
63
+ const desired = parts ? mergeParts(current, template, parts) : template;
64
+ const known = { ...base, status: existing.status, templateId: existing.id };
65
+ const categoryNote =
66
+ template.category && current.category && template.category !== current.category
67
+ ? `category ${current.category} in target, ${template.category} in source (not changed)`
68
+ : undefined;
69
+ if (comparableContent(desired) === comparableContent(current)) {
70
+ actions.push({ ...known, action: 'unchanged', note: categoryNote });
71
+ } else if (isMetaSampleTemplate(existing)) {
72
+ actions.push({ ...known, action: 'skipped', note: META_SAMPLE_NOTE });
73
+ } else if (EDITABLE_STATUSES.has(existing.status)) {
74
+ actions.push({
75
+ ...known,
76
+ action: 'update',
77
+ body: toUpdateBody(desired),
78
+ note: categoryNote,
79
+ });
80
+ } else {
81
+ actions.push({
82
+ ...known,
83
+ action: 'blocked',
84
+ note: `status ${existing.status} cannot be edited`,
85
+ });
86
+ }
87
+ }
88
+ if (fullSet) {
89
+ for (const [key, existing] of live) {
90
+ if (sourceKeys.has(key)) {
91
+ continue;
92
+ }
93
+
94
+ // Never delete what this tool cannot recreate (media, OTP, carousel), nor Meta's
95
+ // samples, which Meta refuses to delete.
96
+ const reason =
97
+ unsupportedReason(normalizeTemplate(existing)) ??
98
+ (isMetaSampleTemplate(existing) ? META_SAMPLE_NOTE : undefined);
99
+ actions.push({
100
+ name: existing.name,
101
+ language: existing.language,
102
+ status: existing.status,
103
+ templateId: existing.id,
104
+ action: prune && !reason ? 'delete' : 'extra',
105
+ ...(reason && { note: `kept: ${reason}` }),
106
+ });
107
+ }
108
+ }
109
+ return actions;
110
+ }