@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,375 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isCliError } from "@wirecat/cli-base";
3
+ import { tagOf } from "../../domain/tags.js";
4
+ import { fold, normalize } from "../normalize.js";
5
+ import { accountPk, findAccountPk } from "./accounts.js";
6
+ import { excerptOf, matchOf } from "./crm-files.js";
7
+ import { addTags, ensureTag } from "./tags.js";
8
+ import { write } from "./transaction.js";
9
+ const MOST = 500;
10
+ const TABLE = {
11
+ author: "content_authors",
12
+ term: "content_terms",
13
+ post: "content_posts",
14
+ };
15
+ const definedOnly = (record) => Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
16
+ const itemOf = (kind, row) => ({
17
+ kind,
18
+ record: JSON.parse(String(row.data)),
19
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at),
20
+ syncedAt: Number(row.synced_at),
21
+ });
22
+ /** The hash a post's text keeps: a change of either part is a new version. */
23
+ export const contentHashOf = (post) => createHash("sha256")
24
+ .update(JSON.stringify([post.title ?? null, post.body ?? null]))
25
+ .digest("hex");
26
+ /** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
27
+ export const resetContentPostWords = (database) => {
28
+ if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'content_post_words'").get())
29
+ return 0;
30
+ return write(database, () => {
31
+ const update = database.prepare("UPDATE content_posts SET normalized_text = ? WHERE id = ?");
32
+ for (const row of database.prepare("SELECT id, title, body, normalized_text FROM content_posts").all()) {
33
+ const normalized = normalize([row.title, row.body].filter(Boolean).join("\n"));
34
+ if (normalized !== row.normalized_text)
35
+ update.run(normalized, Number(row.id));
36
+ }
37
+ database.exec("INSERT INTO content_post_words (content_post_words) VALUES ('delete-all')");
38
+ const { changes } = database
39
+ .prepare("INSERT INTO content_post_words (rowid, normalized_text) SELECT id, normalized_text FROM content_posts " +
40
+ "WHERE normalized_text <> ''")
41
+ .run();
42
+ return Number(changes);
43
+ });
44
+ };
45
+ /**
46
+ * The shared tag a term stands for: by its slug, else its name. A name that is no valid tag, or that the vocabulary
47
+ * review holds back as too close to another, links to none; the owner can add an alias.
48
+ */
49
+ const tagIdOf = (context, term) => {
50
+ const name = tagOf(term.slug ?? "") ?? tagOf(term.name);
51
+ if (name === undefined)
52
+ return null;
53
+ try {
54
+ return ensureTag(context, name).id;
55
+ }
56
+ catch (error) {
57
+ if (isCliError(error))
58
+ return null;
59
+ throw error;
60
+ }
61
+ };
62
+ export const contentStoreOver = (context) => {
63
+ const { database } = context;
64
+ const keepRevision = (postId, row, reason, now) => database
65
+ .prepare("INSERT INTO content_post_revisions (post_id, title, body, status, content_hash, version, reason, created_at) " +
66
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
67
+ .run(postId, (row.title ?? null), (row.body ?? null), String(row.status), String(row.content_hash), (row.version ?? null), reason, now);
68
+ /** A post's tags follow its terms: the ones the source states, never the owner's own. */
69
+ const tagPost = (accountId, postId, terms) => {
70
+ const ids = terms.length
71
+ ? database
72
+ .prepare(`SELECT DISTINCT t.name FROM content_terms ct JOIN canonical_tags t ON t.id = ct.tag_id ` +
73
+ `WHERE ct.account_id = ? AND ct.deleted_at IS NULL AND ct.external_id IN (${terms.map(() => "?").join(", ")})`)
74
+ .all(accountId, ...terms)
75
+ .map((row) => String(row.name))
76
+ : [];
77
+ database
78
+ .prepare("DELETE FROM taggings WHERE taggable_type = 'post' AND taggable_id = ? AND source = 'file' " +
79
+ "AND tag_id NOT IN (SELECT t.id FROM canonical_tags t JOIN json_each(?) j ON j.value = t.name)")
80
+ .run(postId, JSON.stringify(ids));
81
+ if (ids.length)
82
+ addTags(context, { type: "post", id: postId }, ids, "file");
83
+ };
84
+ const savePost = (accountId, record, before, now, reason) => {
85
+ const merged = {
86
+ ...(before ? JSON.parse(String(before.data)) : {}),
87
+ ...definedOnly(record),
88
+ };
89
+ const title = merged.title ?? null;
90
+ const body = merged.body ?? null;
91
+ const hash = contentHashOf(merged);
92
+ if (before && (before.content_hash !== hash || before.status !== merged.status || before.title !== title))
93
+ keepRevision(Number(before.id), before, reason, now);
94
+ const row = database
95
+ .prepare("INSERT INTO content_posts (account_id, external_id, channel_id, type, title, title_folded, body, content_hash, " +
96
+ "status, published_at, scheduled_for, source_created_at, source_updated_at, version, normalized_text, data, " +
97
+ "deleted_at, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
98
+ "ON CONFLICT (account_id, external_id) DO UPDATE SET channel_id = excluded.channel_id, type = excluded.type, " +
99
+ "title = excluded.title, title_folded = excluded.title_folded, body = excluded.body, " +
100
+ "content_hash = excluded.content_hash, status = excluded.status, published_at = excluded.published_at, " +
101
+ "scheduled_for = excluded.scheduled_for, source_created_at = excluded.source_created_at, " +
102
+ "source_updated_at = excluded.source_updated_at, version = excluded.version, " +
103
+ "normalized_text = excluded.normalized_text, data = excluded.data, deleted_at = NULL, " +
104
+ "synced_at = excluded.synced_at RETURNING id")
105
+ .get(accountId, merged.externalId, merged.channel ?? null, merged.type ?? "post", title, fold(title ?? ""), body, hash, merged.status, merged.publishedAt ?? null, merged.scheduledFor ?? null, merged.createdAt ?? null, merged.updatedAt ?? null, merged.version ?? null, normalize([title, body].filter(Boolean).join("\n")), JSON.stringify(merged), now);
106
+ tagPost(accountId, Number(row?.id), merged.terms ?? []);
107
+ };
108
+ const save = (key, kind, records, now, reason) => write(database, () => {
109
+ const accountId = accountPk(context, key);
110
+ const stored = database.prepare(`SELECT * FROM ${TABLE[kind]} WHERE account_id = ? AND external_id = ?`);
111
+ for (const record of records) {
112
+ const before = stored.get(accountId, record.externalId);
113
+ if (kind === "post") {
114
+ savePost(accountId, record, before, now, reason);
115
+ continue;
116
+ }
117
+ const merged = {
118
+ ...(before ? JSON.parse(String(before.data)) : {}),
119
+ ...definedOnly(record),
120
+ };
121
+ if (kind === "author")
122
+ database
123
+ .prepare("INSERT INTO content_authors (account_id, external_id, name, email, data, source_updated_at, deleted_at, " +
124
+ "synced_at) VALUES (?, ?, ?, ?, ?, ?, NULL, ?) ON CONFLICT (account_id, external_id) DO UPDATE SET " +
125
+ "name = excluded.name, email = excluded.email, data = excluded.data, " +
126
+ "source_updated_at = excluded.source_updated_at, deleted_at = NULL, synced_at = excluded.synced_at")
127
+ .run(accountId, merged.externalId, merged.name, merged.email ?? null, JSON.stringify(merged), merged.updatedAt ?? null, now);
128
+ else
129
+ database
130
+ .prepare("INSERT INTO content_terms (account_id, external_id, kind, name, slug, parent_id, tag_id, data, " +
131
+ "source_updated_at, deleted_at, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
132
+ "ON CONFLICT (account_id, external_id) DO UPDATE SET kind = excluded.kind, name = excluded.name, " +
133
+ "slug = excluded.slug, parent_id = excluded.parent_id, tag_id = excluded.tag_id, data = excluded.data, " +
134
+ "source_updated_at = excluded.source_updated_at, deleted_at = NULL, synced_at = excluded.synced_at")
135
+ .run(accountId, merged.externalId, merged.kind, merged.name, merged.slug ?? null, merged.parent ?? null, tagIdOf(context, merged), JSON.stringify(merged), merged.updatedAt ?? null, now);
136
+ }
137
+ return records.length;
138
+ });
139
+ const mark = (accountId, kind, row, now) => {
140
+ if (kind === "post") {
141
+ keepRevision(Number(row.id), row, "deleted", now);
142
+ database
143
+ .prepare("DELETE FROM taggings WHERE taggable_type = 'post' AND taggable_id = ? AND source = 'file'")
144
+ .run(Number(row.id));
145
+ }
146
+ database
147
+ .prepare(`UPDATE ${TABLE[kind]} SET deleted_at = ? WHERE id = ? AND account_id = ?`)
148
+ .run(now, Number(row.id), accountId);
149
+ };
150
+ const unlisted = (key, kind, listed, before) => {
151
+ const accountId = findAccountPk(context, key);
152
+ if (accountId === undefined)
153
+ return [];
154
+ const keep = new Set(listed);
155
+ return database
156
+ .prepare(`SELECT external_id FROM ${TABLE[kind]} WHERE account_id = ? AND deleted_at IS NULL AND synced_at < ?`)
157
+ .all(accountId, before)
158
+ .map((row) => String(row.external_id))
159
+ .filter((id) => !keep.has(id));
160
+ };
161
+ const list = (key, kind, filter = {}) => {
162
+ const accountId = findAccountPk(context, key);
163
+ if (accountId === undefined)
164
+ return { items: [], hasMore: false };
165
+ const limit = Math.min(Math.max(filter.limit ?? 100, 1), MOST);
166
+ const params = [accountId];
167
+ let sql = `SELECT t.* FROM ${TABLE[kind]} t WHERE t.account_id = ? AND t.deleted_at IS NULL`;
168
+ if (kind === "post") {
169
+ if (filter.channel !== undefined) {
170
+ sql += " AND t.channel_id = ?";
171
+ params.push(filter.channel);
172
+ }
173
+ if (filter.statuses?.length) {
174
+ sql += ` AND t.status IN (${filter.statuses.map(() => "?").join(", ")})`;
175
+ params.push(...filter.statuses);
176
+ }
177
+ if (filter.type !== undefined) {
178
+ sql += " AND t.type = ?";
179
+ params.push(filter.type);
180
+ }
181
+ for (const [field, value] of [
182
+ ["terms", filter.term],
183
+ ["authors", filter.author],
184
+ ])
185
+ if (value !== undefined) {
186
+ sql += ` AND EXISTS (SELECT 1 FROM json_each(t.data, '$.${field}') j WHERE j.value = ?)`;
187
+ params.push(value);
188
+ }
189
+ if (filter.since !== undefined) {
190
+ sql += " AND t.published_at >= ?";
191
+ params.push(filter.since);
192
+ }
193
+ if (filter.until !== undefined) {
194
+ sql += " AND t.published_at < ?";
195
+ params.push(filter.until);
196
+ }
197
+ }
198
+ sql += " ORDER BY coalesce(t.source_updated_at, t.synced_at) DESC, t.id DESC LIMIT ? OFFSET ?";
199
+ params.push(limit + 1, filter.offset ?? 0);
200
+ const rows = database.prepare(sql).all(...params);
201
+ return { items: rows.slice(0, limit).map((row) => itemOf(kind, row)), hasMore: rows.length > limit };
202
+ };
203
+ const find = ({ words, anyWord = false, exact = false, accounts, limit, offset = 0 }) => {
204
+ const match = matchOf(words, anyWord, exact);
205
+ if (!match)
206
+ return { items: [], hasMore: false };
207
+ const most = Math.min(Math.max(limit ?? 100, 1), MOST);
208
+ const scoped = accounts?.map((one) => findAccountPk(context, one)).filter((one) => one !== undefined) ?? [];
209
+ if (accounts !== undefined && !scoped.length)
210
+ return { items: [], hasMore: false };
211
+ const params = [match];
212
+ let sql = "SELECT t.*, a.provider, a.external_id AS account FROM content_posts t JOIN accounts a ON a.id = t.account_id " +
213
+ "JOIN (SELECT rowid, rank FROM content_post_words WHERE content_post_words MATCH ?) w ON w.rowid = t.id " +
214
+ "WHERE t.deleted_at IS NULL";
215
+ if (accounts !== undefined) {
216
+ sql += ` AND t.account_id IN (${scoped.map(() => "?").join(", ")})`;
217
+ params.push(...scoped);
218
+ }
219
+ sql += " ORDER BY w.rank, t.source_updated_at DESC, t.id DESC LIMIT ? OFFSET ?";
220
+ params.push(most + 1, offset);
221
+ const rows = database.prepare(sql).all(...params);
222
+ return {
223
+ items: rows.slice(0, most).map((row) => ({
224
+ account: { provider: String(row.provider), account: String(row.account) },
225
+ item: itemOf("post", row),
226
+ excerpt: excerptOf([row.title, row.body].filter(Boolean).join("\n"), words),
227
+ })),
228
+ hasMore: rows.length > most,
229
+ };
230
+ };
231
+ const postId = (key, post) => {
232
+ const accountId = findAccountPk(context, key);
233
+ if (accountId === undefined)
234
+ return undefined;
235
+ const row = database
236
+ .prepare("SELECT id FROM content_posts WHERE account_id = ? AND external_id = ?")
237
+ .get(accountId, post);
238
+ return row ? Number(row.id) : undefined;
239
+ };
240
+ return {
241
+ saveChannels: async (key, channels, now) => write(database, () => {
242
+ const accountId = accountPk(context, key);
243
+ const upsert = database.prepare("INSERT INTO content_channels (account_id, external_id, kind, network, name, url, handle, deleted_at, " +
244
+ "synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?) ON CONFLICT (account_id, external_id) DO UPDATE SET " +
245
+ "kind = excluded.kind, network = excluded.network, name = excluded.name, url = excluded.url, " +
246
+ "handle = excluded.handle, deleted_at = NULL, synced_at = excluded.synced_at");
247
+ for (const one of channels)
248
+ upsert.run(accountId, one.externalId, one.kind, one.network, one.name, one.url ?? null, one.handle ?? null, now);
249
+ return channels.length;
250
+ }),
251
+ channels: async (key) => {
252
+ const accountId = findAccountPk(context, key);
253
+ if (accountId === undefined)
254
+ return [];
255
+ return database
256
+ .prepare("SELECT * FROM content_channels WHERE account_id = ? AND deleted_at IS NULL ORDER BY id")
257
+ .all(accountId)
258
+ .map((row) => ({
259
+ externalId: String(row.external_id),
260
+ kind: String(row.kind),
261
+ network: String(row.network),
262
+ name: String(row.name),
263
+ url: row.url == null ? null : String(row.url),
264
+ handle: row.handle == null ? null : String(row.handle),
265
+ }));
266
+ },
267
+ save: async (key, kind, records, now, options) => save(key, kind, records, now, options?.reason ?? "sync"),
268
+ unlisted: async (key, kind, listed, before) => unlisted(key, kind, listed, before),
269
+ markDeleted: async (key, kind, externalId, now) => {
270
+ const accountId = findAccountPk(context, key);
271
+ if (accountId === undefined)
272
+ return false;
273
+ return write(database, () => {
274
+ const row = database
275
+ .prepare(`SELECT * FROM ${TABLE[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
276
+ .get(accountId, externalId);
277
+ if (!row)
278
+ return false;
279
+ mark(accountId, kind, row, now);
280
+ return true;
281
+ });
282
+ },
283
+ get: async (key, kind, externalId) => {
284
+ const accountId = findAccountPk(context, key);
285
+ if (accountId === undefined)
286
+ return undefined;
287
+ const row = database
288
+ .prepare(`SELECT * FROM ${TABLE[kind]} WHERE account_id = ? AND external_id = ?`)
289
+ .get(accountId, externalId);
290
+ return row ? itemOf(kind, row) : undefined;
291
+ },
292
+ list: async (key, kind, filter) => list(key, kind, filter),
293
+ find: async (search) => find(search),
294
+ count: async (key, kind) => {
295
+ const accountId = findAccountPk(context, key);
296
+ if (accountId === undefined)
297
+ return 0;
298
+ return Number(database
299
+ .prepare(`SELECT count(*) AS n FROM ${TABLE[kind]} WHERE account_id = ? AND deleted_at IS NULL`)
300
+ .get(accountId)?.n ?? 0);
301
+ },
302
+ due: async (key, now) => {
303
+ const accountId = findAccountPk(context, key);
304
+ if (accountId === undefined)
305
+ return [];
306
+ return database
307
+ .prepare("SELECT external_id FROM content_posts WHERE account_id = ? AND deleted_at IS NULL AND status = 'scheduled' " +
308
+ "AND scheduled_for IS NOT NULL AND scheduled_for <= ? ORDER BY synced_at, scheduled_for, id")
309
+ .all(accountId, now)
310
+ .map((row) => String(row.external_id));
311
+ },
312
+ revisions: async (key, post) => {
313
+ const id = postId(key, post);
314
+ if (id === undefined)
315
+ return [];
316
+ return database
317
+ .prepare("SELECT * FROM content_post_revisions WHERE post_id = ? ORDER BY created_at DESC, id DESC")
318
+ .all(id)
319
+ .map((row) => ({
320
+ title: row.title == null ? null : String(row.title),
321
+ body: row.body == null ? null : String(row.body),
322
+ status: String(row.status),
323
+ contentHash: String(row.content_hash),
324
+ version: row.version == null ? null : String(row.version),
325
+ reason: String(row.reason),
326
+ createdAt: Number(row.created_at),
327
+ }));
328
+ },
329
+ saveMetrics: async (key, metrics) => write(database, () => {
330
+ const insert = database.prepare("INSERT INTO content_metrics (post_id, at, views, reactions, comments, shares, clicks, raw) " +
331
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
332
+ let saved = 0;
333
+ for (const one of metrics) {
334
+ const id = postId(key, one.post);
335
+ if (id === undefined)
336
+ continue;
337
+ insert.run(id, one.at, one.views ?? null, one.reactions ?? null, one.comments ?? null, one.shares ?? null, one.clicks ?? null, one.raw === undefined ? null : JSON.stringify(one.raw));
338
+ saved += 1;
339
+ }
340
+ return saved;
341
+ }),
342
+ metrics: async (key, post, limit = 100) => {
343
+ const id = postId(key, post);
344
+ if (id === undefined)
345
+ return [];
346
+ return database
347
+ .prepare("SELECT * FROM content_metrics WHERE post_id = ? ORDER BY at DESC, id DESC LIMIT ?")
348
+ .all(id, Math.min(Math.max(limit, 1), MOST))
349
+ .map((row) => ({
350
+ post,
351
+ at: Number(row.at),
352
+ ...Object.fromEntries(["views", "reactions", "comments", "shares", "clicks"].flatMap((name) => row[name] == null ? [] : [[name, Number(row[name])]])),
353
+ ...(row.raw == null ? {} : { raw: JSON.parse(String(row.raw)) }),
354
+ }));
355
+ },
356
+ people: async (key, authors) => {
357
+ const accountId = findAccountPk(context, key);
358
+ if (accountId === undefined || authors.length === 0)
359
+ return [];
360
+ return database
361
+ .prepare("SELECT u.external_id AS author, p.id AS person, p.name AS name FROM content_authors u " +
362
+ "JOIN identities i ON i.email IS NOT NULL AND lower(i.email) = lower(u.email) " +
363
+ "JOIN identity_links l ON l.identity_id = i.id JOIN persons p ON p.id = l.person_id " +
364
+ `WHERE u.account_id = ? AND u.external_id IN (${authors.map(() => "?").join(", ")}) ` +
365
+ // Two persons behind one address say nothing about which one this author is.
366
+ "GROUP BY u.external_id HAVING count(DISTINCT p.id) = 1 ORDER BY u.external_id")
367
+ .all(accountId, ...authors)
368
+ .map((row) => ({
369
+ author: String(row.author),
370
+ person: `person:${String(row.person)}`,
371
+ name: row.name == null ? null : String(row.name),
372
+ }));
373
+ },
374
+ };
375
+ };
@@ -42,6 +42,7 @@ export declare const ENTITY_TABLES: {
42
42
  readonly message: "messages";
43
43
  readonly note: "notes";
44
44
  readonly place: "places";
45
+ readonly post: "content_posts";
45
46
  readonly tag: "canonical_tags";
46
47
  readonly task: "tasks";
47
48
  };
@@ -29,6 +29,7 @@ export const ENTITY_TABLES = {
29
29
  message: "messages",
30
30
  note: "notes",
31
31
  place: "places",
32
+ post: "content_posts",
32
33
  tag: "canonical_tags",
33
34
  task: "tasks",
34
35
  };
@@ -138,6 +138,8 @@ export const MANIFEST = [
138
138
  { name: "20261117015457_version-69-conversation-readiness-triggers", version: 69, minCompatible: 56 },
139
139
  { name: "20261117211410_version-70-tracker-items", version: 70, minCompatible: 56 },
140
140
  { name: "20261117211414_version-70-tracker-item-words", version: 70, minCompatible: 56 },
141
+ { name: "20261118230213_version-71-content", version: 71, minCompatible: 56 },
142
+ { name: "20261118230214_version-71-content-words", version: 71, minCompatible: 56 },
141
143
  ];
142
144
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
143
145
  const migrations = [];
@@ -1398,5 +1398,31 @@ export const GENERATED = [
1398
1398
  "CREATE TRIGGER tracker_item_words_au AFTER UPDATE OF normalized_text ON tracker_items\n WHEN old.normalized_text IS NOT new.normalized_text BEGIN\n DELETE FROM tracker_item_words WHERE rowid = old.id;\n INSERT INTO tracker_item_words (rowid, normalized_text)\n SELECT new.id, new.normalized_text WHERE new.normalized_text <> '';\nEND;",
1399
1399
  "CREATE TRIGGER tracker_item_words_ad AFTER DELETE ON tracker_items BEGIN\n DELETE FROM tracker_item_words WHERE rowid = old.id;\nEND;"
1400
1400
  ]
1401
+ },
1402
+ {
1403
+ "name": "20261118230213_version-71-content",
1404
+ "statements": [
1405
+ "CREATE TABLE `content_authors` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`external_id` text NOT NULL,\n\t`name` text NOT NULL,\n\t`email` text,\n\t`data` text NOT NULL,\n\t`source_updated_at` integer,\n\t`deleted_at` integer,\n\t`synced_at` integer NOT NULL,\n\tCONSTRAINT `fk_content_authors_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `content_authors_account_id_external_id_unique` UNIQUE(`account_id`,`external_id`)\n);",
1406
+ "CREATE TABLE `content_channels` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`external_id` text NOT NULL,\n\t`kind` text NOT NULL,\n\t`network` text NOT NULL,\n\t`name` text NOT NULL,\n\t`url` text,\n\t`handle` text,\n\t`deleted_at` integer,\n\t`synced_at` integer NOT NULL,\n\tCONSTRAINT `fk_content_channels_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `content_channels_account_id_external_id_unique` UNIQUE(`account_id`,`external_id`)\n);",
1407
+ "CREATE TABLE `content_metrics` (\n\t`id` integer PRIMARY KEY,\n\t`post_id` integer NOT NULL,\n\t`at` integer NOT NULL,\n\t`views` integer,\n\t`reactions` integer,\n\t`comments` integer,\n\t`shares` integer,\n\t`clicks` integer,\n\t`raw` text,\n\tCONSTRAINT `fk_content_metrics_post_id_content_posts_id_fk` FOREIGN KEY (`post_id`) REFERENCES `content_posts`(`id`)\n);",
1408
+ "CREATE TABLE `content_post_revisions` (\n\t`id` integer PRIMARY KEY,\n\t`post_id` integer NOT NULL,\n\t`title` text,\n\t`body` text,\n\t`status` text NOT NULL,\n\t`content_hash` text NOT NULL,\n\t`version` text,\n\t`reason` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\tCONSTRAINT `fk_content_post_revisions_post_id_content_posts_id_fk` FOREIGN KEY (`post_id`) REFERENCES `content_posts`(`id`)\n);",
1409
+ "CREATE TABLE `content_posts` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`external_id` text NOT NULL,\n\t`channel_id` text,\n\t`type` text NOT NULL,\n\t`title` text,\n\t`title_folded` text NOT NULL,\n\t`body` text,\n\t`content_hash` text NOT NULL,\n\t`status` text NOT NULL,\n\t`published_at` integer,\n\t`scheduled_for` integer,\n\t`source_created_at` integer,\n\t`source_updated_at` integer,\n\t`version` text,\n\t`normalized_text` text NOT NULL,\n\t`data` text NOT NULL,\n\t`deleted_at` integer,\n\t`synced_at` integer NOT NULL,\n\tCONSTRAINT `fk_content_posts_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `content_posts_account_id_external_id_unique` UNIQUE(`account_id`,`external_id`)\n);",
1410
+ "CREATE TABLE `content_terms` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`external_id` text NOT NULL,\n\t`kind` text NOT NULL,\n\t`name` text NOT NULL,\n\t`slug` text,\n\t`parent_id` text,\n\t`tag_id` integer,\n\t`data` text NOT NULL,\n\t`source_updated_at` integer,\n\t`deleted_at` integer,\n\t`synced_at` integer NOT NULL,\n\tCONSTRAINT `fk_content_terms_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `fk_content_terms_tag_id_canonical_tags_id_fk` FOREIGN KEY (`tag_id`) REFERENCES `canonical_tags`(`id`),\n\tCONSTRAINT `content_terms_account_id_external_id_unique` UNIQUE(`account_id`,`external_id`)\n);",
1411
+ "CREATE INDEX `content_metrics_by_post_id_at` ON `content_metrics` (`post_id`,`at`);",
1412
+ "CREATE INDEX `content_post_revisions_by_post_id_created_at` ON `content_post_revisions` (`post_id`,`created_at`);",
1413
+ "CREATE INDEX `content_posts_by_account_id_status` ON `content_posts` (`account_id`,`status`);",
1414
+ "CREATE INDEX `content_posts_by_account_id_published_at` ON `content_posts` (`account_id`,`published_at`);",
1415
+ "CREATE INDEX `content_terms_by_tag_id` ON `content_terms` (`tag_id`);"
1416
+ ]
1417
+ },
1418
+ {
1419
+ "name": "20261118230214_version-71-content-words",
1420
+ "statements": [
1421
+ "-- Words of a post's title and text, rowid = content_posts.id.\nCREATE VIRTUAL TABLE content_post_words USING fts5(\n normalized_text,\n content = '', contentless_delete = 1,\n tokenize = 'unicode61 remove_diacritics 2', prefix = '3');",
1422
+ "CREATE VIRTUAL TABLE content_post_words_vocab USING fts5vocab(content_post_words, 'col');",
1423
+ "CREATE TRIGGER content_post_words_ai AFTER INSERT ON content_posts WHEN new.normalized_text <> '' BEGIN\n INSERT INTO content_post_words (rowid, normalized_text) VALUES (new.id, new.normalized_text);\nEND;",
1424
+ "CREATE TRIGGER content_post_words_au AFTER UPDATE OF normalized_text ON content_posts\n WHEN old.normalized_text IS NOT new.normalized_text BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n INSERT INTO content_post_words (rowid, normalized_text)\n SELECT new.id, new.normalized_text WHERE new.normalized_text <> '';\nEND;",
1425
+ "-- Taggings are polymorphic, with no foreign key: a post row that goes takes its tags along.\nCREATE TRIGGER content_post_words_ad AFTER DELETE ON content_posts BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n DELETE FROM taggings WHERE taggable_type = 'post' AND taggable_id = old.id;\nEND;"
1426
+ ]
1401
1427
  }
1402
1428
  ];