odf.js 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
3
3
  import { unzipSync, zipSync } from "fflate";
4
+ import { AlignmentSchema, ColorSchema, colorToRgbHex, rgbHexToColor } from "document-content-model";
4
5
  //#region src/model/node.ts
5
6
  const AttributeSchema = z.object({
6
7
  name: z.string(),
@@ -473,7 +474,7 @@ const STANDARD_XML_PART_NAMES = /* @__PURE__ */ new Set([
473
474
  function findChildElement(nodes, tag) {
474
475
  for (const node of nodes) if (node.type === "element" && node.tag === tag) return node;
475
476
  }
476
- function attrValue(element, name) {
477
+ function attrValue$1(element, name) {
477
478
  return element.attributes.find((attribute) => attribute.name === name)?.value;
478
479
  }
479
480
  function readManifest(pkg) {
@@ -481,15 +482,15 @@ function readManifest(pkg) {
481
482
  if (part?.kind !== "xml") throw new Error(`package has no ${MANIFEST_PART} XML part to read`);
482
483
  const root = findChildElement(part.nodes, "manifest:manifest");
483
484
  if (root === void 0) throw new Error(`${MANIFEST_PART} has no manifest:manifest root element`);
484
- const version = attrValue(root, "manifest:version");
485
+ const version = attrValue$1(root, "manifest:version");
485
486
  if (version === void 0) throw new Error(`${MANIFEST_PART}'s manifest:manifest root is missing the required manifest:version attribute`);
486
487
  const entries = [];
487
488
  for (const child of root.children) {
488
489
  if (child.type !== "element" || child.tag !== "manifest:file-entry") continue;
489
- const fullPath = attrValue(child, "manifest:full-path");
490
- const mediaType = attrValue(child, "manifest:media-type");
490
+ const fullPath = attrValue$1(child, "manifest:full-path");
491
+ const mediaType = attrValue$1(child, "manifest:media-type");
491
492
  if (fullPath === void 0 || mediaType === void 0) throw new Error(`${MANIFEST_PART} has a manifest:file-entry missing manifest:full-path or manifest:media-type`);
492
- const entryVersion = attrValue(child, "manifest:version");
493
+ const entryVersion = attrValue$1(child, "manifest:version");
493
494
  entries.push(entryVersion === void 0 ? {
494
495
  fullPath,
495
496
  mediaType
@@ -648,7 +649,7 @@ function validateManifest(pkg) {
648
649
  for (const child of root.children) {
649
650
  if (child.type !== "element" || child.tag !== "manifest:file-entry") continue;
650
651
  if (!child.children.some((grandchild) => grandchild.type === "element" && grandchild.tag === "manifest:encryption-data")) continue;
651
- const fullPath = attrValue(child, "manifest:full-path");
652
+ const fullPath = attrValue$1(child, "manifest:full-path");
652
653
  if (fullPath === void 0) continue;
653
654
  problems.push({
654
655
  severity: "warning",
@@ -680,4 +681,656 @@ function setDocumentMediaType(pkg, mediaType, version = DEFAULT_MANIFEST_VERSION
680
681
  });
681
682
  }
682
683
  //#endregion
683
- export { AttributeSchema, BinaryPartSchema, MANIFEST_PART, MIMETYPE_PART, ManifestEntrySchema, ManifestProblemSchema, ManifestSchema, ODF_MEDIA_TYPES, ODF_NAMESPACES, PackageSchema, PartSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, base64ToBytes, buildManifest, buildXml, bytesToBase64, decodePackage, el, encodePackage, encodeXmlText, isXmlNode, mediaTypeForExtension, packageCodec, parsePackage, parseXml, readManifest, readMimetype, serializePackage, setDocumentMediaType, sniffImageFormat, syncManifest, txt, unzipPackage, validateManifest, writeManifest, writeMimetype, xmlCodec, xmlnsAttributes, zipPackage };
684
+ //#region src/styles/properties.ts
685
+ const StylePropertiesSchema = z.object({
686
+ bold: z.boolean().optional(),
687
+ italic: z.boolean().optional(),
688
+ underline: z.boolean().optional(),
689
+ strike: z.boolean().optional(),
690
+ fontFamily: z.string().optional(),
691
+ sizePt: z.number().optional(),
692
+ color: ColorSchema.optional(),
693
+ alignment: AlignmentSchema.optional(),
694
+ spacingBeforePt: z.number().optional(),
695
+ spacingAfterPt: z.number().optional(),
696
+ lineSpacing: z.number().optional(),
697
+ indentLeftPt: z.number().optional(),
698
+ indentFirstLinePt: z.number().optional()
699
+ });
700
+ const ATTR = {
701
+ fontWeight: "fo:font-weight",
702
+ fontStyle: "fo:font-style",
703
+ underlineStyle: "style:text-underline-style",
704
+ underlineWidth: "style:text-underline-width",
705
+ underlineColor: "style:text-underline-color",
706
+ lineThroughStyle: "style:text-line-through-style",
707
+ lineThroughType: "style:text-line-through-type",
708
+ fontFamily: "fo:font-family",
709
+ fontSize: "fo:font-size",
710
+ color: "fo:color",
711
+ textAlign: "fo:text-align",
712
+ marginTop: "fo:margin-top",
713
+ marginBottom: "fo:margin-bottom",
714
+ lineHeight: "fo:line-height",
715
+ marginLeft: "fo:margin-left",
716
+ textIndent: "fo:text-indent"
717
+ };
718
+ const TEXT_ATTR_NAMES = /* @__PURE__ */ new Set([
719
+ ATTR.fontWeight,
720
+ ATTR.fontStyle,
721
+ ATTR.underlineStyle,
722
+ ATTR.underlineWidth,
723
+ ATTR.underlineColor,
724
+ ATTR.lineThroughStyle,
725
+ ATTR.lineThroughType,
726
+ ATTR.fontFamily,
727
+ ATTR.fontSize,
728
+ ATTR.color
729
+ ]);
730
+ const PARAGRAPH_ATTR_NAMES = /* @__PURE__ */ new Set([
731
+ ATTR.textAlign,
732
+ ATTR.marginTop,
733
+ ATTR.marginBottom,
734
+ ATTR.lineHeight,
735
+ ATTR.marginLeft,
736
+ ATTR.textIndent
737
+ ]);
738
+ function attributeMap(element) {
739
+ const map = /* @__PURE__ */ new Map();
740
+ for (const attribute of element.attributes) map.set(attribute.name, attribute.value);
741
+ return map;
742
+ }
743
+ const LENGTH_PATTERN = /^(-?(?:\d+(?:\.\d+)?|\.\d+))(cm|mm|in|pt|pc|px)$/;
744
+ function unitToPtFactor(unit) {
745
+ switch (unit) {
746
+ case "pt": return 1;
747
+ case "in": return 72;
748
+ case "cm": return 72 / 2.54;
749
+ case "mm": return 72 / 25.4;
750
+ case "pc": return 12;
751
+ case "px": return .75;
752
+ }
753
+ }
754
+ function isLengthUnit(value) {
755
+ return value === "cm" || value === "mm" || value === "in" || value === "pt" || value === "pc" || value === "px";
756
+ }
757
+ function parseLength(value) {
758
+ const match = LENGTH_PATTERN.exec(value);
759
+ if (match === null) return;
760
+ const numeric = match[1];
761
+ const unit = match[2];
762
+ if (numeric === void 0 || unit === void 0 || !isLengthUnit(unit)) return;
763
+ return Number(numeric) * unitToPtFactor(unit);
764
+ }
765
+ function formatPt(valuePt) {
766
+ return `${valuePt}pt`;
767
+ }
768
+ const PERCENTAGE_PATTERN = /^(-?(?:\d+(?:\.\d+)?|\.\d+))%$/;
769
+ function parsePercentageMultiplier(value) {
770
+ const match = PERCENTAGE_PATTERN.exec(value);
771
+ if (match === null) return;
772
+ const numeric = match[1];
773
+ if (numeric === void 0) return;
774
+ return Number(numeric) / 100;
775
+ }
776
+ function formatPercentageMultiplier(multiplier) {
777
+ return `${multiplier * 100}%`;
778
+ }
779
+ const COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
780
+ function parseColor(value) {
781
+ if (!COLOR_PATTERN.test(value)) return;
782
+ return rgbHexToColor(value);
783
+ }
784
+ function formatColor(color) {
785
+ return `#${colorToRgbHex(color)}`;
786
+ }
787
+ function parseLineDecoration(style, companionA, companionAOnValue, companionB, companionBOnValue) {
788
+ if (style === void 0 && companionA === void 0 && companionB === void 0) return;
789
+ if (style === "solid" && (companionA === void 0 || companionA === companionAOnValue) && (companionB === void 0 || companionB === companionBOnValue)) return true;
790
+ if (style === "none" && companionA === void 0 && companionB === void 0) return false;
791
+ return "unknown";
792
+ }
793
+ const RISKY_STYLE_ELEMENT_ATTRS = /* @__PURE__ */ new Set(["style:master-page-name", "style:next-style-name"]);
794
+ function parseTextProperties(element) {
795
+ const attrs = attributeMap(element);
796
+ const properties = {};
797
+ let hasUnknown = false;
798
+ for (const name of attrs.keys()) if (!TEXT_ATTR_NAMES.has(name)) hasUnknown = true;
799
+ const fontWeight = attrs.get(ATTR.fontWeight);
800
+ if (fontWeight === "bold") properties.bold = true;
801
+ else if (fontWeight === "normal") properties.bold = false;
802
+ else if (fontWeight !== void 0) hasUnknown = true;
803
+ const fontStyle = attrs.get(ATTR.fontStyle);
804
+ if (fontStyle === "italic") properties.italic = true;
805
+ else if (fontStyle === "normal") properties.italic = false;
806
+ else if (fontStyle !== void 0) hasUnknown = true;
807
+ const underline = parseLineDecoration(attrs.get(ATTR.underlineStyle), attrs.get(ATTR.underlineWidth), "auto", attrs.get(ATTR.underlineColor), "font-color");
808
+ if (underline === "unknown") hasUnknown = true;
809
+ else if (underline !== void 0) properties.underline = underline;
810
+ const strike = parseLineDecoration(attrs.get(ATTR.lineThroughStyle), attrs.get(ATTR.lineThroughType), "single", void 0, "");
811
+ if (strike === "unknown") hasUnknown = true;
812
+ else if (strike !== void 0) properties.strike = strike;
813
+ const fontFamily = attrs.get(ATTR.fontFamily);
814
+ if (fontFamily !== void 0) properties.fontFamily = fontFamily;
815
+ const fontSize = attrs.get(ATTR.fontSize);
816
+ if (fontSize !== void 0) {
817
+ const pt = parseLength(fontSize);
818
+ if (pt === void 0) hasUnknown = true;
819
+ else properties.sizePt = pt;
820
+ }
821
+ const color = attrs.get(ATTR.color);
822
+ if (color !== void 0) {
823
+ const parsed = parseColor(color);
824
+ if (parsed === void 0) hasUnknown = true;
825
+ else properties.color = parsed;
826
+ }
827
+ return {
828
+ properties,
829
+ hasUnknown
830
+ };
831
+ }
832
+ function parseParagraphProperties(element) {
833
+ const attrs = attributeMap(element);
834
+ const properties = {};
835
+ let hasUnknown = false;
836
+ for (const name of attrs.keys()) if (!PARAGRAPH_ATTR_NAMES.has(name)) hasUnknown = true;
837
+ const textAlign = attrs.get(ATTR.textAlign);
838
+ if (textAlign === "left" || textAlign === "center" || textAlign === "right" || textAlign === "justify") properties.alignment = textAlign;
839
+ else if (textAlign !== void 0) hasUnknown = true;
840
+ const marginTop = attrs.get(ATTR.marginTop);
841
+ if (marginTop !== void 0) {
842
+ const pt = parseLength(marginTop);
843
+ if (pt === void 0) hasUnknown = true;
844
+ else properties.spacingBeforePt = pt;
845
+ }
846
+ const marginBottom = attrs.get(ATTR.marginBottom);
847
+ if (marginBottom !== void 0) {
848
+ const pt = parseLength(marginBottom);
849
+ if (pt === void 0) hasUnknown = true;
850
+ else properties.spacingAfterPt = pt;
851
+ }
852
+ const marginLeft = attrs.get(ATTR.marginLeft);
853
+ if (marginLeft !== void 0) {
854
+ const pt = parseLength(marginLeft);
855
+ if (pt === void 0) hasUnknown = true;
856
+ else properties.indentLeftPt = pt;
857
+ }
858
+ const textIndent = attrs.get(ATTR.textIndent);
859
+ if (textIndent !== void 0) {
860
+ const pt = parseLength(textIndent);
861
+ if (pt === void 0) hasUnknown = true;
862
+ else properties.indentFirstLinePt = pt;
863
+ }
864
+ const lineHeight = attrs.get(ATTR.lineHeight);
865
+ if (lineHeight !== void 0) {
866
+ const multiplier = parsePercentageMultiplier(lineHeight);
867
+ if (multiplier === void 0) hasUnknown = true;
868
+ else properties.lineSpacing = multiplier;
869
+ }
870
+ return {
871
+ properties,
872
+ hasUnknown
873
+ };
874
+ }
875
+ function parseStyleElementProperties(styleElement) {
876
+ let properties = {};
877
+ let hasUnknown = false;
878
+ for (const attribute of styleElement.attributes) if (RISKY_STYLE_ELEMENT_ATTRS.has(attribute.name)) hasUnknown = true;
879
+ for (const child of styleElement.children) {
880
+ if (child.type !== "element") continue;
881
+ if (child.tag === "style:text-properties") {
882
+ const result = parseTextProperties(child);
883
+ properties = {
884
+ ...properties,
885
+ ...result.properties
886
+ };
887
+ if (result.hasUnknown) hasUnknown = true;
888
+ } else if (child.tag === "style:paragraph-properties") {
889
+ const result = parseParagraphProperties(child);
890
+ properties = {
891
+ ...properties,
892
+ ...result.properties
893
+ };
894
+ if (result.hasUnknown) hasUnknown = true;
895
+ } else hasUnknown = true;
896
+ }
897
+ return {
898
+ properties,
899
+ hasUnknown
900
+ };
901
+ }
902
+ function textPropertiesToAttributes(properties) {
903
+ const attributes = [];
904
+ if (properties.bold !== void 0) attributes.push({
905
+ name: ATTR.fontWeight,
906
+ value: properties.bold ? "bold" : "normal"
907
+ });
908
+ if (properties.italic !== void 0) attributes.push({
909
+ name: ATTR.fontStyle,
910
+ value: properties.italic ? "italic" : "normal"
911
+ });
912
+ if (properties.underline !== void 0) if (properties.underline) {
913
+ attributes.push({
914
+ name: ATTR.underlineStyle,
915
+ value: "solid"
916
+ });
917
+ attributes.push({
918
+ name: ATTR.underlineWidth,
919
+ value: "auto"
920
+ });
921
+ attributes.push({
922
+ name: ATTR.underlineColor,
923
+ value: "font-color"
924
+ });
925
+ } else attributes.push({
926
+ name: ATTR.underlineStyle,
927
+ value: "none"
928
+ });
929
+ if (properties.strike !== void 0) if (properties.strike) {
930
+ attributes.push({
931
+ name: ATTR.lineThroughStyle,
932
+ value: "solid"
933
+ });
934
+ attributes.push({
935
+ name: ATTR.lineThroughType,
936
+ value: "single"
937
+ });
938
+ } else attributes.push({
939
+ name: ATTR.lineThroughStyle,
940
+ value: "none"
941
+ });
942
+ if (properties.fontFamily !== void 0) attributes.push({
943
+ name: ATTR.fontFamily,
944
+ value: encodeXmlText(properties.fontFamily)
945
+ });
946
+ if (properties.sizePt !== void 0) attributes.push({
947
+ name: ATTR.fontSize,
948
+ value: formatPt(properties.sizePt)
949
+ });
950
+ if (properties.color !== void 0) attributes.push({
951
+ name: ATTR.color,
952
+ value: formatColor(properties.color)
953
+ });
954
+ return attributes;
955
+ }
956
+ function paragraphPropertiesToAttributes(properties) {
957
+ const attributes = [];
958
+ if (properties.alignment !== void 0) attributes.push({
959
+ name: ATTR.textAlign,
960
+ value: properties.alignment
961
+ });
962
+ if (properties.spacingBeforePt !== void 0) attributes.push({
963
+ name: ATTR.marginTop,
964
+ value: formatPt(properties.spacingBeforePt)
965
+ });
966
+ if (properties.spacingAfterPt !== void 0) attributes.push({
967
+ name: ATTR.marginBottom,
968
+ value: formatPt(properties.spacingAfterPt)
969
+ });
970
+ if (properties.lineSpacing !== void 0) attributes.push({
971
+ name: ATTR.lineHeight,
972
+ value: formatPercentageMultiplier(properties.lineSpacing)
973
+ });
974
+ if (properties.indentLeftPt !== void 0) attributes.push({
975
+ name: ATTR.marginLeft,
976
+ value: formatPt(properties.indentLeftPt)
977
+ });
978
+ if (properties.indentFirstLinePt !== void 0) attributes.push({
979
+ name: ATTR.textIndent,
980
+ value: formatPt(properties.indentFirstLinePt)
981
+ });
982
+ return attributes;
983
+ }
984
+ //#endregion
985
+ //#region src/styles/serialize.ts
986
+ function attributesToRecord(attributes) {
987
+ const record = {};
988
+ for (const attribute of attributes) record[attribute.name] = attribute.value;
989
+ return record;
990
+ }
991
+ function buildStylePropertyElements(properties) {
992
+ const elements = [];
993
+ const paragraphAttributes = paragraphPropertiesToAttributes(properties);
994
+ if (paragraphAttributes.length > 0) elements.push(el("style:paragraph-properties", attributesToRecord(paragraphAttributes)));
995
+ const textAttributes = textPropertiesToAttributes(properties);
996
+ if (textAttributes.length > 0) elements.push(el("style:text-properties", attributesToRecord(textAttributes)));
997
+ return elements;
998
+ }
999
+ function canonicalPropertiesString(properties) {
1000
+ return [...paragraphPropertiesToAttributes(properties), ...textPropertiesToAttributes(properties)].map((attribute) => `${attribute.name}=${attribute.value}`).join("|");
1001
+ }
1002
+ //#endregion
1003
+ //#region src/styles/registry.ts
1004
+ const STYLE_FAMILIES = [
1005
+ "paragraph",
1006
+ "text",
1007
+ "table",
1008
+ "table-column",
1009
+ "table-row",
1010
+ "table-cell",
1011
+ "graphic"
1012
+ ];
1013
+ function isStyleFamily(value) {
1014
+ return value === "paragraph" || value === "text" || value === "table" || value === "table-column" || value === "table-row" || value === "table-cell" || value === "graphic";
1015
+ }
1016
+ const CONTENT_PREFIXES = {
1017
+ paragraph: "P",
1018
+ text: "T",
1019
+ table: "ta",
1020
+ "table-column": "co",
1021
+ "table-row": "ro",
1022
+ "table-cell": "ce",
1023
+ graphic: "fr"
1024
+ };
1025
+ const STYLES_PREFIXES = {
1026
+ paragraph: "PS",
1027
+ text: "TS",
1028
+ table: "taS",
1029
+ "table-column": "coS",
1030
+ "table-row": "roS",
1031
+ "table-cell": "ceS",
1032
+ graphic: "frS"
1033
+ };
1034
+ function prefixesForPart(partPath) {
1035
+ const baseName = partPath.slice(partPath.lastIndexOf("/") + 1);
1036
+ if (baseName === "content.xml") return CONTENT_PREFIXES;
1037
+ if (baseName === "styles.xml") return STYLES_PREFIXES;
1038
+ throw new Error(`StyleRegistry.forPart: expected a part named "content.xml" or "styles.xml" (by base name), got "${partPath}"`);
1039
+ }
1040
+ function emptyFamilySets() {
1041
+ return {
1042
+ paragraph: /* @__PURE__ */ new Set(),
1043
+ text: /* @__PURE__ */ new Set(),
1044
+ table: /* @__PURE__ */ new Set(),
1045
+ "table-column": /* @__PURE__ */ new Set(),
1046
+ "table-row": /* @__PURE__ */ new Set(),
1047
+ "table-cell": /* @__PURE__ */ new Set(),
1048
+ graphic: /* @__PURE__ */ new Set()
1049
+ };
1050
+ }
1051
+ function attrValue(element, name) {
1052
+ return element.attributes.find((attribute) => attribute.name === name)?.value;
1053
+ }
1054
+ function findDirectChild(nodes, tag) {
1055
+ for (const node of nodes) if (node.type === "element" && node.tag === tag) return node;
1056
+ }
1057
+ function findRootElement(nodes) {
1058
+ const root = nodes.find((node) => node.type === "element");
1059
+ if (root === void 0) throw new Error("StyleRegistry: part has no root XML element -- construct the part's minimal root (office:document-content/office:document-styles) before building a StyleRegistry for it");
1060
+ return root;
1061
+ }
1062
+ function ensureAutomaticStyles(root) {
1063
+ const existing = findDirectChild(root.children, "office:automatic-styles");
1064
+ if (existing !== void 0) return existing;
1065
+ const created = el("office:automatic-styles");
1066
+ const insertBeforeTags = /* @__PURE__ */ new Set([
1067
+ "office:body",
1068
+ "office:master-styles",
1069
+ "office:settings"
1070
+ ]);
1071
+ const insertIndex = root.children.findIndex((node) => node.type === "element" && insertBeforeTags.has(node.tag));
1072
+ if (insertIndex === -1) root.children.push(created);
1073
+ else root.children.splice(insertIndex, 0, created);
1074
+ return created;
1075
+ }
1076
+ function reserveStyleNames(container, reserved) {
1077
+ for (const child of container.children) {
1078
+ if (child.type !== "element" || child.tag !== "style:style") continue;
1079
+ const name = attrValue(child, "style:name");
1080
+ const family = attrValue(child, "style:family");
1081
+ if (name === void 0 || family === void 0 || !isStyleFamily(family)) continue;
1082
+ reserved[family].add(name);
1083
+ }
1084
+ }
1085
+ const FINGERPRINT_SEPARATOR = "\0";
1086
+ const NO_PARENT_SENTINEL = "";
1087
+ function computeFingerprint(family, properties, parentStyleName) {
1088
+ const parentComponent = parentStyleName ?? NO_PARENT_SENTINEL;
1089
+ return [
1090
+ family,
1091
+ canonicalPropertiesString(properties),
1092
+ parentComponent
1093
+ ].join(FINGERPRINT_SEPARATOR);
1094
+ }
1095
+ var StyleRegistry = class StyleRegistry {
1096
+ automaticStyles;
1097
+ prefixes;
1098
+ reservedByFamily;
1099
+ knownStyles = /* @__PURE__ */ new Map();
1100
+ fingerprintToName = /* @__PURE__ */ new Map();
1101
+ nameToFingerprint = /* @__PURE__ */ new Map();
1102
+ familyCounters = {
1103
+ paragraph: 1,
1104
+ text: 1,
1105
+ table: 1,
1106
+ "table-column": 1,
1107
+ "table-row": 1,
1108
+ "table-cell": 1,
1109
+ graphic: 1
1110
+ };
1111
+ constructor(automaticStyles, prefixes, reservedByFamily) {
1112
+ this.automaticStyles = automaticStyles;
1113
+ this.prefixes = prefixes;
1114
+ this.reservedByFamily = reservedByFamily;
1115
+ }
1116
+ static forPart(pkg, partPath, options = {}) {
1117
+ const part = pkg.parts[partPath];
1118
+ if (part?.kind !== "xml") throw new Error(`StyleRegistry.forPart: "${partPath}" is not an XML part of the given package`);
1119
+ const prefixes = prefixesForPart(partPath);
1120
+ const root = findRootElement(part.nodes);
1121
+ const automaticStyles = ensureAutomaticStyles(root);
1122
+ const reservedByFamily = emptyFamilySets();
1123
+ const registry = new StyleRegistry(automaticStyles, prefixes, reservedByFamily);
1124
+ for (const child of automaticStyles.children) {
1125
+ if (child.type !== "element" || child.tag !== "style:style") continue;
1126
+ const name = attrValue(child, "style:name");
1127
+ const family = attrValue(child, "style:family");
1128
+ if (name === void 0 || family === void 0 || !isStyleFamily(family)) continue;
1129
+ registry.knownStyles.set(name, child);
1130
+ reservedByFamily[family].add(name);
1131
+ const parsed = parseStyleElementProperties(child);
1132
+ if (!parsed.hasUnknown) {
1133
+ const parentStyleName = attrValue(child, "style:parent-style-name");
1134
+ const fingerprint = computeFingerprint(family, parsed.properties, parentStyleName);
1135
+ if (!registry.fingerprintToName.has(fingerprint)) {
1136
+ registry.fingerprintToName.set(fingerprint, name);
1137
+ registry.nameToFingerprint.set(name, fingerprint);
1138
+ }
1139
+ }
1140
+ }
1141
+ const ownStyles = findDirectChild(root.children, "office:styles");
1142
+ if (ownStyles !== void 0) reserveStyleNames(ownStyles, reservedByFamily);
1143
+ if (options.otherPart !== void 0) {
1144
+ const otherPart = options.otherPart.pkg.parts[options.otherPart.partPath];
1145
+ if (otherPart?.kind === "xml") {
1146
+ const otherRoot = findRootElement(otherPart.nodes);
1147
+ const otherAutomatic = findDirectChild(otherRoot.children, "office:automatic-styles");
1148
+ if (otherAutomatic !== void 0) reserveStyleNames(otherAutomatic, reservedByFamily);
1149
+ const otherStyles = findDirectChild(otherRoot.children, "office:styles");
1150
+ if (otherStyles !== void 0) reserveStyleNames(otherStyles, reservedByFamily);
1151
+ }
1152
+ }
1153
+ if (options.additionalReservedNames !== void 0) for (const family of STYLE_FAMILIES) for (const name of options.additionalReservedNames) reservedByFamily[family].add(name);
1154
+ return registry;
1155
+ }
1156
+ fingerprint(request) {
1157
+ return computeFingerprint(request.family, request.properties, request.parentStyleName);
1158
+ }
1159
+ intern(request) {
1160
+ const fingerprint = this.fingerprint(request);
1161
+ const existingName = this.fingerprintToName.get(fingerprint);
1162
+ if (existingName !== void 0) return existingName;
1163
+ const name = this.mintName(request.family);
1164
+ const attributes = {
1165
+ "style:name": name,
1166
+ "style:family": request.family
1167
+ };
1168
+ if (request.parentStyleName !== void 0) attributes["style:parent-style-name"] = encodeXmlText(request.parentStyleName);
1169
+ const styleElement = el("style:style", attributes, buildStylePropertyElements(request.properties));
1170
+ this.automaticStyles.children.push(styleElement);
1171
+ this.knownStyles.set(name, styleElement);
1172
+ this.reservedByFamily[request.family].add(name);
1173
+ this.fingerprintToName.set(fingerprint, name);
1174
+ this.nameToFingerprint.set(name, fingerprint);
1175
+ return name;
1176
+ }
1177
+ mintName(family) {
1178
+ const prefix = this.prefixes[family];
1179
+ const reserved = this.reservedByFamily[family];
1180
+ let counter = this.familyCounters[family];
1181
+ while (reserved.has(`${prefix}${counter}`)) counter += 1;
1182
+ const name = `${prefix}${counter}`;
1183
+ this.familyCounters[family] = counter + 1;
1184
+ return name;
1185
+ }
1186
+ names() {
1187
+ return [...this.knownStyles.keys()];
1188
+ }
1189
+ gc(referenced) {
1190
+ let removed = 0;
1191
+ for (const [name, element] of [...this.knownStyles]) {
1192
+ if (referenced.has(name)) continue;
1193
+ const index = this.automaticStyles.children.indexOf(element);
1194
+ if (index !== -1) this.automaticStyles.children.splice(index, 1);
1195
+ this.knownStyles.delete(name);
1196
+ const fingerprint = this.nameToFingerprint.get(name);
1197
+ if (fingerprint !== void 0) {
1198
+ this.fingerprintToName.delete(fingerprint);
1199
+ this.nameToFingerprint.delete(name);
1200
+ }
1201
+ removed += 1;
1202
+ }
1203
+ return removed;
1204
+ }
1205
+ };
1206
+ //#endregion
1207
+ //#region src/styles/span.ts
1208
+ function ensureSpan(paragraph, start, end, styleName) {
1209
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start) throw new Error(`ensureSpan: invalid range [${start}, ${end})`);
1210
+ const total = sumLength(paragraph.children);
1211
+ if (end > total) throw new Error(`ensureSpan: range end ${end} exceeds the container's total character length ${total}`);
1212
+ const { before, after: rest } = splitChildrenAt(paragraph.children, start);
1213
+ const { before: middle, after } = splitChildrenAt(rest, end - start);
1214
+ let span;
1215
+ const soleChild = middle.length === 1 ? middle[0] : void 0;
1216
+ if (soleChild?.type === "element" && soleChild.tag === "text:span") {
1217
+ span = soleChild;
1218
+ setStyleName(span, styleName);
1219
+ } else span = el("text:span", { "text:style-name": encodeXmlText(styleName) }, middle);
1220
+ paragraph.children = [
1221
+ ...before,
1222
+ span,
1223
+ ...after
1224
+ ];
1225
+ return span;
1226
+ }
1227
+ function cloneAttributes(attributes) {
1228
+ return attributes.map((attribute) => ({ ...attribute }));
1229
+ }
1230
+ function setStyleName(span, styleName) {
1231
+ const encoded = encodeXmlText(styleName);
1232
+ const existing = span.attributes.find((attribute) => attribute.name === "text:style-name");
1233
+ if (existing !== void 0) {
1234
+ existing.value = encoded;
1235
+ return;
1236
+ }
1237
+ span.attributes.push({
1238
+ name: "text:style-name",
1239
+ value: encoded
1240
+ });
1241
+ }
1242
+ function getSpaceCount(spaceElement) {
1243
+ const raw = spaceElement.attributes.find((attribute) => attribute.name === "text:c")?.value;
1244
+ if (raw === void 0) return 1;
1245
+ const parsed = Number.parseInt(raw, 10);
1246
+ if (!Number.isInteger(parsed) || parsed < 0 || String(parsed) !== raw) throw new Error(`ensureSpan: text:s has a malformed text:c attribute: "${raw}"`);
1247
+ return parsed;
1248
+ }
1249
+ function buildSpaceRun(count) {
1250
+ return count === 1 ? el("text:s") : el("text:s", { "text:c": String(count) });
1251
+ }
1252
+ function measureLength(node) {
1253
+ if (node.type === "text") return node.value.length;
1254
+ if (node.type !== "element") return 0;
1255
+ if (node.tag === "text:s") return getSpaceCount(node);
1256
+ if (node.tag === "text:tab" || node.tag === "text:line-break") return 1;
1257
+ if (node.tag === "text:span") return sumLength(node.children);
1258
+ return 0;
1259
+ }
1260
+ function sumLength(nodes) {
1261
+ let total = 0;
1262
+ for (const node of nodes) total += measureLength(node);
1263
+ return total;
1264
+ }
1265
+ function splitNode(node, offset) {
1266
+ if (node.type === "text") return {
1267
+ left: {
1268
+ type: "text",
1269
+ value: node.value.slice(0, offset)
1270
+ },
1271
+ right: {
1272
+ type: "text",
1273
+ value: node.value.slice(offset)
1274
+ }
1275
+ };
1276
+ if (node.type === "element" && node.tag === "text:s") {
1277
+ const count = getSpaceCount(node);
1278
+ return {
1279
+ left: buildSpaceRun(offset),
1280
+ right: buildSpaceRun(count - offset)
1281
+ };
1282
+ }
1283
+ if (node.type === "element" && node.tag === "text:span") {
1284
+ const inner = splitChildrenAt(node.children, offset);
1285
+ return {
1286
+ left: inner.before.length === 0 ? void 0 : {
1287
+ ...node,
1288
+ attributes: cloneAttributes(node.attributes),
1289
+ children: inner.before
1290
+ },
1291
+ right: inner.after.length === 0 ? void 0 : {
1292
+ ...node,
1293
+ attributes: cloneAttributes(node.attributes),
1294
+ children: inner.after
1295
+ }
1296
+ };
1297
+ }
1298
+ const label = node.type === "element" ? node.tag : node.type;
1299
+ throw new Error(`ensureSpan: cannot split "${label}" at a fractional offset -- this indicates a character-length computation bug, since every node type with length 1 or 0 should never reach this branch`);
1300
+ }
1301
+ function splitChildrenAt(children, offset) {
1302
+ if (offset <= 0) return {
1303
+ before: [],
1304
+ after: [...children]
1305
+ };
1306
+ const before = [];
1307
+ let remaining = offset;
1308
+ for (let index = 0; index < children.length; index += 1) {
1309
+ if (remaining === 0) return {
1310
+ before,
1311
+ after: children.slice(index)
1312
+ };
1313
+ const node = children[index];
1314
+ const length = measureLength(node);
1315
+ if (remaining >= length) {
1316
+ before.push(node);
1317
+ remaining -= length;
1318
+ continue;
1319
+ }
1320
+ const { left, right } = splitNode(node, remaining);
1321
+ const after = [];
1322
+ if (left !== void 0) before.push(left);
1323
+ if (right !== void 0) after.push(right);
1324
+ after.push(...children.slice(index + 1));
1325
+ return {
1326
+ before,
1327
+ after
1328
+ };
1329
+ }
1330
+ return {
1331
+ before,
1332
+ after: []
1333
+ };
1334
+ }
1335
+ //#endregion
1336
+ export { AttributeSchema, BinaryPartSchema, MANIFEST_PART, MIMETYPE_PART, ManifestEntrySchema, ManifestProblemSchema, ManifestSchema, ODF_MEDIA_TYPES, ODF_NAMESPACES, PackageSchema, PartSchema, STYLE_FAMILIES, StylePropertiesSchema, StyleRegistry, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, base64ToBytes, buildManifest, buildStylePropertyElements, buildXml, bytesToBase64, canonicalPropertiesString, decodePackage, el, encodePackage, encodeXmlText, ensureSpan, formatPercentageMultiplier, formatPt, isXmlNode, mediaTypeForExtension, packageCodec, paragraphPropertiesToAttributes, parseLength, parsePackage, parseParagraphProperties, parseStyleElementProperties, parseTextProperties, parseXml, readManifest, readMimetype, serializePackage, setDocumentMediaType, sniffImageFormat, syncManifest, textPropertiesToAttributes, txt, unzipPackage, validateManifest, writeManifest, writeMimetype, xmlCodec, xmlnsAttributes, zipPackage };