uniweb 1.35.0 → 1.35.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uniweb",
3
- "version": "1.35.0",
3
+ "version": "1.35.2",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,15 +41,15 @@
41
41
  "js-yaml": "^4.3.2",
42
42
  "prompts": "^2.4.2",
43
43
  "tar": "^7.5.21",
44
- "@uniweb/content-writer": "~1.3.2",
44
+ "@uniweb/core": "~1.6.13",
45
45
  "@uniweb/semantic-parser": "~1.13.5",
46
- "@uniweb/schemas": "~1.7.4",
47
- "@uniweb/core": "~1.6.13"
46
+ "@uniweb/content-writer": "~1.3.2",
47
+ "@uniweb/schemas": "~1.7.4"
48
48
  },
49
49
  "peerDependencies": {
50
- "@uniweb/content-reader": "~1.5.11",
50
+ "@uniweb/build": "~1.24.1",
51
51
  "@uniweb/semantic-parser": "~1.13.5",
52
- "@uniweb/build": "~1.24.0"
52
+ "@uniweb/content-reader": "~1.5.11"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -218,6 +218,8 @@ await createEntity({ schema: '@/submission', unit: course.unit, items: [...] })
218
218
 
219
219
  Nested items in one create: give an item `uuid: uuidv7()` and a later item names it as `parent` (`{ section: 'degrees/thesis', parent: degree, data }`); those uuids serve the write alone.
220
220
 
221
+ **Sent twice, made once:** give a create the new entry's own `uuid`, made once when the person starts adding it (`const [uuid] = useState(uuidv7)`), and a second click or a retry answers with the entry the first one made. Without it, each call makes an entry.
222
+
221
223
  ## A backend on your machine
222
224
 
223
225
  ```yaml
@@ -6,6 +6,7 @@ On-demand guide (`uniweb guide promote`); AGENTS.md is assumed read. For a site
6
6
 
7
7
  - **The person** connects each account at its network, in a browser signed in to the app; you hand them the address `uniweb promote connect <network>` prints. They turn on the site's Analytics, which carries Promote, in the app. They reconnect an account that needs it, and an admin hands on one whose person left. They decide what goes out and what is spent.
8
8
  - **You** draft posts and campaigns, check the pages they link to, send and start what your person agreed to, and read what it brought. You act with their session, at the access they have; an account's tokens never pass through the CLI.
9
+ - **Access follows the site's.** Reading and drafting take edit on the site; sending, scheduling, starting, pausing and resuming take admin. Someone who can only view the site sees none of its Promote.
9
10
 
10
11
  ## On one screen
11
12
 
@@ -50,9 +51,10 @@ uniweb promote send holiday.md # now, or at its send_at; --at <time> set
50
51
  uniweb promote unschedule holiday.md # a draft again, its time kept
51
52
  ```
52
53
 
54
+ - **`send` given the file writes it first,** as `post` does, so what goes out is what the file says. If the app changed the post since, it is refused and nothing goes out. `send <id>` sends the post as stored.
53
55
  - **`via`** names a network, and the post goes out through the site's account there. The first time, the CLI chooses it from your one account on that network. With several, give `via: { network: x, connection: <id> }`; the refusal lists them.
54
56
  - **`page`** is a page of the site as pushed, so push a new page first. The live site must serve it in the post's language, or the send fails: publish first.
55
- - **A picture** given as a file is uploaded as one of the site's own, in its format. An address is kept as written.
57
+ - **A picture** given as a file is uploaded as one of the site's own, in its format. An `https:` address is kept as written, and so is one `show` printed.
56
58
  - **The words go out as written**, as plain text: Markdown formatting shows as typed.
57
59
  - YAML and JSON work too: `text` and `pictures` for one part, or `parts: [{ text, pictures }]`.
58
60
 
@@ -86,6 +88,7 @@ uniweb promote resume holiday --yes
86
88
 
87
89
  - **An ad runs in one of its campaign's accounts.** Name it with the ad's own `via`, or leave it out when the campaign has only one.
88
90
  - **`start` and `resume` say what they will spend before they spend it:** the dates, each account's daily budgets and the most they come to, and the pages. At a terminal they ask. Without one they refuse unless given `--yes`, so show your person that summary and pass `--yes` only after they agree. The network bills the owner's ad account.
91
+ - **An ad group with no `daily_budget` leaves its spend to the network,** so the summary states no most for that account. Give each ad group one.
89
92
  - **Once a campaign starts in an account, what runs there is fixed.** An edit to it is refused, and nothing changes. Add another ad account to its `via`, or draft a new campaign.
90
93
 
91
94
  ## Drafts stay right
@@ -134,7 +137,7 @@ A campaign with `goal: conversions` optimizes for what its network hears back. T
134
137
  | `post <file>` · `campaign <file>` | a draft, made or updated; `-` reads stdin |
135
138
  | `show <id>` | one post or campaign as its file holds it; its state goes to stderr |
136
139
  | `delete <id>` | a post, a campaign, an ad group or an ad |
137
- | `send <post> [--at <time> \| --now]` | post it now, or at its time |
140
+ | `send <post> [--at <time> \| --now]` | post it now, or at its time; a file is written first |
138
141
  | `unschedule <post>` | a scheduled post a draft again |
139
142
  | `start <campaign>` · `resume <campaign>` | spend, after saying what; `--yes` answers |
140
143
  | `pause <campaign>` | wherever it runs |
@@ -194,6 +194,32 @@ export function reasonWords(code) {
194
194
  /** A network's review of an ad, in words: `in_review` → `in review`. */
195
195
  export const reviewWords = (code) => String(code).replace(/_/g, ' ')
196
196
 
197
+ /** Why a post or an ad did not go out, in words: its reason, then the network's own words; null when it gave neither. */
198
+ export function whyNot(delivery) {
199
+ const said = [delivery?.reason ? reasonWords(delivery.reason) : null, delivery?.detail || null].filter(Boolean)
200
+ return said.length ? said.join(' — ') : null
201
+ }
202
+
203
+ /**
204
+ * A post's states as its delivery's `status` holds them, in the order a person reads them, what
205
+ * needs looking at first. A post with no delivery is a draft.
206
+ */
207
+ export const POST_STATES = ['failed', 'refused', 'draft', 'scheduled', 'review', 'published']
208
+
209
+ /**
210
+ * Posts counted by state, every state present: the known ones in `POST_STATES`'s order, then any
211
+ * other as the backend gave it, so a state the CLI has no word for yet is still counted.
212
+ *
213
+ * @param {Array<string|null|undefined>} states - each post's, empty for a draft
214
+ * @returns {Array<[string, number]>}
215
+ */
216
+ export function stateCounts(states) {
217
+ const counts = new Map()
218
+ for (const s of states) counts.set(s || 'draft', (counts.get(s || 'draft') ?? 0) + 1)
219
+ const order = [...POST_STATES.filter((s) => counts.has(s)), ...[...counts.keys()].filter((s) => !POST_STATES.includes(s))]
220
+ return order.map((s) => [s, counts.get(s)])
221
+ }
222
+
197
223
  // ── The input ──────────────────────────────────────────────────────────────────────
198
224
 
199
225
  const FRONT = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/
@@ -409,6 +435,20 @@ export function isAddress(picture) {
409
435
  return /^https?:\/\//i.test(picture)
410
436
  }
411
437
 
438
+ /**
439
+ * The pictures the site's Promote holds, as a read gives them back, each an address on the
440
+ * backend's own origin: what a draft may name again as written, though it is neither a file here
441
+ * nor an `https:` address. Any other path is a file, and one that isn't there is refused.
442
+ */
443
+ export function heldPictures(index) {
444
+ const held = new Set()
445
+ for (const i of index.items) {
446
+ if (i.section !== 'posts/parts' && i.section !== 'campaigns/ad_groups/ads/parts') continue
447
+ for (const p of Array.isArray(i.data?.pictures) ? i.data.pictures : []) if (typeof p === 'string') held.add(p)
448
+ }
449
+ return held
450
+ }
451
+
412
452
  // ── Pages, by their routes on the site as pushed ───────────────────────────────────
413
453
 
414
454
  /**
@@ -54,6 +54,7 @@ import {
54
54
  fileWithIdentity,
55
55
  findItem,
56
56
  formatOf,
57
+ heldPictures,
57
58
  idMatches,
58
59
  indexPromotion,
59
60
  isAddress,
@@ -70,9 +71,11 @@ import {
70
71
  shortIds,
71
72
  sitePages,
72
73
  splitFrontmatter,
74
+ stateCounts,
73
75
  versionOf,
74
76
  viaResolver,
75
- wentOut
77
+ wentOut,
78
+ whyNot
76
79
  } from '../backend/promote-drafts.js'
77
80
  import { checkFlags } from '../utils/flag-guard.js'
78
81
  import { confirm, isNonInteractive } from '../utils/interactive.js'
@@ -110,7 +113,8 @@ const USAGE = [
110
113
  ' show <id> One post or campaign, as a draft holds it',
111
114
  ' delete <id> Delete a post, a campaign, an ad group or an ad',
112
115
  ' send <post> Post it now, or at its send_at; --at <time> sets the time,',
113
- ' --now sends it now whatever its time',
116
+ ' --now sends it now whatever its time. Given its file, it writes',
117
+ ' the file first, so what goes out is what the file says',
114
118
  ' unschedule <post> A scheduled post a draft again, its time kept',
115
119
  ' start <campaign> Start it in its ad accounts — it says what it will spend and',
116
120
  ' asks; --yes answers for you',
@@ -199,7 +203,7 @@ async function targetSite(args, client, verb) {
199
203
  * @param {{ site: string, origin: string, what: string, index?: object }} ctx - `what` completes
200
204
  * "You may not …"; `index` names a campaign a refusal names by uuid
201
205
  */
202
- async function sayRefusal(res, { site, origin, what, index = null, notFound = null }) {
206
+ async function sayRefusal(res, { site, origin, what, index = null, notFound = null, forbidden = null }) {
203
207
  const body = await res.clone().json().catch(() => null)
204
208
  const reason = typeof body?.reason === 'string' ? body.reason : null
205
209
  const own = [reason, body?.detail ?? body?.message ?? body?.title].filter((x) => typeof x === 'string' && x).join(': ')
@@ -211,6 +215,8 @@ async function sayRefusal(res, { site, origin, what, index = null, notFound = nu
211
215
  say.err(`Only an admin of the site may ${what}. What is written stays, for one of them to do it.`)
212
216
  } else if (res.status === 403 && body?.op === 'edit' && body?.target) {
213
217
  say.err(`The account it goes out through is not shared with you for that. Use one you can use, or ask whoever connected it to share it.`)
218
+ } else if (res.status === 403 && forbidden) {
219
+ say.err(forbidden)
214
220
  } else if (res.status === 403) {
215
221
  say.err(`You may not ${what} on this site${body?.op ? ` (it takes ${body.op})` : ''}.`)
216
222
  } else if (res.status === 404) {
@@ -231,7 +237,14 @@ async function sayRefusal(res, { site, origin, what, index = null, notFound = nu
231
237
  /** A 404 on reading a site's Promote: no such site there, or a backend without these routes. */
232
238
  const notOffered = (origin, site) => `${origin} has no site ${site}, or does not offer Promote to this CLI yet.`
233
239
 
234
- /** The networks the deployment offers to connect, as tokens; null when it does not say. */
240
+ /** A 403 on reading it: the site is shared with you to view, and Promote takes edit. */
241
+ const VIEW_ONLY = 'Promote is for those who can edit the site, and you can only view it: an owner or admin of the site can give you edit, in the app.'
242
+
243
+ /**
244
+ * The networks the deployment offers to connect, as tokens. None when `/dev/config` names none,
245
+ * since the backend leaves `promote.networks` out while it offers none; null when `/dev/config`
246
+ * could not be read, so nothing is known.
247
+ */
235
248
  async function offeredNetworks(client) {
236
249
  const config = await client.discover().catch(() => null)
237
250
  const list = config?.promote?.networks
@@ -345,7 +358,7 @@ async function status(args) {
345
358
  offeredNetworks(client)
346
359
  ])
347
360
  if (!res.ok) {
348
- await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
361
+ await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site), forbidden: VIEW_ONLY })
349
362
  return { exitCode: 1 }
350
363
  }
351
364
  const promotion = (await res.json().catch(() => null))?.promotion ?? null
@@ -456,7 +469,8 @@ function printNetworks(networks, connections) {
456
469
  }
457
470
 
458
471
  function printPosts(posts) {
459
- const count = (state) => posts.filter((p) => p.state === state).length
472
+ const counts = new Map(stateCounts(posts.map((p) => p.state)))
473
+ const count = (state) => counts.get(state) ?? 0
460
474
  const scheduled = posts
461
475
  .filter((p) => p.state === 'scheduled')
462
476
  .map((p) => p.send_at)
@@ -467,14 +481,18 @@ function printPosts(posts) {
467
481
  `${count('scheduled')} scheduled${scheduled[0] ? ` (next ${scheduled[0]})` : ''}`,
468
482
  `${count('published')} published`
469
483
  ]
470
- if (count('failed')) parts.push(`${c.red}${count('failed')} failed${c.reset}`)
484
+ // Every other state the posts are in, counted: one in the network's review, and what didn't go out.
485
+ for (const [state, n] of counts) {
486
+ if (state === 'draft' || state === 'scheduled' || state === 'published') continue
487
+ parts.push(state === 'failed' || state === 'refused' ? `${c.red}${n} ${state}${c.reset}` : `${n} ${state}`)
488
+ }
471
489
  console.log(` ${c.bold}Posts${c.reset} ${parts.join(' · ')}`)
472
- // What can still be acted on, each by its id: a draft, a scheduled post, one that failed.
490
+ // What can still be acted on, each by its id: a draft, a scheduled post, one that didn't go out.
473
491
  for (const p of posts.filter((x) => x.state !== 'published' && x.state !== 'review')) {
474
492
  const first = String(p.parts?.[0]?.text ?? '').replace(/\s+/g, ' ').trim()
475
493
  const words = first ? `“${first.length > 40 ? `${first.slice(0, 39)}…` : first}”` : '(no words yet)'
476
494
  const when = p.state === 'scheduled' && p.send_at ? ` ${p.send_at}` : ''
477
- const why = p.state === 'failed' && p.delivery?.reason ? ` — ${reasonWords(p.delivery.reason)}` : ''
495
+ const why = (p.state === 'failed' || p.state === 'refused') && whyNot(p.delivery) ? ` — ${whyNot(p.delivery)}` : ''
478
496
  console.log(`${' '.repeat(17)}${c.cyan}${p.short ?? p.uuid}${c.reset} ${p.state}${when} ${words}${why}`)
479
497
  }
480
498
  }
@@ -709,7 +727,7 @@ async function begin(args, command, verb) {
709
727
  async function readIndex(client, site) {
710
728
  const res = await client.readPromotion(site)
711
729
  if (!res.ok) {
712
- await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site) })
730
+ await sayRefusal(res, { site, origin: client.origin, what: 'read Promote', notFound: notOffered(client.origin, site), forbidden: VIEW_ONLY })
713
731
  return null
714
732
  }
715
733
  return indexPromotion((await res.json().catch(() => null))?.promotion ?? null)
@@ -818,6 +836,9 @@ const sameInstant = (a, b) => typeof a === 'string' && typeof b === 'string' &&
818
836
  /** An amount as money reads: `10.00` for the `10` YAML reads `10.00` as; a string as written. */
819
837
  const money = (v) => (typeof v === 'number' && Number.isFinite(v) ? v.toFixed(2) : String(v))
820
838
 
839
+ /** Whether a value is an amount of money: a number, or the decimal text of one. */
840
+ const isAmount = (v) => v !== null && v !== undefined && v !== '' && Number.isFinite(Number(v))
841
+
821
842
  /** Amounts summed in cents, kept as the decimal text a network reads: `15.00`; null when none is given. */
822
843
  function sumAmounts(values) {
823
844
  let cents = 0
@@ -903,10 +924,11 @@ function translateDraft(draft, { index, pages, connections }) {
903
924
  if (a.fields.via !== undefined && a.fields.via !== null) {
904
925
  const raw = a.fields.via
905
926
  const want = typeof raw === 'object' ? raw : { network: raw }
927
+ // A stored account's connection reads back as an entity reference, one made in this write as its uuid.
906
928
  const matches = accounts.filter((n) =>
907
929
  typeof raw === 'string' && idMatches(n.uuid, raw)
908
930
  ? true
909
- : n.data?.network === want.network && (!want.connection || idMatches(n.data?.connection, String(want.connection)))
931
+ : n.data?.network === want.network && (!want.connection || idMatches(connectionOf(n.data?.connection).uuid, String(want.connection)))
910
932
  )
911
933
  if (matches.length === 1) ad.fields.via = matches[0].uuid
912
934
  else if (!matches.length) errors.push(`${where} goes through ${typeof raw === 'string' ? raw : want.network}, and the campaign does not run there — add it to the campaign's \`via\`.`)
@@ -923,21 +945,25 @@ function translateDraft(draft, { index, pages, connections }) {
923
945
 
924
946
  /**
925
947
  * Upload the pictures a draft names as files, each as one of the site's own and kept in its
926
- * format, as the app uploads a post's picture. An address is kept as written.
948
+ * format, as the app uploads a post's picture. An address is kept as written: an `https:` one, or
949
+ * one the site's Promote holds already, as a read gives it back (`held`).
927
950
  *
951
+ * @param {Set<string>} held - `heldPictures` of the promotion as read
928
952
  * @returns {Promise<{ map: Map<string,string> } | { error: string }>} picture as written → its address
929
953
  */
930
- async function uploadPictures(client, site, pictures, dir) {
954
+ async function uploadPictures(client, site, pictures, dir, held) {
931
955
  const map = new Map()
932
956
  const located = []
933
957
  const used = new Set()
934
958
  for (const p of pictures) {
935
- if (isAddress(p)) continue
959
+ if (isAddress(p) || held.has(p)) continue
936
960
  const path = isAbsolute(p) ? p : resolve(dir, p)
937
961
  if (!existsSync(path) || !statSync(path).isFile()) {
938
- // An address on the backend's own origin, as a read gives one back, is kept.
939
- if (p.startsWith('/')) continue
940
- return { error: `No picture ${p} (looked for ${path}).` }
962
+ return {
963
+ error: path === p
964
+ ? `No picture ${p}: there is no such file, and the site's Promote holds no picture at that address. A picture is a file, or an address starting https://.`
965
+ : `No picture ${p} (looked for ${path}).`
966
+ }
941
967
  }
942
968
  // The name the upload is planned under: the file's own, never where it sits on this machine.
943
969
  let name = basename(path)
@@ -987,29 +1013,15 @@ function indexAfterWrite(index, ops, results) {
987
1013
  }
988
1014
 
989
1015
  /**
990
- * `uniweb promote post <file>` and `campaign <file>` — make a draft, or update the one the file
991
- * names, and write its ids and versions back into the file.
1016
+ * Write a draft as `post` and `campaign` write one: checked against the promotion as read, its
1017
+ * names put in the backend's terms, its pictures uploaded, then written in one batch, and the
1018
+ * file it came from given its ids and versions. `send` writes a file this way before it sends it,
1019
+ * so what goes out is what the file says.
1020
+ *
1021
+ * @returns {Promise<object>} what the write left — `after`, the promotion once written — or
1022
+ * `{ exitCode }` once it has said why nothing was written
992
1023
  */
993
- async function writeDraft(args, kind) {
994
- const json = args.includes('--json')
995
- const input = readInput(args, kind)
996
- if (input.error) {
997
- say.err(input.error)
998
- return { exitCode: 2 }
999
- }
1000
- const format = formatOf(input.file, input.text)
1001
- const parsed = parseDraft(input.text, { format, kind })
1002
- if (parsed.error) {
1003
- say.err(parsed.error)
1004
- return { exitCode: 2 }
1005
- }
1006
- const draft = parsed.draft
1007
-
1008
- const at = await begin(args, kind === 'post' ? 'Writing a post' : 'Writing a campaign', kind)
1009
- if (!at.client) return at
1010
- const { client, site } = at
1011
- const index = await readIndex(client, site)
1012
- if (!index) return { exitCode: 1 }
1024
+ async function writeParsed({ client, site, index, input, format, draft, kind }) {
1013
1025
  const problems = checkDraft(index, draft)
1014
1026
  if (problems.length) {
1015
1027
  for (const p of problems) say.err(p)
@@ -1022,7 +1034,7 @@ async function writeDraft(args, kind) {
1022
1034
  for (const e of translated.errors) say.err(e)
1023
1035
  return { exitCode: 2 }
1024
1036
  }
1025
- const pictures = await uploadPictures(client, site, picturesOf(draft), input.dir)
1037
+ const pictures = await uploadPictures(client, site, picturesOf(draft), input.dir, heldPictures(index))
1026
1038
  if (pictures.error) {
1027
1039
  say.err(pictures.error)
1028
1040
  return { exitCode: 1 }
@@ -1053,11 +1065,41 @@ async function writeDraft(args, kind) {
1053
1065
  if (input.file) {
1054
1066
  const next = fileWithIdentity(input.text, { format, kind }, { uuid: plan.uuid, groups: plan.groups }, version)
1055
1067
  if (!next) fileNote = `Could not write the ids into ${input.shown} — its next run would make another draft. Add \`id: ${plan.uuid}\` and \`version: ${version(plan.uuid)}\` to it.`
1056
- else if (next.text !== input.text) {
1068
+ else if (next.text !== readFileSync(input.file, 'utf8')) {
1057
1069
  writeFileSync(input.file, next.text)
1058
1070
  if (next.whole) fileNote = `Wrote ${input.shown} again whole, with its ids: its layout could not be kept.`
1059
1071
  }
1060
1072
  }
1073
+ return { after, plan, ops, pages, connections, wasScheduled, version, fileNote }
1074
+ }
1075
+
1076
+ /**
1077
+ * `uniweb promote post <file>` and `campaign <file>` — make a draft, or update the one the file
1078
+ * names, and write its ids and versions back into the file.
1079
+ */
1080
+ async function writeDraft(args, kind) {
1081
+ const json = args.includes('--json')
1082
+ const input = readInput(args, kind)
1083
+ if (input.error) {
1084
+ say.err(input.error)
1085
+ return { exitCode: 2 }
1086
+ }
1087
+ const format = formatOf(input.file, input.text)
1088
+ const parsed = parseDraft(input.text, { format, kind })
1089
+ if (parsed.error) {
1090
+ say.err(parsed.error)
1091
+ return { exitCode: 2 }
1092
+ }
1093
+ const draft = parsed.draft
1094
+
1095
+ const at = await begin(args, kind === 'post' ? 'Writing a post' : 'Writing a campaign', kind)
1096
+ if (!at.client) return at
1097
+ const { client, site } = at
1098
+ const index = await readIndex(client, site)
1099
+ if (!index) return { exitCode: 1 }
1100
+ const wrote = await writeParsed({ client, site, index, input, format, draft, kind })
1101
+ if (!wrote.after) return wrote
1102
+ const { after, plan, ops, pages, connections, wasScheduled, version, fileNote } = wrote
1061
1103
 
1062
1104
  const ids = shortIds(after.items.map((i) => i.uuid))
1063
1105
  const item = after.byUuid.get(plan.uuid)
@@ -1270,6 +1312,10 @@ function sayDelivery(index, post, delivery, id) {
1270
1312
  * ⭐ A POST WITH A TIME GOES OUT AT ITS TIME. Its `send_at` is the draft's own field, so `send`
1271
1313
  * schedules a post that holds one and posts one that holds none; `--at` sets the time first, and
1272
1314
  * `--now` posts it now whatever its time.
1315
+ *
1316
+ * ⭐ GIVEN ITS FILE, WHAT GOES OUT IS WHAT THE FILE SAYS. `send <file>` writes the file's draft
1317
+ * first, as `post` does: an edit not written yet is written, and a copy the app changed since is
1318
+ * refused, with nothing sent. `send <id>` sends the post as the backend holds it.
1273
1319
  */
1274
1320
  async function send(args) {
1275
1321
  const json = args.includes('--json')
@@ -1293,29 +1339,72 @@ async function send(args) {
1293
1339
  say.err(`\`--at ${time}\` has passed: give a time ahead, or send it now with --now.`)
1294
1340
  return { exitCode: 2 }
1295
1341
  }
1342
+ const file = draftFile(arg)
1343
+ const parsed = file ? parseDraft(file.text, { format: file.format, kind: 'post' }) : null
1344
+ if (parsed?.error) {
1345
+ say.err(parsed.error)
1346
+ return { exitCode: 2 }
1347
+ }
1296
1348
  const at = await begin(args, 'Sending a post', `send ${arg}`)
1297
1349
  if (!at.client) return at
1298
1350
  const { client, site } = at
1299
- const index = await readIndex(client, site)
1351
+ let index = await readIndex(client, site)
1300
1352
  if (!index) return { exitCode: 1 }
1301
- const post = pick(index, arg, ['post'])
1302
- if (!post) return { exitCode: 2 }
1303
- const id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
1304
- const before = deliveryOf(index, post)
1353
+ // The post as the backend holds it: the one the file names (none yet for a new file), or the id's.
1354
+ let post = file ? (parsed.draft.id ? (index.byUuid.get(parsed.draft.id) ?? null) : null) : pick(index, arg, ['post'])
1355
+ if (!file && !post) return { exitCode: 2 }
1356
+ let id = post ? shortIds(index.items.map((i) => i.uuid)).get(post.uuid) : arg
1357
+ let before = post ? deliveryOf(index, post) : null
1358
+ let writes = 0
1305
1359
  const out = (delivery, exitCode) => {
1306
- if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, delivery }))
1360
+ if (json) console.log(JSON.stringify({ backend: client.origin, site, id: post.uuid, short: id, writes, delivery }))
1307
1361
  return { exitCode }
1308
1362
  }
1309
- if (wentOut(before)) {
1363
+ if (post && wentOut(before)) {
1310
1364
  if (!json) say.warn(`Post ${id} went out already${before.network_url ? `: ${before.network_url}` : ''}. A new post is a new draft.`)
1311
1365
  return out(before, 0)
1312
1366
  }
1313
1367
 
1314
- const when = now ? null : atGiven ? time : (post.data?.send_at ?? null)
1368
+ // The time it goes out at: --at's, else the file's own send_at where it names one, else the post's.
1369
+ const held = parsed && parsed.draft.fields.send_at !== undefined ? parsed.draft.fields.send_at : (post?.data?.send_at ?? null)
1370
+ const when = now ? null : atGiven ? time : held
1315
1371
  if (when && !atGiven && Date.parse(when) <= Date.now()) {
1316
1372
  say.err(`Post ${id} holds send_at ${when}, which has passed: send it now with --now, or at another time with --at <time>.`)
1317
1373
  return { exitCode: 2 }
1318
1374
  }
1375
+ // Scheduled before this command, so a write that makes it a draft again is said if sending is refused.
1376
+ const scheduledFor = before?.status === 'scheduled' ? (post.data?.send_at ?? null) : null
1377
+
1378
+ if (file) {
1379
+ // `--at` moves the file's own send_at, so the one write carries it and the file keeps saying it.
1380
+ let text = file.text
1381
+ if (atGiven && !sameInstant(held, time)) {
1382
+ text = fileWithFields(file.text, file.format, { send_at: time })
1383
+ if (!text) {
1384
+ say.err(`Could not set the time in ${arg}: give it \`send_at: ${time}\`, then send it.`)
1385
+ return { exitCode: 2 }
1386
+ }
1387
+ }
1388
+ const draft = text === file.text ? parsed.draft : parseDraft(text, { format: file.format, kind: 'post' }).draft
1389
+ const wrote = await writeParsed({
1390
+ client,
1391
+ site,
1392
+ index,
1393
+ input: { file: file.path, shown: arg, text, dir: dirname(file.path) },
1394
+ format: file.format,
1395
+ draft,
1396
+ kind: 'post'
1397
+ })
1398
+ if (!wrote.after) return wrote
1399
+ if (wrote.fileNote && !json) say.warn(wrote.fileNote)
1400
+ writes = wrote.ops.length
1401
+ index = wrote.after
1402
+ post = index.byUuid.get(wrote.plan.uuid)
1403
+ id = shortIds(index.items.map((i) => i.uuid)).get(post.uuid)
1404
+ before = deliveryOf(index, post)
1405
+ if (writes && text === file.text && !json) say.info(`Wrote what ${arg} says to post ${id} first: it differed from the post as stored.`)
1406
+ }
1407
+
1319
1408
  let res
1320
1409
  let moved = false
1321
1410
  if (when) {
@@ -1334,6 +1423,7 @@ async function send(args) {
1334
1423
  }
1335
1424
  post.data = { ...post.data, send_at: when }
1336
1425
  moved = true
1426
+ writes++
1337
1427
  }
1338
1428
  res = await client.postAction(site, post.uuid, 'schedule')
1339
1429
  } else {
@@ -1341,18 +1431,15 @@ async function send(args) {
1341
1431
  }
1342
1432
  if (!res.ok) {
1343
1433
  await sayRefusal(res, { site, origin: client.origin, what: 'send posts', index })
1434
+ // What this command wrote stays written, so say what the post is now.
1435
+ if (scheduledFor && writes) {
1436
+ say.warn(`Post ${id} was scheduled for ${scheduledFor}, and writing to it made it a draft again${moved || (when && !sameInstant(scheduledFor, when)) ? `, its time now ${when}` : ''}: it is not scheduled now.`)
1437
+ } else if (moved) {
1438
+ say.warn(`Post ${id}'s time is ${when} now, and it is not scheduled.`)
1439
+ }
1344
1440
  return { exitCode: 1 }
1345
1441
  }
1346
1442
  const delivery = (await res.json().catch(() => null))?.delivery ?? null
1347
- // A file the post was drafted in keeps its new time and version, so its next run is not stale.
1348
- const file = moved ? draftFile(arg) : null
1349
- if (file) {
1350
- const after = await readIndex(client, site).catch(() => null)
1351
- const item = after?.byUuid.get(post.uuid)
1352
- const next = item ? fileWithFields(file.text, file.format, { send_at: when, version: versionOf(after, item) }) : null
1353
- if (next) writeFileSync(file.path, next)
1354
- else if (!json) say.warn(`Could not write its new time into ${arg}: run \`uniweb promote show ${id} > ${arg}\` before you edit it again.`)
1355
- }
1356
1443
  if (json) return out(delivery, delivery?.status === 'failed' || delivery?.status === 'refused' ? 1 : 0)
1357
1444
  return { exitCode: sayDelivery(index, post, delivery, id) }
1358
1445
  }
@@ -1394,6 +1481,10 @@ async function unschedule(args) {
1394
1481
  * What starting (or resuming) a campaign in these ad accounts will spend, as far as the draft
1395
1482
  * says: its dates, and per account the ad groups whose ads run there, with their daily budgets
1396
1483
  * and the most that comes to. The currency is the account's, which the network knows.
1484
+ *
1485
+ * ⭐ A MOST IS SAID ONLY WHEN EVERY AD GROUP STATES ITS DAILY BUDGET. One without leaves what it
1486
+ * spends to the network, so the summary names it rather than add up the others as if it were the
1487
+ * whole: that total is the one number the person agrees to.
1397
1488
  */
1398
1489
  function spendSummary(index, campaign, accounts, { connections, pages }) {
1399
1490
  const starts = campaign.data?.starts ?? null
@@ -1409,13 +1500,15 @@ function spendSummary(index, campaign, accounts, { connections, pages }) {
1409
1500
  .children('campaigns/ad_groups', campaign.uuid)
1410
1501
  .map((g) => ({ g, ads: index.children('campaigns/ad_groups/ads', g.uuid).filter((a) => a.data?.via === via) }))
1411
1502
  .filter((x) => x.ads.length)
1412
- const daily = sumAmounts(groups.map((x) => x.g.data?.daily_budget))
1503
+ const unbudgeted = groups.filter((x) => !isAmount(x.g.data?.daily_budget)).map((x) => x.g.data?.name ?? null)
1504
+ const daily = unbudgeted.length ? null : sumAmounts(groups.map((x) => x.g.data?.daily_budget))
1413
1505
  const total = daily !== null && Number.isFinite(days) && days > 0 ? (Math.round(Number(daily) * 100) * days / 100).toFixed(2) : null
1414
1506
  return {
1415
1507
  via,
1416
1508
  account: accountName(index, via, connections),
1417
1509
  groups: groups.map((x) => ({ name: x.g.data?.name ?? null, daily_budget: x.g.data?.daily_budget ?? null, ads: x.ads.length })),
1418
1510
  daily,
1511
+ unbudgeted,
1419
1512
  upTo: total,
1420
1513
  pages: [...new Set(groups.flatMap((x) => x.ads.map((a) => pageRoute(a.data?.page, pages) ?? '(no page)')))]
1421
1514
  }
@@ -1433,8 +1526,12 @@ function printSummary(summary, act) {
1433
1526
  console.log(` ${a.account}: no ad runs there yet`)
1434
1527
  continue
1435
1528
  }
1436
- const budgets = a.groups.map((g) => (g.daily_budget == null ? 'no daily budget' : money(g.daily_budget))).join(' + ')
1437
- console.log(` ${a.account}: ${a.groups.length} ad group${a.groups.length === 1 ? '' : 's'}, ${budgets} a day in the account's currency${a.upTo ? ` — up to ${a.upTo}` : summary.ends ? '' : ', until paused'}`)
1529
+ const budgets = a.groups.map((g) => (isAmount(g.daily_budget) ? money(g.daily_budget) : 'no daily budget')).join(' + ')
1530
+ console.log(` ${a.account}: ${a.groups.length} ad group${a.groups.length === 1 ? '' : 's'}, ${budgets} a day in the account's currency${a.upTo ? ` — up to ${a.upTo}` : a.unbudgeted.length || summary.ends ? '' : ', until paused'}`)
1531
+ if (a.unbudgeted.length) {
1532
+ const named = a.unbudgeted.map((n) => (n ? `“${n}”` : 'one unnamed')).join(', ')
1533
+ console.log(` ${c.yellow}No most can be said: ad group ${named} states no daily budget, so the network decides what ${a.unbudgeted.length === 1 ? 'it spends' : 'they spend'}. Give ${a.unbudgeted.length === 1 ? 'it' : 'each'} a daily_budget to bound it.${c.reset}`)
1534
+ }
1438
1535
  const ads = a.groups.reduce((n, g) => n + g.ads, 0)
1439
1536
  console.log(` ${ads} ad${ads === 1 ? '' : 's'}, linking to ${a.pages.join(', ')}`)
1440
1537
  }
@@ -48,7 +48,7 @@
48
48
  * uniweb pull --no-delete Keep files with no backend item
49
49
  * uniweb pull --force Take the backend's version, discarding local changes
50
50
  * uniweb pull --dry-run In git, name each file it would change (a YAML file's keys
51
- * too); write nothing
51
+ * too, and whether this copy changed it too); write nothing
52
52
  *
53
53
  * The content + folder pull lanes are both keyed by the site's uuid on that backend
54
54
  * (sync.json).
@@ -168,11 +168,13 @@ const colors = {
168
168
  blue: '\x1b[36m'
169
169
  }
170
170
  // Looked up at each call, so a caller that captures the console captures these too — and
171
- // silent while a probe runs (`probePull`), which answers by what it returns.
171
+ // silent while a probe runs (`probePull`), which answers by what it returns. What it would
172
+ // have said went wrong is kept (`quietErrors`), so a dry run whose probe stopped can say why.
172
173
  let quiet = false
174
+ let quietErrors = []
173
175
  const log = (...a) => quiet || console.log(...a)
174
176
  const success = (m) => log(`${colors.green}✓${colors.reset} ${m}`)
175
- const error = (m) => quiet || console.error(`${colors.red}✗${colors.reset} ${m}`)
177
+ const error = (m) => (quiet ? quietErrors.push(m) : console.error(`${colors.red}✗${colors.reset} ${m}`))
176
178
  const info = (m) => log(`${colors.blue}→${colors.reset} ${m}`)
177
179
  const note = (m) => log(` ${colors.dim}${m}${colors.reset}`)
178
180
 
@@ -765,11 +767,19 @@ const takenFrom = (origin) => `Take the site's content from ${origin}`
765
767
  * `files` — `[status, path]`, status `A`, `M` or `D`, the path relative to the site
766
768
  */
767
769
  export async function probePull(args = [], deps = {}) {
770
+ return (await probeWithReason(args, deps)).probe
771
+ }
772
+
773
+ /** `probePull`, and when it does not answer, the last thing the pull would have said went wrong. */
774
+ async function probeWithReason(args, deps) {
768
775
  quiet = true
776
+ quietErrors = []
769
777
  try {
770
- return (await pull(args, { ...deps, probe: true }))?.probe ?? null
778
+ const probe = (await pull(args, { ...deps, probe: true }))?.probe ?? null
779
+ return { probe, reason: probe ? null : quietErrors.at(-1) ?? null }
771
780
  } finally {
772
781
  quiet = false
782
+ quietErrors = []
773
783
  }
774
784
  }
775
785
 
@@ -798,6 +808,21 @@ function yamlKeysChanged(files, { repo, rev, siteDir }) {
798
808
  return out
799
809
  }
800
810
 
811
+ /**
812
+ * Of the files a pull would change, those this copy's commits changed too since `rev`, the sync point
813
+ * the pull merges from: the pull merges each with the backend's, where a dry run could not show the result.
814
+ * A file outside the site (a mounted folder's, `..`) is left out, as `yamlKeysChanged` leaves it.
815
+ *
816
+ * @param {object} repo
817
+ * @param {string} rev - the sync point
818
+ * @param {Array<[string, string]>} files - the stand-in's `changes()`
819
+ * @returns {string[]} their paths, relative to the site
820
+ */
821
+ function changedSince(repo, rev, files) {
822
+ const same = (a, b) => (a === null || b === null ? a === b : a.equals(b))
823
+ return files.filter(([, path]) => !path.startsWith('..') && !same(fileAt(repo, rev, path), fileAt(repo, repo.head, path))).map(([, path]) => path)
824
+ }
825
+
801
826
  function changedKeys(was, now, at = '', depth = 0) {
802
827
  const plainMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
803
828
  if (!plainMap(was) || !plainMap(now)) return JSON.stringify(was) === JSON.stringify(now) ? [] : [at || '(the whole file)']
@@ -814,7 +839,7 @@ function changedKeys(was, now, at = '', depth = 0) {
814
839
  }
815
840
 
816
841
  /** A dry run's account of the pull it stands for (`probePull`). */
817
- function printPreview({ files, keys = {}, noBase, recordsNotPlaced, itemsBehind = 0, mountedMoved = [], held = [] }, origin) {
842
+ function printPreview({ files, keys = {}, changedHereToo = [], noBase, recordsNotPlaced, itemsBehind = 0, mountedMoved = [], held = [] }, origin) {
818
843
  const from = `${colors.dim}${origin}${colors.reset}`
819
844
  if (!files.length) {
820
845
  info(`Dry run — a pull from ${from} would change no file.`)
@@ -822,10 +847,12 @@ function printPreview({ files, keys = {}, noBase, recordsNotPlaced, itemsBehind
822
847
  return
823
848
  }
824
849
  info(`Dry run — a pull from ${from} would change ${files.length === 1 ? '1 file' : `${files.length} files`}:`)
850
+ const both = new Set(changedHereToo)
825
851
  for (const [status, path] of files) {
826
852
  const what = status === 'A' ? ' (new)' : status === 'D' ? ' (removed)' : ''
827
- note(`${path}${what}${keys[path] ? ` — ${keys[path].join(', ')}` : ''}`)
853
+ note(`${path}${what}${keys[path] ? ` — ${keys[path].join(', ')}` : ''}${both.has(path) ? ' (changed here too: the pull merges the two)' : ''}`)
828
854
  }
855
+ if (both.size) note('A file changed in both places is merged, and the pull stops on any part changed both ways, for you to settle.')
829
856
  if (noBase) note('This copy has no sync point with the site, so these are the files that differ, either way.')
830
857
  if (recordsNotPlaced) note('Some records could not be placed in files; the pull says which, and why.')
831
858
  }
@@ -889,8 +916,8 @@ export async function pull(args = [], deps = {}) {
889
916
  // anything is asked or taken, as it stops the build.
890
917
  const mounts = writableMounts(siteDir)
891
918
  if (mounts.refused.length) {
892
- if (probe) return { exitCode: 1, probe: null }
893
919
  error(`${mounts.refused.length === 1 ? 'A mount is' : `${mounts.refused.length} mounts are`} written in a form a pull no longer reads:`)
920
+ if (probe) return { exitCode: 1, probe: null }
894
921
  for (const m of mounts.refused) for (const line of refusedMountLines(m)) note(line)
895
922
  return { exitCode: 1 }
896
923
  }
@@ -982,10 +1009,18 @@ export async function pull(args = [], deps = {}) {
982
1009
  // `uniweb status` asks it: each file it would change, and in a YAML file the keys. ⛔ Until 2026-11-16
983
1010
  // it said only "would pull content", and a pull that rewrote a whole `site.yml` to change its favicon
984
1011
  // gave no sign of it beforehand (measured on a site, 2026-11-16).
985
- const preview = repo?.head && !probe ? await probePull(args.filter((a) => a !== '--dry-run'), deps) : null
986
- if (preview) {
987
- printPreview(preview, client.origin)
988
- return { exitCode: 0 }
1012
+ if (repo?.head && !probe) {
1013
+ const { probe: preview, reason } = await probeWithReason(args.filter((a) => a !== '--dry-run'), deps)
1014
+ if (preview) {
1015
+ printPreview(preview, client.origin)
1016
+ return { exitCode: 0 }
1017
+ }
1018
+ // ⛔ Not the lines below, which say only what a pull fetches: a preview that stopped is no
1019
+ // answer, and until 2026-11-16 "would pull content" stood in for one (a clone whose videos
1020
+ // git could not fetch, measured that day).
1021
+ error(`Dry run — could not tell what a pull from ${client.origin} would change, so nothing was pulled.`)
1022
+ if (reason) for (const line of String(reason).split('\n').map((l) => l.trim()).filter(Boolean).slice(0, 12)) note(line)
1023
+ return { exitCode: 1 }
989
1024
  }
990
1025
  info(
991
1026
  `Dry run — would pull content from ${colors.dim}${client.origin}${colors.reset}`
@@ -1150,7 +1185,11 @@ export async function pull(args = [], deps = {}) {
1150
1185
  if (probe) {
1151
1186
  // A lane that did not answer is not knowing — a records lane the backend has none of
1152
1187
  // (404) is no records; both unchanged is nothing to take.
1153
- if (!content || (!noRecords && !folderLane && !missing.has('records'))) return { exitCode: 1, probe: null }
1188
+ if (!content || (!noRecords && !folderLane && !missing.has('records'))) {
1189
+ // A lane that failed said why (`getDocs`); a site the backend answers 404 for only noted it.
1190
+ if (missing.has('content')) error(`${client.origin} has no such site — it was deleted there, or you lack access.`)
1191
+ return { exitCode: 1, probe: null }
1192
+ }
1154
1193
  if (!projected) return { exitCode: 0, probe: { files: [], recordsNotPlaced: false } }
1155
1194
  }
1156
1195
 
@@ -1535,6 +1574,10 @@ export async function pull(args = [], deps = {}) {
1535
1574
  files,
1536
1575
  // In a YAML file the pull would change, the keys whose values it changes (`changedKeys`).
1537
1576
  keys: yamlKeysChanged(files, { repo, rev: onto, siteDir: standIn.siteDir }),
1577
+ // Of those, the files this copy changed too since the sync point: the pull merges the two, and
1578
+ // stops on a part changed both ways. ⛔ Until 2026-11-16 a dry run named such a file as one the
1579
+ // pull "would change", and the pull then stopped on it (measured that day on a site's copy).
1580
+ changedHereToo: base ? changedSince(repo, onto, files) : [],
1538
1581
  itemsBehind,
1539
1582
  // By route: the mounted pages the backend moved, which the next push puts back, and the pages
1540
1583
  // held because their files cannot say what the app made of them.
@@ -98,7 +98,9 @@ import {
98
98
  deliveryOf,
99
99
  indexPromotion,
100
100
  reasonWords,
101
- shortIds
101
+ shortIds,
102
+ stateCounts,
103
+ whyNot
102
104
  } from '../backend/promote-drafts.js'
103
105
 
104
106
  const c = {
@@ -867,7 +869,8 @@ async function appChecks(siteDir, siteYml, { offline, args, git }) {
867
869
  * @param {Response|null} res - the promotion read, made beside the site's other reads
868
870
  */
869
871
  async function promoteChecks(client, uuid, res, { now = Date.now() } = {}) {
870
- if (!res || res.status === 404) return { checks: [], proposals: [] }
872
+ // A 403 is someone who can only view the site: Promote is shown to those who can edit it.
873
+ if (!res || res.status === 404 || res.status === 403) return { checks: [], proposals: [] }
871
874
  if (!res.ok) {
872
875
  return { checks: [{ id: 'promote.site', state: 'unknown', summary: `Could not read the site's Promote: HTTP ${res.status}.` }], proposals: [] }
873
876
  }
@@ -928,16 +931,14 @@ async function promoteChecks(client, uuid, res, { now = Date.now() } = {}) {
928
931
  .filter((p) => p.delivery?.status === 'scheduled' && Date.parse(p.item.data?.send_at) <= weekAhead)
929
932
  .sort((a, b) => Date.parse(a.item.data?.send_at) - Date.parse(b.item.data?.send_at))
930
933
  const network = (p) => index.byUuid.get(p.item.data?.via)?.data?.network ?? 'its network'
931
- const tally = ['draft', 'scheduled', 'published']
932
- .map((state) => [state, posts.filter((p) => (p.delivery?.status ?? 'draft') === state).length])
933
- .filter(([, n]) => n)
934
- .map(([state, n]) => `${n} ${state}`)
934
+ // Every state the posts are in, a network's review included, so no post goes uncounted.
935
+ const tally = stateCounts(posts.map((p) => p.delivery?.status)).map(([state, n]) => `${n} ${state}`)
935
936
  checks.push({
936
937
  id: 'promote.posts',
937
938
  state: failed.length ? 'attention' : 'ok',
938
- summary: `Posts: ${[...(failed.length ? [`${failed.length} failed`] : []), ...tally].join(' · ')}.`,
939
+ summary: `Posts: ${tally.join(' · ')}.`,
939
940
  lines: [
940
- ...failed.map((p) => `${ids.get(p.item.uuid)} failed on ${network(p)}: ${reasonWords(p.delivery.reason)}${p.delivery.detail ? ` — ${p.delivery.detail}` : ''}`),
941
+ ...failed.map((p) => `${ids.get(p.item.uuid)} ${p.delivery.status} on ${network(p)}: ${whyNot(p.delivery) ?? 'no reason given'}`),
941
942
  ...soon.map((p) => `${ids.get(p.item.uuid)} goes out on ${network(p)} at ${p.item.data.send_at}`)
942
943
  ],
943
944
  detail: {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-16T19:23:17.851Z",
3
+ "generatedAt": "2026-11-16T23:13:17.578Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
- "version": "1.7.1"
6
+ "version": "1.7.2"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.24.0"
9
+ "version": "1.24.1"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.11"
package/src/index.js CHANGED
@@ -2144,8 +2144,9 @@ Outside a repository there is nothing to merge against: the files are rewritten
2144
2144
  what the backend holds, after asking if any of them are yours.
2145
2145
 
2146
2146
  ${colors.bright}Options:${colors.reset}
2147
- --dry-run Name each file it would change, and in a YAML file the keys;
2148
- write nothing (outside a repository: what it would fetch)
2147
+ --dry-run Name each file it would change, and in a YAML file the keys, and
2148
+ mark those changed here too, which it merges; write nothing
2149
+ (outside a repository: what it would fetch)
2149
2150
  --force Take the backend's version, discarding local changes
2150
2151
  --no-records Pull pages only; skip records
2151
2152
  --no-assets Don't download media; the content keeps its URLs