@wirecat/cli-core 0.704.0 → 0.705.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 +86 -0
- package/dist/cli/bot/api-http.d.ts +8 -2
- package/dist/cli/bot/api-http.js +20 -4
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/index.d.ts +3 -3
- package/dist/cli/index.js +3 -3
- package/dist/cli/messenger/store-maintenance-command.js +6 -2
- package/dist/cli/service-api-call.d.ts +13 -3
- package/dist/cli/service-api-call.js +19 -9
- package/dist/cli/service-api-manifest.d.ts +11 -2
- package/dist/cli/service-api-manifest.js +30 -9
- package/dist/cli/service-api.d.ts +14 -6
- package/dist/cli/service-api.js +137 -29
- package/dist/cli/token-session.d.ts +5 -2
- package/dist/cli/token-session.js +13 -4
- package/dist/content/cli/index.d.ts +33 -0
- package/dist/content/cli/index.js +368 -0
- package/dist/content/index.d.ts +8 -0
- package/dist/content/index.js +7 -0
- package/dist/content/manifest/index.d.ts +4 -0
- package/dist/content/manifest/index.js +4 -0
- package/dist/content/manifest/manifest.d.ts +92 -0
- package/dist/content/manifest/manifest.js +137 -0
- package/dist/content/manifest/map.d.ts +25 -0
- package/dist/content/manifest/map.js +94 -0
- package/dist/content/manifest/source.d.ts +41 -0
- package/dist/content/manifest/source.js +288 -0
- package/dist/content/manifest/writer.d.ts +26 -0
- package/dist/content/manifest/writer.js +133 -0
- package/dist/content/source.d.ts +64 -0
- package/dist/content/source.js +2 -0
- package/dist/content/sync.d.ts +61 -0
- package/dist/content/sync.js +387 -0
- package/dist/content/testing/index.d.ts +4 -0
- package/dist/content/testing/index.js +4 -0
- package/dist/content/testing/source-contract.d.ts +38 -0
- package/dist/content/testing/source-contract.js +274 -0
- package/dist/content/testing/source.d.ts +55 -0
- package/dist/content/testing/source.js +276 -0
- package/dist/content/testing/sync-contract.d.ts +10 -0
- package/dist/content/testing/sync-contract.js +172 -0
- package/dist/content/testing/write-contract.d.ts +14 -0
- package/dist/content/testing/write-contract.js +102 -0
- package/dist/content/writer.d.ts +64 -0
- package/dist/content/writer.js +38 -0
- package/dist/content/writes.d.ts +58 -0
- package/dist/content/writes.js +129 -0
- package/dist/documents/file-mirror-model.d.ts +3 -1
- package/dist/documents/index.d.ts +3 -3
- package/dist/documents/index.js +1 -1
- package/dist/domain/content.d.ts +102 -0
- package/dist/domain/content.js +11 -0
- package/dist/errors/reasons.js +14 -0
- package/dist/manifest/index.d.ts +21 -7
- package/dist/manifest/index.js +7 -4
- package/dist/services/documents/mirrors.d.ts +13 -1
- package/dist/services/documents/mirrors.js +12 -3
- package/dist/services/files/mirror.d.ts +20 -8
- package/dist/services/files/mirror.js +84 -27
- package/dist/services/files/versions.d.ts +17 -7
- package/dist/services/files/versions.js +56 -21
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/recover.js +2 -0
- package/dist/store/sqlite/account-purge.js +7 -0
- package/dist/store/sqlite/content.d.ts +100 -0
- package/dist/store/sqlite/content.js +375 -0
- package/dist/store/sqlite/entity-types.d.ts +1 -0
- package/dist/store/sqlite/entity-types.js +1 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +26 -0
- package/dist/store/sqlite/schema.d.ts +1140 -0
- package/dist/store/sqlite/schema.js +100 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +12 -4
|
@@ -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;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { crmValues } from "../../crm/index.js";
|
|
3
|
+
import { markdownToHtml } from "../../documents/html-markdown.js";
|
|
4
|
+
import { contentConflict } from "../writer.js";
|
|
5
|
+
import { parseContentManifest } from "./manifest.js";
|
|
6
|
+
import { mapContentRecord, postBodyOf } from "./map.js";
|
|
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.
|
|
9
|
+
const pagesUnwritten = () => new CliError("validation_error", "this CLI writes posts, not pages", { reason: "content.write-unsupported" });
|
|
10
|
+
const iso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
|
|
11
|
+
/**
|
|
12
|
+
* A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
|
|
13
|
+
* publish of a published post sends nothing. A body goes as the source keeps text (HTML from Markdown).
|
|
14
|
+
*/
|
|
15
|
+
export const contentWriterFromManifest = (input, options) => {
|
|
16
|
+
const manifest = parseContentManifest(input, options.api);
|
|
17
|
+
const writes = manifest.writes;
|
|
18
|
+
if (!writes)
|
|
19
|
+
throw new CliError("configuration_error", "the source manifest has no writes");
|
|
20
|
+
const [entity] = manifest.entities.post ?? [];
|
|
21
|
+
if (!entity)
|
|
22
|
+
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) => {
|
|
25
|
+
const raw = crmValues.isRaw(answer) && crmValues.isRaw(answer.previous) && answer.deleted === true ? null : answer;
|
|
26
|
+
if (!crmValues.isRaw(raw))
|
|
27
|
+
return null;
|
|
28
|
+
const post = mapContentRecord("post", entity.map, raw);
|
|
29
|
+
if (!post)
|
|
30
|
+
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));
|
|
32
|
+
};
|
|
33
|
+
const bodyOf = async (fields) => {
|
|
34
|
+
const out = {};
|
|
35
|
+
const put = (path, value) => {
|
|
36
|
+
const keys = path.split(".");
|
|
37
|
+
const last = keys.pop();
|
|
38
|
+
let inner = out;
|
|
39
|
+
for (const key of keys) {
|
|
40
|
+
if (!crmValues.isRaw(inner[key]))
|
|
41
|
+
inner[key] = {};
|
|
42
|
+
inner = inner[key];
|
|
43
|
+
}
|
|
44
|
+
inner[last] = value;
|
|
45
|
+
};
|
|
46
|
+
const to = writes.fields;
|
|
47
|
+
if (fields.title !== undefined && to.title)
|
|
48
|
+
put(to.title, fields.title ?? "");
|
|
49
|
+
if (fields.excerpt !== undefined && to.excerpt)
|
|
50
|
+
put(to.excerpt, fields.excerpt ?? "");
|
|
51
|
+
if (fields.slug !== undefined && to.slug)
|
|
52
|
+
put(to.slug, fields.slug ?? "");
|
|
53
|
+
if (fields.body !== undefined && to.body)
|
|
54
|
+
put(to.body, html ? await markdownToHtml(fields.body) : fields.body);
|
|
55
|
+
if (fields.terms !== undefined && to.terms) {
|
|
56
|
+
const kinds = new Map();
|
|
57
|
+
for (const term of fields.terms) {
|
|
58
|
+
const found = await options.source.get("term", term);
|
|
59
|
+
if (!found)
|
|
60
|
+
throw new CliError("not_found", `no tag or category ${term} at ${manifest.provider}`);
|
|
61
|
+
kinds.set(found.kind, [...(kinds.get(found.kind) ?? []), term]);
|
|
62
|
+
}
|
|
63
|
+
// A numeric id goes as a number: the API's body schema types WordPress's term lists as integers.
|
|
64
|
+
for (const [kind, name] of Object.entries(to.terms))
|
|
65
|
+
if (name)
|
|
66
|
+
put(name, (kinds.get(kind) ?? []).map((one) => (/^\d+$/.test(one) ? Number(one) : one)));
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
};
|
|
70
|
+
/** The post as the source holds it now, checked against the copy's version. */
|
|
71
|
+
const current = async (externalId, { version }) => {
|
|
72
|
+
const found = await options.source.get("post", externalId);
|
|
73
|
+
if (!found)
|
|
74
|
+
throw new CliError("not_found", `${manifest.provider} has no post ${externalId}; sync, then try again`);
|
|
75
|
+
if (version != null && found.version != null && found.version !== version)
|
|
76
|
+
throw contentConflict();
|
|
77
|
+
if (found.type === "page")
|
|
78
|
+
throw pagesUnwritten();
|
|
79
|
+
return found;
|
|
80
|
+
};
|
|
81
|
+
const send = async (call, slots, body) => {
|
|
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 }));
|
|
84
|
+
return result;
|
|
85
|
+
};
|
|
86
|
+
const updated = async (externalId, body) => {
|
|
87
|
+
const post = await postOf(await send(writes.update, { id: externalId }, body));
|
|
88
|
+
if (!post)
|
|
89
|
+
throw new CliError("invalid_response", `${manifest.provider} answered an update with no post`);
|
|
90
|
+
return post;
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
provider: manifest.provider,
|
|
94
|
+
async createDraft(draft) {
|
|
95
|
+
if (draft.type === "page")
|
|
96
|
+
throw pagesUnwritten();
|
|
97
|
+
const post = await postOf(await send(writes.create, {}, await bodyOf(draft)));
|
|
98
|
+
if (!post)
|
|
99
|
+
throw new CliError("invalid_response", `${manifest.provider} answered a create with no post`);
|
|
100
|
+
return post;
|
|
101
|
+
},
|
|
102
|
+
async update(externalId, patch, options_) {
|
|
103
|
+
await current(externalId, options_);
|
|
104
|
+
return updated(externalId, await bodyOf(patch));
|
|
105
|
+
},
|
|
106
|
+
async publish(externalId, options_) {
|
|
107
|
+
const found = await current(externalId, options_);
|
|
108
|
+
if (found.status === "published")
|
|
109
|
+
return found;
|
|
110
|
+
return updated(externalId, { ...writes.publish });
|
|
111
|
+
},
|
|
112
|
+
async schedule(externalId, when, options_) {
|
|
113
|
+
await current(externalId, options_);
|
|
114
|
+
return updated(externalId, fill(writes.schedule, { at: iso(when) }));
|
|
115
|
+
},
|
|
116
|
+
async unpublish(externalId, options_) {
|
|
117
|
+
await current(externalId, options_);
|
|
118
|
+
return updated(externalId, { ...writes.unpublish });
|
|
119
|
+
},
|
|
120
|
+
async trash(externalId, options_) {
|
|
121
|
+
await current(externalId, options_);
|
|
122
|
+
if (options_.force) {
|
|
123
|
+
if (!writes.delete)
|
|
124
|
+
throw new CliError("validation_error", `${manifest.provider} takes no deletion past the trash`, {
|
|
125
|
+
reason: "content.write-unsupported",
|
|
126
|
+
});
|
|
127
|
+
await send(writes.delete, { id: externalId });
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
return postOf(await send(writes.trash, { id: externalId }));
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ContentChannel, ContentKind, ContentMetric, ContentRecords } from "../domain/content.js";
|
|
2
|
+
export interface ContentSourceTraits {
|
|
3
|
+
/** What this source has, in `CONTENT_KINDS` order: a social account without terms leaves `term` out. */
|
|
4
|
+
kinds: readonly ContentKind[];
|
|
5
|
+
/** The source has numbers per post that `metrics` reads. */
|
|
6
|
+
metrics: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ContentPage<T> {
|
|
9
|
+
items: T[];
|
|
10
|
+
hasMore: boolean;
|
|
11
|
+
nextCursor?: string;
|
|
12
|
+
/** On the last page: the cursor the next run reads changes after; `null` when the source keeps none. */
|
|
13
|
+
cursor?: string | null;
|
|
14
|
+
}
|
|
15
|
+
/** `reset`: the cursor is dead, and the kind must be listed in full again. */
|
|
16
|
+
export type ContentChanges<T> = ContentPage<T> | {
|
|
17
|
+
reset: true;
|
|
18
|
+
};
|
|
19
|
+
export interface ContentIdPage {
|
|
20
|
+
items: string[];
|
|
21
|
+
hasMore: boolean;
|
|
22
|
+
nextCursor?: string;
|
|
23
|
+
}
|
|
24
|
+
/** What the last sync could not read: drafts a role may not see, a kind the sign-in's scope refused. */
|
|
25
|
+
export interface ContentGap {
|
|
26
|
+
kind: ContentKind;
|
|
27
|
+
message: string;
|
|
28
|
+
scope?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface ContentCallContext {
|
|
31
|
+
/** Takes one request from the run's budget for each request beyond the first; throws once it is spent. */
|
|
32
|
+
spend(): void;
|
|
33
|
+
/** Says what the call could not read without failing it. A gap holds the kind's deletions. */
|
|
34
|
+
gap(gap: ContentGap): void;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One content account, as an adapter reads it: a blog, or a social account. A trashed post is listed with its status,
|
|
38
|
+
* as every status is: a list that leaves trash out would make a trashed post look deleted. A post deleted for good is
|
|
39
|
+
* found by `ids()`, which lists every id of every status, or by `get` answering `null`.
|
|
40
|
+
*/
|
|
41
|
+
export interface ContentSource {
|
|
42
|
+
/** The registry name: `wordpress`. */
|
|
43
|
+
readonly provider: string;
|
|
44
|
+
readonly traits: ContentSourceTraits;
|
|
45
|
+
/** The sites or accounts this sign-in publishes on; their address is how a sync tells a moved site. */
|
|
46
|
+
channels(context?: ContentCallContext): Promise<ContentChannel[]>;
|
|
47
|
+
/**
|
|
48
|
+
* What changed since `cursor`, a page at a time; `cursor: null` lists everything. A source without a change feed
|
|
49
|
+
* reads by its own modified time less an overlap, and gives back as the last page's cursor the time the round's first
|
|
50
|
+
* page was read.
|
|
51
|
+
*/
|
|
52
|
+
changes<K extends ContentKind>(kind: K, cursor: string | null, page?: string, context?: ContentCallContext): Promise<ContentChanges<ContentRecords[K]>>;
|
|
53
|
+
/** Every id the source holds of the kind, trashed ones too, a page at a time: how deletions are found. */
|
|
54
|
+
ids(kind: ContentKind, page?: string, context?: ContentCallContext): Promise<ContentIdPage>;
|
|
55
|
+
/**
|
|
56
|
+
* One record by its id; `null` only when the source said it has none, which proves it deleted. A source that cannot
|
|
57
|
+
* read the kind one by one throws with the reason `GET_UNSUPPORTED`.
|
|
58
|
+
*/
|
|
59
|
+
get<K extends ContentKind>(kind: K, externalId: string, context?: ContentCallContext): Promise<ContentRecords[K] | null>;
|
|
60
|
+
/** A reading of each post's numbers now; a source without metrics answers none. */
|
|
61
|
+
metrics?(posts: readonly string[], context?: ContentCallContext): Promise<ContentMetric[]>;
|
|
62
|
+
}
|
|
63
|
+
/** A source that cannot read one row by its id throws a CliError with this reason; it never answers null for it. */
|
|
64
|
+
export declare const GET_UNSUPPORTED = "content.get-unsupported";
|