@tiens.nguyen/gu-cli 1.0.903 → 1.0.905

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.
Files changed (188) hide show
  1. package/NOTICE +18 -0
  2. package/gu-repl.mjs +1 -1
  3. package/package.json +3 -2
  4. package/skills/core/deep-research/SKILL.md +51 -0
  5. package/skills/core/docx/LICENSE.txt +202 -0
  6. package/skills/core/docx/SKILL.md +97 -0
  7. package/skills/core/docx/scripts/__init__.py +1 -0
  8. package/skills/core/docx/scripts/accept_changes.py +135 -0
  9. package/skills/core/docx/scripts/comment.py +368 -0
  10. package/skills/core/docx/scripts/merge_runs.py +310 -0
  11. package/skills/core/docx/scripts/office/helpers/__init__.py +121 -0
  12. package/skills/core/docx/scripts/office/helpers/pptx_chart.py +283 -0
  13. package/skills/core/docx/scripts/office/helpers/pptx_slide.py +100 -0
  14. package/skills/core/docx/scripts/office/helpers/pptx_theme.py +114 -0
  15. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  16. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  17. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  18. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  19. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  20. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  21. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  22. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  23. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  24. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  25. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  26. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  27. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  28. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  29. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  30. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  31. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  32. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  33. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  34. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  35. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  36. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  37. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  38. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  39. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  40. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  41. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  42. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  43. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  44. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  45. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  46. package/skills/core/docx/scripts/office/schemas/mce/mc.xsd +75 -0
  47. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  48. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  49. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  50. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  51. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  52. package/skills/core/docx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  53. package/skills/core/docx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  54. package/skills/core/docx/scripts/office/soffice.py +192 -0
  55. package/skills/core/docx/scripts/office/validate.py +210 -0
  56. package/skills/core/docx/scripts/office/validators/__init__.py +15 -0
  57. package/skills/core/docx/scripts/office/validators/base.py +874 -0
  58. package/skills/core/docx/scripts/office/validators/docx.py +519 -0
  59. package/skills/core/docx/scripts/office/validators/pptx.py +549 -0
  60. package/skills/core/docx/scripts/office/validators/redlining.py +461 -0
  61. package/skills/core/docx/scripts/templates/comments.xml +3 -0
  62. package/skills/core/docx/scripts/templates/commentsExtended.xml +3 -0
  63. package/skills/core/docx/scripts/templates/commentsExtensible.xml +3 -0
  64. package/skills/core/docx/scripts/templates/commentsIds.xml +3 -0
  65. package/skills/core/docx/scripts/templates/people.xml +3 -0
  66. package/skills/core/pdf/FORMS.md +294 -0
  67. package/skills/core/pdf/LICENSE.txt +202 -0
  68. package/skills/core/pdf/REFERENCE.md +613 -0
  69. package/skills/core/pdf/SKILL.md +314 -0
  70. package/skills/core/pdf/scripts/check_bounding_boxes.py +65 -0
  71. package/skills/core/pdf/scripts/check_fillable_fields.py +11 -0
  72. package/skills/core/pdf/scripts/convert_pdf_to_images.py +33 -0
  73. package/skills/core/pdf/scripts/create_validation_image.py +37 -0
  74. package/skills/core/pdf/scripts/extract_form_field_info.py +122 -0
  75. package/skills/core/pdf/scripts/extract_form_structure.py +115 -0
  76. package/skills/core/pdf/scripts/fill_fillable_fields.py +98 -0
  77. package/skills/core/pdf/scripts/fill_pdf_form_with_annotations.py +107 -0
  78. package/skills/core/pptx/LICENSE.txt +202 -0
  79. package/skills/core/pptx/SKILL.md +275 -0
  80. package/skills/core/pptx/scripts/__init__.py +0 -0
  81. package/skills/core/pptx/scripts/add_slide.py +463 -0
  82. package/skills/core/pptx/scripts/apply_theme.js +107 -0
  83. package/skills/core/pptx/scripts/clean.py +309 -0
  84. package/skills/core/pptx/scripts/office/helpers/__init__.py +121 -0
  85. package/skills/core/pptx/scripts/office/helpers/pptx_chart.py +283 -0
  86. package/skills/core/pptx/scripts/office/helpers/pptx_slide.py +100 -0
  87. package/skills/core/pptx/scripts/office/helpers/pptx_theme.py +114 -0
  88. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  89. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  90. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  91. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  92. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  93. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  94. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  95. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  96. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  97. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  98. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  99. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  100. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  101. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  102. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  103. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  104. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  105. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  106. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  107. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  108. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  109. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  110. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  111. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  112. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  113. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  114. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  115. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  116. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  117. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  118. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  119. package/skills/core/pptx/scripts/office/schemas/mce/mc.xsd +75 -0
  120. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  121. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  122. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  123. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  124. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  125. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  126. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  127. package/skills/core/pptx/scripts/office/soffice.py +192 -0
  128. package/skills/core/pptx/scripts/office/validate.py +210 -0
  129. package/skills/core/pptx/scripts/office/validators/__init__.py +15 -0
  130. package/skills/core/pptx/scripts/office/validators/base.py +874 -0
  131. package/skills/core/pptx/scripts/office/validators/docx.py +519 -0
  132. package/skills/core/pptx/scripts/office/validators/pptx.py +549 -0
  133. package/skills/core/pptx/scripts/office/validators/redlining.py +461 -0
  134. package/skills/core/pptx/scripts/slide_text.py +132 -0
  135. package/skills/core/pptx/scripts/thumbnail.py +311 -0
  136. package/skills/core/xlsx/LICENSE.txt +202 -0
  137. package/skills/core/xlsx/SKILL.md +99 -0
  138. package/skills/core/xlsx/scripts/office/helpers/__init__.py +121 -0
  139. package/skills/core/xlsx/scripts/office/helpers/pptx_chart.py +283 -0
  140. package/skills/core/xlsx/scripts/office/helpers/pptx_slide.py +100 -0
  141. package/skills/core/xlsx/scripts/office/helpers/pptx_theme.py +114 -0
  142. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  143. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  144. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  145. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  146. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  147. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  148. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  149. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  150. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  151. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  152. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  153. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  154. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  155. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  156. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  157. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  158. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  159. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  160. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  161. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  162. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  163. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  164. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  165. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  166. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  167. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  168. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  169. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  170. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  171. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  172. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  173. package/skills/core/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
  174. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  175. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  176. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  177. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  178. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  179. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  180. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  181. package/skills/core/xlsx/scripts/office/soffice.py +192 -0
  182. package/skills/core/xlsx/scripts/office/validate.py +210 -0
  183. package/skills/core/xlsx/scripts/office/validators/__init__.py +15 -0
  184. package/skills/core/xlsx/scripts/office/validators/base.py +874 -0
  185. package/skills/core/xlsx/scripts/office/validators/docx.py +519 -0
  186. package/skills/core/xlsx/scripts/office/validators/pptx.py +549 -0
  187. package/skills/core/xlsx/scripts/office/validators/redlining.py +461 -0
  188. package/skills/core/xlsx/scripts/recalc.py +456 -0
@@ -0,0 +1,519 @@
1
+ """
2
+ Validator for Word document XML files against XSD schemas.
3
+ """
4
+
5
+ import random
6
+ import re
7
+ import tempfile
8
+ import zipfile
9
+ from collections import Counter
10
+ from pathlib import Path
11
+
12
+ import defusedxml.minidom
13
+ import lxml.etree
14
+
15
+ from helpers import one_line, safe_extract
16
+
17
+ from .base import BaseSchemaValidator
18
+
19
+
20
+ class DOCXSchemaValidator(BaseSchemaValidator):
21
+
22
+ WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
23
+ W14_NAMESPACE = "http://schemas.microsoft.com/office/word/2010/wordml"
24
+ W16CID_NAMESPACE = "http://schemas.microsoft.com/office/word/2016/wordml/cid"
25
+
26
+ ELEMENT_RELATIONSHIP_TYPES = {}
27
+
28
+ def validate(self):
29
+ if not self.validate_xml():
30
+ return False
31
+
32
+ all_valid = True
33
+ if not self.validate_namespaces():
34
+ all_valid = False
35
+
36
+ if not self.validate_unique_ids():
37
+ all_valid = False
38
+
39
+ if not self.validate_file_references():
40
+ all_valid = False
41
+
42
+ if not self.validate_content_types():
43
+ all_valid = False
44
+
45
+ if not self.validate_against_xsd():
46
+ all_valid = False
47
+
48
+ if not self.validate_whitespace_preservation():
49
+ all_valid = False
50
+
51
+ if not self.validate_deletions():
52
+ all_valid = False
53
+
54
+ if not self.validate_insertions():
55
+ all_valid = False
56
+
57
+ if not self.validate_all_relationship_ids():
58
+ all_valid = False
59
+
60
+ if not self.validate_id_constraints():
61
+ all_valid = False
62
+
63
+ if not self.validate_comment_markers():
64
+ all_valid = False
65
+
66
+ if not self.validate_style_ids():
67
+ all_valid = False
68
+
69
+ self.compare_paragraph_counts()
70
+
71
+ return all_valid
72
+
73
+ def validate_whitespace_preservation(self):
74
+ errors = []
75
+
76
+ for xml_file in self.xml_files:
77
+ if xml_file.name != "document.xml":
78
+ continue
79
+
80
+ try:
81
+ root = lxml.etree.parse(str(xml_file)).getroot()
82
+
83
+ for elem in root.iter(f"{{{self.WORD_2006_NAMESPACE}}}t"):
84
+ if elem.text:
85
+ text = elem.text
86
+ if re.search(r"^[ \t\n\r]", text) or re.search(
87
+ r"[ \t\n\r]$", text
88
+ ):
89
+ xml_space_attr = f"{{{self.XML_NAMESPACE}}}space"
90
+ if (
91
+ xml_space_attr not in elem.attrib
92
+ or elem.attrib[xml_space_attr] != "preserve"
93
+ ):
94
+ text_preview = (
95
+ repr(text)[:50] + "..."
96
+ if len(repr(text)) > 50
97
+ else repr(text)
98
+ )
99
+ errors.append(
100
+ f" {xml_file.relative_to(self.unpacked_dir)}: "
101
+ f"Line {elem.sourceline}: w:t element with whitespace missing xml:space='preserve': {text_preview}"
102
+ )
103
+
104
+ except (lxml.etree.XMLSyntaxError, Exception) as e:
105
+ errors.append(
106
+ f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
107
+ )
108
+
109
+ if errors:
110
+ print(f"FAILED - Found {len(errors)} whitespace preservation violations:")
111
+ for error in errors:
112
+ print(error)
113
+ return False
114
+ else:
115
+ if self.verbose:
116
+ print("PASSED - All whitespace is properly preserved")
117
+ return True
118
+
119
+ def validate_deletions(self):
120
+ errors = []
121
+
122
+ for xml_file in self.xml_files:
123
+ if xml_file.name != "document.xml":
124
+ continue
125
+
126
+ try:
127
+ root = lxml.etree.parse(str(xml_file)).getroot()
128
+ namespaces = {"w": self.WORD_2006_NAMESPACE}
129
+
130
+ for t_elem in root.xpath(".//w:del//w:t", namespaces=namespaces):
131
+ if t_elem.text:
132
+ text_preview = (
133
+ repr(t_elem.text)[:50] + "..."
134
+ if len(repr(t_elem.text)) > 50
135
+ else repr(t_elem.text)
136
+ )
137
+ errors.append(
138
+ f" {xml_file.relative_to(self.unpacked_dir)}: "
139
+ f"Line {t_elem.sourceline}: <w:t> found within <w:del>: {text_preview}"
140
+ )
141
+
142
+ for instr_elem in root.xpath(
143
+ ".//w:del//w:instrText", namespaces=namespaces
144
+ ):
145
+ text_preview = (
146
+ repr(instr_elem.text or "")[:50] + "..."
147
+ if len(repr(instr_elem.text or "")) > 50
148
+ else repr(instr_elem.text or "")
149
+ )
150
+ errors.append(
151
+ f" {xml_file.relative_to(self.unpacked_dir)}: "
152
+ f"Line {instr_elem.sourceline}: <w:instrText> found within <w:del> (use <w:delInstrText>): {text_preview}"
153
+ )
154
+
155
+ except (lxml.etree.XMLSyntaxError, Exception) as e:
156
+ errors.append(
157
+ f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
158
+ )
159
+
160
+ if errors:
161
+ print(f"FAILED - Found {len(errors)} deletion validation violations:")
162
+ for error in errors:
163
+ print(error)
164
+ return False
165
+ else:
166
+ if self.verbose:
167
+ print("PASSED - No w:t elements found within w:del elements")
168
+ return True
169
+
170
+ def count_paragraphs_in_unpacked(self):
171
+ count = 0
172
+
173
+ for xml_file in self.xml_files:
174
+ if xml_file.name != "document.xml":
175
+ continue
176
+
177
+ try:
178
+ root = lxml.etree.parse(str(xml_file)).getroot()
179
+ paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p")
180
+ count = len(paragraphs)
181
+ except Exception as e:
182
+ print(f"Error counting paragraphs in unpacked document: {e}")
183
+
184
+ return count
185
+
186
+ def count_paragraphs_in_original(self):
187
+ original = self.original_file
188
+ if original is None:
189
+ return 0
190
+
191
+ count = 0
192
+
193
+ try:
194
+ with tempfile.TemporaryDirectory() as temp_dir:
195
+ with zipfile.ZipFile(original, "r") as zip_ref:
196
+ safe_extract(zip_ref, Path(temp_dir))
197
+
198
+ doc_xml_path = temp_dir + "/word/document.xml"
199
+ root = lxml.etree.parse(doc_xml_path).getroot()
200
+
201
+ paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p")
202
+ count = len(paragraphs)
203
+
204
+ except Exception as e:
205
+ print(f"Error counting paragraphs in original document: {e}")
206
+
207
+ return count
208
+
209
+ def validate_insertions(self):
210
+ errors = []
211
+
212
+ for xml_file in self.xml_files:
213
+ if xml_file.name != "document.xml":
214
+ continue
215
+
216
+ try:
217
+ root = lxml.etree.parse(str(xml_file)).getroot()
218
+ namespaces = {"w": self.WORD_2006_NAMESPACE}
219
+
220
+ invalid_elements = root.xpath(
221
+ ".//w:ins//w:delText[not(ancestor::w:del)]", namespaces=namespaces
222
+ )
223
+
224
+ for elem in invalid_elements:
225
+ text_preview = (
226
+ repr(elem.text or "")[:50] + "..."
227
+ if len(repr(elem.text or "")) > 50
228
+ else repr(elem.text or "")
229
+ )
230
+ errors.append(
231
+ f" {xml_file.relative_to(self.unpacked_dir)}: "
232
+ f"Line {elem.sourceline}: <w:delText> within <w:ins>: {text_preview}"
233
+ )
234
+
235
+ except (lxml.etree.XMLSyntaxError, Exception) as e:
236
+ errors.append(
237
+ f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
238
+ )
239
+
240
+ if errors:
241
+ print(f"FAILED - Found {len(errors)} insertion validation violations:")
242
+ for error in errors:
243
+ print(error)
244
+ return False
245
+ else:
246
+ if self.verbose:
247
+ print("PASSED - No w:delText elements within w:ins elements")
248
+ return True
249
+
250
+ def compare_paragraph_counts(self):
251
+ new_count = self.count_paragraphs_in_unpacked()
252
+ if self.original_file is None:
253
+ print(f"\nParagraphs: {new_count}")
254
+ return
255
+
256
+ original_count = self.count_paragraphs_in_original()
257
+ diff = new_count - original_count
258
+ diff_str = f"+{diff}" if diff > 0 else str(diff)
259
+ print(f"\nParagraphs: {original_count} → {new_count} ({diff_str})")
260
+
261
+ def _parse_id_value(self, val: str, base: int = 16) -> int:
262
+ return int(val, base)
263
+
264
+ def validate_id_constraints(self):
265
+ errors = []
266
+ para_id_attr = f"{{{self.W14_NAMESPACE}}}paraId"
267
+ durable_id_attr = f"{{{self.W16CID_NAMESPACE}}}durableId"
268
+
269
+ for xml_file in self.xml_files:
270
+ try:
271
+ tree = lxml.etree.parse(str(xml_file))
272
+ is_numbering = lxml.etree.QName(tree.getroot()).localname == "numbering"
273
+ for elem in tree.iter():
274
+ if val := elem.get(para_id_attr):
275
+ try:
276
+ if self._parse_id_value(val, base=16) >= 0x80000000:
277
+ errors.append(
278
+ f" {xml_file.name}:{elem.sourceline}: paraId={val} >= 0x80000000"
279
+ )
280
+ except ValueError:
281
+ errors.append(
282
+ f" {xml_file.name}:{elem.sourceline}: "
283
+ f"paraId={val} is not valid hex"
284
+ )
285
+
286
+ if val := elem.get(durable_id_attr):
287
+ if is_numbering:
288
+ try:
289
+ if self._parse_id_value(val, base=10) >= 0x7FFFFFFF:
290
+ errors.append(
291
+ f" {xml_file.name}:{elem.sourceline}: "
292
+ f"durableId={val} >= 0x7FFFFFFF"
293
+ )
294
+ except ValueError:
295
+ errors.append(
296
+ f" {xml_file.name}:{elem.sourceline}: "
297
+ f"durableId={val} must be decimal in a numbering part"
298
+ )
299
+ else:
300
+ try:
301
+ if self._parse_id_value(val, base=16) >= 0x7FFFFFFF:
302
+ errors.append(
303
+ f" {xml_file.name}:{elem.sourceline}: "
304
+ f"durableId={val} >= 0x7FFFFFFF"
305
+ )
306
+ except ValueError:
307
+ errors.append(
308
+ f" {xml_file.name}:{elem.sourceline}: "
309
+ f"durableId={val} is not valid hex"
310
+ )
311
+ except lxml.etree.XMLSyntaxError:
312
+ continue
313
+
314
+ if errors:
315
+ print(f"FAILED - {len(errors)} ID constraint violations:")
316
+ for e in errors:
317
+ print(one_line(e, 300))
318
+ elif self.verbose:
319
+ print("PASSED - All paraId/durableId values within constraints")
320
+ return not errors
321
+
322
+ def _repeated_style_ids(self, styles_root) -> set[str]:
323
+ attr = f"{{{self.WORD_2006_NAMESPACE}}}styleId"
324
+ ids = Counter(s.get(attr) for s in styles_root.iter(f"{{{self.WORD_2006_NAMESPACE}}}style"))
325
+ return {i for i, n in ids.items() if i is not None and n > 1}
326
+
327
+ def _original_part(self, xml_file) -> bytes | None:
328
+ if self.original_file is None:
329
+ return None
330
+ name = xml_file.relative_to(self.unpacked_dir).as_posix()
331
+ try:
332
+ with zipfile.ZipFile(self.original_file) as zf:
333
+ return zf.read(name)
334
+ except (KeyError, OSError, zipfile.BadZipFile):
335
+ return None
336
+
337
+ def validate_style_ids(self):
338
+ errors = []
339
+ styles_tag = f"{{{self.WORD_2006_NAMESPACE}}}styles"
340
+ if self.original_file is None:
341
+ return True
342
+
343
+ for xml_file in self.xml_files:
344
+ try:
345
+ root = lxml.etree.parse(str(xml_file)).getroot()
346
+ if root.tag != styles_tag:
347
+ continue
348
+ repeated = self._repeated_style_ids(root)
349
+ original = self._original_part(xml_file) if repeated else None
350
+ if original is not None:
351
+ repeated -= self._repeated_style_ids(lxml.etree.fromstring(original))
352
+ except lxml.etree.XMLSyntaxError:
353
+ continue
354
+ errors.extend(
355
+ f" {xml_file.relative_to(self.unpacked_dir)}: style id {style_id!r:.40} is now "
356
+ f"defined more than once, and Word uses only the last definition, without "
357
+ f"warning. Delete the earlier ones"
358
+ for style_id in sorted(repeated)
359
+ )
360
+
361
+ if errors:
362
+ print(f"FAILED - Found {len(errors)} style id(s) defined more than once:")
363
+ for error in errors:
364
+ print(one_line(error, 300))
365
+ elif self.verbose:
366
+ print("PASSED - The edit defined no style id a second time")
367
+ return not errors
368
+
369
+ def validate_comment_markers(self):
370
+ errors = []
371
+
372
+ document_xml = None
373
+ comments_xml = None
374
+ for xml_file in self.xml_files:
375
+ if xml_file.name == "document.xml" and "word" in str(xml_file):
376
+ document_xml = xml_file
377
+ elif xml_file.name == "comments.xml":
378
+ comments_xml = xml_file
379
+
380
+ if not document_xml:
381
+ if self.verbose:
382
+ print("PASSED - No document.xml found (skipping comment validation)")
383
+ return True
384
+
385
+ try:
386
+ doc_root = lxml.etree.parse(str(document_xml)).getroot()
387
+ namespaces = {"w": self.WORD_2006_NAMESPACE}
388
+
389
+ range_starts = {
390
+ elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
391
+ for elem in doc_root.xpath(
392
+ ".//w:commentRangeStart", namespaces=namespaces
393
+ )
394
+ }
395
+ range_ends = {
396
+ elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
397
+ for elem in doc_root.xpath(
398
+ ".//w:commentRangeEnd", namespaces=namespaces
399
+ )
400
+ }
401
+ references = {
402
+ elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
403
+ for elem in doc_root.xpath(
404
+ ".//w:commentReference", namespaces=namespaces
405
+ )
406
+ }
407
+
408
+ orphaned_ends = range_ends - range_starts
409
+ for comment_id in sorted(
410
+ orphaned_ends, key=lambda x: int(x) if x and x.isdigit() else 0
411
+ ):
412
+ errors.append(
413
+ f' document.xml: commentRangeEnd id="{comment_id}" has no matching commentRangeStart'
414
+ )
415
+
416
+ orphaned_starts = range_starts - range_ends
417
+ for comment_id in sorted(
418
+ orphaned_starts, key=lambda x: int(x) if x and x.isdigit() else 0
419
+ ):
420
+ errors.append(
421
+ f' document.xml: commentRangeStart id="{comment_id}" has no matching commentRangeEnd'
422
+ )
423
+
424
+ comment_ids = set()
425
+ if comments_xml and comments_xml.exists():
426
+ comments_root = lxml.etree.parse(str(comments_xml)).getroot()
427
+ comment_ids = {
428
+ elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
429
+ for elem in comments_root.xpath(
430
+ ".//w:comment", namespaces=namespaces
431
+ )
432
+ }
433
+
434
+ marker_ids = range_starts | range_ends | references
435
+ invalid_refs = marker_ids - comment_ids
436
+ for comment_id in sorted(
437
+ invalid_refs, key=lambda x: int(x) if x and x.isdigit() else 0
438
+ ):
439
+ if comment_id:
440
+ errors.append(
441
+ f' document.xml: marker id="{comment_id}" references non-existent comment'
442
+ )
443
+
444
+ except (lxml.etree.XMLSyntaxError, Exception) as e:
445
+ errors.append(f" Error parsing XML: {e}")
446
+
447
+ if errors:
448
+ print(f"FAILED - {len(errors)} comment marker violations:")
449
+ for error in errors:
450
+ print(error)
451
+ return False
452
+ else:
453
+ if self.verbose:
454
+ print("PASSED - All comment markers properly paired")
455
+ return True
456
+
457
+ def repair(self) -> int:
458
+ repairs = super().repair()
459
+ repairs += self.repair_durableId()
460
+ return repairs
461
+
462
+ def repair_durableId(self) -> int:
463
+ DURABLE_ID_ATTRS = ("w16cid:durableId", "w16cex:durableId")
464
+ repairs = 0
465
+ renames: dict = {}
466
+
467
+ for xml_file in self.xml_files:
468
+ try:
469
+ content = xml_file.read_text(encoding="utf-8")
470
+ dom = defusedxml.minidom.parseString(content)
471
+ is_numbering = dom.documentElement.localName == "numbering"
472
+ base = 10 if is_numbering else 16
473
+ pending = []
474
+ seen_in_file = set()
475
+ modified = False
476
+
477
+ for elem in dom.getElementsByTagName("*"):
478
+ for attr_name in DURABLE_ID_ATTRS:
479
+ if not elem.hasAttribute(attr_name):
480
+ continue
481
+
482
+ durable_id = elem.getAttribute(attr_name)
483
+ try:
484
+ key = self._parse_id_value(durable_id, base=base)
485
+ needs_repair = key >= 0x7FFFFFFF
486
+ except ValueError:
487
+ key = durable_id
488
+ needs_repair = True
489
+
490
+ if needs_repair:
491
+ if key in seen_in_file:
492
+ value = random.randint(1, 0x7FFFFFFE)
493
+ else:
494
+ seen_in_file.add(key)
495
+ if key not in renames:
496
+ renames[key] = random.randint(1, 0x7FFFFFFE)
497
+ value = renames[key]
498
+ new_id = str(value) if is_numbering else f"{value:08X}"
499
+
500
+ elem.setAttribute(attr_name, new_id)
501
+ pending.append(
502
+ f" Repaired: {xml_file.name}: durableId {durable_id} → {new_id}"
503
+ )
504
+ modified = True
505
+
506
+ if modified:
507
+ xml_file.write_bytes(dom.toxml(encoding="UTF-8"))
508
+ for message in pending:
509
+ print(message)
510
+ repairs += len(pending)
511
+
512
+ except Exception:
513
+ pass
514
+
515
+ return repairs
516
+
517
+
518
+ if __name__ == "__main__":
519
+ raise RuntimeError("This module should not be run directly.")