@wirecat/cli-core 0.719.0 → 0.720.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.
@@ -0,0 +1,152 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { OWN, referencesTo } from "./accounts.js";
3
+ import { pointerPairs } from "./entity-types.js";
4
+ import { forgetDanglingEvidence } from "./evidence-signature.js";
5
+ import { forgetErasedLinks } from "./identity-link-rows.js";
6
+ import { forgetErasedSplits } from "./identity-split-proposals.js";
7
+ import { currentPerson } from "./merged-persons.js";
8
+ import { ownerOnly } from "./person-merges.js";
9
+ import { forgetErasedTestData } from "./test-people.js";
10
+ /** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
11
+ const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
12
+ /** Business rows that cannot be without the person: the owner moves them first. */
13
+ const blocking = (table, pointer, database) => AUTHORS.has(pointer) || hasChildren(database, table);
14
+ const hasChildren = (database, table) => database
15
+ .prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
16
+ LIMIT 1`)
17
+ .get(table) !== undefined;
18
+ const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
19
+ 0;
20
+ /** A link is about both ends: one that loses an end means nothing, so it goes. */
21
+ const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
22
+ const personOf = (context, uid) => {
23
+ const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
24
+ const known = asked === undefined ? undefined : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
25
+ if (known === undefined)
26
+ throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
27
+ return currentPerson(context.database, Number(known.id));
28
+ };
29
+ const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
30
+ /**
31
+ * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
32
+ * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
33
+ * message, mail or meeting is the source's: its sender stays as an identity with no person. Refused for the owner,
34
+ * and while an invoice, order, subscription or a row they wrote cannot be without them. `apply: false` answers the
35
+ * same without changing anything.
36
+ */
37
+ export const erasePerson = (context, uid, by, apply) => {
38
+ ownerOnly(by, "deletes a person");
39
+ const { database } = context;
40
+ const person = personOf(context, uid);
41
+ const row = database.prepare("SELECT owner, name FROM persons WHERE id = ?").get(person);
42
+ if (Number(row?.owner) === 1)
43
+ throw new CliError("validation_error", "your own person cannot be deleted", { reason: "person.owner" });
44
+ const linked = database
45
+ .prepare(`SELECT i.id AS id, i.provider || ':' || i.external_id AS ref FROM identity_links l
46
+ JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ? ORDER BY i.id`)
47
+ .all(person)
48
+ .map((one) => ({ id: Number(one.id), ref: String(one.ref) }));
49
+ const ids = JSON.stringify(linked.map(({ id }) => id));
50
+ const theirs = "SELECT value FROM json_each(?)";
51
+ const outside = referencesTo(database, "identities", new Set([...OWN, "account_identities", "organization_identities", "involvements"]), theirs);
52
+ const named = new Map();
53
+ for (const one of database
54
+ .prepare(`SELECT id, count(*) AS n FROM (${outside}) GROUP BY id`)
55
+ .all(...refsOf(outside, ids)))
56
+ named.set(Number(one.id), Number(one.n));
57
+ const going = linked.filter(({ id }) => !named.has(id));
58
+ const kept = linked.filter(({ id }) => named.has(id));
59
+ const goingIds = JSON.stringify(going.map(({ id }) => id));
60
+ const deleted = {};
61
+ const detached = {};
62
+ const blocked = [];
63
+ const plan = [];
64
+ const pointing = (type, among, params) => {
65
+ for (const { table, pointer } of pointerPairs(database)) {
66
+ const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
67
+ const n = count(database, `"${table}" WHERE ${where}`, ...params);
68
+ if (n === 0)
69
+ continue;
70
+ const key = `${table}.${pointer}`;
71
+ if (LINK_ROWS.has(table) || !nullable(database, table, `${pointer}_id`)) {
72
+ if (!LINK_ROWS.has(table) && blocking(table, pointer, database)) {
73
+ blocked.push(`${n} ${table} (${pointer})`);
74
+ continue;
75
+ }
76
+ deleted[key] = (deleted[key] ?? 0) + n;
77
+ plan.push(() => database.prepare(`DELETE FROM "${table}" WHERE ${where}`).run(...params));
78
+ }
79
+ else {
80
+ detached[key] = (detached[key] ?? 0) + n;
81
+ plan.push(() => database
82
+ .prepare(`UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`)
83
+ .run(...params));
84
+ }
85
+ }
86
+ };
87
+ pointing("person", "?", [person]);
88
+ pointing("identity", theirs, [goingIds]);
89
+ const involvements = count(database, `involvements WHERE person_id = ? OR identity_id IN (${theirs})`, person, goingIds);
90
+ if (involvements > 0)
91
+ deleted["involvements.person"] = (deleted["involvements.person"] ?? 0) + involvements;
92
+ const bots = count(database, "bots WHERE owner_person_id = ?", person);
93
+ if (bots > 0)
94
+ detached["bots.owner_person"] = bots;
95
+ if (blocked.length > 0)
96
+ throw new CliError("validation_error", `person:${person} is still named by ${blocked.join(", ")}; change those first — nothing was deleted`, { reason: "person.erase-blocked", blocked });
97
+ const answer = (erased) => ({
98
+ person: `person:${person}`,
99
+ name: row?.name == null ? null : String(row.name),
100
+ erased,
101
+ identities: going.map(({ ref }) => ref),
102
+ kept: kept.map(({ id, ref }) => ({ identity: ref, references: named.get(id) ?? 0 })),
103
+ deleted,
104
+ detached,
105
+ });
106
+ if (!apply)
107
+ return answer(false);
108
+ for (const step of plan)
109
+ step();
110
+ database.prepare(`DELETE FROM involvements WHERE person_id = ? OR identity_id IN (${theirs})`).run(person, goingIds);
111
+ database.prepare("UPDATE bots SET owner_person_id = NULL WHERE owner_person_id = ?").run(person);
112
+ for (const table of ["account_identities", "organization_identities", "identity_revisions"])
113
+ database.prepare(`DELETE FROM ${table} WHERE identity_id IN (${theirs})`).run(goingIds);
114
+ database
115
+ .prepare(`DELETE FROM identity_link_events WHERE to_person_id = ? OR identity_id IN (${theirs})`)
116
+ .run(person, goingIds);
117
+ database.prepare("UPDATE identity_link_events SET from_person_id = NULL WHERE from_person_id = ?").run(person);
118
+ database.prepare("DELETE FROM identity_links WHERE person_id = ?").run(person);
119
+ database.prepare(`DELETE FROM identities WHERE id IN (${theirs})`).run(goingIds);
120
+ database.prepare("DELETE FROM persons WHERE id = ?").run(person);
121
+ forgetErasedLinks(database);
122
+ forgetErasedSplits(database);
123
+ forgetErasedTestData(database);
124
+ forgetDanglingEvidence(database, context.now());
125
+ return answer(true);
126
+ };
127
+ /** `referencesTo` with `among` binds the ids once per arm. */
128
+ const refsOf = (sql, ids) => Array.from({ length: sql.split("json_each(?)").length - 1 }, () => ids);
129
+ /** The people an account's records made into persons: read before a purge deletes the records. */
130
+ export const importedPeople = (database, accountKey) => database
131
+ .prepare("SELECT DISTINCT entity_id AS id FROM records WHERE account_id = ? AND entity_type = 'person'")
132
+ .all(accountKey)
133
+ .map(({ id }) => Number(id));
134
+ /**
135
+ * After a purge, the people only its records made go too: nothing else names them, and no message, mail or meeting
136
+ * names their identities; their involvements are derived and go with them. One the owner tagged, linked or gave a
137
+ * task to stays.
138
+ */
139
+ export const eraseImportedPeople = (context, people) => {
140
+ const { database } = context;
141
+ const others = referencesTo(database, "persons", new Set(["identity_links", "identity_link_events", "involvements"]), "?");
142
+ for (const person of people) {
143
+ if (database.prepare("SELECT 1 FROM persons WHERE id = ? AND owner = 0").get(person) === undefined)
144
+ continue;
145
+ const params = Array.from({ length: others.split("IN (?)").length - 1 }, () => person);
146
+ if (database.prepare(`SELECT 1 FROM (${others}) LIMIT 1`).get(...params) !== undefined)
147
+ continue;
148
+ const plan = erasePerson(context, String(person), "owner", false);
149
+ if (plan.kept.length === 0)
150
+ erasePerson(context, String(person), "owner", true);
151
+ }
152
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.719.0",
3
+ "version": "0.720.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -219,6 +219,10 @@
219
219
  "types": "./dist/mount/index.d.ts",
220
220
  "default": "./dist/mount/index.js"
221
221
  },
222
+ "./office": {
223
+ "types": "./dist/office/index.d.ts",
224
+ "default": "./dist/office/index.js"
225
+ },
222
226
  "./sql": {
223
227
  "types": "./dist/sql/index.d.ts",
224
228
  "default": "./dist/sql/index.js"