@wirecat/cli-core 0.715.0 → 0.717.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,57 @@ 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.717.0 — 21.11.2026
9
+
10
+ ### Changed — may break callers
11
+
12
+ - **`account rename` of a profile that is not here fails with `profile.unknown`.** It had its own reason,
13
+ `account-rename.unknown-profile`, with the same code and message as `account remove`'s, and the family audit
14
+ counts one failure under two names as a new finding, which blocked `cli-dev audit --family` of every CLI on
15
+ cli-core. `profile.unknown` is what the rest of the tool gives for a profile that is not here, with the same
16
+ `details.profiles`; `account remove` keeps `account-remove.unknown-profile`, which WireCat Desktop matches. An
17
+ agent that matched `account-rename.unknown-profile` matches `profile.unknown` instead.
18
+
19
+ ### Fixed
20
+
21
+ - **`session` help names the sign-in the CLI keeps,** as its prompt does: "application password" for a WordPress
22
+ CLI, "API token" when the CLI names none, "password" for a sign-in with `--login`. It said "token" for all.
23
+ A CLI's generated command pages change with it at its next bump.
24
+ - **`api` help names what the commands were made from.** `serviceApiCommand` takes `spec`, such as
25
+ "its index at /wp-json"; left out, it is still "its OpenAPI document", or "its GraphQL schema" when every
26
+ operation is GraphQL.
27
+ - **whatsapp-cli is off the parity known-broken list.** whatsapp-cli#418 adopted cli-core 0.714.0 and names the
28
+ scheduled-message methods WhatsApp never has, so a release fails again when whatsapp-cli breaks. The list is empty.
29
+
30
+ ## 0.716.0 — 21.11.2026
31
+
32
+ ### Added
33
+
34
+ - **A content manifest writes pages: `writes.page`.** It names a page's own create, update, trash and delete calls,
35
+ and its `fields` when they differ from a post's. `posts create --type page` and every write to a page then go by
36
+ those calls, and the answer stays a page in the copy. Without it a page write is still refused as
37
+ `content.write-unsupported`, and so are tags on a type whose fields have none
38
+ ([CONTENT.md](docs/dev/CONTENT.md#content-from-a-manifest)).
39
+ - **`optional.fallback`: a refused call is sent again in a simpler form.** It names query values over the call's own
40
+ (WordPress: `context: "view"` for the users, which only an administrator lists with `context=edit`). An editor or
41
+ an author then gets the authors with published posts, by name and without e-mail, and the gap says the fallback's
42
+ message. `contentManifestFake` answers that form of a `denied` operation, and its new `hidden` names rows a
43
+ sign-in may not see.
44
+ - **`openContentStore`** (`@wirecat/cli-core/content`): the store helper of a content CLI's `open`, so content no
45
+ longer opens the store with the CRM's `openCrmStore`. Both come from `openProfileStore`; `openCrmStore` stays.
46
+
47
+ ### Fixed
48
+
49
+ - **An author or a contributor no longer lists every post on every sync, and sees a post deleted for good.** A gap
50
+ that is a right the role lacks (`optional.requires`, `needs`, `fallback`; `ContentGap.lasting`) now lets the cursor
51
+ move on, and the id pass reads each post it no longer lists once more by its id: only a 404 marks it deleted, a
52
+ refusal keeps it. The cursor keeps the rights the role lacked; once it has one more, the kind is listed in full
53
+ again. Only an entity with a `get` gives such a gap; without one it still holds the pass. A post's tags in a
54
+ manifest whose `writes.fields` has no `terms` are now refused instead of dropped without a word.
55
+ - **A post's text keeps its `-` list marker.** `htmlToMarkdown` wrote `* one` for `- one`, so a body read back
56
+ differed from the file it was written from. A stored post with a list gets one new revision the next time it is read.
57
+ - **`content.schedule-past` names `--at-time`,** the option `posts publish` takes, not `--at`.
58
+
8
59
  ## 0.715.0 — 21.11.2026
9
60
 
10
61
  ### Added
@@ -65,7 +65,7 @@ export const accountRenameCommand = (app, renaming, options = {}) => annotate(ne
65
65
  const next = usableProfileName(wanted);
66
66
  const known = (name) => settings.profilesHere.includes(name) || existsSync(accountFileFor(app, name, env));
67
67
  if (!known(profile))
68
- throw new CliError("not_found", `no profile ${profile} on this computer — ${settings.profilesHere.join(", ") || "there is none"}`, { reason: "account-rename.unknown-profile", profiles: settings.profilesHere });
68
+ throw new CliError("not_found", `no profile ${profile} on this computer — ${settings.profilesHere.join(", ") || "there is none"}`, { reason: "profile.unknown", profiles: settings.profilesHere });
69
69
  if (next === profile)
70
70
  throw new CliError("validation_error", `${profile} already has that name`);
71
71
  if (known(next) || (settings.botProfiles ?? []).includes(next))
@@ -0,0 +1,31 @@
1
+ import { type AppIdentity } from "../ports/app.js";
2
+ import type { MessageStore } from "../store/store.js";
3
+ import type { AccountKey } from "../store/types.js";
4
+ export interface ProfileStoreOptions {
5
+ app: AppIdentity;
6
+ env: NodeJS.ProcessEnv;
7
+ profile: string;
8
+ /** The command only reads the store: the `readOnly` its category's `open` is given. */
9
+ readOnly: boolean;
10
+ /** The service's provider, as the store names it: the empty store's account under the read-only lock. */
11
+ provider: string;
12
+ /** Opens the shared store as the CLI does; a writable open also registers its provider. */
13
+ open: (env: NodeJS.ProcessEnv, options?: {
14
+ readOnly?: boolean;
15
+ }) => Promise<MessageStore>;
16
+ /** The profile's account from its sign-in; asked only when no earlier run saved it. */
17
+ account: () => AccountKey;
18
+ }
19
+ /**
20
+ * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
21
+ * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
22
+ * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
23
+ * may change) and the profile.
24
+ *
25
+ * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
26
+ * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
27
+ */
28
+ export declare const openProfileStore: (options: ProfileStoreOptions) => Promise<{
29
+ store: MessageStore;
30
+ account: AccountKey;
31
+ }>;
@@ -0,0 +1,64 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { isCliError } from "@wirecat/cli-base";
5
+ import { readOnlyLockOf } from "../ports/app.js";
6
+ /**
7
+ * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
8
+ * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
9
+ * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
10
+ * may change) and the profile.
11
+ *
12
+ * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
13
+ * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
14
+ */
15
+ export const openProfileStore = async (options) => {
16
+ const { app, env, profile, readOnly, open } = options;
17
+ const locked = readOnly && readOnlyLockOf(app, env) !== undefined;
18
+ if (readOnly) {
19
+ const store = await open(env, { readOnly: true }).catch((error) => {
20
+ if (locked && !(isCliError(error) && error.code === "not_found"))
21
+ throw error;
22
+ return undefined;
23
+ });
24
+ if (store) {
25
+ const saved = await store.accounts
26
+ .profiles()
27
+ .then((all) => all[app.command]?.[profile])
28
+ .catch(() => undefined);
29
+ if (saved)
30
+ return { store, account: { provider: saved.provider, account: saved.account } };
31
+ await store.close();
32
+ }
33
+ }
34
+ if (!locked)
35
+ return withProfile(options, env, options.account());
36
+ const folder = mkdtempSync(join(tmpdir(), `${app.command}-empty-`));
37
+ const removing = () => rmSync(folder, { recursive: true, force: true });
38
+ try {
39
+ const empty = await withProfile(options, { ...env, MESSAGING_STORE: join(folder, "wirecat.db") }, {
40
+ provider: options.provider,
41
+ account: profile,
42
+ });
43
+ const close = empty.store.close.bind(empty.store);
44
+ empty.store.close = () => close().finally(removing);
45
+ return empty;
46
+ }
47
+ catch (error) {
48
+ removing();
49
+ throw error;
50
+ }
51
+ };
52
+ const withProfile = async ({ app, profile, open }, env, account) => {
53
+ const store = await open(env);
54
+ try {
55
+ // An account already stored keeps the scope the owner gave it.
56
+ await store.accounts.saveAccount(account, { name: null, scope: "work" });
57
+ await store.accounts.saveProfile(app.command, profile, account);
58
+ return { store, account };
59
+ }
60
+ catch (error) {
61
+ await store.close();
62
+ throw error;
63
+ }
64
+ };
@@ -30,6 +30,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
30
30
  service: string;
31
31
  /** In place of the manifest's first server. */
32
32
  baseUrl?: string;
33
+ /**
34
+ * What the operations were made from, for the group's help: "its index at /wp-json". Left out, "its OpenAPI
35
+ * document", or "its GraphQL schema" when every operation is GraphQL.
36
+ */
37
+ spec?: string;
33
38
  /**
34
39
  * The values of the server's free variables for this run, such as `{ site }` from the profile's sign-in
35
40
  * (`recalledSite`). Read only when a call is sent, so `api list` and `api show` work before sign-in.
@@ -416,8 +416,8 @@ export const serviceApiCommand = (options) => {
416
416
  renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...(schema ? { request_schema: schema } : {}) }));
417
417
  });
418
418
  const graphql = operations.length > 0 && operations.every((one) => one.binding.kind === "graphql");
419
- const described = graphql ? "GraphQL schema" : "OpenAPI document";
420
- const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its ${described}`);
419
+ const described = options.spec ?? (graphql ? "its GraphQL schema" : "its OpenAPI document");
420
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of ${described}`);
421
421
  group.addCommand(list).addCommand(show);
422
422
  for (const child of [...generated.commands])
423
423
  group.addCommand(child);
@@ -163,7 +163,7 @@ export const tokenSessionCommand = (options) => {
163
163
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
164
164
  });
165
165
  return annotate(new Command("session"), { effects: LOCAL_READ })
166
- .description(`keep this profile's ${service} token in the OS keyring`)
166
+ .description(`keep this profile's ${service} ${word} in the OS keyring`)
167
167
  .addCommand(start)
168
168
  .addCommand(status)
169
169
  .addCommand(end)
@@ -0,0 +1,4 @@
1
+ import { openProfileStore, type ProfileStoreOptions } from "../../cli/profile-store.js";
2
+ export type ContentStoreOptions = ProfileStoreOptions;
3
+ /** The store a content command reads, and the profile's account in it (`openProfileStore`). */
4
+ export declare const openContentStore: typeof openProfileStore;
@@ -0,0 +1,3 @@
1
+ import { openProfileStore } from "../../cli/profile-store.js";
2
+ /** The store a content command reads, and the profile's account in it (`openProfileStore`). */
3
+ export const openContentStore = openProfileStore;
@@ -1,5 +1,6 @@
1
1
  export { CHANNEL_KINDS, type ChannelKind, CONTENT_KINDS, type ContentAuthor, type ContentChannel, type ContentKind, type ContentMedia, type ContentMetric, type ContentPost, type ContentRecords, type ContentTerm, POST_STATUSES, POST_TYPES, type PostStatus, type PostType, TERM_KINDS, type TermKind, } from "../domain/content.js";
2
2
  export { addContentCommands, type ContentCommandOptions, type ContentRun } from "./cli/index.js";
3
+ export { type ContentStoreOptions, openContentStore } from "./cli/store.js";
3
4
  export * from "./manifest/index.js";
4
5
  export type { ContentCallContext, ContentChanges, ContentGap, ContentIdPage, ContentPage, ContentSource, ContentSourceTraits, } from "./source.js";
5
6
  export { GET_UNSUPPORTED } from "./source.js";
@@ -1,5 +1,6 @@
1
1
  export { CHANNEL_KINDS, CONTENT_KINDS, POST_STATUSES, POST_TYPES, TERM_KINDS, } from "../domain/content.js";
2
2
  export { addContentCommands } from "./cli/index.js";
3
+ export { openContentStore } from "./cli/store.js";
3
4
  export * from "./manifest/index.js";
4
5
  export { GET_UNSUPPORTED } from "./source.js";
5
6
  export { contentCursorName, contentGapsOf, syncContent, } from "./sync.js";
@@ -40,7 +40,9 @@ export interface ContentManifestEntity {
40
40
  * The sign-in may be refused this call (a role without the right): a gap with this text, and the rest syncs. A
41
41
  * source that leaves rows out without an error names `requires`: a read whose value at `check` is true when the
42
42
  * sign-in sees every row; false or missing is the same gap. A source that refuses the call outright to a role names
43
- * `needs`: unless its `check` is true the call is never sent, and the gap says its own `message`.
43
+ * `needs`: unless its `check` is true the call is never sent, and the gap says its own `message`. A source that
44
+ * answers a simpler form of a refused call names `fallback`: the same calls with these query values over their own
45
+ * (WordPress: `context=view` for a role that may not edit users), and the gap says its `message`.
44
46
  */
45
47
  optional?: {
46
48
  message: string;
@@ -50,27 +52,49 @@ export interface ContentManifestEntity {
50
52
  message: string;
51
53
  scope?: string;
52
54
  };
55
+ fallback?: ContentFallback;
53
56
  };
54
57
  }
58
+ /** The simpler form of a kind's calls, sent once the first was refused; it reads part of the rows, or fewer fields. */
59
+ export interface ContentFallback {
60
+ query: Readonly<Record<string, string | number | boolean>>;
61
+ message: string;
62
+ scope?: string;
63
+ }
55
64
  /** A read of the sign-in's rights, true at `check` when it has the right (WordPress: `users/me`'s capabilities). */
56
65
  export type ContentRightsCall = CrmOperationCall & {
57
66
  check: string;
58
67
  };
59
- /** A post's writes, as calls and values over the update call. `"{id}"` and `"{at}"` are filled by the engine. */
68
+ /** Where each of our fields goes in a write's body, a dotted path (`title.raw`); `terms` by the term's kind. */
69
+ export interface ContentWriteFields {
70
+ title?: string;
71
+ body?: string;
72
+ excerpt?: string;
73
+ slug?: string;
74
+ terms?: Partial<Record<(typeof TERM_KINDS)[number], string>>;
75
+ }
76
+ /** The calls that write one type of post. */
77
+ export interface ContentTypeWrites {
78
+ create: CrmOperationCall;
79
+ update: CrmOperationCall;
80
+ trash: CrmOperationCall;
81
+ /** Deleting for good, past the trash; absent, the source has no such write. */
82
+ delete?: CrmOperationCall;
83
+ /** Absent, the post's own `fields`. */
84
+ fields?: ContentWriteFields;
85
+ }
86
+ /**
87
+ * A post's writes, as calls and values over the update call. `"{id}"` and `"{at}"` are filled by the engine. A page is
88
+ * written by `page`'s calls, with the same publish, schedule and unpublish values; absent, pages are not written.
89
+ */
60
90
  export interface ContentManifestWrites {
61
91
  create: CrmOperationCall;
62
92
  update: CrmOperationCall;
63
93
  trash: CrmOperationCall;
64
94
  /** Deleting for good, past the trash; absent, the source has no such write. */
65
95
  delete?: CrmOperationCall;
66
- /** Where each of our fields goes in a write's body, a dotted path (`title.raw`); `terms` by the term's kind. */
67
- fields: {
68
- title?: string;
69
- body?: string;
70
- excerpt?: string;
71
- slug?: string;
72
- terms?: Partial<Record<(typeof TERM_KINDS)[number], string>>;
73
- };
96
+ fields: ContentWriteFields;
97
+ page?: ContentTypeWrites;
74
98
  /** Body values over `update` that publish now, schedule at `"{at}"` (ISO in UTC), and bring back to a draft. */
75
99
  publish: Readonly<Record<string, unknown>>;
76
100
  schedule: Readonly<Record<string, unknown>>;
@@ -15,6 +15,13 @@ const call = v.strictObject({
15
15
  items: v.optional(path),
16
16
  });
17
17
  const format = v.picklist(BODY_FORMATS);
18
+ const writeFields = v.strictObject({
19
+ title: v.optional(v.string()),
20
+ body: v.optional(v.string()),
21
+ excerpt: v.optional(v.string()),
22
+ slug: v.optional(v.string()),
23
+ terms: v.optional(v.record(v.picklist(TERM_KINDS), v.optional(v.string()))),
24
+ });
18
25
  const entity = v.strictObject({
19
26
  list: call,
20
27
  changes: v.optional(v.strictObject({
@@ -36,6 +43,11 @@ const entity = v.strictObject({
36
43
  message: v.pipe(v.string(), v.minLength(1)),
37
44
  scope: v.optional(v.string()),
38
45
  })),
46
+ fallback: v.optional(v.strictObject({
47
+ query: v.record(v.string(), v.union([v.string(), v.number(), v.boolean()])),
48
+ message: v.pipe(v.string(), v.minLength(1)),
49
+ scope: v.optional(v.string()),
50
+ })),
39
51
  })),
40
52
  });
41
53
  const schema = v.strictObject({
@@ -49,13 +61,14 @@ const schema = v.strictObject({
49
61
  update: call,
50
62
  trash: call,
51
63
  delete: v.optional(call),
52
- fields: v.strictObject({
53
- title: v.optional(v.string()),
54
- body: v.optional(v.string()),
55
- excerpt: v.optional(v.string()),
56
- slug: v.optional(v.string()),
57
- terms: v.optional(v.record(v.picklist(TERM_KINDS), v.optional(v.string()))),
58
- }),
64
+ fields: writeFields,
65
+ page: v.optional(v.strictObject({
66
+ create: call,
67
+ update: call,
68
+ trash: call,
69
+ delete: v.optional(call),
70
+ fields: v.optional(writeFields),
71
+ })),
59
72
  publish: v.record(v.string(), v.unknown()),
60
73
  schedule: v.record(v.string(), v.unknown()),
61
74
  unpublish: v.record(v.string(), v.unknown()),
@@ -130,14 +143,18 @@ export const parseContentManifest = (input, api) => {
130
143
  if (writes) {
131
144
  if (!manifest.entities.post?.some((one) => one.get))
132
145
  throw invalid("writes", "a write checks the post's version first, and no post entity has a get");
133
- for (const name of ["create", "update", "trash", "delete"]) {
134
- const one = writes[name];
135
- if (!one)
136
- continue;
137
- checkCall(`writes.${name}`, one, false);
138
- if (name !== "create" && !holds([one.path, one.query], "{id}"))
139
- throw invalid(`writes.${name}`, 'no "{id}" in its path or query');
140
- }
146
+ for (const [where, calls] of [
147
+ ["writes", writes],
148
+ ["writes.page", writes.page],
149
+ ])
150
+ for (const name of ["create", "update", "trash", "delete"]) {
151
+ const one = calls?.[name];
152
+ if (!one)
153
+ continue;
154
+ checkCall(`${where}.${name}`, one, false);
155
+ if (name !== "create" && !holds([one.path, one.query], "{id}"))
156
+ throw invalid(`${where}.${name}`, 'no "{id}" in its path or query');
157
+ }
141
158
  if (!holds(writes.schedule, "{at}"))
142
159
  throw invalid("writes.schedule", 'no "{at}" for the time it goes out');
143
160
  }
@@ -65,7 +65,13 @@ const pageOf = (page, now) => {
65
65
  const token = dot < 0 ? undefined : head.slice(dot + 1) || undefined;
66
66
  return Number.isSafeInteger(call) && call >= 0 ? { call, token, started } : { call: -1, token: undefined, started };
67
67
  };
68
+ /**
69
+ * A right the role lacks is a lasting gap only where each row the list leaves out can be read by its id: there a 404
70
+ * proves a row gone. A kind without that read keeps the gap a refusal, which holds its deletions.
71
+ */
72
+ const lastingOf = (entity) => (entity.get ? { lasting: true } : {});
68
73
  const gone = (error) => isCliError(error) && error.code === "not_found";
74
+ const forbidden = (error) => isCliError(error) && (error.code === "permission_error" || error.details.inner_status === 403);
69
75
  // A service may refuse a role with a 400 whose details say 403 (WordPress, for a status the role may not read).
70
76
  const refused = (error) => isCliError(error) &&
71
77
  (error.code === "permission_error" || error.code === "not_found" || error.details.inner_status === 403);
@@ -157,7 +163,12 @@ export const contentSourceFromManifest = (input, options) => {
157
163
  const checkRights = async (kind, entity, send, context) => {
158
164
  const { needs, requires } = entity.optional ?? {};
159
165
  if (needs && !(await has(needs, send))) {
160
- context?.gap({ kind, message: needs.message, ...(needs.scope ? { scope: needs.scope } : {}) });
166
+ context?.gap({
167
+ kind,
168
+ message: needs.message,
169
+ ...(needs.scope ? { scope: needs.scope } : {}),
170
+ ...lastingOf(entity),
171
+ });
161
172
  return false;
162
173
  }
163
174
  if (requires && !(await has(requires, send)))
@@ -165,9 +176,35 @@ export const contentSourceFromManifest = (input, options) => {
165
176
  kind,
166
177
  message: entity.optional?.message ?? "",
167
178
  ...(entity.optional?.scope ? { scope: entity.optional.scope } : {}),
179
+ ...lastingOf(entity),
168
180
  });
169
181
  return true;
170
182
  };
183
+ const simpler = new Set();
184
+ /** The call as this sign-in is answered: in its `fallback` form once the first form was refused. */
185
+ const formOf = (entity, call) => {
186
+ const fallback = entity.optional?.fallback;
187
+ return fallback && simpler.has(entity) ? { ...call, query: { ...call.query, ...fallback.query } } : call;
188
+ };
189
+ /** Sends a read of the entity; refused, once more in its simpler form, which is a gap of its own. */
190
+ const reading = async (kind, entity, read, context) => {
191
+ try {
192
+ return await read();
193
+ }
194
+ catch (error) {
195
+ const fallback = entity.optional?.fallback;
196
+ if (!fallback || simpler.has(entity) || !forbidden(error))
197
+ throw error;
198
+ simpler.add(entity);
199
+ context?.gap({
200
+ kind,
201
+ message: fallback.message,
202
+ ...(fallback.scope ? { scope: fallback.scope } : {}),
203
+ ...lastingOf(entity),
204
+ });
205
+ return read();
206
+ }
207
+ };
171
208
  const gapOf = (kind, entity, error, context) => {
172
209
  if (!entity.optional || !refused(error))
173
210
  return false;
@@ -205,9 +242,9 @@ export const contentSourceFromManifest = (input, options) => {
205
242
  try {
206
243
  read = !(await checkRights(kind, entity, send, context))
207
244
  ? { rows: [], next: undefined }
208
- : changes?.keyset && since !== null
209
- ? await keysetPage({ ...changes, keyset: changes.keyset }, spot.token === undefined ? since - overlap : Number(spot.token), send)
210
- : await readPage(changes ?? entity.list, changes && since !== null ? { since: SINCE[changes.since](since - overlap) } : {}, spot.token, send);
245
+ : await reading(kind, entity, () => changes?.keyset && since !== null
246
+ ? keysetPage(formOf(entity, { ...changes, keyset: changes.keyset }), spot.token === undefined ? since - overlap : Number(spot.token), send)
247
+ : readPage(formOf(entity, changes ?? entity.list), changes && since !== null ? { since: SINCE[changes.since](since - overlap) } : {}, spot.token, send), context);
211
248
  }
212
249
  catch (error) {
213
250
  if (!gapOf(kind, entity, error, context))
@@ -233,7 +270,7 @@ export const contentSourceFromManifest = (input, options) => {
233
270
  const send = metered(context);
234
271
  try {
235
272
  read = (await checkRights(kind, entity, send, context))
236
- ? await readPage(entity.ids ?? entity.list, {}, spot.token, send)
273
+ ? await reading(kind, entity, () => readPage(formOf(entity, entity.ids ?? entity.list), {}, spot.token, send), context)
237
274
  : { rows: [], next: undefined };
238
275
  }
239
276
  catch (error) {
@@ -260,8 +297,9 @@ export const contentSourceFromManifest = (input, options) => {
260
297
  if (!entity.get)
261
298
  continue;
262
299
  let answer;
300
+ const get = entity.get;
263
301
  try {
264
- answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId }));
302
+ answer = await reading(kind, entity, () => send(get.operation, inputOf(formOf(entity, get), { id: externalId })), context);
265
303
  }
266
304
  catch (error) {
267
305
  // A post and a page share one id space; a 404 from one call may be the other's row.
@@ -5,8 +5,14 @@ import { contentConflict } from "../writer.js";
5
5
  import { parseContentManifest } from "./manifest.js";
6
6
  import { mapContentRecord, postBodyOf } from "./map.js";
7
7
  import { fill, inputOf, SITE_CHANNEL } from "./source.js";
8
- // The manifest's writes name the post calls; a page is read, and written in the source's own editor for now.
8
+ // A manifest without `writes.page` reads pages, and they are written in the source's own editor.
9
9
  const pagesUnwritten = () => new CliError("validation_error", "this CLI writes posts, not pages", { reason: "content.write-unsupported" });
10
+ const mapType = (entity) => {
11
+ const rule = entity.map.type;
12
+ return rule && typeof rule === "object" && "value" in rule ? rule.value : "post";
13
+ };
14
+ /** `posts.delete.force` → `delete.force`: the action, whatever route it is on. */
15
+ const actionOf = (key) => key.slice(key.indexOf(".") + 1);
10
16
  const iso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
11
17
  /**
12
18
  * A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
@@ -17,20 +23,36 @@ export const contentWriterFromManifest = (input, options) => {
17
23
  const writes = manifest.writes;
18
24
  if (!writes)
19
25
  throw new CliError("configuration_error", "the source manifest has no writes");
20
- const [entity] = manifest.entities.post ?? [];
21
- if (!entity)
26
+ const entities = manifest.entities.post ?? [];
27
+ const [first] = entities;
28
+ if (!first)
22
29
  throw new CliError("configuration_error", "the source manifest has no post entity");
23
- const html = entity.body !== undefined && entity.body.format !== "markdown";
24
- const postOf = async (answer) => {
30
+ const callsOf = (type) => {
31
+ if (type === undefined || type === "post")
32
+ return writes;
33
+ if (!writes.page)
34
+ throw pagesUnwritten();
35
+ return { ...writes.page, fields: writes.page.fields ?? writes.fields };
36
+ };
37
+ const postOf = async (answer, type) => {
25
38
  const raw = crmValues.isRaw(answer) && crmValues.isRaw(answer.previous) && answer.deleted === true ? null : answer;
26
39
  if (!crmValues.isRaw(raw))
27
40
  return null;
28
- const post = mapContentRecord("post", entity.map, raw);
41
+ // Posts and pages map alike but for their type: the answer is read by the entity of the type written.
42
+ for (const entity of entities) {
43
+ const post = mapContentRecord("post", entity.map, raw);
44
+ if (post && (post.type ?? "post") === type)
45
+ return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(entity, raw));
46
+ }
47
+ const post = mapContentRecord("post", first.map, raw);
29
48
  if (!post)
30
49
  throw new CliError("invalid_response", `${manifest.provider} answered a write with no post`);
31
- return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(entity, raw));
50
+ return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(first, raw));
32
51
  };
33
- const bodyOf = async (fields) => {
52
+ const bodyOf = async (fields, type) => {
53
+ const to = callsOf(type).fields;
54
+ const entity = entities.find((one) => mapType(one) === type) ?? first;
55
+ const html = entity.body !== undefined && entity.body.format !== "markdown";
34
56
  const out = {};
35
57
  const put = (path, value) => {
36
58
  const keys = path.split(".");
@@ -43,7 +65,6 @@ export const contentWriterFromManifest = (input, options) => {
43
65
  }
44
66
  inner[last] = value;
45
67
  };
46
- const to = writes.fields;
47
68
  if (fields.title !== undefined && to.title)
48
69
  put(to.title, fields.title ?? "");
49
70
  if (fields.excerpt !== undefined && to.excerpt)
@@ -52,6 +73,10 @@ export const contentWriterFromManifest = (input, options) => {
52
73
  put(to.slug, fields.slug ?? "");
53
74
  if (fields.body !== undefined && to.body)
54
75
  put(to.body, html ? await markdownToHtml(fields.body) : fields.body);
76
+ if (fields.terms?.length && !to.terms)
77
+ throw new CliError("validation_error", `${manifest.provider} takes no tags or categories on a ${type}`, {
78
+ reason: "content.write-unsupported",
79
+ });
55
80
  if (fields.terms !== undefined && to.terms) {
56
81
  const kinds = new Map();
57
82
  for (const term of fields.terms) {
@@ -74,20 +99,25 @@ export const contentWriterFromManifest = (input, options) => {
74
99
  throw new CliError("not_found", `${manifest.provider} has no post ${externalId}; sync, then try again`);
75
100
  if (version != null && found.version != null && found.version !== version)
76
101
  throw contentConflict();
77
- if (found.type === "page")
78
- throw pagesUnwritten();
79
- return found;
102
+ const type = found.type ?? "post";
103
+ return { found, type, calls: callsOf(type) };
80
104
  };
81
105
  const send = async (call, slots, confirmed, body) => {
82
106
  const base = call.body === undefined ? {} : fill(call.body, slots);
83
107
  // 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}`])]);
108
+ // command did not ask about, as the publish key for a post that is published at the source now, still is. A page's
109
+ // call checks its own route's keys (`pages.publish`): the one for the action the owner said yes to goes with it.
110
+ const operation = options.api.operations.find((one) => one.id === call.operation);
111
+ const route = (operation?.permissions ?? [])
112
+ .map((one) => one.key)
113
+ .filter((key) => confirmed?.some((yes) => actionOf(yes) === actionOf(key)) && !confirmed.includes(key));
114
+ const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }), !confirmed?.length
115
+ ? []
116
+ : [...confirmed, ...route, ...(operation?.command === undefined ? [] : [`api.${operation.command}`])]);
87
117
  return result;
88
118
  };
89
- const updated = async (externalId, body, confirmed) => {
90
- const post = await postOf(await send(writes.update, { id: externalId }, confirmed, body));
119
+ const updated = async ({ type, calls }, externalId, body, confirmed) => {
120
+ const post = await postOf(await send(calls.update, { id: externalId }, confirmed, body), type);
91
121
  if (!post)
92
122
  throw new CliError("invalid_response", `${manifest.provider} answered an update with no post`);
93
123
  return post;
@@ -95,42 +125,42 @@ export const contentWriterFromManifest = (input, options) => {
95
125
  return {
96
126
  provider: manifest.provider,
97
127
  async createDraft(draft, options_) {
98
- if (draft.type === "page")
99
- throw pagesUnwritten();
100
- const post = await postOf(await send(writes.create, {}, options_.confirmed, await bodyOf(draft)));
128
+ const type = draft.type ?? "post";
129
+ const calls = callsOf(type);
130
+ const post = await postOf(await send(calls.create, {}, options_.confirmed, await bodyOf(draft, type)), type);
101
131
  if (!post)
102
132
  throw new CliError("invalid_response", `${manifest.provider} answered a create with no post`);
103
133
  return post;
104
134
  },
105
135
  async update(externalId, patch, options_) {
106
- await current(externalId, options_);
107
- return updated(externalId, await bodyOf(patch), options_.confirmed);
136
+ const now = await current(externalId, options_);
137
+ return updated(now, externalId, await bodyOf(patch, now.type), options_.confirmed);
108
138
  },
109
139
  async publish(externalId, options_) {
110
- const found = await current(externalId, options_);
111
- if (found.status === "published")
112
- return found;
113
- return updated(externalId, { ...writes.publish }, options_.confirmed);
140
+ const now = await current(externalId, options_);
141
+ if (now.found.status === "published")
142
+ return now.found;
143
+ return updated(now, externalId, { ...writes.publish }, options_.confirmed);
114
144
  },
115
145
  async schedule(externalId, when, options_) {
116
- await current(externalId, options_);
117
- return updated(externalId, fill(writes.schedule, { at: iso(when) }), options_.confirmed);
146
+ const now = await current(externalId, options_);
147
+ return updated(now, externalId, fill(writes.schedule, { at: iso(when) }), options_.confirmed);
118
148
  },
119
149
  async unpublish(externalId, options_) {
120
- await current(externalId, options_);
121
- return updated(externalId, { ...writes.unpublish }, options_.confirmed);
150
+ const now = await current(externalId, options_);
151
+ return updated(now, externalId, { ...writes.unpublish }, options_.confirmed);
122
152
  },
123
153
  async trash(externalId, options_) {
124
- await current(externalId, options_);
154
+ const { type, calls } = await current(externalId, options_);
125
155
  if (options_.force) {
126
- if (!writes.delete)
156
+ if (!calls.delete)
127
157
  throw new CliError("validation_error", `${manifest.provider} takes no deletion past the trash`, {
128
158
  reason: "content.write-unsupported",
129
159
  });
130
- await send(writes.delete, { id: externalId }, options_.confirmed);
160
+ await send(calls.delete, { id: externalId }, options_.confirmed);
131
161
  return null;
132
162
  }
133
- return postOf(await send(writes.trash, { id: externalId }, options_.confirmed));
163
+ return postOf(await send(calls.trash, { id: externalId }, options_.confirmed), type);
134
164
  },
135
165
  };
136
166
  };
@@ -26,6 +26,11 @@ export interface ContentGap {
26
26
  kind: ContentKind;
27
27
  message: string;
28
28
  scope?: string;
29
+ /**
30
+ * A right the sign-in's role lacks, the same each run: what it reads is whole for what it may see. The cursor moves
31
+ * on, and a row a complete id list lacks is read once more by its id, so only a source's "gone" deletes it.
32
+ */
33
+ lasting?: true;
29
34
  }
30
35
  export interface ContentCallContext {
31
36
  /** Takes one request from the run's budget for each request beyond the first; throws once it is spent. */
@@ -10,6 +10,10 @@ const GUARDED_FROM = 10;
10
10
  const MOST_DUE = 50;
11
11
  /** The sign-in may not read it, which proves nothing about the row; WordPress also refuses with 400 and 403 inside. */
12
12
  const refusedRead = (error) => isCliError(error) && (error.code === "permission_error" || error.details.inner_status === 403);
13
+ const lackOf = (gap) => gap.scope ?? gap.message;
14
+ /** A refusal of this kind in this run, which proves nothing about the rows it left out; a right the role lacks does. */
15
+ const refusedIn = (run, kind) => run.report.gaps.some((gap) => gap.kind === kind && !gap.lasting);
16
+ const lackedIn = (run, kind) => run.report.gaps.flatMap((gap) => (gap.kind === kind && gap.lasting ? [lackOf(gap)] : []));
13
17
  const fresh = () => ({ v: 1, token: null, round: null, passAt: 0 });
14
18
  const parsed = (value) => {
15
19
  try {
@@ -39,7 +43,13 @@ const syncChanges = async (run, kind, result, mode) => {
39
43
  let round = mode.drop
40
44
  ? { from: null, page: null }
41
45
  : (cursor.round ?? { from: mode.full ? null : cursor.token, page: null });
42
- const gapped = () => run.report.gaps.some((gap) => gap.kind === kind);
46
+ const noted = () => {
47
+ if (refusedIn(run, kind))
48
+ round = { ...round, gapped: true };
49
+ const lacks = [...new Set([...(round.lacks ?? []), ...lackedIn(run, kind)])].sort();
50
+ if (lacks.length)
51
+ round = { ...round, lacks };
52
+ };
43
53
  const save = (patch) => {
44
54
  cursor = { ...cursor, ...patch };
45
55
  return store.sync.setSyncState(account, name, JSON.stringify(cursor));
@@ -54,8 +64,7 @@ const syncChanges = async (run, kind, result, mode) => {
54
64
  }
55
65
  run.report.progress.requests += 1;
56
66
  const page = await source.changes(kind, round.from, round.page ?? undefined, run.context);
57
- if (gapped())
58
- round = { ...round, gapped: true };
67
+ noted();
59
68
  if (run.signal?.aborted) {
60
69
  await save({ round });
61
70
  return "cancelled";
@@ -74,8 +83,20 @@ const syncChanges = async (run, kind, result, mode) => {
74
83
  }
75
84
  run.report.progress.steps += 1;
76
85
  if (!page.hasMore) {
86
+ const lacks = round.lacks ?? [];
87
+ // A right gained shows rows changed before the cursor, which a read of changes never reaches: list them all.
88
+ if (round.from !== null && (cursor.lacks ?? []).some((one) => !lacks.includes(one))) {
89
+ result.reset = true;
90
+ round = { from: null, page: null };
91
+ pages.clear();
92
+ continue;
93
+ }
77
94
  // Changes made while a read was refused would be past a new cursor: the next run reads from the old one again.
78
- await save({ token: round.gapped ? round.from : (page.cursor ?? null), round: null });
95
+ await save({
96
+ token: round.gapped ? round.from : (page.cursor ?? null),
97
+ round: null,
98
+ lacks: lacks.length ? lacks : undefined,
99
+ });
79
100
  return null;
80
101
  }
81
102
  if (page.nextCursor === undefined)
@@ -112,7 +133,7 @@ const passIds = async (run, kind, result, mode) => {
112
133
  return "cancelled";
113
134
  }
114
135
  pass = { ...pass, ids: [...pass.ids, ...page.items] };
115
- if (run.report.gaps.some((gap) => gap.kind === kind))
136
+ if (refusedIn(run, kind))
116
137
  pass = { ...pass, gapped: true };
117
138
  if (page.hasMore) {
118
139
  if (page.nextCursor === undefined || page.nextCursor === pass.page)
@@ -124,7 +145,8 @@ const passIds = async (run, kind, result, mode) => {
124
145
  const stored = await store.content.count(account, kind);
125
146
  const missing = await store.content.unlisted(account, kind, pass.ids, pass.started);
126
147
  const unlisted = missing.length;
127
- const unread = pass.gapped === true || run.report.gaps.some((gap) => gap.kind === kind);
148
+ // A role that sees only part lists less, the same each run: each row its list lacks is read once more below.
149
+ const unread = pass.gapped === true || refusedIn(run, kind);
128
150
  const moved = (run.report.moved?.length ?? 0) > 0;
129
151
  const emptied = pass.ids.length === 0 && unlisted > 0;
130
152
  const many = emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED);
@@ -309,7 +331,8 @@ export const syncContent = async (source, store, account, options = {}) => {
309
331
  report.progress.requests += 1;
310
332
  },
311
333
  gap: (gap) => {
312
- const key = `${gap.kind} ${gap.message}`;
334
+ // A refusal with the same words as a right the role lacks still holds the cursor and the pass.
335
+ const key = `${gap.kind} ${gap.message}${gap.lasting ? " lasting" : ""}`;
313
336
  if (said.has(key))
314
337
  return;
315
338
  said.add(key);
@@ -340,7 +363,7 @@ export const syncContent = async (source, store, account, options = {}) => {
340
363
  if (resumed)
341
364
  for (const gap of await contentGapsOf(store, account))
342
365
  if (done.has(gap.kind)) {
343
- said.add(`${gap.kind} ${gap.message}`);
366
+ said.add(`${gap.kind} ${gap.message}${gap.lasting ? " lasting" : ""}`);
344
367
  report.gaps.push(gap);
345
368
  }
346
369
  for (const kind of kinds.filter((one) => !done.has(one))) {
@@ -19,8 +19,13 @@ export interface ContentManifestFakeOptions {
19
19
  * `refusals`.
20
20
  */
21
21
  lacks?: readonly string[];
22
- /** Operations refused with 403 to this sign-in, as WordPress refuses an author the users list. */
22
+ /**
23
+ * Operations refused with 403 to this sign-in, as WordPress refuses an author the users list with `context=edit`. A
24
+ * kind's `optional.fallback` form of the same call is answered.
25
+ */
23
26
  denied?: readonly string[];
27
+ /** Rows this sign-in may not see, by kind: left out of every list, and a read of one refused with 403. */
28
+ hidden?: Partial<Record<ContentKind, readonly string[]>>;
24
29
  }
25
30
  export interface ContentManifestFake {
26
31
  /** Reads as `serviceApiCall` sends them, with the answer's headers through `withHeaders`. */
@@ -164,13 +164,27 @@ export const contentManifestFake = (input, options) => {
164
164
  if (path)
165
165
  put(row, path, stamp(clock()));
166
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, entity.optional?.needs].flatMap((call) => call ? [{ kind, index, role: "rights", call }] : []),
173
- ]));
167
+ const routes = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity, index) => {
168
+ const own = [
169
+ ...(entity.changes ? [{ kind, index, role: "changes", call: entity.changes }] : []),
170
+ ...(entity.get ? [{ kind, index, role: "get", call: entity.get }] : []),
171
+ { kind, index, role: "list", call: entity.list },
172
+ ...(entity.ids ? [{ kind, index, role: "list", call: entity.ids }] : []),
173
+ ];
174
+ const fallback = entity.optional?.fallback;
175
+ return [
176
+ ...own,
177
+ ...(fallback
178
+ ? own.map((route) => ({
179
+ ...route,
180
+ call: { ...route.call, query: { ...route.call.query, ...fallback.query } },
181
+ simpler: true,
182
+ }))
183
+ : []),
184
+ ...[entity.optional?.requires, entity.optional?.needs].flatMap((call) => call ? [{ kind, index, role: "rights", call }] : []),
185
+ ];
186
+ }));
187
+ const hidden = (kind, id) => options.hidden?.[kind]?.includes(id) === true;
174
188
  const lacks = new Set(options.lacks ?? []);
175
189
  const checks = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity) => [entity.optional?.requires, entity.optional?.needs].flatMap((call) => (call ? [call] : []))));
176
190
  const carries = (route, request) => {
@@ -241,7 +255,7 @@ export const contentManifestFake = (input, options) => {
241
255
  refusals.push(operation);
242
256
  throw new CliError("configuration_error", `the content fake answers no ${operation} call like this`);
243
257
  }
244
- if (options.denied?.includes(operation))
258
+ if (options.denied?.includes(operation) && !route.simpler)
245
259
  throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
246
260
  const entity = entities(route.kind)[route.index];
247
261
  const held = rows[route.kind]?.[route.index] ?? [];
@@ -254,24 +268,31 @@ export const contentManifestFake = (input, options) => {
254
268
  return { body, headers: new Headers() };
255
269
  }
256
270
  const needs = entity.optional?.needs;
257
- if (needs && lacks.has(needs.check)) {
258
- refusals.push(operation);
259
- if (route.role === "get")
260
- throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
261
- throw new CliError("validation_error", `the content fake refuses ${operation} to this sign-in`, {
262
- status: 400,
263
- inner_status: 403,
264
- });
265
- }
271
+ const lacked = needs !== undefined && lacks.has(needs.check);
266
272
  if (route.role === "get") {
267
273
  const place = placeOf(route.call, "{id}");
268
274
  const id = place ? request[place.in][place.name] : undefined;
269
275
  const row = held.find((one) => idOf(entity, one) === String(id));
276
+ // A missing row is a 404 whoever asks; only a row that is there is refused to a role.
270
277
  if (!row)
271
278
  throw new CliError("not_found", `no ${route.kind} ${id}`);
279
+ if (lacked || hidden(route.kind, String(id))) {
280
+ if (lacked)
281
+ refusals.push(operation);
282
+ throw new CliError("permission_error", `the content fake denies ${operation} to this sign-in`);
283
+ }
272
284
  return { body: wrapped(route.call.items, structuredClone(row)), headers: new Headers() };
273
285
  }
274
- let list = [...held].sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
286
+ if (lacked) {
287
+ refusals.push(operation);
288
+ throw new CliError("validation_error", `the content fake refuses ${operation} to this sign-in`, {
289
+ status: 400,
290
+ inner_status: 403,
291
+ });
292
+ }
293
+ let list = [...held]
294
+ .filter((row) => !hidden(route.kind, idOf(entity, row)))
295
+ .sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
275
296
  if (route.role === "changes" && entity.changes) {
276
297
  const place = placeOf(entity.changes, "{since}");
277
298
  const raw = String(request[place.in][place.name]);
@@ -279,17 +300,24 @@ export const contentManifestFake = (input, options) => {
279
300
  if (Number.isNaN(since))
280
301
  throw new CliError("validation_error", `${raw} is not a time`);
281
302
  list = held
282
- .filter((row) => changedOf(entity, row) > since)
303
+ .filter((row) => changedOf(entity, row) > since && !hidden(route.kind, idOf(entity, row)))
283
304
  .sort((a, b) => changedOf(entity, a) - changedOf(entity, b));
284
305
  }
285
306
  return page(found, route.call, structuredClone(list), request);
286
307
  };
287
308
  const write = (operation, request) => {
288
- const ours = manifest.writes;
289
- const [entity] = entities("post");
290
- const held = rows.post?.[0];
291
- if (!ours || !entity || !held)
309
+ const writes_ = manifest.writes;
310
+ if (!writes_)
292
311
  throw new CliError("configuration_error", "the source manifest writes no posts");
312
+ const touches = (calls) => calls !== undefined &&
313
+ [calls.create, calls.update, calls.trash, calls.delete].some((call) => call?.operation === operation);
314
+ const type = touches(writes_.page) && !touches(writes_) ? "page" : "post";
315
+ const ours = type === "page" && writes_.page ? writes_.page : writes_;
316
+ const index = entityIndex("post", { type });
317
+ const entity = entities("post")[index];
318
+ const held = rows.post?.[index];
319
+ if (!entity || !held)
320
+ throw new CliError("configuration_error", `the source manifest reads no ${type}s`);
293
321
  const matches = (call) => call?.operation === operation &&
294
322
  fixedOf(call.query ?? {}).every(([key, value]) => String(request.query[key]) === value);
295
323
  const body = request.body ? JSON.parse(request.body) : {};
@@ -100,7 +100,8 @@ export const publishPost = async (context, externalId) => {
100
100
  export const schedulePost = async (context, externalId, at) => {
101
101
  const now = context.now?.() ?? Date.now();
102
102
  if (!Number.isFinite(at) || at <= now)
103
- throw new CliError("validation_error", "--at is in the past, and the source would publish the post at once; give a later time, or use posts publish", { reason: "content.schedule-past", param: "--at" });
103
+ throw new CliError("validation_error", "--at-time is in the past, and the source would publish the post at once; give a later time, or leave " +
104
+ "--at-time out to publish now", { reason: "content.schedule-past", param: "--at-time" });
104
105
  const copy = await copyOf(context, externalId);
105
106
  if (copy.record.status === "published")
106
107
  throw new CliError("validation_error", `post ${externalId} is already published`, {
@@ -1,30 +1,4 @@
1
- import { type AppIdentity } from "../../ports/app.js";
2
- import type { MessageStore } from "../../store/store.js";
3
- import type { AccountKey } from "../../store/types.js";
4
- export interface CrmStoreOptions {
5
- app: AppIdentity;
6
- env: NodeJS.ProcessEnv;
7
- profile: string;
8
- /** The command only reads the store: `CrmCommandOptions.open`'s `readOnly`. */
9
- readOnly: boolean;
10
- /** The CRM's provider, as the store names it: the empty store's account under the read-only lock. */
11
- provider: string;
12
- /** Opens the shared store as the CLI does; a writable open also registers its provider. */
13
- open: (env: NodeJS.ProcessEnv, options?: {
14
- readOnly?: boolean;
15
- }) => Promise<MessageStore>;
16
- /** The profile's account from its sign-in; asked only when no earlier run saved it. */
17
- account: () => AccountKey;
18
- }
19
- /**
20
- * The store a CRM command reads, and the profile's account in it. A read takes the account an earlier run saved, so it
21
- * never reads the sign-in; the first read of a profile, a store that is missing or needs a migration, and every sync
22
- * and write open it for writing and save the account (scope work: a CRM is the owner's work) and the profile.
23
- *
24
- * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
25
- * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
26
- */
27
- export declare const openCrmStore: (options: CrmStoreOptions) => Promise<{
28
- store: MessageStore;
29
- account: AccountKey;
30
- }>;
1
+ import { openProfileStore, type ProfileStoreOptions } from "../../cli/profile-store.js";
2
+ export type CrmStoreOptions = ProfileStoreOptions;
3
+ /** The store a CRM command reads, and the profile's account in it (`openProfileStore`): a CRM is the owner's work. */
4
+ export declare const openCrmStore: typeof openProfileStore;
@@ -1,63 +1,3 @@
1
- import { mkdtempSync, rmSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { isCliError } from "@wirecat/cli-base";
5
- import { readOnlyLockOf } from "../../ports/app.js";
6
- /**
7
- * The store a CRM command reads, and the profile's account in it. A read takes the account an earlier run saved, so it
8
- * never reads the sign-in; the first read of a profile, a store that is missing or needs a migration, and every sync
9
- * and write open it for writing and save the account (scope work: a CRM is the owner's work) and the profile.
10
- *
11
- * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
12
- * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
13
- */
14
- export const openCrmStore = async (options) => {
15
- const { app, env, profile, readOnly, open } = options;
16
- const locked = readOnly && readOnlyLockOf(app, env) !== undefined;
17
- if (readOnly) {
18
- const store = await open(env, { readOnly: true }).catch((error) => {
19
- if (locked && !(isCliError(error) && error.code === "not_found"))
20
- throw error;
21
- return undefined;
22
- });
23
- if (store) {
24
- const saved = await store.accounts
25
- .profiles()
26
- .then((all) => all[app.command]?.[profile])
27
- .catch(() => undefined);
28
- if (saved)
29
- return { store, account: { provider: saved.provider, account: saved.account } };
30
- await store.close();
31
- }
32
- }
33
- if (!locked)
34
- return withProfile(options, env, options.account());
35
- const folder = mkdtempSync(join(tmpdir(), `${app.command}-empty-`));
36
- const removing = () => rmSync(folder, { recursive: true, force: true });
37
- try {
38
- const empty = await withProfile(options, { ...env, MESSAGING_STORE: join(folder, "wirecat.db") }, {
39
- provider: options.provider,
40
- account: profile,
41
- });
42
- const close = empty.store.close.bind(empty.store);
43
- empty.store.close = () => close().finally(removing);
44
- return empty;
45
- }
46
- catch (error) {
47
- removing();
48
- throw error;
49
- }
50
- };
51
- const withProfile = async ({ app, profile, open }, env, account) => {
52
- const store = await open(env);
53
- try {
54
- // An account already stored keeps the scope the owner gave it.
55
- await store.accounts.saveAccount(account, { name: null, scope: "work" });
56
- await store.accounts.saveProfile(app.command, profile, account);
57
- return { store, account };
58
- }
59
- catch (error) {
60
- await store.close();
61
- throw error;
62
- }
63
- };
1
+ import { openProfileStore } from "../../cli/profile-store.js";
2
+ /** The store a CRM command reads, and the profile's account in it (`openProfileStore`): a CRM is the owner's work. */
3
+ export const openCrmStore = openProfileStore;
@@ -68,7 +68,8 @@ const makeSafe = (tree) => {
68
68
  export const htmlToMarkdown = async (html) => {
69
69
  const { fromHtml, toMdast, toMarkdown, gfmToMarkdown } = await loaded();
70
70
  const tree = makeSafe(toMdast(fromHtml(html, { fragment: true })));
71
- return toMarkdown(tree, { extensions: [gfmToMarkdown()] });
71
+ // `-` as most Markdown is written: a body read back then compares equal to the file it was written from.
72
+ return toMarkdown(tree, { bullet: "-", extensions: [gfmToMarkdown()] });
72
73
  };
73
74
  /**
74
75
  * Markdown (CommonMark + GFM) as HTML for a service that stores HTML, such as WordPress or Ghost. Raw HTML in the
@@ -57,7 +57,6 @@ const SIGN_IN = [
57
57
  "configuration_error",
58
58
  "the tool named a folder of its own outside the home folder",
59
59
  ],
60
- ["account-rename.unknown-profile", "not_found", "no profile by this name on this computer"],
61
60
  ["account-rename.taken", "conflict", "the new name, or a file or keyring entry under it, already exists"],
62
61
  ["account-rename.busy", "conflict", "a serve, a background service, a schedule or a sync uses this profile"],
63
62
  ["account-rename.bot", "conflict", "the profile is also a bot profile, which keeps its name"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.715.0",
3
+ "version": "0.717.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",