uniweb 1.34.12 → 1.35.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,992 @@
1
+ /**
2
+ * Drafts for `uniweb promote`: a post or a campaign as an agent writes it in a file, and the batch
3
+ * that makes the backend's copy say it.
4
+ *
5
+ * ⭐ THE BACKEND HOLDS THE ONLY COPY, AND A FILE IS ONE CLIENT'S DRAFT OF IT. A draft names what it
6
+ * was read at: each unit's `id` and `version`. A unit is an item with the parts of its body — a post
7
+ * and its parts, an ad and its parts, a campaign, an ad group — so its version covers them together.
8
+ * A unit changed since (in the app, or by another run) is refused, never written over: whoever wrote
9
+ * last reads it again (`uniweb promote show`), as the app's own editor does on a stale write.
10
+ *
11
+ * ⭐ NOTHING IS DELETED BY LEAVING IT OUT. An ad group or an ad the file doesn't hold is kept, since
12
+ * it may be the person's, added in the app after the agent read the campaign; `uniweb promote
13
+ * delete` deletes. A post's or an ad's parts are its body, read at its version, so the body the file
14
+ * gives is the body it gets.
15
+ *
16
+ * ⭐ THE CLI TRANSLATES ONLY WHAT THE FILES NAME DIFFERENTLY: a page by its route, an account by its
17
+ * network, a picture by its file. Every other field is the backend's, carried as it reads, so a field
18
+ * the Model adds reaches the agent with no CLI release, and an update carries back what it doesn't
19
+ * edit (an update replaces the item's data).
20
+ *
21
+ * Pure: the command reads, uploads and writes; this module decides.
22
+ */
23
+
24
+ import { createHash } from 'node:crypto'
25
+ import yaml from 'js-yaml'
26
+ import {
27
+ buildRouteOf,
28
+ documentSourceLocale,
29
+ editYamlText,
30
+ pageRefIndex,
31
+ setYamlKeyFirst
32
+ } from '@uniweb/build/uwx'
33
+
34
+ /** How the build reads YAML: no implicit timestamp, so `starts: 2026-12-01` stays the text written. */
35
+ export const YAML_READ = Object.freeze({ schema: yaml.CORE_SCHEMA.extend({ implicit: [yaml.types.merge] }) })
36
+ /** How it is written: one line per value, and a string that reads as another type quoted. */
37
+ const YAML_WRITE = Object.freeze({ lineWidth: -1, quotingType: "'", noRefs: true })
38
+
39
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
40
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
41
+
42
+ // ── The promotion, indexed ─────────────────────────────────────────────────────────
43
+
44
+ /** The sections a command names an item in, and what it calls each. */
45
+ const KINDS = {
46
+ posts: 'post',
47
+ campaigns: 'campaign',
48
+ 'campaigns/ad_groups': 'ad group',
49
+ 'campaigns/ad_groups/ads': 'ad',
50
+ networks: 'account'
51
+ }
52
+
53
+ /**
54
+ * A promotion as the backend read it (`{ uuid, items }`), indexed: each item by uuid, and the
55
+ * items of a section under a parent, in the order the read gives them.
56
+ *
57
+ * @param {{ uuid?: string, items?: object[] } | null} promotion
58
+ */
59
+ export function indexPromotion(promotion) {
60
+ const items = Array.isArray(promotion?.items) ? promotion.items.filter((i) => i && typeof i.uuid === 'string') : []
61
+ const byUuid = new Map(items.map((i) => [i.uuid, i]))
62
+ return {
63
+ uuid: promotion?.uuid ?? null,
64
+ items,
65
+ byUuid,
66
+ top: (section) => items.filter((i) => i.section === section),
67
+ children: (section, parent) => items.filter((i) => i.section === section && i.parent === parent),
68
+ child: (section, parent) => items.find((i) => i.section === section && i.parent === parent) ?? null
69
+ }
70
+ }
71
+
72
+ /** What a command calls an item: `post`, `campaign`, `ad group`, `ad`, `account`, or null. */
73
+ export function kindOf(item) {
74
+ return KINDS[item?.section] ?? null
75
+ }
76
+
77
+ /** The items a unit's version covers: the item, and the parts of its body where it has them. */
78
+ export function unitItems(index, item) {
79
+ if (item?.section === 'posts') return [item, ...index.children('posts/parts', item.uuid)]
80
+ if (item?.section === 'campaigns/ad_groups/ads') return [item, ...index.children('campaigns/ad_groups/ads/parts', item.uuid)]
81
+ return item ? [item] : []
82
+ }
83
+
84
+ /**
85
+ * A unit's version: the same while none of its items is made, changed or removed. Backend's own
86
+ * children (a delivery) are not in it, as they never stale a draft in the app either. It leads with
87
+ * a letter, so YAML reads it back as the same string.
88
+ */
89
+ export function unitVersion(items) {
90
+ const lines = items.filter(Boolean).map((i) => `${i.uuid}@${i.updated_at ?? ''}`).sort()
91
+ return `v${createHash('sha256').update(lines.join('\n')).digest('hex').slice(0, 12)}`
92
+ }
93
+
94
+ export function versionOf(index, item) {
95
+ return unitVersion(unitItems(index, item))
96
+ }
97
+
98
+ /**
99
+ * Short ids, as git shortens a hash: the shortest END of each uuid, at least `min` characters,
100
+ * that no other uuid ends with. The end, since a uuid made by the backend leads with the time it
101
+ * was made, so two made in the same minute share their first characters.
102
+ *
103
+ * @param {string[]} uuids
104
+ * @returns {Map<string, string>}
105
+ */
106
+ export function shortIds(uuids, min = 4) {
107
+ const hex = [...new Set(uuids.filter(Boolean))].map((u) => [u, String(u).replace(/-/g, '').toLowerCase()])
108
+ const out = new Map()
109
+ for (const [u, h] of hex) {
110
+ let n = Math.min(min, h.length)
111
+ while (n < h.length && hex.some(([v, g]) => v !== u && g.endsWith(h.slice(-n)))) n++
112
+ out.set(u, h.slice(-n))
113
+ }
114
+ return out
115
+ }
116
+
117
+ /** Whether `ref` names `uuid`: the whole of it, or its end. */
118
+ export function idMatches(uuid, ref) {
119
+ if (typeof uuid !== 'string' || typeof ref !== 'string' || !ref) return false
120
+ const want = ref.replace(/-/g, '').toLowerCase()
121
+ return uuid.toLowerCase() === ref.toLowerCase() || (want.length >= 2 && uuid.replace(/-/g, '').toLowerCase().endsWith(want))
122
+ }
123
+
124
+ /**
125
+ * The item a command names: a uuid or its end, or a campaign by its name.
126
+ *
127
+ * @returns {{ item: object } | { none: true } | { many: object[] }}
128
+ */
129
+ export function findItem(index, ref, { kinds = ['post', 'campaign', 'ad group', 'ad'] } = {}) {
130
+ const pool = index.items.filter((i) => kinds.includes(kindOf(i)))
131
+ const exact = pool.find((i) => i.uuid.toLowerCase() === String(ref).toLowerCase())
132
+ if (exact) return { item: exact }
133
+ const byEnd = pool.filter((i) => idMatches(i.uuid, String(ref)))
134
+ const byName = kinds.includes('campaign')
135
+ ? pool.filter((i) => i.section === 'campaigns' && typeof i.data?.name === 'string' && i.data.name.toLowerCase() === String(ref).toLowerCase())
136
+ : []
137
+ const found = [...new Set([...byEnd, ...byName])]
138
+ if (found.length === 1) return { item: found[0] }
139
+ return found.length ? { many: found } : { none: true }
140
+ }
141
+
142
+ /** The campaign an ad group or an ad belongs to, or the campaign itself. */
143
+ export function campaignOf(index, item) {
144
+ let at = item
145
+ while (at && at.section !== 'campaigns') at = index.byUuid.get(at.parent)
146
+ return at ?? null
147
+ }
148
+
149
+ /** A post's or an ad's state: its delivery's status, or `draft` while it has none. */
150
+ export function deliveryOf(index, item) {
151
+ if (item?.section === 'posts') return index.child('posts/delivery', item.uuid)?.data ?? null
152
+ if (item?.section === 'campaigns/ad_groups/ads') return index.child('campaigns/ad_groups/ads/delivery', item.uuid)?.data ?? null
153
+ return null
154
+ }
155
+
156
+ /** A campaign's deliveries, one per ad account it has been started in. */
157
+ export function campaignDeliveries(index, campaign) {
158
+ return index.children('campaigns/delivery', campaign.uuid).map((d) => d.data).filter(Boolean)
159
+ }
160
+
161
+ /** A post went out, so it is not edited: published, or with a network's review. */
162
+ export function wentOut(delivery) {
163
+ return ['published', 'review', 'refused'].includes(delivery?.status)
164
+ }
165
+
166
+ // ── Words for the backend's codes ──────────────────────────────────────────────────
167
+
168
+ /**
169
+ * A reason the backend gave — a delivery's, or a refusal's — in words. One the CLI has no words
170
+ * for yet is shown as it is, so a reason can ship before the CLI has a sentence for it; `--json`
171
+ * gives the codes.
172
+ */
173
+ export const REASONS = {
174
+ no_network: 'the account it goes out through is no longer chosen for the site',
175
+ no_connection: 'no account is connected for it',
176
+ site_not_published: 'the site is not published yet — publish it first',
177
+ no_page: 'it links to no page of the site',
178
+ page_gone: 'the page it links to was removed from the site',
179
+ page_not_published: 'the page it links to is not published in its language yet — publish the site again',
180
+ connection_stopped: 'its account stopped: whoever connected it left the workspace, and an admin hands it on, in the app',
181
+ connection_gone: 'its account was disconnected',
182
+ connection_needs_reconnect: 'its account needs reconnecting, by its person, in the app',
183
+ connection_not_permitted: 'whoever scheduled it may no longer post through its account',
184
+ network_not_offered: 'this backend does not offer that network',
185
+ network_refused: 'the network refused it',
186
+ promote_off: 'the site has no Promote: it comes with the site\'s Analytics, which the person turns on in the app',
187
+ feature_not_subscribed: 'Promote comes with the site\'s Analytics, which this site does not have yet. The person turns it on in the app'
188
+ }
189
+
190
+ export function reasonWords(code) {
191
+ return REASONS[code] ?? code
192
+ }
193
+
194
+ /** A network's review of an ad, in words: `in_review` → `in review`. */
195
+ export const reviewWords = (code) => String(code).replace(/_/g, ' ')
196
+
197
+ // ── The input ──────────────────────────────────────────────────────────────────────
198
+
199
+ const FRONT = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/
200
+ const PART_BREAK = /^---[ \t]*$/
201
+ const PICTURE_LINE = /^!\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)$/
202
+
203
+ /** The keys of each unit that are its structure rather than its fields. */
204
+ const STRUCTURE = {
205
+ post: ['id', 'version', 'text', 'pictures', 'parts'],
206
+ campaign: ['id', 'version', 'ad_groups'],
207
+ 'ad group': ['id', 'version', 'ads'],
208
+ ad: ['id', 'version', 'text', 'pictures', 'parts']
209
+ }
210
+ /** Backend's, read and never written: what `status --json` or `show --json` carry beside a draft. */
211
+ const BACKENDS = ['delivery', 'deliveries', 'reading', 'state', 'started', 'spend', 'uuid', 'updated_at', 'tag', 'short']
212
+
213
+ /** The format of an input: by its file's extension, else by what it holds. */
214
+ export function formatOf(file, text) {
215
+ const ext = /\.([a-z]+)$/i.exec(file || '')?.[1]?.toLowerCase()
216
+ if (ext === 'md' || ext === 'markdown') return 'markdown'
217
+ if (ext === 'yml' || ext === 'yaml') return 'yaml'
218
+ if (ext === 'json') return 'json'
219
+ const t = String(text ?? '').trimStart()
220
+ if (t.startsWith('{')) return 'json'
221
+ return FRONT.test(String(text ?? '')) ? 'markdown' : 'yaml'
222
+ }
223
+
224
+ /** A Markdown file's frontmatter and body. */
225
+ export function splitFrontmatter(text) {
226
+ const m = FRONT.exec(text)
227
+ if (!m) return { front: null, body: text }
228
+ return { front: m[1] ?? '', body: text.slice(m[0].length) }
229
+ }
230
+
231
+ /** A post's parts from a Markdown body: a `---` line between parts, a picture alone on its line. */
232
+ function partsFromBody(body) {
233
+ const parts = []
234
+ let lines = []
235
+ const flush = () => {
236
+ const pictures = []
237
+ const text = []
238
+ for (const line of lines) {
239
+ const picture = PICTURE_LINE.exec(line.trim())
240
+ if (picture) pictures.push(picture[1])
241
+ else text.push(line)
242
+ }
243
+ const words = text.join('\n').trim()
244
+ if (words || pictures.length) parts.push({ text: words, pictures })
245
+ lines = []
246
+ }
247
+ for (const line of String(body).split(/\r?\n/)) {
248
+ if (PART_BREAK.test(line)) flush()
249
+ else lines.push(line)
250
+ }
251
+ flush()
252
+ return parts
253
+ }
254
+
255
+ function fieldsOf(obj, kind) {
256
+ const out = {}
257
+ for (const [k, v] of Object.entries(obj)) {
258
+ if (!STRUCTURE[kind].includes(k) && !BACKENDS.includes(k)) out[k] = v
259
+ }
260
+ return out
261
+ }
262
+
263
+ function partOf(p, where) {
264
+ if (typeof p === 'string') return { part: { text: p.trimEnd(), pictures: [] } }
265
+ if (!isPlainObject(p)) return { error: `${where}: a part is { text, pictures }` }
266
+ const text = p.text == null ? '' : p.text
267
+ if (typeof text !== 'string') return { error: `${where}: \`text\` is text` }
268
+ let pictures = p.pictures == null ? [] : p.pictures
269
+ if (typeof pictures === 'string') pictures = [pictures]
270
+ if (!Array.isArray(pictures) || pictures.some((x) => typeof x !== 'string' || !x)) {
271
+ return { error: `${where}: \`pictures\` is a list of files or addresses` }
272
+ }
273
+ return { part: { text: text.trimEnd(), pictures } }
274
+ }
275
+
276
+ /** A unit's parts from an object: `text` and `pictures` for one, `parts` for several, null for none given. */
277
+ function partsOf(obj, where) {
278
+ const hasParts = obj.parts !== undefined
279
+ const hasOne = obj.text !== undefined || obj.pictures !== undefined
280
+ if (hasParts && hasOne) return { error: `${where}: give its words as \`text\` and \`pictures\`, or as \`parts\`, not both` }
281
+ if (hasParts) {
282
+ if (!Array.isArray(obj.parts)) return { error: `${where}: \`parts\` is a list of { text, pictures }` }
283
+ const parts = []
284
+ for (const [i, p] of obj.parts.entries()) {
285
+ const one = partOf(p, `${where}, part ${i + 1}`)
286
+ if (one.error) return one
287
+ parts.push(one.part)
288
+ }
289
+ return { parts }
290
+ }
291
+ if (hasOne) {
292
+ const one = partOf(obj, where)
293
+ return one.error ? one : { parts: [one.part] }
294
+ }
295
+ return { parts: null }
296
+ }
297
+
298
+ function identityOf(obj, where) {
299
+ const id = obj.id == null ? null : obj.id
300
+ const version = obj.version == null ? null : obj.version
301
+ if (id !== null && typeof id !== 'string') return { error: `${where}: \`id\` is the id the CLI wrote` }
302
+ if (version !== null && typeof version !== 'string') return { error: `${where}: \`version\` is the version the CLI wrote` }
303
+ if (id && !version) return { error: `${where}: it names \`id\` without the \`version\` it was read at — start from \`uniweb promote show ${id}\`` }
304
+ return { id, version }
305
+ }
306
+
307
+ function adOf(obj, where) {
308
+ if (!isPlainObject(obj)) return { error: `${where}: an ad is a map of its fields` }
309
+ const ident = identityOf(obj, where)
310
+ if (ident.error) return ident
311
+ const parts = partsOf(obj, where)
312
+ if (parts.error) return parts
313
+ return { ad: { ...ident, fields: fieldsOf(obj, 'ad'), parts: parts.parts } }
314
+ }
315
+
316
+ function adGroupOf(obj, where) {
317
+ if (!isPlainObject(obj)) return { error: `${where}: an ad group is a map of its fields` }
318
+ const ident = identityOf(obj, where)
319
+ if (ident.error) return ident
320
+ let ads = null
321
+ if (obj.ads !== undefined) {
322
+ if (!Array.isArray(obj.ads)) return { error: `${where}: \`ads\` is a list` }
323
+ ads = []
324
+ for (const [i, a] of obj.ads.entries()) {
325
+ const one = adOf(a, `${where}, ad ${i + 1}`)
326
+ if (one.error) return one
327
+ ads.push(one.ad)
328
+ }
329
+ }
330
+ return { group: { ...ident, fields: fieldsOf(obj, 'ad group'), ads } }
331
+ }
332
+
333
+ /**
334
+ * A draft from its text.
335
+ *
336
+ * A post is Markdown — its frontmatter its fields, its body its text, a `---` line between the
337
+ * parts of a thread, a picture alone on its line — or YAML or JSON, with `text` and `pictures`, or
338
+ * `parts`. A campaign is YAML or JSON, its `ad_groups` and their `ads` nested in it.
339
+ *
340
+ * @param {string} text
341
+ * @param {{ format: 'markdown'|'yaml'|'json', kind: 'post'|'campaign' }} opts
342
+ * @returns {{ draft: object } | { error: string }}
343
+ */
344
+ export function parseDraft(text, { format, kind }) {
345
+ let obj
346
+ let body = null
347
+ if (format === 'markdown') {
348
+ if (kind !== 'post') return { error: 'A campaign is YAML or JSON, with its ad groups and their ads nested in it.' }
349
+ const split = splitFrontmatter(text)
350
+ try {
351
+ obj = split.front === null ? {} : (yaml.load(split.front, YAML_READ) ?? {})
352
+ } catch (err) {
353
+ return { error: `Its frontmatter is not YAML: ${err.message.split('\n')[0]}` }
354
+ }
355
+ body = split.body
356
+ } else {
357
+ try {
358
+ obj = format === 'json' ? JSON.parse(text) : (yaml.load(text, YAML_READ) ?? {})
359
+ } catch (err) {
360
+ return { error: `It is not ${format === 'json' ? 'JSON' : 'YAML'}: ${err.message.split('\n')[0]}` }
361
+ }
362
+ }
363
+ if (!isPlainObject(obj)) return { error: `A ${kind} is a map of its fields.` }
364
+
365
+ const ident = identityOf(obj, `The ${kind}`)
366
+ if (ident.error) return ident
367
+ if (kind === 'post') {
368
+ let parts
369
+ const bodyParts = body === null ? [] : partsFromBody(body)
370
+ if (bodyParts.length) {
371
+ if (obj.text !== undefined || obj.parts !== undefined || obj.pictures !== undefined) {
372
+ return { error: 'Its words are its body: leave `text`, `pictures` and `parts` out of the frontmatter.' }
373
+ }
374
+ parts = bodyParts
375
+ } else {
376
+ const given = partsOf(obj, 'The post')
377
+ if (given.error) return given
378
+ parts = given.parts
379
+ }
380
+ return { draft: { kind, ...ident, fields: fieldsOf(obj, 'post'), parts } }
381
+ }
382
+
383
+ let adGroups = null
384
+ if (obj.ad_groups !== undefined) {
385
+ if (!Array.isArray(obj.ad_groups)) return { error: '`ad_groups` is a list' }
386
+ adGroups = []
387
+ for (const [i, g] of obj.ad_groups.entries()) {
388
+ const one = adGroupOf(g, `Ad group ${i + 1}`)
389
+ if (one.error) return one
390
+ adGroups.push(one.group)
391
+ }
392
+ }
393
+ return { draft: { kind, ...ident, fields: fieldsOf(obj, 'campaign'), adGroups } }
394
+ }
395
+
396
+ /** Every picture a draft names, as written: the files among them are uploaded before it is written. */
397
+ export function picturesOf(draft) {
398
+ const out = []
399
+ const take = (parts) => {
400
+ for (const p of parts ?? []) out.push(...p.pictures)
401
+ }
402
+ take(draft.parts)
403
+ for (const g of draft.adGroups ?? []) for (const a of g.ads ?? []) take(a.parts)
404
+ return [...new Set(out)]
405
+ }
406
+
407
+ /** Whether a picture is an address already, kept as written, rather than a file to upload. */
408
+ export function isAddress(picture) {
409
+ return /^https?:\/\//i.test(picture)
410
+ }
411
+
412
+ // ── Pages, by their routes on the site as pushed ───────────────────────────────────
413
+
414
+ /**
415
+ * The site's pages, from its document as the backend holds it: each page's item uuid, its stable
416
+ * id and its route, by the build's rule (`buildRouteOf`), indexed as a `page:` link is read.
417
+ *
418
+ * @param {object} doc - the site's `@uniweb/site-content` document
419
+ */
420
+ export function sitePages(doc) {
421
+ const language = documentSourceLocale(doc)
422
+ const list = []
423
+ const walk = (records, parentRoute) => {
424
+ for (const record of records || []) {
425
+ if (!isPlainObject(record)) continue
426
+ const route = buildRouteOf(record, parentRoute, language)
427
+ list.push({
428
+ uuid: typeof record.$uuid === 'string' ? record.$uuid : null,
429
+ id: typeof record.stable_id === 'string' && record.stable_id ? record.stable_id : null,
430
+ route,
431
+ dynamic: record.is_dynamic === true
432
+ })
433
+ walk(record.$children, route)
434
+ }
435
+ }
436
+ walk(doc?.pages, '/')
437
+ return { language, list, index: pageRefIndex(list), byUuid: new Map(list.filter((p) => p.uuid).map((p) => [p.uuid, p])) }
438
+ }
439
+
440
+ /**
441
+ * The page item a draft's `page` names: a route (`/holiday`), a `page:` link (`page:holiday`,
442
+ * `page:/holiday`), or the page's item uuid as the backend stores it.
443
+ *
444
+ * @returns {{ uuid: string|null, route?: string } | { error: string }}
445
+ */
446
+ export function resolvePage(raw, pages, where = 'The draft') {
447
+ if (raw === null || raw === undefined || raw === '') return { uuid: null }
448
+ if (typeof raw !== 'string') return { error: `${where}: \`page\` is the page's route, such as /holiday` }
449
+ if (UUID.test(raw)) return { uuid: raw, route: pages?.byUuid.get(raw)?.route }
450
+ const target = raw.startsWith('page:') ? raw.slice('page:'.length) : raw
451
+ if (target.includes('#')) return { error: `${where}: a post or an ad links to a page, not to a place on it — \`page: ${raw.split('#')[0]}\`` }
452
+ const page = pages?.index.resolve(target)
453
+ if (!page?.uuid) {
454
+ return { error: `${where}: the site as pushed has no page ${raw}. Push it first (uniweb push), or name a page it has.` }
455
+ }
456
+ if (page.dynamic) {
457
+ return { error: `${where}: ${page.route} is a template for many pages, and a post or an ad links to one page.` }
458
+ }
459
+ return { uuid: page.uuid, route: page.route }
460
+ }
461
+
462
+ /** A page's route for a file: `/holiday`, or the uuid as stored when the site no longer has it. */
463
+ export function pageRoute(uuid, pages) {
464
+ if (!uuid) return null
465
+ return pages?.byUuid.get(uuid)?.route ?? uuid
466
+ }
467
+
468
+ // ── Accounts: a draft's `via` ──────────────────────────────────────────────────────
469
+
470
+ /**
471
+ * A `networks` item's connection, as a read gives it: an entity reference, `{ model, entity, brief }`,
472
+ * the connection's uuid its `entity` and its card's words in its `brief` — or the uuid alone, as a
473
+ * write gives it.
474
+ *
475
+ * @returns {{ uuid: string|null, name: string|null, handle: string|null, state: string|null }}
476
+ */
477
+ export function connectionOf(value) {
478
+ if (typeof value === 'string') return { uuid: value, name: null, handle: null, state: null }
479
+ if (!isPlainObject(value)) return { uuid: null, name: null, handle: null, state: null }
480
+ const brief = isPlainObject(value.brief) ? value.brief : {}
481
+ return {
482
+ uuid: typeof value.entity === 'string' ? value.entity : typeof value.uuid === 'string' ? value.uuid : null,
483
+ name: brief.name ?? null,
484
+ handle: brief.handle ?? null,
485
+ state: brief.state ?? null
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Resolves a draft's `via` to the site's `networks` item for that network and use — and, where the
491
+ * site has none, makes one in the same batch, as the app does the first time a site uses a network,
492
+ * through the one account of that network the caller can use.
493
+ *
494
+ * `via` is a network (`x`), `{ network, connection }` to choose among the caller's accounts there,
495
+ * or a `networks` item's id.
496
+ *
497
+ * @param {{ networks: object[], connections: object[]|null, mint: () => string }} ctx
498
+ */
499
+ export function viaResolver({ networks, connections, mint }) {
500
+ const made = new Map()
501
+ const all = () => [...networks, ...[...made.values()].map((op) => ({ uuid: op.uuid, data: op.data }))]
502
+ const connectionIds = shortIds((connections ?? []).map((k) => k?.uuid))
503
+ const describe = (k) => `${connectionIds.get(k.uuid) ?? k.uuid} (“${k.card?.name || k.card?.handle || k.uuid}”${k.card?.state && k.card.state !== 'connected' ? `, ${k.card.state}` : ''})`
504
+
505
+ function make(network, connection, use, where) {
506
+ if (connections === null) return { error: `${where}: the site has no ${use} account on ${network} yet, and your connections could not be listed.` }
507
+ const reach = connections.filter((k) => k?.card?.network === network)
508
+ let chosen
509
+ if (connection) {
510
+ const named = reach.filter((k) => idMatches(k.uuid, connection))
511
+ if (named.length !== 1) {
512
+ return { error: `${where}: you reach no ${network} account ${connection}${reach.length ? ` — you reach ${reach.map(describe).join(', ')}` : ''}.` }
513
+ }
514
+ chosen = named[0]
515
+ } else {
516
+ const usable = reach.filter((k) => k.card?.state === 'connected')
517
+ if (usable.length > 1) {
518
+ return { error: `${where}: you reach ${usable.length} accounts on ${network} — choose one: \`via: { network: ${network}, connection: <id> }\`, from ${usable.map(describe).join(', ')}.` }
519
+ }
520
+ if (!usable.length && !reach.length) {
521
+ return { error: `${where}: no ${network} account is connected that you can use. The person connects one: uniweb promote connect ${network}`, connect: network }
522
+ }
523
+ chosen = usable[0] ?? reach[0]
524
+ }
525
+ if (chosen.card?.state !== 'connected') {
526
+ return {
527
+ error: chosen.card?.state === 'stopped'
528
+ ? `${where}: the ${network} account ${describe(chosen)} stopped: its person left the workspace. An admin hands it on, in the app.`
529
+ : `${where}: the ${network} account ${describe(chosen)} needs reconnecting, by its person, in the app.`
530
+ }
531
+ }
532
+ const key = `${use}\u0000${network}\u0000${chosen.uuid}`
533
+ if (!made.has(key)) made.set(key, { kind: 'create', section: 'networks', uuid: mint(), data: { network, use, connection: chosen.uuid } })
534
+ return { uuid: made.get(key).uuid }
535
+ }
536
+
537
+ function resolve(raw, use, where) {
538
+ if (raw === undefined || raw === null || raw === '') return { error: `${where}: name the network it goes out on — \`via: x\`, say` }
539
+ const ofUse = all().filter((n) => n.data?.use === use)
540
+ if (typeof raw === 'string') {
541
+ const byId = ofUse.filter((n) => idMatches(n.uuid, raw))
542
+ if (byId.length === 1) return { uuid: byId[0].uuid }
543
+ const same = ofUse.filter((n) => n.data?.network === raw)
544
+ if (same.length === 1) return { uuid: same[0].uuid }
545
+ if (same.length > 1) {
546
+ const ids = shortIds(networks.map((n) => n.uuid))
547
+ const named = (n) => n.data?.target?.name ?? connectionOf(n.data?.connection).name ?? '?'
548
+ return { error: `${where}: the site goes out on ${raw} through ${same.length} accounts — name one by its id: ${same.map((n) => `${ids.get(n.uuid) ?? n.uuid} (“${named(n)}”)`).join(', ')}.` }
549
+ }
550
+ return make(raw, null, use, where)
551
+ }
552
+ if (isPlainObject(raw) && typeof raw.network === 'string' && raw.network) {
553
+ const connection = raw.connection == null ? null : String(raw.connection)
554
+ if (!connection) return resolve(raw.network, use, where)
555
+ const same = ofUse.filter((n) => n.data?.network === raw.network && idMatches(connectionOf(n.data?.connection).uuid, connection))
556
+ if (same.length === 1) return { uuid: same[0].uuid }
557
+ return make(raw.network, connection, use, where)
558
+ }
559
+ return { error: `${where}: \`via\` is a network, such as x, or { network, connection }` }
560
+ }
561
+
562
+ return { resolve, creates: () => [...made.values()] }
563
+ }
564
+
565
+ /**
566
+ * A `networks` item's name in a file: its network, where the site has one item of that use there,
567
+ * else its uuid.
568
+ */
569
+ export function viaName(index, uuid) {
570
+ const item = index.byUuid.get(uuid)
571
+ if (!item || item.section !== 'networks') return uuid
572
+ const same = index.top('networks').filter((n) => n.data?.use === item.data?.use && n.data?.network === item.data?.network)
573
+ return same.length === 1 && item.data?.network ? item.data.network : uuid
574
+ }
575
+
576
+ // ── The write ──────────────────────────────────────────────────────────────────────
577
+
578
+ /** Two data values the same, whatever their key order. */
579
+ export function sameData(a, b) {
580
+ const norm = (v) =>
581
+ Array.isArray(v)
582
+ ? v.map(norm)
583
+ : isPlainObject(v)
584
+ ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, norm(v[k])]))
585
+ : v
586
+ return JSON.stringify(norm(a ?? {})) === JSON.stringify(norm(b ?? {}))
587
+ }
588
+
589
+ /** An item's data: what it holds, with the fields the draft gives over it, and a `null` removing one. */
590
+ function merged(stored, fields) {
591
+ const out = { ...(stored ?? {}) }
592
+ for (const [k, v] of Object.entries(fields)) {
593
+ if (v === undefined) continue
594
+ if (v === null) delete out[k]
595
+ else out[k] = v
596
+ }
597
+ return out
598
+ }
599
+
600
+ function partData(stored, part) {
601
+ const out = { ...(stored ?? {}) }
602
+ if (part.text) out.text = part.text
603
+ else delete out.text
604
+ if (part.pictures.length) out.pictures = part.pictures
605
+ else delete out.pictures
606
+ return out
607
+ }
608
+
609
+ /** A body's parts, by position: each changed one updated, a new one added last, one past the end removed. */
610
+ function partOps(section, stored, parent, parts, mint) {
611
+ if (parts === null) return []
612
+ const ops = []
613
+ for (let i = 0; i < Math.max(stored.length, parts.length); i++) {
614
+ const s = stored[i]
615
+ const p = parts[i]
616
+ if (s && p) {
617
+ const data = partData(s.data, p)
618
+ if (!sameData(s.data, data)) ops.push({ kind: 'update', uuid: s.uuid, data, if_unmodified_since: s.updated_at })
619
+ } else if (p) {
620
+ ops.push({ kind: 'create', section, parent, uuid: mint(), data: partData(null, p), position: 'last' })
621
+ } else {
622
+ ops.push({ kind: 'delete', uuid: s.uuid, if_unmodified_since: s.updated_at })
623
+ }
624
+ }
625
+ return ops
626
+ }
627
+
628
+ /**
629
+ * Whether the units a draft names are still as it read them, and are its to write: each `id` an
630
+ * item of the right kind, where the draft holds it, at its `version`; and a post not gone out.
631
+ *
632
+ * @returns {string[]} what refuses it, in words; empty when it may be written
633
+ */
634
+ export function checkDraft(index, draft) {
635
+ const problems = []
636
+ const stale = (what, item) =>
637
+ `${what} changed since your copy — in the app, or by another run. \`uniweb promote show ${shortIds(index.items.map((i) => i.uuid)).get(item.uuid) ?? item.uuid}\` prints it as it stands now; take your changes into that.`
638
+ const unit = (want, d, what, parent) => {
639
+ if (!d.id) return null
640
+ const item = index.byUuid.get(d.id)
641
+ if (!item || item.section !== want || (parent !== undefined && item.parent !== parent)) {
642
+ problems.push(
643
+ item && item.section === want
644
+ ? `${what} ${d.id} is not in the ${want === 'campaigns/ad_groups' ? 'campaign' : 'ad group'} it is under in your file — it moves in the app.`
645
+ : `${what} ${d.id} is not on this site — removed in the app? Drop its \`id\` and \`version\` to make it again.`
646
+ )
647
+ return null
648
+ }
649
+ if (versionOf(index, item) !== d.version) problems.push(stale(what, item))
650
+ return item
651
+ }
652
+ if (draft.kind === 'post') {
653
+ const post = unit('posts', draft, 'The post')
654
+ if (post && wentOut(deliveryOf(index, post))) {
655
+ problems.push('The post went out, so it isn\'t edited. Draft a new one: drop `id` and `version` from the file.')
656
+ }
657
+ return problems
658
+ }
659
+ const campaign = unit('campaigns', draft, 'The campaign')
660
+ for (const [i, g] of (draft.adGroups ?? []).entries()) {
661
+ const what = `Ad group ${i + 1}`
662
+ let group = null
663
+ if (g.id) {
664
+ if (!draft.id) {
665
+ problems.push(`${what} names an id, and the campaign none: a new campaign's ad groups are new too.`)
666
+ continue
667
+ }
668
+ if (!campaign) continue
669
+ group = unit('campaigns/ad_groups', g, what, campaign.uuid)
670
+ if (!group) continue
671
+ }
672
+ for (const [j, a] of (g.ads ?? []).entries()) {
673
+ if (!a.id) continue
674
+ const adWhat = `Ad ${j + 1} of ad group ${i + 1}`
675
+ if (!group) problems.push(`${adWhat} names an id, and its ad group none: a new ad group's ads are new too.`)
676
+ else unit('campaigns/ad_groups/ads', a, adWhat, group.uuid)
677
+ }
678
+ }
679
+ return problems
680
+ }
681
+
682
+ /**
683
+ * The batch that makes the backend's post say what the draft says, its fields already in the
684
+ * backend's terms (`via` and `page` as item uuids, pictures as addresses).
685
+ *
686
+ * @returns {{ ops: object[], uuid: string }}
687
+ */
688
+ export function planPost(index, draft, { mint, language }) {
689
+ const stored = draft.id ? index.byUuid.get(draft.id) : null
690
+ const uuid = stored?.uuid ?? mint()
691
+ const data = merged(stored?.data, draft.fields)
692
+ if (!stored && data.language == null && language) data.language = language
693
+ const ops = []
694
+ if (!stored) ops.push({ kind: 'create', section: 'posts', uuid, data })
695
+ else if (!sameData(stored.data, data)) ops.push({ kind: 'update', uuid, data, if_unmodified_since: stored.updated_at })
696
+ ops.push(...partOps('posts/parts', stored ? index.children('posts/parts', uuid) : [], uuid, draft.parts, mint))
697
+ return { ops, uuid }
698
+ }
699
+
700
+ /**
701
+ * The batch for a campaign, with its ad groups and ads: each named one updated where it changed,
702
+ * each new one made, and each the file leaves out kept and reported (`kept`).
703
+ *
704
+ * @returns {{ ops: object[], uuid: string, groups: Array<{ uuid: string, ads: string[] }>, kept: object[] }}
705
+ */
706
+ export function planCampaign(index, draft, { mint, language }) {
707
+ const stored = draft.id ? index.byUuid.get(draft.id) : null
708
+ const uuid = stored?.uuid ?? mint()
709
+ const ops = []
710
+ const data = merged(stored?.data, draft.fields)
711
+ if (!stored) ops.push({ kind: 'create', section: 'campaigns', uuid, data })
712
+ else if (!sameData(stored.data, data)) ops.push({ kind: 'update', uuid, data, if_unmodified_since: stored.updated_at })
713
+
714
+ const groups = []
715
+ const kept = []
716
+ if (draft.adGroups !== null) {
717
+ const storedGroups = stored ? index.children('campaigns/ad_groups', uuid) : []
718
+ const named = new Set()
719
+ for (const g of draft.adGroups) {
720
+ const sg = g.id ? storedGroups.find((x) => x.uuid === g.id) : null
721
+ const gUuid = sg?.uuid ?? mint()
722
+ named.add(gUuid)
723
+ const gData = merged(sg?.data, g.fields)
724
+ if (!sg) ops.push({ kind: 'create', section: 'campaigns/ad_groups', parent: uuid, uuid: gUuid, data: gData, position: 'last' })
725
+ else if (!sameData(sg.data, gData)) ops.push({ kind: 'update', uuid: gUuid, data: gData, if_unmodified_since: sg.updated_at })
726
+ const ads = []
727
+ if (g.ads !== null) {
728
+ const storedAds = sg ? index.children('campaigns/ad_groups/ads', gUuid) : []
729
+ const namedAds = new Set()
730
+ for (const a of g.ads) {
731
+ const sa = a.id ? storedAds.find((x) => x.uuid === a.id) : null
732
+ const aUuid = sa?.uuid ?? mint()
733
+ namedAds.add(aUuid)
734
+ ads.push(aUuid)
735
+ const aData = merged(sa?.data, a.fields)
736
+ if (!sa && aData.language == null && language) aData.language = language
737
+ if (!sa) ops.push({ kind: 'create', section: 'campaigns/ad_groups/ads', parent: gUuid, uuid: aUuid, data: aData, position: 'last' })
738
+ else if (!sameData(sa.data, aData)) ops.push({ kind: 'update', uuid: aUuid, data: aData, if_unmodified_since: sa.updated_at })
739
+ ops.push(...partOps('campaigns/ad_groups/ads/parts', sa ? index.children('campaigns/ad_groups/ads/parts', aUuid) : [], aUuid, a.parts, mint))
740
+ }
741
+ for (const sa of storedAds) if (!namedAds.has(sa.uuid)) kept.push({ kind: 'ad', uuid: sa.uuid, name: sa.data?.headlines?.[0] ?? null, group: sg?.data?.name ?? null })
742
+ }
743
+ groups.push({ uuid: gUuid, ads })
744
+ }
745
+ for (const sg of storedGroups) if (!named.has(sg.uuid)) kept.push({ kind: 'ad group', uuid: sg.uuid, name: sg.data?.name ?? null })
746
+ }
747
+ return { ops, uuid, groups, kept }
748
+ }
749
+
750
+ // ── What `show` prints, and the ids a write leaves in the file ────────────────────
751
+
752
+ const POST_ORDER = ['via', 'language', 'page', 'send_at']
753
+ const CAMPAIGN_ORDER = ['name', 'goal', 'devices', 'starts', 'ends', 'via']
754
+ const GROUP_ORDER = ['name', 'daily_budget']
755
+ const AD_ORDER = ['via', 'language', 'page', 'headlines', 'descriptions']
756
+ const NOT_SHOWN = ['tag']
757
+
758
+ function ordered(data, order, translate) {
759
+ const out = {}
760
+ for (const k of order) if (data?.[k] !== undefined) out[k] = translate(k, data[k])
761
+ for (const k of Object.keys(data ?? {}).sort()) {
762
+ if (!order.includes(k) && !NOT_SHOWN.includes(k)) out[k] = data[k]
763
+ }
764
+ return out
765
+ }
766
+
767
+ function bodyOf(parts) {
768
+ const list = parts.map((p) => ({ text: p.data?.text ?? '', pictures: Array.isArray(p.data?.pictures) ? p.data.pictures : [] }))
769
+ return list
770
+ }
771
+
772
+ function withBody(shape, parts) {
773
+ if (parts.length === 1) {
774
+ if (parts[0].text) shape.text = parts[0].text
775
+ if (parts[0].pictures.length) shape.pictures = parts[0].pictures
776
+ } else if (parts.length > 1) {
777
+ shape.parts = parts.map((p) => ({ ...(p.text ? { text: p.text } : {}), ...(p.pictures.length ? { pictures: p.pictures } : {}) }))
778
+ }
779
+ return shape
780
+ }
781
+
782
+ /**
783
+ * A post as a draft holds it — `id`, `version`, its fields with `via` and `page` named as files
784
+ * name them, and its parts — so `show` and `post` round-trip.
785
+ */
786
+ export function postShape(index, post, pages) {
787
+ const translate = (k, v) => (k === 'via' ? viaName(index, v) : k === 'page' ? pageRoute(v, pages) : v)
788
+ return {
789
+ id: post.uuid,
790
+ version: versionOf(index, post),
791
+ ...ordered(post.data, POST_ORDER, translate),
792
+ parts: bodyOf(index.children('posts/parts', post.uuid))
793
+ }
794
+ }
795
+
796
+ /** A campaign as a draft holds it, its ad groups and their ads nested in it. */
797
+ export function campaignShape(index, campaign, pages) {
798
+ const translate = (k, v) =>
799
+ k === 'via' ? (Array.isArray(v) ? v.map((u) => viaName(index, u)) : viaName(index, v)) : k === 'page' ? pageRoute(v, pages) : v
800
+ const groups = index.children('campaigns/ad_groups', campaign.uuid).map((g) => ({
801
+ id: g.uuid,
802
+ version: versionOf(index, g),
803
+ ...ordered(g.data, GROUP_ORDER, translate),
804
+ ads: index.children('campaigns/ad_groups/ads', g.uuid).map((a) =>
805
+ withBody(
806
+ { id: a.uuid, version: versionOf(index, a), ...ordered(a.data, AD_ORDER, translate) },
807
+ bodyOf(index.children('campaigns/ad_groups/ads/parts', a.uuid))
808
+ )
809
+ )
810
+ }))
811
+ return { id: campaign.uuid, version: versionOf(index, campaign), ...ordered(campaign.data, CAMPAIGN_ORDER, translate), ad_groups: groups }
812
+ }
813
+
814
+ /** Whether a post's parts can be written as a Markdown body, and read back the same. */
815
+ function markdownHolds(parts) {
816
+ return parts.every(
817
+ (p) => !p.text.split('\n').some((line) => PART_BREAK.test(line) || PICTURE_LINE.test(line.trim())) && p.pictures.every((a) => !/[\s)]/.test(a))
818
+ )
819
+ }
820
+
821
+ /**
822
+ * A post's shape as a Markdown file: its fields as frontmatter, its parts as the body. Null when
823
+ * its words would not read back the same (a line of `---` in them, say); YAML holds it then.
824
+ */
825
+ export function postMarkdown(shape) {
826
+ const { parts, ...front } = shape
827
+ if (!markdownHolds(parts)) return null
828
+ const body = parts
829
+ .map((p) => [p.text, ...p.pictures.map((a) => `![](${a})`)].filter(Boolean).join('\n\n'))
830
+ .join('\n\n---\n\n')
831
+ return `---\n${yaml.dump(front, YAML_WRITE)}---\n${body ? `\n${body}\n` : ''}`
832
+ }
833
+
834
+ /** A shape as YAML, for a campaign, or a post Markdown cannot hold. */
835
+ export function shapeYaml(shape) {
836
+ if (Array.isArray(shape.parts)) return yaml.dump(withBody(Object.fromEntries(Object.entries(shape).filter(([k]) => k !== 'parts')), shape.parts), YAML_WRITE)
837
+ return yaml.dump(shape, YAML_WRITE)
838
+ }
839
+
840
+ /** `{ id, version, ...rest }` — the identity a sync writes leads its map. */
841
+ function leading(obj, id, version) {
842
+ const { id: _id, version: _version, ...rest } = obj
843
+ return { id, version, ...rest }
844
+ }
845
+
846
+ /**
847
+ * The draft's file once a write has landed: each unit it holds names its `id` and `version`, so the
848
+ * next run updates the same draft, and a teammate with the file updates it too. Everything else in
849
+ * the file is left as its author wrote it where the format allows (YAML's comments, a Markdown body).
850
+ *
851
+ * @param {string} text - the file as it was read
852
+ * @param {{ format: string, kind: string }} input
853
+ * @param {{ uuid: string, groups?: Array<{ uuid: string, ads: string[] }> }} map - the units the write
854
+ * made or named, in the file's order
855
+ * @param {(uuid: string) => string} version - each unit's version after the write
856
+ * @returns {{ text: string, whole?: boolean } | null} null when the file could not be read again
857
+ */
858
+ export function fileWithIdentity(text, { format, kind }, map, version) {
859
+ const nested = (obj) => {
860
+ if (kind !== 'campaign' || !Array.isArray(obj.ad_groups) || !map.groups) return obj
861
+ return {
862
+ ...obj,
863
+ ad_groups: obj.ad_groups.map((g, i) => {
864
+ const gm = map.groups[i]
865
+ if (!gm || !isPlainObject(g)) return g
866
+ const ads = Array.isArray(g.ads) ? g.ads.map((a, j) => (gm.ads[j] && isPlainObject(a) ? leading(a, gm.ads[j], version(gm.ads[j])) : a)) : g.ads
867
+ return leading(ads === undefined ? g : { ...g, ads }, gm.uuid, version(gm.uuid))
868
+ })
869
+ }
870
+ }
871
+ if (format === 'json') {
872
+ let obj
873
+ try {
874
+ obj = JSON.parse(text)
875
+ } catch {
876
+ return null
877
+ }
878
+ return { text: `${JSON.stringify(leading(nested(obj), map.uuid, version(map.uuid)), null, 2)}\n` }
879
+ }
880
+ const lead = (yamlText) => {
881
+ const withVersion = setYamlKeyFirst(yamlText, 'version', version(map.uuid))
882
+ return withVersion === null ? null : setYamlKeyFirst(withVersion, 'id', map.uuid)
883
+ }
884
+ if (format === 'markdown') {
885
+ const split = splitFrontmatter(text)
886
+ if (split.front === null) {
887
+ return { text: `---\n${yaml.dump({ id: map.uuid, version: version(map.uuid) }, YAML_WRITE)}---\n${text}` }
888
+ }
889
+ const front = lead(split.front === '' ? '' : `${split.front}\n`)
890
+ if (front === null) return null
891
+ return { text: `---\n${front.endsWith('\n') ? front : `${front}\n`}---\n${split.body}` }
892
+ }
893
+ let before
894
+ try {
895
+ before = yaml.load(text, YAML_READ) ?? {}
896
+ } catch {
897
+ return null
898
+ }
899
+ if (!isPlainObject(before)) return null
900
+ const after = nested(before)
901
+ const edited = after === before ? text : editYamlText(text, before, after)
902
+ const done = edited === null ? null : lead(edited)
903
+ if (done !== null) return { text: done }
904
+ return { text: yaml.dump(leading(after, map.uuid, version(map.uuid)), YAML_WRITE), whole: true }
905
+ }
906
+
907
+ // ── What a network will hear ───────────────────────────────────────────────────────
908
+
909
+ /**
910
+ * The site's services row a network's conversions go out through: the host sends X and Meta the
911
+ * site's conversions from its servers, each name mapped to the network's event.
912
+ */
913
+ const CONVERSION_ROWS = { x: 'x', facebook: 'meta' }
914
+
915
+ /**
916
+ * What a network will hear of the site's conversions, from its `site.yml`: whether the site asks
917
+ * for tracking, the conversions it lists, and — for a campaign that optimizes for conversions —
918
+ * whether each network it runs on has them mapped to its events. Notes, never a gate: whoever sends
919
+ * or starts decides, with them in front of them.
920
+ *
921
+ * @param {object|null} siteYml
922
+ * @param {{ networks?: string[], goal?: string|null }} [opts] - the networks a draft goes out on;
923
+ * with no networks, each the site maps (`services.x`, `services.meta`)
924
+ * @returns {Array<{ ok: boolean, id: string, text: string }>}
925
+ */
926
+ export function conversionNotes(siteYml, { networks = null, goal = null } = {}) {
927
+ const services = isPlainObject(siteYml?.services) ? siteYml.services : {}
928
+ const tracking = services.tracking
929
+ const on = tracking === true || (typeof tracking === 'string' && tracking !== '') || (isPlainObject(tracking) && tracking.enabled !== false)
930
+ if (!on) {
931
+ return [{ ok: false, id: 'tracking-off', text: 'site.yml does not ask for `services.tracking`, so the site reports no visit or conversion for a network to hear (`uniweb guide services`)' }]
932
+ }
933
+ const notes = []
934
+ const listed = isPlainObject(tracking) && Array.isArray(tracking.conversions)
935
+ ? tracking.conversions.map((c) => c?.name).filter((n) => typeof n === 'string' && n)
936
+ : []
937
+ notes.push(
938
+ listed.length
939
+ ? { ok: true, id: 'conversions-listed', text: `the site counts the conversion${listed.length === 1 ? '' : 's'} it lists: ${listed.join(', ')}` }
940
+ : { ok: false, id: 'conversions-none', text: 'the site lists no conversion of its own in `services.tracking.conversions`: it counts phone and email taps, and what its foundation reports' }
941
+ )
942
+ if (goal !== 'conversions') return notes
943
+ const asked = networks ?? Object.keys(CONVERSION_ROWS).filter((n) => services[CONVERSION_ROWS[n]])
944
+ for (const network of [...new Set(asked)]) {
945
+ const row = CONVERSION_ROWS[network]
946
+ if (!row) continue
947
+ const events = isPlainObject(services[row]?.events) ? Object.keys(services[row].events) : []
948
+ if (!events.length) {
949
+ notes.push({ ok: false, id: 'network-hears-none', text: `${network} hears none of the site's conversions: \`services.${row}\` maps none to its events, so a campaign there optimizes for clicks (\`uniweb guide services\`, X and Meta)` })
950
+ } else {
951
+ const unheard = listed.filter((n) => !events.includes(n))
952
+ notes.push({ ok: true, id: 'network-hears', text: `${network} hears ${events.join(', ')}${unheard.length ? ` — not ${unheard.join(', ')}` : ''}` })
953
+ }
954
+ }
955
+ return notes
956
+ }
957
+
958
+ /**
959
+ * A draft's file with top-level fields set where they stand, editing nothing else: a post's new
960
+ * `send_at` and `version` once `send --at` has moved its time, so the file still says what the
961
+ * backend holds. Null when the file cannot be read again.
962
+ *
963
+ * @param {string} text
964
+ * @param {'markdown'|'yaml'|'json'} format
965
+ * @param {object} fields
966
+ * @returns {string|null}
967
+ */
968
+ export function fileWithFields(text, format, fields) {
969
+ if (format === 'json') {
970
+ try {
971
+ return `${JSON.stringify({ ...JSON.parse(text), ...fields }, null, 2)}\n`
972
+ } catch {
973
+ return null
974
+ }
975
+ }
976
+ const edit = (yamlText) => {
977
+ let before
978
+ try {
979
+ before = yaml.load(yamlText, YAML_READ) ?? {}
980
+ } catch {
981
+ return null
982
+ }
983
+ return isPlainObject(before) ? editYamlText(yamlText, before, { ...before, ...fields }) : null
984
+ }
985
+ if (format === 'markdown') {
986
+ const split = splitFrontmatter(text)
987
+ if (split.front === null) return null
988
+ const front = edit(split.front === '' ? '' : `${split.front}\n`)
989
+ return front === null ? null : `---\n${front.endsWith('\n') ? front : `${front}\n`}---\n${split.body}`
990
+ }
991
+ return edit(text)
992
+ }