@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,186 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
3
+ const ATTRIBUTE = /([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
4
+ const invalid = (reason) => new CliError("validation_error", `the file's XML cannot be edited: ${reason}`);
5
+ export const decodeEntities = (raw) => raw.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-z]+);/g, (whole, entity) => {
6
+ if (entity.startsWith("#x"))
7
+ return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
8
+ if (entity.startsWith("#"))
9
+ return String.fromCodePoint(Number(entity.slice(1)));
10
+ const value = ENTITIES[entity];
11
+ if (value === undefined)
12
+ throw invalid(`unknown entity ${whole}`);
13
+ return value;
14
+ });
15
+ /** Element content as text: entities decoded, CDATA unwrapped, comments and processing instructions dropped. */
16
+ export const contentText = (raw) => raw
17
+ .split(/(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->|<\?[\s\S]*?\?>)/)
18
+ .map((part) => part.startsWith("<![CDATA[")
19
+ ? part.slice(9, -3)
20
+ : part.startsWith("<!--") || part.startsWith("<?")
21
+ ? ""
22
+ : decodeEntities(part))
23
+ .join("");
24
+ // XML 1.0 allows tab, newline, carriage return and everything from U+0020 except lone surrogates and U+FFFE/U+FFFF.
25
+ const storable = (value) => {
26
+ for (const character of value) {
27
+ const code = character.codePointAt(0);
28
+ if (code < 0x20
29
+ ? ![9, 10, 13].includes(code)
30
+ : (code >= 0xd800 && code <= 0xdfff) || code === 0xfffe || code === 0xffff)
31
+ return false;
32
+ }
33
+ return true;
34
+ };
35
+ export const escapeText = (value) => {
36
+ if (!storable(value))
37
+ throw new CliError("validation_error", "the text holds a character XML cannot store (a control character)");
38
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
39
+ };
40
+ export const parseXml = (text) => {
41
+ if (/<!DOCTYPE|<!ENTITY/i.test(text))
42
+ throw invalid("a DOCTYPE");
43
+ const root = [];
44
+ const stack = [];
45
+ for (let index = text.indexOf("<"); index >= 0 && index < text.length; index = text.indexOf("<", index)) {
46
+ const skip = text.startsWith("<!--", index)
47
+ ? "-->"
48
+ : text.startsWith("<![CDATA[", index)
49
+ ? "]]>"
50
+ : text.startsWith("<?", index)
51
+ ? "?>"
52
+ : undefined;
53
+ if (skip) {
54
+ const end = text.indexOf(skip, index);
55
+ if (end < 0)
56
+ throw invalid("an unclosed comment or CDATA");
57
+ index = end + skip.length;
58
+ continue;
59
+ }
60
+ const start = index;
61
+ let quote = "";
62
+ for (index++; index < text.length; index++) {
63
+ const char = text[index];
64
+ if (quote) {
65
+ if (char === quote)
66
+ quote = "";
67
+ }
68
+ else if (char === '"' || char === "'")
69
+ quote = char;
70
+ else if (char === ">")
71
+ break;
72
+ }
73
+ if (index >= text.length)
74
+ throw invalid("an unclosed tag");
75
+ index++;
76
+ const tag = text.slice(start, index);
77
+ if (tag.startsWith("</")) {
78
+ const name = tag.slice(2, -1).trim();
79
+ const open = stack.pop();
80
+ if (!open || open.name !== name)
81
+ throw invalid(`a closing </${name}> without its opening tag`);
82
+ open.closeStart = start;
83
+ open.end = index;
84
+ continue;
85
+ }
86
+ const selfClosing = /\/\s*>$/.test(tag);
87
+ const body = tag.slice(1, selfClosing ? tag.lastIndexOf("/") : -1);
88
+ const name = /^[^\s/>]+/.exec(body)?.[0];
89
+ if (!name)
90
+ throw invalid("a tag without a name");
91
+ const attributes = new Map();
92
+ for (const match of body.slice(name.length).matchAll(ATTRIBUTE))
93
+ attributes.set(match[1], decodeEntities(match[2] ?? match[3] ?? ""));
94
+ const parent = stack.at(-1);
95
+ const namespaces = new Map(parent?.namespaces ?? [["xml", "http://www.w3.org/XML/1998/namespace"]]);
96
+ for (const [key, value] of attributes) {
97
+ if (key === "xmlns")
98
+ namespaces.set("", value);
99
+ else if (key.startsWith("xmlns:"))
100
+ namespaces.set(key.slice(6), value);
101
+ }
102
+ const colon = name.indexOf(":");
103
+ const prefix = colon < 0 ? "" : name.slice(0, colon);
104
+ const ns = namespaces.get(prefix);
105
+ if (ns === undefined && prefix)
106
+ throw invalid(`an undeclared prefix ${prefix}:`);
107
+ const element = {
108
+ name,
109
+ prefix,
110
+ local: colon < 0 ? name : name.slice(colon + 1),
111
+ ns: ns ?? "",
112
+ attributes,
113
+ start,
114
+ openEnd: index,
115
+ closeStart: index,
116
+ end: index,
117
+ children: [],
118
+ parent,
119
+ namespaces,
120
+ };
121
+ (parent ? parent.children : root).push(element);
122
+ if (!selfClosing)
123
+ stack.push(element);
124
+ }
125
+ if (stack.length || root.length !== 1)
126
+ throw invalid("unbalanced elements");
127
+ return root[0];
128
+ };
129
+ /** An attribute by its namespace and local name, whatever prefix the file uses for it. */
130
+ export const attributeOf = (element, ns, local) => {
131
+ for (const [key, value] of element.attributes) {
132
+ const colon = key.indexOf(":");
133
+ if (colon < 0) {
134
+ if (!ns && key === local)
135
+ return value;
136
+ continue;
137
+ }
138
+ if (key.slice(colon + 1) === local && element.namespaces.get(key.slice(0, colon)) === ns)
139
+ return value;
140
+ }
141
+ return undefined;
142
+ };
143
+ export const childrenOf = (element, ns, local) => element.children.filter((child) => child.ns === ns && child.local === local);
144
+ export const descendants = (element, ns, local) => {
145
+ const found = [];
146
+ const visit = (current) => {
147
+ for (const child of current.children) {
148
+ if (child.ns === ns && child.local === local)
149
+ found.push(child);
150
+ visit(child);
151
+ }
152
+ };
153
+ visit(element);
154
+ return found;
155
+ };
156
+ /** Applies non-overlapping replacements; an insert goes before a replacement at its offset, inserts keep their order. */
157
+ export const applySplices = (text, splices) => {
158
+ const ordered = splices
159
+ .map((splice, order) => ({ ...splice, order }))
160
+ .sort((a, b) => a.start - b.start || Number(a.end > a.start) - Number(b.end > b.start) || a.order - b.order);
161
+ let result = "";
162
+ let at = 0;
163
+ for (const splice of ordered) {
164
+ if (splice.start < at)
165
+ throw new Error("overlapping_edits");
166
+ result += text.slice(at, splice.start) + splice.text;
167
+ at = splice.end;
168
+ }
169
+ return result + text.slice(at);
170
+ };
171
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
172
+ const encoder = new TextEncoder();
173
+ /** A part's text; only UTF-8 parts are edited, since a rewrite in another encoding would contradict its declaration. */
174
+ export const partText = (bytes, path) => {
175
+ const head = new TextDecoder("latin1").decode(bytes.subarray(0, 100));
176
+ const declared = /^(?:|)?<\?xml[^>]*encoding\s*=\s*["']([^"']+)["']/.exec(head)?.[1];
177
+ if (declared && !/^utf-?8$/i.test(declared))
178
+ throw new CliError("validation_error", `${path} is stored as ${declared}; only UTF-8 parts can be edited`);
179
+ try {
180
+ return decoder.decode(bytes);
181
+ }
182
+ catch {
183
+ throw new CliError("validation_error", `${path} is not UTF-8; only UTF-8 parts can be edited`);
184
+ }
185
+ };
186
+ export const partBytes = (text) => encoder.encode(text);
@@ -0,0 +1,10 @@
1
+ /** The XML parts of an Office file, after `readContainer`'s checks: sizes, checksums, names, no encryption. */
2
+ export declare const openPackage: (bytes: Uint8Array) => Promise<Map<string, Uint8Array<ArrayBufferLike>>>;
3
+ /**
4
+ * The archive with some entries replaced (or removed with `null`). Every other entry — its local header, compressed
5
+ * data, data descriptor and central record — is copied byte for byte, in the original order, so images, fonts and
6
+ * parts this module never reads come out exactly as they went in.
7
+ */
8
+ export declare const rewriteZip: (bytes: Uint8Array, replaced: ReadonlyMap<string, Uint8Array | null>) => Uint8Array<ArrayBuffer>;
9
+ /** The raw bytes an entry occupies, local header to the next entry — what a byte-for-byte copy must keep. */
10
+ export declare const rawEntry: (bytes: Uint8Array, name: string) => Uint8Array<ArrayBufferLike> | undefined;
@@ -0,0 +1,116 @@
1
+ import { crc32 } from "node:zlib";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { deflateSync } from "fflate";
4
+ import { ReaderLimit, readContainer } from "../attachments/container.js";
5
+ const decoder = new TextDecoder();
6
+ /** The XML parts of an Office file, after `readContainer`'s checks: sizes, checksums, names, no encryption. */
7
+ export const openPackage = async (bytes) => {
8
+ try {
9
+ return await readContainer(bytes);
10
+ }
11
+ catch (error) {
12
+ if (error instanceof CliError)
13
+ throw error;
14
+ throw new CliError("validation_error", error instanceof ReaderLimit
15
+ ? "the file is too large to edit (over 50 MB unpacked, 10 MB in one part or 1,000 entries)"
16
+ : `the file is not a readable Office file (${error instanceof Error ? error.message : String(error)})`);
17
+ }
18
+ };
19
+ const endRecord = (view) => {
20
+ for (let index = view.byteLength - 22; index >= Math.max(0, view.byteLength - 65_557); index--)
21
+ if (view.getUint32(index, true) === 0x06054b50)
22
+ return index;
23
+ throw new CliError("validation_error", "the file is not a zip archive");
24
+ };
25
+ const entriesOf = (bytes) => {
26
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27
+ const end = endRecord(view);
28
+ const count = view.getUint16(end + 10, true);
29
+ const directory = view.getUint32(end + 16, true);
30
+ const entries = [];
31
+ let offset = directory;
32
+ for (let index = 0; index < count; index++) {
33
+ const length = view.getUint16(offset + 28, true);
34
+ const next = offset + 46 + length + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);
35
+ entries.push({
36
+ name: decoder.decode(bytes.subarray(offset + 46, offset + 46 + length)),
37
+ central: offset,
38
+ centralEnd: next,
39
+ local: view.getUint32(offset + 42, true),
40
+ });
41
+ offset = next;
42
+ }
43
+ return { view, end, directory, entries };
44
+ };
45
+ const concat = (parts) => {
46
+ const result = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
47
+ let offset = 0;
48
+ for (const part of parts) {
49
+ result.set(part, offset);
50
+ offset += part.length;
51
+ }
52
+ return result;
53
+ };
54
+ /**
55
+ * The archive with some entries replaced (or removed with `null`). Every other entry — its local header, compressed
56
+ * data, data descriptor and central record — is copied byte for byte, in the original order, so images, fonts and
57
+ * parts this module never reads come out exactly as they went in.
58
+ */
59
+ export const rewriteZip = (bytes, replaced) => {
60
+ const { view, end, directory, entries } = entriesOf(bytes);
61
+ const starts = [...entries.map((entry) => entry.local), directory].sort((a, b) => a - b);
62
+ const locals = [];
63
+ const centrals = [];
64
+ let written = 0;
65
+ let kept = 0;
66
+ for (const entry of entries) {
67
+ const replacement = replaced.get(entry.name);
68
+ if (replacement === null)
69
+ continue;
70
+ const central = bytes.slice(entry.central, entry.centralEnd);
71
+ const centralView = new DataView(central.buffer);
72
+ let local;
73
+ if (replacement === undefined) {
74
+ const spanEnd = starts.find((start) => start > entry.local);
75
+ local = bytes.subarray(entry.local, spanEnd);
76
+ }
77
+ else {
78
+ const header = entry.local + 30 + view.getUint16(entry.local + 26, true) + view.getUint16(entry.local + 28, true);
79
+ const data = deflateSync(replacement, { level: 6 });
80
+ local = concat([bytes.slice(entry.local, header), data]);
81
+ const localView = new DataView(local.buffer);
82
+ for (const [target, base] of [
83
+ [localView, 0],
84
+ [centralView, 2],
85
+ ]) {
86
+ target.setUint16(base + 6, target.getUint16(base + 6, true) & ~0x0008, true);
87
+ target.setUint16(base + 8, 8, true);
88
+ target.setUint32(base + 14, crc32(replacement), true);
89
+ target.setUint32(base + 18, data.length, true);
90
+ target.setUint32(base + 22, replacement.length, true);
91
+ }
92
+ }
93
+ centralView.setUint32(42, written, true);
94
+ locals.push(local);
95
+ centrals.push(central);
96
+ written += local.length;
97
+ kept++;
98
+ }
99
+ const tail = bytes.slice(end);
100
+ const tailView = new DataView(tail.buffer);
101
+ const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
102
+ tailView.setUint16(8, kept, true);
103
+ tailView.setUint16(10, kept, true);
104
+ tailView.setUint32(12, centralSize, true);
105
+ tailView.setUint32(16, written, true);
106
+ return concat([...locals, ...centrals, tail]);
107
+ };
108
+ /** The raw bytes an entry occupies, local header to the next entry — what a byte-for-byte copy must keep. */
109
+ export const rawEntry = (bytes, name) => {
110
+ const { directory, entries } = entriesOf(bytes);
111
+ const entry = entries.find((candidate) => candidate.name === name);
112
+ if (!entry)
113
+ return undefined;
114
+ const starts = [...entries.map((other) => other.local), directory].sort((a, b) => a - b);
115
+ return bytes.subarray(entry.local, starts.find((start) => start > entry.local));
116
+ };
@@ -0,0 +1,28 @@
1
+ import * as v from "valibot";
2
+ import type { FileMirrorState, FileTarget, RemoteFile } from "../../documents/file-mirror-model.js";
3
+ /**
4
+ * The remote listing, gone on from where the last run's stopped, and what to save of it when it is incomplete. This
5
+ * run's files win over the saved ones by path and by id, so a file met twice, or moved between runs, is kept once at
6
+ * its latest path.
7
+ */
8
+ export declare const listRemote: (target: FileTarget, folder: string, signal: AbortSignal | undefined, excluded: (path: string) => boolean, saved: FileMirrorState["listing"], now: number, maxFiles: number) => Promise<{
9
+ listed?: {
10
+ rootId: string;
11
+ files: RemoteFile[];
12
+ complete: boolean;
13
+ };
14
+ progress?: FileMirrorState["listing"];
15
+ }>;
16
+ export declare const listingSchema: v.ObjectSchema<{
17
+ readonly rootId: v.StringSchema<undefined>;
18
+ readonly startedAt: v.StringSchema<undefined>;
19
+ readonly next: v.StringSchema<undefined>;
20
+ readonly files: v.ArraySchema<v.ObjectSchema<{
21
+ readonly path: v.StringSchema<undefined>;
22
+ readonly id: v.StringSchema<undefined>;
23
+ readonly size: v.NumberSchema<undefined>;
24
+ readonly sha256: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
25
+ readonly md5: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
26
+ readonly modifiedAt: v.StringSchema<undefined>;
27
+ }, undefined>, undefined>;
28
+ }, undefined>;
@@ -0,0 +1,47 @@
1
+ import * as v from "valibot";
2
+ /**
3
+ * A stopped listing older than this starts over. Staleness costs a conflict or a deletion found a run later, never
4
+ * data; the bound is days so that a sync run once a day still finishes a listing that takes several runs.
5
+ */
6
+ const MAX_LISTING_AGE_MS = 7 * 24 * 3_600_000;
7
+ /**
8
+ * The remote listing, gone on from where the last run's stopped, and what to save of it when it is incomplete. This
9
+ * run's files win over the saved ones by path and by id, so a file met twice, or moved between runs, is kept once at
10
+ * its latest path.
11
+ */
12
+ export const listRemote = async (target, folder, signal, excluded, saved, now, maxFiles) => {
13
+ const resumed = saved && now - Date.parse(saved.startedAt) <= MAX_LISTING_AGE_MS ? saved : undefined;
14
+ const listed = await target.list(folder, signal, { excluded, ...(resumed ? { from: resumed.next } : {}) });
15
+ if (!listed)
16
+ return {};
17
+ const { rootId, next } = listed;
18
+ // Its pages went on part-way through another folder, so they are not a whole listing of this one.
19
+ if (resumed && rootId !== resumed.rootId)
20
+ return { listed: { rootId, files: listed.files, complete: false } };
21
+ const paths = new Set(listed.files.map((file) => file.path));
22
+ const ids = new Set(listed.files.map((file) => file.id));
23
+ const files = resumed
24
+ ? [...resumed.files.filter((file) => !paths.has(file.path) && !ids.has(file.id)), ...listed.files]
25
+ : listed.files;
26
+ if (resumed && files.filter((file) => !excluded(file.path)).length > maxFiles)
27
+ return { listed: { rootId, files, complete: false } };
28
+ const startedAt = resumed?.startedAt ?? new Date(now).toISOString();
29
+ return {
30
+ listed: { rootId, files, complete: listed.complete },
31
+ ...(!listed.complete && next !== undefined ? { progress: { rootId, startedAt, next, files } } : {}),
32
+ };
33
+ };
34
+ const remoteFileSchema = v.object({
35
+ path: v.string(),
36
+ id: v.string(),
37
+ size: v.number(),
38
+ sha256: v.optional(v.string()),
39
+ md5: v.optional(v.string()),
40
+ modifiedAt: v.string(),
41
+ });
42
+ export const listingSchema = v.object({
43
+ rootId: v.string(),
44
+ startedAt: v.string(),
45
+ next: v.string(),
46
+ files: v.array(remoteFileSchema),
47
+ });
@@ -50,7 +50,7 @@ export interface FileMirrorOptions {
50
50
  /** Throws once the sync lock is lost; checked before every write. */
51
51
  assertHeld(): void | Promise<void>;
52
52
  signal?: AbortSignal;
53
- /** Local files the mirror takes at most; more fail the run. */
53
+ /** Files the mirror takes at most: more local ones fail the run, more remote ones leave the listing incomplete. */
54
54
  maxFiles?: number;
55
55
  /** Bytes free for this process on the file system holding `path`, and its device. */
56
56
  space?(path: string): Promise<{
@@ -6,6 +6,7 @@ import * as v from "valibot";
6
6
  import { eachMirror, heldCheck, jsonState } from "../documents/mirrors.js";
7
7
  import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
8
8
  import { excludedBy } from "./exclusions.js";
9
+ import { listingSchema, listRemote } from "./listing.js";
9
10
  const HINTS = {
10
11
  preview: "--dry-run",
11
12
  repin: "--repin",
@@ -194,7 +195,16 @@ export const syncFileMirror = async (options) => {
194
195
  const state = options.state.read();
195
196
  if (state.principal !== principal || state.root !== root || state.target !== folder)
196
197
  throw new CliError("configuration_error", "mirror state belongs to another account or mirror");
197
- const listed = await target.list(folder, signal, { excluded });
198
+ const { listed, progress } = await listRemote(target, folder, signal, excluded, state.listing, now(), options.maxFiles ?? MAX_FILES);
199
+ // Kept before any refusal below, so a stopped run's pages are not listed again. A completed listing's progress is
200
+ // cleared only once the run gets past its refusals: a run stopped by the guard goes on from there.
201
+ if (!options.dryRun && listed?.complete !== true && (progress || state.listing)) {
202
+ if (progress)
203
+ state.listing = progress;
204
+ else
205
+ delete state.listing;
206
+ options.state.save(state);
207
+ }
198
208
  const localRoot = await stat(root).catch(() => undefined);
199
209
  const remoteReplaced = listed !== undefined && state.rootId !== undefined && listed.rootId !== state.rootId;
200
210
  const localReplaced = localRoot?.isDirectory() === true &&
@@ -445,9 +455,12 @@ export const syncFileMirror = async (options) => {
445
455
  if (!cutOff.has(path))
446
456
  delete state.pending[path];
447
457
  }
458
+ if (listed?.complete)
459
+ delete state.listing;
448
460
  let savedAt = now();
449
461
  // A big mirror's state is megabytes of JSON: saved less often, it costs no more than a small one's.
450
- const saveEvery = SAVE_EVERY_MS * Math.max(1, Object.keys(state.entries).length / 10_000);
462
+ const saved = Object.keys(state.entries).length + (state.listing?.files.length ?? 0);
463
+ const saveEvery = SAVE_EVERY_MS * Math.max(1, saved / 10_000);
451
464
  const save = (force = false) => {
452
465
  if (!force && now() - savedAt < saveEvery)
453
466
  return;
@@ -747,6 +760,7 @@ const stateSchema = v.object({
747
760
  localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
748
761
  entries: v.record(v.string(), entrySchema),
749
762
  pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
763
+ listing: v.optional(listingSchema),
750
764
  });
751
765
  /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
752
766
  export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -87,6 +87,7 @@ export type { OrganizationFilter } from "./sqlite/organization-categories.js";
87
87
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
88
88
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
89
89
  export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
90
+ export type { PersonErasure } from "./sqlite/person-erase.js";
90
91
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
91
92
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
92
93
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -9,6 +9,7 @@ import { type IdentityRekey, type IdentityRekeys } from "./sqlite/identity-rekey
9
9
  import type { StoreContext } from "./sqlite/open.js";
10
10
  import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
11
11
  import { type KeptPerson, type PersonDoubts, type TestDataPerson } from "./sqlite/person-doubts.js";
12
+ import { type PersonErasure } from "./sqlite/person-erase.js";
12
13
  import type { PersonMerge } from "./sqlite/person-merges.js";
13
14
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
14
15
  import { type ShownBecause } from "./sqlite/person-ties.js";
@@ -177,6 +178,13 @@ export interface PeopleStore extends AccountPeople {
177
178
  * The owner's alone; refused for the owner's own person.
178
179
  */
179
180
  markTestData(person: string, by: Decider): Promise<TestDataPerson>;
181
+ /**
182
+ * Deletes a person and what memo knows of them alone; see `erasePerson`. `apply: false` answers what would go and
183
+ * changes nothing. The owner's alone; refused for the owner's own person.
184
+ */
185
+ erase(person: string, by: Decider, options: {
186
+ apply: boolean;
187
+ }): Promise<PersonErasure>;
180
188
  /** The identity, and everyone linked with it, is the owner. */
181
189
  linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
182
190
  /** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
@@ -9,6 +9,7 @@ import * as identitySplits from "./sqlite/identity-split-proposals.js";
9
9
  import { linkToOwner } from "./sqlite/own-identities.js";
10
10
  import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
11
11
  import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
12
+ import { erasePerson } from "./sqlite/person-erase.js";
12
13
  import * as personLinks from "./sqlite/person-links.js";
13
14
  import { linkPhones, PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
14
15
  import * as personMerges from "./sqlite/person-merges.js";
@@ -155,6 +156,7 @@ export const peopleStoreOver = (context, keyed) => {
155
156
  doubts: async (page) => personDoubts(context, page),
156
157
  keep: async (person, by) => write(database, () => keepPerson(context, person, by)),
157
158
  markTestData: async (person, by) => write(database, () => markTestData(context, person, by)),
159
+ erase: async (person, by, { apply }) => write(database, () => erasePerson(context, person, by, apply)),
158
160
  linkToOwner: async (identity) => linkToOwner(context, identity),
159
161
  list: async (options) => listPeople(database, options),
160
162
  counts: async (query) => countPeople(database, query),
@@ -3,12 +3,14 @@ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
3
3
  import { forgetCalendarRows } from "./calendar-forget.js";
4
4
  import { eq, inArray, sql } from "./drizzle/core.js";
5
5
  import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
6
+ import { eraseImportedPeople, importedPeople } from "./person-erase.js";
6
7
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
7
8
  import { dropUnusedVectors } from "./vector-index.js";
8
9
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
9
10
  export const purgeAccount = (context, accountKey) => {
10
11
  const { orm, database, now } = context;
11
12
  const unseenBefore = unreferenced(database, "identities");
13
+ const imported = importedPeople(database, accountKey);
12
14
  const at = now();
13
15
  const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
14
16
  const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
@@ -111,6 +113,7 @@ export const purgeAccount = (context, accountKey) => {
111
113
  orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
112
114
  orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
113
115
  dropOrphanPeople(database, unseenBefore);
116
+ eraseImportedPeople(context, imported);
114
117
  forgetDanglingEvidence(database, at);
115
118
  dropUnusedVectors(database, hashes);
116
119
  // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
@@ -0,0 +1,39 @@
1
+ import type { Decider } from "../decisions.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface PersonErasure {
5
+ person: string;
6
+ name: string | null;
7
+ /** `false`: what `erase` would do, nothing changed. */
8
+ erased: boolean;
9
+ /** Identities that go with the person. */
10
+ identities: string[];
11
+ /**
12
+ * Identities a message, mail, meeting or chat still names: they stay, with no person, and the next sync or people
13
+ * scan gives them one again.
14
+ */
15
+ kept: {
16
+ identity: string;
17
+ references: number;
18
+ }[];
19
+ /** Rows that only tied something to the person, such as a tag, a link or a mention, by `table.column`. */
20
+ deleted: Record<string, number>;
21
+ /** Rows that stay and lose the person, such as a fact about them or a record made into them. */
22
+ detached: Record<string, number>;
23
+ }
24
+ /**
25
+ * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
26
+ * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
27
+ * message, mail or meeting is the source's: its sender stays as an identity with no person. Refused for the owner,
28
+ * and while an invoice, order, subscription or a row they wrote cannot be without them. `apply: false` answers the
29
+ * same without changing anything.
30
+ */
31
+ export declare const erasePerson: (context: StoreContext, uid: string, by: Decider, apply: boolean) => PersonErasure;
32
+ /** The people an account's records made into persons: read before a purge deletes the records. */
33
+ export declare const importedPeople: (database: CacheDatabase, accountKey: number) => number[];
34
+ /**
35
+ * After a purge, the people only its records made go too: nothing else names them, and no message, mail or meeting
36
+ * names their identities; their involvements are derived and go with them. One the owner tagged, linked or gave a
37
+ * task to stays.
38
+ */
39
+ export declare const eraseImportedPeople: (context: StoreContext, people: readonly number[]) => void;