@stll/docx-core 0.40.0 → 0.42.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.
Binary file
package/dist/index.d.ts CHANGED
@@ -161,6 +161,12 @@ type SerializeDocumentOptions = {
161
161
  * not the other way round.
162
162
  */
163
163
  export declare const serializeDocumentToDocx: (document: Document, options?: SerializeDocumentOptions) => Promise<ArrayBuffer>;
164
+ type OoxmlNumericIdAttributeOptions = {
165
+ elementName: string;
166
+ attributeName: string;
167
+ };
168
+ /** Attributes an identity scan must retain, derived from the domain classifier. */
169
+ export declare const isOoxmlNumericIdAttributeName: ({ elementName, attributeName }: OoxmlNumericIdAttributeOptions) => boolean;
164
170
  declare const InvalidOoxmlNumericIdErrorBase: TaggedErrorClass<"InvalidOoxmlNumericIdError">;
165
171
  /** A writer would emit an identifier outside its OOXML schema's numeric domain. */
166
172
  export declare class InvalidOoxmlNumericIdError extends InvalidOoxmlNumericIdErrorBase<{
@@ -187,12 +193,6 @@ type NumericIdAttributeOptions = {
187
193
  };
188
194
  /** Shared schema classification for import normalization and writer validation. */
189
195
  export declare const ooxmlNumericIdDomain: ({ elementName, elementNamespace, attributeName, attributeNamespace }: NumericIdAttributeOptions) => "signed32" | "unsigned32" | undefined;
190
- type OoxmlNumericIdAttributeOptions = {
191
- elementName: string;
192
- attributeName: string;
193
- };
194
- /** Attributes an identity scan must retain, derived from the domain classifier. */
195
- export declare const isOoxmlNumericIdAttributeName: ({ elementName, attributeName }: OoxmlNumericIdAttributeOptions) => boolean;
196
196
  /** Conservative presence check; safe IDs must still be reserved during import repair. */
197
197
  export declare const mayContainOoxmlNumericIds: (xml: string) => boolean;
198
198
  /**
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 { i as serializeSequenceChildren } from "./sequenceChildren-CrMcryEF.js";
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";
3
4
  import { _ as ZipError } from "./format-DXPXB02u.js";
4
5
  import { t as ZipArchive } from "./archive-yBR7X-Qc.js";
5
6
  import { a as hasIllegalXmlCharacters, i as escapeXmlText, n as sanitizeMarkdownHref, o as sanitizeXmlCharacters, r as escapeXmlAttribute, t as sanitizeExternalUrl } from "./href-ogmJmncc.js";
6
7
  import { Result, TaggedError, panic } from "better-result";
7
- import { XMLParser, XMLValidator } from "fast-xml-parser";
8
8
  import { decodeText } from "@stll/utf8-boundaries";
9
- import { ENTITY_ACTION, EntityDecoder } from "@nodable/entities";
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 parser = new XMLParser({
159
- preserveOrder: true,
160
- ignoreAttributes: false,
161
- attributeNamePrefix: "",
162
- parseTagValue: false,
163
- parseAttributeValue: false,
164
- processEntities: false,
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 (!isRecord$2(node)) continue;
173
- const attributes = node[":@"];
149
+ if (node.type !== "element" || node.name === void 0) continue;
150
+ const attributes = /* @__PURE__ */ new Map();
174
151
  let localBindings;
175
- if (isRecord$2(attributes)) for (const [name, value] of Object.entries(attributes)) {
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), value);
158
+ localBindings.set(name === "xmlns" ? "" : name.slice(6), decoded);
180
159
  }
181
160
  }
182
161
  const bindings = localBindings ?? inherited;
183
- for (const [elementName, children] of Object.entries(node)) {
184
- if (elementName === ":@" || elementName.startsWith("#") || elementName.startsWith("?")) continue;
185
- const elementNamespace = namespaceUri(elementName, bindings);
186
- if (isRecord$2(attributes)) for (const [attributeName, value] of Object.entries(attributes)) {
187
- if (typeof value !== "string" && typeof value !== "number") continue;
188
- const attributeNamespace = attributeName.includes(":") ? namespaceUri(attributeName, bindings) : void 0;
189
- const domain = ooxmlNumericIdDomain({
190
- elementName,
191
- elementNamespace,
192
- attributeName,
193
- attributeNamespace
194
- });
195
- if (domain !== void 0) assertValidOoxmlNumericId({
196
- value,
197
- partPath,
198
- elementName,
199
- attributeName,
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(parser.parse(xml), /* @__PURE__ */ new Map());
183
+ visit(read.value.elements ?? [], /* @__PURE__ */ new Map());
208
184
  };
209
185
  // src/serialize/textWhitespace.ts
210
186
  /**
@@ -651,16 +627,6 @@ const serializeCoreProperties = (document) => {
651
627
  const modified = properties?.modified?.toISOString() ?? now;
652
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>`;
653
629
  };
654
- // src/validate/xmlEntityDecoder.ts
655
- const MAX_XML_ENTITY_EXPANDED_LENGTH = 1e5;
656
- const createXmlEntityDecoder = () => new EntityDecoder({
657
- numericAllowed: true,
658
- onInputEntity: () => ENTITY_ACTION.THROW,
659
- limit: {
660
- maxExpandedLength: MAX_XML_ENTITY_EXPANDED_LENGTH,
661
- applyLimitsTo: "all"
662
- }
663
- });
664
630
  // src/validate/packageGraph.ts
665
631
  const CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types";
666
632
  const RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
@@ -677,45 +643,33 @@ const WORDPROCESSING_PART_ROLES = /* @__PURE__ */ new Set([
677
643
  "webSettings"
678
644
  ]);
679
645
  const OFFICE_DOCUMENT_TYPES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument"]);
680
- const parser = new XMLParser({
681
- preserveOrder: true,
682
- ignoreAttributes: false,
683
- attributeNamePrefix: "",
684
- parseTagValue: false,
685
- parseAttributeValue: false,
686
- processEntities: true,
687
- entityDecoder: createXmlEntityDecoder(),
688
- ignoreDeclaration: true
689
- });
690
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
691
646
  const localName$1 = (name) => name.slice(name.indexOf(":") + 1);
692
647
  const namespace = (name, scope) => {
693
648
  const separator = name.indexOf(":");
694
649
  return scope[separator < 0 ? "xmlns" : `xmlns:${name.slice(0, separator)}`];
695
650
  };
696
651
  const elements = (xml) => {
697
- if (XMLValidator.validate(xml) !== true) return null;
698
- const tree = parser.parse(xml);
699
- if (!Array.isArray(tree)) return null;
652
+ const read = readXml(xml, {
653
+ conformance: "well-formed",
654
+ undeclaredEntities: "accept"
655
+ });
656
+ if (read.status === "rejected") return null;
700
657
  const output = [];
701
658
  const visit = (nodes, parent) => {
702
659
  for (const node of nodes) {
703
- if (!isRecord$1(node)) continue;
704
- const name = Object.keys(node).find((key) => key !== ":@" && !key.startsWith("#") && !key.startsWith("?"));
705
- if (!name) continue;
706
- const attributes = isRecord$1(node[":@"]) ? node[":@"] : {};
660
+ if (node.type !== "element" || !node.name) continue;
661
+ const attributes = node.attributes ?? {};
707
662
  const scope = Object.assign({}, parent, attributes);
708
663
  output.push({
709
- name: localName$1(name),
710
- namespace: namespace(name, scope),
664
+ name: localName$1(node.name),
665
+ namespace: namespace(node.name, scope),
711
666
  scope,
712
667
  attributes
713
668
  });
714
- const children = node[name];
715
- if (Array.isArray(children)) visit(children, scope);
669
+ if (node.elements) visit(node.elements, scope);
716
670
  }
717
671
  };
718
- visit(tree, {});
672
+ visit(read.value.elements ?? [], {});
719
673
  return output;
720
674
  };
721
675
  const relationshipSource = (path) => {
@@ -859,7 +813,6 @@ const accepts = (constraint, value) => {
859
813
  default: return constraint;
860
814
  }
861
815
  };
862
- const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
863
816
  const validateAttributes = (model, values) => {
864
817
  for (const index of model.attributes) {
865
818
  const attribute = SCHEMA_ATTRIBUTE_FACTS.definitions.at(index);
@@ -881,34 +834,22 @@ const validateAttributes = (model, values) => {
881
834
  * Unknown extension vocabularies remain available for lossless round trips.
882
835
  */
883
836
  const validateSchemaAttributes = (xml) => {
884
- const syntax = XMLValidator.validate(xml);
885
- if (syntax !== true) return `Malformed XML: ${syntax.err.msg}`;
886
- if (/<!DOCTYPE/i.test(xml)) return "DOCTYPE is not allowed in DOCX XML";
887
- const parsed = Result.try(() => new XMLParser({
888
- preserveOrder: true,
889
- ignoreAttributes: false,
890
- attributeNamePrefix: "",
891
- parseTagValue: false,
892
- parseAttributeValue: false,
893
- trimValues: false,
894
- processEntities: true,
895
- entityDecoder: createXmlEntityDecoder(),
896
- ignoreDeclaration: true
897
- }).parse(xml));
898
- if (parsed.isErr()) return "Malformed XML: XML parser rejected the part";
899
- if (!Array.isArray(parsed.value)) return "Malformed XML: expected a document element";
900
- 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}`;
901
842
  const pending = [{
902
- nodes: parsed.value,
843
+ nodes: read.value.elements ?? [],
903
844
  scope: /* @__PURE__ */ new Map([["xml", XML_NAMESPACE]]),
904
845
  types: []
905
846
  }];
906
847
  while (pending.length > 0) {
907
848
  const current = pending.pop();
908
- if (!current || !Array.isArray(current.nodes)) continue;
849
+ if (!current) continue;
909
850
  for (const node of current.nodes) {
910
- if (!record(node)) continue;
911
- const attributes = record(node[":@"]) ? node[":@"] : {};
851
+ if (node.type !== "element" || node.name === void 0) continue;
852
+ const attributes = node.attributes ?? {};
912
853
  const scope = new Map(current.scope);
913
854
  for (const [name, value] of Object.entries(attributes)) {
914
855
  if (typeof value !== "string") continue;
@@ -927,30 +868,28 @@ const validateSchemaAttributes = (xml) => {
927
868
  if (values.has(resolved)) return `Duplicate XML attribute: ${name}`;
928
869
  if (typeof value === "string") values.set(resolved, value);
929
870
  }
930
- for (const [tag, nodes] of Object.entries(node)) {
931
- if (tag === ":@" || tag.startsWith("#") || tag.startsWith("?")) continue;
932
- const name = resolveName({
933
- name: tag,
934
- scope,
935
- attribute: false
936
- });
937
- if (name === null) return `Unbound XML element prefix: ${tag}`;
938
- const contextual = current.types.flatMap((type) => SCHEMA_ATTRIBUTE_FACTS.types[type]?.children[name] ?? []);
939
- const types = contextual.length ? contextual : SCHEMA_ATTRIBUTE_FACTS.elements[name] ?? [];
940
- let issue = null;
941
- for (const type of types) {
942
- const model = SCHEMA_ATTRIBUTE_FACTS.types[type];
943
- if (!model) continue;
944
- issue = validateAttributes(model, values);
945
- if (issue === null) break;
946
- }
947
- if (issue !== null) return `${tag}: ${issue}`;
948
- pending.push({
949
- nodes,
950
- scope,
951
- types
952
- });
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;
953
886
  }
887
+ if (issue !== null) return `${tag}: ${issue}`;
888
+ pending.push({
889
+ nodes: node.elements ?? [],
890
+ scope,
891
+ types
892
+ });
954
893
  }
955
894
  }
956
895
  return null;
@@ -989,15 +928,6 @@ const VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES = 33554432;
989
928
  const VALIDATE_DOCX_MAX_COMPRESSION_RATIO = 200;
990
929
  const VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES = 4194304;
991
930
  const WORDPROCESSINGML_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
992
- const packageXmlParser = new XMLParser({
993
- preserveOrder: true,
994
- ignoreAttributes: false,
995
- attributeNamePrefix: "",
996
- parseTagValue: false,
997
- parseAttributeValue: false,
998
- processEntities: false,
999
- ignoreDeclaration: true
1000
- });
1001
931
  const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
1002
932
  "xml",
1003
933
  "rels",
@@ -1084,8 +1014,6 @@ const openArchive = async (bytes) => {
1084
1014
  }
1085
1015
  };
1086
1016
  };
1087
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1088
- const elementName = (node) => Object.keys(node).find((key) => key !== ":@" && !key.startsWith("?")) ?? null;
1089
1017
  const localName = (name) => name.slice(name.indexOf(":") + 1);
1090
1018
  const prefix = (name) => {
1091
1019
  const separator = name.indexOf(":");
@@ -1097,22 +1025,19 @@ const namespaceFor = (name, attributes, inherited = {}) => {
1097
1025
  return typeof value === "string" ? value : null;
1098
1026
  };
1099
1027
  const validateDocumentXml = (xml) => {
1100
- if (XMLValidator.validate(xml) !== true) return "Generated DOCX has malformed word/document.xml.";
1101
- const parsed = packageXmlParser.parse(xml);
1102
- if (!Array.isArray(parsed)) return "Generated DOCX has no word/document.xml root document.";
1103
- const root = parsed.find(isRecord);
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"));
1104
1036
  if (!root) return "Generated DOCX has no word/document.xml root document.";
1105
- const rootName = elementName(root);
1106
- const rootAttributes = isRecord(root[":@"]) ? root[":@"] : {};
1037
+ const rootName = root.type === "element" ? root.name ?? null : null;
1038
+ const rootAttributes = root.attributes ?? {};
1107
1039
  if (rootName === null || localName(rootName) !== "document" || !WORDPROCESSINGML_NAMESPACES.has(namespaceFor(rootName, rootAttributes) ?? "")) return "Generated DOCX has no WordprocessingML document root.";
1108
- const children = root[rootName];
1109
- if (!Array.isArray(children)) return "Generated DOCX document root has no WordprocessingML body.";
1110
- return children.some((child) => {
1111
- if (!isRecord(child)) return false;
1112
- const childName = elementName(child);
1113
- const childAttributes = isRecord(child[":@"]) ? child[":@"] : {};
1114
- return childName !== null && localName(childName) === "body" && WORDPROCESSINGML_NAMESPACES.has(namespaceFor(childName, childAttributes, rootAttributes) ?? "");
1115
- }) ? 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.";
1116
1041
  };
1117
1042
  const validateDocxPackage = async (buffer) => {
1118
1043
  try {
@@ -1836,6 +1836,31 @@ export declare const contentRank: (operation: ContentRankOperation, target: {
1836
1836
  export declare const compareBatchOrder: (left: BatchOrderAddress, right: BatchOrderAddress) => number;
1837
1837
  /** Order operations once from addresses captured before the batch changes the document. */
1838
1838
  export declare const orderBatchOperations: <T>(operations: readonly T[], addressOf: (operation: T) => BatchOrderAddress) => T[];
1839
+ /** The pre-batch blocks an operation names and the ones it takes away. */
1840
+ type BatchBlockAccess<Block> = {
1841
+ /** Blocks the operation edits or places something beside. */
1842
+ addresses: readonly Block[];
1843
+ /** Blocks the operation deletes, or merges into the block before them. */
1844
+ removes: readonly Block[];
1845
+ };
1846
+ /**
1847
+ * Whether deleting a block takes it out of the document. A container (a
1848
+ * story, cell, note or text box) has to end with a paragraph, so deleting its
1849
+ * last one with no paragraph the batch keeps before it to take its break only
1850
+ * empties it: it stays, and can still be addressed.
1851
+ */
1852
+ export declare const deletionRemovesBlock: (deletion: {
1853
+ endsContainer: boolean;
1854
+ hasKeptParagraphBefore: boolean;
1855
+ }) => boolean;
1856
+ /**
1857
+ * A batch equals its operations applied one at a time with every operation
1858
+ * that addresses a block before any operation that removes that block: a
1859
+ * single edit can only address a block that still stands. Each operation
1860
+ * that addresses a block another one ahead of it removes moves to just before
1861
+ * the earliest such remover; every other operation keeps its place.
1862
+ */
1863
+ export declare const orderAddressingBeforeRemoval: <T, Block>(ordered: readonly T[], accessOf: (operation: T) => BatchBlockAccess<Block>) => T[];
1839
1864
  /**
1840
1865
  * Partition an ordered batch into execution runs. Insertions at the same
1841
1866
  * position share a run; every other operation remains a singleton.
@@ -1848,4 +1873,4 @@ export declare const orderBatchOperations: <T>(operations: readonly T[], address
1848
1873
  * requested sequence, which no series of single edits produces.
1849
1874
  */
1850
1875
  export declare const groupInsertionRuns: <T>(operations: readonly T[], insertionPositionOf: (operation: T) => number | null, keepsGap?: (operation: T) => boolean) => T[][];
1851
- export type { AddNoteOp, AppliedDocumentOp, BatchOrderAddress, BatchRejectionReason, BlockInsertionPoint, BoundaryOccurrence, CommentAnchor, CommentExhaustionInput, CommentState, CopyOriginAncestorList, CreateCommentOp, CreateHeaderFooterOp, CreateNumberingInstanceOp, DeleteBlocksOp, DeleteColumnOp, DeleteCommentOp, DeleteNumberingInstanceOp, DeleteRangeOp, DeleteRowOp, DeleteTableOp, DocumentBatch, DocumentOp, DocumentOpEnvelope, DocumentOpRefusalReason, DocumentOpType, EditorIntent, EditorIntentMode, EmptyPropertySet, FormattingPatch, HeaderFooterStory, InlineSlice, InsertBlocksOp, InsertColumnOp, InsertContentOp, InsertRowOp, InsertTableOp, InsertTextOp, InsertedRunProps, JoinBlocksOp, JoinInlineOp, MergeCellsOp, NewIds, NoteStory, NumberingPartState, OpStory, PackageResourceEntry, PackageResourceEntryChange, PackageResourceMapChange, PackageResourceMedia, PackageResourcePart, PackageResources, ParagraphContentVerdict, ParagraphPropsPatch, ParagraphReviewFields, PlanTrackedDeletionOptions, PlanTrackedReplaceOptions, RemoveHeaderFooterOp, RemoveNoteOp, ReplaceBlocksOp, ReplaceInlineOp, ResolveRevisionOp, RestoreCommentStateOp, RestoreStoryPartsOp, RevisionDecision, RevisionStamp, RunPropsPatch, SectionEndpoint, SectionMapState, SectionPropertiesState, SectionViewEntry, SectionViewState, SequencedBatch, SetCellPropsOp, SetCommentResolutionOp, SetContainerBlocksOp, SetPackageResourcesOp, SetParagraphPropsOp, SetParagraphReviewOp, SetRowPropsOp, SetRunPropsOp, SetSectionEndpointOp, SetSectionPropsOp, SetTableGridOp, SetTableOp, SetTablePropsOp, SetTableRowsOp, SplitBlockOp, SplitCellOp, SplitHalf, SplitInlineOp, SplitParagraphFields, TableEditOp, TableIntentOperation, TextPosition, TouchedBlocks, UpdateCommentContentOp, WellFormedRangePlan, ZeroWidthItem };
1876
+ export type { AddNoteOp, AppliedDocumentOp, BatchBlockAccess, BatchOrderAddress, BatchRejectionReason, BlockInsertionPoint, BoundaryOccurrence, CommentAnchor, CommentExhaustionInput, CommentState, CopyOriginAncestorList, CreateCommentOp, CreateHeaderFooterOp, CreateNumberingInstanceOp, DeleteBlocksOp, DeleteColumnOp, DeleteCommentOp, DeleteNumberingInstanceOp, DeleteRangeOp, DeleteRowOp, DeleteTableOp, DocumentBatch, DocumentOp, DocumentOpEnvelope, DocumentOpRefusalReason, DocumentOpType, EditorIntent, EditorIntentMode, EmptyPropertySet, FormattingPatch, HeaderFooterStory, InlineSlice, InsertBlocksOp, InsertColumnOp, InsertContentOp, InsertRowOp, InsertTableOp, InsertTextOp, InsertedRunProps, JoinBlocksOp, JoinInlineOp, MergeCellsOp, NewIds, NoteStory, NumberingPartState, OpStory, PackageResourceEntry, PackageResourceEntryChange, PackageResourceMapChange, PackageResourceMedia, PackageResourcePart, PackageResources, ParagraphContentVerdict, ParagraphPropsPatch, ParagraphReviewFields, PlanTrackedDeletionOptions, PlanTrackedReplaceOptions, RemoveHeaderFooterOp, RemoveNoteOp, ReplaceBlocksOp, ReplaceInlineOp, ResolveRevisionOp, RestoreCommentStateOp, RestoreStoryPartsOp, RevisionDecision, RevisionStamp, RunPropsPatch, SectionEndpoint, SectionMapState, SectionPropertiesState, SectionViewEntry, SectionViewState, SequencedBatch, SetCellPropsOp, SetCommentResolutionOp, SetContainerBlocksOp, SetPackageResourcesOp, SetParagraphPropsOp, SetParagraphReviewOp, SetRowPropsOp, SetRunPropsOp, SetSectionEndpointOp, SetSectionPropsOp, SetTableGridOp, SetTableOp, SetTablePropsOp, SetTableRowsOp, SplitBlockOp, SplitCellOp, SplitHalf, SplitInlineOp, SplitParagraphFields, TableEditOp, TableIntentOperation, TextPosition, TouchedBlocks, UpdateCommentContentOp, WellFormedRangePlan, ZeroWidthItem };
@@ -16447,6 +16447,41 @@ const compareBatchOrder = (left, right) => {
16447
16447
  /** Order operations once from addresses captured before the batch changes the document. */
16448
16448
  const orderBatchOperations = (operations, addressOf) => operations.toSorted((left, right) => compareBatchOrder(addressOf(left), addressOf(right)));
16449
16449
  /**
16450
+ * Whether deleting a block takes it out of the document. A container (a
16451
+ * story, cell, note or text box) has to end with a paragraph, so deleting its
16452
+ * last one with no paragraph the batch keeps before it to take its break only
16453
+ * empties it: it stays, and can still be addressed.
16454
+ */
16455
+ const deletionRemovesBlock = (deletion) => !deletion.endsContainer || deletion.hasKeptParagraphBefore;
16456
+ /**
16457
+ * A batch equals its operations applied one at a time with every operation
16458
+ * that addresses a block before any operation that removes that block: a
16459
+ * single edit can only address a block that still stands. Each operation
16460
+ * that addresses a block another one ahead of it removes moves to just before
16461
+ * the earliest such remover; every other operation keeps its place.
16462
+ */
16463
+ const orderAddressingBeforeRemoval = (ordered, accessOf) => {
16464
+ const result = [...ordered];
16465
+ const removesAny = (remover, blocks) => {
16466
+ const { removes } = accessOf(remover);
16467
+ return blocks.some((block) => removes.includes(block));
16468
+ };
16469
+ for (let round = 0; round <= result.length * result.length; round += 1) {
16470
+ const from = result.findIndex((operation, at) => {
16471
+ const { addresses } = accessOf(operation);
16472
+ return addresses.length > 0 && result.slice(0, at).some((earlier) => removesAny(earlier, addresses));
16473
+ });
16474
+ if (from < 0) return result;
16475
+ const operation = result[from];
16476
+ if (operation === void 0) return result;
16477
+ const { addresses } = accessOf(operation);
16478
+ const to = result.findIndex((candidate) => removesAny(candidate, addresses));
16479
+ result.splice(from, 1);
16480
+ result.splice(to, 0, operation);
16481
+ }
16482
+ throw new Error("A batch has no order that addresses each block before removing it");
16483
+ };
16484
+ /**
16450
16485
  * Partition an ordered batch into execution runs. Insertions at the same
16451
16486
  * position share a run; every other operation remains a singleton.
16452
16487
  *
@@ -16480,4 +16515,4 @@ const groupInsertionRuns = (operations, insertionPositionOf, keepsGap = () => fa
16480
16515
  }
16481
16516
  return groups;
16482
16517
  };
16483
- export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, groupInsertionRuns, idKey, inlineLeafSpans, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, orderBatchOperations, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphIdsIn, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphRemains, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, reconcileDocumentPartRelationships, registerParagraphPropertySnapshot, rejectCopyOriginAncestors, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, shiftCopyOriginAncestors, storyBody, survivingComments, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withoutCommentThreads, zeroWidthLeavesAt };
16518
+ export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, groupInsertionRuns, idKey, inlineLeafSpans, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphIdsIn, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphRemains, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, reconcileDocumentPartRelationships, registerParagraphPropertySnapshot, rejectCopyOriginAncestors, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, shiftCopyOriginAncestors, storyBody, survivingComments, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withoutCommentThreads, zeroWidthLeavesAt };
@@ -1 +1 @@
1
- export { a as SEQUENCE_CHILDREN, o as SETTINGS_CHILDREN, t as assertSafePreservedMarkup, n as isSafePreservedChildXml, r as isWithinPreservedMarkupBudget, i as serializeSequenceChildren } from "../sequenceChildren-CrMcryEF.js";
1
+ export { a as SEQUENCE_CHILDREN, o as SETTINGS_CHILDREN, t as assertSafePreservedMarkup, n as isSafePreservedChildXml, r as isWithinPreservedMarkupBudget, i as serializeSequenceChildren } from "../sequenceChildren-CSn0-1ov.js";
@@ -1,5 +1,5 @@
1
+ import { o as readXml } from "./streamingXmlParser-GnKxUuw_.js";
1
2
  import { TaggedError } from "better-result";
2
- import { XMLParser, XMLValidator } from "fast-xml-parser";
3
3
  import { OOXML_NS } from "@stll/docx-utils";
4
4
  // src/schema/sequenceChildren.gen.ts
5
5
  /**
@@ -375,18 +375,6 @@ const MAX_PRESERVED_CHILD_XML_CHARACTERS = 1048576;
375
375
  const MAX_PRESERVED_CHILD_COUNT = 4096;
376
376
  const MAX_PRESERVED_MARKUP_CHARACTERS = 4194304;
377
377
  const PRESERVED_CHILD_WRAPPER = "folio-preserved-child-root";
378
- const preservedChildParser = new XMLParser({
379
- preserveOrder: true,
380
- ignoreAttributes: false,
381
- attributeNamePrefix: "",
382
- trimValues: false,
383
- parseTagValue: false,
384
- parseAttributeValue: false,
385
- ignoreDeclaration: false,
386
- ignorePiTags: false,
387
- processEntities: false,
388
- htmlEntities: false
389
- });
390
378
  const InvalidPreservedChildXmlErrorBase = TaggedError("InvalidPreservedChildXmlError");
391
379
  var InvalidPreservedChildXmlError = class extends InvalidPreservedChildXmlErrorBase {};
392
380
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -467,12 +455,9 @@ const hasValidNamespaces = (root, inherited) => {
467
455
  const current = pending.pop();
468
456
  if (current === void 0) continue;
469
457
  const { node, bindings: parentBindings } = current;
470
- const nodeNames = Object.keys(node).filter((name) => name !== ":@");
471
- const name = nodeNames[0];
472
- if (nodeNames.length !== 1 || name === void 0) return false;
473
- if (name.startsWith("#") || name.startsWith("?") || name.startsWith("!")) continue;
474
- const rawAttributes = node[":@"];
475
- const attributes = isRecord(rawAttributes) ? rawAttributes : {};
458
+ const name = node.name;
459
+ if (node.type !== "element" || name === void 0) continue;
460
+ const attributes = node.attributes ?? {};
476
461
  const bindings = applyNamespaceDeclarations(attributes, parentBindings);
477
462
  if (bindings === void 0) return false;
478
463
  const elementPrefix = namespacePrefix(name);
@@ -489,15 +474,10 @@ const hasValidNamespaces = (root, inherited) => {
489
474
  if (expandedAttributeNames.has(expandedName)) return false;
490
475
  expandedAttributeNames.add(expandedName);
491
476
  }
492
- const children = node[name];
493
- if (!Array.isArray(children)) return false;
494
- for (const child of children) {
495
- if (!isRecord(child)) return false;
496
- pending.push({
497
- node: child,
498
- bindings
499
- });
500
- }
477
+ for (const child of node.elements ?? []) pending.push({
478
+ node: child,
479
+ bindings
480
+ });
501
481
  }
502
482
  return true;
503
483
  };
@@ -506,23 +486,15 @@ const isSafePreservedChildXml = (xml) => {
506
486
  const trimmed = xml.trim();
507
487
  if (trimmed.length === 0 || trimmed.length > MAX_PRESERVED_CHILD_XML_CHARACTERS || /<!\s*(?:DOCTYPE|ENTITY)\b/iu.test(trimmed) || !hasOnlyValidXmlReferences(trimmed)) return false;
508
488
  const wrapped = `<${PRESERVED_CHILD_WRAPPER}>${trimmed}</${PRESERVED_CHILD_WRAPPER}>`;
509
- if (XMLValidator.validate(wrapped) !== true) return false;
510
- let parsed;
511
- try {
512
- parsed = preservedChildParser.parse(wrapped);
513
- } catch {
514
- return false;
515
- }
516
- if (!Array.isArray(parsed) || parsed.length !== 1) return false;
517
- const wrapper = parsed[0];
518
- if (!isRecord(wrapper)) return false;
519
- const children = wrapper[PRESERVED_CHILD_WRAPPER];
520
- if (!Array.isArray(children) || children.length !== 1) return false;
521
- const child = children[0];
522
- if (!isRecord(child)) return false;
523
- const nodeNames = Object.keys(child).filter((name) => name !== ":@");
524
- const nodeName = nodeNames[0];
525
- return nodeNames.length === 1 && nodeName !== void 0 && !nodeName.startsWith("#") && !nodeName.startsWith("?") && !nodeName.startsWith("!") && hasValidNamespaces(child, INHERITED_NAMESPACE_BINDINGS);
489
+ const read = readXml(wrapped, {
490
+ conformance: "well-formed",
491
+ references: "raw",
492
+ instructions: "retain"
493
+ });
494
+ if (read.status === "rejected") return false;
495
+ const children = read.value.elements?.at(0)?.elements ?? [];
496
+ const child = children.at(0);
497
+ return children.length === 1 && child?.type === "element" && hasValidNamespaces(child, INHERITED_NAMESPACE_BINDINGS);
526
498
  };
527
499
  /** Whether a capture collection stays within its aggregate resource budget. */
528
500
  const isWithinPreservedMarkupBudget = (children) => {