@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.
- package/CHANGELOG.md +33 -0
- package/dist/attachments/documents.d.ts +5 -0
- package/dist/attachments/documents.js +2 -2
- package/dist/documents/file-mirror-model.d.ts +14 -0
- package/dist/errors/reasons.js +2 -1
- package/dist/office/docx.d.ts +43 -0
- package/dist/office/docx.js +349 -0
- package/dist/office/index.d.ts +2 -0
- package/dist/office/index.js +2 -0
- package/dist/office/package.d.ts +39 -0
- package/dist/office/package.js +98 -0
- package/dist/office/xlsx.d.ts +55 -0
- package/dist/office/xlsx.js +550 -0
- package/dist/office/xml.d.ts +34 -0
- package/dist/office/xml.js +186 -0
- package/dist/office/zip.d.ts +10 -0
- package/dist/office/zip.js +116 -0
- package/dist/services/files/listing.d.ts +28 -0
- package/dist/services/files/listing.js +47 -0
- package/dist/services/files/mirror.d.ts +1 -1
- package/dist/services/files/mirror.js +16 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/people.d.ts +8 -0
- package/dist/store/people.js +2 -0
- package/dist/store/sqlite/account-purge.js +3 -0
- package/dist/store/sqlite/person-erase.d.ts +39 -0
- package/dist/store/sqlite/person-erase.js +152 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,39 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.720.0 — 23.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **A file mirror's remote listing goes on across runs**, so a cloud disk too big to list in one run (100,000 files
|
|
13
|
+
at about 30 s a page) syncs fully over several. `FileTarget.list` takes an optional `from` and may return `next`
|
|
14
|
+
for an incomplete listing; the engine keeps the files so far and `next` in the mirror's state (`listing`), merges
|
|
15
|
+
the next run's files by path and by id, and proves deletions only once the listing completes, each still by a
|
|
16
|
+
direct `exists` read. A saved listing over 7 days old, of another root folder, or past 100,000 files starts over;
|
|
17
|
+
a dry run saves none. A target without `next` lists from the start each run, as before
|
|
18
|
+
([DOCUMENTS.md, point 12](docs/dev/DOCUMENTS.md#sync-plain-files-with-a-provider)).
|
|
19
|
+
- **Edit `.xlsx` cells and `.docx` paragraphs in place** (`@wirecat/cli-core/office`), for a service with no
|
|
20
|
+
document API that downloads and uploads whole files, such as Yandex Disk. `readXlsxCells` and `editXlsxCells` work
|
|
21
|
+
by sheet and A1 address: shared or inline strings, numbers, booleans and empty cells, the cell's format kept, new
|
|
22
|
+
cells and rows in order, formula cells refused unless `overwriteFormulas`, and the workbook marked to calculate
|
|
23
|
+
again on open. `readDocxParagraphs` and `editDocxParagraphs` replace, insert or delete body and table-cell
|
|
24
|
+
paragraphs, keeping each paragraph's properties and its first run's formatting (mixed inline formatting
|
|
25
|
+
collapses, and the result lists where); a paragraph with tracked changes, a field, an image, a comment, a link or
|
|
26
|
+
a footnote is refused with the reason. Only the changed XML is spliced in; every other zip entry is copied byte for
|
|
27
|
+
byte ([Editing Office files](docs/office.md)).
|
|
28
|
+
- **`people.erase` deletes a person and what memo knows of them alone.** Their identities go, with the tags, links,
|
|
29
|
+
aliases, mentions and involvements that name them. A fact, note, task or import record that names them stays and
|
|
30
|
+
loses the name. A message, mail or meeting belongs to its source: the sender stays as an identity with no person,
|
|
31
|
+
and the next sync or people scan gives it one again. `apply: false` answers what would go and changes nothing.
|
|
32
|
+
Owner only; refused for the owner's own person (`person.owner`), and while an invoice, order, subscription or a row
|
|
33
|
+
the person wrote still names them (`person.erase-blocked`).
|
|
34
|
+
|
|
35
|
+
### Fixed
|
|
36
|
+
|
|
37
|
+
- **Removing an import's account now takes the people only its records made.** Its e-mail and phone identities were
|
|
38
|
+
never referenced by anything, so the purge kept them and the person stayed. A person the owner tagged, linked or
|
|
39
|
+
gave a task to, or one another source or a message also names, still stays.
|
|
40
|
+
|
|
8
41
|
## 0.719.0 — 22.11.2026
|
|
9
42
|
|
|
10
43
|
### Added
|
|
@@ -4,6 +4,11 @@ export type DocumentKind = "odt" | "ods" | "odp" | "xlsx" | "pptx" | "epub";
|
|
|
4
4
|
export declare const documentKind: (hint: FileHint) => DocumentKind | undefined;
|
|
5
5
|
/** v2 for spreadsheets: rows under their header instead of one line per cell, so older text is read again. */
|
|
6
6
|
export declare const documentExtractor: (kind: DocumentKind) => string;
|
|
7
|
+
export declare const relationships: (archive: Map<string, Uint8Array>, owner: string) => Map<string, {
|
|
8
|
+
path: string;
|
|
9
|
+
type: string;
|
|
10
|
+
}>;
|
|
11
|
+
export declare const mainPart: (archive: Map<string, Uint8Array>, contentType: string) => string;
|
|
7
12
|
/** The cells of an XLSX or ODS workbook, one `Sheet` per worksheet in workbook order, values as displayed. */
|
|
8
13
|
export declare const readSpreadsheet: (bytes: Uint8Array, kind: "xlsx" | "ods", signal?: AbortSignal) => Promise<Sheet[]>;
|
|
9
14
|
export declare const readDocument: (bytes: Uint8Array, kind: DocumentKind, signal?: AbortSignal) => Promise<Extraction>;
|
|
@@ -83,7 +83,7 @@ const target = (owner, reference) => {
|
|
|
83
83
|
throw new Error("external_part");
|
|
84
84
|
return path;
|
|
85
85
|
};
|
|
86
|
-
const relationships = (archive, owner) => {
|
|
86
|
+
export const relationships = (archive, owner) => {
|
|
87
87
|
const path = owner ? posix.join(posix.dirname(owner), "_rels", `${posix.basename(owner)}.rels`) : "_rels/.rels";
|
|
88
88
|
const document = xmlPart(archive, path);
|
|
89
89
|
rootIs(document, "Relationships", [PACKAGE_REL]);
|
|
@@ -102,7 +102,7 @@ const relationships = (archive, owner) => {
|
|
|
102
102
|
return result;
|
|
103
103
|
};
|
|
104
104
|
const relationId = (element) => required(attribute(element, "id", REL) || attribute(element, "id", STRICT_REL));
|
|
105
|
-
const mainPart = (archive, contentType) => {
|
|
105
|
+
export const mainPart = (archive, contentType) => {
|
|
106
106
|
const types = xmlPart(archive, "[Content_Types].xml");
|
|
107
107
|
const namespace = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
108
108
|
rootIs(types, "Types", [namespace]);
|
|
@@ -30,13 +30,17 @@ export interface FileTarget {
|
|
|
30
30
|
* Every file under `root`, with the root folder's own id; undefined when the folder does not exist. `complete` is
|
|
31
31
|
* false when any page was skipped or a cap was hit: a file missing from such a listing is not taken as deleted.
|
|
32
32
|
* Files at paths `excluded` names are listed too, so a file moved there is found by its id, but count toward no cap.
|
|
33
|
+
* An incomplete listing that can go on later returns `next`, its position; given back as `from` in a later run, the
|
|
34
|
+
* listing returns only the files from there on.
|
|
33
35
|
*/
|
|
34
36
|
list(root: string, signal?: AbortSignal, options?: {
|
|
35
37
|
excluded?(path: string): boolean;
|
|
38
|
+
from?: string;
|
|
36
39
|
}): Promise<{
|
|
37
40
|
rootId: string;
|
|
38
41
|
files: RemoteFile[];
|
|
39
42
|
complete: boolean;
|
|
43
|
+
next?: string;
|
|
40
44
|
} | undefined>;
|
|
41
45
|
/**
|
|
42
46
|
* Whether anything is at `path` now, read directly rather than from a listing; false only when the provider says
|
|
@@ -90,6 +94,16 @@ export interface FileMirrorState {
|
|
|
90
94
|
operationId: string;
|
|
91
95
|
created?: boolean;
|
|
92
96
|
}>;
|
|
97
|
+
/**
|
|
98
|
+
* A remote listing that stopped before its end: the files listed so far and where the next run goes on. Cleared once
|
|
99
|
+
* a run completes it, or when it is too old, of another root, or cannot go on.
|
|
100
|
+
*/
|
|
101
|
+
listing?: {
|
|
102
|
+
rootId: string;
|
|
103
|
+
startedAt: string;
|
|
104
|
+
next: string;
|
|
105
|
+
files: RemoteFile[];
|
|
106
|
+
};
|
|
93
107
|
}
|
|
94
108
|
export interface FileMirrorStatePort {
|
|
95
109
|
read(): FileMirrorState;
|
package/dist/errors/reasons.js
CHANGED
|
@@ -583,8 +583,9 @@ const OTHERS = [
|
|
|
583
583
|
["person.no-owner", "not_found", "no person is marked as the owner in the store"],
|
|
584
584
|
["person.unknown", "not_found", "the store has no person by that reference; people list gives person:<uid>"],
|
|
585
585
|
["person.no-doubt", "not_found", "nothing about that person is in doubt; people links check lists who is"],
|
|
586
|
-
validation("person.owner", "the owner's own person is not test data"),
|
|
586
|
+
validation("person.owner", "the owner's own person is not test data, and is never deleted"),
|
|
587
587
|
validation("person.no-identity", "a person with no identity is not test data; there is nothing to hide"),
|
|
588
|
+
validation("person.erase-blocked", "an invoice, order, subscription or a row the person wrote still names them; change those first, nothing was deleted"),
|
|
588
589
|
validation("person.from-required", "say whom the identity leaves: --from person:<uid>, or person:me for the owner"),
|
|
589
590
|
[
|
|
590
591
|
"identity.separated",
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface DocxParagraph {
|
|
2
|
+
/** Position among the body's paragraphs, table cells included, in document order; edits address it. */
|
|
3
|
+
readonly index: number;
|
|
4
|
+
readonly text: string;
|
|
5
|
+
readonly styleId?: string;
|
|
6
|
+
/** The style's display name from styles.xml, such as "Heading 1". */
|
|
7
|
+
readonly style?: string;
|
|
8
|
+
readonly location: "body" | "table";
|
|
9
|
+
/** Whether `editDocxParagraphs` may replace or delete it; `reason` says why not. */
|
|
10
|
+
readonly editable: boolean;
|
|
11
|
+
readonly reason?: string;
|
|
12
|
+
/** Runs with different formatting: replacing the text collapses them to the first run's formatting. */
|
|
13
|
+
readonly mixedFormatting: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type DocxEdit = {
|
|
16
|
+
readonly index: number;
|
|
17
|
+
readonly text: string;
|
|
18
|
+
}
|
|
19
|
+
/** `insertAfter: -1` puts the paragraph before the first one. `styleFrom` defaults to the neighbour. */
|
|
20
|
+
| {
|
|
21
|
+
readonly insertAfter: number;
|
|
22
|
+
readonly text: string;
|
|
23
|
+
readonly styleFrom?: number;
|
|
24
|
+
} | {
|
|
25
|
+
readonly delete: number;
|
|
26
|
+
};
|
|
27
|
+
export interface EditDocxResult {
|
|
28
|
+
readonly bytes: Uint8Array;
|
|
29
|
+
readonly replaced: number[];
|
|
30
|
+
readonly inserted: number;
|
|
31
|
+
readonly deleted: number[];
|
|
32
|
+
/** Replaced paragraphs whose mixed inline formatting (bold words, links of colour) became the first run's. */
|
|
33
|
+
readonly collapsed: number[];
|
|
34
|
+
}
|
|
35
|
+
/** The body's paragraphs, table cells included, with their style and whether the editor can change them. */
|
|
36
|
+
export declare const readDocxParagraphs: (bytes: Uint8Array) => Promise<DocxParagraph[]>;
|
|
37
|
+
/**
|
|
38
|
+
* Edits paragraph text in place: only document.xml is rewritten, by splicing the edited paragraphs into its original
|
|
39
|
+
* text, and every other zip entry is copied byte for byte. Indexes refer to the document as it was read. A replaced
|
|
40
|
+
* paragraph keeps its properties (style, numbering, alignment) and its first text run's formatting; the rest of its
|
|
41
|
+
* inline formatting collapses to that (listed in `collapsed`).
|
|
42
|
+
*/
|
|
43
|
+
export declare const editDocxParagraphs: (bytes: Uint8Array, edits: readonly DocxEdit[]) => Promise<EditDocxResult>;
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { OfficePackage, openTag, qualified } from "./package.js";
|
|
3
|
+
import { attributeOf, childrenOf, contentText, escapeText } from "./xml.js";
|
|
4
|
+
const MAIN = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
|
|
5
|
+
const WORD_NAMESPACES = [
|
|
6
|
+
"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
|
|
7
|
+
"http://purl.oclc.org/ooxml/wordprocessingml/main",
|
|
8
|
+
];
|
|
9
|
+
const refuse = (message, reason) => new CliError("validation_error", message, { reason });
|
|
10
|
+
/** Run content that is plain text; anything else in a run makes the paragraph read-only. */
|
|
11
|
+
const RUN_TEXT = new Set(["rPr", "t", "tab", "br", "cr", "noBreakHyphen", "softHyphen", "lastRenderedPageBreak"]);
|
|
12
|
+
const RUN_REASONS = {
|
|
13
|
+
drawing: "an image or a drawing",
|
|
14
|
+
pict: "an image or a drawing",
|
|
15
|
+
object: "an embedded object",
|
|
16
|
+
fldChar: "a field",
|
|
17
|
+
instrText: "a field",
|
|
18
|
+
footnoteReference: "a footnote reference",
|
|
19
|
+
endnoteReference: "an endnote reference",
|
|
20
|
+
footnoteRef: "a footnote mark",
|
|
21
|
+
endnoteRef: "an endnote mark",
|
|
22
|
+
commentReference: "a comment",
|
|
23
|
+
annotationRef: "a comment",
|
|
24
|
+
delText: "a tracked change",
|
|
25
|
+
delInstrText: "a tracked change",
|
|
26
|
+
sym: "a symbol",
|
|
27
|
+
ruby: "ruby text",
|
|
28
|
+
ptab: "a positional tab",
|
|
29
|
+
separator: "a footnote separator",
|
|
30
|
+
continuationSeparator: "a footnote separator",
|
|
31
|
+
};
|
|
32
|
+
const PARAGRAPH_REASONS = {
|
|
33
|
+
ins: "a tracked change",
|
|
34
|
+
del: "a tracked change",
|
|
35
|
+
moveFrom: "a tracked change",
|
|
36
|
+
moveTo: "a tracked change",
|
|
37
|
+
moveFromRangeStart: "a tracked change",
|
|
38
|
+
moveFromRangeEnd: "a tracked change",
|
|
39
|
+
moveToRangeStart: "a tracked change",
|
|
40
|
+
moveToRangeEnd: "a tracked change",
|
|
41
|
+
commentRangeStart: "a comment",
|
|
42
|
+
commentRangeEnd: "a comment",
|
|
43
|
+
hyperlink: "a hyperlink",
|
|
44
|
+
fldSimple: "a field",
|
|
45
|
+
sdt: "a content control",
|
|
46
|
+
smartTag: "a smart tag",
|
|
47
|
+
customXml: "custom XML markup",
|
|
48
|
+
subDoc: "a subdocument",
|
|
49
|
+
oMath: "an equation",
|
|
50
|
+
oMathPara: "an equation",
|
|
51
|
+
};
|
|
52
|
+
/** Kept in place of the old runs: bookmark starts go first, ends last, so cross-references still find them. */
|
|
53
|
+
const MARKERS = new Set(["bookmarkStart", "bookmarkEnd", "permStart", "permEnd"]);
|
|
54
|
+
const TRACKED_PROPERTIES = new Set(["pPrChange", "rPrChange", "ins", "del", "moveFrom", "moveTo"]);
|
|
55
|
+
const CONTAINERS = new Set(["tbl", "tr", "tc", "sdt", "sdtContent", "customXml"]);
|
|
56
|
+
const hasTracked = (element) => !!element?.children.some((child) => TRACKED_PROPERTIES.has(child.local) || hasTracked(child));
|
|
57
|
+
class Document {
|
|
58
|
+
pack;
|
|
59
|
+
ns;
|
|
60
|
+
part;
|
|
61
|
+
found = [];
|
|
62
|
+
styles = new Map();
|
|
63
|
+
constructor(pack) {
|
|
64
|
+
this.pack = pack;
|
|
65
|
+
this.part = pack.part(pack.main(MAIN));
|
|
66
|
+
const root = this.part.root;
|
|
67
|
+
this.ns = root.ns;
|
|
68
|
+
if (root.local !== "document" || !WORD_NAMESPACES.includes(this.ns))
|
|
69
|
+
throw refuse("the file is not a Word document", "office.wrong_format");
|
|
70
|
+
const body = childrenOf(root, this.ns, "body")[0];
|
|
71
|
+
if (!body)
|
|
72
|
+
throw refuse("the document has no body", "office.wrong_format");
|
|
73
|
+
this.walk(body, "body", false);
|
|
74
|
+
const styles = pack.related(this.part.path, "styles");
|
|
75
|
+
if (styles && pack.has(styles[1].path)) {
|
|
76
|
+
const part = pack.part(styles[1].path);
|
|
77
|
+
for (const style of childrenOf(part.root, this.ns, "style")) {
|
|
78
|
+
const id = attributeOf(style, this.ns, "styleId");
|
|
79
|
+
const name = childrenOf(style, this.ns, "name")[0];
|
|
80
|
+
if (id && name)
|
|
81
|
+
this.styles.set(id, attributeOf(name, this.ns, "val") ?? id);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
static async open(bytes) {
|
|
86
|
+
return new Document(await OfficePackage.open(bytes, "Word document"));
|
|
87
|
+
}
|
|
88
|
+
walk(container, location, locked) {
|
|
89
|
+
for (const child of container.children) {
|
|
90
|
+
if (child.ns !== this.ns)
|
|
91
|
+
continue;
|
|
92
|
+
if (child.local === "p")
|
|
93
|
+
this.found.push({ element: child, location, lockedControl: locked });
|
|
94
|
+
else if (CONTAINERS.has(child.local)) {
|
|
95
|
+
const properties = child.local === "sdt" ? childrenOf(child, this.ns, "sdtPr")[0] : undefined;
|
|
96
|
+
const lock = properties && childrenOf(properties, this.ns, "lock")[0];
|
|
97
|
+
const lockValue = lock && attributeOf(lock, this.ns, "val");
|
|
98
|
+
const controlLocked = !!properties &&
|
|
99
|
+
(lockValue === "contentLocked" ||
|
|
100
|
+
lockValue === "sdtContentLocked" ||
|
|
101
|
+
properties.children.some((entry) => entry.local === "dataBinding"));
|
|
102
|
+
this.walk(child, child.local === "tbl" ? "table" : location, locked || controlLocked);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
raw(element) {
|
|
107
|
+
return this.part.text.slice(element.start, element.end);
|
|
108
|
+
}
|
|
109
|
+
/** Why a paragraph cannot be rewritten, or undefined when it holds only plain runs. */
|
|
110
|
+
reasonOf(found) {
|
|
111
|
+
if (found.lockedControl)
|
|
112
|
+
return "it sits in a locked or data-bound content control";
|
|
113
|
+
for (const child of found.element.children) {
|
|
114
|
+
if (child.ns !== this.ns)
|
|
115
|
+
return child.local === "AlternateContent" ? "an image or a drawing" : `<${child.name}>`;
|
|
116
|
+
if (child.local === "pPr") {
|
|
117
|
+
if (hasTracked(child))
|
|
118
|
+
return "a tracked change";
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (child.local === "proofErr" || MARKERS.has(child.local))
|
|
122
|
+
continue;
|
|
123
|
+
if (child.local !== "r")
|
|
124
|
+
return PARAGRAPH_REASONS[child.local] ?? `<${child.name}>`;
|
|
125
|
+
for (const part of child.children) {
|
|
126
|
+
if (part.ns !== this.ns)
|
|
127
|
+
return part.local === "AlternateContent" ? "an image or a drawing" : `<${part.name}>`;
|
|
128
|
+
if (part.local === "rPr" && hasTracked(part))
|
|
129
|
+
return "a tracked change";
|
|
130
|
+
if (part.local === "br" && ["page", "column"].includes(attributeOf(part, this.ns, "type") ?? ""))
|
|
131
|
+
return "a page or column break";
|
|
132
|
+
if (!RUN_TEXT.has(part.local))
|
|
133
|
+
return RUN_REASONS[part.local] ?? `<${part.name}>`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
textOf(element) {
|
|
139
|
+
let text = "";
|
|
140
|
+
for (const child of element.children) {
|
|
141
|
+
if (child.ns !== this.ns)
|
|
142
|
+
continue;
|
|
143
|
+
if (child.local === "t")
|
|
144
|
+
text += contentText(this.part.text.slice(child.openEnd, child.closeStart));
|
|
145
|
+
else if (child.local === "tab")
|
|
146
|
+
text += "\t";
|
|
147
|
+
else if (child.local === "br" || child.local === "cr")
|
|
148
|
+
text += "\n";
|
|
149
|
+
else if (child.local === "noBreakHyphen")
|
|
150
|
+
text += "‑";
|
|
151
|
+
else if (child.local === "softHyphen")
|
|
152
|
+
text += "";
|
|
153
|
+
else if (!["pPr", "rPr", "del", "moveFrom", "drawing", "pict", "object", "instrText"].includes(child.local))
|
|
154
|
+
text += this.textOf(child);
|
|
155
|
+
}
|
|
156
|
+
return text;
|
|
157
|
+
}
|
|
158
|
+
runs(element) {
|
|
159
|
+
return childrenOf(element, this.ns, "r");
|
|
160
|
+
}
|
|
161
|
+
/** The formatting a rewritten paragraph's single run takes: the first run that holds text. */
|
|
162
|
+
firstRunProperties(element) {
|
|
163
|
+
const runs = this.runs(element);
|
|
164
|
+
const run = runs.find((candidate) => this.textOf(candidate) !== "") ?? runs[0];
|
|
165
|
+
const properties = run && childrenOf(run, this.ns, "rPr")[0];
|
|
166
|
+
return properties ? this.raw(properties) : "";
|
|
167
|
+
}
|
|
168
|
+
mixed(element) {
|
|
169
|
+
const formats = new Set(this.runs(element)
|
|
170
|
+
.filter((run) => this.textOf(run) !== "")
|
|
171
|
+
.map((run) => {
|
|
172
|
+
const properties = childrenOf(run, this.ns, "rPr")[0];
|
|
173
|
+
return properties ? this.raw(properties) : "";
|
|
174
|
+
}));
|
|
175
|
+
return formats.size > 1;
|
|
176
|
+
}
|
|
177
|
+
paragraphs() {
|
|
178
|
+
return this.found.map((found, index) => {
|
|
179
|
+
const element = found.element;
|
|
180
|
+
const properties = childrenOf(element, this.ns, "pPr")[0];
|
|
181
|
+
const styleElement = properties && childrenOf(properties, this.ns, "pStyle")[0];
|
|
182
|
+
const styleId = styleElement && attributeOf(styleElement, this.ns, "val");
|
|
183
|
+
const reason = this.reasonOf(found);
|
|
184
|
+
const style = styleId && this.styles.get(styleId);
|
|
185
|
+
return {
|
|
186
|
+
index,
|
|
187
|
+
text: this.textOf(element),
|
|
188
|
+
...(styleId ? { styleId } : {}),
|
|
189
|
+
...(style ? { style } : {}),
|
|
190
|
+
location: found.location,
|
|
191
|
+
editable: reason === undefined,
|
|
192
|
+
...(reason === undefined
|
|
193
|
+
? {}
|
|
194
|
+
: {
|
|
195
|
+
reason: reason.startsWith("<")
|
|
196
|
+
? `unsupported element ${reason}`
|
|
197
|
+
: reason.startsWith("it ")
|
|
198
|
+
? reason
|
|
199
|
+
: `it holds ${reason}`,
|
|
200
|
+
}),
|
|
201
|
+
mixedFormatting: this.mixed(element),
|
|
202
|
+
};
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
/** The paragraph properties without a section break, which must not be copied into a new paragraph. */
|
|
206
|
+
propertiesForCopy(element) {
|
|
207
|
+
const properties = childrenOf(element, this.ns, "pPr")[0];
|
|
208
|
+
if (!properties)
|
|
209
|
+
return "";
|
|
210
|
+
if (hasTracked(properties))
|
|
211
|
+
throw refuse("the paragraph to copy the style from holds a tracked change", "office.tracked_change");
|
|
212
|
+
let raw = this.raw(properties);
|
|
213
|
+
for (const section of childrenOf(properties, this.ns, "sectPr").reverse())
|
|
214
|
+
raw = raw.slice(0, section.start - properties.start) + raw.slice(section.end - properties.start);
|
|
215
|
+
return raw;
|
|
216
|
+
}
|
|
217
|
+
runsXml(element, text, runProperties) {
|
|
218
|
+
if (!text)
|
|
219
|
+
return "";
|
|
220
|
+
const r = qualified(element, "r");
|
|
221
|
+
const t = qualified(element, "t");
|
|
222
|
+
const content = text
|
|
223
|
+
.split(/(\n|\t)/)
|
|
224
|
+
.filter((piece) => piece !== "")
|
|
225
|
+
.map((piece) => piece === "\n"
|
|
226
|
+
? `<${qualified(element, "br")}/>`
|
|
227
|
+
: piece === "\t"
|
|
228
|
+
? `<${qualified(element, "tab")}/>`
|
|
229
|
+
: `<${t} xml:space="preserve">${escapeText(piece)}</${t}>`)
|
|
230
|
+
.join("");
|
|
231
|
+
return `<${r}>${runProperties}${content}</${r}>`;
|
|
232
|
+
}
|
|
233
|
+
rewritten(element, text) {
|
|
234
|
+
const properties = childrenOf(element, this.ns, "pPr")[0];
|
|
235
|
+
const markers = element.children.filter((child) => child.ns === this.ns && MARKERS.has(child.local));
|
|
236
|
+
const starts = markers.filter((marker) => marker.local.endsWith("Start")).map((marker) => this.raw(marker));
|
|
237
|
+
const ends = markers.filter((marker) => marker.local.endsWith("End")).map((marker) => this.raw(marker));
|
|
238
|
+
return `${openTag(this.part.text, element)}${properties ? this.raw(properties) : ""}${starts.join("")}${this.runsXml(element, text, this.firstRunProperties(element))}${ends.join("")}</${element.name}>`;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** The body's paragraphs, table cells included, with their style and whether the editor can change them. */
|
|
242
|
+
export const readDocxParagraphs = async (bytes) => (await Document.open(bytes)).paragraphs();
|
|
243
|
+
const normalized = (text) => text.replace(/\r\n?/g, "\n");
|
|
244
|
+
/**
|
|
245
|
+
* Edits paragraph text in place: only document.xml is rewritten, by splicing the edited paragraphs into its original
|
|
246
|
+
* text, and every other zip entry is copied byte for byte. Indexes refer to the document as it was read. A replaced
|
|
247
|
+
* paragraph keeps its properties (style, numbering, alignment) and its first text run's formatting; the rest of its
|
|
248
|
+
* inline formatting collapses to that (listed in `collapsed`).
|
|
249
|
+
*/
|
|
250
|
+
export const editDocxParagraphs = async (bytes, edits) => {
|
|
251
|
+
const document = await Document.open(bytes);
|
|
252
|
+
const { found } = document;
|
|
253
|
+
const infos = document.paragraphs();
|
|
254
|
+
const check = (index, what) => {
|
|
255
|
+
if (!Number.isInteger(index) || index < 0 || index >= found.length)
|
|
256
|
+
throw refuse(`${what} ${index} does not exist; the document has ${found.length} paragraphs`, "office.no_paragraph");
|
|
257
|
+
return found[index];
|
|
258
|
+
};
|
|
259
|
+
const editable = (index, action) => {
|
|
260
|
+
const info = infos[index];
|
|
261
|
+
if (!info.editable)
|
|
262
|
+
throw refuse(`paragraph ${index} cannot be ${action}: ${info.reason}`, "office.unsafe_paragraph");
|
|
263
|
+
};
|
|
264
|
+
const touched = new Set();
|
|
265
|
+
const once = (index) => {
|
|
266
|
+
if (touched.has(index))
|
|
267
|
+
throw refuse(`paragraph ${index} is changed twice in one call`, "office.duplicate_edit");
|
|
268
|
+
touched.add(index);
|
|
269
|
+
};
|
|
270
|
+
const splices = [];
|
|
271
|
+
const replaced = [];
|
|
272
|
+
const deleted = [];
|
|
273
|
+
const collapsed = [];
|
|
274
|
+
const expected = infos.map((info) => info.text);
|
|
275
|
+
const insertedAfter = new Map();
|
|
276
|
+
let inserted = 0;
|
|
277
|
+
for (const edit of edits) {
|
|
278
|
+
if ("delete" in edit) {
|
|
279
|
+
const target = check(edit.delete, "paragraph");
|
|
280
|
+
once(edit.delete);
|
|
281
|
+
editable(edit.delete, "deleted");
|
|
282
|
+
const properties = childrenOf(target.element, document.ns, "pPr")[0];
|
|
283
|
+
if (properties && childrenOf(properties, document.ns, "sectPr").length)
|
|
284
|
+
throw refuse(`paragraph ${edit.delete} ends a section; deleting it would merge two sections`, "office.section_break");
|
|
285
|
+
if (target.element.children.some((child) => MARKERS.has(child.local)))
|
|
286
|
+
throw refuse(`paragraph ${edit.delete} holds a bookmark that a cross-reference may point at`, "office.bookmark");
|
|
287
|
+
splices.push({ start: target.element.start, end: target.element.end, text: "" });
|
|
288
|
+
deleted.push(edit.delete);
|
|
289
|
+
expected[edit.delete] = undefined;
|
|
290
|
+
}
|
|
291
|
+
else if ("index" in edit) {
|
|
292
|
+
const target = check(edit.index, "paragraph");
|
|
293
|
+
once(edit.index);
|
|
294
|
+
editable(edit.index, "replaced");
|
|
295
|
+
const text = normalized(edit.text);
|
|
296
|
+
splices.push({
|
|
297
|
+
start: target.element.start,
|
|
298
|
+
end: target.element.end,
|
|
299
|
+
text: document.rewritten(target.element, text),
|
|
300
|
+
});
|
|
301
|
+
replaced.push(edit.index);
|
|
302
|
+
if (infos[edit.index].mixedFormatting)
|
|
303
|
+
collapsed.push(edit.index);
|
|
304
|
+
expected[edit.index] = text;
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
if (edit.insertAfter !== -1)
|
|
308
|
+
check(edit.insertAfter, "paragraph");
|
|
309
|
+
if (!found.length)
|
|
310
|
+
throw refuse("the document has no paragraph to insert next to", "office.no_paragraph");
|
|
311
|
+
const neighbour = found[Math.max(0, edit.insertAfter)];
|
|
312
|
+
if (neighbour.lockedControl)
|
|
313
|
+
throw refuse(`paragraph ${edit.insertAfter} sits in a locked content control`, "office.unsafe_paragraph");
|
|
314
|
+
const source = check(edit.styleFrom ?? Math.max(0, edit.insertAfter), "styleFrom paragraph").element;
|
|
315
|
+
const element = neighbour.element;
|
|
316
|
+
const text = normalized(edit.text);
|
|
317
|
+
const p = qualified(element, "p");
|
|
318
|
+
const xml = `<${p}>${document.propertiesForCopy(source)}${document.runsXml(element, text, document.firstRunProperties(source))}</${p}>`;
|
|
319
|
+
const at = edit.insertAfter === -1 ? element.start : element.end;
|
|
320
|
+
splices.push({ start: at, end: at, text: xml });
|
|
321
|
+
insertedAfter.set(edit.insertAfter, [...(insertedAfter.get(edit.insertAfter) ?? []), text]);
|
|
322
|
+
inserted++;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
// Word and LibreOffice expect a paragraph after the last table of the body or a cell; LibreOffice's text export
|
|
326
|
+
// loops on a body that ends in a table.
|
|
327
|
+
const containers = new Set(deleted.map((index) => found[index]?.element.parent));
|
|
328
|
+
for (const container of containers) {
|
|
329
|
+
if (!container || !["tc", "body"].includes(container.local))
|
|
330
|
+
continue;
|
|
331
|
+
const blocks = container.children.filter((child) => child.ns === document.ns && ["p", "tbl", "sdt", "customXml"].includes(child.local));
|
|
332
|
+
const remaining = blocks.filter((block) => !deleted.includes(found.findIndex((entry) => entry.element === block)));
|
|
333
|
+
const addsAtEnd = found.some((entry, index) => insertedAfter.has(index) && entry.element === blocks.at(-1));
|
|
334
|
+
if (!addsAtEnd && remaining.at(-1)?.local !== "p")
|
|
335
|
+
throw refuse(`${container.local === "tc" ? "a table cell" : "the document"} must end with a paragraph; this delete would leave it without one`, "office.last_paragraph");
|
|
336
|
+
}
|
|
337
|
+
if (!edits.length)
|
|
338
|
+
return { bytes: bytes.slice(), replaced, inserted, deleted, collapsed };
|
|
339
|
+
document.pack.write(document.part, splices);
|
|
340
|
+
const output = document.pack.build();
|
|
341
|
+
const after = (await readDocxParagraphs(output)).map((paragraph) => paragraph.text);
|
|
342
|
+
const want = [
|
|
343
|
+
...(insertedAfter.get(-1) ?? []),
|
|
344
|
+
...expected.flatMap((text, index) => [...(text === undefined ? [] : [text]), ...(insertedAfter.get(index) ?? [])]),
|
|
345
|
+
];
|
|
346
|
+
if (after.length !== want.length || after.some((text, index) => text !== want[index]))
|
|
347
|
+
throw new Error("the edited document does not read back as written");
|
|
348
|
+
return { bytes: output, replaced, inserted, deleted, collapsed };
|
|
349
|
+
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { type DocxEdit, type DocxParagraph, type EditDocxResult, editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
|
|
2
|
+
export { type CellType, type CellValue, type EditXlsxOptions, type EditXlsxResult, editXlsxCells, type ReadXlsxOptions, readXlsxCells, type XlsxCell, type XlsxEdit, type XlsxSheet, } from "./xlsx.js";
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type Splice, type XmlElement } from "./xml.js";
|
|
2
|
+
export declare const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
3
|
+
export declare const STRICT_REL = "http://purl.oclc.org/ooxml/officeDocument/relationships";
|
|
4
|
+
export interface Part {
|
|
5
|
+
readonly path: string;
|
|
6
|
+
readonly text: string;
|
|
7
|
+
readonly root: XmlElement;
|
|
8
|
+
}
|
|
9
|
+
/** An Office package opened for editing: its XML parts as text, and the parts the edit changed or removed. */
|
|
10
|
+
export declare class OfficePackage {
|
|
11
|
+
readonly bytes: Uint8Array;
|
|
12
|
+
readonly archive: Map<string, Uint8Array>;
|
|
13
|
+
readonly what: string;
|
|
14
|
+
private readonly changed;
|
|
15
|
+
private constructor();
|
|
16
|
+
static open(bytes: Uint8Array, what: string): Promise<OfficePackage>;
|
|
17
|
+
main(contentType: string): string;
|
|
18
|
+
relationships(owner: string): Map<string, {
|
|
19
|
+
path: string;
|
|
20
|
+
type: string;
|
|
21
|
+
}>;
|
|
22
|
+
related(owner: string, type: string): [string, {
|
|
23
|
+
path: string;
|
|
24
|
+
type: string;
|
|
25
|
+
}] | undefined;
|
|
26
|
+
has(path: string): boolean;
|
|
27
|
+
part(path: string): Part;
|
|
28
|
+
write(part: Part, splices: readonly Splice[]): void;
|
|
29
|
+
remove(path: string): void;
|
|
30
|
+
/** The new file: changed parts recompressed, every other entry copied as it was. */
|
|
31
|
+
build(): Uint8Array<ArrayBuffer>;
|
|
32
|
+
}
|
|
33
|
+
/** A start tag with one attribute set (added at the end when it was not there). */
|
|
34
|
+
export declare const withAttribute: (tag: string, name: string, value: string) => string;
|
|
35
|
+
export declare const withoutAttribute: (tag: string, name: string) => string;
|
|
36
|
+
export declare const startTag: (text: string, element: XmlElement) => string;
|
|
37
|
+
export declare const isSelfClosing: (text: string, element: XmlElement) => boolean;
|
|
38
|
+
export declare const openTag: (text: string, element: XmlElement) => string;
|
|
39
|
+
export declare const qualified: (element: XmlElement, local: string) => string;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { xmlPart } from "../attachments/container.js";
|
|
3
|
+
import { mainPart, relationships } from "../attachments/documents.js";
|
|
4
|
+
import { applySplices, parseXml, partBytes, partText } from "./xml.js";
|
|
5
|
+
import { openPackage, rewriteZip } from "./zip.js";
|
|
6
|
+
export const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
7
|
+
export const STRICT_REL = "http://purl.oclc.org/ooxml/officeDocument/relationships";
|
|
8
|
+
const unreadable = (what, error) => error instanceof CliError
|
|
9
|
+
? error
|
|
10
|
+
: new CliError("validation_error", `the file is not a ${what} this editor reads (${error.message})`);
|
|
11
|
+
/** An Office package opened for editing: its XML parts as text, and the parts the edit changed or removed. */
|
|
12
|
+
export class OfficePackage {
|
|
13
|
+
bytes;
|
|
14
|
+
archive;
|
|
15
|
+
what;
|
|
16
|
+
changed = new Map();
|
|
17
|
+
constructor(bytes, archive, what) {
|
|
18
|
+
this.bytes = bytes;
|
|
19
|
+
this.archive = archive;
|
|
20
|
+
this.what = what;
|
|
21
|
+
}
|
|
22
|
+
static async open(bytes, what) {
|
|
23
|
+
return new OfficePackage(bytes, await openPackage(bytes), what);
|
|
24
|
+
}
|
|
25
|
+
main(contentType) {
|
|
26
|
+
try {
|
|
27
|
+
return mainPart(this.archive, contentType);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw unreadable(this.what, error);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
relationships(owner) {
|
|
34
|
+
try {
|
|
35
|
+
return relationships(this.archive, owner);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
throw unreadable(this.what, error);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
related(owner, type) {
|
|
42
|
+
return [...this.relationships(owner).entries()].find(([, entry]) => entry.type.endsWith(`/${type}`));
|
|
43
|
+
}
|
|
44
|
+
has(path) {
|
|
45
|
+
return this.archive.has(path);
|
|
46
|
+
}
|
|
47
|
+
part(path) {
|
|
48
|
+
const bytes = this.archive.get(path);
|
|
49
|
+
if (!bytes)
|
|
50
|
+
throw new CliError("validation_error", `the ${this.what} has no ${path}`);
|
|
51
|
+
try {
|
|
52
|
+
xmlPart(this.archive, path);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
throw unreadable(this.what, error);
|
|
56
|
+
}
|
|
57
|
+
const text = partText(bytes, path);
|
|
58
|
+
return { path, text, root: parseXml(text) };
|
|
59
|
+
}
|
|
60
|
+
write(part, splices) {
|
|
61
|
+
if (!splices.length)
|
|
62
|
+
return;
|
|
63
|
+
const text = applySplices(part.text, splices);
|
|
64
|
+
const bytes = partBytes(text);
|
|
65
|
+
const archive = new Map(this.archive);
|
|
66
|
+
archive.set(part.path, bytes);
|
|
67
|
+
try {
|
|
68
|
+
xmlPart(archive, part.path);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
throw new Error(`the edit produced invalid XML in ${part.path} (${error.message})`);
|
|
72
|
+
}
|
|
73
|
+
this.changed.set(part.path, bytes);
|
|
74
|
+
}
|
|
75
|
+
remove(path) {
|
|
76
|
+
this.changed.set(path, null);
|
|
77
|
+
}
|
|
78
|
+
/** The new file: changed parts recompressed, every other entry copied as it was. */
|
|
79
|
+
build() {
|
|
80
|
+
return this.changed.size ? rewriteZip(this.bytes, this.changed) : this.bytes.slice();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const escapeAttribute = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll('"', """);
|
|
84
|
+
/** A start tag with one attribute set (added at the end when it was not there). */
|
|
85
|
+
export const withAttribute = (tag, name, value) => {
|
|
86
|
+
const pattern = new RegExp(`(\\s)${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
|
|
87
|
+
if (pattern.test(tag))
|
|
88
|
+
return tag.replace(pattern, `$1${name}="${escapeAttribute(value)}"`);
|
|
89
|
+
return tag.replace(/\s*(\/?)>$/, ` ${name}="${escapeAttribute(value)}"$1>`);
|
|
90
|
+
};
|
|
91
|
+
export const withoutAttribute = (tag, name) => tag.replace(new RegExp(`\\s+${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`), "");
|
|
92
|
+
export const startTag = (text, element) => text.slice(element.start, element.openEnd);
|
|
93
|
+
export const isSelfClosing = (text, element) => /\/\s*>$/.test(text.slice(element.start, element.openEnd));
|
|
94
|
+
export const openTag = (text, element) => {
|
|
95
|
+
const tag = text.slice(element.start, element.openEnd);
|
|
96
|
+
return isSelfClosing(text, element) ? tag.replace(/\s*\/\s*>$/, ">") : tag;
|
|
97
|
+
};
|
|
98
|
+
export const qualified = (element, local) => (element.prefix ? `${element.prefix}:${local}` : local);
|