@wirecat/cli-core 0.719.0 → 0.721.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 (81) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/attachments/documents.d.ts +5 -0
  3. package/dist/attachments/documents.js +2 -2
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  5. package/dist/cli/config-command.js +8 -2
  6. package/dist/cli/config-issues.d.ts +3 -1
  7. package/dist/cli/config-issues.js +9 -2
  8. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  9. package/dist/cli/documents/file-conflicts.js +102 -0
  10. package/dist/cli/documents/file-edit.d.ts +29 -0
  11. package/dist/cli/documents/file-edit.js +352 -0
  12. package/dist/cli/documents/file-update.d.ts +43 -0
  13. package/dist/cli/documents/file-update.js +95 -0
  14. package/dist/cli/documents/history.d.ts +34 -0
  15. package/dist/cli/documents/history.js +89 -0
  16. package/dist/cli/documents/index.d.ts +9 -2
  17. package/dist/cli/documents/index.js +9 -2
  18. package/dist/cli/documents/library.js +10 -0
  19. package/dist/cli/permission-keys.d.ts +6 -0
  20. package/dist/cli/permission-keys.js +15 -3
  21. package/dist/cli/service-api.d.ts +1 -1
  22. package/dist/cli/service-api.js +16 -34
  23. package/dist/documents/file-mirror-model.d.ts +32 -1
  24. package/dist/documents/index.d.ts +7 -4
  25. package/dist/documents/index.js +4 -1
  26. package/dist/documents/model.d.ts +16 -1
  27. package/dist/errors/reasons.js +6 -1
  28. package/dist/office/docx.d.ts +43 -0
  29. package/dist/office/docx.js +349 -0
  30. package/dist/office/index.d.ts +2 -0
  31. package/dist/office/index.js +2 -0
  32. package/dist/office/package.d.ts +39 -0
  33. package/dist/office/package.js +98 -0
  34. package/dist/office/xlsx.d.ts +55 -0
  35. package/dist/office/xlsx.js +550 -0
  36. package/dist/office/xml.d.ts +34 -0
  37. package/dist/office/xml.js +186 -0
  38. package/dist/office/zip.d.ts +10 -0
  39. package/dist/office/zip.js +116 -0
  40. package/dist/services/documents/block-diff.d.ts +13 -3
  41. package/dist/services/documents/block-diff.js +13 -7
  42. package/dist/services/documents/ingestion.d.ts +21 -2
  43. package/dist/services/documents/ingestion.js +29 -2
  44. package/dist/services/documents/plan.js +16 -7
  45. package/dist/services/documents/ports.d.ts +2 -0
  46. package/dist/services/documents/sync.d.ts +1 -0
  47. package/dist/services/documents/sync.js +9 -4
  48. package/dist/services/files/conflicts.d.ts +78 -0
  49. package/dist/services/files/conflicts.js +183 -0
  50. package/dist/services/files/guarded-write.d.ts +34 -0
  51. package/dist/services/files/guarded-write.js +42 -0
  52. package/dist/services/files/listing.d.ts +36 -0
  53. package/dist/services/files/listing.js +47 -0
  54. package/dist/services/files/local-files.d.ts +54 -0
  55. package/dist/services/files/local-files.js +143 -0
  56. package/dist/services/files/mirror-state.d.ts +14 -0
  57. package/dist/services/files/mirror-state.js +65 -0
  58. package/dist/services/files/mirror.d.ts +4 -14
  59. package/dist/services/files/mirror.js +177 -204
  60. package/dist/services/files/text-merge.d.ts +27 -0
  61. package/dist/services/files/text-merge.js +134 -0
  62. package/dist/services/files/versions.d.ts +36 -9
  63. package/dist/services/files/versions.js +40 -12
  64. package/dist/store/index.d.ts +2 -0
  65. package/dist/store/index.js +1 -0
  66. package/dist/store/people.d.ts +8 -0
  67. package/dist/store/people.js +2 -0
  68. package/dist/store/sqlite/account-purge.js +3 -0
  69. package/dist/store/sqlite/document-history.d.ts +84 -0
  70. package/dist/store/sqlite/document-history.js +158 -0
  71. package/dist/store/sqlite/manifest.js +2 -0
  72. package/dist/store/sqlite/migrations.generated.js +17 -0
  73. package/dist/store/sqlite/notes.d.ts +9 -10
  74. package/dist/store/sqlite/notes.js +33 -21
  75. package/dist/store/sqlite/person-erase.d.ts +39 -0
  76. package/dist/store/sqlite/person-erase.js +152 -0
  77. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  78. package/dist/store/sqlite/schema/document-changes.js +11 -0
  79. package/dist/store/sqlite/schema.d.ts +65 -0
  80. package/dist/store/sqlite/schema.js +5 -0
  81. package/package.json +6 -2
@@ -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
+ };
@@ -1,11 +1,14 @@
1
1
  import { type Block } from "../../documents/blocks.js";
2
2
  import type { Keep } from "../../documents/push-model.js";
3
3
  /** `base[from, to)` is replaced by `blocks`; an empty range is an insert, an empty `blocks` a delete. */
4
- export interface BlockHunk {
4
+ export interface Hunk<T> {
5
5
  from: number;
6
6
  to: number;
7
- blocks: Block[];
7
+ blocks: T[];
8
8
  }
9
+ export type BlockHunk = Hunk<Block>;
10
+ /** The edits that turn `base` into `next`, leaving every unchanged item in place: blocks, or a text's lines. */
11
+ export declare const diffSequence: <T>(base: T[], next: T[], keyOf: (item: T) => string) => Hunk<T>[];
9
12
  /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
10
13
  export declare const diffBlocks: (base: Block[], next: Block[], keyOf?: (block: Block) => string) => BlockHunk[];
11
14
  /** A stretch both sides changed differently: the blocks it held at the last sync and on each side now. */
@@ -24,10 +27,17 @@ export type Merged = {
24
27
  } | {
25
28
  status: "unaligned";
26
29
  };
30
+ /** Two hunks touch the same stretch: their ranges overlap, both insert at one point, or one inserts inside the other. */
31
+ export declare const touches: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean;
32
+ /** Two hunks touch or sit side by side with no unchanged item between them: Git's diff3 conflicts on both. */
33
+ export declare const adjoins: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean;
34
+ /** `base[from, to)` with `hunks`, which lie inside it in order, applied. */
35
+ export declare const applied: <T>(base: T[], from: number, to: number, hunks: Hunk<T>[]) => T[];
27
36
  /**
28
37
  * Three-way merge of a document changed on both sides since the last sync. `baseLocal` and `baseRemote` are each
29
38
  * side as the last sync left it; they hold the same blocks, though a tick may differ. Blocks line up by their
30
39
  * shape, so a checklist tick never collides with a text edit: each tick follows the side that changed it, the
31
40
  * remote when neither did. A stretch both sides changed differently is a conflict, settled by `keep` when given.
41
+ * `overlap` decides which hunks share a stretch; `adjoins` also joins neighbours, as a file merge needs.
32
42
  */
33
- export declare const mergeBlocks: (baseLocal: Block[], baseRemote: Block[], local: Block[], remote: Block[], keep?: Keep) => Merged;
43
+ export declare const mergeBlocks: (baseLocal: Block[], baseRemote: Block[], local: Block[], remote: Block[], keep?: Keep, overlap?: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean) => Merged;
@@ -1,6 +1,6 @@
1
1
  import { blockKey, blockShape } from "../../documents/blocks.js";
2
2
  const MAX_CELLS = 4_000_000;
3
- /** Longest common subsequence: index pairs [inA, inB] of blocks with equal keys, in order. */
3
+ /** Longest common subsequence: index pairs [inA, inB] of items with equal keys, in order. */
4
4
  const matches = (a, b, keyOf) => {
5
5
  const ka = a.map(keyOf);
6
6
  const kb = b.map(keyOf);
@@ -47,8 +47,8 @@ const matches = (a, b, keyOf) => {
47
47
  pairs.push([endA + offset, endB + offset]);
48
48
  return pairs;
49
49
  };
50
- /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
51
- export const diffBlocks = (base, next, keyOf = blockKey) => {
50
+ /** The edits that turn `base` into `next`, leaving every unchanged item in place: blocks, or a text's lines. */
51
+ export const diffSequence = (base, next, keyOf) => {
52
52
  const hunks = [];
53
53
  let a = 0;
54
54
  let b = 0;
@@ -60,14 +60,19 @@ export const diffBlocks = (base, next, keyOf = blockKey) => {
60
60
  }
61
61
  return hunks;
62
62
  };
63
+ /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
64
+ export const diffBlocks = (base, next, keyOf = blockKey) => diffSequence(base, next, keyOf);
63
65
  const isCheck = (block) => block?.kind === "item" && block.list === "check";
64
66
  const sameKeys = (a, b) => a.length === b.length && a.every((block, index) => blockKey(block) === blockKey(b[index]));
65
67
  /** Two hunks touch the same stretch: their ranges overlap, both insert at one point, or one inserts inside the other. */
66
- const touches = (a, b) => Math.max(a.from, b.from) < Math.min(a.to, b.to) ||
68
+ export const touches = (a, b) => Math.max(a.from, b.from) < Math.min(a.to, b.to) ||
67
69
  a.from === b.from ||
68
70
  (a.from === a.to && b.from < a.from && a.from < b.to) ||
69
71
  (b.from === b.to && a.from < b.from && b.from < a.to);
70
- const applied = (base, from, to, hunks) => {
72
+ /** Two hunks touch or sit side by side with no unchanged item between them: Git's diff3 conflicts on both. */
73
+ export const adjoins = (a, b) => touches(a, b) || a.to === b.from || b.to === a.from;
74
+ /** `base[from, to)` with `hunks`, which lie inside it in order, applied. */
75
+ export const applied = (base, from, to, hunks) => {
71
76
  let out = [];
72
77
  let at = from;
73
78
  for (const hunk of hunks) {
@@ -81,8 +86,9 @@ const applied = (base, from, to, hunks) => {
81
86
  * side as the last sync left it; they hold the same blocks, though a tick may differ. Blocks line up by their
82
87
  * shape, so a checklist tick never collides with a text edit: each tick follows the side that changed it, the
83
88
  * remote when neither did. A stretch both sides changed differently is a conflict, settled by `keep` when given.
89
+ * `overlap` decides which hunks share a stretch; `adjoins` also joins neighbours, as a file merge needs.
84
90
  */
85
- export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep) => {
91
+ export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep, overlap = touches) => {
86
92
  if (baseLocal.length !== baseRemote.length ||
87
93
  baseLocal.some((block, index) => blockShape(block) !== blockShape(baseRemote[index])))
88
94
  return { status: "unaligned" };
@@ -93,7 +99,7 @@ export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep) => {
93
99
  const clusters = [];
94
100
  for (const hunk of tagged) {
95
101
  const last = clusters.at(-1);
96
- if (last?.some((other) => touches(other, hunk)))
102
+ if (last?.some((other) => overlap(other, hunk)))
97
103
  last.push(hunk);
98
104
  else
99
105
  clusters.push([hunk]);
@@ -1,4 +1,4 @@
1
- import type { SourceContent, SourceFile } from "../../documents/model.js";
1
+ import type { SourceContent, SourceFile, SourceRemoval } from "../../documents/model.js";
2
2
  import type { CatalogInput, CatalogQuery, MessageStore } from "../../store/index.js";
3
3
  export interface IngestionOptions<M extends SourceFile> {
4
4
  /**
@@ -35,5 +35,24 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
35
35
  until: () => boolean;
36
36
  }) => Promise<number>;
37
37
  save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
38
- remove: (principal: string, id: string) => Promise<void>;
38
+ remove: (principal: string, id: string, reason?: SourceRemoval) => Promise<void>;
39
+ prune: (principal: string, before: string) => Promise<{
40
+ versions: number;
41
+ changes: number;
42
+ texts: number;
43
+ } | undefined>;
44
+ /** The profile's local history: earlier versions of a document and what changed when. */
45
+ history: {
46
+ /** `id` is the source's id, or a `document:<n>` ref; a removed document is found too. */
47
+ reference: (principal: string, id: string) => Promise<string | undefined>;
48
+ versions: (reference: string) => Promise<import("../../store/index.js").DocumentHistoryAnswer>;
49
+ version: (reference: string, revision: number) => Promise<import("../../store/index.js").DocumentVersionText>;
50
+ changes: (principal: string, query: Parameters<MessageStore["notes"]["documentChanges"]>[1]) => Promise<{
51
+ items: import("../../store/index.js").DocumentChange[];
52
+ hasMore: boolean;
53
+ } | {
54
+ items: never[];
55
+ hasMore: boolean;
56
+ }>;
57
+ };
39
58
  };
@@ -101,7 +101,7 @@ export const documentIngestion = (store, options) => {
101
101
  await options.observed?.(principal, content.metadata, note.id);
102
102
  return note.ref;
103
103
  },
104
- remove: async (principal, id) => {
104
+ remove: async (principal, id, reason) => {
105
105
  const selected = await folder(principal, false);
106
106
  if (selected) {
107
107
  const path = options.externalId(id);
@@ -110,8 +110,35 @@ export const documentIngestion = (store, options) => {
110
110
  const ref = note?.ref ?? retired?.ref;
111
111
  if (ref)
112
112
  await stale(ref);
113
- await store.notes.deleteFileNotes(selected.id, [path]);
113
+ await store.notes.deleteFileNotes(selected.id, [path], reason);
114
114
  }
115
115
  },
116
+ prune: async (principal, before) => {
117
+ const selected = await folder(principal, false);
118
+ return selected ? store.notes.pruneDocumentHistory?.(selected.id, before) : undefined;
119
+ },
120
+ /** The profile's local history: earlier versions of a document and what changed when. */
121
+ history: {
122
+ /** `id` is the source's id, or a `document:<n>` ref; a removed document is found too. */
123
+ reference: async (principal, id) => {
124
+ if (/^document:\d+$/.test(id))
125
+ return id;
126
+ const selected = await folder(principal, false);
127
+ if (!selected)
128
+ return undefined;
129
+ for (const path of both(id)) {
130
+ const found = await store.notes.documentAt(selected.id, path);
131
+ if (found)
132
+ return found;
133
+ }
134
+ return undefined;
135
+ },
136
+ versions: (reference) => store.notes.documentHistory(reference),
137
+ version: (reference, revision) => store.notes.documentVersion(reference, revision),
138
+ changes: async (principal, query) => {
139
+ const selected = await folder(principal, false);
140
+ return selected ? store.notes.documentChanges(selected.id, query) : { items: [], hasMore: false };
141
+ },
142
+ },
116
143
  };
117
144
  };
@@ -45,7 +45,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
45
45
  cursor: state.cursor ?? "",
46
46
  folders: {},
47
47
  skipped: [],
48
- jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove" })),
48
+ jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove", reason: "unsynced" })),
49
49
  },
50
50
  };
51
51
  if (!source)
@@ -78,11 +78,13 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
78
78
  changed.add(file.id);
79
79
  delta.set(file.id, file);
80
80
  };
81
- const drop = (id) => {
81
+ const removals = new Map();
82
+ const drop = (id, reason) => {
82
83
  const known = files.get(id);
83
84
  if (known)
84
85
  delta.set(id, { ...known, trashed: true });
85
86
  files.delete(id);
87
+ removals.set(id, reason);
86
88
  };
87
89
  const container = (file) => {
88
90
  if (options.isDocument?.(file))
@@ -126,7 +128,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
126
128
  // Apply all ancestry changes before classifying document scope.
127
129
  for (const change of latest.values()) {
128
130
  if (change.removed || change.file?.trashed) {
129
- drop(change.id);
131
+ drop(change.id, change.file?.trashed ? "deleted" : (change.gone ?? "unavailable"));
130
132
  if (folders[change.id])
131
133
  folders[change.id] = { ...folders[change.id], trashed: true };
132
134
  }
@@ -188,8 +190,9 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
188
190
  const visited = new Set(walk.visited);
189
191
  Object.assign(folders, walk.folders);
190
192
  for (const file of walk.files) {
193
+ // A walk saved part way keeps no reason; one it cannot prove is a deletion keeps the text.
191
194
  if (file.trashed)
192
- drop(file.id);
195
+ drop(file.id, "unavailable");
193
196
  else
194
197
  keep(file);
195
198
  }
@@ -280,7 +283,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
280
283
  walk.stack.pop();
281
284
  visited.add(folder.id);
282
285
  folders[folder.id] = { ...folder, trashed: true };
283
- drop(folder.id);
286
+ drop(folder.id, "unavailable");
284
287
  spent++;
285
288
  listed++;
286
289
  continue;
@@ -386,10 +389,16 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
386
389
  // After every real edit, so a run that stops on its deadline spends it on those first.
387
390
  for (const job of again)
388
391
  jobs.push(job);
392
+ // Absent from the listing is not a deletion: only the source's own signal is (`drop`). Out of scope is `unsynced`
393
+ // only when the owner changed the scope; a folder above that was unshared or vanished leaves its files unavailable.
394
+ const narrowed = state.scope !== scope;
389
395
  for (const id of Object.keys(state.documents)) {
390
396
  const file = files.get(id);
391
- if (!file || !inScope(file, roots, folders, matched, scoped))
392
- jobs.push({ id, kind: "remove" });
397
+ const known = file ?? state.documents[id]?.metadata;
398
+ if (file && inScope(file, roots, folders, matched, scoped))
399
+ continue;
400
+ const outside = narrowed && known !== undefined && !inScope(known, roots, folders, matched, scoped);
401
+ jobs.push({ id, kind: "remove", reason: removals.get(id) ?? (outside ? "unsynced" : "unavailable") });
393
402
  }
394
403
  // Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
395
404
  const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => roots.includes(file.id) || (!excluded(file) && within(file, roots, folders, new Set(), cut))));
@@ -43,5 +43,7 @@ export interface SyncOptions<M extends SourceFile> {
43
43
  signal?: AbortSignal;
44
44
  rescan?: boolean;
45
45
  pictures?: boolean;
46
+ /** How long earlier versions and the change log are kept, in days (`keep_versions_for_days`); 365 unless given. */
47
+ keepVersionsForDays?: number;
46
48
  now?(): number;
47
49
  }
@@ -1,6 +1,7 @@
1
1
  import type { SourceFile } from "../../documents/model.js";
2
2
  import { type WalkStop } from "./plan.js";
3
3
  import type { SyncOptions } from "./ports.js";
4
+ export declare const KEEP_VERSIONS_FOR_DAYS = 365;
4
5
  export interface SyncResult {
5
6
  saved: number;
6
7
  names_only: number;
@@ -8,6 +8,8 @@ const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
8
8
  const SAVE_EVERY_MS = 2000;
9
9
  const SAVE_EVERY_ITEMS = 25;
10
10
  const SETTLE_MS = 10_000;
11
+ const DAY_MS = 24 * 60 * 60 * 1000;
12
+ export const KEEP_VERSIONS_FOR_DAYS = 365;
11
13
  const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
12
14
  const hashText = (text) => createHash("sha256").update(text).digest("hex");
13
15
  export const syncDocuments = async (options) => {
@@ -53,7 +55,7 @@ export const syncDocuments = async (options) => {
53
55
  // Work the new plan cannot see: a file saved to the index before its state was.
54
56
  for (const job of state.pending.jobs)
55
57
  if (!state.documents[job.id]) {
56
- await index.remove(profile.principal, job.id);
58
+ await index.remove(profile.principal, job.id, "unsynced");
57
59
  statePort.removeSnapshot(job.id);
58
60
  }
59
61
  delete state.pending;
@@ -166,7 +168,7 @@ export const syncDocuments = async (options) => {
166
168
  lock.assertHeld();
167
169
  try {
168
170
  if (job.kind === "remove") {
169
- await index.remove(profile.principal, job.id);
171
+ await index.remove(profile.principal, job.id, job.reason ?? "unavailable");
170
172
  statePort.removeSnapshot(job.id);
171
173
  delete state.documents[job.id];
172
174
  result.removed++;
@@ -190,7 +192,7 @@ export const syncDocuments = async (options) => {
190
192
  const content = await source.content(job.id, limit, job.file);
191
193
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
192
194
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
193
- await index.remove(profile.principal, job.id);
195
+ await index.remove(profile.principal, job.id, "unsynced");
194
196
  statePort.removeSnapshot(job.id);
195
197
  delete state.documents[job.id];
196
198
  result.removed++;
@@ -235,7 +237,8 @@ export const syncDocuments = async (options) => {
235
237
  if (job.file && safe.code === "validation_error")
236
238
  await saveNamesOnly(job.file, skipped.reason);
237
239
  else {
238
- await index.remove(profile.principal, job.id);
240
+ // A 404 or a refusal says the sign-in cannot read it now, not that it is gone: its text stays.
241
+ await index.remove(profile.principal, job.id, "unavailable");
239
242
  statePort.removeSnapshot(job.id);
240
243
  delete state.documents[job.id];
241
244
  }
@@ -263,6 +266,8 @@ export const syncDocuments = async (options) => {
263
266
  delete state.pending;
264
267
  state.lastSync = new Date(now()).toISOString();
265
268
  statePort.save(state);
269
+ const days = options.keepVersionsForDays ?? KEEP_VERSIONS_FOR_DAYS;
270
+ await index.prune?.(profile.principal, new Date(now() - days * DAY_MS).toISOString());
266
271
  }
267
272
  // A reader that cannot write finds the text by its words only once it is indexed; a search that can write does it
268
273
  // itself, so what this bound leaves, or a failure here, is indexed by the next one. Skipped after a stop, and kept