@wirecat/cli-core 0.706.0 → 0.707.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,53 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.707.0 — 19.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A content write asks once.** `ContentWriteOptions.confirmed` carries the keys the `posts` command asked the owner
13
+ about (those at level `ask`), and `contentWriterFromManifest` hands them, with the call's own `api.<operation>` key
14
+ when there are any, to its `write` as a fourth argument. A CLI passes them to
15
+ `serviceApiWriter(...)(command, operation, input, { confirmed })`, so a terminal publish asks the owner once; a key
16
+ the command did not ask (the publish key for a post published at the source since the last sync) is still asked,
17
+ and `deny` or `readonly` still refuse.
18
+ - **`contentManifestFake` in `@wirecat/cli-core/content/testing`.** A content service in memory, built from a CLI's
19
+ own source manifest and generated API, as `crmManifestFake` is for a CRM: the contract kits and the CLI's `sync` run
20
+ over it without a hand-written fake of the service.
21
+
22
+ ### Changed — may break callers
23
+
24
+ - **The content commands use the vocabulary's words**, so a CLI made from them passes `cli-dev lint` (it needs
25
+ cli-base 0.123.0 or later). A script that called the old names must change:
26
+
27
+ | Before | Now |
28
+ |---|---|
29
+ | `authors list` | `users list` |
30
+ | `terms list` | `tags list` |
31
+ | `metrics show <post>` | `posts stats <post>` |
32
+ | `posts schedule <post> --at <time>` | `posts publish <post> --at-time <time>` |
33
+ | `posts list --since <day> --until <day>` | `posts list published:[<day> TO <day>]` (or `published:<day>`) |
34
+ | `posts list term:<id>` | `posts list tag:<id>` |
35
+ | `posts create\|update --body-file <path>` | `--text-file <path>` |
36
+ | `posts create\|update --excerpt <text>` | `--description <text>` |
37
+ | `posts create\|update --term <id>` (repeated) | `--tags <id,id>` |
38
+ | `posts delete --force` | `posts delete --allow-delete` |
39
+
40
+ `channels list`, `users list` and `tags list` take a query, which narrows by no field yet. The `posts.schedule` key
41
+ is gone: scheduling checks `posts.publish`, as it did already. A config that still sets `posts.schedule` now holds
42
+ an unknown key, so every command refuses to run and names the `config unset` that removes it.
43
+
44
+ ### Fixed
45
+
46
+ - **A profile on its own site keeps the site in its account.** `tokenSessionCommand` with `site` remembers
47
+ `<site>:<user id>`, the site as `--site` cleans it (host in lower case, no trailing slash), as bitrix24-cli keeps
48
+ `<portal>:<user id>`. Each WordPress site numbers its users from 1, so two profiles on two sites shared one copy in
49
+ the store, and a sync of one marked the other's posts deleted.
50
+ - **`posts list published:>…` leaves out a post published at that very second.** A strict start was read as `>=`.
51
+ - **`posts create|update --tags` with no ids is refused**, not taken as "remove every tag".
52
+ - **`contentManifestFake` puts a list where the call's own `items` says**, wraps a `get` answer at `get.items`, and
53
+ matches a route from the server's path only, so `/posts` no longer answers `/users/5/posts`.
54
+
8
55
  ## 0.706.0 — 19.11.2026
9
56
 
10
57
  ### Added
@@ -59,10 +59,12 @@ export declare const queryTerms: (words: QueryWords, registry: QueryRegistry, co
59
59
  * A `time` term as epoch ms bounds: `time>=7d`, `time:[2026-10-01 TO 2026-10-07]`, `time:today`, and the `meta`
60
60
  * an answer reports them by: the zone calendar words and bare dates were read in, and the bounds in UTC.
61
61
  * `until` is inclusive: an exclusive end (a bare date's next midnight, `… TO …}`) comes back 1 ms inside. `since` stays
62
- * as written, because the inbox reads strictly after a `date>` start.
62
+ * as written, because the inbox reads strictly after a `date>` start; `from` is the first moment taken, for a reader
63
+ * that takes its start.
63
64
  */
64
65
  export declare const timeBounds: (term: Predicate | undefined, zone?: string, now?: number) => {
65
66
  since?: number;
67
+ from?: number;
66
68
  until?: number;
67
69
  meta?: {
68
70
  timezone: string;
@@ -169,7 +169,8 @@ export const queryTerms = (words, registry, command, ranged = []) => {
169
169
  * A `time` term as epoch ms bounds: `time>=7d`, `time:[2026-10-01 TO 2026-10-07]`, `time:today`, and the `meta`
170
170
  * an answer reports them by: the zone calendar words and bare dates were read in, and the bounds in UTC.
171
171
  * `until` is inclusive: an exclusive end (a bare date's next midnight, `… TO …}`) comes back 1 ms inside. `since` stays
172
- * as written, because the inbox reads strictly after a `date>` start.
172
+ * as written, because the inbox reads strictly after a `date>` start; `from` is the first moment taken, for a reader
173
+ * that takes its start.
173
174
  */
174
175
  export const timeBounds = (term, zone = timezoneOf(), now) => {
175
176
  if (!term)
@@ -178,7 +179,9 @@ export const timeBounds = (term, zone = timezoneOf(), now) => {
178
179
  const range = dateRange(term.value, upper, term.operator === "range" ? term.lower_inclusive !== false : true, term.operator === "range" ? term.upper_inclusive !== false : true, zone, term.span, now);
179
180
  const until = range.upper === undefined ? undefined : range.upper - (range.upper_inclusive ? 0 : 1);
180
181
  return {
181
- ...(range.lower === undefined ? {} : { since: range.lower }),
182
+ ...(range.lower === undefined
183
+ ? {}
184
+ : { since: range.lower, from: range.lower_inclusive ? range.lower : range.lower + 1 }),
182
185
  ...(until === undefined ? {} : { until }),
183
186
  meta: {
184
187
  timezone: zone,
@@ -37,7 +37,10 @@ export interface TokenSessionOptions {
37
37
  login?: {
38
38
  page?: (site: string | undefined) => string;
39
39
  };
40
- /** Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so. */
40
+ /**
41
+ * Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so.
42
+ * With `site`, `id` is `<site>:<id>`, the site as `--site` was cleaned.
43
+ */
41
44
  claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
42
45
  /** What the token is, for the prompt and help: "API token" when not given. */
43
46
  token?: string;
@@ -102,7 +102,7 @@ export const tokenSessionCommand = (options) => {
102
102
  throw new CliError("validation_error", `no ${word} was given`);
103
103
  const token = login === undefined ? secret : `${login}:${secret}`;
104
104
  const { id, account } = await run((events) => options.verify(this, token, events, site));
105
- (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, id, tokens);
105
+ (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, siteAccount(site, id), tokens);
106
106
  const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
107
107
  answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
108
108
  });
@@ -170,6 +170,11 @@ export const tokenSessionCommand = (options) => {
170
170
  .addCommand(list);
171
171
  };
172
172
  const SITE = "site";
173
+ /**
174
+ * The account a profile keeps: on a service of the owner's own site, `<site>:<id>`, as bitrix24-cli keeps
175
+ * `<portal>:<user id>`. Each site numbers its users from 1, so the id alone would put two sites' records together.
176
+ */
177
+ const siteAccount = (site, id) => (site === undefined ? id : `${site}:${id}`);
173
178
  const noSite = (app, profile) => new CliError("authentication_error", `profile ${profile} is not signed in to a site — run \`${app.command} ${profile} session start --site <address>\``, { reason: "session.missing" });
174
179
  /**
175
180
  * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
@@ -27,7 +27,7 @@ export interface ContentCommandOptions {
27
27
  now?: () => number;
28
28
  }
29
29
  /**
30
- * The content commands: `sync`, `channels list`, `posts list|show|search`, `authors list`, `terms list`,
31
- * `metrics show`, and with `writes` `posts create|update|publish|schedule|unpublish|delete`.
30
+ * The content commands: `sync`, `channels list`, `posts list|show|search|stats`, `users list`, `tags list`, and with
31
+ * `writes` `posts create|update|publish|unpublish|delete`.
32
32
  */
33
33
  export declare const addContentCommands: (program: Command, options: ContentCommandOptions) => void;
@@ -8,7 +8,7 @@ import { environmentOf, inCommandRun, outputFor, runBudgetOf } from "../../cli/c
8
8
  import { honoursDryRun } from "../../cli/dry-run-guard.js";
9
9
  import { FETCH, LOCAL_READ, NO_EFFECTS, REMOTE_WRITE } from "../../cli/effects.js";
10
10
  import { itemOf, listOf, renderAnswer } from "../../cli/envelope.js";
11
- import { listQuery, nativeTermLists, termField, typedQuery, withQuery } from "../../cli/list-query.js";
11
+ import { listQuery, nativeField, nativeTermLists, termField, timeBounds, typedQuery, unfilteredQuery, withQuery, } from "../../cli/list-query.js";
12
12
  import { terminalAsker } from "../../cli/messenger/ask.js";
13
13
  import { CONTENT_KINDS, POST_STATUSES, POST_TYPES } from "../../domain/content.js";
14
14
  import { aheadOf } from "../../domain/moment.js";
@@ -33,8 +33,15 @@ const POSTS_QUERY = {
33
33
  }),
34
34
  termField("type", "enum", "type:page", { values: [...POST_TYPES] }),
35
35
  termField("channel", "kw", "channel:site", { relation: "the channel's id, as channels list shows it" }),
36
- termField("term", "kw", "term:12", { relation: "a tag's or category's id, as terms list shows it" }),
37
- termField("author", "kw", "author:3", { relation: "the author's id, as authors list shows it" }),
36
+ termField("tag", "kw", "tag:12", { relation: "a tag's or category's id, as tags list shows it" }),
37
+ termField("author", "kw", "author:3", { relation: "the author's id, as users list shows it" }),
38
+ nativeField({
39
+ name: "published",
40
+ type: "time",
41
+ operators: ["term", "range"],
42
+ example: "published:>=2026-01-01",
43
+ relation: "published in this time",
44
+ }),
38
45
  ],
39
46
  };
40
47
  const TIMES = new Set(["createdAt", "updatedAt", "publishedAt", "scheduledFor"]);
@@ -58,6 +65,7 @@ const viewOf = (item, extra = {}) => ({
58
65
  const postBody = (post) => viewOf({ kind: "post", record: post, deletedAt: null, syncedAt: 0 });
59
66
  const contentView = v.looseObject({ kind: v.picklist(CONTENT_KINDS), external_id: text, deleted: v.boolean() });
60
67
  const channelView = v.looseObject({ external_id: text, kind: text, network: text, name: text });
68
+ const CHANNELS_QUERY = unfilteredQuery("content_channel", channelView);
61
69
  const contentWrite = v.looseObject({ operation_id: text, post: v.optional(contentView) });
62
70
  const contentSync = v.looseObject({
63
71
  provider: text,
@@ -76,13 +84,6 @@ const contentSync = v.looseObject({
76
84
  })),
77
85
  gaps: v.array(v.looseObject({ kind: v.picklist(CONTENT_KINDS), message: text })),
78
86
  });
79
- const dayOrTime = (flag) => (typed) => {
80
- const at = Date.parse(typed);
81
- if (Number.isNaN(at))
82
- throw new InvalidArgumentError(`${flag} takes a day (YYYY-MM-DD) or an ISO 8601 time`);
83
- return at;
84
- };
85
- const collect = (value, previous) => [...previous, value];
86
87
  const addContentCommandsDefinition = (program, options) => {
87
88
  const now = () => options.now?.() ?? Date.now();
88
89
  const within = (command, readOnly, work) => inCommandRun(command, async () => {
@@ -152,7 +153,8 @@ const addContentCommandsDefinition = (program, options) => {
152
153
  });
153
154
  });
154
155
  const channels = annotate(program.command("channels"), { effects: NO_EFFECTS }).description("the sites and social accounts this profile publishes on");
155
- example(answerEntity(annotate(channels.command("list"), { effects: LOCAL_READ }), "content_channel", channelView).description("the channels copied by the last sync"), "channels list").action(async (_opts, command) => {
156
+ example(withQuery(answerEntity(annotate(channels.command("list"), { effects: LOCAL_READ }), "content_channel", channelView), CHANNELS_QUERY).description("the channels copied by the last sync"), "channels list").action(async (words, _opts, command) => {
157
+ listQuery(typedQuery(words), CHANNELS_QUERY, "channels list");
156
158
  await within(command, true, async (run) => {
157
159
  const items = (await run.store.content.channels(run.account)).map((one) => ({
158
160
  ...Object.fromEntries(Object.entries(one).map(([name, value]) => [snake(name), value])),
@@ -162,11 +164,10 @@ const addContentCommandsDefinition = (program, options) => {
162
164
  });
163
165
  });
164
166
  const posts = annotate(program.command("posts"), { effects: NO_EFFECTS }).description("posts and pages as last synced, with their text as Markdown");
165
- example(paging(withQuery(answerEntity(annotate(posts.command("list"), { effects: LOCAL_READ }), "content_post", contentView), POSTS_QUERY)
166
- .description("posts copied from the source, newest change first; run sync to bring them up to date")
167
- .option("--since <day>", "published on or after this day or time", dayOrTime("--since"))
168
- .option("--until <day>", "published before this day or time", dayOrTime("--until"))), "posts list status:draft", "posts list type:page --since 2026-01-01").action(async (words, opts, command) => {
167
+ example(paging(withQuery(answerEntity(annotate(posts.command("list"), { effects: LOCAL_READ }), "content_post", contentView), POSTS_QUERY).description("posts copied from the source, newest change first; run sync to bring them up to date")), "posts list status:draft", "posts list type:page published:>=2026-01-01").action(async (words, opts, command) => {
169
168
  const lists = nativeTermLists(listQuery(typedQuery(words), POSTS_QUERY, "posts list"), "posts list", ["status"]);
169
+ const published = timeBounds(lists.get("published")?.[0]);
170
+ lists.delete("published");
170
171
  if ([...lists.values()].flat().some((one) => one.operator !== "term" && one.operator !== "phrase"))
171
172
  throw new InvalidArgumentError("posts list takes field:value terms, each one whole value");
172
173
  const statuses = (lists.get("status") ?? []).map((one) => String(one.value).toLowerCase());
@@ -176,10 +177,11 @@ const addContentCommandsDefinition = (program, options) => {
176
177
  ...(statuses.length ? { statuses } : {}),
177
178
  ...(terms.has("type") ? { type: terms.get("type") } : {}),
178
179
  ...(terms.has("channel") ? { channel: terms.get("channel") } : {}),
179
- ...(terms.has("term") ? { term: terms.get("term") } : {}),
180
+ ...(terms.has("tag") ? { term: terms.get("tag") } : {}),
180
181
  ...(terms.has("author") ? { author: terms.get("author") } : {}),
181
- ...(opts.since === undefined ? {} : { since: opts.since }),
182
- ...(opts.until === undefined ? {} : { until: opts.until }),
182
+ ...(published.from === undefined ? {} : { since: published.from }),
183
+ // The store reads before `until`; the query's upper bound is the last moment it takes.
184
+ ...(published.until === undefined ? {} : { until: published.until + 1 }),
183
185
  limit: opts.limit,
184
186
  offset: (opts.page - 1) * opts.limit,
185
187
  };
@@ -240,11 +242,13 @@ const addContentCommandsDefinition = (program, options) => {
240
242
  });
241
243
  });
242
244
  for (const [kind, plural, what] of [
243
- ["author", "authors", "the source's authors, each with the person the store knows by the same e-mail"],
244
- ["term", "terms", "the source's tags and categories"],
245
+ ["author", "users", "the source's users who write, each with the person the store knows by the same e-mail"],
246
+ ["term", "tags", "the source's tags and categories"],
245
247
  ]) {
246
248
  const group = annotate(program.command(plural), { effects: NO_EFFECTS }).description(what);
247
- example(paging(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), `content_${kind}`, contentView)).description(`${plural} copied from the source`), `${plural} list`).action(async (opts, command) => {
249
+ const query = unfilteredQuery(`content_${kind}`, contentView);
250
+ example(paging(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), `content_${kind}`, contentView), query)).description(`${plural} copied from the source`), `${plural} list`).action(async (words, opts, command) => {
251
+ listQuery(typedQuery(words), query, `${plural} list`);
248
252
  await within(command, true, async (run) => {
249
253
  const found = await run.store.content.list(run.account, kind, {
250
254
  limit: opts.limit,
@@ -262,16 +266,15 @@ const addContentCommandsDefinition = (program, options) => {
262
266
  });
263
267
  });
264
268
  }
265
- const metrics = annotate(program.command("metrics"), { effects: NO_EFFECTS }).description("readings of a post's numbers, one per sync, each kept");
266
- example(answerEntity(annotate(metrics.command("show"), { effects: LOCAL_READ }), "content_metric", v.looseObject({ post: text, at: text }))
267
- .description("a post's readings, the newest first")
268
- .argument("<post>", "the post's id at the source"), "metrics show 10").action(async (id, _opts, command) => {
269
+ example(answerEntity(annotate(posts.command("stats"), { effects: LOCAL_READ }), "content_metric", v.looseObject({ post: text, at: text }))
270
+ .description("a post's readings of its numbers, one per sync, each kept, the newest first")
271
+ .argument("<post>", "the post's id at the source"), "posts stats 10").action(async (id, _opts, command) => {
269
272
  await within(command, true, async (run) => {
270
273
  const items = (await run.store.content.metrics(run.account, id)).map((one) => ({
271
274
  ...one,
272
275
  at: new Date(one.at).toISOString(),
273
276
  }));
274
- return listOf("metrics show", { items, limit: items.length, page: 1, has_more: false });
277
+ return listOf("posts stats", { items, limit: items.length, page: 1, has_more: false });
275
278
  });
276
279
  });
277
280
  if (!options.writes)
@@ -292,8 +295,8 @@ const addContentCommandsDefinition = (program, options) => {
292
295
  if (path === undefined)
293
296
  return undefined;
294
297
  if (path !== "-" && refusedPlace(path, options.app, run.env ?? process.env))
295
- throw new CliError("validation_error", `--body-file may not read ${path}: it holds sign-ins or state`, {
296
- param: "--body-file",
298
+ throw new CliError("validation_error", `--text-file may not read ${path}: it holds sign-ins or state`, {
299
+ param: "--text-file",
297
300
  });
298
301
  return readFileSync(path === "-" ? 0 : path, "utf8");
299
302
  };
@@ -301,21 +304,28 @@ const addContentCommandsDefinition = (program, options) => {
301
304
  const write = (name, description) => answerEntity(annotate(posts.command(name), { effects: REMOTE_WRITE, offline: false }), "content_write", contentWrite).description(description);
302
305
  const fields = (command) => command
303
306
  .option("--title <title>", "the post's title")
304
- .option("--body-file <path>", "the text as Markdown, from a file, or - for stdin")
305
- .option("--excerpt <text>", "the short text lists show")
307
+ .option("--text-file <path>", "the text as Markdown, from a file, or - for stdin")
308
+ .option("--description <text>", "the short text lists show, the excerpt")
306
309
  .option("--slug <slug>", "the address's last part")
307
- .option("--term <id>", "a tag's or category's id, as terms list shows it; repeat it; replaces the list", collect, []);
310
+ .option("--tags <ids>", "its tags and categories, by comma-separated ids as tags list shows them; replaces them");
308
311
  const fieldsOf = (run, typed) => {
309
- const body = bodyOf(run, typed.bodyFile);
312
+ const body = bodyOf(run, typed.textFile);
313
+ const tags = typed.tags
314
+ ?.split(",")
315
+ .map((one) => one.trim())
316
+ .filter(Boolean);
317
+ // An unset "$TAGS" in a script would otherwise strip every tag from the post.
318
+ if (tags?.length === 0)
319
+ throw new InvalidArgumentError("--tags takes one or more ids");
310
320
  return {
311
321
  ...(typed.title === undefined ? {} : { title: typed.title }),
312
322
  ...(body === undefined ? {} : { body }),
313
- ...(typed.excerpt === undefined ? {} : { excerpt: typed.excerpt }),
323
+ ...(typed.description === undefined ? {} : { excerpt: typed.description }),
314
324
  ...(typed.slug === undefined ? {} : { slug: typed.slug }),
315
- ...(typed.term.length ? { terms: typed.term } : {}),
325
+ ...(tags === undefined ? {} : { terms: tags }),
316
326
  };
317
327
  };
318
- example(fields(write("create", "write a new draft; publishing is its own step, posts publish")).option("--type <type>", `${POST_TYPES.join(" or ")}; post when left out`), "posts create --title 'Version 3' --body-file notes.md").action(async (typed, command) => {
328
+ example(fields(write("create", "write a new draft; publishing is its own step, posts publish")).option("--type <type>", `${POST_TYPES.join(" or ")}; post when left out`), "posts create --title 'Version 3' --text-file notes.md").action(async (typed, command) => {
319
329
  if (typed.type !== undefined && !POST_TYPES.includes(typed.type))
320
330
  throw new InvalidArgumentError(`--type is ${POST_TYPES.join(" or ")}`);
321
331
  await within(command, false, async (run) => {
@@ -334,35 +344,35 @@ const addContentCommandsDefinition = (program, options) => {
334
344
  return answered(done.operationId, done.post);
335
345
  });
336
346
  });
337
- for (const [name, description, act] of [
338
- ["publish", "publish a post now; a published post is answered as it is", publishPost],
339
- ["unpublish", "bring a published or scheduled post back to a draft", unpublishPost],
340
- ])
341
- example(write(name, description).argument("<post>", "the post's id at the source"), `posts ${name} 11`).action(async (id, _opts, command) => {
342
- await within(command, false, async (run) => {
343
- const done = await act(contextOf(run, command), id);
344
- return answered(done.operationId, done.post, done.unchanged ? { unchanged: true } : {});
345
- });
346
- });
347
- example(write("schedule", "publish a post at a later time; checks posts.publish too")
347
+ example(write("publish", "publish a post now, or at a later time with --at-time; a published post is answered as it is")
348
348
  .argument("<post>", "the post's id at the source")
349
- .requiredOption("--at <time>", "when it goes out: an ISO 8601 time, a day, or 3d from now; it must be ahead", (typed) => aheadOf(typed, "--at", Date.now())), "posts schedule 11 --at 2026-12-01T09:00:00Z").action(async (id, opts, command) => {
349
+ .option("--at-time <time>", "when it goes out instead of now: an ISO 8601 time, a day, or 3d from now; it must be ahead", (typed) => aheadOf(typed, "--at-time", Date.now())), "posts publish 11", "posts publish 11 --at-time 2026-12-01T09:00:00Z").action(async (id, opts, command) => {
350
350
  await within(command, false, async (run) => {
351
- const done = await schedulePost(contextOf(run, command), id, opts.at);
352
- return answered(done.operationId, done.post);
351
+ if (opts.atTime !== undefined) {
352
+ const scheduled = await schedulePost(contextOf(run, command), id, opts.atTime);
353
+ return answered(scheduled.operationId, scheduled.post);
354
+ }
355
+ const done = await publishPost(contextOf(run, command), id);
356
+ return answered(done.operationId, done.post, done.unchanged ? { unchanged: true } : {});
357
+ });
358
+ });
359
+ example(write("unpublish", "bring a published or scheduled post back to a draft").argument("<post>", "the post's id at the source"), "posts unpublish 11").action(async (id, _opts, command) => {
360
+ await within(command, false, async (run) => {
361
+ const done = await unpublishPost(contextOf(run, command), id);
362
+ return answered(done.operationId, done.post, done.unchanged ? { unchanged: true } : {});
353
363
  });
354
364
  });
355
- example(write("delete", "move a post to the source's trash, from which it comes back; --force deletes it for good")
365
+ example(write("delete", "move a post to the source's trash, from which it comes back; --allow-delete deletes it for good")
356
366
  .argument("<post>", "the post's id at the source")
357
- .option("--force", "delete it for good, past the trash; checks posts.delete.force"), "posts delete 11").action(async (id, opts, command) => {
367
+ .option("--allow-delete", "delete it for good, past the trash; checks posts.delete.force"), "posts delete 11").action(async (id, opts, command) => {
358
368
  await within(command, false, async (run) => {
359
- const done = await deletePost(contextOf(run, command), id, opts.force ? { force: true } : {});
369
+ const done = await deletePost(contextOf(run, command), id, opts.allowDelete ? { force: true } : {});
360
370
  return answered(done.operationId, done.post, { deleted: done.deleted });
361
371
  });
362
372
  });
363
373
  };
364
374
  /**
365
- * The content commands: `sync`, `channels list`, `posts list|show|search`, `authors list`, `terms list`,
366
- * `metrics show`, and with `writes` `posts create|update|publish|schedule|unpublish|delete`.
375
+ * The content commands: `sync`, `channels list`, `posts list|show|search|stats`, `users list`, `tags list`, and with
376
+ * `writes` `posts create|update|publish|unpublish|delete`.
367
377
  */
368
378
  export const addContentCommands = honoursDryRun(sharedCommand(addContentCommandsDefinition));
@@ -1,13 +1,16 @@
1
1
  import type { Command } from "commander";
2
2
  import type { ApiCommandInput } from "../../cli/bot/api.js";
3
3
  import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
+ import type { PermissionKey } from "../../sends/permissions.js";
4
5
  import type { ContentSource } from "../source.js";
5
6
  import { type ContentWriter } from "../writer.js";
6
7
  /**
7
8
  * Sends one write the way the `api` group does: `serviceApiWriter` bound to the invoking command, which checks the
8
9
  * profile's keys (the publish value keys, the force-delete key) and asks. Nothing else may write for a CLI.
9
10
  */
10
- export type ContentWriteCall = (command: Command, operation: string, input: ApiCommandInput) => Promise<{
11
+ export type ContentWriteCall = (command: Command, operation: string, input: ApiCommandInput,
12
+ /** The keys the owner was already asked about (level `ask`); with any, the call's own `api.<operation>` too. */
13
+ confirmed: readonly PermissionKey[]) => Promise<{
11
14
  operation_id: string;
12
15
  result: unknown;
13
16
  }>;
@@ -78,44 +78,47 @@ export const contentWriterFromManifest = (input, options) => {
78
78
  throw pagesUnwritten();
79
79
  return found;
80
80
  };
81
- const send = async (call, slots, body) => {
81
+ const send = async (call, slots, confirmed, body) => {
82
82
  const base = call.body === undefined ? {} : fill(call.body, slots);
83
- const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }));
83
+ // The owner said yes to this write in the content command, so its one call is not asked about again; a key that
84
+ // command did not ask about, as the publish key for a post that is published at the source now, still is.
85
+ const own = options.api.operations.find((one) => one.id === call.operation)?.command;
86
+ const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }), !confirmed?.length ? [] : [...confirmed, ...(own === undefined ? [] : [`api.${own}`])]);
84
87
  return result;
85
88
  };
86
- const updated = async (externalId, body) => {
87
- const post = await postOf(await send(writes.update, { id: externalId }, body));
89
+ const updated = async (externalId, body, confirmed) => {
90
+ const post = await postOf(await send(writes.update, { id: externalId }, confirmed, body));
88
91
  if (!post)
89
92
  throw new CliError("invalid_response", `${manifest.provider} answered an update with no post`);
90
93
  return post;
91
94
  };
92
95
  return {
93
96
  provider: manifest.provider,
94
- async createDraft(draft) {
97
+ async createDraft(draft, options_) {
95
98
  if (draft.type === "page")
96
99
  throw pagesUnwritten();
97
- const post = await postOf(await send(writes.create, {}, await bodyOf(draft)));
100
+ const post = await postOf(await send(writes.create, {}, options_.confirmed, await bodyOf(draft)));
98
101
  if (!post)
99
102
  throw new CliError("invalid_response", `${manifest.provider} answered a create with no post`);
100
103
  return post;
101
104
  },
102
105
  async update(externalId, patch, options_) {
103
106
  await current(externalId, options_);
104
- return updated(externalId, await bodyOf(patch));
107
+ return updated(externalId, await bodyOf(patch), options_.confirmed);
105
108
  },
106
109
  async publish(externalId, options_) {
107
110
  const found = await current(externalId, options_);
108
111
  if (found.status === "published")
109
112
  return found;
110
- return updated(externalId, { ...writes.publish });
113
+ return updated(externalId, { ...writes.publish }, options_.confirmed);
111
114
  },
112
115
  async schedule(externalId, when, options_) {
113
116
  await current(externalId, options_);
114
- return updated(externalId, fill(writes.schedule, { at: iso(when) }));
117
+ return updated(externalId, fill(writes.schedule, { at: iso(when) }), options_.confirmed);
115
118
  },
116
119
  async unpublish(externalId, options_) {
117
120
  await current(externalId, options_);
118
- return updated(externalId, { ...writes.unpublish });
121
+ return updated(externalId, { ...writes.unpublish }, options_.confirmed);
119
122
  },
120
123
  async trash(externalId, options_) {
121
124
  await current(externalId, options_);
@@ -124,10 +127,10 @@ export const contentWriterFromManifest = (input, options) => {
124
127
  throw new CliError("validation_error", `${manifest.provider} takes no deletion past the trash`, {
125
128
  reason: "content.write-unsupported",
126
129
  });
127
- await send(writes.delete, { id: externalId });
130
+ await send(writes.delete, { id: externalId }, options_.confirmed);
128
131
  return null;
129
132
  }
130
- return postOf(await send(writes.trash, { id: externalId }));
133
+ return postOf(await send(writes.trash, { id: externalId }, options_.confirmed));
131
134
  },
132
135
  };
133
136
  };
@@ -1,3 +1,4 @@
1
+ export { type ContentManifestFake, type ContentManifestFakeOptions, contentManifestFake } from "./manifest-fake.js";
1
2
  export { exampleContentRows, type FakeContentRows, type FakeContentSource, type FakeContentSourceOptions, fakeContentSource, } from "./source.js";
2
3
  export { type ContentSourceFaults, type ContentSourceFixture, contentSourceContract, } from "./source-contract.js";
3
4
  export { type ContentSyncFixture, contentSyncContract } from "./sync-contract.js";
@@ -1,3 +1,4 @@
1
+ export { contentManifestFake } from "./manifest-fake.js";
1
2
  export { exampleContentRows, fakeContentSource, } from "./source.js";
2
3
  export { contentSourceContract, } from "./source-contract.js";
3
4
  export { contentSyncContract } from "./sync-contract.js";
@@ -0,0 +1,54 @@
1
+ import type { ApiCommandInput } from "../../cli/bot/api.js";
2
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import type { ContentKind } from "../../domain/content.js";
4
+ import { type FakeContentRows } from "./source.js";
5
+ type Row = Record<string, unknown>;
6
+ export interface ContentManifestFakeOptions {
7
+ /** The generated API manifest the source manifest names its operations in. */
8
+ api: ServiceApiManifest;
9
+ /** Our records, written into the service's own shape by each entity's map; default `exampleContentRows()`. */
10
+ rows?: FakeContentRows;
11
+ /** Each page holds at most this many rows, whatever limit the call asks: a small page makes every list page. */
12
+ pageSize?: number;
13
+ /** The service's clock, for the change time a write stamps. */
14
+ clock?: () => number;
15
+ }
16
+ export interface ContentManifestFake {
17
+ /** Reads as `serviceApiCall` sends them, with the answer's headers through `withHeaders`. */
18
+ call: ((operation: string, input: ApiCommandInput) => Promise<unknown>) & {
19
+ withHeaders: (operation: string, input: ApiCommandInput) => Promise<{
20
+ body: unknown;
21
+ headers: Headers;
22
+ }>;
23
+ };
24
+ /** Writes as `serviceApiWriter` sends them: the `write` a manifest writer takes. */
25
+ write: (command: unknown, operation: string, input: ApiCommandInput, confirmed?: readonly string[]) => Promise<{
26
+ operation_id: string;
27
+ result: unknown;
28
+ }>;
29
+ /** The same service over HTTP, for a CLI's own commands: each request matched to its operation by method and path. */
30
+ fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
31
+ /** Each kind's rows in the service's shape, by entity, as a test may change them. */
32
+ rows: Partial<Record<ContentKind, Row[][]>>;
33
+ /** The ids of each kind's rows as the service holds them: what a contract's `held` names. */
34
+ ids(kind: ContentKind): string[];
35
+ /** The operations each write reached, in order. */
36
+ writes: string[];
37
+ /** Calls no route of the manifest makes: a source that sends one would fail on the real service. */
38
+ refusals: string[];
39
+ /** Moves a post's change time to now, as an edit elsewhere does. */
40
+ touch(kind: ContentKind, id: string): void;
41
+ /** Moves a post to the trash, as the owner does in the service's own editor. */
42
+ trash(id: string): void;
43
+ remove(kind: ContentKind, id: string): void;
44
+ loseNextAnswer(): void;
45
+ }
46
+ /**
47
+ * A content service in memory, built from a source manifest and the generated API it names. Our records are written
48
+ * into each entity's shape by its map (the status by its `map`, a post's text by its body format), read back by the
49
+ * calls the manifest names, paged by each operation's own pagination (the page count in its header where it has one,
50
+ * a page past the end refused), and written by the manifest's writes. Service-neutral: a content CLI's own config
51
+ * drives it, as `crmManifestFake` does a CRM's.
52
+ */
53
+ export declare const contentManifestFake: (input: unknown, options: ContentManifestFakeOptions) => ContentManifestFake;
54
+ export {};
@@ -0,0 +1,426 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { at } from "../../crm/manifest/map.js";
3
+ import { parseContentManifest } from "../manifest/manifest.js";
4
+ import { utcEpoch } from "../manifest/map.js";
5
+ import { exampleContentRows } from "./source.js";
6
+ const T0 = Date.parse("2026-11-01T10:00:00Z");
7
+ // A time with no offset: what `utcEpoch` reads as UTC, as WordPress's `*_gmt` fields are written.
8
+ const stamp = (ms) => new Date(ms).toISOString().slice(0, 19);
9
+ const digits = (id) => (/^\d+$/.test(id) ? Number(id) : Number(id.replace(/\D/g, "")) || id);
10
+ const pathOf = (rule) => {
11
+ if (rule === undefined || typeof rule === "function")
12
+ return undefined;
13
+ if (typeof rule === "string")
14
+ return rule;
15
+ if ("each" in rule || "value" in rule)
16
+ return undefined;
17
+ if ("first" in rule)
18
+ return rule.first[0];
19
+ if ("join" in rule)
20
+ return rule.join[0];
21
+ if ("all" in rule)
22
+ return rule.all[0];
23
+ return rule.path;
24
+ };
25
+ const put = (row, path, value) => {
26
+ const keys = path.split(".");
27
+ const last = keys.pop();
28
+ let inner = row;
29
+ for (const key of keys) {
30
+ if (typeof inner[key] !== "object" || inner[key] === null || Array.isArray(inner[key]))
31
+ inner[key] = {};
32
+ inner = inner[key];
33
+ }
34
+ inner[last] = value;
35
+ };
36
+ const merged = (row, body) => {
37
+ for (const [key, value] of Object.entries(body)) {
38
+ const inner = row[key];
39
+ if (value && typeof value === "object" && !Array.isArray(value) && inner && typeof inner === "object")
40
+ merged(inner, value);
41
+ else
42
+ row[key] = structuredClone(value);
43
+ }
44
+ };
45
+ /** The service's value a rule maps onto ours: a `map` rule's key whose value is ours. */
46
+ const sourceValue = (rule, ours) => {
47
+ if (rule && typeof rule === "object" && "map" in rule && rule.map)
48
+ return Object.entries(rule.map).find(([, value]) => value === ours)?.[0] ?? ours;
49
+ return ours;
50
+ };
51
+ const constantOf = (entity, field) => {
52
+ const rule = entity.map[field];
53
+ return rule && typeof rule === "object" && "value" in rule ? rule.value : undefined;
54
+ };
55
+ const fixedOf = (value, trail = []) => {
56
+ if (value && typeof value === "object")
57
+ return Object.entries(value).flatMap(([key, inner]) => fixedOf(inner, [...trail, key]));
58
+ if (value === undefined || /^\{\w+\}$/.test(String(value)))
59
+ return [];
60
+ return [[trail.join("."), String(value)]];
61
+ };
62
+ const placeOf = (call, placeholder) => {
63
+ for (const where of ["path", "query"])
64
+ for (const [key, value] of Object.entries(call[where] ?? {}))
65
+ if (value === placeholder)
66
+ return { in: where, name: key };
67
+ return undefined;
68
+ };
69
+ const html = (markdown) => `<p>${markdown.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>")}</p>`;
70
+ const statusOf = (error) => error.code === "not_found"
71
+ ? 404
72
+ : error.code === "permission_error"
73
+ ? 403
74
+ : error.code === "validation_error"
75
+ ? 400
76
+ : 500;
77
+ /**
78
+ * A content service in memory, built from a source manifest and the generated API it names. Our records are written
79
+ * into each entity's shape by its map (the status by its `map`, a post's text by its body format), read back by the
80
+ * calls the manifest names, paged by each operation's own pagination (the page count in its header where it has one,
81
+ * a page past the end refused), and written by the manifest's writes. Service-neutral: a content CLI's own config
82
+ * drives it, as `crmManifestFake` does a CRM's.
83
+ */
84
+ export const contentManifestFake = (input, options) => {
85
+ const manifest = parseContentManifest(input, options.api);
86
+ const operations = new Map(options.api.operations.map((one) => [one.id, one]));
87
+ const size = options.pageSize ?? 2;
88
+ let last = 0;
89
+ // After every example row by default, as a sync's own clock is: an edit made now is a change since the last sync.
90
+ // Whole seconds, as the service writes its times: a change stamped in the cursor's own second would be lost.
91
+ const clock = options.clock ??
92
+ (() => {
93
+ last = Math.max(last + 1000, Math.ceil(Math.max(Date.now(), T0) / 1000) * 1000 + 1000);
94
+ return last;
95
+ });
96
+ const given = options.rows ?? exampleContentRows();
97
+ const writes = [];
98
+ const refusals = [];
99
+ let lose = false;
100
+ let made = 1000;
101
+ const entities = (kind) => manifest.entities[kind] ?? [];
102
+ // A record goes to the entity whose constant (a term's kind, a post's type) is its own; else the first.
103
+ const entityIndex = (kind, record) => {
104
+ const field = kind === "term" ? "kind" : kind === "post" ? "type" : undefined;
105
+ const found = field ? entities(kind).findIndex((one) => constantOf(one, field) === record[field]) : -1;
106
+ return Math.max(found, 0);
107
+ };
108
+ const termPaths = manifest.writes?.fields.terms ?? {};
109
+ const termKinds = new Map((given.term ?? []).map((one) => [one.externalId, one.kind]));
110
+ const rawOf = (kind, entity, record) => {
111
+ const row = {};
112
+ const time = (value) => (typeof value === "number" ? stamp(value) : value);
113
+ for (const [field, rule] of Object.entries(entity.map)) {
114
+ const path = pathOf(rule);
115
+ const value = record[field];
116
+ if (path === undefined || value === undefined || value === null)
117
+ continue;
118
+ if (field === "terms" && rule && typeof rule === "object" && "all" in rule) {
119
+ for (const one of rule.all)
120
+ put(row, one, []);
121
+ for (const term of value) {
122
+ const into = termPaths[termKinds.get(term) ?? "tag"] ?? rule.all[0];
123
+ if (into)
124
+ at(row, into)?.push(digits(term));
125
+ }
126
+ continue;
127
+ }
128
+ // The source keeps one date where ours keeps two: the one this status has goes there.
129
+ if (field === "publishedAt" && record.status === "scheduled")
130
+ continue;
131
+ if (field === "version" && path === pathOf(entity.map.updatedAt))
132
+ continue;
133
+ const written = field === "externalId" || field === "parent"
134
+ ? digits(String(value))
135
+ : field === "authors" || field === "terms"
136
+ ? value.map(digits)
137
+ : field.endsWith("At") || field === "scheduledFor"
138
+ ? time(value)
139
+ : sourceValue(rule, value);
140
+ put(row, path, written);
141
+ }
142
+ if (kind === "post" && entity.body && typeof record.body === "string")
143
+ put(row, entity.body.path, entity.body.format === "markdown" ? record.body : html(record.body));
144
+ return row;
145
+ };
146
+ const rows = {};
147
+ for (const kind of manifest.kinds) {
148
+ rows[kind] = entities(kind).map(() => []);
149
+ for (const record of (given[kind] ?? [])) {
150
+ const index = entityIndex(kind, record);
151
+ const entity = entities(kind)[index];
152
+ if (entity)
153
+ rows[kind]?.[index]?.push(rawOf(kind, entity, record));
154
+ }
155
+ }
156
+ const idOf = (entity, row) => String(at(row, pathOf(entity.map.externalId) ?? "id"));
157
+ const changedOf = (entity, row) => {
158
+ const path = entity.changes?.keyset?.field ?? pathOf(entity.map.updatedAt);
159
+ const value = path === undefined ? undefined : at(row, path);
160
+ return utcEpoch(value) ?? 0;
161
+ };
162
+ const stampRow = (entity, row) => {
163
+ const path = entity.changes?.keyset?.field ?? pathOf(entity.map.updatedAt);
164
+ if (path)
165
+ put(row, path, stamp(clock()));
166
+ };
167
+ const routes = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity, index) => [
168
+ ...(entity.changes ? [{ kind, index, role: "changes", call: entity.changes }] : []),
169
+ ...(entity.get ? [{ kind, index, role: "get", call: entity.get }] : []),
170
+ { kind, index, role: "list", call: entity.list },
171
+ ...(entity.ids ? [{ kind, index, role: "list", call: entity.ids }] : []),
172
+ ...(entity.optional?.requires
173
+ ? [{ kind, index, role: "requires", call: entity.optional.requires }]
174
+ : []),
175
+ ]));
176
+ const carries = (route, request) => {
177
+ const fixed = fixedOf({ path: route.call.path ?? {}, query: route.call.query ?? {} });
178
+ const own = { path: request.path, query: request.query };
179
+ if (!fixed.every(([path, value]) => String(at(own, path)) === value))
180
+ return false;
181
+ for (const placeholder of ["{since}", "{id}"]) {
182
+ const place = placeOf(route.call, placeholder);
183
+ if (place && request[place.in][place.name] === undefined)
184
+ return false;
185
+ }
186
+ return true;
187
+ };
188
+ // The list sits where the source reads it: the call's own `items` first, then the operation's.
189
+ const wrapped = (items, value) => {
190
+ if (items === undefined || items === "")
191
+ return value;
192
+ const body = {};
193
+ put(body, items, value);
194
+ return body;
195
+ };
196
+ const page = (operation, call, list, request) => {
197
+ const pagination = operation.pagination;
198
+ const items = call.items ?? pagination?.items;
199
+ if (!pagination)
200
+ return { body: wrapped(items, list), headers: new Headers() };
201
+ const pageValue = (parameter) => {
202
+ if (parameter.in !== "query")
203
+ throw new CliError("configuration_error", `the content fake pages by a query parameter, not ${parameter.in}`);
204
+ return request.query[parameter.name];
205
+ };
206
+ let from = 0;
207
+ let pages;
208
+ if (pagination.style === "page") {
209
+ const start = pagination.start ?? 1;
210
+ const number = Number(pageValue(pagination.page) ?? start);
211
+ pages = Math.max(1, Math.ceil(list.length / size));
212
+ if (pagination.pagesHeader !== undefined && number - start + 1 > pages)
213
+ throw new CliError("validation_error", "the page number is past the last page");
214
+ from = (number - start) * size;
215
+ }
216
+ else if (pagination.style === "offset")
217
+ from = Number(pageValue(pagination.offset) ?? 0);
218
+ else if (pagination.style === "cursor")
219
+ from = Number(pageValue(pagination.cursor) ?? 0);
220
+ else
221
+ throw new CliError("configuration_error", `the content fake does not page by ${pagination.style}`);
222
+ const rows = list.slice(from, from + size);
223
+ const headers = new Headers(pagination.style === "page" && pagination.pagesHeader ? { [pagination.pagesHeader]: String(pages) } : {});
224
+ if (items === undefined || items === "")
225
+ return { body: rows, headers };
226
+ const body = wrapped(items, rows);
227
+ if ("total" in pagination && pagination.total)
228
+ put(body, pagination.total, list.length);
229
+ if (pagination.style === "cursor") {
230
+ const more = from + size < list.length;
231
+ put(body, pagination.next, more ? String(from + size) : "");
232
+ if (pagination.hasMore)
233
+ put(body, pagination.hasMore, more);
234
+ }
235
+ return { body, headers };
236
+ };
237
+ const read = async (operation, request) => {
238
+ const found = operations.get(operation);
239
+ const route = routes.find((one) => one.call.operation === operation && carries(one, request));
240
+ if (!found || !route) {
241
+ refusals.push(operation);
242
+ throw new CliError("configuration_error", `the content fake answers no ${operation} call like this`);
243
+ }
244
+ const entity = entities(route.kind)[route.index];
245
+ const held = rows[route.kind]?.[route.index] ?? [];
246
+ if (route.role === "requires") {
247
+ const body = {};
248
+ put(body, route.call.check, true);
249
+ return { body, headers: new Headers() };
250
+ }
251
+ if (route.role === "get") {
252
+ const place = placeOf(route.call, "{id}");
253
+ const id = place ? request[place.in][place.name] : undefined;
254
+ const row = held.find((one) => idOf(entity, one) === String(id));
255
+ if (!row)
256
+ throw new CliError("not_found", `no ${route.kind} ${id}`);
257
+ return { body: wrapped(route.call.items, structuredClone(row)), headers: new Headers() };
258
+ }
259
+ let list = [...held].sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
260
+ if (route.role === "changes" && entity.changes) {
261
+ const place = placeOf(entity.changes, "{since}");
262
+ const raw = String(request[place.in][place.name]);
263
+ const since = entity.changes.since === "iso" ? Date.parse(raw) : Number(raw) * (entity.changes.since === "seconds" ? 1000 : 1);
264
+ if (Number.isNaN(since))
265
+ throw new CliError("validation_error", `${raw} is not a time`);
266
+ list = held
267
+ .filter((row) => changedOf(entity, row) > since)
268
+ .sort((a, b) => changedOf(entity, a) - changedOf(entity, b));
269
+ }
270
+ return page(found, route.call, structuredClone(list), request);
271
+ };
272
+ const write = (operation, request) => {
273
+ const ours = manifest.writes;
274
+ const [entity] = entities("post");
275
+ const held = rows.post?.[0];
276
+ if (!ours || !entity || !held)
277
+ throw new CliError("configuration_error", "the source manifest writes no posts");
278
+ const matches = (call) => call?.operation === operation &&
279
+ fixedOf(call.query ?? {}).every(([key, value]) => String(request.query[key]) === value);
280
+ const body = request.body ? JSON.parse(request.body) : {};
281
+ writes.push(operation);
282
+ const find = () => {
283
+ const place = placeOf(ours.update, "{id}") ?? { in: "path", name: "id" };
284
+ const id = request[place.in][place.name];
285
+ const row = held.find((one) => idOf(entity, one) === String(id));
286
+ if (!row)
287
+ throw new CliError("not_found", `no post ${id}`);
288
+ return row;
289
+ };
290
+ let answer;
291
+ if (matches(ours.create)) {
292
+ made += 1;
293
+ const row = {};
294
+ put(row, pathOf(entity.map.externalId) ?? "id", made);
295
+ merged(row, body);
296
+ stampRow(entity, row);
297
+ held.push(row);
298
+ answer = structuredClone(row);
299
+ }
300
+ else if (matches(ours.delete)) {
301
+ const row = find();
302
+ held.splice(held.indexOf(row), 1);
303
+ answer = { deleted: true, previous: structuredClone(row) };
304
+ }
305
+ else if (matches(ours.trash)) {
306
+ const row = find();
307
+ const status = pathOf(entity.map.status);
308
+ if (status)
309
+ put(row, status, sourceValue(entity.map.status, "trashed"));
310
+ stampRow(entity, row);
311
+ answer = structuredClone(row);
312
+ }
313
+ else if (matches(ours.update)) {
314
+ const row = find();
315
+ merged(row, body);
316
+ stampRow(entity, row);
317
+ answer = structuredClone(row);
318
+ }
319
+ else {
320
+ refusals.push(operation);
321
+ throw new CliError("configuration_error", `the content fake takes no ${operation} write like this`);
322
+ }
323
+ if (lose) {
324
+ lose = false;
325
+ throw new CliError("outcome_unknown", "the connection dropped after the service got the write");
326
+ }
327
+ return answer;
328
+ };
329
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
330
+ // The server's own path, as /wp-json; a site with a path of its own (`host/blog`) stands before it.
331
+ const serverPath = (options.api.servers?.[0]?.url ?? "").replace(/^https:\/\/[^/]*/, "").replace(/\/+$/, "");
332
+ const base = serverPath ? `(?:/[^/]+)*?${escaped(serverPath)}` : "";
333
+ // A literal segment wins over a placeholder: /users/me is not the user whose id is "me".
334
+ const placeholders = (path) => (path.match(/\{\w+\}/g) ?? []).length;
335
+ const http = [...operations.values()]
336
+ .sort((a, b) => a.binding.kind === "http" && b.binding.kind === "http"
337
+ ? placeholders(a.binding.path) - placeholders(b.binding.path) || b.binding.path.length - a.binding.path.length
338
+ : 0)
339
+ .flatMap((operation) => operation.binding.kind === "http"
340
+ ? [
341
+ {
342
+ operation,
343
+ method: operation.binding.method,
344
+ names: [...operation.binding.path.matchAll(/\{(\w+)\}/g)].map((one) => one[1]),
345
+ pattern: new RegExp(`^${base}${operation.binding.path
346
+ .split(/\{\w+\}/)
347
+ .map(escaped)
348
+ .join("([^/]+)")}$`),
349
+ },
350
+ ]
351
+ : []);
352
+ const fetch = async (target, init) => {
353
+ const url = new URL(target instanceof Request ? target.url : target);
354
+ const method = (init?.method ?? (target instanceof Request ? target.method : "GET")).toUpperCase();
355
+ const found = http.find((one) => one.method === method && one.pattern.test(url.pathname));
356
+ if (!found) {
357
+ refusals.push(`${method} ${url.pathname}`);
358
+ return Response.json({ message: "no such route" }, { status: 404 });
359
+ }
360
+ const values = url.pathname.match(found.pattern)?.slice(1) ?? [];
361
+ const request = {
362
+ path: Object.fromEntries(found.names.map((name, index) => [name, decodeURIComponent(values[index] ?? "")])),
363
+ query: Object.fromEntries(url.searchParams),
364
+ headers: {},
365
+ fields: {},
366
+ ...(typeof init?.body === "string" ? { body: init.body } : {}),
367
+ };
368
+ try {
369
+ if (found.operation.effect === "read") {
370
+ const answer = await read(found.operation.id, request);
371
+ return Response.json(answer.body, { headers: answer.headers });
372
+ }
373
+ return Response.json(write(found.operation.id, request));
374
+ }
375
+ catch (error) {
376
+ if (!(error instanceof CliError) || error.code === "outcome_unknown")
377
+ throw error;
378
+ return Response.json({ message: error.message }, { status: statusOf(error) });
379
+ }
380
+ };
381
+ const call = Object.assign(async (operation, request) => (await read(operation, request)).body, {
382
+ withHeaders: read,
383
+ });
384
+ const locate = (kind, id) => {
385
+ for (const [index, held] of (rows[kind] ?? []).entries()) {
386
+ const entity = entities(kind)[index];
387
+ const row = held.find((one) => idOf(entity, one) === id);
388
+ if (row)
389
+ return { entity, held, row };
390
+ }
391
+ return undefined;
392
+ };
393
+ return {
394
+ call,
395
+ write: async (_command, operation, request) => ({
396
+ operation_id: `op-${writes.length + 1}`,
397
+ result: write(operation, request),
398
+ }),
399
+ fetch,
400
+ rows,
401
+ ids: (kind) => (rows[kind] ?? []).flatMap((held, index) => held.map((row) => idOf(entities(kind)[index], row))),
402
+ writes,
403
+ refusals,
404
+ touch(kind, id) {
405
+ const found = locate(kind, id);
406
+ if (found)
407
+ stampRow(found.entity, found.row);
408
+ },
409
+ trash(id) {
410
+ const found = locate("post", id);
411
+ const status = found && pathOf(found.entity.map.status);
412
+ if (!found || !status)
413
+ return;
414
+ put(found.row, status, sourceValue(found.entity.map.status, "trashed"));
415
+ stampRow(found.entity, found.row);
416
+ },
417
+ remove(kind, id) {
418
+ const found = locate(kind, id);
419
+ if (found)
420
+ found.held.splice(found.held.indexOf(found.row), 1);
421
+ },
422
+ loseNextAnswer() {
423
+ lose = true;
424
+ },
425
+ };
426
+ };
@@ -18,6 +18,11 @@ export type ContentDraft = ContentFields & {
18
18
  export interface ContentWriteOptions {
19
19
  /** Journaled before the call. */
20
20
  operationId: string;
21
+ /**
22
+ * The keys the owner was asked about for this write, those at level `ask`: a writer over the `api` group does not
23
+ * ask them again. A key at `allow` is not among them, and passing one would skip a question the owner set.
24
+ */
25
+ confirmed?: readonly PermissionKey[];
21
26
  /**
22
27
  * The version the copy holds. A source whose post has another one now refuses with `content.conflict`: someone
23
28
  * changed it since the last sync, and the write would overwrite that.
@@ -15,7 +15,6 @@ export const CONTENT_WRITE_DEFAULTS = {
15
15
  "posts.create": "ask",
16
16
  "posts.update": "ask",
17
17
  [POSTS_PUBLISH_KEY]: "ask",
18
- "posts.schedule": "ask",
19
18
  "posts.unpublish": "ask",
20
19
  "posts.delete": "ask",
21
20
  [POSTS_DELETE_FORCE_KEY]: "ask",
@@ -28,11 +27,9 @@ export const contentAlsoChecks = (path) => {
28
27
  const [noun, command] = path;
29
28
  if (path.length !== 2 || noun !== "posts")
30
29
  return [];
31
- if (command === "schedule")
32
- return [POSTS_PUBLISH_KEY];
33
30
  if (command === "update")
34
31
  return [{ key: POSTS_PUBLISH_KEY, when: "the post is published or scheduled" }];
35
32
  if (command === "delete")
36
- return [{ key: POSTS_DELETE_FORCE_KEY, when: "--force" }];
33
+ return [{ key: POSTS_DELETE_FORCE_KEY, when: "--allow-delete" }];
37
34
  return [];
38
35
  };
@@ -14,7 +14,12 @@ const guardOf = (context, extra) => {
14
14
  /** Checked and journaled once; a lost answer is `outcome_unknown`, and the owner syncs before writing again. */
15
15
  const written = async (context, key, extra, operationId, act) => {
16
16
  try {
17
- return await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, act);
17
+ // The keys the owner was asked about here (an `ask` level) need not be asked again by a writer's own call; a key
18
+ // allowed here was asked about by nobody, so it confirms nothing.
19
+ const settings = context.writes.settings();
20
+ const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
21
+ const asked = [key, ...extra].filter((one) => levelFor(settings.permissions, one, defaults).level === "ask");
22
+ return await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, () => act(asked));
18
23
  }
19
24
  catch (error) {
20
25
  if (!isCliError(error) || error.code !== "outcome_unknown")
@@ -63,7 +68,7 @@ export const createPost = async (context, draft) => {
63
68
  if (!draft.title?.trim() && !draft.body?.trim())
64
69
  throw new CliError("validation_error", "a new post needs a title or a body", { reason: "content.empty" });
65
70
  const operationId = newOperationId();
66
- const post = await written(context, "posts.create", [], operationId, () => context.writes.writer.createDraft(draft, { operationId }));
71
+ const post = await written(context, "posts.create", [], operationId, (confirmed) => context.writes.writer.createDraft(draft, { operationId, confirmed }));
67
72
  return kept(context, post, operationId);
68
73
  };
69
74
  /**
@@ -79,7 +84,7 @@ export const updatePost = async (context, externalId, fields, options = {}) => {
79
84
  "Change only its title, excerpt or tags, or add --replace-body to replace the body anyway", { reason: "content.lossy-body", param: "--replace-body" });
80
85
  const operationId = newOperationId();
81
86
  const extra = PUBLIC.has(copy.record.status) ? [POSTS_PUBLISH_KEY] : [];
82
- const post = await written(context, "posts.update", extra, operationId, () => context.writes.writer.update(externalId, fields, { operationId, version: copy.record.version ?? null }));
87
+ const post = await written(context, "posts.update", extra, operationId, (confirmed) => context.writes.writer.update(externalId, fields, { operationId, version: copy.record.version ?? null, confirmed }));
83
88
  return kept(context, post, operationId);
84
89
  };
85
90
  /** Publishes now. A post the copy holds as published is answered as it is, and nothing is sent. */
@@ -88,7 +93,7 @@ export const publishPost = async (context, externalId) => {
88
93
  if (copy.record.status === "published")
89
94
  return { operationId: "", post: copy.record, unchanged: true };
90
95
  const operationId = newOperationId();
91
- const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, () => context.writes.writer.publish(externalId, { operationId, version: copy.record.version ?? null }));
96
+ const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, (confirmed) => context.writes.writer.publish(externalId, { operationId, version: copy.record.version ?? null, confirmed }));
92
97
  return kept(context, post, operationId);
93
98
  };
94
99
  /** Publishes at `at`, which must be ahead: a source publishes a post dated in the past at once. */
@@ -102,7 +107,7 @@ export const schedulePost = async (context, externalId, at) => {
102
107
  reason: "content.already-published",
103
108
  });
104
109
  const operationId = newOperationId();
105
- const post = await written(context, "posts.schedule", [POSTS_PUBLISH_KEY], operationId, () => context.writes.writer.schedule(externalId, at, { operationId, version: copy.record.version ?? null }));
110
+ const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, (confirmed) => context.writes.writer.schedule(externalId, at, { operationId, version: copy.record.version ?? null, confirmed }));
106
111
  return kept(context, post, operationId);
107
112
  };
108
113
  export const unpublishPost = async (context, externalId) => {
@@ -110,15 +115,16 @@ export const unpublishPost = async (context, externalId) => {
110
115
  if (copy.record.status === "draft")
111
116
  return { operationId: "", post: copy.record, unchanged: true };
112
117
  const operationId = newOperationId();
113
- const post = await written(context, "posts.unpublish", [], operationId, () => context.writes.writer.unpublish(externalId, { operationId, version: copy.record.version ?? null }));
118
+ const post = await written(context, "posts.unpublish", [], operationId, (confirmed) => context.writes.writer.unpublish(externalId, { operationId, version: copy.record.version ?? null, confirmed }));
114
119
  return kept(context, post, operationId);
115
120
  };
116
121
  /** Into the trash; `force` deletes for good and checks its own key. The copy keeps the last text as a revision. */
117
122
  export const deletePost = async (context, externalId, options = {}) => {
118
123
  const copy = await copyOf(context, externalId);
119
124
  const operationId = newOperationId();
120
- const post = await written(context, "posts.delete", options.force ? [POSTS_DELETE_FORCE_KEY] : [], operationId, () => context.writes.writer.trash(externalId, {
125
+ const post = await written(context, "posts.delete", options.force ? [POSTS_DELETE_FORCE_KEY] : [], operationId, (confirmed) => context.writes.writer.trash(externalId, {
121
126
  operationId,
127
+ confirmed,
122
128
  version: copy.record.version ?? null,
123
129
  ...(options.force ? { force: true } : {}),
124
130
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.706.0",
3
+ "version": "0.707.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -326,7 +326,7 @@
326
326
  "@types/pngjs": "6.0.5",
327
327
  "@types/ssh2": "1.15.5",
328
328
  "@vitest/coverage-v8": "^5.0.5",
329
- "@wirecat/cli-base": "0.122.0",
329
+ "@wirecat/cli-base": "0.123.0",
330
330
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
331
331
  "ajv": "8.17.1",
332
332
  "commander": "15.0.0",