@wirecat/cli-core 1.0.0 → 1.1.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 (72) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/THIRD_PARTY_NOTICES +43 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/domain-lists-command.d.ts +16 -0
  6. package/dist/cli/domain-lists-command.js +88 -0
  7. package/dist/cli/index.d.ts +4 -3
  8. package/dist/cli/index.js +3 -2
  9. package/dist/cli/model-catalogue-command.d.ts +6 -0
  10. package/dist/cli/model-catalogue-command.js +1 -1
  11. package/dist/cli/oauth-session.d.ts +38 -4
  12. package/dist/cli/oauth-session.js +66 -22
  13. package/dist/cli/shared-command-exports.d.ts +2 -0
  14. package/dist/cli/shared-command-exports.js +3 -0
  15. package/dist/cli/token-session.d.ts +9 -0
  16. package/dist/cli/token-session.js +29 -2
  17. package/dist/domain/domain-lists.d.ts +86 -0
  18. package/dist/domain/domain-lists.js +110 -0
  19. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  20. package/dist/domain/free-mail-domains.generated.js +4 -0
  21. package/dist/domain/organization-sectors.d.ts +9 -3
  22. package/dist/domain/organization-sectors.generated.d.ts +1 -0
  23. package/dist/domain/organization-sectors.generated.js +1 -0
  24. package/dist/domain/organization-sectors.js +16 -3
  25. package/dist/domain/person-kinds.d.ts +6 -1
  26. package/dist/domain/person-kinds.js +5 -0
  27. package/dist/entities/domain-list.d.ts +27 -0
  28. package/dist/entities/domain-list.js +28 -0
  29. package/dist/entities/index.d.ts +20 -2
  30. package/dist/entities/index.js +3 -1
  31. package/dist/entities/knowledge-lists.d.ts +1 -1
  32. package/dist/errors/reasons.js +4 -2
  33. package/dist/mail/mail-types.d.ts +48 -0
  34. package/dist/mail/mail-types.js +218 -0
  35. package/dist/oauth/index.d.ts +1 -1
  36. package/dist/oauth/storage.d.ts +10 -2
  37. package/dist/oauth/storage.js +23 -9
  38. package/dist/services/domain-lists-download.d.ts +26 -0
  39. package/dist/services/domain-lists-download.js +155 -0
  40. package/dist/services/metadata.d.ts +1 -1
  41. package/dist/store/areas.d.ts +1 -1
  42. package/dist/store/index.d.ts +2 -2
  43. package/dist/store/index.js +1 -1
  44. package/dist/store/people.d.ts +18 -9
  45. package/dist/store/people.js +8 -7
  46. package/dist/store/sqlite/accounts.js +3 -1
  47. package/dist/store/sqlite/domain-organizations.d.ts +7 -4
  48. package/dist/store/sqlite/domain-organizations.js +94 -36
  49. package/dist/store/sqlite/email-types.d.ts +79 -0
  50. package/dist/store/sqlite/email-types.js +261 -0
  51. package/dist/store/sqlite/emails.d.ts +11 -2
  52. package/dist/store/sqlite/emails.js +18 -7
  53. package/dist/store/sqlite/identities.d.ts +4 -1
  54. package/dist/store/sqlite/identities.js +11 -2
  55. package/dist/store/sqlite/identity-rekey.js +2 -0
  56. package/dist/store/sqlite/manifest.js +4 -0
  57. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  58. package/dist/store/sqlite/merged-persons.js +5 -3
  59. package/dist/store/sqlite/migrations.generated.js +56 -0
  60. package/dist/store/sqlite/people-list.d.ts +1 -6
  61. package/dist/store/sqlite/people-list.js +38 -32
  62. package/dist/store/sqlite/person-links.js +13 -3
  63. package/dist/store/sqlite/person-match-scan.js +5 -2
  64. package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
  65. package/dist/store/sqlite/schema/sender-bots.js +9 -1
  66. package/dist/store/sqlite/schema.d.ts +49 -1
  67. package/dist/store/sqlite/schema.js +6 -1
  68. package/dist/store/sqlite/sender-bots.d.ts +80 -15
  69. package/dist/store/sqlite/sender-bots.js +378 -136
  70. package/dist/store/sqlite/sender-signals.d.ts +11 -4
  71. package/dist/store/sqlite/sender-signals.js +14 -10
  72. package/package.json +2 -2
@@ -1,16 +1,124 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { releaseDomainHolds } from "./domain-organizations.js";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
4
+ import { fold } from "../normalize.js";
5
+ import { groupByDomain, releaseDomainHolds } from "./domain-organizations.js";
3
6
  import { currentPerson } from "./merged-persons.js";
4
- import { isOwner, mergePerson, move, recordOf, renameAfterLeaving, required, unlinkIdentity } from "./person-links.js";
5
- import { write } from "./transaction.js";
6
- export const SENDER_BOT_PREFIX = "sender-bot:";
7
- export const senderBotsOf = (database) => new Map(database
8
- .prepare("SELECT id, person_id, author, name FROM sender_bots")
9
- .all()
10
- .map((row) => [
11
- Number(row.person_id),
12
- { id: Number(row.id), author: row.author, name: row.name == null ? null : String(row.name) },
13
- ]));
7
+ import { isOwner, mergePerson, move, recordOf, renameAfterLeaving } from "./person-links.js";
8
+ import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
9
+ import { read, write } from "./transaction.js";
10
+ const MIN_QUERY = 3;
11
+ const HOLDS = "EXISTS (SELECT 1 FROM sender_bot_identities h WHERE h.bot_id = b.id)";
12
+ const SHOWN = "coalesce(b.name, (SELECT coalesce(i.name, i.username, i.external_id) FROM sender_bot_identities s " +
13
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id ORDER BY i.name IS NULL, i.id LIMIT 1))";
14
+ const refOf = (side) => side.person !== undefined
15
+ ? `person:${side.person}`
16
+ : side.bot !== undefined
17
+ ? `${SENDER_BOT_PREFIX}${side.bot}`
18
+ : null;
19
+ const holderOf = (database, identity) => {
20
+ const linked = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
21
+ if (linked !== undefined)
22
+ return { person: Number(linked.person_id) };
23
+ const held = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
24
+ return held === undefined ? {} : { bot: Number(held.bot_id) };
25
+ };
26
+ const identitiesOf = (database, person) => database
27
+ .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
28
+ .all(person)
29
+ .map((row) => Number(row.identity_id));
30
+ const botIdentitiesOf = (database, bot) => database
31
+ .prepare("SELECT identity_id FROM sender_bot_identities WHERE bot_id = ? ORDER BY identity_id")
32
+ .all(bot)
33
+ .map((row) => Number(row.identity_id));
34
+ const logMove = (database, identity, from, to, { author, reason, at }) => database
35
+ .prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, " +
36
+ "reason, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
37
+ .run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
38
+ /** `person_id` only keeps builds before version 75 from reading the bot as a person: a negative one names none. */
39
+ const createBot = (database, { author, reason, at }, name = null) => Number(database
40
+ .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) " +
41
+ "VALUES ((SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots), ?, ?, ?, ?, ?) RETURNING id")
42
+ .get(name, author, reason, at, at)?.id);
43
+ /** A person every identity left for a bot is stored as a merge's emptied person is: no list shows them. */
44
+ const retireEmptied = (database, people) => {
45
+ const retire = database.prepare("UPDATE persons SET kind = 'merged' WHERE id = ? AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?)");
46
+ for (const person of people)
47
+ retire.run(person, person);
48
+ };
49
+ /**
50
+ * Moves identities to a bot, off a person or another bot, each move logged. Answers the people each left, and which
51
+ * identities. The caller holds the write lock.
52
+ */
53
+ const intoBot = (database, identities, bot, log) => {
54
+ const left = new Map();
55
+ for (const identity of identities) {
56
+ const from = holderOf(database, identity);
57
+ if (from.bot === bot)
58
+ continue;
59
+ if (from.person !== undefined) {
60
+ database.prepare("DELETE FROM identity_links WHERE identity_id = ?").run(identity);
61
+ left.set(from.person, [...(left.get(from.person) ?? []), identity]);
62
+ }
63
+ if (from.bot !== undefined)
64
+ database.prepare("UPDATE sender_bot_identities SET bot_id = ? WHERE identity_id = ?").run(bot, identity);
65
+ else
66
+ database
67
+ .prepare("INSERT INTO sender_bot_identities (identity_id, bot_id, created_at) VALUES (?, ?, ?)")
68
+ .run(identity, bot, log.at);
69
+ logMove(database, identity, from, { bot }, log);
70
+ }
71
+ retireEmptied(database, left.keys());
72
+ return left;
73
+ };
74
+ /** The person an identity last left for a bot, as that person is now; `undefined` when it came from none. */
75
+ const originOf = (database, identity) => {
76
+ const row = database
77
+ .prepare("SELECT m.from_person_id FROM sender_bot_moves m JOIN persons p ON p.id = m.from_person_id " +
78
+ "WHERE m.identity_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
79
+ .get(identity);
80
+ return row === undefined ? undefined : currentPerson(database, Number(row.from_person_id));
81
+ };
82
+ const newPerson = (database, identity, at) => Number(database
83
+ .prepare("INSERT INTO persons (name, created_at, updated_at) VALUES ((SELECT name FROM identities WHERE id = ?), ?, ?) " +
84
+ "RETURNING id")
85
+ .get(identity, at, at)?.id);
86
+ /**
87
+ * Gives a bot's identities to a person: `to`, else the person each came from, else a person row of its own. The bot
88
+ * goes with its last identity. Answers the person each went to. The caller holds the write lock.
89
+ */
90
+ const outOfBot = (database, identities, to, log) => {
91
+ const by = log.author === "owner" ? "owner" : "rules";
92
+ const went = new Map();
93
+ for (const identity of identities) {
94
+ const from = holderOf(database, identity);
95
+ if (from.bot === undefined)
96
+ continue;
97
+ database.prepare("DELETE FROM sender_bot_identities WHERE identity_id = ?").run(identity);
98
+ const target = to ?? originOf(database, identity) ?? newPerson(database, identity, log.at);
99
+ database
100
+ .prepare("INSERT INTO identity_links (identity_id, person_id, method, confidence, created_at, author, updated_at) " +
101
+ "VALUES (?, ?, 'bot', 1, ?, ?, ?)")
102
+ .run(identity, target, log.at, by, log.at);
103
+ database
104
+ .prepare("INSERT INTO identity_link_events (identity_id, from_person_id, to_person_id, method, created_at, author) " +
105
+ "VALUES (?, NULL, ?, 'bot', ?, ?)")
106
+ .run(identity, target, log.at, by);
107
+ logMove(database, identity, from, { person: target }, log);
108
+ went.set(identity, target);
109
+ }
110
+ return went;
111
+ };
112
+ /**
113
+ * The source re-keyed `from` onto `to`, both stored: a bot holding `from` takes `to` from its person, since one
114
+ * account is one program. The person it leaves is hidden as `intoBot` hides one. The caller holds the write lock.
115
+ */
116
+ export const rekeyIntoBot = (database, from, to, at) => {
117
+ const bot = holderOf(database, from).bot;
118
+ if (bot === undefined || holderOf(database, to).bot !== undefined)
119
+ return;
120
+ intoBot(database, [to], bot, { author: "rules", reason: "the source re-keyed the identity", at });
121
+ };
14
122
  /** People holding an identity the owner last moved to a person, or kept as one: no rule makes them a bot. */
15
123
  export const ownerPeopleOf = (database) => new Set(database
16
124
  .prepare("SELECT DISTINCT l.person_id AS person FROM sender_bot_moves m JOIN identity_links l ON l.identity_id = m.identity_id " +
@@ -18,172 +126,306 @@ export const ownerPeopleOf = (database) => new Set(database
18
126
  "AND m.id = (SELECT max(id) FROM sender_bot_moves WHERE identity_id = m.identity_id)")
19
127
  .all()
20
128
  .map((row) => Number(row.person)));
129
+ /** A person every identity left for a bot is no one's assignee: the bot has no tasks. */
21
130
  export const refuseBotAssignee = (database, person) => {
22
- if (database.prepare("SELECT 1 FROM sender_bots WHERE person_id = ?").get(person) !== undefined)
23
- throw new CliError("validation_error", `person:${person} is a sender bot, which is no one's assignee`, {
24
- reason: "sender-bot.assignee",
25
- });
131
+ const bot = database
132
+ .prepare("SELECT m.to_bot_id FROM sender_bot_moves m WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL " +
133
+ "AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?) ORDER BY m.id DESC LIMIT 1")
134
+ .get(person, person);
135
+ if (bot !== undefined)
136
+ throw new CliError("validation_error", `person:${person} moved to ${SENDER_BOT_PREFIX}${bot.to_bot_id}, which is no one's assignee`, { reason: "sender-bot.assignee" });
26
137
  };
27
- const identitiesOf = (database, person) => database
28
- .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
29
- .all(person)
30
- .map((row) => Number(row.identity_id));
31
- const logMoves = (database, identities, from, to, { author, reason, at }) => {
32
- const row = database.prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, reason, " +
33
- "created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
34
- for (const identity of identities)
35
- row.run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
36
- };
37
- const createBot = (database, person, { author, reason, at, name = null }) => Number(database
38
- .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) " +
39
- "RETURNING id")
40
- .get(person, name, author, reason, at, at)?.id);
41
- /** A rule's move of a whole person to a bot, or of a rule's bot back to a person; the caller holds the write lock. */
42
- export const ruleMove = (database, person, to, reason, at) => {
43
- const identities = identitiesOf(database, person);
44
- const options = { author: "rules", reason, at };
45
- if (to === "bot") {
46
- const bot = createBot(database, person, options);
47
- logMoves(database, identities, { person }, { bot }, options);
48
- return;
138
+ /** A rule's move of a whole person to a new bot; answers the bot. The caller holds the write lock. */
139
+ export const ruleToBot = (database, person, reason, at) => {
140
+ const log = { author: "rules", reason, at };
141
+ const bot = createBot(database, log);
142
+ intoBot(database, identitiesOf(database, person), bot, log);
143
+ return bot;
144
+ };
145
+ /**
146
+ * A rule's bot the owner wrote to, by mail or in a private chat both wrote in, goes back to the people its identities
147
+ * came from; a messenger's own bot flag holds anyway. The caller holds the write lock.
148
+ */
149
+ export const ruleBotsBack = (database, at) => {
150
+ const back = database
151
+ .prepare("SELECT b.id FROM sender_bots b WHERE b.author = 'rules' AND NOT EXISTS (SELECT 1 FROM sender_bot_identities s " +
152
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id AND i.bot = 1) " +
153
+ "AND EXISTS (SELECT 1 FROM sender_bot_identities s WHERE s.bot_id = b.id AND (" +
154
+ "EXISTS (SELECT 1 FROM email_recipients r JOIN emails e ON e.id = r.email_id WHERE r.identity_id = s.identity_id " +
155
+ "AND e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1) OR " +
156
+ "EXISTS (SELECT 1 FROM messages m JOIN chats c ON c.id = m.chat_id WHERE m.sender_identity_id = s.identity_id " +
157
+ "AND m.outgoing IS NOT 1 AND c.kind = 'dialog' AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id " +
158
+ "AND o.outgoing = 1))))")
159
+ .all();
160
+ const log = { author: "rules", reason: "the owner wrote to it", at };
161
+ for (const row of back)
162
+ outOfBot(database, botIdentitiesOf(database, Number(row.id)), undefined, log);
163
+ };
164
+ /** Whether a build before version 75 sorted a bot onto a person row since the last kept list. */
165
+ export const hasLegacyBots = (database) => database.prepare("SELECT 1 FROM sender_bots WHERE person_id > 0 LIMIT 1").get() !== undefined;
166
+ /**
167
+ * A bot a build before version 75 sorted after the upgrade holds its person row's identities there: they move to the
168
+ * bot, as the upgrade moved the others. The caller holds the write lock.
169
+ */
170
+ export const settleLegacyBots = (database, at) => {
171
+ const legacy = database.prepare("SELECT id, person_id, author, reason FROM sender_bots WHERE person_id > 0").all();
172
+ for (const row of legacy) {
173
+ const bot = Number(row.id);
174
+ const identities = identitiesOf(database, Number(row.person_id));
175
+ database
176
+ .prepare("UPDATE sender_bots SET person_id = (SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots) WHERE id = ?")
177
+ .run(bot);
178
+ const log = { author: row.author, reason: "sorted by a build before store version 75", at };
179
+ intoBot(database, identities, bot, log);
180
+ if (identities.length === 0)
181
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
49
182
  }
50
- const held = database.prepare("SELECT id FROM sender_bots WHERE person_id = ? AND author = 'rules'").get(person);
51
- if (held === undefined)
52
- return;
53
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(Number(held.id));
54
- logMoves(database, identities, { bot: Number(held.id) }, { person }, options);
55
183
  };
56
- const botRow = (database, ref) => {
184
+ const botIdOf = (database, ref) => {
57
185
  const id = ref.startsWith(SENDER_BOT_PREFIX) ? ref.slice(SENDER_BOT_PREFIX.length) : "";
58
186
  const row = /^[1-9]\d*$/.test(id)
59
- ? database.prepare("SELECT id, person_id FROM sender_bots WHERE id = ?").get(Number(id))
187
+ ? database.prepare("SELECT id FROM sender_bots WHERE id = ?").get(Number(id))
60
188
  : undefined;
61
189
  if (row === undefined)
62
190
  throw new CliError("not_found", `no ${ref} in the store`, { reason: "sender-bot.not-found", reference: ref });
63
- return { id: Number(row.id), person: Number(row.person_id) };
191
+ return Number(row.id);
64
192
  };
65
- const botOfPerson = (database, person) => {
66
- const row = database.prepare("SELECT id FROM sender_bots WHERE person_id = ?").get(person);
67
- return row === undefined ? undefined : Number(row.id);
68
- };
69
- const personRow = (database, ref) => {
193
+ const personIdOf = (database, ref) => {
70
194
  const uid = ref.startsWith("person:") ? ref.slice("person:".length) : "";
71
195
  const found = /^[1-9]\d*$/.test(uid) ? database.prepare("SELECT id FROM persons WHERE id = ?").get(uid) : undefined;
72
196
  if (found === undefined)
73
197
  throw new CliError("not_found", `no ${ref} in the store`, { reference: ref });
74
198
  return currentPerson(database, Number(found.id));
75
199
  };
76
- /** What a move names: a whole person or bot, or one identity and the person it sits on. */
77
- const subjectOf = (context, subject) => {
78
- const { database } = context;
79
- if (typeof subject !== "string") {
80
- const found = required(context, subject);
81
- const alone = identitiesOf(database, found.personPk).length === 1;
82
- return alone ? { person: found.personPk } : { person: found.personPk, identity: found.pk, ref: subject };
200
+ const identityIdOf = (database, { provider, id }) => {
201
+ const row = database.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?").get(provider, id);
202
+ if (row === undefined)
203
+ throw new CliError("not_found", `no ${provider} identity ${id} in the store`);
204
+ return Number(row.id);
205
+ };
206
+ /** What a move names: a person's identities, a bot's, or one identity. */
207
+ const subjectOf = (database, subject) => {
208
+ if (typeof subject !== "string")
209
+ return { identities: [identityIdOf(database, subject)] };
210
+ if (subject.startsWith(SENDER_BOT_PREFIX)) {
211
+ const bot = botIdOf(database, subject);
212
+ return { bot, identities: botIdentitiesOf(database, bot) };
83
213
  }
84
- if (subject.startsWith(SENDER_BOT_PREFIX))
85
- return { person: botRow(database, subject).person };
86
- return { person: personRow(database, subject) };
87
- };
88
- const senderBotOf = (database, id) => {
89
- const row = database.prepare("SELECT person_id, name, author, reason FROM sender_bots WHERE id = ?").get(id);
90
- return {
91
- bot: `${SENDER_BOT_PREFIX}${id}`,
92
- person: `person:${Number(row?.person_id)}`,
93
- name: row?.name == null ? null : String(row.name),
94
- author: row?.author,
95
- reason: row?.reason == null ? null : String(row.reason),
96
- };
214
+ const person = personIdOf(database, subject);
215
+ const identities = identitiesOf(database, person);
216
+ const took = identities.length === 0 ? botThatTook(database, person) : undefined;
217
+ return took === undefined ? { person, identities } : { bot: took, identities: botIdentitiesOf(database, took) };
218
+ };
219
+ /** The bot that took every identity of a person, so their `person:` ref still names it. */
220
+ const botThatTook = (database, person) => {
221
+ const row = database
222
+ .prepare("SELECT s.bot_id FROM sender_bot_moves m JOIN sender_bot_identities s ON s.identity_id = m.identity_id " +
223
+ "WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
224
+ .get(person);
225
+ return row === undefined ? undefined : Number(row.bot_id);
97
226
  };
227
+ const botsOf = (database, ids) => {
228
+ if (ids.length === 0)
229
+ return [];
230
+ const json = JSON.stringify(ids);
231
+ const rows = new Map(database
232
+ .prepare("SELECT id, name, organization_id, author, reason FROM sender_bots WHERE id IN (SELECT value FROM json_each(?))")
233
+ .all(json)
234
+ .map((row) => [Number(row.id), row]));
235
+ const identities = new Map();
236
+ for (const row of database
237
+ .prepare("SELECT s.bot_id, i.provider, i.external_id, i.name, i.username, i.phone FROM sender_bot_identities s " +
238
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) ORDER BY i.id")
239
+ .all(json)) {
240
+ const held = identities.get(Number(row.bot_id)) ?? [];
241
+ held.push({
242
+ provider: String(row.provider),
243
+ id: String(row.external_id),
244
+ name: row.name == null ? null : String(row.name),
245
+ username: row.username == null ? null : String(row.username),
246
+ phone: row.phone == null ? null : String(row.phone),
247
+ });
248
+ identities.set(Number(row.bot_id), held);
249
+ }
250
+ const counts = new Map();
251
+ for (const row of database
252
+ .prepare("SELECT s.bot_id AS bot, count(*) AS n, max(m.sent_at) AS at FROM sender_bot_identities s " +
253
+ "JOIN messages m ON m.sender_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
254
+ "AND m.deleted_at IS NULL AND m.outgoing IS NOT 1 GROUP BY 1 UNION ALL " +
255
+ "SELECT s.bot_id, count(*), max(coalesce(e.sent_at, e.received_at)) FROM sender_bot_identities s " +
256
+ "JOIN emails e ON e.from_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
257
+ "AND e.deleted_at IS NULL AND e.outgoing IS NOT 1 GROUP BY 1")
258
+ .all(json, json)) {
259
+ const was = counts.get(Number(row.bot)) ?? { n: 0, at: null };
260
+ const at = row.at == null ? was.at : Math.max(Number(row.at), was.at ?? 0);
261
+ counts.set(Number(row.bot), { n: was.n + Number(row.n), at });
262
+ }
263
+ const sent = sentMailOf(database, ids, "bot");
264
+ return ids.flatMap((id) => {
265
+ const row = rows.get(id);
266
+ if (row === undefined)
267
+ return [];
268
+ const held = identities.get(id) ?? [];
269
+ const first = held.find((one) => one.name !== null) ?? held[0];
270
+ const emails = held.flatMap((one) => (one.provider === "email" ? [one.id] : []));
271
+ const name = row.name == null ? null : String(row.name);
272
+ const counted = counts.get(id);
273
+ return [
274
+ {
275
+ bot: `${SENDER_BOT_PREFIX}${id}`,
276
+ name,
277
+ displayName: displayName(name, {
278
+ name: first?.name ?? null,
279
+ username: first?.username ?? null,
280
+ phone: first?.phone ?? null,
281
+ email: emails[0] ?? null,
282
+ }),
283
+ organization: row.organization_id == null ? null : `organization:${Number(row.organization_id)}`,
284
+ author: row.author,
285
+ reason: row.reason == null ? null : String(row.reason),
286
+ identities: held.map(({ phone: _, ...one }) => one),
287
+ messagesFrom: counted?.n ?? 0,
288
+ lastContact: counted?.at == null ? null : new Date(counted.at).toISOString(),
289
+ ...senderSignalsOf(sent.get(id) ?? [], { addresses: emails, ownerWrote: false, chatted: false }),
290
+ },
291
+ ];
292
+ });
293
+ };
294
+ const movesOf = (database, bot) => database
295
+ .prepare("SELECT m.*, i.provider, i.external_id FROM sender_bot_moves m JOIN identities i ON i.id = m.identity_id " +
296
+ "WHERE m.from_bot_id = ? OR m.to_bot_id = ? ORDER BY m.id")
297
+ .all(bot, bot)
298
+ .map((row) => ({
299
+ identity: { provider: String(row.provider), id: String(row.external_id) },
300
+ from: refOf({
301
+ ...(row.from_person_id == null ? {} : { person: Number(row.from_person_id) }),
302
+ ...(row.from_bot_id == null ? {} : { bot: Number(row.from_bot_id) }),
303
+ }),
304
+ to: refOf({
305
+ ...(row.to_person_id == null ? {} : { person: Number(row.to_person_id) }),
306
+ ...(row.to_bot_id == null ? {} : { bot: Number(row.to_bot_id) }),
307
+ }),
308
+ author: row.author,
309
+ reason: row.reason == null ? null : String(row.reason),
310
+ at: new Date(Number(row.created_at)).toISOString(),
311
+ }));
312
+ const detailsOf = (database, bot) => {
313
+ const [found] = botsOf(database, [bot]);
314
+ if (found === undefined)
315
+ throw new CliError("not_found", `no ${SENDER_BOT_PREFIX}${bot} in the store`, { reason: "sender-bot.not-found" });
316
+ return { ...found, moves: movesOf(database, bot) };
317
+ };
318
+ /** The sender bots, by name; a bot a build before version 75 sorted shows once a list has settled it. */
319
+ export const listBots = (database, options) => {
320
+ const { limit, offset = 0 } = options;
321
+ const where = [HOLDS];
322
+ const params = [];
323
+ if (options.query !== undefined) {
324
+ const text = options.query.trim();
325
+ if (text.length < MIN_QUERY)
326
+ throw new CliError("validation_error", `a bots search takes at least ${MIN_QUERY} characters, got "${options.query}"`, { reason: "query.short-text" });
327
+ const like = (form) => `%${form.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
328
+ where.push("(b.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM sender_bot_identities s JOIN identities i ON " +
329
+ "i.id = s.identity_id WHERE s.bot_id = b.id AND (i.name_folded LIKE ? ESCAPE '\\' " +
330
+ "OR i.external_id LIKE ? ESCAPE '\\' OR i.username LIKE ? ESCAPE '\\')))");
331
+ params.push(like(text), like(fold(text)), like(text), like(text));
332
+ }
333
+ if (options.organization !== undefined) {
334
+ const id = options.organization.startsWith("organization:")
335
+ ? options.organization.slice("organization:".length)
336
+ : "";
337
+ if (!/^[1-9]\d*$/.test(id))
338
+ throw new CliError("validation_error", `an organization is organization:<id>, got "${options.organization}"`);
339
+ where.push("b.organization_id = ?");
340
+ params.push(Number(id));
341
+ }
342
+ return read(database, () => {
343
+ const filter = where.join(" AND ");
344
+ const total = Number(database.prepare(`SELECT count(*) AS n FROM sender_bots b WHERE ${filter}`).get(...params)?.n);
345
+ const ids = database
346
+ .prepare(`SELECT b.id FROM sender_bots b WHERE ${filter} ORDER BY ${SHOWN} COLLATE NOCASE, b.id LIMIT ? OFFSET ?`)
347
+ .all(...params, limit, offset)
348
+ .map((row) => Number(row.id));
349
+ return { items: botsOf(database, ids), hasMore: total > offset + limit, total };
350
+ });
351
+ };
352
+ /** One sender bot with its identities and every move to or from it. */
353
+ export const showBot = (database, ref) => read(database, () => detailsOf(database, botIdOf(database, ref)));
98
354
  /**
99
- * The owner's word that a person, or one of their identities, is a program, for its whole history: its messages stay
100
- * where they are, and no rule moves it back. `bot` joins it to a bot already stored; one identity of a person with
101
- * others gets a person row of its own first.
355
+ * The owner's word that a person, a bot or one identity is a program, for its whole history: its messages stay where
356
+ * they are, and no rule gives it back. `bot` joins it to a stored bot; else a bot that already holds it keeps it, or a
357
+ * new one takes it. A person every identity left is hidden, and a move back gives their uid back.
102
358
  */
103
359
  export const moveToBot = (context, subject, options = {}) => {
104
360
  const { database } = context;
105
361
  return write(database, () => {
106
362
  const at = context.now();
363
+ settleLegacyBots(database, at);
107
364
  const log = { author: "owner", reason: options.reason ?? null, at };
108
- const chosen = subjectOf(context, subject);
109
- if (isOwner(context, chosen.person))
365
+ const chosen = subjectOf(database, subject);
366
+ const people = new Set(chosen.identities.flatMap((one) => holderOf(database, one).person ?? []));
367
+ if ([...people].some((person) => isOwner(context, person)))
110
368
  throw new CliError("validation_error", "the owner's own person is never a bot", { reason: "sender-bot.owner" });
111
- const target = options.bot === undefined ? undefined : botRow(database, options.bot);
112
- const from = { person: chosen.person, bot: botOfPerson(database, chosen.person) };
113
- const claim = (bot) => database
369
+ if (chosen.identities.length === 0)
370
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
371
+ reason: "sender-bot.empty",
372
+ });
373
+ const held = new Set(chosen.identities.flatMap((one) => holderOf(database, one).bot ?? []));
374
+ const target = options.bot !== undefined
375
+ ? botIdOf(database, options.bot)
376
+ : (chosen.bot ?? (held.size === 1 && people.size === 0 ? [...held][0] : undefined));
377
+ const bot = target ?? createBot(database, log, options.name ?? null);
378
+ database
114
379
  .prepare("UPDATE sender_bots SET author = 'owner', name = coalesce(?, name), updated_at = ? WHERE id = ?")
115
380
  .run(options.name ?? null, at, bot);
116
- if (target !== undefined && target.person !== chosen.person) {
117
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
118
- if (chosen.identity === undefined) {
119
- mergePerson(context, chosen.person, target.person, { method: "bot", by: "owner" });
120
- if (from.bot !== undefined)
121
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(from.bot);
122
- }
123
- else {
124
- move(context, chosen.identity, chosen.person, target.person, { method: "bot", by: "owner" });
125
- renameAfterLeaving(context, chosen.person, [chosen.identity]);
126
- }
127
- claim(target.id);
128
- logMoves(database, moving, from, { bot: target.id }, log);
129
- return senderBotOf(database, target.id);
130
- }
131
- if (chosen.identity !== undefined && chosen.ref !== undefined) {
132
- const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
133
- const bot = createBot(database, alone, { ...log, name: options.name ?? null });
134
- logMoves(database, [chosen.identity], from, { bot }, log);
135
- return senderBotOf(database, bot);
136
- }
137
- const held = from.bot ?? createBot(database, chosen.person, { ...log, name: options.name ?? null });
138
- if (from.bot !== undefined)
139
- claim(held);
140
- logMoves(database, identitiesOf(database, chosen.person), from, { bot: held }, log);
141
- return senderBotOf(database, held);
381
+ const left = intoBot(database, chosen.identities, bot, log);
382
+ for (const [person, gone] of left)
383
+ if (identitiesOf(database, person).length > 0)
384
+ renameAfterLeaving(context, person, gone);
385
+ groupByDomain(database, [{ id: bot, displayName: options.name ?? null, holds: true, bot: true }], at);
386
+ return detailsOf(database, bot);
142
387
  });
143
388
  };
144
389
  /**
145
390
  * The owner's word that a bot, a person or one identity is a person, for its whole history; no rule makes it a bot
146
- * again. `person` joins it to that person; one identity of a bot with others gets a person row of its own.
391
+ * again. `person` takes it; else each identity goes back to the person it came from, or a person of its own. Said of a
392
+ * person, it keeps them one. Answers the person the first identity is on.
147
393
  */
148
394
  export const moveToPerson = (context, subject, options = {}) => {
149
395
  const { database } = context;
150
396
  return write(database, () => {
151
397
  const at = context.now();
398
+ settleLegacyBots(database, at);
152
399
  const log = { author: "owner", reason: options.reason ?? null, at };
153
- const chosen = subjectOf(context, subject);
154
- const bot = botOfPerson(database, chosen.person);
155
- const from = { person: chosen.person, bot };
156
- const target = options.person === undefined ? undefined : personRow(database, options.person);
157
- if (target !== undefined && botOfPerson(database, target) !== undefined)
158
- throw new CliError("validation_error", `${options.person} is a bot; name a person`, {
159
- reason: "sender-bot.not-a-person",
160
- reference: options.person,
400
+ const chosen = subjectOf(database, subject);
401
+ const target = options.person === undefined ? undefined : personIdOf(database, options.person);
402
+ if (chosen.identities.length === 0)
403
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
404
+ reason: "sender-bot.empty",
161
405
  });
162
- if (target !== undefined && target !== chosen.person) {
163
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
164
- if (chosen.identity === undefined)
165
- mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
166
- else {
167
- move(context, chosen.identity, chosen.person, target, { method: "manual", by: "owner" });
168
- renameAfterLeaving(context, chosen.person, [chosen.identity]);
169
- }
170
- if (bot !== undefined && identitiesOf(database, chosen.person).length === 0)
171
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
172
- releaseDomainHolds(database, moving);
173
- logMoves(database, moving, from, { person: target }, log);
406
+ if (chosen.person !== undefined && target !== undefined && target !== chosen.person) {
407
+ for (const identity of chosen.identities)
408
+ logMove(database, identity, { person: chosen.person }, { person: target }, log);
409
+ mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
174
410
  return recordOf(context, target);
175
411
  }
176
- if (chosen.identity !== undefined && chosen.ref !== undefined && bot !== undefined) {
177
- const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
178
- releaseDomainHolds(database, [chosen.identity]);
179
- logMoves(database, [chosen.identity], from, { person: alone }, log);
180
- return recordOf(context, alone);
412
+ const went = outOfBot(database, chosen.identities, target, log);
413
+ for (const identity of chosen.identities) {
414
+ if (went.has(identity))
415
+ continue;
416
+ const person = holderOf(database, identity).person;
417
+ if (person === undefined)
418
+ continue;
419
+ const to = target ?? person;
420
+ if (to !== person) {
421
+ move(context, identity, person, to, { method: "manual", by: "owner" });
422
+ renameAfterLeaving(context, person, [identity]);
423
+ }
424
+ logMove(database, identity, { person }, { person: to }, log);
425
+ went.set(identity, to);
181
426
  }
182
- if (bot !== undefined)
183
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
184
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
185
- releaseDomainHolds(database, moving);
186
- logMoves(database, moving, from, { person: chosen.person }, log);
187
- return recordOf(context, chosen.person);
427
+ releaseDomainHolds(database, chosen.identities);
428
+ const first = went.get(chosen.identities[0]);
429
+ return recordOf(context, first ?? target ?? chosen.person);
188
430
  });
189
431
  };
@@ -22,6 +22,11 @@ export interface SentMail {
22
22
  }
23
23
  /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
24
24
  export declare const DISCUSSION_SENDERS = 3;
25
+ /** How one email reached the owner, and the signal that says so. */
26
+ export declare const reachOfOne: (mail: SentMail) => {
27
+ reach: Reach;
28
+ signal?: SenderSignal;
29
+ };
25
30
  /**
26
31
  * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
27
32
  * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
@@ -35,11 +40,13 @@ export declare const senderSignalsOf: (mail: readonly SentMail[], { addresses, o
35
40
  signals: SenderSignal[];
36
41
  reach: Reach | null;
37
42
  };
38
- /** `bob+news@x` and `bob@x` are one sender. */
43
+ export declare const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
39
44
  /** The senders of each of these List-Ids, through `emails_by_list_id`. */
40
45
  export declare const LIST_SENDERS: string;
46
+ /** `bob+news@x` and `bob@x` are one sender. */
47
+ export declare const senderKey: (address: string) => string;
41
48
  /**
42
- * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: the
43
- * senders of their List-Ids tell a discussion list from a newsletter.
49
+ * The mail each of these people, or sender bots, sent the owner, as `senderSignalsOf` reads it. Asked for a page
50
+ * only: the senders of their List-Ids tell a discussion list from a newsletter.
44
51
  */
45
- export declare const sentMailOf: (database: CacheDatabase, people: readonly number[]) => Map<number, SentMail[]>;
52
+ export declare const sentMailOf: (database: CacheDatabase, people: readonly number[], holder?: "person" | "bot") => Map<number, SentMail[]>;