@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.
- package/CHANGELOG.md +69 -0
- package/dist/attachments/documents.d.ts +5 -0
- package/dist/attachments/documents.js +2 -2
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/config-command.js +8 -2
- package/dist/cli/config-issues.d.ts +3 -1
- package/dist/cli/config-issues.js +9 -2
- package/dist/cli/documents/file-conflicts.d.ts +25 -0
- package/dist/cli/documents/file-conflicts.js +102 -0
- package/dist/cli/documents/file-edit.d.ts +29 -0
- package/dist/cli/documents/file-edit.js +352 -0
- package/dist/cli/documents/file-update.d.ts +43 -0
- package/dist/cli/documents/file-update.js +95 -0
- package/dist/cli/documents/history.d.ts +34 -0
- package/dist/cli/documents/history.js +89 -0
- package/dist/cli/documents/index.d.ts +9 -2
- package/dist/cli/documents/index.js +9 -2
- package/dist/cli/documents/library.js +10 -0
- package/dist/cli/permission-keys.d.ts +6 -0
- package/dist/cli/permission-keys.js +15 -3
- package/dist/cli/service-api.d.ts +1 -1
- package/dist/cli/service-api.js +16 -34
- package/dist/documents/file-mirror-model.d.ts +32 -1
- package/dist/documents/index.d.ts +7 -4
- package/dist/documents/index.js +4 -1
- package/dist/documents/model.d.ts +16 -1
- package/dist/errors/reasons.js +6 -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/documents/block-diff.d.ts +13 -3
- package/dist/services/documents/block-diff.js +13 -7
- package/dist/services/documents/ingestion.d.ts +21 -2
- package/dist/services/documents/ingestion.js +29 -2
- package/dist/services/documents/plan.js +16 -7
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.d.ts +1 -0
- package/dist/services/documents/sync.js +9 -4
- package/dist/services/files/conflicts.d.ts +78 -0
- package/dist/services/files/conflicts.js +183 -0
- package/dist/services/files/guarded-write.d.ts +34 -0
- package/dist/services/files/guarded-write.js +42 -0
- package/dist/services/files/listing.d.ts +36 -0
- package/dist/services/files/listing.js +47 -0
- package/dist/services/files/local-files.d.ts +54 -0
- package/dist/services/files/local-files.js +143 -0
- package/dist/services/files/mirror-state.d.ts +14 -0
- package/dist/services/files/mirror-state.js +65 -0
- package/dist/services/files/mirror.d.ts +4 -14
- package/dist/services/files/mirror.js +177 -204
- package/dist/services/files/text-merge.d.ts +27 -0
- package/dist/services/files/text-merge.js +134 -0
- package/dist/services/files/versions.d.ts +36 -9
- package/dist/services/files/versions.js +40 -12
- package/dist/store/index.d.ts +2 -0
- package/dist/store/index.js +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/document-history.d.ts +84 -0
- package/dist/store/sqlite/document-history.js +158 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/notes.d.ts +9 -10
- package/dist/store/sqlite/notes.js +33 -21
- package/dist/store/sqlite/person-erase.d.ts +39 -0
- package/dist/store/sqlite/person-erase.js +152 -0
- package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
- package/dist/store/sqlite/schema/document-changes.js +11 -0
- package/dist/store/sqlite/schema.d.ts +65 -0
- package/dist/store/sqlite/schema.js +5 -0
- package/package.json +6 -2
|
@@ -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);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export type CellValue = string | number | boolean | null;
|
|
2
|
+
export type CellType = "string" | "number" | "boolean" | "error" | "date" | "empty";
|
|
3
|
+
export interface XlsxCell {
|
|
4
|
+
/** A1 style, upper case. */
|
|
5
|
+
readonly address: string;
|
|
6
|
+
readonly row: number;
|
|
7
|
+
readonly column: number;
|
|
8
|
+
/** The stored value; for a formula cell, its last calculated result. */
|
|
9
|
+
readonly value: CellValue;
|
|
10
|
+
readonly type: CellType;
|
|
11
|
+
/** The formula without `=`, when the cell holds one. */
|
|
12
|
+
readonly formula?: string;
|
|
13
|
+
/** The index into the workbook's cell formats (`s`); 0 is the default. */
|
|
14
|
+
readonly style: number;
|
|
15
|
+
}
|
|
16
|
+
export interface XlsxSheet {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly cells: XlsxCell[];
|
|
19
|
+
}
|
|
20
|
+
export interface ReadXlsxOptions {
|
|
21
|
+
/** One sheet by its name; all sheets when left out. */
|
|
22
|
+
readonly sheet?: string;
|
|
23
|
+
/** `B2` or `A1:C10`; every cell when left out. */
|
|
24
|
+
readonly range?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface XlsxEdit {
|
|
27
|
+
readonly sheet: string;
|
|
28
|
+
readonly cell: string;
|
|
29
|
+
/** A string is stored as text (also one that starts with `=`), `null` empties the cell and keeps its format. */
|
|
30
|
+
readonly value: CellValue;
|
|
31
|
+
}
|
|
32
|
+
export interface EditXlsxOptions {
|
|
33
|
+
/** Replace a formula with the value; without it a formula cell is refused. */
|
|
34
|
+
readonly overwriteFormulas?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface EditXlsxResult {
|
|
37
|
+
readonly bytes: Uint8Array;
|
|
38
|
+
readonly changed: {
|
|
39
|
+
sheet: string;
|
|
40
|
+
cell: string;
|
|
41
|
+
before: CellValue;
|
|
42
|
+
after: CellValue;
|
|
43
|
+
created: boolean;
|
|
44
|
+
}[];
|
|
45
|
+
/** True when a formula was replaced, so the workbook's calculation chain was dropped for Excel to rebuild. */
|
|
46
|
+
readonly calcChainDropped: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** The workbook's sheets and their stored cells, with each cell's type, formula and format index. */
|
|
49
|
+
export declare const readXlsxCells: (bytes: Uint8Array, options?: ReadXlsxOptions) => Promise<XlsxSheet[]>;
|
|
50
|
+
/**
|
|
51
|
+
* Changes cells in place. Only the edited worksheets, the shared strings and the workbook part (marked to recalculate
|
|
52
|
+
* on open) are rewritten, each by splicing the changed elements into its original text; every other zip entry is
|
|
53
|
+
* copied byte for byte. A new cell or row goes in address order; an edited cell keeps its format (`s`).
|
|
54
|
+
*/
|
|
55
|
+
export declare const editXlsxCells: (bytes: Uint8Array, edits: readonly XlsxEdit[], options?: EditXlsxOptions) => Promise<EditXlsxResult>;
|