@wirecat/cli-core 0.704.0 → 0.706.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/dist/cli/bot/api-http.d.ts +8 -2
  3. package/dist/cli/bot/api-http.js +20 -4
  4. package/dist/cli/bot/api.d.ts +8 -0
  5. package/dist/cli/bot/api.js +31 -3
  6. package/dist/cli/documents/words.d.ts +1 -1
  7. package/dist/cli/index.d.ts +4 -4
  8. package/dist/cli/index.js +3 -3
  9. package/dist/cli/messenger/lacks.js +3 -0
  10. package/dist/cli/messenger/messages-delete-command.js +30 -25
  11. package/dist/cli/messenger/messages-edit-command.js +2 -0
  12. package/dist/cli/messenger/messages-scheduled-command.js +110 -4
  13. package/dist/cli/messenger/store-maintenance-command.js +6 -2
  14. package/dist/cli/service-api-call.d.ts +13 -3
  15. package/dist/cli/service-api-call.js +19 -9
  16. package/dist/cli/service-api-manifest.d.ts +11 -2
  17. package/dist/cli/service-api-manifest.js +30 -9
  18. package/dist/cli/service-api.d.ts +14 -6
  19. package/dist/cli/service-api.js +198 -52
  20. package/dist/cli/token-session.d.ts +5 -2
  21. package/dist/cli/token-session.js +13 -4
  22. package/dist/content/cli/index.d.ts +33 -0
  23. package/dist/content/cli/index.js +368 -0
  24. package/dist/content/index.d.ts +8 -0
  25. package/dist/content/index.js +7 -0
  26. package/dist/content/manifest/index.d.ts +4 -0
  27. package/dist/content/manifest/index.js +4 -0
  28. package/dist/content/manifest/manifest.d.ts +92 -0
  29. package/dist/content/manifest/manifest.js +137 -0
  30. package/dist/content/manifest/map.d.ts +25 -0
  31. package/dist/content/manifest/map.js +94 -0
  32. package/dist/content/manifest/source.d.ts +41 -0
  33. package/dist/content/manifest/source.js +288 -0
  34. package/dist/content/manifest/writer.d.ts +26 -0
  35. package/dist/content/manifest/writer.js +133 -0
  36. package/dist/content/source.d.ts +64 -0
  37. package/dist/content/source.js +2 -0
  38. package/dist/content/sync.d.ts +61 -0
  39. package/dist/content/sync.js +387 -0
  40. package/dist/content/testing/index.d.ts +4 -0
  41. package/dist/content/testing/index.js +4 -0
  42. package/dist/content/testing/source-contract.d.ts +38 -0
  43. package/dist/content/testing/source-contract.js +274 -0
  44. package/dist/content/testing/source.d.ts +55 -0
  45. package/dist/content/testing/source.js +276 -0
  46. package/dist/content/testing/sync-contract.d.ts +10 -0
  47. package/dist/content/testing/sync-contract.js +172 -0
  48. package/dist/content/testing/write-contract.d.ts +14 -0
  49. package/dist/content/testing/write-contract.js +102 -0
  50. package/dist/content/writer.d.ts +64 -0
  51. package/dist/content/writer.js +38 -0
  52. package/dist/content/writes.d.ts +58 -0
  53. package/dist/content/writes.js +129 -0
  54. package/dist/documents/file-mirror-model.d.ts +3 -1
  55. package/dist/documents/index.d.ts +3 -3
  56. package/dist/documents/index.js +1 -1
  57. package/dist/domain/content.d.ts +102 -0
  58. package/dist/domain/content.js +11 -0
  59. package/dist/entities/index.d.ts +8 -2
  60. package/dist/entities/index.js +4 -2
  61. package/dist/entities/message-change.d.ts +240 -0
  62. package/dist/entities/message-change.js +6 -0
  63. package/dist/errors/reasons.js +14 -0
  64. package/dist/kit/fake.d.ts +2 -2
  65. package/dist/kit/fake.js +21 -0
  66. package/dist/manifest/index.d.ts +21 -7
  67. package/dist/manifest/index.js +7 -4
  68. package/dist/mcp/surface.js +6 -3
  69. package/dist/ports/messenger.d.ts +20 -1
  70. package/dist/sends/permissions.js +11 -1
  71. package/dist/services/documents/mirrors.d.ts +13 -1
  72. package/dist/services/documents/mirrors.js +12 -3
  73. package/dist/services/files/mirror.d.ts +20 -8
  74. package/dist/services/files/mirror.js +84 -27
  75. package/dist/services/files/versions.d.ts +17 -7
  76. package/dist/services/files/versions.js +56 -21
  77. package/dist/services/messages.d.ts +31 -0
  78. package/dist/services/messages.js +62 -0
  79. package/dist/store/exports.d.ts +1 -0
  80. package/dist/store/exports.js +1 -0
  81. package/dist/store/recover.js +2 -0
  82. package/dist/store/sqlite/account-purge.js +7 -0
  83. package/dist/store/sqlite/content.d.ts +100 -0
  84. package/dist/store/sqlite/content.js +375 -0
  85. package/dist/store/sqlite/entity-types.d.ts +1 -0
  86. package/dist/store/sqlite/entity-types.js +1 -0
  87. package/dist/store/sqlite/manifest.js +2 -0
  88. package/dist/store/sqlite/migrations.generated.js +26 -0
  89. package/dist/store/sqlite/schema.d.ts +1140 -0
  90. package/dist/store/sqlite/schema.js +100 -0
  91. package/dist/store/store.d.ts +3 -0
  92. package/dist/store/store.js +5 -0
  93. package/package.json +12 -4
@@ -0,0 +1,137 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import * as v from "valibot";
3
+ import { crmRuleSchema } from "../../crm/manifest/manifest.js";
4
+ import { CHANNEL_KINDS, CONTENT_KINDS, TERM_KINDS } from "../../domain/content.js";
5
+ import { editDistance } from "../../search/correct.js";
6
+ import { CONTENT_FIELDS } from "./map.js";
7
+ /** How the source keeps a post's text, which the engine turns into Markdown and back. */
8
+ export const BODY_FORMATS = ["markdown", "html", "wp-blocks"];
9
+ const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as title.raw"));
10
+ const call = v.strictObject({
11
+ operation: v.pipe(v.string(), v.minLength(1)),
12
+ path: v.optional(v.record(v.string(), v.string())),
13
+ query: v.optional(v.record(v.string(), v.union([v.string(), v.number(), v.boolean()]))),
14
+ body: v.optional(v.unknown()),
15
+ items: v.optional(path),
16
+ });
17
+ const format = v.picklist(BODY_FORMATS);
18
+ const entity = v.strictObject({
19
+ list: call,
20
+ changes: v.optional(v.strictObject({
21
+ ...call.entries,
22
+ since: v.picklist(["iso", "seconds", "ms"]),
23
+ keyset: v.optional(v.strictObject({ field: path, step: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))) })),
24
+ })),
25
+ ids: v.optional(call),
26
+ get: v.optional(call),
27
+ map: v.record(v.string(), crmRuleSchema),
28
+ body: v.optional(v.strictObject({ path, format, fallback: v.optional(v.strictObject({ path, format })) })),
29
+ optional: v.optional(v.strictObject({
30
+ message: v.pipe(v.string(), v.minLength(1)),
31
+ scope: v.optional(v.string()),
32
+ requires: v.optional(v.strictObject({ ...call.entries, check: path })),
33
+ })),
34
+ });
35
+ const schema = v.strictObject({
36
+ provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as wordpress")),
37
+ kinds: v.pipe(v.array(v.picklist(CONTENT_KINDS)), v.minLength(1)),
38
+ overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
39
+ channel: v.strictObject({ kind: v.picklist(CHANNEL_KINDS), network: v.pipe(v.string(), v.minLength(1)) }),
40
+ entities: v.record(v.picklist(CONTENT_KINDS), v.optional(v.pipe(v.array(entity), v.minLength(1)))),
41
+ writes: v.optional(v.strictObject({
42
+ create: call,
43
+ update: call,
44
+ trash: call,
45
+ delete: v.optional(call),
46
+ fields: v.strictObject({
47
+ title: v.optional(v.string()),
48
+ body: v.optional(v.string()),
49
+ excerpt: v.optional(v.string()),
50
+ slug: v.optional(v.string()),
51
+ terms: v.optional(v.record(v.picklist(TERM_KINDS), v.optional(v.string()))),
52
+ }),
53
+ publish: v.record(v.string(), v.unknown()),
54
+ schedule: v.record(v.string(), v.unknown()),
55
+ unpublish: v.record(v.string(), v.unknown()),
56
+ })),
57
+ });
58
+ const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
59
+ const nearest = (wanted, known) => known
60
+ .map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
61
+ .filter(({ edits }) => edits <= 2)
62
+ .sort((a, b) => a.edits - b.edits)[0]?.one;
63
+ const holds = (value, placeholder) => value === placeholder ||
64
+ (Array.isArray(value) && value.some((one) => holds(one, placeholder))) ||
65
+ (typeof value === "object" && value !== null && Object.values(value).some((one) => holds(one, placeholder)));
66
+ /**
67
+ * The manifest checked against its shape and the generated API: each operation exists and reads or writes as its
68
+ * place says, a change call places `{since}`, a get `{id}`, each map names only our fields. Every error names where.
69
+ */
70
+ export const parseContentManifest = (input, api) => {
71
+ const parsed = v.safeParse(schema, input);
72
+ if (!parsed.success) {
73
+ const [issue] = parsed.issues;
74
+ throw invalid(v.getDotPath(issue) ?? "(root)", issue.message);
75
+ }
76
+ const manifest = parsed.output;
77
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
78
+ const known = [...operations.keys()];
79
+ const checkCall = (where, one, reads) => {
80
+ const operation = operations.get(one.operation);
81
+ if (!operation) {
82
+ const near = nearest(one.operation, known);
83
+ throw invalid(`${where}.operation`, `no operation ${one.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
84
+ }
85
+ if (reads !== (operation.effect === "read"))
86
+ throw invalid(`${where}.operation`, `${one.operation} is a ${operation.effect}, and this place ${reads ? "reads" : "writes"}`);
87
+ };
88
+ for (const kind of manifest.kinds) {
89
+ const calls = manifest.entities[kind];
90
+ if (!calls)
91
+ throw invalid(`entities.${kind}`, `${kind} is in kinds but has no entity`);
92
+ calls.forEach((one, at) => {
93
+ const where = `entities.${kind}.${at}`;
94
+ checkCall(`${where}.list`, one.list, true);
95
+ if (one.changes) {
96
+ checkCall(`${where}.changes`, one.changes, true);
97
+ if (!holds([one.changes.path, one.changes.query, one.changes.body], "{since}"))
98
+ throw invalid(`${where}.changes`, 'no "{since}" in its path, query or body');
99
+ }
100
+ if (one.ids)
101
+ checkCall(`${where}.ids`, one.ids, true);
102
+ if (one.optional?.requires)
103
+ checkCall(`${where}.optional.requires`, one.optional.requires, true);
104
+ if (one.get) {
105
+ checkCall(`${where}.get`, one.get, true);
106
+ if (!holds([one.get.path, one.get.query], "{id}"))
107
+ throw invalid(`${where}.get`, 'no "{id}" in its path or query');
108
+ }
109
+ if (one.map.externalId === undefined)
110
+ throw invalid(`${where}.map.externalId`, "every kind maps its id");
111
+ const fields = Object.keys(CONTENT_FIELDS[kind]);
112
+ for (const field of Object.keys(one.map))
113
+ if (!fields.includes(field)) {
114
+ const near = nearest(field, fields);
115
+ throw invalid(`${where}.map.${field}`, `${kind} has no such field${near ? `; did you mean ${near}?` : ""}`);
116
+ }
117
+ if (one.body && kind !== "post")
118
+ throw invalid(`${where}.body`, "only a post has a text");
119
+ });
120
+ }
121
+ const writes = manifest.writes;
122
+ if (writes) {
123
+ if (!manifest.entities.post?.some((one) => one.get))
124
+ throw invalid("writes", "a write checks the post's version first, and no post entity has a get");
125
+ for (const name of ["create", "update", "trash", "delete"]) {
126
+ const one = writes[name];
127
+ if (!one)
128
+ continue;
129
+ checkCall(`writes.${name}`, one, false);
130
+ if (name !== "create" && !holds([one.path, one.query], "{id}"))
131
+ throw invalid(`writes.${name}`, 'no "{id}" in its path or query');
132
+ }
133
+ if (!holds(writes.schedule, "{at}"))
134
+ throw invalid("writes.schedule", 'no "{at}" for the time it goes out');
135
+ }
136
+ return manifest;
137
+ };
@@ -0,0 +1,25 @@
1
+ import type { crmValues } from "../../crm/index.js";
2
+ import type { CrmRule } from "../../crm/manifest/manifest.js";
3
+ import { type Conversion } from "../../crm/manifest/map.js";
4
+ import { type ContentKind, type ContentRecords } from "../../domain/content.js";
5
+ import type { ContentManifestEntity } from "./manifest.js";
6
+ /** A time: read by `utcEpoch`, so a time the source wrote with no offset is UTC, as WordPress's `*_gmt` fields are. */
7
+ declare const TIME = "time";
8
+ type Field = Conversion | typeof TIME;
9
+ /** Each of our fields and how a value the source sent becomes it. */
10
+ export declare const CONTENT_FIELDS: {
11
+ readonly [K in ContentKind]: Readonly<Record<string, Field>>;
12
+ };
13
+ /** Epoch ms from ISO, or from epoch seconds or ms; an ISO time without an offset is UTC. */
14
+ export declare const utcEpoch: (value: unknown) => number | null;
15
+ /**
16
+ * One row as our record of the kind, or null for a row without an id, a term of no known kind, or a post of no known
17
+ * status: a post whose status we cannot say could be taken for published.
18
+ */
19
+ export declare const mapContentRecord: <K extends ContentKind>(kind: K, map: Readonly<Record<string, CrmRule | undefined>>, raw: crmValues.CrmRaw) => ContentRecords[K] | null;
20
+ /** A post's text as Markdown, and whether its source markup is more than Markdown keeps. */
21
+ export declare const postBodyOf: (entity: ContentManifestEntity, raw: crmValues.CrmRaw) => Promise<{
22
+ body?: string;
23
+ lossy?: boolean;
24
+ }>;
25
+ export {};
@@ -0,0 +1,94 @@
1
+ import { at, mapFields } from "../../crm/manifest/map.js";
2
+ import { htmlToMarkdown } from "../../documents/html-markdown.js";
3
+ import { POST_STATUSES, POST_TYPES, TERM_KINDS, } from "../../domain/content.js";
4
+ /** A time: read by `utcEpoch`, so a time the source wrote with no offset is UTC, as WordPress's `*_gmt` fields are. */
5
+ const TIME = "time";
6
+ const TIMES = { createdAt: TIME, updatedAt: TIME };
7
+ /** Each of our fields and how a value the source sent becomes it. */
8
+ export const CONTENT_FIELDS = {
9
+ author: { externalId: "id", name: "text", email: "text", slug: "text", ...TIMES },
10
+ term: { externalId: "id", kind: "text", name: "text", slug: "text", parent: "id", ...TIMES },
11
+ post: {
12
+ externalId: "id",
13
+ channel: "id",
14
+ type: "text",
15
+ title: "text",
16
+ excerpt: "text",
17
+ status: "text",
18
+ url: "text",
19
+ slug: "text",
20
+ publishedAt: TIME,
21
+ scheduledFor: TIME,
22
+ authors: "ids",
23
+ terms: "ids",
24
+ parent: "id",
25
+ version: "text",
26
+ ...TIMES,
27
+ },
28
+ };
29
+ const ZONED = /(Z|[+-]\d{2}:?\d{2})$/i;
30
+ /** Epoch ms from ISO, or from epoch seconds or ms; an ISO time without an offset is UTC. */
31
+ export const utcEpoch = (value) => {
32
+ if (typeof value === "number")
33
+ return Number.isFinite(value) && value > 0 ? (value > 1e11 ? value : value * 1000) : null;
34
+ if (typeof value !== "string" || !value.trim())
35
+ return null;
36
+ const text = value.trim();
37
+ if (/^\d{10,16}$/.test(text))
38
+ return utcEpoch(Number(text));
39
+ const parsed = Date.parse(/T\d/.test(text) && !ZONED.test(text) ? `${text}Z` : text);
40
+ return Number.isNaN(parsed) ? null : parsed;
41
+ };
42
+ const REQUIRED = {
43
+ author: { name: "" },
44
+ term: { name: "" },
45
+ post: {},
46
+ };
47
+ /**
48
+ * One row as our record of the kind, or null for a row without an id, a term of no known kind, or a post of no known
49
+ * status: a post whose status we cannot say could be taken for published.
50
+ */
51
+ export const mapContentRecord = (kind, map, raw) => {
52
+ const types = CONTENT_FIELDS[kind];
53
+ const out = mapFields(map, Object.fromEntries(Object.entries(types).map(([field, type]) => [field, type === TIME ? "text" : type])), raw);
54
+ for (const [field, type] of Object.entries(types))
55
+ if (type === TIME && out[field] !== undefined)
56
+ out[field] = utcEpoch(out[field]);
57
+ if (typeof out.externalId !== "string")
58
+ return null;
59
+ for (const [field, empty] of Object.entries(REQUIRED[kind]))
60
+ if (out[field] == null)
61
+ out[field] = empty;
62
+ if (kind === "term" && !TERM_KINDS.includes(out.kind))
63
+ return null;
64
+ if (kind === "post") {
65
+ if (!POST_STATUSES.includes(out.status))
66
+ return null;
67
+ if (out.type !== undefined && !POST_TYPES.includes(out.type))
68
+ out.type = "post";
69
+ const post = out;
70
+ // The source keeps one date per post: it is when a scheduled post goes out, or when a published one went out.
71
+ if (post.status !== "scheduled" && post.scheduledFor !== undefined)
72
+ post.scheduledFor = null;
73
+ if (post.status !== "published" && post.status !== "private" && post.publishedAt !== undefined)
74
+ post.publishedAt = null;
75
+ }
76
+ return out;
77
+ };
78
+ /** Block comments, frames and embeds that Markdown does not keep: writing the body back would flatten them. */
79
+ const LOSSY = /<!--\s*wp:|<(iframe|embed|object|video|audio|script|form)\b/i;
80
+ /** A post's text as Markdown, and whether its source markup is more than Markdown keeps. */
81
+ export const postBodyOf = async (entity, raw) => {
82
+ if (!entity.body)
83
+ return {};
84
+ const read = (where) => {
85
+ const value = at(raw, where.path);
86
+ return typeof value === "string" ? { text: value, format: where.format } : undefined;
87
+ };
88
+ const found = read(entity.body) ?? (entity.body.fallback ? read(entity.body.fallback) : undefined);
89
+ if (!found)
90
+ return {};
91
+ if (found.format === "markdown")
92
+ return { body: found.text, lossy: false };
93
+ return { body: (await htmlToMarkdown(found.text)).trim(), lossy: LOSSY.test(found.text) };
94
+ };
@@ -0,0 +1,41 @@
1
+ import type { ApiCommandInput } from "../../cli/bot/api.js";
2
+ import type { ServiceApiCall } from "../../cli/service-api-call.js";
3
+ import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
+ import type { CrmOperationCall } from "../../crm/manifest/manifest.js";
5
+ import { type ContentSource } from "../source.js";
6
+ /**
7
+ * Sends one read. A call that can also answer the response's headers lets paging stop where the source says the
8
+ * last page is (WordPress's `X-WP-TotalPages`).
9
+ */
10
+ export type ContentReadCall = ServiceApiCall & {
11
+ withHeaders?: (operation: string, input: ApiCommandInput) => Promise<{
12
+ body: unknown;
13
+ headers: Headers;
14
+ }>;
15
+ };
16
+ export interface ContentManifestSourceOptions {
17
+ api: ServiceApiManifest;
18
+ call: ContentReadCall;
19
+ /** The site the profile signed in to, as it keeps it: `blog.example.com/news`. The channel's address. */
20
+ site: string;
21
+ /** The site's name; the address when absent. */
22
+ name?: string;
23
+ now?: () => number;
24
+ }
25
+ /**
26
+ * The one channel's id, the same whatever the site's address: a profile pointed at another address is then a moved
27
+ * channel, which holds deletions until `sync --rescan`, and never a second channel whose posts share the first's ids.
28
+ */
29
+ export declare const SITE_CHANNEL = "site";
30
+ export interface Slots {
31
+ since?: string;
32
+ id?: string;
33
+ at?: string;
34
+ }
35
+ export declare const fill: (value: unknown, slots: Slots) => unknown;
36
+ export declare const inputOf: (call: CrmOperationCall, slots: Slots, body?: unknown) => ApiCommandInput;
37
+ /**
38
+ * A `ContentSource` read from a manifest: each kind by the calls it names, paged by each operation's own
39
+ * `pagination`, each row mapped onto the content domain, a post's text turned into Markdown.
40
+ */
41
+ export declare const contentSourceFromManifest: (input: unknown, options: ContentManifestSourceOptions) => ContentSource;
@@ -0,0 +1,288 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
3
+ import { crmValues } from "../../crm/index.js";
4
+ import { at, evaluate, MISSING } from "../../crm/manifest/map.js";
5
+ import { GET_UNSUPPORTED, } from "../source.js";
6
+ import { parseContentManifest } from "./manifest.js";
7
+ import { mapContentRecord, postBodyOf, utcEpoch } from "./map.js";
8
+ /**
9
+ * The one channel's id, the same whatever the site's address: a profile pointed at another address is then a moved
10
+ * channel, which holds deletions until `sync --rescan`, and never a second channel whose posts share the first's ids.
11
+ */
12
+ export const SITE_CHANNEL = "site";
13
+ const OVERLAP_MS = 10 * 60_000;
14
+ const KEYSET_STEP = 1000;
15
+ const DROP = Symbol("drop");
16
+ export const fill = (value, slots) => {
17
+ if (value === "{since}")
18
+ return slots.since ?? DROP;
19
+ if (value === "{id}")
20
+ return slots.id ?? DROP;
21
+ if (value === "{at}")
22
+ return slots.at ?? DROP;
23
+ if (Array.isArray(value))
24
+ return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
25
+ if (crmValues.isRaw(value))
26
+ return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
27
+ const filled = fill(one, slots);
28
+ return filled === DROP ? [] : [[key, filled]];
29
+ }));
30
+ return value;
31
+ };
32
+ export const inputOf = (call, slots, body) => {
33
+ const path = fill(call.path ?? {}, slots);
34
+ const query = fill(call.query ?? {}, slots);
35
+ const sent = body ?? (call.body === undefined ? undefined : fill(call.body, slots));
36
+ return {
37
+ path: Object.fromEntries(Object.entries(path).map(([key, one]) => [key, String(one)])),
38
+ query: Object.fromEntries(Object.entries(query).map(([key, one]) => [key, Array.isArray(one) ? one.join(",") : String(one)])),
39
+ headers: {},
40
+ fields: {},
41
+ ...(sent === undefined || sent === DROP ? {} : { body: JSON.stringify(sent) }),
42
+ };
43
+ };
44
+ const SINCE = {
45
+ iso: (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`,
46
+ seconds: (ms) => String(Math.floor(ms / 1000)),
47
+ ms: (ms) => String(ms),
48
+ };
49
+ const pageParameter = (pagination) => pagination.style === "cursor"
50
+ ? pagination.cursor
51
+ : pagination.style === "offset"
52
+ ? pagination.offset
53
+ : pagination.style === "page"
54
+ ? pagination.page
55
+ : undefined;
56
+ /** `<call>.<token>@<when the round started>`: a round spread over runs ends with its first page's time. */
57
+ const pageOf = (page, now) => {
58
+ const cut = page?.lastIndexOf("@") ?? -1;
59
+ const started = Number(page?.slice(cut + 1));
60
+ if (page === undefined || cut < 0 || !Number.isSafeInteger(started))
61
+ return { call: 0, token: undefined, started: now };
62
+ const head = page.slice(0, cut);
63
+ const dot = head.indexOf(".");
64
+ const call = Number(dot < 0 ? head : head.slice(0, dot));
65
+ const token = dot < 0 ? undefined : head.slice(dot + 1) || undefined;
66
+ return Number.isSafeInteger(call) && call >= 0 ? { call, token, started } : { call: -1, token: undefined, started };
67
+ };
68
+ const gone = (error) => isCliError(error) && error.code === "not_found";
69
+ const refused = (error) => isCliError(error) && (error.code === "permission_error" || error.code === "not_found");
70
+ /**
71
+ * A `ContentSource` read from a manifest: each kind by the calls it names, paged by each operation's own
72
+ * `pagination`, each row mapped onto the content domain, a post's text turned into Markdown.
73
+ */
74
+ export const contentSourceFromManifest = (input, options) => {
75
+ const manifest = parseContentManifest(input, options.api);
76
+ const now = options.now ?? Date.now;
77
+ const overlap = manifest.overlapMs ?? OVERLAP_MS;
78
+ const operations = new Map(options.api.operations.map((one) => [one.id, one]));
79
+ const metered = (context) => {
80
+ let paid = false;
81
+ const pay = () => {
82
+ if (paid)
83
+ context?.spend();
84
+ paid = true;
85
+ };
86
+ const send = (operation, request) => {
87
+ pay();
88
+ return options.call(operation, request);
89
+ };
90
+ if (options.call.withHeaders) {
91
+ const withHeaders = options.call.withHeaders;
92
+ send.withHeaders = (operation, request) => {
93
+ pay();
94
+ return withHeaders(operation, request);
95
+ };
96
+ }
97
+ return send;
98
+ };
99
+ const readPage = async (call, slots, token, send) => {
100
+ const pagination = operations.get(call.operation)?.pagination;
101
+ const parameter = pagination && pageParameter(pagination);
102
+ let request = inputOf(call, slots);
103
+ if (token !== undefined && parameter)
104
+ request = withValue(request, parameter, pagination.style === "cursor" ? token : Number(token));
105
+ const read = send.withHeaders
106
+ ? await send.withHeaders(call.operation, request)
107
+ : { body: await send(call.operation, request), headers: new Headers() };
108
+ const answer = read.body;
109
+ if (!pagination || !parameter) {
110
+ const listed = call.items === undefined ? answer : at(answer, call.items);
111
+ return { rows: crmValues.rawsOf(listed), next: undefined };
112
+ }
113
+ const step = nextPage(pagination, request, answer, read.headers);
114
+ const rows = crmValues.rawsOf(call.items === undefined ? step.items : at(answer, call.items));
115
+ const value = step.next && "input" in step.next ? parameterValue(step.next.input, parameter) : undefined;
116
+ if (value === undefined || value === null)
117
+ return { rows, next: undefined };
118
+ return { rows, next: String(value) };
119
+ };
120
+ const callsOf = (kind) => {
121
+ const found = manifest.entities[kind];
122
+ if (!found)
123
+ throw new CliError("configuration_error", `the source manifest has no ${kind}`);
124
+ return found;
125
+ };
126
+ const mapped = async (kind, entity, rows) => {
127
+ const records = [];
128
+ for (const raw of rows) {
129
+ const record = mapContentRecord(kind, entity.map, raw);
130
+ if (record === null)
131
+ continue;
132
+ if (kind === "post")
133
+ Object.assign(record, { channel: SITE_CHANNEL }, await postBodyOf(entity, raw));
134
+ records.push(record);
135
+ }
136
+ return records;
137
+ };
138
+ const rights = new Map();
139
+ /** Whether the sign-in sees every row of the entity, by its `requires` read; asked once per source. */
140
+ const checkRights = async (kind, entity, send, context) => {
141
+ const requires = entity.optional?.requires;
142
+ if (!requires)
143
+ return;
144
+ const key = JSON.stringify(requires);
145
+ let seen = rights.get(key);
146
+ if (seen === undefined) {
147
+ seen = at(await send(requires.operation, inputOf(requires, {})), requires.check) === true;
148
+ rights.set(key, seen);
149
+ }
150
+ if (!seen)
151
+ context?.gap({
152
+ kind,
153
+ message: entity.optional?.message ?? "",
154
+ ...(entity.optional?.scope ? { scope: entity.optional.scope } : {}),
155
+ });
156
+ };
157
+ const gapOf = (kind, entity, error, context) => {
158
+ if (!entity.optional || !refused(error))
159
+ return false;
160
+ context?.gap({
161
+ kind,
162
+ message: entity.optional.message,
163
+ ...(entity.optional.scope ? { scope: entity.optional.scope } : {}),
164
+ });
165
+ return true;
166
+ };
167
+ /** One page of a change read sorted by modified time: the next page starts just before the last row's time. */
168
+ const keysetPage = async (changes, since, send) => {
169
+ const { rows, next } = await readPage(changes, { since: SINCE[changes.since](since) }, undefined, send);
170
+ if (next === undefined)
171
+ return { rows, next: undefined };
172
+ const last = utcEpoch(at(rows.at(-1), changes.keyset.field));
173
+ const from = last === null ? null : last - (changes.keyset.step ?? KEYSET_STEP);
174
+ // A whole page at one time: only a full list reads past it.
175
+ if (from === null || from <= since)
176
+ return { reset: true };
177
+ return { rows, next: String(from) };
178
+ };
179
+ const readChanges = async (kind, cursor, page, context) => {
180
+ const since = cursor === null ? null : Date.parse(cursor);
181
+ if (since !== null && Number.isNaN(since))
182
+ return { reset: true };
183
+ const calls = callsOf(kind);
184
+ const spot = pageOf(page, now());
185
+ const entity = calls[spot.call];
186
+ if (!entity)
187
+ return { reset: true };
188
+ const send = metered(context);
189
+ const changes = since === null ? undefined : entity.changes;
190
+ let read;
191
+ try {
192
+ await checkRights(kind, entity, send, context);
193
+ read =
194
+ changes?.keyset && since !== null
195
+ ? await keysetPage({ ...changes, keyset: changes.keyset }, spot.token === undefined ? since - overlap : Number(spot.token), send)
196
+ : await readPage(changes ?? entity.list, changes && since !== null ? { since: SINCE[changes.since](since - overlap) } : {}, spot.token, send);
197
+ }
198
+ catch (error) {
199
+ if (!gapOf(kind, entity, error, context))
200
+ throw error;
201
+ read = { rows: [], next: undefined };
202
+ }
203
+ if ("reset" in read)
204
+ return { reset: true };
205
+ const items = await mapped(kind, entity, read.rows);
206
+ if (read.next !== undefined)
207
+ return { items, hasMore: true, nextCursor: `${spot.call}.${read.next}@${spot.started}` };
208
+ if (spot.call + 1 < calls.length)
209
+ return { items, hasMore: true, nextCursor: `${spot.call + 1}.@${spot.started}` };
210
+ return { items, hasMore: false, cursor: new Date(spot.started).toISOString() };
211
+ };
212
+ const readIds = async (kind, page, context) => {
213
+ const calls = callsOf(kind);
214
+ const spot = pageOf(page, 0);
215
+ const entity = calls[spot.call];
216
+ if (!entity)
217
+ throw new CliError("validation_error", `not a page of ${kind} ids: ${page}`);
218
+ let read;
219
+ const send = metered(context);
220
+ try {
221
+ await checkRights(kind, entity, send, context);
222
+ read = await readPage(entity.ids ?? entity.list, {}, spot.token, send);
223
+ }
224
+ catch (error) {
225
+ // Refused, the ids read so far would mark every unread row deleted: the gap holds the pass.
226
+ if (!gapOf(kind, entity, error, context))
227
+ throw error;
228
+ read = { rows: [], next: undefined };
229
+ }
230
+ const items = read.rows.flatMap((raw) => {
231
+ const found = evaluate(entity.map.externalId, raw);
232
+ const externalId = found === MISSING ? null : crmValues.id(found);
233
+ return externalId === null ? [] : [externalId];
234
+ });
235
+ const next = read.next !== undefined
236
+ ? `${spot.call}.${read.next}@0`
237
+ : spot.call + 1 < calls.length
238
+ ? `${spot.call + 1}.@0`
239
+ : undefined;
240
+ return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
241
+ };
242
+ const readOne = async (kind, externalId, context) => {
243
+ const send = metered(context);
244
+ for (const entity of callsOf(kind)) {
245
+ if (!entity.get)
246
+ continue;
247
+ let answer;
248
+ try {
249
+ answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId }));
250
+ }
251
+ catch (error) {
252
+ // A post and a page share one id space; a 404 from one call may be the other's row.
253
+ if (gone(error))
254
+ continue;
255
+ throw error;
256
+ }
257
+ const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
258
+ const [record] = crmValues.isRaw(raw) ? await mapped(kind, entity, [raw]) : [];
259
+ // Only a 404 proves a row gone: an answer we cannot read must not mark it deleted.
260
+ if (!record)
261
+ throw new CliError("invalid_response", `${manifest.provider} answered ${kind} ${externalId} with no row we read`);
262
+ return record;
263
+ }
264
+ if (!callsOf(kind).some((entity) => entity.get))
265
+ throw new CliError("configuration_error", `the source manifest reads no single ${kind}`, {
266
+ reason: GET_UNSUPPORTED,
267
+ });
268
+ return null;
269
+ };
270
+ return {
271
+ provider: manifest.provider,
272
+ traits: { kinds: manifest.kinds, metrics: false },
273
+ async channels() {
274
+ return [
275
+ {
276
+ externalId: SITE_CHANNEL,
277
+ kind: manifest.channel.kind,
278
+ network: manifest.channel.network,
279
+ name: options.name ?? options.site,
280
+ url: `https://${options.site}`,
281
+ },
282
+ ];
283
+ },
284
+ changes: readChanges,
285
+ ids: (kind, page, context) => readIds(kind, page, context),
286
+ get: readOne,
287
+ };
288
+ };
@@ -0,0 +1,26 @@
1
+ import type { Command } from "commander";
2
+ import type { ApiCommandInput } from "../../cli/bot/api.js";
3
+ import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
+ import type { ContentSource } from "../source.js";
5
+ import { type ContentWriter } from "../writer.js";
6
+ /**
7
+ * Sends one write the way the `api` group does: `serviceApiWriter` bound to the invoking command, which checks the
8
+ * profile's keys (the publish value keys, the force-delete key) and asks. Nothing else may write for a CLI.
9
+ */
10
+ export type ContentWriteCall = (command: Command, operation: string, input: ApiCommandInput) => Promise<{
11
+ operation_id: string;
12
+ result: unknown;
13
+ }>;
14
+ export interface ContentManifestWriterOptions {
15
+ api: ServiceApiManifest;
16
+ write: ContentWriteCall;
17
+ /** The command the owner ran, for the write's checks and question. */
18
+ command: Command;
19
+ /** The source built from the same manifest: a write reads the post first, for its version and its status. */
20
+ source: ContentSource;
21
+ }
22
+ /**
23
+ * A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
24
+ * publish of a published post sends nothing. A body goes as the source keeps text (HTML from Markdown).
25
+ */
26
+ export declare const contentWriterFromManifest: (input: unknown, options: ContentManifestWriterOptions) => ContentWriter;