@wirecat/cli-core 0.703.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/bot/api-http.d.ts +8 -2
  4. package/dist/cli/bot/api-http.js +20 -4
  5. package/dist/cli/documents/words.d.ts +1 -1
  6. package/dist/cli/index.d.ts +3 -3
  7. package/dist/cli/index.js +3 -3
  8. package/dist/cli/messenger/store-maintenance-command.js +6 -2
  9. package/dist/cli/service-api-call.d.ts +13 -3
  10. package/dist/cli/service-api-call.js +19 -9
  11. package/dist/cli/service-api-manifest.d.ts +11 -2
  12. package/dist/cli/service-api-manifest.js +30 -9
  13. package/dist/cli/service-api.d.ts +14 -6
  14. package/dist/cli/service-api.js +137 -29
  15. package/dist/cli/token-session.d.ts +5 -2
  16. package/dist/cli/token-session.js +13 -4
  17. package/dist/content/cli/index.d.ts +33 -0
  18. package/dist/content/cli/index.js +368 -0
  19. package/dist/content/index.d.ts +8 -0
  20. package/dist/content/index.js +7 -0
  21. package/dist/content/manifest/index.d.ts +4 -0
  22. package/dist/content/manifest/index.js +4 -0
  23. package/dist/content/manifest/manifest.d.ts +92 -0
  24. package/dist/content/manifest/manifest.js +137 -0
  25. package/dist/content/manifest/map.d.ts +25 -0
  26. package/dist/content/manifest/map.js +94 -0
  27. package/dist/content/manifest/source.d.ts +41 -0
  28. package/dist/content/manifest/source.js +288 -0
  29. package/dist/content/manifest/writer.d.ts +26 -0
  30. package/dist/content/manifest/writer.js +133 -0
  31. package/dist/content/source.d.ts +64 -0
  32. package/dist/content/source.js +2 -0
  33. package/dist/content/sync.d.ts +61 -0
  34. package/dist/content/sync.js +387 -0
  35. package/dist/content/testing/index.d.ts +4 -0
  36. package/dist/content/testing/index.js +4 -0
  37. package/dist/content/testing/source-contract.d.ts +38 -0
  38. package/dist/content/testing/source-contract.js +274 -0
  39. package/dist/content/testing/source.d.ts +55 -0
  40. package/dist/content/testing/source.js +276 -0
  41. package/dist/content/testing/sync-contract.d.ts +10 -0
  42. package/dist/content/testing/sync-contract.js +172 -0
  43. package/dist/content/testing/write-contract.d.ts +14 -0
  44. package/dist/content/testing/write-contract.js +102 -0
  45. package/dist/content/writer.d.ts +64 -0
  46. package/dist/content/writer.js +38 -0
  47. package/dist/content/writes.d.ts +58 -0
  48. package/dist/content/writes.js +129 -0
  49. package/dist/documents/file-mirror-model.d.ts +90 -0
  50. package/dist/documents/file-mirror-model.js +1 -0
  51. package/dist/documents/index.d.ts +6 -3
  52. package/dist/documents/index.js +3 -1
  53. package/dist/documents/push-model.d.ts +3 -0
  54. package/dist/domain/content.d.ts +102 -0
  55. package/dist/domain/content.js +11 -0
  56. package/dist/embeddings/onnx-runtime.d.ts +1 -1
  57. package/dist/embeddings/onnx-runtime.js +42 -61
  58. package/dist/errors/reasons.js +22 -0
  59. package/dist/manifest/index.d.ts +21 -7
  60. package/dist/manifest/index.js +7 -4
  61. package/dist/ports/wirecat-tools.js +7 -0
  62. package/dist/sends/upload.js +0 -1
  63. package/dist/services/documents/mirror-watch.d.ts +12 -4
  64. package/dist/services/documents/mirror-watch.js +2 -0
  65. package/dist/services/documents/mirrors.d.ts +67 -35
  66. package/dist/services/documents/mirrors.js +72 -66
  67. package/dist/services/documents/push.d.ts +56 -4
  68. package/dist/services/documents/push.js +131 -24
  69. package/dist/services/files/mirror.d.ts +157 -0
  70. package/dist/services/files/mirror.js +660 -0
  71. package/dist/services/files/versions.d.ts +60 -0
  72. package/dist/services/files/versions.js +177 -0
  73. package/dist/services/metadata.d.ts +1 -1
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/recover.js +2 -0
  77. package/dist/store/sqlite/account-purge.js +7 -0
  78. package/dist/store/sqlite/content.d.ts +100 -0
  79. package/dist/store/sqlite/content.js +375 -0
  80. package/dist/store/sqlite/entity-types.d.ts +1 -0
  81. package/dist/store/sqlite/entity-types.js +1 -0
  82. package/dist/store/sqlite/manifest.js +2 -0
  83. package/dist/store/sqlite/migrations.generated.js +26 -0
  84. package/dist/store/sqlite/schema.d.ts +1140 -0
  85. package/dist/store/sqlite/schema.js +100 -0
  86. package/dist/store/store.d.ts +3 -0
  87. package/dist/store/store.js +5 -0
  88. package/package.json +12 -4
@@ -0,0 +1,274 @@
1
+ import assert from "node:assert/strict";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { CHANNEL_KINDS, POST_STATUSES, TERM_KINDS, } from "../../domain/content.js";
4
+ const SKEW_MS = 10 * 60_000;
5
+ const MAX_PAGES = 1_000;
6
+ const idsOf = (items) => items.map((item) => item.externalId);
7
+ const listAll = async (source, kind, cursor) => {
8
+ const items = [];
9
+ const pages = new Set();
10
+ let page;
11
+ for (let read = 0; read < MAX_PAGES; read += 1) {
12
+ const answer = await source.changes(kind, cursor, page);
13
+ assert.ok(!("reset" in answer), `${kind}: a full list is never a dead cursor`);
14
+ const listed = answer;
15
+ assert.ok(Array.isArray(listed.items), `${kind}: a page has items`);
16
+ items.push(...listed.items);
17
+ assert.equal(listed.hasMore, listed.nextCursor !== undefined, `${kind}: a next cursor exactly when there is more`);
18
+ if (!listed.hasMore) {
19
+ assert.ok(listed.cursor === null || typeof listed.cursor === "string", `${kind}: the last page gives a cursor`);
20
+ return { items, cursor: listed.cursor ?? null };
21
+ }
22
+ const next = listed.nextCursor;
23
+ assert.ok(!pages.has(next), `${kind}: the same page twice`);
24
+ pages.add(next);
25
+ page = next;
26
+ }
27
+ throw new assert.AssertionError({ message: `${kind}: more than ${MAX_PAGES} pages` });
28
+ };
29
+ const allIds = async (source, kind) => {
30
+ const listed = new Set();
31
+ let page;
32
+ for (let read = 0; read < MAX_PAGES; read += 1) {
33
+ const answer = await source.ids(kind, page);
34
+ for (const id of answer.items)
35
+ listed.add(id);
36
+ if (!answer.hasMore)
37
+ return listed;
38
+ assert.ok(answer.nextCursor !== undefined && answer.nextCursor !== page, `${kind}: ids() gives a new page`);
39
+ page = answer.nextCursor;
40
+ }
41
+ throw new assert.AssertionError({ message: `${kind}: more than ${MAX_PAGES} pages of ids` });
42
+ };
43
+ const optionalText = (value) => value === undefined || value === null || typeof value === "string";
44
+ const optionalTime = (value) => value === undefined || value === null || (typeof value === "number" && Number.isSafeInteger(value));
45
+ const idList = (value) => value === undefined || (Array.isArray(value) && value.every((one) => typeof one === "string"));
46
+ /** The shape every record of the kind keeps, in the content domain's fields. */
47
+ const checkShape = (kind, record) => {
48
+ const at = `${kind} ${String(record.externalId)}`;
49
+ assert.ok(typeof record.externalId === "string" && record.externalId.trim(), `${kind}: a record has an id`);
50
+ for (const field of ["createdAt", "updatedAt", "publishedAt", "scheduledFor"])
51
+ assert.ok(optionalTime(record[field]), `${at}: ${field} is epoch ms or null`);
52
+ if (kind === "author") {
53
+ assert.ok(typeof record.name === "string", `${at} has its name`);
54
+ assert.ok(optionalText(record.email), `${at}: email is text or null`);
55
+ }
56
+ if (kind === "term") {
57
+ assert.ok(typeof record.name === "string", `${at} has its name`);
58
+ assert.ok(TERM_KINDS.includes(record.kind), `${at}: kind is one of ${TERM_KINDS}`);
59
+ }
60
+ if (kind === "post") {
61
+ assert.ok(POST_STATUSES.includes(record.status), `${at}: status is one of ${POST_STATUSES}`);
62
+ for (const field of ["title", "body", "excerpt", "url", "slug", "channel", "version", "parent"])
63
+ assert.ok(optionalText(record[field]), `${at}: ${field} is text or null`);
64
+ assert.ok(idList(record.authors) && idList(record.terms), `${at}: authors and terms are lists of ids`);
65
+ if (record.status === "scheduled")
66
+ assert.ok(typeof record.scheduledFor === "number", `${at}: a scheduled post says when it goes out`);
67
+ }
68
+ };
69
+ /** What every content adapter answers, whatever the source: run each case in the adapter's tests. */
70
+ export const contentSourceContract = (make) => [
71
+ {
72
+ name: "channels: the sign-in names where it publishes, each with its kind, network and name",
73
+ async run() {
74
+ const { source } = await make();
75
+ const channels = await source.channels();
76
+ assert.ok(channels.length > 0, "at least one channel");
77
+ for (const one of channels) {
78
+ assert.ok(typeof one.externalId === "string" && one.externalId, "a channel has an id");
79
+ assert.ok(CHANNEL_KINDS.includes(one.kind), `channel ${one.externalId}: its kind`);
80
+ assert.ok(typeof one.network === "string" && typeof one.name === "string", `channel ${one.externalId}`);
81
+ }
82
+ },
83
+ },
84
+ {
85
+ name: "changes: a full list pages to its end, each record in the content domain's shape",
86
+ async run() {
87
+ const { source } = await make();
88
+ assert.ok(source.traits.kinds.length > 0, "the source names its kinds");
89
+ for (const kind of source.traits.kinds) {
90
+ const { items } = await listAll(source, kind, null);
91
+ assert.ok(items.length > 0, `${kind}: the fixture lists at least one`);
92
+ for (const item of items)
93
+ checkShape(kind, item);
94
+ const ids = idsOf(items);
95
+ assert.equal(new Set(ids).size, ids.length, `${kind}: no row twice in one full list`);
96
+ }
97
+ },
98
+ },
99
+ {
100
+ name: "changes: a full list gives every row the fixture holds, none lost between the source's pages",
101
+ async run() {
102
+ const { source, held } = await make();
103
+ if (!held)
104
+ return;
105
+ for (const kind of source.traits.kinds) {
106
+ const ids = held[kind];
107
+ if (!ids)
108
+ continue;
109
+ assert.deepEqual(idsOf((await listAll(source, kind, null)).items).sort(), [...ids].sort(), `${kind}: every row`);
110
+ }
111
+ },
112
+ },
113
+ {
114
+ name: "changes: the cursor a full list gave reads again without failing",
115
+ async run() {
116
+ const { source } = await make();
117
+ for (const kind of source.traits.kinds) {
118
+ const { cursor } = await listAll(source, kind, null);
119
+ if (cursor !== null)
120
+ await listAll(source, kind, cursor);
121
+ }
122
+ },
123
+ },
124
+ {
125
+ name: "ids: a list of every id holds every row a full list gave",
126
+ async run() {
127
+ const { source } = await make();
128
+ for (const kind of source.traits.kinds) {
129
+ const listed = await allIds(source, kind);
130
+ for (const id of idsOf((await listAll(source, kind, null)).items))
131
+ assert.ok(listed.has(id), `${kind} ${id} is missing from ids()`);
132
+ }
133
+ },
134
+ },
135
+ {
136
+ name: "get: a post a list gave reads by its id, the same post",
137
+ async run() {
138
+ const { source } = await make();
139
+ if (!source.traits.kinds.includes("post"))
140
+ return;
141
+ const [first] = (await listAll(source, "post", null)).items;
142
+ assert.ok(first, "the fixture lists a post");
143
+ const found = await source.get("post", first.externalId);
144
+ assert.equal(found?.externalId, first.externalId);
145
+ assert.equal(found?.status, first.status);
146
+ },
147
+ },
148
+ {
149
+ name: "changes: a dead cursor answers reset",
150
+ async run() {
151
+ const { source, deadCursor } = await make();
152
+ if (!deadCursor)
153
+ return;
154
+ const answer = await source.changes(deadCursor.kind, deadCursor.cursor);
155
+ assert.ok("reset" in answer, `${deadCursor.kind}: a cursor the source refuses answers reset`);
156
+ },
157
+ },
158
+ {
159
+ name: "faults: a clock off by ten minutes either way loses no change",
160
+ async run() {
161
+ for (const ms of [SKEW_MS, -SKEW_MS]) {
162
+ const { faults, held } = await make();
163
+ if (!faults?.skewed || !faults.change)
164
+ return;
165
+ const source = await faults.skewed(ms);
166
+ const cursors = new Map();
167
+ for (const kind of source.traits.kinds)
168
+ cursors.set(kind, (await listAll(source, kind, null)).cursor);
169
+ const { kind, id } = await faults.change();
170
+ const cursor = cursors.get(kind) ?? null;
171
+ assert.ok(cursor !== null, `${kind}: a full list gives a cursor for the change to be read after`);
172
+ const { items } = await listAll(source, kind, cursor);
173
+ assert.ok(idsOf(items).includes(id), `${kind} ${id} is in the changes with the clock ${ms / 60_000} min off`);
174
+ for (const one of held?.[kind]?.filter((other) => other !== id) ?? [])
175
+ assert.ok(!idsOf(items).includes(one), `${kind} ${one} did not change, yet a read of changes lists it`);
176
+ }
177
+ },
178
+ },
179
+ {
180
+ name: "faults: a trashed post is still listed, in changes and ids, with the status trashed",
181
+ async run() {
182
+ const { source, faults } = await make();
183
+ if (!faults?.trash)
184
+ return;
185
+ const { cursor } = await listAll(source, "post", null);
186
+ const id = await faults.trash();
187
+ const found = (await listAll(source, "post", cursor)).items.find((one) => one.externalId === id);
188
+ assert.ok(found, `post ${id}: a trashed post is in the changes`);
189
+ assert.equal(found.status, "trashed", `post ${id}: trash is a status`);
190
+ assert.ok((await allIds(source, "post")).has(id), `post ${id}: a trashed post is still in ids()`);
191
+ },
192
+ },
193
+ {
194
+ name: "faults: a row deleted for good leaves ids(), and get answers none",
195
+ async run() {
196
+ const { source, faults } = await make();
197
+ if (!faults?.remove)
198
+ return;
199
+ const { kind, id } = await faults.remove();
200
+ assert.ok(!(await allIds(source, kind)).has(id), `${kind} ${id}: a deleted row is not in ids()`);
201
+ assert.equal(await source.get(kind, id), null, `${kind} ${id}: get answers null`);
202
+ },
203
+ },
204
+ {
205
+ name: "faults: a full list cut after its first page goes on from that page in a new run, nothing lost or repeated",
206
+ async run() {
207
+ const { source, faults } = await make();
208
+ if (!faults)
209
+ return;
210
+ let cut = false;
211
+ for (const kind of source.traits.kinds) {
212
+ const whole = idsOf((await listAll(source, kind, null)).items);
213
+ const first = (await source.changes(kind, null));
214
+ if (!first.hasMore)
215
+ continue;
216
+ cut = true;
217
+ const { source: resumed } = await make();
218
+ const rest = [];
219
+ let page = first.nextCursor;
220
+ for (let read = 0; page !== undefined && read < MAX_PAGES; read += 1) {
221
+ const answer = (await resumed.changes(kind, null, page));
222
+ rest.push(...answer.items);
223
+ page = answer.nextCursor;
224
+ }
225
+ const joined = [...idsOf(first.items), ...idsOf(rest)];
226
+ assert.equal(new Set(joined).size, joined.length, `${kind}: no row twice across the cut`);
227
+ assert.deepEqual(joined.sort(), whole.sort(), `${kind}: the cut list adds up to the whole one`);
228
+ }
229
+ assert.ok(cut, "the fixture holds more than one page of some kind, so a list can be cut");
230
+ },
231
+ },
232
+ {
233
+ name: "faults: a call that pages inside stops when the run's budget is spent, and says so",
234
+ async run() {
235
+ const { source, faults } = await make();
236
+ if (!faults)
237
+ return;
238
+ const spent = new CliError("provider_error", "the run's budget is spent", { reason: "sync.partial" });
239
+ for (const kind of source.traits.kinds) {
240
+ let asked = false;
241
+ const context = {
242
+ spend: () => {
243
+ asked = true;
244
+ throw spent;
245
+ },
246
+ gap: () => { },
247
+ };
248
+ const ended = await source.changes(kind, null, undefined, context).then(() => undefined, (error) => error);
249
+ if (asked)
250
+ assert.equal(ended, spent, `${kind}: a spent budget ends the call with its own error`);
251
+ else
252
+ assert.equal(ended, undefined, `${kind}: a call that asks for no more requests is not stopped`);
253
+ }
254
+ },
255
+ },
256
+ {
257
+ name: "metrics: a source with numbers reads them per post; one without has none, and that is no error",
258
+ async run() {
259
+ const { source } = await make();
260
+ if (!source.traits.metrics) {
261
+ assert.deepEqual((await source.metrics?.([])) ?? [], [], "no metrics, no readings");
262
+ return;
263
+ }
264
+ assert.ok(source.metrics, "a source with metrics reads them");
265
+ const posts = idsOf((await listAll(source, "post", null)).items);
266
+ for (const one of await source.metrics(posts)) {
267
+ assert.ok(posts.includes(one.post), `a reading names a listed post, not ${one.post}`);
268
+ assert.ok(Number.isSafeInteger(one.at), "a reading has its time");
269
+ for (const name of ["views", "reactions", "comments", "shares", "clicks"])
270
+ assert.ok(one[name] == null || Number.isFinite(one[name]), `${one.post}: ${name} is a number`);
271
+ }
272
+ },
273
+ },
274
+ ];
@@ -0,0 +1,55 @@
1
+ import type { ContentChannel, ContentKind, ContentMetric, ContentRecords } from "../../domain/content.js";
2
+ import type { ContentSource } from "../source.js";
3
+ import { type ContentWriter } from "../writer.js";
4
+ export type FakeContentRows = {
5
+ [K in ContentKind]?: ContentRecords[K][];
6
+ };
7
+ export interface FakeContentSourceOptions {
8
+ rows: FakeContentRows;
9
+ channel?: ContentChannel;
10
+ /** The source's own clock, which stamps `updatedAt`; this computer's is `skew` off it. */
11
+ clock?: () => number;
12
+ skew?: number;
13
+ pageSize?: number;
14
+ provider?: string;
15
+ /** Numbers per post id; absent, the source has no metrics. */
16
+ metrics?: Record<string, Omit<ContentMetric, "post" | "at">>;
17
+ /**
18
+ * A sign-in that sees only its own posts, as a WordPress contributor: the others' drafts and the trash are refused,
19
+ * and each read says so with a gap.
20
+ */
21
+ only?: {
22
+ author: string;
23
+ };
24
+ }
25
+ export interface FakeContentSource extends ContentSource {
26
+ readonly writer: ContentWriter;
27
+ /** The rows behind it, shared by every source made over them. */
28
+ readonly rows: FakeContentRows;
29
+ /** Changes one row on the source's side: it gets a new `updatedAt`. */
30
+ touch(kind: ContentKind, externalId: string): void;
31
+ /** Moves a post to the trash on the source's side, as its own action would. */
32
+ trashed(externalId: string): void;
33
+ /** Deletes one row for good, as only an id pass or a read finds. */
34
+ remove(kind: ContentKind, externalId: string): void;
35
+ /** A scheduled post goes out by the source's own timer, without a new modified time. */
36
+ elapse(externalId: string): void;
37
+ /** The site answers from another address, as a moved or replaced site does. */
38
+ move(url: string): void;
39
+ /** The same source read from a computer whose clock is `ms` off. */
40
+ skewed(ms: number): FakeContentSource;
41
+ /** Each write request that reached the source, by verb. */
42
+ readonly requests: string[];
43
+ /** How many times each post went from not published to published. */
44
+ readonly publishes: Map<string, number>;
45
+ /** The next write is done at the source, and its answer is lost. */
46
+ loseNextAnswer(): void;
47
+ }
48
+ /**
49
+ * A blog in memory, read the way WordPress is: changes by `updatedAt` from the cursor less an overlap, every status
50
+ * listed with trash among them, pages by offset, a post deleted for good gone from `ids()` and answered `null` by `get`.
51
+ * It also takes writes, checking each one's version.
52
+ */
53
+ export declare const fakeContentSource: (options: FakeContentSourceOptions) => FakeContentSource;
54
+ /** A small blog: two authors, a tag and a category, and posts in every status but trash. */
55
+ export declare const exampleContentRows: () => Required<FakeContentRows>;
@@ -0,0 +1,276 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { contentConflict } from "../writer.js";
3
+ const OVERLAP_MS = 10 * 60_000;
4
+ const T0 = Date.UTC(2026, 10, 1);
5
+ /**
6
+ * A blog in memory, read the way WordPress is: changes by `updatedAt` from the cursor less an overlap, every status
7
+ * listed with trash among them, pages by offset, a post deleted for good gone from `ids()` and answered `null` by `get`.
8
+ * It also takes writes, checking each one's version.
9
+ */
10
+ export const fakeContentSource = (options) => {
11
+ let tick = 0;
12
+ const clock = options.clock ?? (() => Date.UTC(2026, 10, 17) + tick++ * 1000);
13
+ const rows = options.rows;
14
+ const size = options.pageSize ?? 2;
15
+ let channel = options.channel ?? {
16
+ externalId: "site",
17
+ kind: "blog",
18
+ network: "fake-blog",
19
+ name: "Example blog",
20
+ url: "https://blog.example.com",
21
+ };
22
+ const requests = [];
23
+ const publishes = new Map();
24
+ let lose = false;
25
+ let made = 0;
26
+ const listOf = (kind) => {
27
+ rows[kind] ??= [];
28
+ return rows[kind];
29
+ };
30
+ const find = (kind, externalId) => listOf(kind).find((one) => one.externalId === externalId);
31
+ const visible = (kind, row) => {
32
+ if (!options.only || kind !== "post")
33
+ return true;
34
+ const post = row;
35
+ return post.authors?.includes(options.only.author) || post.status === "published";
36
+ };
37
+ const gapOf = (kind, context) => {
38
+ if (options.only && kind === "post")
39
+ context?.gap({ kind, message: "the sign-in sees only its own drafts and no trash", scope: "edit_others_posts" });
40
+ };
41
+ const postOf = (externalId) => {
42
+ const found = find("post", externalId);
43
+ if (!found)
44
+ throw new CliError("not_found", `the fake blog has no post ${externalId}`);
45
+ return found;
46
+ };
47
+ const versionOf = (post) => String(post.updatedAt ?? 0);
48
+ /** One write: checked against the version, stamped, and its answer lost when asked. */
49
+ const write = (verb, post, version, change) => {
50
+ requests.push(verb);
51
+ if (version != null && version !== versionOf(post))
52
+ throw contentConflict();
53
+ const was = post.status;
54
+ change();
55
+ post.updatedAt = clock();
56
+ post.version = versionOf(post);
57
+ if (was !== "published" && post.status === "published")
58
+ publishes.set(post.externalId, (publishes.get(post.externalId) ?? 0) + 1);
59
+ if (lose) {
60
+ lose = false;
61
+ throw new CliError("outcome_unknown", "the connection dropped after the source got the write");
62
+ }
63
+ return { ...post };
64
+ };
65
+ const writer = {
66
+ provider: options.provider ?? "fake-blog",
67
+ async createDraft(draft, { operationId: _ }) {
68
+ made += 1;
69
+ const post = {
70
+ externalId: `new-${made}`,
71
+ type: draft.type ?? "post",
72
+ title: draft.title ?? null,
73
+ body: draft.body ?? "",
74
+ excerpt: draft.excerpt ?? null,
75
+ slug: draft.slug ?? null,
76
+ status: "draft",
77
+ terms: draft.terms ?? [],
78
+ authors: [],
79
+ createdAt: clock(),
80
+ };
81
+ listOf("post").push(post);
82
+ return write("create", post, null, () => { });
83
+ },
84
+ async update(externalId, patch, { version }) {
85
+ const post = postOf(externalId);
86
+ return write("update", post, version, () => {
87
+ for (const [field, value] of Object.entries(patch))
88
+ if (value !== undefined)
89
+ post[field] = value;
90
+ });
91
+ },
92
+ async publish(externalId, { version }) {
93
+ const post = postOf(externalId);
94
+ if (post.status === "published")
95
+ return { ...post };
96
+ return write("publish", post, version, () => {
97
+ post.status = "published";
98
+ post.publishedAt = clock();
99
+ post.scheduledFor = null;
100
+ });
101
+ },
102
+ async schedule(externalId, at, { version }) {
103
+ const post = postOf(externalId);
104
+ return write("schedule", post, version, () => {
105
+ post.status = "scheduled";
106
+ post.scheduledFor = at;
107
+ });
108
+ },
109
+ async unpublish(externalId, { version }) {
110
+ const post = postOf(externalId);
111
+ return write("unpublish", post, version, () => {
112
+ post.status = "draft";
113
+ post.scheduledFor = null;
114
+ });
115
+ },
116
+ async trash(externalId, { version, force }) {
117
+ const post = postOf(externalId);
118
+ if (force) {
119
+ requests.push("delete");
120
+ if (version != null && version !== versionOf(post))
121
+ throw contentConflict();
122
+ listOf("post").splice(listOf("post").indexOf(post), 1);
123
+ return null;
124
+ }
125
+ return write("trash", post, version, () => {
126
+ post.status = "trashed";
127
+ });
128
+ },
129
+ };
130
+ const make = (skew) => ({
131
+ provider: options.provider ?? "fake-blog",
132
+ traits: {
133
+ kinds: ["author", "term", "post"].filter((kind) => listOf(kind).length > 0),
134
+ metrics: options.metrics !== undefined,
135
+ },
136
+ writer,
137
+ rows,
138
+ requests,
139
+ publishes,
140
+ async channels() {
141
+ return [{ ...channel }];
142
+ },
143
+ async changes(kind, cursor, page, context) {
144
+ const since = cursor === null ? null : Date.parse(cursor);
145
+ if (since !== null && Number.isNaN(since))
146
+ return { reset: true };
147
+ const [offsetText, startedText] = (page ?? "").split("@");
148
+ const offset = page === undefined ? 0 : Number(offsetText);
149
+ const started = page === undefined ? clock() + skew : Number(startedText);
150
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(started))
151
+ throw new CliError("validation_error", `not a page of the fake blog: ${page}`);
152
+ gapOf(kind, context);
153
+ const listed = listOf(kind)
154
+ .filter((one) => visible(kind, one))
155
+ .filter((one) => since === null || (one.updatedAt ?? 0) >= since - OVERLAP_MS)
156
+ .sort((a, b) => (a.updatedAt ?? 0) - (b.updatedAt ?? 0) || a.externalId.localeCompare(b.externalId));
157
+ const items = listed.slice(offset, offset + size).map((one) => structuredClone(one));
158
+ const next = offset + size;
159
+ return next < listed.length
160
+ ? { items, hasMore: true, nextCursor: `${next}@${started}` }
161
+ : { items, hasMore: false, cursor: new Date(started).toISOString() };
162
+ },
163
+ async ids(kind, page, context) {
164
+ gapOf(kind, context);
165
+ const offset = page === undefined ? 0 : Number(page);
166
+ const all = listOf(kind)
167
+ .filter((one) => visible(kind, one))
168
+ .map((one) => one.externalId);
169
+ const items = all.slice(offset, offset + size);
170
+ return offset + size < all.length
171
+ ? { items, hasMore: true, nextCursor: String(offset + size) }
172
+ : { items, hasMore: false };
173
+ },
174
+ async get(kind, externalId) {
175
+ const found = find(kind, externalId);
176
+ return found && visible(kind, found) ? structuredClone(found) : null;
177
+ },
178
+ ...(options.metrics
179
+ ? {
180
+ async metrics(posts) {
181
+ const at = clock();
182
+ return posts.flatMap((post) => {
183
+ const numbers = options.metrics?.[post];
184
+ return numbers ? [{ post, at, ...numbers }] : [];
185
+ });
186
+ },
187
+ }
188
+ : {}),
189
+ touch(kind, externalId) {
190
+ const found = find(kind, externalId);
191
+ if (!found)
192
+ throw new Error(`the fake blog has no ${kind} ${externalId}`);
193
+ found.updatedAt = clock();
194
+ if (kind === "post")
195
+ found.version = String(found.updatedAt);
196
+ },
197
+ trashed(externalId) {
198
+ const post = postOf(externalId);
199
+ post.status = "trashed";
200
+ post.updatedAt = clock();
201
+ },
202
+ remove(kind, externalId) {
203
+ const list = listOf(kind);
204
+ const at = list.findIndex((one) => one.externalId === externalId);
205
+ if (at < 0)
206
+ throw new Error(`the fake blog has no ${kind} ${externalId}`);
207
+ list.splice(at, 1);
208
+ },
209
+ elapse(externalId) {
210
+ const post = postOf(externalId);
211
+ post.status = "published";
212
+ post.publishedAt = post.scheduledFor ?? clock();
213
+ },
214
+ move(url) {
215
+ channel = { ...channel, url };
216
+ },
217
+ skewed: (ms) => make(ms),
218
+ loseNextAnswer() {
219
+ lose = true;
220
+ },
221
+ });
222
+ return make(options.skew ?? 0);
223
+ };
224
+ /** A small blog: two authors, a tag and a category, and posts in every status but trash. */
225
+ export const exampleContentRows = () => ({
226
+ author: [
227
+ { externalId: "1", name: "Ada Owner", email: "ada@example.com", slug: "ada", updatedAt: T0 },
228
+ { externalId: "2", name: "Bob Writer", email: "bob@example.com", slug: "bob", updatedAt: T0 + 1 },
229
+ ],
230
+ term: [
231
+ { externalId: "tag-7", kind: "tag", name: "Releases", slug: "releases", updatedAt: T0 },
232
+ { externalId: "cat-1", kind: "category", name: "News", slug: "news", updatedAt: T0 },
233
+ ],
234
+ post: [
235
+ {
236
+ externalId: "10",
237
+ type: "post",
238
+ title: "Version 2 is out",
239
+ body: "We shipped **version 2**.",
240
+ status: "published",
241
+ url: "https://blog.example.com/version-2",
242
+ slug: "version-2",
243
+ publishedAt: T0 + 5,
244
+ authors: ["1"],
245
+ terms: ["tag-7", "cat-1"],
246
+ createdAt: T0,
247
+ updatedAt: T0 + 10,
248
+ version: String(T0 + 10),
249
+ },
250
+ {
251
+ externalId: "11",
252
+ type: "post",
253
+ title: "Draft about pricing",
254
+ body: "Prices change in December.",
255
+ status: "draft",
256
+ authors: ["2"],
257
+ terms: [],
258
+ createdAt: T0,
259
+ updatedAt: T0 + 20,
260
+ version: String(T0 + 20),
261
+ },
262
+ {
263
+ externalId: "12",
264
+ type: "page",
265
+ title: "About",
266
+ body: "Who we are.",
267
+ status: "published",
268
+ publishedAt: T0,
269
+ authors: ["1"],
270
+ terms: [],
271
+ createdAt: T0,
272
+ updatedAt: T0 + 30,
273
+ version: String(T0 + 30),
274
+ },
275
+ ],
276
+ });
@@ -0,0 +1,10 @@
1
+ import type { ContractCase } from "../../meetings/index.js";
2
+ import type { MessageStore } from "../../store/store.js";
3
+ import type { AccountKey } from "../../store/types.js";
4
+ /** A fresh, empty store and the content account to sync into it. */
5
+ export interface ContentSyncFixture {
6
+ store: MessageStore;
7
+ account: AccountKey;
8
+ }
9
+ /** What the sync engine does over any store, whatever the source: core runs it, and a CLI may run it over its store. */
10
+ export declare const contentSyncContract: (make: () => ContentSyncFixture | Promise<ContentSyncFixture>) => ContractCase[];