@stll/docx-core 0.29.0 → 0.30.1

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
@@ -177,6 +177,55 @@ type SerializeDocumentOptions = {
177
177
  */
178
178
  declare const serializeDocumentToDocx: (document: Document, options?: SerializeDocumentOptions) => Promise<ArrayBuffer>;
179
179
  //#endregion
180
+ //#region src/serialize/numericIds.d.ts
181
+ declare const InvalidOoxmlNumericIdError_base: import("better-result").TaggedErrorClass<"InvalidOoxmlNumericIdError">;
182
+ /** A writer would emit an identifier outside its OOXML schema's numeric domain. */
183
+ declare class InvalidOoxmlNumericIdError extends InvalidOoxmlNumericIdError_base<{
184
+ message: string;
185
+ partPath: string;
186
+ elementName: string;
187
+ attributeName: string;
188
+ value: string;
189
+ }> {}
190
+ type NumericIdOptions = {
191
+ value: string | number;
192
+ partPath: string;
193
+ elementName: string;
194
+ attributeName: string;
195
+ domain?: "signed32" | "unsigned32";
196
+ };
197
+ declare const isValidOoxmlNumericId: (value: string | number, domain?: "signed32" | "unsigned32") => boolean;
198
+ declare const assertValidOoxmlNumericId: ({ value, partPath, elementName, attributeName, domain }: NumericIdOptions) => void;
199
+ type NumericIdAttributeOptions = {
200
+ elementName: string;
201
+ elementNamespace: string | undefined;
202
+ attributeName: string;
203
+ attributeNamespace: string | undefined;
204
+ };
205
+ /** Shared schema classification for import normalization and writer validation. */
206
+ declare const ooxmlNumericIdDomain: ({ elementName, elementNamespace, attributeName, attributeNamespace }: NumericIdAttributeOptions) => "signed32" | "unsigned32" | undefined;
207
+ type OoxmlNumericIdAttributeOptions = {
208
+ elementName: string;
209
+ attributeName: string;
210
+ };
211
+ /** Attributes an identity scan must retain, derived from the domain classifier. */
212
+ declare const isOoxmlNumericIdAttributeName: ({ elementName, attributeName }: OoxmlNumericIdAttributeOptions) => boolean;
213
+ /** Conservative presence check; safe IDs must still be reserved during import repair. */
214
+ declare const mayContainOoxmlNumericIds: (xml: string) => boolean;
215
+ /**
216
+ * Conservative lexical preflight; namespace classification remains authoritative.
217
+ * A prefix is considered numeric if any scope binds it to WordprocessingML. This can send
218
+ * a shadowed foreign attribute to the full parser, but cannot hide a numeric one.
219
+ * Suspicious values with entity-encoded bindings or values require the authoritative scan.
220
+ */
221
+ declare const mayContainInvalidOoxmlNumericIds: (xml: string, mode?: "schema" | "range") => boolean;
222
+ /**
223
+ * Validate both authored and opaque replayed identifiers by namespace URI.
224
+ * This runs at ZIP exits too, so unchanged parts cannot bypass the writer guard.
225
+ * Permission-range ids are strings in OOXML and intentionally remain unrestricted.
226
+ */
227
+ declare const assertValidOoxmlNumericIds: (xml: string, partPath: string) => void;
228
+ //#endregion
180
229
  //#region src/serialize/xml.d.ts
181
230
  /**
182
231
  * The one writer for a `CT_OnOff` element: `w:b`, `w:cantSplit`, `w:hideMark`,
@@ -320,4 +369,4 @@ declare const validateDocxPackage: (buffer: ArrayBuffer | Uint8Array) => Promise
320
369
  declare const validateDocumentModel: (document: Document) => ValidateDocumentModelResult;
321
370
  declare const assertValidDocumentModel: (document: Document) => void;
322
371
  //#endregion
323
- export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBackground, type DocumentBackgroundDrawing, type DocumentBody, type DocxConformanceClass, type DocxPackage, type DocxPackageIssueCode, type LegalDraft, type LegalDraftBlock, type LegalDraftDiagnostic, type LegalSourceCompileOptions, type LegalSourceCompileResult, type LegalSourceDocxCompileResult, type LegalSourceParseResult, type MarkdownContent, type Paragraph, type ParagraphContent, type PositionalTab, type Run, type RunContent, type SectionProperties, type Style, type Table, type TableCell, type TableRow, type TextContent, type ValidateDocumentModelIssue, type ValidateDocumentModelResult, type ValidateDocxPackageResult, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
372
+ export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBackground, type DocumentBackgroundDrawing, type DocumentBody, type DocxConformanceClass, type DocxPackage, type DocxPackageIssueCode, InvalidOoxmlNumericIdError, type LegalDraft, type LegalDraftBlock, type LegalDraftDiagnostic, type LegalSourceCompileOptions, type LegalSourceCompileResult, type LegalSourceDocxCompileResult, type LegalSourceParseResult, type MarkdownContent, type Paragraph, type ParagraphContent, type PositionalTab, type Run, type RunContent, type SectionProperties, type Style, type Table, type TableCell, type TableRow, type TextContent, type ValidateDocumentModelIssue, type ValidateDocumentModelResult, type ValidateDocxPackageResult, assertValidDocumentModel, assertValidOoxmlNumericId, assertValidOoxmlNumericIds, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, isOoxmlNumericIdAttributeName, isValidOoxmlNumericId, mayContainInvalidOoxmlNumericIds, mayContainOoxmlNumericIds, ooxmlNumericIdDomain, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { $ as paragraphNumberingReferenceId, Q as paragraphNumberingReference, U as headingOutlineLevel, Z as paragraphNumberingLevel, _ as borderStyleToken, c as isNoteReferenceId, et as paragraphNumberingSlots, l as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, x as statesNoBorder } from "./document-DdWrTPQY.js";
1
+ import { $ as paragraphNumberingReferenceId, Q as paragraphNumberingReference, U as headingOutlineLevel, Z as paragraphNumberingLevel, _ as borderStyleToken, c as isNoteReferenceId, et as paragraphNumberingSlots, i as MAX_REVISION_ID, l as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, x as statesNoBorder } from "./document-DdWrTPQY.js";
2
2
  import { i as serializeSequenceChildren } from "./sequenceChildren-BIixCB49.js";
3
3
  import { i as sanitizeXmlCharacters, n as escapeXmlText, r as hasIllegalXmlCharacters, t as escapeXmlAttribute } from "./xmlEscape-T-2DeGlS.js";
4
- import { panic } from "better-result";
4
+ import { TaggedError, panic } from "better-result";
5
5
  import JSZip from "jszip";
6
6
  import { XMLParser, XMLValidator } from "fast-xml-parser";
7
7
  import { Marked } from "marked";
@@ -18,6 +18,204 @@ import { Marked } from "marked";
18
18
  */
19
19
  const requiresXmlSpacePreserve = (text) => text.startsWith(" ") || text.endsWith(" ") || text.includes(" ");
20
20
  //#endregion
21
+ //#region src/serialize/numericIds.ts
22
+ const WORD_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
23
+ const DRAWING_NAMESPACES = /* @__PURE__ */ new Set([
24
+ "http://schemas.openxmlformats.org/drawingml/2006/main",
25
+ "http://schemas.openxmlformats.org/drawingml/2006/picture",
26
+ "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
27
+ "http://purl.oclc.org/ooxml/drawingml/main",
28
+ "http://purl.oclc.org/ooxml/drawingml/picture",
29
+ "http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing",
30
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
31
+ ]);
32
+ const NUMBERING_ATTRIBUTES = /* @__PURE__ */ new Set([
33
+ "numId",
34
+ "abstractNumId",
35
+ "numPicBulletId"
36
+ ]);
37
+ const ID_VALUE_ELEMENTS = /* @__PURE__ */ new Set([
38
+ "id",
39
+ "numId",
40
+ "abstractNumId",
41
+ "lvlPicBulletId"
42
+ ]);
43
+ const STRING_ID_ELEMENTS = /* @__PURE__ */ new Set(["permStart", "permEnd"]);
44
+ const MAX_UNSIGNED_ID = 4294967295;
45
+ const MIN_SIGNED_ID = -2147483648;
46
+ /** A writer would emit an identifier outside its OOXML schema's numeric domain. */
47
+ var InvalidOoxmlNumericIdError = class extends TaggedError("InvalidOoxmlNumericIdError") {};
48
+ const isValidOoxmlNumericId = (value, domain = "signed32") => {
49
+ const spelling = String(value).trim();
50
+ const numeric = Number(spelling);
51
+ const min = domain === "unsigned32" ? 0 : MIN_SIGNED_ID;
52
+ const max = domain === "unsigned32" ? MAX_UNSIGNED_ID : MAX_REVISION_ID;
53
+ return /^[+-]?\d+$/u.test(spelling) && Number.isInteger(numeric) && numeric >= min && numeric <= max;
54
+ };
55
+ const assertValidOoxmlNumericId = ({ value, partPath, elementName, attributeName, domain = "signed32" }) => {
56
+ if (isValidOoxmlNumericId(value, domain)) return;
57
+ throw new InvalidOoxmlNumericIdError({
58
+ message: `${partPath}: ${elementName} ${attributeName} must be an integer in [${domain === "unsigned32" ? 0 : MIN_SIGNED_ID}, ${domain === "unsigned32" ? MAX_UNSIGNED_ID : MAX_REVISION_ID}], got ${String(value)}`,
59
+ partPath,
60
+ elementName,
61
+ attributeName,
62
+ value: String(value)
63
+ });
64
+ };
65
+ /** Shared schema classification for import normalization and writer validation. */
66
+ const ooxmlNumericIdDomain = ({ elementName, elementNamespace, attributeName, attributeNamespace }) => {
67
+ const elementLocalName = localName$1(elementName);
68
+ const attributeLocalName = localName$1(attributeName);
69
+ 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";
70
+ if (attributeName === "id" && DRAWING_NAMESPACES.has(elementNamespace ?? "") && (elementLocalName === "docPr" || elementLocalName === "cNvPr")) return "unsigned32";
71
+ };
72
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
73
+ const localName$1 = (name) => name.slice(name.indexOf(":") + 1);
74
+ const namespaceUri = (name, bindings) => {
75
+ const colon = name.indexOf(":");
76
+ return bindings.get(colon === -1 ? "" : name.slice(0, colon));
77
+ };
78
+ const decodeAttributeReferences = (value) => value.replace(/&(?:#(x[\da-f]+|\d+)|amp|lt|gt|quot|apos);/giu, (reference, digits) => {
79
+ if (digits !== void 0) {
80
+ const codePoint = digits.toLowerCase().startsWith("x") ? Number.parseInt(digits.slice(1), 16) : Number(digits);
81
+ if (codePoint <= 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) return reference;
82
+ return String.fromCodePoint(codePoint);
83
+ }
84
+ switch (reference) {
85
+ case "&amp;": return "&";
86
+ case "&lt;": return "<";
87
+ case "&gt;": return ">";
88
+ case "&quot;": return "\"";
89
+ case "&apos;": return "'";
90
+ default: return reference;
91
+ }
92
+ });
93
+ const ID_ATTRIBUTE_NAMES = ["id", ...NUMBERING_ATTRIBUTES].join("|");
94
+ const ID_ELEMENT_NAMES = [...ID_VALUE_ELEMENTS].join("|");
95
+ /** Attributes an identity scan must retain, derived from the domain classifier. */
96
+ const isOoxmlNumericIdAttributeName = ({ elementName, attributeName }) => {
97
+ const attribute = localName$1(attributeName);
98
+ return attribute === "id" || NUMBERING_ATTRIBUTES.has(attribute) || attribute === "val" && ID_VALUE_ELEMENTS.has(localName$1(elementName));
99
+ };
100
+ const ID_CANDIDATE = new RegExp(`\\b(?:${ID_ATTRIBUTE_NAMES})\\s*=|<(?:[^\\s<>/:]+:)?(?:${ID_ELEMENT_NAMES})(?:[\\s/>])`, "u");
101
+ /** Conservative presence check; safe IDs must still be reserved during import repair. */
102
+ const mayContainOoxmlNumericIds = (xml) => ID_CANDIDATE.test(xml);
103
+ const PREFIX = "[^\\s<>/:=\"']+";
104
+ const ID_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?(?:${ID_ATTRIBUTE_NAMES}))\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
105
+ const ID_VALUE_TAG = new RegExp(`<((?:${PREFIX}:)?(?:${ID_ELEMENT_NAMES}))(?=[\\s/>])((?:[^<>"']|"[^"]*"|'[^']*')*)>`, "gu");
106
+ const VALUE_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?val)\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
107
+ const RANGE_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?(?:${ID_ATTRIBUTE_NAMES}|val))\\s*=\\s*(["'])\\s*([+-]?\\d{10,}|-\\d+|[^"'<>]*&[^"'<>]*)\\s*\\2`, "gu");
108
+ const hasRangeCandidate = (xml) => {
109
+ for (const match of xml.matchAll(RANGE_ATTRIBUTE)) {
110
+ const value = match[3] ?? "";
111
+ if (value.includes("&")) return true;
112
+ const domain = (match[1] ?? "").includes(":") ? "signed32" : "unsigned32";
113
+ if (!isValidOoxmlNumericId(value.trim(), domain)) return true;
114
+ }
115
+ return false;
116
+ };
117
+ const NAMESPACE_BINDING = new RegExp(`\\bxmlns(?::(${PREFIX}))?\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
118
+ const prefixOf = (name) => {
119
+ const colon = name.indexOf(":");
120
+ return colon === -1 ? "" : name.slice(0, colon);
121
+ };
122
+ /**
123
+ * Conservative lexical preflight; namespace classification remains authoritative.
124
+ * A prefix is considered numeric if any scope binds it to WordprocessingML. This can send
125
+ * a shadowed foreign attribute to the full parser, but cannot hide a numeric one.
126
+ * Suspicious values with entity-encoded bindings or values require the authoritative scan.
127
+ */
128
+ const mayContainInvalidOoxmlNumericIds = (xml, mode = "schema") => {
129
+ if (mode === "range") {
130
+ if (!hasRangeCandidate(xml)) return false;
131
+ } else if (!mayContainOoxmlNumericIds(xml)) return false;
132
+ const wordPrefixes = /* @__PURE__ */ new Set();
133
+ for (const match of xml.matchAll(NAMESPACE_BINDING)) {
134
+ const namespace = match[3] ?? "";
135
+ if (namespace.includes("&")) return true;
136
+ if (WORD_NAMESPACES.has(namespace)) wordPrefixes.add(match[1] ?? "");
137
+ }
138
+ const needsScan = (value, domain) => {
139
+ if (value.includes("&")) return true;
140
+ if (mode === "range" && !/^[+-]?\d+$/u.test(value.trim())) return false;
141
+ return !isValidOoxmlNumericId(value, domain ?? "unsigned32");
142
+ };
143
+ for (const match of xml.matchAll(ID_ATTRIBUTE)) {
144
+ const name = match[1] ?? "";
145
+ if (name.includes(":")) {
146
+ if (wordPrefixes.has(prefixOf(name)) && needsScan(match[3] ?? "", "signed32")) return true;
147
+ continue;
148
+ }
149
+ if (name === "id" && needsScan(match[3] ?? "")) return true;
150
+ }
151
+ for (const match of xml.matchAll(ID_VALUE_TAG)) {
152
+ if (!wordPrefixes.has(prefixOf(match[1] ?? ""))) continue;
153
+ for (const attribute of (match[2] ?? "").matchAll(VALUE_ATTRIBUTE)) {
154
+ const name = attribute[1] ?? "";
155
+ if (name.includes(":") && wordPrefixes.has(prefixOf(name)) && needsScan(attribute[3] ?? "", "signed32")) return true;
156
+ }
157
+ }
158
+ return false;
159
+ };
160
+ /**
161
+ * Validate both authored and opaque replayed identifiers by namespace URI.
162
+ * This runs at ZIP exits too, so unchanged parts cannot bypass the writer guard.
163
+ * Permission-range ids are strings in OOXML and intentionally remain unrestricted.
164
+ */
165
+ const assertValidOoxmlNumericIds = (xml, partPath) => {
166
+ if (!mayContainInvalidOoxmlNumericIds(xml)) return;
167
+ const parser = new XMLParser({
168
+ preserveOrder: true,
169
+ ignoreAttributes: false,
170
+ attributeNamePrefix: "",
171
+ parseTagValue: false,
172
+ parseAttributeValue: false,
173
+ processEntities: false,
174
+ attributeValueProcessor: (_name, value) => decodeAttributeReferences(value),
175
+ htmlEntities: false,
176
+ ignoreDeclaration: true
177
+ });
178
+ const visit = (nodes, inherited) => {
179
+ if (!Array.isArray(nodes)) return;
180
+ for (const node of nodes) {
181
+ if (!isRecord$1(node)) continue;
182
+ const attributes = node[":@"];
183
+ let localBindings;
184
+ if (isRecord$1(attributes)) for (const [name, value] of Object.entries(attributes)) {
185
+ if (typeof value !== "string") continue;
186
+ if (name === "xmlns" || name.startsWith("xmlns:")) {
187
+ localBindings ??= new Map(inherited);
188
+ localBindings.set(name === "xmlns" ? "" : name.slice(6), value);
189
+ }
190
+ }
191
+ const bindings = localBindings ?? inherited;
192
+ for (const [elementName, children] of Object.entries(node)) {
193
+ if (elementName === ":@" || elementName.startsWith("#") || elementName.startsWith("?")) continue;
194
+ const elementNamespace = namespaceUri(elementName, bindings);
195
+ if (isRecord$1(attributes)) for (const [attributeName, value] of Object.entries(attributes)) {
196
+ if (typeof value !== "string" && typeof value !== "number") continue;
197
+ const attributeNamespace = attributeName.includes(":") ? namespaceUri(attributeName, bindings) : void 0;
198
+ const domain = ooxmlNumericIdDomain({
199
+ elementName,
200
+ elementNamespace,
201
+ attributeName,
202
+ attributeNamespace
203
+ });
204
+ if (domain !== void 0) assertValidOoxmlNumericId({
205
+ value,
206
+ partPath,
207
+ elementName,
208
+ attributeName,
209
+ domain
210
+ });
211
+ }
212
+ visit(children, bindings);
213
+ }
214
+ }
215
+ };
216
+ visit(parser.parse(xml), /* @__PURE__ */ new Map());
217
+ };
218
+ //#endregion
21
219
  //#region src/serialize/xml.ts
22
220
  const attr = (name, value) => value === void 0 ? "" : ` ${name}="${escapeXmlAttribute(String(value))}"`;
23
221
  /**
@@ -173,6 +371,10 @@ const serializeDocumentToDocx = async (document, options = {}) => {
173
371
  if (hasNumbering) word?.file("numbering.xml", serializeNumbering(document.package.numbering));
174
372
  word?.file(DEFAULT_FOOTER_PART_NAME, buildFooterXml(options.language));
175
373
  word?.folder("_rels")?.file("document.xml.rels", documentRelsXml(hasNumbering));
374
+ for (const [path, file] of Object.entries(zip.files)) {
375
+ if (file.dir || !path.endsWith(".xml")) continue;
376
+ assertValidOoxmlNumericIds(await file.async("text"), path);
377
+ }
176
378
  return await zip.generateAsync({
177
379
  type: "arraybuffer",
178
380
  compression: "DEFLATE",
@@ -2847,4 +3049,4 @@ const compileMarkdownToContent = (markdown) => {
2847
3049
  };
2848
3050
  };
2849
3051
  //#endregion
2850
- export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
3052
+ export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, InvalidOoxmlNumericIdError, assertValidDocumentModel, assertValidOoxmlNumericId, assertValidOoxmlNumericIds, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, isOoxmlNumericIdAttributeName, isValidOoxmlNumericId, mayContainInvalidOoxmlNumericIds, mayContainOoxmlNumericIds, ooxmlNumericIdDomain, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
@@ -1,16 +1,19 @@
1
- import { Jt as ParagraphMarkChange, Kt as Paragraph, Wr as TextFormatting, Xt as ParagraphPropertyChange, kr as ParagraphFormatting, n as Document, qt as ParagraphContent, zn as TableRow } from "../document-DrtmJ_hz.js";
1
+ import { A as BlockContent, An as Table, Jt as ParagraphMarkChange, Kt as Paragraph, Wr as TextFormatting, Xt as ParagraphPropertyChange, kr as ParagraphFormatting, n as Document, qt as ParagraphContent, zn as TableRow } from "../document-DrtmJ_hz.js";
2
2
  import { Result } from "better-result";
3
3
  //#region src/ops/types.d.ts
4
4
  /**
5
5
  * The operation schema this module reads and writes.
6
6
  *
7
- * Version 3 adds paragraph insertion through `insertBlocks` and the table-row
7
+ * Version 4 adds paragraph deletion through `deleteBlocks`, direct and tracked
8
+ * whole-table operations with their exact structural inverse, terminal insertion,
9
+ * and cell-ending paragraph marks on tracked row operations.
10
+ * Version 3 added paragraph insertion through `insertBlocks` and the table-row
8
11
  * operations `insertRow`, `deleteRow` and `setTableRows`.
9
12
  * Version 2 added tracked changes: the `revision` stamp on the text, formatting
10
13
  * and paragraph operations, and the review operations `setParagraphReview`,
11
14
  * `replaceInline` and `resolveRevision`.
12
15
  */
13
- declare const DOCUMENT_OP_SCHEMA_VERSION = 3;
16
+ declare const DOCUMENT_OP_SCHEMA_VERSION = 4;
14
17
  /**
15
18
  * The stories an operation can address. Headers, footers, notes and comment
16
19
  * bodies are stories too; this version addresses the main story only.
@@ -112,8 +115,9 @@ type RevisionStamp = {
112
115
  };
113
116
  /** The paragraph fields a split gives the new paragraph, besides its id, content and mark. */
114
117
  type SplitParagraphFields = Omit<Paragraph, "type" | "paraId" | "content" | "sectionProperties" | "pPrMark">;
115
- /** The operation kinds of schema version 3. */
118
+ /** The operation kinds of schema version 4. */
116
119
  declare const DOCUMENT_OP_TYPES: Readonly<{
120
+ readonly DELETE_BLOCKS: "deleteBlocks";
117
121
  readonly INSERT_BLOCKS: "insertBlocks";
118
122
  readonly INSERT_TEXT: "insertText";
119
123
  readonly INSERT_CONTENT: "insertContent";
@@ -128,6 +132,9 @@ declare const DOCUMENT_OP_TYPES: Readonly<{
128
132
  readonly SET_PARAGRAPH_REVIEW: "setParagraphReview";
129
133
  readonly REPLACE_INLINE: "replaceInline";
130
134
  readonly RESOLVE_REVISION: "resolveRevision";
135
+ readonly INSERT_TABLE: "insertTable";
136
+ readonly DELETE_TABLE: "deleteTable";
137
+ readonly SET_CONTAINER_BLOCKS: "setContainerBlocks";
131
138
  readonly INSERT_ROW: "insertRow";
132
139
  readonly DELETE_ROW: "deleteRow";
133
140
  readonly SET_TABLE_ROWS: "setTableRows";
@@ -320,7 +327,9 @@ type SplitHalf = (typeof SPLIT_HALVES)[keyof typeof SPLIT_HALVES];
320
327
  * (`firstMark` must then be absent), and the new paragraph, when its paragraph
321
328
  * properties differ from the source's and it carries no property change,
322
329
  * records one from the source's. Rejecting the mark removes it, which leaves
323
- * the second half with the first's content before its own.
330
+ * the second half with the first's content before its own. A property change
331
+ * does not record the mark's run properties, so a new second half, which ends
332
+ * with the paragraph's own mark, must state the same ones as the paragraph.
324
333
  */
325
334
  type SplitBlockOp = {
326
335
  type: typeof DOCUMENT_OP_TYPES.SPLIT_BLOCK;
@@ -394,6 +403,26 @@ type InsertBlocksOp = {
394
403
  revision?: RevisionStamp;
395
404
  newIds?: NewIds;
396
405
  };
406
+ /**
407
+ * Delete adjacent paragraphs in one block list. A following paragraph keeps
408
+ * its identity and fields. At the end of a block list, the last selected
409
+ * paragraph survives: it takes the preceding paragraph's content and
410
+ * paragraph properties when present, keeping its own mark properties and id;
411
+ * without a preceding paragraph it becomes empty.
412
+ *
413
+ * With `revision`, selected content is wrapped in deletions and the removed
414
+ * breaks are marked. The container-final paragraph never receives a mark.
415
+ * Section boundaries, non-paragraph following blocks and conflicting
416
+ * paragraph reviews are refused rather than partially removed. Tracked deletion
417
+ * of content carrying revision or content-control ids is also unsupported.
418
+ */
419
+ type DeleteBlocksOp = {
420
+ type: typeof DOCUMENT_OP_TYPES.DELETE_BLOCKS;
421
+ story: OpStory;
422
+ blockIds: readonly string[];
423
+ revision?: RevisionStamp;
424
+ newIds?: NewIds;
425
+ };
397
426
  /**
398
427
  * Replace a run of adjacent paragraphs with other paragraphs.
399
428
  *
@@ -471,8 +500,8 @@ type RevisionDecision = (typeof REVISION_DECISIONS)[keyof typeof REVISION_DECISI
471
500
  * a join at a section break.
472
501
  * - Row insertions and deletions are resolved after inline changes and before
473
502
  * paragraph marks. Keeping a row clears its structural revision; removing
474
- * it also removes its nested revisions. Removing every row requires a
475
- * whole-table operation and is refused as `untrackable`.
503
+ * it also removes its nested revisions. Removing every row removes the
504
+ * table, preserving the surrounding paragraphs.
476
505
  * - Records the resolution leaves meeting are merged as far as they are
477
506
  * alike: the pieces a change cut apart are one record again.
478
507
  *
@@ -489,8 +518,9 @@ type ResolveRevisionOp = {
489
518
  /**
490
519
  * Insert a row at a zero-based index in the table holding `blockId`.
491
520
  * The paragraph reference selects the innermost table containing it.
492
- * With `revision`, the row and its cell content record an insertion; no
493
- * paragraph mark changes. `newIds` names the additional wrapper ids.
521
+ * With `revision`, the row, its cell content and
522
+ * cell-ending paragraph marks record insertion. `newIds` supplies the
523
+ * additional physical revision ids.
494
524
  */
495
525
  type InsertRowOp = {
496
526
  type: typeof DOCUMENT_OP_TYPES.INSERT_ROW;
@@ -504,8 +534,8 @@ type InsertRowOp = {
504
534
  /**
505
535
  * Remove the row holding `blockId`, or record a row and cell-content deletion
506
536
  * with `revision`. The innermost containing row is selected. `expected`, when
507
- * present, refuses a stale row. Removing the last row requires a table
508
- * operation and is refused; tracked deletion keeps a row not pending deletion.
537
+ * present, refuses a stale row. Direct removal of the last row removes its
538
+ * table; tracked deletion keeps a row not pending deletion.
509
539
  */
510
540
  type DeleteRowOp = {
511
541
  type: typeof DOCUMENT_OP_TYPES.DELETE_ROW;
@@ -517,9 +547,8 @@ type DeleteRowOp = {
517
547
  };
518
548
  /**
519
549
  * Replace a table's rows exactly, with a structural staleness precondition.
520
- * This is the inverse and resolution primitive for row operations. The table
521
- * holding `blockId` must retain at least one row; whole-table removal is a
522
- * separate operation.
550
+ * This is the inverse and resolution primitive for row operations. An empty
551
+ * row list removes the table, with an exact structural inverse.
523
552
  */
524
553
  type SetTableRowsOp = {
525
554
  type: typeof DOCUMENT_OP_TYPES.SET_TABLE_ROWS;
@@ -528,8 +557,51 @@ type SetTableRowsOp = {
528
557
  expected: readonly TableRow[];
529
558
  rows: readonly TableRow[];
530
559
  };
531
- /** A schema-version-3 document operation. */
532
- type DocumentOp = InsertBlocksOp | InsertTextOp | InsertContentOp | DeleteRangeOp | SplitInlineOp | JoinInlineOp | SetRunPropsOp | SetParagraphPropsOp | SplitBlockOp | JoinBlocksOp | ReplaceBlocksOp | SetParagraphReviewOp | ReplaceInlineOp | ResolveRevisionOp | InsertRowOp | DeleteRowOp | SetTableRowsOp;
560
+ /**
561
+ * Insert a table before or after a paragraph. Tracking records each row,
562
+ * cell content and cell-ending paragraph mark. At a container's end,
563
+ * `terminal` moves the source content into a new preceding paragraph while
564
+ * retaining the source id and fields on the untracked final paragraph.
565
+ */
566
+ type InsertTableOp = {
567
+ type: typeof DOCUMENT_OP_TYPES.INSERT_TABLE;
568
+ story: OpStory;
569
+ at: BlockInsertionPoint;
570
+ table: Table;
571
+ revision?: RevisionStamp;
572
+ newIds?: NewIds;
573
+ terminal?: {
574
+ beforeBlockId: string;
575
+ };
576
+ };
577
+ /**
578
+ * Remove the innermost table holding the addressed paragraph. Its block list
579
+ * must retain a paragraph for the inverse. Tracking records row, cell-content
580
+ * and cell-ending paragraph-mark deletions without removing content.
581
+ */
582
+ type DeleteTableOp = {
583
+ type: typeof DOCUMENT_OP_TYPES.DELETE_TABLE;
584
+ story: OpStory;
585
+ blockId: string;
586
+ expected?: Table;
587
+ revision?: RevisionStamp;
588
+ newIds?: NewIds;
589
+ };
590
+ /**
591
+ * Exact structural inverse for table edits. The addressed paragraph must
592
+ * remain in the same block list; unrelated edits in that list make it stale.
593
+ * Section boundaries and story-final marks are preserved; cell-ending marks
594
+ * are exact model data, including after independent row resolution.
595
+ */
596
+ type SetContainerBlocksOp = {
597
+ type: typeof DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS;
598
+ story: OpStory;
599
+ blockId: string;
600
+ expected: readonly BlockContent[];
601
+ blocks: readonly BlockContent[];
602
+ };
603
+ /** A schema-version-4 document operation. */
604
+ type DocumentOp = DeleteBlocksOp | InsertTableOp | DeleteTableOp | SetContainerBlocksOp | InsertBlocksOp | InsertTextOp | InsertContentOp | DeleteRangeOp | SplitInlineOp | JoinInlineOp | SetRunPropsOp | SetParagraphPropsOp | SplitBlockOp | JoinBlocksOp | ReplaceBlocksOp | SetParagraphReviewOp | ReplaceInlineOp | ResolveRevisionOp | InsertRowOp | DeleteRowOp | SetTableRowsOp;
533
605
  /**
534
606
  * An operation as it is journaled and sent: the schema that reads it, and the
535
607
  * operation. A reader refuses an envelope of a schema it does not know rather
@@ -715,18 +787,33 @@ type PlanTrackedDeletionOptions = {
715
787
  newIds?: NewIds;
716
788
  };
717
789
  /**
718
- * The operations a tracked deletion of a range is made of, to apply in
719
- * order as one batch: a direct `deleteRange` for each stretch of the author's
720
- * own insertions (retracting a suggestion removes it), and a tracked one for
721
- * each other stretch, split around comment boundaries and references, which
722
- * no tracked change can hold and which therefore stay. Stretches go from the
723
- * last to the first, so each position still names what it named in the
724
- * input. The positions default their `zeroWidthBefore` as `deleteRange` does.
725
- *
726
- * The first tracked deletion carries the stamp's id. Each later one takes the
727
- * next id of `newIds.revision` the package does not use for its stamp, then
728
- * the ones it needs for the records it cuts.
790
+ * Plan a same-list range as inline deletions followed by tracked paragraph
791
+ * joins. Own insertions are retracted directly; comment anchors remain.
792
+ * Inline ranges run in reverse order, then joins run from last to first.
793
+ * All physical revision ids come from one pool for the complete batch.
729
794
  */
730
795
  declare const planTrackedDeletion: (document: Document, options: PlanTrackedDeletionOptions) => Result<DocumentOp[], DocumentOpRefusal>;
731
796
  //#endregion
732
- export { type AppliedDocumentOp, type BlockInsertionPoint, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, type DeleteRangeOp, type DeleteRowOp, type DocumentOp, type DocumentOpEnvelope, DocumentOpRefusal, type DocumentOpRefusalReason, type DocumentOpType, DocumentOpsContractError, EMPTY_PROPERTY_SETS, type EmptyPropertySet, type FormattingPatch, INHERIT_RUN_PROPS, type InlineSlice, type InsertBlocksOp, type InsertContentOp, type InsertRowOp, type InsertTextOp, type InsertedRunProps, type JoinBlocksOp, type JoinInlineOp, type NewIds, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, type OpStory, PARAGRAPH_MARK_FORMATTING_KEYS, type ParagraphPropsPatch, type ParagraphReviewFields, type PlanTrackedDeletionOptions, REVISION_DECISIONS, type ReplaceBlocksOp, type ReplaceInlineOp, type ResolveRevisionOp, type RevisionDecision, type RevisionStamp, type RunPropsPatch, SPLIT_HALVES, type SetParagraphPropsOp, type SetParagraphReviewOp, type SetRunPropsOp, type SetTableRowsOp, type SplitBlockOp, type SplitHalf, type SplitInlineOp, type SplitParagraphFields, type TextPosition, type TouchedBlocks, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, planTrackedDeletion, revisionIdDemand, toOpEnvelope, validateOpsDocument };
797
+ //#region src/ops/rangeReplacement.d.ts
798
+ /**
799
+ * A range replacement fragment: newly identified paragraphs before its last
800
+ * paragraph, and the inline tail inserted into the retained original paragraph.
801
+ * Each new paragraph's own fields apply to it, including when it takes the
802
+ * source prefix. The last fragment keeps the original survivor's identity.
803
+ * Closed inline slices are required; review and content-control ids in the
804
+ * fragment, and section-bearing paragraphs, are unsupported.
805
+ */
806
+ type PlanTrackedReplaceOptions = PlanTrackedDeletionOptions & {
807
+ replacement: {
808
+ paragraphs: readonly Paragraph[];
809
+ tail: InlineSlice;
810
+ };
811
+ };
812
+ /**
813
+ * Plan a tracked replacement of a same-list range: the range's tracked
814
+ * deletion followed by the replacement fragment as tracked insertions.
815
+ * All physical revision ids come from one pool for the complete batch.
816
+ */
817
+ declare const planTrackedReplace: (document: Document, options: PlanTrackedReplaceOptions) => Result<DocumentOp[], DocumentOpRefusal>;
818
+ //#endregion
819
+ export { type AppliedDocumentOp, type BlockInsertionPoint, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, type DeleteBlocksOp, type DeleteRangeOp, type DeleteRowOp, type DeleteTableOp, type DocumentOp, type DocumentOpEnvelope, DocumentOpRefusal, type DocumentOpRefusalReason, type DocumentOpType, DocumentOpsContractError, EMPTY_PROPERTY_SETS, type EmptyPropertySet, type FormattingPatch, INHERIT_RUN_PROPS, type InlineSlice, type InsertBlocksOp, type InsertContentOp, type InsertRowOp, type InsertTableOp, type InsertTextOp, type InsertedRunProps, type JoinBlocksOp, type JoinInlineOp, type NewIds, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, type OpStory, PARAGRAPH_MARK_FORMATTING_KEYS, type ParagraphPropsPatch, type ParagraphReviewFields, type PlanTrackedDeletionOptions, type PlanTrackedReplaceOptions, REVISION_DECISIONS, type ReplaceBlocksOp, type ReplaceInlineOp, type ResolveRevisionOp, type RevisionDecision, type RevisionStamp, type RunPropsPatch, SPLIT_HALVES, type SetContainerBlocksOp, type SetParagraphPropsOp, type SetParagraphReviewOp, type SetRunPropsOp, type SetTableRowsOp, type SplitBlockOp, type SplitHalf, type SplitInlineOp, type SplitParagraphFields, type TextPosition, type TouchedBlocks, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, planTrackedDeletion, planTrackedReplace, revisionIdDemand, toOpEnvelope, validateOpsDocument };