@stll/docx-core 0.39.2 → 0.41.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/dist/archive-yBR7X-Qc.js +456 -0
- package/dist/docx_kernel_bg.wasm +0 -0
- package/dist/errors-Dm3jsb5q.d.ts +57 -0
- package/dist/format-DXPXB02u.js +378 -0
- package/dist/index.d.ts +6 -13
- package/dist/index.js +192 -354
- package/dist/schema/sequenceChildren.js +1 -1
- package/dist/{sequenceChildren-CrMcryEF.js → sequenceChildren-CSn0-1ov.js} +17 -45
- package/dist/streamingXmlParser-GnKxUuw_.js +743 -0
- package/dist/xml/streamingXmlParser.d.ts +109 -0
- package/dist/xml/streamingXmlParser.js +1 -0
- package/dist/xml/xmlNamespaceContext.d.ts +6 -0
- package/dist/xml/xmlNamespaceContext.js +53 -0
- package/dist/xml/xmlResourceLimits.d.ts +107 -0
- package/dist/xml/xmlResourceLimits.js +194 -0
- package/dist/xmlElement-C-vuKoul.d.ts +31 -0
- package/dist/zip/archive.d.ts +114 -0
- package/dist/zip/archive.js +3 -0
- package/dist/zip/stream.d.ts +30 -0
- package/dist/zip/stream.js +117 -0
- package/package.json +25 -8
- package/dist/zip/writeZipPart.d.ts +0 -10
- package/dist/zip/writeZipPart.js +0 -16
package/dist/index.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { T as borderStyleToken, Z as headingOutlineLevel, _t as isCanonicallyEmptyParagraphFormatting, ct as paragraphNumberingReferenceId, d as isNoteReferenceId, f as isOoxmlSymbolCharacter, gt as finalizeParagraphFormatting, k as statesNoBorder, lt as paragraphNumberingSlots, ot as paragraphNumberingLevel, r as DOCX_CONFORMANCE_CLASSES, s as MAX_REVISION_ID, st as paragraphNumberingReference, vt as setDocumentBodyComments } from "./document-NtScxyHH.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { d as ID_VALUE_ELEMENTS, f as NUMBERING_ATTRIBUTES, m as localName$2, o as readXml, p as isOoxmlNumericIdAttributeName, t as XmlReadError } from "./streamingXmlParser-GnKxUuw_.js";
|
|
3
|
+
import { i as serializeSequenceChildren } from "./sequenceChildren-CSn0-1ov.js";
|
|
4
|
+
import { _ as ZipError } from "./format-DXPXB02u.js";
|
|
5
|
+
import { t as ZipArchive } from "./archive-yBR7X-Qc.js";
|
|
4
6
|
import { a as hasIllegalXmlCharacters, i as escapeXmlText, n as sanitizeMarkdownHref, o as sanitizeXmlCharacters, r as escapeXmlAttribute, t as sanitizeExternalUrl } from "./href-ogmJmncc.js";
|
|
5
7
|
import { Result, TaggedError, panic } from "better-result";
|
|
6
|
-
import
|
|
7
|
-
import { decodeText, encodeUtf8 } from "@stll/utf8-boundaries";
|
|
8
|
-
import { XMLParser, XMLValidator } from "fast-xml-parser";
|
|
9
|
-
import { ENTITY_ACTION, EntityDecoder } from "@nodable/entities";
|
|
8
|
+
import { decodeText } from "@stll/utf8-boundaries";
|
|
10
9
|
import { Marked } from "marked";
|
|
11
10
|
// src/serialize/numericIds.ts
|
|
12
11
|
const WORD_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
|
|
@@ -19,17 +18,6 @@ const DRAWING_NAMESPACES = /* @__PURE__ */ new Set([
|
|
|
19
18
|
"http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing",
|
|
20
19
|
"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
|
|
21
20
|
]);
|
|
22
|
-
const NUMBERING_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
23
|
-
"numId",
|
|
24
|
-
"abstractNumId",
|
|
25
|
-
"numPicBulletId"
|
|
26
|
-
]);
|
|
27
|
-
const ID_VALUE_ELEMENTS = /* @__PURE__ */ new Set([
|
|
28
|
-
"id",
|
|
29
|
-
"numId",
|
|
30
|
-
"abstractNumId",
|
|
31
|
-
"lvlPicBulletId"
|
|
32
|
-
]);
|
|
33
21
|
const STRING_ID_ELEMENTS = /* @__PURE__ */ new Set(["permStart", "permEnd"]);
|
|
34
22
|
const MAX_UNSIGNED_ID = 4294967295;
|
|
35
23
|
const MIN_SIGNED_ID = -2147483648;
|
|
@@ -60,8 +48,6 @@ const ooxmlNumericIdDomain = ({ elementName, elementNamespace, attributeName, at
|
|
|
60
48
|
if (WORD_NAMESPACES.has(attributeNamespace ?? "") && (attributeLocalName === "id" && !(WORD_NAMESPACES.has(elementNamespace ?? "") && STRING_ID_ELEMENTS.has(elementLocalName)) || NUMBERING_ATTRIBUTES.has(attributeLocalName) || attributeLocalName === "val" && WORD_NAMESPACES.has(elementNamespace ?? "") && ID_VALUE_ELEMENTS.has(elementLocalName))) return "signed32";
|
|
61
49
|
if (attributeName === "id" && DRAWING_NAMESPACES.has(elementNamespace ?? "") && (elementLocalName === "docPr" || elementLocalName === "cNvPr")) return "unsigned32";
|
|
62
50
|
};
|
|
63
|
-
const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
64
|
-
const localName$2 = (name) => name.slice(name.indexOf(":") + 1);
|
|
65
51
|
const namespaceUri = (name, bindings) => {
|
|
66
52
|
const colon = name.indexOf(":");
|
|
67
53
|
return bindings.get(colon === -1 ? "" : name.slice(0, colon));
|
|
@@ -83,11 +69,6 @@ const decodeAttributeReferences = (value) => value.replace(/&(?:#(x[\da-f]+|\d+)
|
|
|
83
69
|
});
|
|
84
70
|
const ID_ATTRIBUTE_NAMES = ["id", ...NUMBERING_ATTRIBUTES].join("|");
|
|
85
71
|
const ID_ELEMENT_NAMES = [...ID_VALUE_ELEMENTS].join("|");
|
|
86
|
-
/** Attributes an identity scan must retain, derived from the domain classifier. */
|
|
87
|
-
const isOoxmlNumericIdAttributeName = ({ elementName, attributeName }) => {
|
|
88
|
-
const attribute = localName$2(attributeName);
|
|
89
|
-
return attribute === "id" || NUMBERING_ATTRIBUTES.has(attribute) || attribute === "val" && ID_VALUE_ELEMENTS.has(localName$2(elementName));
|
|
90
|
-
};
|
|
91
72
|
const ID_CANDIDATE = new RegExp(`\\b(?:${ID_ATTRIBUTE_NAMES})\\s*=|<(?:[^\\s<>/:]+:)?(?:${ID_ELEMENT_NAMES})(?:[\\s/>])`, "u");
|
|
92
73
|
/** Conservative presence check; safe IDs must still be reserved during import repair. */
|
|
93
74
|
const mayContainOoxmlNumericIds = (xml) => ID_CANDIDATE.test(xml);
|
|
@@ -155,56 +136,51 @@ const mayContainInvalidOoxmlNumericIds = (xml, mode = "schema") => {
|
|
|
155
136
|
*/
|
|
156
137
|
const assertValidOoxmlNumericIds = (xml, partPath) => {
|
|
157
138
|
if (!mayContainInvalidOoxmlNumericIds(xml)) return;
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
attributeValueProcessor: (_name, value) => decodeAttributeReferences(value),
|
|
166
|
-
htmlEntities: false,
|
|
167
|
-
ignoreDeclaration: true
|
|
139
|
+
const read = readXml(xml, {
|
|
140
|
+
conformance: "tolerant",
|
|
141
|
+
references: "raw"
|
|
142
|
+
});
|
|
143
|
+
if (read.status === "rejected") throw new XmlReadError({
|
|
144
|
+
message: `${partPath}: XML part could not be read: ${read.reason}`,
|
|
145
|
+
reason: read.reason
|
|
168
146
|
});
|
|
169
147
|
const visit = (nodes, inherited) => {
|
|
170
|
-
if (!Array.isArray(nodes)) return;
|
|
171
148
|
for (const node of nodes) {
|
|
172
|
-
if (
|
|
173
|
-
const attributes =
|
|
149
|
+
if (node.type !== "element" || node.name === void 0) continue;
|
|
150
|
+
const attributes = /* @__PURE__ */ new Map();
|
|
174
151
|
let localBindings;
|
|
175
|
-
|
|
152
|
+
for (const [name, value] of Object.entries(node.attributes ?? {})) {
|
|
176
153
|
if (typeof value !== "string") continue;
|
|
154
|
+
const decoded = decodeAttributeReferences(value);
|
|
155
|
+
attributes.set(name, decoded);
|
|
177
156
|
if (name === "xmlns" || name.startsWith("xmlns:")) {
|
|
178
157
|
localBindings ??= new Map(inherited);
|
|
179
|
-
localBindings.set(name === "xmlns" ? "" : name.slice(6),
|
|
158
|
+
localBindings.set(name === "xmlns" ? "" : name.slice(6), decoded);
|
|
180
159
|
}
|
|
181
160
|
}
|
|
182
161
|
const bindings = localBindings ?? inherited;
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
domain
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
visit(children, bindings);
|
|
162
|
+
const elementName = node.name;
|
|
163
|
+
const elementNamespace = namespaceUri(elementName, bindings);
|
|
164
|
+
for (const [attributeName, value] of attributes) {
|
|
165
|
+
const attributeNamespace = attributeName.includes(":") ? namespaceUri(attributeName, bindings) : void 0;
|
|
166
|
+
const domain = ooxmlNumericIdDomain({
|
|
167
|
+
elementName,
|
|
168
|
+
elementNamespace,
|
|
169
|
+
attributeName,
|
|
170
|
+
attributeNamespace
|
|
171
|
+
});
|
|
172
|
+
if (domain !== void 0) assertValidOoxmlNumericId({
|
|
173
|
+
value,
|
|
174
|
+
partPath,
|
|
175
|
+
elementName,
|
|
176
|
+
attributeName,
|
|
177
|
+
domain
|
|
178
|
+
});
|
|
204
179
|
}
|
|
180
|
+
visit(node.elements ?? [], bindings);
|
|
205
181
|
}
|
|
206
182
|
};
|
|
207
|
-
visit(
|
|
183
|
+
visit(read.value.elements ?? [], /* @__PURE__ */ new Map());
|
|
208
184
|
};
|
|
209
185
|
// src/serialize/textWhitespace.ts
|
|
210
186
|
/**
|
|
@@ -360,62 +336,22 @@ const APP_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><P
|
|
|
360
336
|
* not the other way round.
|
|
361
337
|
*/
|
|
362
338
|
const serializeDocumentToDocx = async (document, options = {}) => {
|
|
363
|
-
const zip = new
|
|
339
|
+
const zip = new ZipArchive();
|
|
364
340
|
const hasNumbering = hasNumberingDefinitions(document.package.numbering);
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
});
|
|
380
|
-
writeZipPart({
|
|
381
|
-
zip,
|
|
382
|
-
path: "docProps/core.xml",
|
|
383
|
-
data: encodeUtf8(serializeCoreProperties(document))
|
|
384
|
-
});
|
|
385
|
-
writeZipPart({
|
|
386
|
-
zip,
|
|
387
|
-
path: "word/document.xml",
|
|
388
|
-
data: encodeUtf8(serializeDocumentXml(document))
|
|
389
|
-
});
|
|
390
|
-
writeZipPart({
|
|
391
|
-
zip,
|
|
392
|
-
path: "word/styles.xml",
|
|
393
|
-
data: encodeUtf8(serializeStyles(document.package.styles))
|
|
394
|
-
});
|
|
395
|
-
if (hasNumbering) writeZipPart({
|
|
396
|
-
zip,
|
|
397
|
-
path: "word/numbering.xml",
|
|
398
|
-
data: encodeUtf8(serializeNumbering(document.package.numbering))
|
|
399
|
-
});
|
|
400
|
-
writeZipPart({
|
|
401
|
-
zip,
|
|
402
|
-
path: `word/${DEFAULT_FOOTER_PART_NAME}`,
|
|
403
|
-
data: encodeUtf8(buildFooterXml(options.language))
|
|
404
|
-
});
|
|
405
|
-
writeZipPart({
|
|
406
|
-
zip,
|
|
407
|
-
path: "word/_rels/document.xml.rels",
|
|
408
|
-
data: encodeUtf8(documentRelsXml(hasNumbering))
|
|
409
|
-
});
|
|
410
|
-
for (const [path, file] of Object.entries(zip.files)) {
|
|
411
|
-
if (file.dir || !path.endsWith(".xml")) continue;
|
|
412
|
-
assertValidOoxmlNumericIds(await file.async("uint8array").then((bytes) => decodeText(bytes, { ignoreBOM: true })), path);
|
|
413
|
-
}
|
|
414
|
-
return await zip.generateAsync({
|
|
415
|
-
type: "arraybuffer",
|
|
416
|
-
compression: "DEFLATE",
|
|
417
|
-
compressionOptions: { level: 6 }
|
|
418
|
-
});
|
|
341
|
+
zip.set("[Content_Types].xml", contentTypesXml(hasNumbering));
|
|
342
|
+
zip.set("_rels/.rels", ROOT_RELS_XML);
|
|
343
|
+
zip.set("docProps/app.xml", APP_XML);
|
|
344
|
+
zip.set("docProps/core.xml", serializeCoreProperties(document));
|
|
345
|
+
zip.set("word/document.xml", serializeDocumentXml(document));
|
|
346
|
+
zip.set("word/styles.xml", serializeStyles(document.package.styles));
|
|
347
|
+
if (hasNumbering) zip.set("word/numbering.xml", serializeNumbering(document.package.numbering));
|
|
348
|
+
zip.set(`word/${DEFAULT_FOOTER_PART_NAME}`, buildFooterXml(options.language));
|
|
349
|
+
zip.set("word/_rels/document.xml.rels", documentRelsXml(hasNumbering));
|
|
350
|
+
for (const entry of zip.entries()) {
|
|
351
|
+
if (!entry.path.endsWith(".xml")) continue;
|
|
352
|
+
assertValidOoxmlNumericIds(await entry.text(), entry.path);
|
|
353
|
+
}
|
|
354
|
+
return (await zip.generate()).buffer;
|
|
419
355
|
};
|
|
420
356
|
const hasNumberingDefinitions = (numbering) => (numbering?.abstractNums.length ?? 0) > 0 || (numbering?.nums.length ?? 0) > 0;
|
|
421
357
|
const serializeDocumentXml = (document) => {
|
|
@@ -691,16 +627,6 @@ const serializeCoreProperties = (document) => {
|
|
|
691
627
|
const modified = properties?.modified?.toISOString() ?? now;
|
|
692
628
|
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${escapeXmlText(title)}</dc:title><dc:creator>${escapeXmlText(creator)}</dc:creator><cp:lastModifiedBy>${escapeXmlText(creator)}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${created}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${modified}</dcterms:modified></cp:coreProperties>`;
|
|
693
629
|
};
|
|
694
|
-
// src/validate/xmlEntityDecoder.ts
|
|
695
|
-
const MAX_XML_ENTITY_EXPANDED_LENGTH = 1e5;
|
|
696
|
-
const createXmlEntityDecoder = () => new EntityDecoder({
|
|
697
|
-
numericAllowed: true,
|
|
698
|
-
onInputEntity: () => ENTITY_ACTION.THROW,
|
|
699
|
-
limit: {
|
|
700
|
-
maxExpandedLength: MAX_XML_ENTITY_EXPANDED_LENGTH,
|
|
701
|
-
applyLimitsTo: "all"
|
|
702
|
-
}
|
|
703
|
-
});
|
|
704
630
|
// src/validate/packageGraph.ts
|
|
705
631
|
const CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
706
632
|
const RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
@@ -717,45 +643,33 @@ const WORDPROCESSING_PART_ROLES = /* @__PURE__ */ new Set([
|
|
|
717
643
|
"webSettings"
|
|
718
644
|
]);
|
|
719
645
|
const OFFICE_DOCUMENT_TYPES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument"]);
|
|
720
|
-
const parser = new XMLParser({
|
|
721
|
-
preserveOrder: true,
|
|
722
|
-
ignoreAttributes: false,
|
|
723
|
-
attributeNamePrefix: "",
|
|
724
|
-
parseTagValue: false,
|
|
725
|
-
parseAttributeValue: false,
|
|
726
|
-
processEntities: true,
|
|
727
|
-
entityDecoder: createXmlEntityDecoder(),
|
|
728
|
-
ignoreDeclaration: true
|
|
729
|
-
});
|
|
730
|
-
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
731
646
|
const localName$1 = (name) => name.slice(name.indexOf(":") + 1);
|
|
732
647
|
const namespace = (name, scope) => {
|
|
733
648
|
const separator = name.indexOf(":");
|
|
734
649
|
return scope[separator < 0 ? "xmlns" : `xmlns:${name.slice(0, separator)}`];
|
|
735
650
|
};
|
|
736
651
|
const elements = (xml) => {
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
652
|
+
const read = readXml(xml, {
|
|
653
|
+
conformance: "well-formed",
|
|
654
|
+
undeclaredEntities: "accept"
|
|
655
|
+
});
|
|
656
|
+
if (read.status === "rejected") return null;
|
|
740
657
|
const output = [];
|
|
741
658
|
const visit = (nodes, parent) => {
|
|
742
659
|
for (const node of nodes) {
|
|
743
|
-
if (!
|
|
744
|
-
const
|
|
745
|
-
if (!name) continue;
|
|
746
|
-
const attributes = isRecord$1(node[":@"]) ? node[":@"] : {};
|
|
660
|
+
if (node.type !== "element" || !node.name) continue;
|
|
661
|
+
const attributes = node.attributes ?? {};
|
|
747
662
|
const scope = Object.assign({}, parent, attributes);
|
|
748
663
|
output.push({
|
|
749
|
-
name: localName$1(name),
|
|
750
|
-
namespace: namespace(name, scope),
|
|
664
|
+
name: localName$1(node.name),
|
|
665
|
+
namespace: namespace(node.name, scope),
|
|
751
666
|
scope,
|
|
752
667
|
attributes
|
|
753
668
|
});
|
|
754
|
-
|
|
755
|
-
if (Array.isArray(children)) visit(children, scope);
|
|
669
|
+
if (node.elements) visit(node.elements, scope);
|
|
756
670
|
}
|
|
757
671
|
};
|
|
758
|
-
visit(
|
|
672
|
+
visit(read.value.elements ?? [], {});
|
|
759
673
|
return output;
|
|
760
674
|
};
|
|
761
675
|
const relationshipSource = (path) => {
|
|
@@ -899,7 +813,6 @@ const accepts = (constraint, value) => {
|
|
|
899
813
|
default: return constraint;
|
|
900
814
|
}
|
|
901
815
|
};
|
|
902
|
-
const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
903
816
|
const validateAttributes = (model, values) => {
|
|
904
817
|
for (const index of model.attributes) {
|
|
905
818
|
const attribute = SCHEMA_ATTRIBUTE_FACTS.definitions.at(index);
|
|
@@ -921,34 +834,22 @@ const validateAttributes = (model, values) => {
|
|
|
921
834
|
* Unknown extension vocabularies remain available for lossless round trips.
|
|
922
835
|
*/
|
|
923
836
|
const validateSchemaAttributes = (xml) => {
|
|
924
|
-
const
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
ignoreAttributes: false,
|
|
930
|
-
attributeNamePrefix: "",
|
|
931
|
-
parseTagValue: false,
|
|
932
|
-
parseAttributeValue: false,
|
|
933
|
-
trimValues: false,
|
|
934
|
-
processEntities: true,
|
|
935
|
-
entityDecoder: createXmlEntityDecoder(),
|
|
936
|
-
ignoreDeclaration: true
|
|
937
|
-
}).parse(xml));
|
|
938
|
-
if (parsed.isErr()) return "Malformed XML: XML parser rejected the part";
|
|
939
|
-
if (!Array.isArray(parsed.value)) return "Malformed XML: expected a document element";
|
|
940
|
-
if (parsed.value.filter((node) => record(node) && Object.keys(node).some((tag) => tag !== ":@" && !tag.startsWith("#") && !tag.startsWith("?"))).length !== 1) return "Malformed XML: expected exactly one document element";
|
|
837
|
+
const read = readXml(xml, {
|
|
838
|
+
conformance: "well-formed",
|
|
839
|
+
undeclaredEntities: "accept"
|
|
840
|
+
});
|
|
841
|
+
if (read.status === "rejected") return /<!DOCTYPE/i.test(xml) ? "DOCTYPE is not allowed in DOCX XML" : `Malformed XML: ${read.reason}`;
|
|
941
842
|
const pending = [{
|
|
942
|
-
nodes:
|
|
843
|
+
nodes: read.value.elements ?? [],
|
|
943
844
|
scope: /* @__PURE__ */ new Map([["xml", XML_NAMESPACE]]),
|
|
944
845
|
types: []
|
|
945
846
|
}];
|
|
946
847
|
while (pending.length > 0) {
|
|
947
848
|
const current = pending.pop();
|
|
948
|
-
if (!current
|
|
849
|
+
if (!current) continue;
|
|
949
850
|
for (const node of current.nodes) {
|
|
950
|
-
if (
|
|
951
|
-
const attributes =
|
|
851
|
+
if (node.type !== "element" || node.name === void 0) continue;
|
|
852
|
+
const attributes = node.attributes ?? {};
|
|
952
853
|
const scope = new Map(current.scope);
|
|
953
854
|
for (const [name, value] of Object.entries(attributes)) {
|
|
954
855
|
if (typeof value !== "string") continue;
|
|
@@ -967,30 +868,28 @@ const validateSchemaAttributes = (xml) => {
|
|
|
967
868
|
if (values.has(resolved)) return `Duplicate XML attribute: ${name}`;
|
|
968
869
|
if (typeof value === "string") values.set(resolved, value);
|
|
969
870
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
if (issue === null) break;
|
|
986
|
-
}
|
|
987
|
-
if (issue !== null) return `${tag}: ${issue}`;
|
|
988
|
-
pending.push({
|
|
989
|
-
nodes,
|
|
990
|
-
scope,
|
|
991
|
-
types
|
|
992
|
-
});
|
|
871
|
+
const tag = node.name;
|
|
872
|
+
const name = resolveName({
|
|
873
|
+
name: tag,
|
|
874
|
+
scope,
|
|
875
|
+
attribute: false
|
|
876
|
+
});
|
|
877
|
+
if (name === null) return `Unbound XML element prefix: ${tag}`;
|
|
878
|
+
const contextual = current.types.flatMap((type) => SCHEMA_ATTRIBUTE_FACTS.types[type]?.children[name] ?? []);
|
|
879
|
+
const types = contextual.length ? contextual : SCHEMA_ATTRIBUTE_FACTS.elements[name] ?? [];
|
|
880
|
+
let issue = null;
|
|
881
|
+
for (const type of types) {
|
|
882
|
+
const model = SCHEMA_ATTRIBUTE_FACTS.types[type];
|
|
883
|
+
if (!model) continue;
|
|
884
|
+
issue = validateAttributes(model, values);
|
|
885
|
+
if (issue === null) break;
|
|
993
886
|
}
|
|
887
|
+
if (issue !== null) return `${tag}: ${issue}`;
|
|
888
|
+
pending.push({
|
|
889
|
+
nodes: node.elements ?? [],
|
|
890
|
+
scope,
|
|
891
|
+
types
|
|
892
|
+
});
|
|
994
893
|
}
|
|
995
894
|
}
|
|
996
895
|
return null;
|
|
@@ -1029,23 +928,6 @@ const VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES = 33554432;
|
|
|
1029
928
|
const VALIDATE_DOCX_MAX_COMPRESSION_RATIO = 200;
|
|
1030
929
|
const VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES = 4194304;
|
|
1031
930
|
const WORDPROCESSINGML_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
|
|
1032
|
-
const packageXmlParser = new XMLParser({
|
|
1033
|
-
preserveOrder: true,
|
|
1034
|
-
ignoreAttributes: false,
|
|
1035
|
-
attributeNamePrefix: "",
|
|
1036
|
-
parseTagValue: false,
|
|
1037
|
-
parseAttributeValue: false,
|
|
1038
|
-
processEntities: false,
|
|
1039
|
-
ignoreDeclaration: true
|
|
1040
|
-
});
|
|
1041
|
-
const getDeclaredUncompressedSize = (file) => {
|
|
1042
|
-
const metadata = file._data;
|
|
1043
|
-
return typeof metadata?.uncompressedSize === "number" ? metadata.uncompressedSize : null;
|
|
1044
|
-
};
|
|
1045
|
-
const getCompressedSize = (file) => {
|
|
1046
|
-
const metadata = file._data;
|
|
1047
|
-
return typeof metadata?.compressedSize === "number" ? metadata.compressedSize : null;
|
|
1048
|
-
};
|
|
1049
931
|
const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1050
932
|
"xml",
|
|
1051
933
|
"rels",
|
|
@@ -1058,109 +940,80 @@ const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
1058
940
|
"rtf"
|
|
1059
941
|
]);
|
|
1060
942
|
const isRatioBoundedPart = (path) => RATIO_BOUNDED_EXTENSIONS.has(path.slice(path.lastIndexOf(".") + 1).toLowerCase());
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
offset = bytes.indexOf(80, offset + 1);
|
|
1076
|
-
}
|
|
1077
|
-
return count;
|
|
1078
|
-
};
|
|
1079
|
-
const concatChunks = (chunks, totalBytes) => {
|
|
1080
|
-
const merged = new Uint8Array(totalBytes);
|
|
1081
|
-
let offset = 0;
|
|
1082
|
-
for (const chunk of chunks) {
|
|
1083
|
-
merged.set(chunk, offset);
|
|
1084
|
-
offset += chunk.length;
|
|
943
|
+
/** The archive refusal `validateDocxPackage` reports for a read limit. */
|
|
944
|
+
const archiveBoundsMessage = (error) => {
|
|
945
|
+
const entry = error.path === void 0 ? "" : ` entry "${error.path}"`;
|
|
946
|
+
switch (error.reason) {
|
|
947
|
+
case "too-many-entries": return `Generated DOCX holds more than ${VALIDATE_DOCX_MAX_ENTRIES} archive entries.`;
|
|
948
|
+
case "entry-too-large": return `Generated DOCX${entry} declares more than ${VALIDATE_DOCX_MAX_ENTRY_BYTES} uncompressed bytes.`;
|
|
949
|
+
case "total-too-large": return `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_TOTAL_BYTES} cumulative uncompressed bytes.`;
|
|
950
|
+
case "compression-ratio": return error.path === void 0 ? `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per archive byte.` : `Generated DOCX${entry} declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per compressed byte.`;
|
|
951
|
+
case "declared-size-exceeded": return `Generated DOCX${entry} inflates past its declared size.`;
|
|
952
|
+
case "corrupt-entry": return `Generated DOCX${entry} does not match its declared size and checksum.`;
|
|
953
|
+
case "malformed":
|
|
954
|
+
case "unsupported":
|
|
955
|
+
case "invalid-entry-name":
|
|
956
|
+
case "duplicate-entry": return null;
|
|
1085
957
|
}
|
|
1086
|
-
return merged;
|
|
1087
958
|
};
|
|
1088
959
|
/**
|
|
1089
|
-
*
|
|
1090
|
-
*
|
|
1091
|
-
* with its declared size only after inflating all of it, so the declared
|
|
1092
|
-
* size alone does not bound the allocation.
|
|
960
|
+
* Read one XML part, refusing it from its declared size before inflating.
|
|
961
|
+
* Inflation itself stops at the declared size.
|
|
1093
962
|
*/
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
const stop = (error) => {
|
|
1103
|
-
settled = true;
|
|
1104
|
-
stream.pause();
|
|
1105
|
-
resolve({
|
|
1106
|
-
ok: false,
|
|
1107
|
-
error
|
|
1108
|
-
});
|
|
1109
|
-
};
|
|
1110
|
-
stream.on("data", (chunk) => {
|
|
1111
|
-
if (settled) return;
|
|
1112
|
-
entryBytes += chunk.length;
|
|
1113
|
-
if (declaredBytes !== null && entryBytes > declaredBytes) {
|
|
1114
|
-
stop(`Generated DOCX entry "${entry.name}" inflates past its declared size.`);
|
|
1115
|
-
return;
|
|
1116
|
-
}
|
|
1117
|
-
if (exceedsCompressionRatio(entryBytes, compressedBytes)) {
|
|
1118
|
-
stop(`Generated DOCX entry "${entry.name}" exceeds the ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO}:1 compression ratio limit.`);
|
|
1119
|
-
return;
|
|
1120
|
-
}
|
|
1121
|
-
if (entryBytes > maxBytes) {
|
|
1122
|
-
stop(`Generated DOCX ${entry.name} exceeds the ${maxBytes}-byte limit.`);
|
|
1123
|
-
return;
|
|
1124
|
-
}
|
|
1125
|
-
chunks.push(chunk);
|
|
1126
|
-
}).on("end", () => {
|
|
1127
|
-
if (settled) return;
|
|
1128
|
-
settled = true;
|
|
1129
|
-
resolve({
|
|
1130
|
-
ok: true,
|
|
1131
|
-
bytes: concatChunks(chunks, entryBytes)
|
|
1132
|
-
});
|
|
1133
|
-
}).on("error", (error) => {
|
|
1134
|
-
if (settled) return;
|
|
1135
|
-
settled = true;
|
|
1136
|
-
reject(error);
|
|
1137
|
-
}).resume();
|
|
963
|
+
const readXmlPart = async (entry, maxBytes) => {
|
|
964
|
+
if (entry.size > maxBytes) return {
|
|
965
|
+
ok: false,
|
|
966
|
+
error: `Generated DOCX ${entry.path} declares ${entry.size} uncompressed bytes, over the ${maxBytes}-byte limit.`
|
|
967
|
+
};
|
|
968
|
+
const bytes = await Result.tryPromise({
|
|
969
|
+
try: async () => await entry.bytes(),
|
|
970
|
+
catch: (cause) => cause
|
|
1138
971
|
});
|
|
972
|
+
if (Result.isOk(bytes)) return {
|
|
973
|
+
ok: true,
|
|
974
|
+
text: decodeText(bytes.value)
|
|
975
|
+
};
|
|
976
|
+
const error = bytes.error;
|
|
977
|
+
if (!(error instanceof ZipError)) throw error;
|
|
978
|
+
return {
|
|
979
|
+
ok: false,
|
|
980
|
+
error: archiveBoundsMessage(error) ?? error.message
|
|
981
|
+
};
|
|
1139
982
|
};
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
if (
|
|
1160
|
-
|
|
983
|
+
const openArchive = async (bytes) => {
|
|
984
|
+
const read = await Result.tryPromise({
|
|
985
|
+
try: async () => await ZipArchive.read(bytes, {
|
|
986
|
+
limits: {
|
|
987
|
+
maxEntries: VALIDATE_DOCX_MAX_ENTRIES,
|
|
988
|
+
maxEntryBytes: VALIDATE_DOCX_MAX_ENTRY_BYTES,
|
|
989
|
+
maxTotalBytes: VALIDATE_DOCX_MAX_TOTAL_BYTES,
|
|
990
|
+
maxCompressionRatio: VALIDATE_DOCX_MAX_COMPRESSION_RATIO,
|
|
991
|
+
compressionRatioGraceBytes: VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES
|
|
992
|
+
},
|
|
993
|
+
isCompressionRatioExempt: (path) => !isRatioBoundedPart(path)
|
|
994
|
+
}),
|
|
995
|
+
catch: (cause) => cause
|
|
996
|
+
});
|
|
997
|
+
if (Result.isOk(read)) return {
|
|
998
|
+
ok: true,
|
|
999
|
+
zip: read.value
|
|
1000
|
+
};
|
|
1001
|
+
const error = read.error;
|
|
1002
|
+
if (!(error instanceof ZipError)) throw error;
|
|
1003
|
+
const bounds = archiveBoundsMessage(error);
|
|
1004
|
+
return {
|
|
1005
|
+
ok: false,
|
|
1006
|
+
result: bounds === null ? {
|
|
1007
|
+
valid: false,
|
|
1008
|
+
code: DOCX_PACKAGE_ISSUE_CODES.InvalidArchive,
|
|
1009
|
+
error: error.message
|
|
1010
|
+
} : {
|
|
1011
|
+
valid: false,
|
|
1012
|
+
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1013
|
+
error: bounds
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1161
1016
|
};
|
|
1162
|
-
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1163
|
-
const elementName = (node) => Object.keys(node).find((key) => key !== ":@" && !key.startsWith("?")) ?? null;
|
|
1164
1017
|
const localName = (name) => name.slice(name.indexOf(":") + 1);
|
|
1165
1018
|
const prefix = (name) => {
|
|
1166
1019
|
const separator = name.indexOf(":");
|
|
@@ -1172,77 +1025,63 @@ const namespaceFor = (name, attributes, inherited = {}) => {
|
|
|
1172
1025
|
return typeof value === "string" ? value : null;
|
|
1173
1026
|
};
|
|
1174
1027
|
const validateDocumentXml = (xml) => {
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1028
|
+
const read = readXml(xml, {
|
|
1029
|
+
conformance: "well-formed",
|
|
1030
|
+
references: "raw",
|
|
1031
|
+
undeclaredEntities: "accept",
|
|
1032
|
+
instructions: "retain"
|
|
1033
|
+
});
|
|
1034
|
+
if (read.status === "rejected") return "Generated DOCX has malformed word/document.xml.";
|
|
1035
|
+
const root = read.value.elements?.find((node) => node.type !== "text" && !(node.type === "instruction" && node.name === "xml"));
|
|
1179
1036
|
if (!root) return "Generated DOCX has no word/document.xml root document.";
|
|
1180
|
-
const rootName =
|
|
1181
|
-
const rootAttributes =
|
|
1037
|
+
const rootName = root.type === "element" ? root.name ?? null : null;
|
|
1038
|
+
const rootAttributes = root.attributes ?? {};
|
|
1182
1039
|
if (rootName === null || localName(rootName) !== "document" || !WORDPROCESSINGML_NAMESPACES.has(namespaceFor(rootName, rootAttributes) ?? "")) return "Generated DOCX has no WordprocessingML document root.";
|
|
1183
|
-
|
|
1184
|
-
if (!Array.isArray(children)) return "Generated DOCX document root has no WordprocessingML body.";
|
|
1185
|
-
return children.some((child) => {
|
|
1186
|
-
if (!isRecord(child)) return false;
|
|
1187
|
-
const childName = elementName(child);
|
|
1188
|
-
const childAttributes = isRecord(child[":@"]) ? child[":@"] : {};
|
|
1189
|
-
return childName !== null && localName(childName) === "body" && WORDPROCESSINGML_NAMESPACES.has(namespaceFor(childName, childAttributes, rootAttributes) ?? "");
|
|
1190
|
-
}) ? null : "Generated DOCX document root has no WordprocessingML body.";
|
|
1040
|
+
return (root.elements ?? []).some((child) => child.type === "element" && child.name !== void 0 && localName(child.name) === "body" && WORDPROCESSINGML_NAMESPACES.has(namespaceFor(child.name, child.attributes ?? {}, rootAttributes) ?? "")) ? null : "Generated DOCX document root has no WordprocessingML body.";
|
|
1191
1041
|
};
|
|
1192
1042
|
const validateDocxPackage = async (buffer) => {
|
|
1193
1043
|
try {
|
|
1194
1044
|
const archiveBytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
error: `Generated DOCX holds more than ${VALIDATE_DOCX_MAX_ENTRIES} archive entries.`
|
|
1199
|
-
};
|
|
1200
|
-
const zip = await JSZip.loadAsync(buffer);
|
|
1201
|
-
const boundsError = checkDocxArchiveBounds(zip, archiveBytes.byteLength);
|
|
1202
|
-
if (boundsError) return {
|
|
1203
|
-
valid: false,
|
|
1204
|
-
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1205
|
-
error: boundsError
|
|
1206
|
-
};
|
|
1045
|
+
const opened = await openArchive(archiveBytes);
|
|
1046
|
+
if (!opened.ok) return opened.result;
|
|
1047
|
+
const { zip } = opened;
|
|
1207
1048
|
for (const requiredPath of [
|
|
1208
1049
|
"[Content_Types].xml",
|
|
1209
1050
|
"_rels/.rels",
|
|
1210
1051
|
"word/document.xml"
|
|
1211
|
-
]) if (!zip.
|
|
1052
|
+
]) if (!zip.has(requiredPath)) return {
|
|
1212
1053
|
valid: false,
|
|
1213
1054
|
code: DOCX_PACKAGE_ISSUE_CODES.MissingPackagePart,
|
|
1214
1055
|
error: `Generated DOCX is missing required package part: ${requiredPath}`
|
|
1215
1056
|
};
|
|
1216
|
-
const documentPart = zip.
|
|
1217
|
-
|
|
1218
|
-
if (declaredDocumentBytes !== null && declaredDocumentBytes > VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) return {
|
|
1057
|
+
const documentPart = zip.entry("word/document.xml");
|
|
1058
|
+
if (documentPart !== void 0 && documentPart.size > VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) return {
|
|
1219
1059
|
valid: false,
|
|
1220
1060
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1221
|
-
error: `Generated DOCX word/document.xml declares ${
|
|
1061
|
+
error: `Generated DOCX word/document.xml declares ${documentPart.size} uncompressed bytes, over the ${VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES}-byte limit.`
|
|
1222
1062
|
};
|
|
1223
|
-
const documentRead = documentPart ? await
|
|
1063
|
+
const documentRead = documentPart ? await readXmlPart(documentPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
|
|
1224
1064
|
if (documentRead !== void 0 && !documentRead.ok) return {
|
|
1225
1065
|
valid: false,
|
|
1226
1066
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1227
1067
|
error: documentRead.error
|
|
1228
1068
|
};
|
|
1229
|
-
const
|
|
1230
|
-
const documentXml = documentBytes ? decodeText(documentBytes) : void 0;
|
|
1069
|
+
const documentXml = documentRead?.text;
|
|
1231
1070
|
const documentError = documentXml ? validateDocumentXml(documentXml) : "Generated DOCX has no word/document.xml root document.";
|
|
1232
1071
|
if (documentError) return {
|
|
1233
1072
|
valid: false,
|
|
1234
1073
|
code: DOCX_PACKAGE_ISSUE_CODES.InvalidDocumentRoot,
|
|
1235
1074
|
error: documentError
|
|
1236
1075
|
};
|
|
1237
|
-
const documentRelsPart = zip.
|
|
1238
|
-
const documentRelsRead = documentRelsPart ? await
|
|
1076
|
+
const documentRelsPart = zip.entry("word/_rels/document.xml.rels");
|
|
1077
|
+
const documentRelsRead = documentRelsPart ? await readXmlPart(documentRelsPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
|
|
1239
1078
|
if (documentRelsRead !== void 0 && !documentRelsRead.ok) return {
|
|
1240
1079
|
valid: false,
|
|
1241
1080
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1242
1081
|
error: documentRelsRead.error
|
|
1243
1082
|
};
|
|
1244
|
-
const documentRelsXml = documentRelsRead
|
|
1245
|
-
if (documentRelsXml?.includes("/relationships/numbering") && !zip.
|
|
1083
|
+
const documentRelsXml = documentRelsRead?.text;
|
|
1084
|
+
if (documentRelsXml?.includes("/relationships/numbering") && !zip.has("word/numbering.xml")) return {
|
|
1246
1085
|
valid: false,
|
|
1247
1086
|
code: DOCX_PACKAGE_ISSUE_CODES.MissingNumberingPart,
|
|
1248
1087
|
error: "Generated DOCX references numbering.xml but does not include it."
|
|
@@ -1251,27 +1090,26 @@ const validateDocxPackage = async (buffer) => {
|
|
|
1251
1090
|
if (documentXml) parts.set("word/document.xml", documentXml);
|
|
1252
1091
|
if (documentRelsXml) parts.set("word/_rels/document.xml.rels", documentRelsXml);
|
|
1253
1092
|
const paths = /* @__PURE__ */ new Set();
|
|
1254
|
-
for (const entry of
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
let xml = parts.get(entry.name);
|
|
1093
|
+
for (const entry of zip.entries()) {
|
|
1094
|
+
paths.add(entry.path);
|
|
1095
|
+
if (!entry.path.endsWith(".xml") && !entry.path.endsWith(".rels")) continue;
|
|
1096
|
+
let xml = parts.get(entry.path);
|
|
1259
1097
|
if (xml === void 0) {
|
|
1260
|
-
const read = await
|
|
1098
|
+
const read = await readXmlPart(entry, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES);
|
|
1261
1099
|
if (!read.ok) return {
|
|
1262
1100
|
valid: false,
|
|
1263
1101
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1264
1102
|
error: read.error
|
|
1265
1103
|
};
|
|
1266
|
-
xml =
|
|
1104
|
+
xml = read.text;
|
|
1267
1105
|
}
|
|
1268
1106
|
const issue = validateSchemaAttributes(xml);
|
|
1269
1107
|
if (issue) return {
|
|
1270
1108
|
valid: false,
|
|
1271
1109
|
code: DOCX_PACKAGE_ISSUE_CODES.InvalidSchemaAttribute,
|
|
1272
|
-
error: `${entry.
|
|
1110
|
+
error: `${entry.path}: ${issue}`
|
|
1273
1111
|
};
|
|
1274
|
-
parts.set(entry.
|
|
1112
|
+
parts.set(entry.path, xml);
|
|
1275
1113
|
}
|
|
1276
1114
|
const graphIssue = validatePackageGraph(parts, paths);
|
|
1277
1115
|
if (graphIssue) return {
|