@stll/folio-core 0.71.1 → 0.73.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/README.md +14 -8
- package/dist/ai-edits/apply.d.ts +6 -114
- package/dist/ai-edits/apply.js +9 -131
- package/dist/ai-edits/applyTypes.d.ts +85 -0
- package/dist/ai-edits/applyTypes.js +24 -0
- package/dist/ai-edits/clean-text.d.ts +7 -1
- package/dist/ai-edits/clean-text.js +23 -2
- package/dist/ai-edits/finalSectionReview.d.ts +1 -1
- package/dist/ai-edits/headless.d.ts +29 -147
- package/dist/ai-edits/headless.js +213 -1634
- package/dist/ai-edits/index.d.ts +3 -3
- package/dist/ai-edits/index.js +2 -3
- package/dist/ai-edits/pending-suggestions.d.ts +14 -4
- package/dist/ai-edits/pending-suggestions.js +183 -90
- package/dist/ai-edits/result-validation.js +1 -1
- package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
- package/dist/ai-edits/snapshot.js +8 -3
- package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
- package/dist/ai-edits/table-cell-mutations.js +1 -1
- package/dist/ai-edits/table-geometry.d.ts +1 -1
- package/dist/ai-edits/table-geometry.js +1 -1
- package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
- package/dist/ai-edits/table-row-column-mutations.js +1 -1
- package/dist/ai-edits/tableNodes.d.ts +38 -0
- package/dist/ai-edits/tableNodes.js +86 -0
- package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
- package/dist/ai-edits/undefinedReferences.d.ts +7 -0
- package/dist/canonical/batchCommentReferences.js +1 -0
- package/dist/canonical/canonicalInlineProjection.js +1 -1
- package/dist/canonical/canonicalPublicOperations.js +228 -64
- package/dist/canonical/canonicalSession.d.ts +9 -1
- package/dist/canonical/canonicalSession.js +95 -15
- package/dist/compare/compare.d.ts +1 -1
- package/dist/compare/inline-atoms-model.d.ts +1 -1
- package/dist/compare/inline-atoms.d.ts +2 -2
- package/dist/compare/inline-provenance-model.d.ts +1 -1
- package/dist/compare/inline-provenance.d.ts +2 -2
- package/dist/compat/eigenpal.d.ts +3 -4
- package/dist/compat/eigenpal.js +2 -4
- package/dist/controller/canonicalClipboard.d.ts +13 -3
- package/dist/controller/canonicalClipboard.js +185 -49
- package/dist/controller/canonicalClipboardResources.d.ts +9 -1
- package/dist/controller/canonicalClipboardResources.js +22 -2
- package/dist/controller/canonicalReview.d.ts +1 -1
- package/dist/controller/canonicalReview.js +1 -1
- package/dist/controller/canonicalStructure.js +1 -1
- package/dist/controller/canonicalWatermark.d.ts +10 -0
- package/dist/controller/canonicalWatermark.js +37 -0
- package/dist/controller/canonicalYjsRoom.d.ts +1 -1
- package/dist/controller/headerFooterEditorManager.d.ts +11 -7
- package/dist/controller/headerFooterEditorManager.js +39 -151
- package/dist/controller/hiddenEditorApi.d.ts +1 -1
- package/dist/controller/hiddenEditorManager.d.ts +6 -40
- package/dist/controller/hiddenEditorManager.js +173 -306
- package/dist/controller/noteEditorManager.d.ts +3 -10
- package/dist/controller/noteEditorManager.js +33 -206
- package/dist/document-operations-apply.d.ts +15 -0
- package/dist/document-operations-apply.js +280 -0
- package/dist/document-operations.d.ts +1 -14
- package/dist/document-operations.js +2 -279
- package/dist/docx/modelValidation.js +1 -1
- package/dist/docx/paragraphParser.js +2 -2
- package/dist/docx/paragraphPropertySource.d.ts +1 -1
- package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
- package/dist/docx/reviewResolutionProvenance.js +32 -9
- package/dist/docx/revisionIdNormalization.js +30 -7
- package/dist/docx/rezip.js +1 -1
- package/dist/docx/serializer/borderSerializer.js +1 -1
- package/dist/docx/serializer/commentSerializer.js +1 -1
- package/dist/docx/serializer/documentSerializer.js +1 -1
- package/dist/docx/serializer/paragraphSerializer.js +3 -3
- package/dist/docx/serializer/runSerializer.js +1 -1
- package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
- package/dist/docx/serializer/tableSerializer.js +5 -37
- package/dist/docx/serializer/textFormattingSerializer.js +1 -1
- package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
- package/dist/docx/server/templatePlan/apply.d.ts +15 -0
- package/dist/docx/server/templatePlan/apply.js +600 -0
- package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
- package/dist/docx/server/templatePlan/blocks.js +355 -0
- package/dist/docx/server/templatePlan/builders.d.ts +72 -0
- package/dist/docx/server/templatePlan/builders.js +237 -0
- package/dist/docx/server/templatePlan/emit.d.ts +118 -0
- package/dist/docx/server/templatePlan/emit.js +466 -0
- package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
- package/dist/docx/server/templatePlan/emphasis.js +173 -0
- package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
- package/dist/docx/server/templatePlan/inspect.js +177 -0
- package/dist/docx/server/templatePlan/labels.d.ts +36 -0
- package/dist/docx/server/templatePlan/labels.js +126 -0
- package/dist/docx/server/templatePlan/package.d.ts +34 -0
- package/dist/docx/server/templatePlan/package.js +99 -0
- package/dist/docx/server/templatePlan/plan.d.ts +143 -0
- package/dist/docx/server/templatePlan/plan.js +841 -0
- package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
- package/dist/docx/server/templatePlan/planShape.js +161 -0
- package/dist/docx/server/templatePlan/resources.d.ts +41 -0
- package/dist/docx/server/templatePlan/resources.js +136 -0
- package/dist/docx/server/templatePlan/story.d.ts +128 -0
- package/dist/docx/server/templatePlan/story.js +440 -0
- package/dist/docx/server/templatePlan/types.d.ts +406 -0
- package/dist/docx/server/templatePlan/types.js +28 -0
- package/dist/docx/server/templatePlan/verify.d.ts +40 -0
- package/dist/docx/server/templatePlan/verify.js +968 -0
- package/dist/docx/server/templatePlan/xml.d.ts +69 -0
- package/dist/docx/server/templatePlan/xml.js +119 -0
- package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
- package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
- package/dist/docx/storyBlockReplay.js +1 -1
- package/dist/docx/structuralXmlPatch.js +9 -1
- package/dist/docx/tableGridXml.d.ts +30 -0
- package/dist/docx/tableGridXml.js +54 -0
- package/dist/docx/tableParser.js +7 -0
- package/dist/docx/xmlParser.js +1 -1
- package/dist/index.d.ts +3 -4
- package/dist/index.js +2 -4
- package/dist/internal/paragraphFormattingSerialization.js +1 -1
- package/dist/internal/wholeStoryRevisionResolution.js +1 -1
- package/dist/managers/ContextMenuManager.js +2 -1
- package/dist/managers/DocumentLoaderManager.d.ts +0 -4
- package/dist/managers/DocumentLoaderManager.js +4 -12
- package/dist/managers/editorShortcuts.d.ts +1 -1
- package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
- package/dist/prosemirror/canonicalCommands.d.ts +1 -1
- package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
- package/dist/prosemirror/canonicalTableCommands.js +2 -2
- package/dist/prosemirror/commands/comments.js +3 -3
- package/dist/prosemirror/commands/contentControls.d.ts +1 -1
- package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
- package/dist/prosemirror/commands/formatting.d.ts +1 -1
- package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
- package/dist/prosemirror/commands/sectionBreak.js +1 -1
- package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
- package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
- package/dist/prosemirror/commentRecords.d.ts +1 -1
- package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
- package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
- package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
- package/dist/prosemirror/documentStructureCounts.js +76 -0
- package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
- package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
- package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
- package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
- package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
- package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
- package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
- package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
- package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
- package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
- package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
- package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
- package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
- package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
- package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
- package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
- package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
- package/dist/prosemirror/extensions/types.d.ts +1 -1
- package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
- package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
- package/dist/prosemirror/index.d.ts +1 -1
- package/dist/prosemirror/index.js +1 -1
- package/dist/prosemirror/insertionGaps.d.ts +1 -1
- package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
- package/dist/prosemirror/listNumbering.d.ts +1 -1
- package/dist/prosemirror/lockedControls.d.ts +1 -1
- package/dist/prosemirror/markupViewProjection.d.ts +1 -1
- package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
- package/dist/prosemirror/noteReferenceReview.js +1 -1
- package/dist/prosemirror/numberingAttr.d.ts +1 -2
- package/dist/prosemirror/numberingAttr.js +1 -2
- package/dist/prosemirror/outlineLevelAttr.d.ts +1 -2
- package/dist/prosemirror/outlineLevelAttr.js +1 -2
- package/dist/prosemirror/paraIds.d.ts +46 -0
- package/dist/prosemirror/paraIds.js +152 -0
- package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
- package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
- package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
- package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
- package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
- package/dist/prosemirror/pastedCommentCopies.js +1 -1
- package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
- package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
- package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
- package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
- package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
- package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
- package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
- package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
- package/dist/prosemirror/replacedAnnotations.js +16 -1
- package/dist/prosemirror/revisionCarriers.d.ts +1 -1
- package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
- package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
- package/dist/prosemirror/selectionBounds.d.ts +10 -0
- package/dist/prosemirror/selectionBounds.js +22 -0
- package/dist/prosemirror/storyListNumbering.d.ts +1 -1
- package/dist/prosemirror/tableCellPaste.d.ts +1 -1
- package/dist/prosemirror/tableGridMutation.d.ts +1 -1
- package/dist/prosemirror/textInput.d.ts +1 -1
- package/dist/server.d.ts +7 -5
- package/dist/server.js +6 -4
- package/dist/types/canonicalCapabilities.d.ts +8 -41
- package/dist/types/canonicalCapabilities.js +6 -34
- package/package.json +4 -6
- package/dist/controller/collaborationModules.d.ts +0 -3
- package/dist/controller/collaborationModules.js +0 -14
- package/dist/docx/server/materializeYjsDocx.d.ts +0 -30
- package/dist/docx/server/materializeYjsDocx.js +0 -96
- package/dist/docx/server/migrateYjsAttrSchema.d.ts +0 -53
- package/dist/docx/server/migrateYjsAttrSchema.js +0 -111
- package/dist/prosemirror/plugins/derivedFields.d.ts +0 -8
- package/dist/prosemirror/plugins/derivedFields.js +0 -52
- package/dist/prosemirror/yjsDocumentMetadata.d.ts +0 -89
- package/dist/prosemirror/yjsDocumentMetadata.js +0 -697
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
import { parseFieldInstruction } from "../../fieldParser.js";
|
|
2
|
+
import { computeListRendering } from "../../numberingParser.js";
|
|
3
|
+
import { NAMESPACES } from "../../xmlParser.js";
|
|
4
|
+
import { bookmarkIdsOf, mintRefBookmarkName, refFieldInstruction } from "./builders.js";
|
|
5
|
+
import { emphasisDeviation, emphasisSignature, paragraphBaseline, readDirectEmphasis, withCharacterStyle, withOverride, withSignatureHighlight } from "./emphasis.js";
|
|
6
|
+
import { styleNumbering } from "./labels.js";
|
|
7
|
+
import { PLAN_HIGHLIGHT_COLORS, planShapeIssue } from "./planShape.js";
|
|
8
|
+
import { TemplatePlanError } from "./types.js";
|
|
9
|
+
import { isW, maxOf, wAttr, wChildVal, walkElements } from "./xml.js";
|
|
10
|
+
import { Result } from "better-result";
|
|
11
|
+
// src/docx/server/templatePlan/plan.ts
|
|
12
|
+
/**
|
|
13
|
+
* A template plan checked against its source and template and resolved into
|
|
14
|
+
* what the output must hold: per output paragraph the expected text and
|
|
15
|
+
* emphasis, derived from the source blocks alone. The writer emits it and the
|
|
16
|
+
* verifier compares the written package against it.
|
|
17
|
+
*/
|
|
18
|
+
const refuse = ({ code, message, blockId }) => new TemplatePlanError({
|
|
19
|
+
code,
|
|
20
|
+
message,
|
|
21
|
+
...blockId === void 0 ? {} : { blockId }
|
|
22
|
+
});
|
|
23
|
+
/** Where a label may end: at white space or a line break. */
|
|
24
|
+
const LABEL_END = /^[ \t\u00A0\n]$/u;
|
|
25
|
+
const MAX_LABEL_LENGTH = 40;
|
|
26
|
+
const ROMAN_NUMERAL = /^(?=.)M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})$/iu;
|
|
27
|
+
const LABEL_WORD = /^(?:\p{L}[\p{L}\p{M}]*\.?|§{1,2}|№|#)$/u;
|
|
28
|
+
const LABEL_DESIGNATOR = /^[([]?(?<core>\d+(?:[.\-\u2013]\d+)*[a-z]?|\p{L}+)[)\]]?[.:)]*$/u;
|
|
29
|
+
const LABEL_BULLET = /^[-\u2013\u2014\u2022\u00B7\u25AA\u25E6*]$/u;
|
|
30
|
+
const MAX_LABEL_WORDS = 3;
|
|
31
|
+
/**
|
|
32
|
+
* Whether `label` reads as a manual list label: up to three leading words
|
|
33
|
+
* ("Article", "§", "Annex No.") and one designator, a number, a roman numeral
|
|
34
|
+
* or a letter with its brackets and punctuation; or a single bullet. This is
|
|
35
|
+
* the only text a plan may have removed.
|
|
36
|
+
*/
|
|
37
|
+
const isManualLabel = (label) => {
|
|
38
|
+
if (label === "" || label.length > MAX_LABEL_LENGTH) return false;
|
|
39
|
+
if (LABEL_BULLET.test(label)) return true;
|
|
40
|
+
const tokens = label.split(/[ \u00A0]/u);
|
|
41
|
+
const designator = tokens.at(-1) ?? "";
|
|
42
|
+
const words = tokens.slice(0, -1);
|
|
43
|
+
const core = LABEL_DESIGNATOR.exec(designator)?.groups?.["core"];
|
|
44
|
+
return core !== void 0 && words.length <= MAX_LABEL_WORDS && words.every((word) => LABEL_WORD.test(word)) && (/^\d/u.test(core) || core.length === 1 || ROMAN_NUMERAL.test(core));
|
|
45
|
+
};
|
|
46
|
+
const NOTES_OF_REFERENCE = {
|
|
47
|
+
footnoteReference: "footnotes",
|
|
48
|
+
endnoteReference: "endnotes"
|
|
49
|
+
};
|
|
50
|
+
const LABEL_SPACE = /^[ \t ]+/u;
|
|
51
|
+
const LEADING_SPACE = /^[ \t ]*/u;
|
|
52
|
+
/** Whether a block holds no text and no object. */
|
|
53
|
+
const isBlankBlock = ({ block }) => block.text.trim() === "" && block.inlineObjects === 0;
|
|
54
|
+
/** Whether a block, or a paragraph inside it, renders a list label. */
|
|
55
|
+
const showsLabel = ({ block }) => block.label !== null || (block.nested ?? []).some(({ label }) => label !== null);
|
|
56
|
+
const HYPERLINK_FIELD = "HYPERLINK";
|
|
57
|
+
const LOCATION_SWITCH = "l";
|
|
58
|
+
/** The link a HYPERLINK field makes: its address and the place in it, if any. */
|
|
59
|
+
const hyperlinkFieldLink = ({ instruction, kind }) => {
|
|
60
|
+
if (kind !== HYPERLINK_FIELD) return null;
|
|
61
|
+
const { argument, switches } = parseFieldInstruction(instruction);
|
|
62
|
+
if (argument === void 0 || argument === "") return null;
|
|
63
|
+
return {
|
|
64
|
+
kind: "url",
|
|
65
|
+
url: argument,
|
|
66
|
+
anchor: switches.find(({ switch: name }) => name.toLowerCase() === LOCATION_SWITCH)?.value ?? null
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
const NOTE_REFERENCE_KINDS = /* @__PURE__ */ new Set(["footnoteReference", "endnoteReference"]);
|
|
70
|
+
/** What a stripped label may consist of. */
|
|
71
|
+
const STRIPPABLE_KINDS = /* @__PURE__ */ new Set(["text", "tab"]);
|
|
72
|
+
/**
|
|
73
|
+
* Character styles that only give a link its look. The template supplies
|
|
74
|
+
* that look; any other character style inside a link is emphasis.
|
|
75
|
+
*/
|
|
76
|
+
const LINK_STYLE_NAMES = /* @__PURE__ */ new Set([
|
|
77
|
+
"hyperlink",
|
|
78
|
+
"followedhyperlink",
|
|
79
|
+
"internet link",
|
|
80
|
+
"visited internet link"
|
|
81
|
+
]);
|
|
82
|
+
/** The pieces of one source paragraph, each with the emphasis it states. */
|
|
83
|
+
const paragraphPieces = ({ read, context: { styles, defaultStyleId, defaultEmphasis }, origin, fields }) => {
|
|
84
|
+
const baseline = paragraphBaseline(styles.get(read.styleId ?? defaultStyleId ?? ""), defaultEmphasis);
|
|
85
|
+
return read.atoms.map((atom) => {
|
|
86
|
+
const fieldLink = atom.fields.map((index) => fields[index]).map((field) => field === void 0 ? null : hyperlinkFieldLink(field)).find((link) => link !== null);
|
|
87
|
+
const link = atom.link ?? fieldLink ?? null;
|
|
88
|
+
let signature = "";
|
|
89
|
+
if (!NOTE_REFERENCE_KINDS.has(atom.kind)) {
|
|
90
|
+
const characterStyle = styles.get(wChildVal(atom.runProperties, "rStyle") ?? "");
|
|
91
|
+
const isLinkLook = link !== null && LINK_STYLE_NAMES.has(characterStyle?.name?.toLowerCase() ?? "");
|
|
92
|
+
signature = emphasisSignature(emphasisDeviation(withOverride(isLinkLook ? baseline : withCharacterStyle(baseline, characterStyle), readDirectEmphasis(atom.runProperties)), baseline));
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
kind: atom.kind,
|
|
96
|
+
text: atom.text,
|
|
97
|
+
signature,
|
|
98
|
+
link,
|
|
99
|
+
atom,
|
|
100
|
+
origin
|
|
101
|
+
};
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
const isHighSurrogate = (unit) => unit >= 55296 && unit <= 56319;
|
|
105
|
+
const isLowSurrogate = (unit) => unit >= 56320 && unit <= 57343;
|
|
106
|
+
/** Whether `offset` falls between the two units of one character. */
|
|
107
|
+
const splitsCharacter = (text, offset) => offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset));
|
|
108
|
+
/**
|
|
109
|
+
* Split text pieces at the offsets in `cuts`. A cut inside a character, or
|
|
110
|
+
* inside a piece that is not text, is not made; the caller finds it missing
|
|
111
|
+
* among the boundaries.
|
|
112
|
+
*/
|
|
113
|
+
const splitPieces = (pieces, cuts) => {
|
|
114
|
+
const out = [];
|
|
115
|
+
let offset = 0;
|
|
116
|
+
for (const piece of pieces) {
|
|
117
|
+
const start = offset;
|
|
118
|
+
const end = start + piece.text.length;
|
|
119
|
+
offset = end;
|
|
120
|
+
const inside = piece.kind === "text" ? cuts.filter((cut) => cut > start && cut < end && !splitsCharacter(piece.text, cut - start)) : [];
|
|
121
|
+
if (inside.length === 0) {
|
|
122
|
+
out.push({
|
|
123
|
+
piece,
|
|
124
|
+
start,
|
|
125
|
+
end
|
|
126
|
+
});
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
let cursor = start;
|
|
130
|
+
for (const cut of [...new Set(inside)].toSorted((a, b) => a - b)) {
|
|
131
|
+
out.push({
|
|
132
|
+
piece: {
|
|
133
|
+
...piece,
|
|
134
|
+
text: piece.text.slice(cursor - start, cut - start)
|
|
135
|
+
},
|
|
136
|
+
start: cursor,
|
|
137
|
+
end: cut
|
|
138
|
+
});
|
|
139
|
+
cursor = cut;
|
|
140
|
+
}
|
|
141
|
+
out.push({
|
|
142
|
+
piece: {
|
|
143
|
+
...piece,
|
|
144
|
+
text: piece.text.slice(cursor - start)
|
|
145
|
+
},
|
|
146
|
+
start: cursor,
|
|
147
|
+
end
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
};
|
|
152
|
+
const isSpanWithin = ({ start, end }, from, length) => Number.isInteger(start) && Number.isInteger(end) && start >= from && start < end && end <= length;
|
|
153
|
+
const spansOverlap = (spans) => {
|
|
154
|
+
const ordered = spans.toSorted((a, b) => a.start - b.start);
|
|
155
|
+
return ordered.some((span, index) => {
|
|
156
|
+
const previous = ordered[index - 1];
|
|
157
|
+
return previous !== void 0 && span.start < previous.end;
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
const partSegments = ({ block, pieces, strippedLength, references, highlights }) => {
|
|
161
|
+
const blockId = block.block.id;
|
|
162
|
+
const length = block.block.text.length;
|
|
163
|
+
const badReference = (message) => Result.err(refuse({
|
|
164
|
+
code: "reference-span-invalid",
|
|
165
|
+
message,
|
|
166
|
+
blockId
|
|
167
|
+
}));
|
|
168
|
+
const badHighlight = (message) => Result.err(refuse({
|
|
169
|
+
code: "highlight-span-invalid",
|
|
170
|
+
message,
|
|
171
|
+
blockId
|
|
172
|
+
}));
|
|
173
|
+
for (const reference of references) if (!isSpanWithin(reference, strippedLength, length)) return badReference(`Reference span ${reference.start}-${reference.end} lies outside block ${blockId}.`);
|
|
174
|
+
for (const highlight of highlights) if (!isSpanWithin(highlight, strippedLength, length) || !PLAN_HIGHLIGHT_COLORS.has(highlight.color)) return badHighlight(`Highlight ${highlight.start}-${highlight.end} (${highlight.color}) does not fit block ${blockId}.`);
|
|
175
|
+
if (spansOverlap(references)) return badReference(`Reference spans overlap in block ${blockId}.`);
|
|
176
|
+
if (spansOverlap(highlights)) return badHighlight(`Highlight spans overlap in block ${blockId}.`);
|
|
177
|
+
const ordered = references.toSorted((a, b) => a.start - b.start);
|
|
178
|
+
const split = splitPieces(pieces, [
|
|
179
|
+
strippedLength,
|
|
180
|
+
...references.flatMap(({ start, end }) => [start, end]),
|
|
181
|
+
...highlights.flatMap(({ start, end }) => [start, end])
|
|
182
|
+
]);
|
|
183
|
+
const boundaries = /* @__PURE__ */ new Set([0, ...split.map(({ end }) => end)]);
|
|
184
|
+
if (!boundaries.has(strippedLength)) return Result.err(refuse({
|
|
185
|
+
code: "strip-label-mismatch",
|
|
186
|
+
message: `The label to strip from block ${blockId} ends inside a character or mark.`,
|
|
187
|
+
blockId
|
|
188
|
+
}));
|
|
189
|
+
for (const { start, end } of references) if (!boundaries.has(start) || !boundaries.has(end)) return badReference(`Reference span ${start}-${end} in block ${blockId} cuts a character or mark.`);
|
|
190
|
+
for (const { start, end } of highlights) if (!boundaries.has(start) || !boundaries.has(end)) return badHighlight(`Highlight ${start}-${end} in block ${blockId} cuts a character or mark.`);
|
|
191
|
+
const positioned = [];
|
|
192
|
+
for (const entry of split) {
|
|
193
|
+
const empty = entry.start === entry.end;
|
|
194
|
+
if (entry.end <= strippedLength && !empty) {
|
|
195
|
+
if (!STRIPPABLE_KINDS.has(entry.piece.kind)) return Result.err(refuse({
|
|
196
|
+
code: "strip-label-mismatch",
|
|
197
|
+
message: `The label to strip from block ${blockId} covers more than text.`,
|
|
198
|
+
blockId
|
|
199
|
+
}));
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const highlight = highlights.find(({ start, end }) => entry.start >= start && entry.end <= end && !empty);
|
|
203
|
+
if (highlight !== void 0 && !NOTE_REFERENCE_KINDS.has(entry.piece.kind)) entry.piece = {
|
|
204
|
+
...entry.piece,
|
|
205
|
+
signature: withSignatureHighlight(entry.piece.signature, highlight.color)
|
|
206
|
+
};
|
|
207
|
+
positioned.push(entry);
|
|
208
|
+
}
|
|
209
|
+
const segments = [];
|
|
210
|
+
let open;
|
|
211
|
+
const close = () => {
|
|
212
|
+
if (open === void 0) return Result.ok(void 0);
|
|
213
|
+
const replacedText = open.pieces.map(({ text }) => text).join("");
|
|
214
|
+
const first = open.pieces.at(0);
|
|
215
|
+
const { reference } = open;
|
|
216
|
+
if (first === void 0 || replacedText === reference.expectedText) segments.push({
|
|
217
|
+
kind: "reference",
|
|
218
|
+
reference,
|
|
219
|
+
replacedText,
|
|
220
|
+
pieces: open.pieces.map((piece) => ({
|
|
221
|
+
...piece,
|
|
222
|
+
link: null
|
|
223
|
+
}))
|
|
224
|
+
});
|
|
225
|
+
else if (open.pieces.some(({ signature }) => signature !== first.signature)) return badReference(`Reference span ${reference.start}-${reference.end} in block ${blockId} changes text that is emphasised in part.`);
|
|
226
|
+
else segments.push({
|
|
227
|
+
kind: "reference",
|
|
228
|
+
reference,
|
|
229
|
+
replacedText,
|
|
230
|
+
pieces: [{
|
|
231
|
+
kind: "text",
|
|
232
|
+
text: reference.expectedText,
|
|
233
|
+
signature: first.signature,
|
|
234
|
+
link: null,
|
|
235
|
+
atom: null,
|
|
236
|
+
origin: first.origin
|
|
237
|
+
}]
|
|
238
|
+
});
|
|
239
|
+
open = void 0;
|
|
240
|
+
return Result.ok(void 0);
|
|
241
|
+
};
|
|
242
|
+
for (const { piece, start, end } of positioned) {
|
|
243
|
+
const empty = start === end;
|
|
244
|
+
const reference = ordered.find((candidate) => empty ? start > candidate.start && start < candidate.end : start >= candidate.start && end <= candidate.end);
|
|
245
|
+
if (reference === void 0) {
|
|
246
|
+
const closed = close();
|
|
247
|
+
if (Result.isError(closed)) return closed;
|
|
248
|
+
segments.push({
|
|
249
|
+
kind: "piece",
|
|
250
|
+
piece
|
|
251
|
+
});
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (piece.kind !== "text") return badReference(`Reference span ${reference.start}-${reference.end} in block ${blockId} covers more than text.`);
|
|
255
|
+
if (empty) continue;
|
|
256
|
+
if (open !== void 0 && open.reference !== reference) {
|
|
257
|
+
const closed = close();
|
|
258
|
+
if (Result.isError(closed)) return closed;
|
|
259
|
+
}
|
|
260
|
+
open ??= {
|
|
261
|
+
reference,
|
|
262
|
+
pieces: []
|
|
263
|
+
};
|
|
264
|
+
open.pieces.push(piece);
|
|
265
|
+
}
|
|
266
|
+
const closed = close();
|
|
267
|
+
return Result.isError(closed) ? closed : Result.ok(segments);
|
|
268
|
+
};
|
|
269
|
+
const SEPARATOR_PIECES = {
|
|
270
|
+
lineBreak: {
|
|
271
|
+
kind: "lineBreak",
|
|
272
|
+
text: "\n",
|
|
273
|
+
signature: "",
|
|
274
|
+
link: null,
|
|
275
|
+
atom: null,
|
|
276
|
+
origin: "document"
|
|
277
|
+
},
|
|
278
|
+
space: {
|
|
279
|
+
kind: "text",
|
|
280
|
+
text: " ",
|
|
281
|
+
signature: "",
|
|
282
|
+
link: null,
|
|
283
|
+
atom: null,
|
|
284
|
+
origin: "document"
|
|
285
|
+
},
|
|
286
|
+
none: null
|
|
287
|
+
};
|
|
288
|
+
/** The pieces of a segment list in order, reference results included. */
|
|
289
|
+
const segmentPieces = (segments) => segments.flatMap((segment) => segment.kind === "piece" ? [segment.piece] : segment.pieces);
|
|
290
|
+
/** The expected text and per-unit signatures of a piece list. */
|
|
291
|
+
const piecesContent = (pieces) => {
|
|
292
|
+
const signatures = [];
|
|
293
|
+
let text = "";
|
|
294
|
+
for (const piece of pieces) {
|
|
295
|
+
text += piece.text;
|
|
296
|
+
for (let unit = 0; unit < piece.text.length; unit += 1) signatures.push(piece.signature);
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
text,
|
|
300
|
+
signatures
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
const SHA256 = /^[0-9a-f]{64}$/u;
|
|
304
|
+
const TRANSITIONAL_WORDPROCESSINGML = NAMESPACES.w;
|
|
305
|
+
const groupByBlock = (entries) => {
|
|
306
|
+
const groups = /* @__PURE__ */ new Map();
|
|
307
|
+
for (const entry of entries) {
|
|
308
|
+
const group = groups.get(entry.blockId);
|
|
309
|
+
if (group === void 0) groups.set(entry.blockId, [entry]);
|
|
310
|
+
else group.push(entry);
|
|
311
|
+
}
|
|
312
|
+
return groups;
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* Check `plan` against the analysed source and template and resolve it.
|
|
316
|
+
* Every refusal the engine documents is decided here, before anything is written.
|
|
317
|
+
*/
|
|
318
|
+
const resolvePlan = (source, template, plan) => {
|
|
319
|
+
const invalid = (message) => Result.err(refuse({
|
|
320
|
+
code: "plan-invalid",
|
|
321
|
+
message
|
|
322
|
+
}));
|
|
323
|
+
const unsupported = (message, blockId) => Result.err(refuse({
|
|
324
|
+
code: "unsupported-content",
|
|
325
|
+
message,
|
|
326
|
+
...blockId === void 0 ? {} : { blockId }
|
|
327
|
+
}));
|
|
328
|
+
const shapeIssue = planShapeIssue(plan);
|
|
329
|
+
if (shapeIssue !== null) return invalid(shapeIssue);
|
|
330
|
+
if (!SHA256.test(plan.sourceSha256) || plan.sourceSha256 !== source.manifest.sha256) return Result.err(refuse({
|
|
331
|
+
code: "sha-mismatch",
|
|
332
|
+
message: "The plan was made for another source document."
|
|
333
|
+
}));
|
|
334
|
+
if (plan.templateSha256 !== template.manifest.sha256) return Result.err(refuse({
|
|
335
|
+
code: "sha-mismatch",
|
|
336
|
+
message: "The plan was made for another template."
|
|
337
|
+
}));
|
|
338
|
+
for (const [name, analyzed] of [["source", source], ["template", template]]) if (analyzed.document.root.namespaceUri !== TRANSITIONAL_WORDPROCESSINGML) return unsupported(`The ${name} is not a Transitional WordprocessingML package.`);
|
|
339
|
+
if (source.manifest.trackedChanges > 0) return Result.err(refuse({
|
|
340
|
+
code: "tracked-changes",
|
|
341
|
+
message: `The source holds ${source.manifest.trackedChanges} tracked change(s); resolve them first.`
|
|
342
|
+
}));
|
|
343
|
+
for (const state of [
|
|
344
|
+
source.story.state,
|
|
345
|
+
source.footnotes.state,
|
|
346
|
+
source.endnotes.state
|
|
347
|
+
]) if (state.open.length > 0 || state.strayFieldEnds > 0) return unsupported("The source holds complex field marks that do not pair up.");
|
|
348
|
+
const unreadBlock = source.story.unreadBlocks.at(0);
|
|
349
|
+
if (unreadBlock !== void 0) return unsupported(`The source holds block-level ${unreadBlock} content that cannot be moved onto a template.`);
|
|
350
|
+
const references = plan.references ?? [];
|
|
351
|
+
const highlights = plan.highlights ?? [];
|
|
352
|
+
const freezeKinds = plan.fields?.freezeKinds ?? [];
|
|
353
|
+
const patches = plan.numberingPatches ?? [];
|
|
354
|
+
const templateNumbering = template.numbering;
|
|
355
|
+
const usedNumIds = (templateNumbering?.definitions.nums ?? []).map(({ numId }) => numId);
|
|
356
|
+
let nextNumId = maxOf(usedNumIds, 0) + 1;
|
|
357
|
+
const mints = /* @__PURE__ */ new Map();
|
|
358
|
+
const paragraphStyle = (styleId, blockId) => {
|
|
359
|
+
if (styleId === void 0) return Result.ok(null);
|
|
360
|
+
return template.styles.get(styleId)?.type === "paragraph" ? Result.ok(styleId) : Result.err(refuse({
|
|
361
|
+
code: "style-unknown",
|
|
362
|
+
message: `The template has no paragraph style ${styleId}.`,
|
|
363
|
+
blockId
|
|
364
|
+
}));
|
|
365
|
+
};
|
|
366
|
+
const resolveNumbering = ({ numbering, styleId, blockId, ordinal }) => {
|
|
367
|
+
if (numbering === void 0) return Result.ok({ kind: "style" });
|
|
368
|
+
if (numbering === null) return Result.ok({ kind: "none" });
|
|
369
|
+
const unknown = (message) => Result.err(refuse({
|
|
370
|
+
code: "numbering-unknown",
|
|
371
|
+
message,
|
|
372
|
+
blockId
|
|
373
|
+
}));
|
|
374
|
+
const { numId, ilvl, restartFrom, baseNumId, group } = numbering;
|
|
375
|
+
if (templateNumbering === null) return unknown("The template has no numbering definitions.");
|
|
376
|
+
if (!(numId === "new" || restartFrom !== void 0 || group !== void 0)) return computeListRendering({
|
|
377
|
+
numId,
|
|
378
|
+
ilvl
|
|
379
|
+
}, templateNumbering) === null ? unknown(`The template has no list ${numId} with level ${ilvl}.`) : Result.ok({
|
|
380
|
+
kind: "direct",
|
|
381
|
+
numId,
|
|
382
|
+
ilvl
|
|
383
|
+
});
|
|
384
|
+
let base = numId === "new" ? baseNumId : numId;
|
|
385
|
+
if (base === void 0) {
|
|
386
|
+
const bound = styleNumbering(styleId ?? template.defaultStyleId, template.styles, templateNumbering);
|
|
387
|
+
base = bound?.kind === "reference" ? bound.numId : void 0;
|
|
388
|
+
}
|
|
389
|
+
const abstractNumId = base === void 0 ? null : templateNumbering.getAbstractNumId(base);
|
|
390
|
+
const baseLevel = base === void 0 ? null : computeListRendering({
|
|
391
|
+
numId: base,
|
|
392
|
+
ilvl
|
|
393
|
+
}, templateNumbering);
|
|
394
|
+
if (base === void 0 || abstractNumId === null || baseLevel === null) return unknown(`Block ${blockId} starts a list the template does not define.`);
|
|
395
|
+
const key = group === void 0 ? `item:${ordinal}` : `group:${group}`;
|
|
396
|
+
let mint = mints.get(key);
|
|
397
|
+
if (mint === void 0) {
|
|
398
|
+
const patchedStart = patches.find((patch) => patch.abstractNumId === abstractNumId && patch.ilvl === ilvl)?.start;
|
|
399
|
+
mint = {
|
|
400
|
+
key,
|
|
401
|
+
numId: nextNumId,
|
|
402
|
+
baseNumId: base,
|
|
403
|
+
abstractNumId,
|
|
404
|
+
starts: /* @__PURE__ */ new Map([[ilvl, restartFrom ?? patchedStart ?? baseLevel.levelStarts?.at(ilvl) ?? 1]])
|
|
405
|
+
};
|
|
406
|
+
nextNumId += 1;
|
|
407
|
+
mints.set(key, mint);
|
|
408
|
+
return Result.ok({
|
|
409
|
+
kind: "direct",
|
|
410
|
+
numId: mint.numId,
|
|
411
|
+
ilvl
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
if (mint.baseNumId !== base) return invalid(`List group ${key} spans two lists.`);
|
|
415
|
+
if (restartFrom !== void 0) {
|
|
416
|
+
const known = mint.starts.get(ilvl);
|
|
417
|
+
if (known !== void 0 && known !== restartFrom) return invalid(`List group ${key} restarts level ${ilvl} from two different numbers.`);
|
|
418
|
+
mint.starts.set(ilvl, restartFrom);
|
|
419
|
+
}
|
|
420
|
+
return Result.ok({
|
|
421
|
+
kind: "direct",
|
|
422
|
+
numId: mint.numId,
|
|
423
|
+
ilvl
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
const referencesByBlock = groupByBlock(references);
|
|
427
|
+
const highlightsByBlock = groupByBlock(highlights);
|
|
428
|
+
const byBlockId = /* @__PURE__ */ new Map();
|
|
429
|
+
const placed = /* @__PURE__ */ new Set();
|
|
430
|
+
const place = (block) => {
|
|
431
|
+
const { id } = block.block;
|
|
432
|
+
if (placed.has(id)) return Result.err(refuse({
|
|
433
|
+
code: "block-placed-twice",
|
|
434
|
+
message: `Source block ${id} is placed more than once.`,
|
|
435
|
+
blockId: id
|
|
436
|
+
}));
|
|
437
|
+
placed.add(id);
|
|
438
|
+
return Result.ok(void 0);
|
|
439
|
+
};
|
|
440
|
+
const resolveParagraph = ({ parts, separators, styleId, numbering, placement, ordinal }) => {
|
|
441
|
+
const first = parts.at(0);
|
|
442
|
+
if (first === void 0) return invalid("A plan item names no source block.");
|
|
443
|
+
const firstId = first.block.block.id;
|
|
444
|
+
const style = paragraphStyle(styleId, firstId);
|
|
445
|
+
if (Result.isError(style)) return style;
|
|
446
|
+
const resolvedNumbering = resolveNumbering({
|
|
447
|
+
numbering,
|
|
448
|
+
styleId: style.value,
|
|
449
|
+
blockId: firstId,
|
|
450
|
+
ordinal
|
|
451
|
+
});
|
|
452
|
+
if (Result.isError(resolvedNumbering)) return resolvedNumbering;
|
|
453
|
+
const segments = [];
|
|
454
|
+
const resolvedParts = [];
|
|
455
|
+
for (const [index, { block, stripLabel }] of parts.entries()) {
|
|
456
|
+
const { id, text } = block.block;
|
|
457
|
+
if (block.read === null) return invalid(`Block ${id} is a table and cannot be joined or slotted.`);
|
|
458
|
+
const placedOnce = place(block);
|
|
459
|
+
if (Result.isError(placedOnce)) return placedOnce;
|
|
460
|
+
const unread = block.read.unsupported.at(0);
|
|
461
|
+
if (unread !== void 0) return unsupported(`Block ${id} holds ${unread} content that cannot be moved onto a template.`, id);
|
|
462
|
+
let strippedPrefix = "";
|
|
463
|
+
if (stripLabel !== void 0) {
|
|
464
|
+
const lead = LEADING_SPACE.exec(text)?.[0] ?? "";
|
|
465
|
+
const labelEnd = lead.length + stripLabel.length;
|
|
466
|
+
if (!isManualLabel(stripLabel) || !text.startsWith(stripLabel, lead.length) || !(labelEnd === text.length || LABEL_END.test(text.charAt(labelEnd)))) return Result.err(refuse({
|
|
467
|
+
code: "strip-label-mismatch",
|
|
468
|
+
message: `Block ${id} does not start with the label to strip.`,
|
|
469
|
+
blockId: id
|
|
470
|
+
}));
|
|
471
|
+
strippedPrefix = text.slice(0, labelEnd + (LABEL_SPACE.exec(text.slice(labelEnd))?.[0].length ?? 0));
|
|
472
|
+
}
|
|
473
|
+
const part = partSegments({
|
|
474
|
+
block,
|
|
475
|
+
pieces: paragraphPieces({
|
|
476
|
+
read: block.read,
|
|
477
|
+
context: source,
|
|
478
|
+
origin: "document",
|
|
479
|
+
fields: source.story.state.fields
|
|
480
|
+
}),
|
|
481
|
+
strippedLength: strippedPrefix.length,
|
|
482
|
+
references: referencesByBlock.get(id) ?? [],
|
|
483
|
+
highlights: highlightsByBlock.get(id) ?? []
|
|
484
|
+
});
|
|
485
|
+
if (Result.isError(part)) return part;
|
|
486
|
+
if (index > 0) {
|
|
487
|
+
const separator = SEPARATOR_PIECES[separators[index - 1] ?? "none"];
|
|
488
|
+
if (separator !== null) segments.push({
|
|
489
|
+
kind: "piece",
|
|
490
|
+
piece: separator
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
segments.push(...part.value);
|
|
494
|
+
resolvedParts.push({
|
|
495
|
+
block,
|
|
496
|
+
strippedPrefix
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
const pieces = segmentPieces(segments);
|
|
500
|
+
for (const piece of pieces) {
|
|
501
|
+
const notes = NOTES_OF_REFERENCE[piece.kind];
|
|
502
|
+
if (notes === void 0) continue;
|
|
503
|
+
const noteId = wAttr(piece.atom?.element, "id") ?? "";
|
|
504
|
+
const note = source[notes].byId.get(noteId);
|
|
505
|
+
if (note === void 0) return unsupported(`Block ${firstId} refers to note ${noteId}, which the source does not hold.`, firstId);
|
|
506
|
+
const unread = note.paragraphs.flatMap((read) => read.unsupported).at(0) ?? (note.hasOtherBlocks ? "table" : void 0);
|
|
507
|
+
if (unread !== void 0) return unsupported(`Note ${noteId} holds ${unread} content that cannot be moved onto a template.`, firstId);
|
|
508
|
+
}
|
|
509
|
+
const paragraph = {
|
|
510
|
+
parts: resolvedParts,
|
|
511
|
+
styleId: style.value,
|
|
512
|
+
numbering: resolvedNumbering.value,
|
|
513
|
+
segments,
|
|
514
|
+
...piecesContent(pieces),
|
|
515
|
+
inlineObjects: pieces.filter(({ kind }) => kind === "object").length,
|
|
516
|
+
placement
|
|
517
|
+
};
|
|
518
|
+
for (const { block } of resolvedParts) byBlockId.set(block.block.id, paragraph);
|
|
519
|
+
return Result.ok(paragraph);
|
|
520
|
+
};
|
|
521
|
+
const sourceTopLevel = (id) => {
|
|
522
|
+
const block = source.story.byId.get(id);
|
|
523
|
+
if (block === void 0 || block.parentId !== null) return Result.err(refuse({
|
|
524
|
+
code: "unknown-block",
|
|
525
|
+
message: block === void 0 ? `The source has no block ${id}.` : `Block ${id} sits in a table and is placed with it.`,
|
|
526
|
+
blockId: id
|
|
527
|
+
}));
|
|
528
|
+
return Result.ok(block);
|
|
529
|
+
};
|
|
530
|
+
const resolveTable = (block, item, tableOrdinal) => {
|
|
531
|
+
const { id } = block.block;
|
|
532
|
+
if (item.mergeNext !== void 0 || item.stripLabel !== void 0 || item.numbering !== void 0) return invalid(`Table ${id} takes a style and nested placements only.`);
|
|
533
|
+
if (item.styleId !== void 0 && template.styles.get(item.styleId)?.type !== "table") return Result.err(refuse({
|
|
534
|
+
code: "style-unknown",
|
|
535
|
+
message: `The template has no table style ${item.styleId}.`,
|
|
536
|
+
blockId: id
|
|
537
|
+
}));
|
|
538
|
+
const placedOnce = place(block);
|
|
539
|
+
if (Result.isError(placedOnce)) return placedOnce;
|
|
540
|
+
const overrides = new Map((item.nested ?? []).map((nested) => [nested.blockId, nested]));
|
|
541
|
+
const cells = /* @__PURE__ */ new Map();
|
|
542
|
+
const nestedBlocks = source.story.order.filter((candidate) => candidate.topLevelId === id && candidate !== block);
|
|
543
|
+
for (const nested of nestedBlocks) {
|
|
544
|
+
if (nested.read === null) {
|
|
545
|
+
const placedTable = place(nested);
|
|
546
|
+
if (Result.isError(placedTable)) return placedTable;
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
const override = overrides.get(nested.block.id);
|
|
550
|
+
overrides.delete(nested.block.id);
|
|
551
|
+
const paragraph = resolveParagraph({
|
|
552
|
+
parts: [{
|
|
553
|
+
block: nested,
|
|
554
|
+
stripLabel: override?.stripLabel
|
|
555
|
+
}],
|
|
556
|
+
separators: [],
|
|
557
|
+
styleId: override?.styleId ?? item.cellStyleId,
|
|
558
|
+
numbering: override?.numbering,
|
|
559
|
+
placement: "nested",
|
|
560
|
+
ordinal: tableOrdinal * 1e6 + nested.block.index
|
|
561
|
+
});
|
|
562
|
+
if (Result.isError(paragraph)) return paragraph;
|
|
563
|
+
cells.set(nested.element, paragraph.value);
|
|
564
|
+
}
|
|
565
|
+
const stray = [...overrides.keys()].at(0);
|
|
566
|
+
if (stray !== void 0) return Result.err(refuse({
|
|
567
|
+
code: "unknown-block",
|
|
568
|
+
message: `Table ${id} holds no paragraph ${stray}.`,
|
|
569
|
+
blockId: stray
|
|
570
|
+
}));
|
|
571
|
+
return Result.ok({
|
|
572
|
+
kind: "table",
|
|
573
|
+
block,
|
|
574
|
+
styleId: item.styleId ?? null,
|
|
575
|
+
cells
|
|
576
|
+
});
|
|
577
|
+
};
|
|
578
|
+
const items = [];
|
|
579
|
+
const nestedSlots = [];
|
|
580
|
+
const keptTemplateBlocks = [];
|
|
581
|
+
const keptTemplateIds = /* @__PURE__ */ new Set();
|
|
582
|
+
const slottedTemplateIds = /* @__PURE__ */ new Set();
|
|
583
|
+
const pendingNestedSlots = [];
|
|
584
|
+
let ordinal = 0;
|
|
585
|
+
for (let index = 0; index < plan.body.length; index += 1) {
|
|
586
|
+
const item = plan.body[index];
|
|
587
|
+
ordinal += 1;
|
|
588
|
+
if (item === void 0) continue;
|
|
589
|
+
switch (item.kind) {
|
|
590
|
+
case "template":
|
|
591
|
+
for (const id of item.templateBlockIds) {
|
|
592
|
+
const block = template.story.byId.get(id);
|
|
593
|
+
if (block === void 0 || block.parentId !== null) return Result.err(refuse({
|
|
594
|
+
code: "unknown-block",
|
|
595
|
+
message: `The template has no top-level block ${id}.`,
|
|
596
|
+
blockId: id
|
|
597
|
+
}));
|
|
598
|
+
if (keptTemplateIds.has(id) || slottedTemplateIds.has(id)) return Result.err(refuse({
|
|
599
|
+
code: "block-placed-twice",
|
|
600
|
+
message: `Template block ${id} is placed more than once.`,
|
|
601
|
+
blockId: id
|
|
602
|
+
}));
|
|
603
|
+
keptTemplateIds.add(id);
|
|
604
|
+
keptTemplateBlocks.push(block);
|
|
605
|
+
items.push({
|
|
606
|
+
kind: "template",
|
|
607
|
+
block
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
break;
|
|
611
|
+
case "source": {
|
|
612
|
+
const block = sourceTopLevel(item.blockId);
|
|
613
|
+
if (Result.isError(block)) return block;
|
|
614
|
+
if (block.value.block.hash !== item.hash) return Result.err(refuse({
|
|
615
|
+
code: "hash-mismatch",
|
|
616
|
+
message: `Block ${item.blockId} does not have the hash the plan pins.`,
|
|
617
|
+
blockId: item.blockId
|
|
618
|
+
}));
|
|
619
|
+
if (block.value.read === null) {
|
|
620
|
+
const table = resolveTable(block.value, item, ordinal);
|
|
621
|
+
if (Result.isError(table)) return table;
|
|
622
|
+
items.push(table.value);
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
const parts = [{
|
|
626
|
+
block: block.value,
|
|
627
|
+
stripLabel: item.stripLabel
|
|
628
|
+
}];
|
|
629
|
+
const separators = [];
|
|
630
|
+
let merge = item.mergeNext;
|
|
631
|
+
while (merge !== void 0) {
|
|
632
|
+
const next = plan.body[index + 1];
|
|
633
|
+
const nextBlock = next?.kind === "source" ? sourceTopLevel(next.blockId) : void 0;
|
|
634
|
+
if (next?.kind !== "source" || nextBlock === void 0 || Result.isError(nextBlock) || nextBlock.value.read === null) return Result.err(refuse({
|
|
635
|
+
code: "merge-invalid",
|
|
636
|
+
message: `Block ${item.blockId} can only join a source paragraph placed right after it.`,
|
|
637
|
+
blockId: item.blockId
|
|
638
|
+
}));
|
|
639
|
+
if (nextBlock.value.block.hash !== next.hash) return Result.err(refuse({
|
|
640
|
+
code: "hash-mismatch",
|
|
641
|
+
message: `Block ${next.blockId} does not have the hash the plan pins.`,
|
|
642
|
+
blockId: next.blockId
|
|
643
|
+
}));
|
|
644
|
+
if (next.styleId !== void 0 || next.numbering !== void 0 || next.cellStyleId !== void 0 || next.nested !== void 0) return Result.err(refuse({
|
|
645
|
+
code: "merge-invalid",
|
|
646
|
+
message: `Block ${next.blockId} joins the paragraph before it and cannot carry a style or list of its own.`,
|
|
647
|
+
blockId: next.blockId
|
|
648
|
+
}));
|
|
649
|
+
separators.push(merge);
|
|
650
|
+
parts.push({
|
|
651
|
+
block: nextBlock.value,
|
|
652
|
+
stripLabel: next.stripLabel
|
|
653
|
+
});
|
|
654
|
+
merge = next.mergeNext;
|
|
655
|
+
index += 1;
|
|
656
|
+
}
|
|
657
|
+
const paragraph = resolveParagraph({
|
|
658
|
+
parts,
|
|
659
|
+
separators,
|
|
660
|
+
styleId: item.styleId,
|
|
661
|
+
numbering: item.numbering,
|
|
662
|
+
placement: "body",
|
|
663
|
+
ordinal
|
|
664
|
+
});
|
|
665
|
+
if (Result.isError(paragraph)) return paragraph;
|
|
666
|
+
items.push({
|
|
667
|
+
kind: "paragraph",
|
|
668
|
+
paragraph: paragraph.value
|
|
669
|
+
});
|
|
670
|
+
break;
|
|
671
|
+
}
|
|
672
|
+
case "slot": {
|
|
673
|
+
const templateBlock = template.story.byId.get(item.templateBlockId);
|
|
674
|
+
if (templateBlock === void 0 || templateBlock.read === null || !Array.isArray(item.sourceBlockIds)) return Result.err(refuse({
|
|
675
|
+
code: "unknown-block",
|
|
676
|
+
message: `The template has no paragraph ${item.templateBlockId} to fill.`,
|
|
677
|
+
blockId: item.templateBlockId
|
|
678
|
+
}));
|
|
679
|
+
if (keptTemplateIds.has(item.templateBlockId) || slottedTemplateIds.has(item.templateBlockId)) return Result.err(refuse({
|
|
680
|
+
code: "block-placed-twice",
|
|
681
|
+
message: `Template block ${item.templateBlockId} is placed more than once.`,
|
|
682
|
+
blockId: item.templateBlockId
|
|
683
|
+
}));
|
|
684
|
+
slottedTemplateIds.add(item.templateBlockId);
|
|
685
|
+
const parts = [];
|
|
686
|
+
for (const id of item.sourceBlockIds) {
|
|
687
|
+
const block = sourceTopLevel(id);
|
|
688
|
+
if (Result.isError(block)) return block;
|
|
689
|
+
parts.push({
|
|
690
|
+
block: block.value,
|
|
691
|
+
stripLabel: void 0
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
const paragraph = resolveParagraph({
|
|
695
|
+
parts,
|
|
696
|
+
separators: parts.slice(1).map(() => "lineBreak"),
|
|
697
|
+
styleId: void 0,
|
|
698
|
+
numbering: void 0,
|
|
699
|
+
placement: "slot",
|
|
700
|
+
ordinal
|
|
701
|
+
});
|
|
702
|
+
if (Result.isError(paragraph)) return paragraph;
|
|
703
|
+
const slot = {
|
|
704
|
+
templateBlock,
|
|
705
|
+
paragraph: paragraph.value
|
|
706
|
+
};
|
|
707
|
+
if (templateBlock.parentId === null) items.push({
|
|
708
|
+
kind: "slot",
|
|
709
|
+
...slot
|
|
710
|
+
});
|
|
711
|
+
else pendingNestedSlots.push(slot);
|
|
712
|
+
break;
|
|
713
|
+
}
|
|
714
|
+
default: return invalid(`Body item ${index} has an unknown kind.`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
for (const slot of pendingNestedSlots) {
|
|
718
|
+
if (!keptTemplateIds.has(slot.templateBlock.topLevelId)) return Result.err(refuse({
|
|
719
|
+
code: "unknown-block",
|
|
720
|
+
message: `Slot ${slot.templateBlock.block.id} sits in a template table the plan does not keep.`,
|
|
721
|
+
blockId: slot.templateBlock.block.id
|
|
722
|
+
}));
|
|
723
|
+
nestedSlots.push(slot);
|
|
724
|
+
}
|
|
725
|
+
const keptPosition = /* @__PURE__ */ new Map();
|
|
726
|
+
for (const [position, item] of items.entries()) if (item.kind === "template") keptPosition.set(item.block.block.id, position);
|
|
727
|
+
const templateOrder = template.story.topLevel.map(({ block }) => block.id);
|
|
728
|
+
const slots = [...nestedSlots, ...items.flatMap((item) => item.kind === "slot" ? [item] : [])];
|
|
729
|
+
for (const field of template.story.state.fields) {
|
|
730
|
+
const lastOrdinal = field.closed ? field.endParagraphOrdinal : Number.POSITIVE_INFINITY;
|
|
731
|
+
if (lastOrdinal === field.paragraphOrdinal) continue;
|
|
732
|
+
const slotted = slots.find(({ templateBlock }) => {
|
|
733
|
+
const slotOrdinal = templateBlock.read?.ordinal ?? -1;
|
|
734
|
+
return slotOrdinal >= field.paragraphOrdinal && slotOrdinal <= lastOrdinal;
|
|
735
|
+
});
|
|
736
|
+
if (slotted !== void 0) return Result.err(refuse({
|
|
737
|
+
code: "plan-invalid",
|
|
738
|
+
message: `Slot ${slotted.templateBlock.block.id} lies inside a ${field.kind} field that runs over several paragraphs.`,
|
|
739
|
+
blockId: slotted.templateBlock.block.id
|
|
740
|
+
}));
|
|
741
|
+
const from = templateOrder.indexOf(template.story.paragraphs[field.paragraphOrdinal]?.topLevelId ?? "");
|
|
742
|
+
const to = field.closed ? templateOrder.indexOf(template.story.paragraphs[field.endParagraphOrdinal]?.topLevelId ?? "") : templateOrder.length - 1;
|
|
743
|
+
if (from === -1 || to <= from) continue;
|
|
744
|
+
const span = templateOrder.slice(from, to + 1);
|
|
745
|
+
if (!span.some((id) => keptPosition.has(id))) continue;
|
|
746
|
+
const first = keptPosition.get(span.at(0) ?? "");
|
|
747
|
+
if (first === void 0 || span.some((id, offset) => keptPosition.get(id) !== first + offset)) return Result.err(refuse({
|
|
748
|
+
code: "plan-invalid",
|
|
749
|
+
message: `Template blocks ${span.at(0) ?? ""} to ${span.at(-1) ?? ""} hold one ${field.kind} field; keep all of them together and in order, or none.`,
|
|
750
|
+
blockId: span.at(0) ?? ""
|
|
751
|
+
}));
|
|
752
|
+
}
|
|
753
|
+
const omitted = /* @__PURE__ */ new Map();
|
|
754
|
+
for (const entry of plan.omit) {
|
|
755
|
+
const block = sourceTopLevel(entry.blockId);
|
|
756
|
+
if (Result.isError(block)) return block;
|
|
757
|
+
if (placed.has(entry.blockId) || omitted.has(entry.blockId)) return Result.err(refuse({
|
|
758
|
+
code: "block-placed-twice",
|
|
759
|
+
message: `Block ${entry.blockId} is both placed and omitted, or omitted twice.`,
|
|
760
|
+
blockId: entry.blockId
|
|
761
|
+
}));
|
|
762
|
+
if (entry.reason === "empty" && !isBlankBlock(block.value)) return invalid(`Block ${entry.blockId} is omitted as empty and is not.`);
|
|
763
|
+
omitted.set(entry.blockId, entry.reason);
|
|
764
|
+
}
|
|
765
|
+
for (const block of source.story.topLevel) {
|
|
766
|
+
const { id } = block.block;
|
|
767
|
+
if (placed.has(id) || omitted.has(id)) continue;
|
|
768
|
+
if (!isBlankBlock(block) || showsLabel(block)) return Result.err(refuse({
|
|
769
|
+
code: "block-unplaced",
|
|
770
|
+
message: `Source block ${id} is neither placed nor omitted.`,
|
|
771
|
+
blockId: id
|
|
772
|
+
}));
|
|
773
|
+
omitted.set(id, "empty");
|
|
774
|
+
}
|
|
775
|
+
for (const [blockId] of [...referencesByBlock, ...highlightsByBlock]) if (!byBlockId.has(blockId)) return Result.err(refuse({
|
|
776
|
+
code: referencesByBlock.has(blockId) ? "reference-span-invalid" : "highlight-span-invalid",
|
|
777
|
+
message: `Block ${blockId} is not placed, so nothing can be marked in it.`,
|
|
778
|
+
blockId
|
|
779
|
+
}));
|
|
780
|
+
const takenNames = /* @__PURE__ */ new Set();
|
|
781
|
+
const takenIds = bookmarkIdsOf(template.document.root);
|
|
782
|
+
walkElements(template.document.root, (element) => {
|
|
783
|
+
if (isW(element, "bookmarkStart")) takenNames.add(wAttr(element, "name") ?? "");
|
|
784
|
+
});
|
|
785
|
+
let nextBookmarkId = maxOf(takenIds, 0) + 1;
|
|
786
|
+
const bookmarks = /* @__PURE__ */ new Map();
|
|
787
|
+
const resolvedReferences = [];
|
|
788
|
+
for (const reference of references) {
|
|
789
|
+
const paragraph = byBlockId.get(reference.blockId);
|
|
790
|
+
const target = byBlockId.get(reference.targetBlockId);
|
|
791
|
+
if (paragraph === void 0) return invalid(`Block ${reference.blockId} is not placed.`);
|
|
792
|
+
if (target === void 0) return Result.err(refuse({
|
|
793
|
+
code: "reference-target-unplaced",
|
|
794
|
+
message: `Reference target ${reference.targetBlockId} is not a placed paragraph.`,
|
|
795
|
+
blockId: reference.blockId
|
|
796
|
+
}));
|
|
797
|
+
if (paragraph === target) return Result.err(refuse({
|
|
798
|
+
code: "reference-span-invalid",
|
|
799
|
+
message: `A reference in ${reference.blockId} targets the paragraph it sits in.`,
|
|
800
|
+
blockId: reference.blockId
|
|
801
|
+
}));
|
|
802
|
+
let bookmark = bookmarks.get(target);
|
|
803
|
+
if (bookmark === void 0) {
|
|
804
|
+
bookmark = {
|
|
805
|
+
id: nextBookmarkId,
|
|
806
|
+
name: mintRefBookmarkName(`${source.manifest.sha256}:${target.parts.at(0)?.block.block.id ?? ""}`, takenNames)
|
|
807
|
+
};
|
|
808
|
+
nextBookmarkId += 1;
|
|
809
|
+
bookmarks.set(target, bookmark);
|
|
810
|
+
}
|
|
811
|
+
const instruction = refFieldInstruction(bookmark.name, reference.instruction);
|
|
812
|
+
if (instruction === null) return invalid(`A reference in ${reference.blockId} carries more than field switches.`);
|
|
813
|
+
const segment = paragraph.segments.find((candidate) => candidate.kind === "reference" && candidate.reference === reference);
|
|
814
|
+
resolvedReferences.push({
|
|
815
|
+
reference,
|
|
816
|
+
paragraph,
|
|
817
|
+
target,
|
|
818
|
+
replacedText: segment?.kind === "reference" ? segment.replacedText : "",
|
|
819
|
+
instruction
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
for (const patch of patches) {
|
|
823
|
+
const abstract = templateNumbering?.getAbstract(patch.abstractNumId);
|
|
824
|
+
if (abstract === null || abstract === void 0 || !abstract.levels.some(({ ilvl }) => ilvl === patch.ilvl)) return Result.err(refuse({
|
|
825
|
+
code: "numbering-unknown",
|
|
826
|
+
message: `The template has no level ${patch.ilvl} in list definition ${patch.abstractNumId}.`
|
|
827
|
+
}));
|
|
828
|
+
}
|
|
829
|
+
return Result.ok({
|
|
830
|
+
items,
|
|
831
|
+
nestedSlots,
|
|
832
|
+
byBlockId,
|
|
833
|
+
omitted,
|
|
834
|
+
mints: [...mints.values()],
|
|
835
|
+
bookmarks,
|
|
836
|
+
references: resolvedReferences,
|
|
837
|
+
freezeKinds: new Set(freezeKinds),
|
|
838
|
+
keptTemplateBlocks
|
|
839
|
+
});
|
|
840
|
+
};
|
|
841
|
+
export { hyperlinkFieldLink, isBlankBlock, isManualLabel, paragraphPieces, piecesContent, resolvePlan, segmentPieces };
|