wolfdocx 0.1.0__py3-none-any.whl

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 (54) hide show
  1. wolfdocx/__init__.py +25 -0
  2. wolfdocx/_cache_root.py +24 -0
  3. wolfdocx/_comment_threads.py +278 -0
  4. wolfdocx/_inspection_cache.py +374 -0
  5. wolfdocx/_version.py +3 -0
  6. wolfdocx/admission.py +163 -0
  7. wolfdocx/assembly.py +463 -0
  8. wolfdocx/authoring.py +2773 -0
  9. wolfdocx/canonical.py +267 -0
  10. wolfdocx/content.py +963 -0
  11. wolfdocx/document.py +215 -0
  12. wolfdocx/errors.py +169 -0
  13. wolfdocx/find_replace.py +1210 -0
  14. wolfdocx/formatting.py +3160 -0
  15. wolfdocx/inspect.py +3999 -0
  16. wolfdocx/model.py +1038 -0
  17. wolfdocx/numbering_authoring.py +1422 -0
  18. wolfdocx/output.py +13 -0
  19. wolfdocx/package.py +2313 -0
  20. wolfdocx/package_profile.py +128 -0
  21. wolfdocx/page_setup.py +2483 -0
  22. wolfdocx/paragraph_authoring.py +1842 -0
  23. wolfdocx/properties.py +2728 -0
  24. wolfdocx/protection.py +1909 -0
  25. wolfdocx/regions.py +1993 -0
  26. wolfdocx/render_warnings.py +106 -0
  27. wolfdocx/reporting.py +943 -0
  28. wolfdocx/review.py +2862 -0
  29. wolfdocx/run_text.py +117 -0
  30. wolfdocx/section_break.py +1810 -0
  31. wolfdocx/session_ops/__init__.py +45 -0
  32. wolfdocx/session_ops/_bridge.py +151 -0
  33. wolfdocx/session_ops/lists.py +104 -0
  34. wolfdocx/session_ops/paragraphs.py +39 -0
  35. wolfdocx/session_ops/rich_objects.py +2598 -0
  36. wolfdocx/session_ops/run_edits.py +70 -0
  37. wolfdocx/session_ops/runs.py +313 -0
  38. wolfdocx/session_ops/sections.py +109 -0
  39. wolfdocx/session_ops/styling.py +99 -0
  40. wolfdocx/session_ops/tables.py +247 -0
  41. wolfdocx/styles_authoring.py +2822 -0
  42. wolfdocx/table_cell_properties.py +1458 -0
  43. wolfdocx/table_column.py +1501 -0
  44. wolfdocx/table_delete.py +942 -0
  45. wolfdocx/table_insert.py +1114 -0
  46. wolfdocx/table_merge.py +1863 -0
  47. wolfdocx/table_properties.py +2429 -0
  48. wolfdocx/table_row_properties.py +1095 -0
  49. wolfdocx/table_structure.py +1044 -0
  50. wolfdocx/text_effects.py +1438 -0
  51. wolfdocx-0.1.0.dist-info/METADATA +127 -0
  52. wolfdocx-0.1.0.dist-info/RECORD +54 -0
  53. wolfdocx-0.1.0.dist-info/WHEEL +4 -0
  54. wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
wolfdocx/canonical.py ADDED
@@ -0,0 +1,267 @@
1
+ """Canonical, private-safe serialization and identity primitives.
2
+
3
+ This module separates persisted presentation JSON from compact semantic identity
4
+ JSON. Callers that need to omit volatile data must construct an explicit
5
+ model-specific projection before calling :func:`semantic_sha256`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ import stat
14
+ import zipfile
15
+ from collections.abc import Callable, Collection
16
+ from datetime import UTC, datetime, timedelta
17
+ from pathlib import Path
18
+ from typing import NoReturn, TypeAlias
19
+
20
+ JsonScalar: TypeAlias = None | bool | int | float | str
21
+ JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]
22
+ Clock: TypeAlias = Callable[[], datetime]
23
+
24
+ _DIAGNOSTIC_CODE_PATTERN = re.compile(r"[a-z][a-z0-9_]{0,127}")
25
+ _STATE_PATTERN = re.compile(r"[a-z][a-z0-9_]{0,63}")
26
+ _SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
27
+ _TIMESTAMP_PATTERN = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z")
28
+ _DETERMINISTIC_ZIP_TIME = (2020, 1, 1, 0, 0, 0)
29
+
30
+
31
+ class StrictJsonError(ValueError):
32
+ """Raised when JSON is structurally unsafe or contains a non-finite value."""
33
+
34
+
35
+ def pretty_json_text(value: object) -> str:
36
+ """Return canonical persisted JSON text with a final newline."""
37
+
38
+ return json.dumps(value, sort_keys=True, indent=2, ensure_ascii=True, allow_nan=False) + "\n"
39
+
40
+
41
+ def pretty_json_bytes(value: object) -> bytes:
42
+ """Return canonical persisted JSON encoded as UTF-8 bytes."""
43
+
44
+ return pretty_json_text(value).encode("utf-8")
45
+
46
+
47
+ def semantic_json_bytes(value: object) -> bytes:
48
+ """Return compact UTF-8 JSON bytes for an explicit semantic projection."""
49
+
50
+ return json.dumps(
51
+ value,
52
+ sort_keys=True,
53
+ separators=(",", ":"),
54
+ ensure_ascii=False,
55
+ allow_nan=False,
56
+ ).encode("utf-8")
57
+
58
+
59
+ def sha256_bytes(value: bytes) -> str:
60
+ """Return the exact-byte SHA-256 identity of ``value``."""
61
+
62
+ return hashlib.sha256(value).hexdigest()
63
+
64
+
65
+ def semantic_sha256(value: object) -> str:
66
+ """Return the SHA-256 identity of compact semantic JSON bytes."""
67
+
68
+ return sha256_bytes(semantic_json_bytes(value))
69
+
70
+
71
+ def sha256_file(path: str | Path, *, chunk_size: int = 64 * 1024) -> str:
72
+ """Return exact-byte SHA-256, using a bounded 64 KiB read buffer by default."""
73
+
74
+ if chunk_size <= 0:
75
+ raise ValueError("chunk_size must be positive")
76
+ digest = hashlib.sha256()
77
+ with Path(path).open("rb") as stream:
78
+ for chunk in iter(lambda: stream.read(chunk_size), b""):
79
+ digest.update(chunk)
80
+ return digest.hexdigest()
81
+
82
+
83
+ def strict_json_loads(value: str | bytes | bytearray) -> JsonValue:
84
+ """Load JSON while rejecting duplicate object keys and non-finite constants."""
85
+
86
+ decoded: object = json.loads(
87
+ value,
88
+ object_pairs_hook=_reject_duplicate_pairs,
89
+ parse_constant=_reject_nonfinite_constant,
90
+ )
91
+ return _json_value(decoded)
92
+
93
+
94
+ def portable_display_path(
95
+ value: str | Path,
96
+ *,
97
+ relative_to: str | Path | None = None,
98
+ ) -> str:
99
+ """Return a portable relative path or a redacted basename, never an absolute path."""
100
+
101
+ raw_value = str(value)
102
+ if "\\" in raw_value or (len(raw_value) > 1 and raw_value[1] == ":"):
103
+ return _redacted_basename(raw_value)
104
+ path = Path(value)
105
+ root = Path.cwd() if relative_to is None else Path(relative_to)
106
+ try:
107
+ return path.resolve().relative_to(root.resolve()).as_posix()
108
+ except (OSError, ValueError):
109
+ return _redacted_basename(raw_value)
110
+
111
+
112
+ def is_portable_display_path(value: object) -> bool:
113
+ """Return whether ``value`` is a bounded, relative POSIX display path."""
114
+
115
+ if (
116
+ type(value) is not str
117
+ or not value
118
+ or len(value) > 1024
119
+ or value.startswith("/")
120
+ or "\\" in value
121
+ or ":" in value
122
+ or "\r" in value
123
+ or "\n" in value
124
+ ):
125
+ return False
126
+ return all(part not in {"", ".", ".."} for part in value.split("/"))
127
+
128
+
129
+ def utc_now(*, clock: Clock | None = None) -> datetime:
130
+ """Return a UTC instant, accepting a deterministic clock for callers and tests."""
131
+
132
+ value = datetime.now(UTC) if clock is None else clock()
133
+ if value.tzinfo is None or value.utcoffset() != timedelta(0):
134
+ raise ValueError("clock must return a UTC datetime")
135
+ return value.astimezone(UTC)
136
+
137
+
138
+ def serialize_utc_timestamp(value: datetime) -> str:
139
+ """Serialize an aware UTC timestamp using the canonical ``Z`` spelling."""
140
+
141
+ if value.tzinfo is None or value.utcoffset() != timedelta(0):
142
+ raise ValueError("timestamp must be UTC")
143
+ return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
144
+
145
+
146
+ def parse_utc_timestamp(value: object) -> datetime:
147
+ """Parse only canonical UTC timestamps that use the ``Z`` suffix."""
148
+
149
+ if type(value) is not str or _TIMESTAMP_PATTERN.fullmatch(value) is None:
150
+ raise ValueError("timestamp must use canonical UTC format")
151
+ try:
152
+ return datetime.fromisoformat(f"{value[:-1]}+00:00")
153
+ except ValueError as exc:
154
+ raise ValueError("timestamp must use canonical UTC format") from exc
155
+
156
+
157
+ def deterministic_zip_info(name: str, *, mode: int = 0o600) -> zipfile.ZipInfo:
158
+ """Build deterministic regular-file ZIP metadata with private permissions."""
159
+
160
+ if type(name) is not str or not name:
161
+ raise ValueError("zip entry name must be non-empty")
162
+ if type(mode) is not int or not 0 <= mode <= 0o777:
163
+ raise ValueError("zip entry mode must be a permission mask")
164
+ metadata = zipfile.ZipInfo(name, date_time=_DETERMINISTIC_ZIP_TIME)
165
+ metadata.create_system = 3
166
+ metadata.compress_type = zipfile.ZIP_DEFLATED
167
+ metadata.external_attr = (stat.S_IFREG | mode) << 16
168
+ return metadata
169
+
170
+
171
+ def is_diagnostic_code(value: object) -> bool:
172
+ """Return whether ``value`` is a bounded structural diagnostic code."""
173
+
174
+ return type(value) is str and _DIAGNOSTIC_CODE_PATTERN.fullmatch(value) is not None
175
+
176
+
177
+ def safe_diagnostic_code(value: object, *, fallback: str) -> str:
178
+ """Keep only an allow-listed diagnostic shape; otherwise return ``fallback``."""
179
+
180
+ if not is_diagnostic_code(fallback):
181
+ raise ValueError("diagnostic fallback must be a code")
182
+ if type(value) is str and _DIAGNOSTIC_CODE_PATTERN.fullmatch(value) is not None:
183
+ return value
184
+ return fallback
185
+
186
+
187
+ def is_state(value: object) -> bool:
188
+ """Return whether ``value`` is a bounded structural state code."""
189
+
190
+ return type(value) is str and _STATE_PATTERN.fullmatch(value) is not None
191
+
192
+
193
+ def safe_state(value: object, *, fallback: str) -> str:
194
+ """Keep only a structural state code; otherwise return ``fallback``."""
195
+
196
+ if not is_state(fallback):
197
+ raise ValueError("state fallback must be a state code")
198
+ if type(value) is str and _STATE_PATTERN.fullmatch(value) is not None:
199
+ return value
200
+ return fallback
201
+
202
+
203
+ def allow_state(value: object, *, allowed: Collection[str], fallback: str) -> str:
204
+ """Return an explicitly allowed state or a caller-declared safe fallback."""
205
+
206
+ if fallback not in allowed:
207
+ raise ValueError("state fallback must be allowed")
208
+ if type(value) is str and value in allowed:
209
+ return value
210
+ return fallback
211
+
212
+
213
+ def is_sha256(value: object) -> bool:
214
+ """Return whether ``value`` is a lowercase SHA-256 hex digest."""
215
+
216
+ return type(value) is str and _SHA256_PATTERN.fullmatch(value) is not None
217
+
218
+
219
+ def safe_sha256(value: object) -> str | None:
220
+ """Return a structurally valid digest, otherwise redact it to ``None``."""
221
+
222
+ if type(value) is str and _SHA256_PATTERN.fullmatch(value) is not None:
223
+ return value
224
+ return None
225
+
226
+
227
+ def _reject_duplicate_pairs(pairs: list[tuple[str, object]]) -> dict[str, JsonValue]:
228
+ result: dict[str, JsonValue] = {}
229
+ for key, item in pairs:
230
+ if key in result:
231
+ raise StrictJsonError("duplicate JSON object key")
232
+ result[key] = _json_value(item)
233
+ return result
234
+
235
+
236
+ def _reject_nonfinite_constant(value: str) -> NoReturn:
237
+ raise StrictJsonError(f"non-finite JSON constant: {value}")
238
+
239
+
240
+ def _json_value(value: object) -> JsonValue:
241
+ if value is None:
242
+ return None
243
+ if type(value) is bool:
244
+ return value
245
+ if type(value) is int:
246
+ return value
247
+ if type(value) is float:
248
+ return value
249
+ if type(value) is str:
250
+ return value
251
+ if type(value) is list:
252
+ return [_json_value(item) for item in value]
253
+ if type(value) is dict:
254
+ result: dict[str, JsonValue] = {}
255
+ for key, item in value.items():
256
+ if type(key) is not str:
257
+ raise StrictJsonError("JSON object key must be a string")
258
+ result[key] = _json_value(item)
259
+ return result
260
+ raise StrictJsonError("JSON value has an unsupported type")
261
+
262
+
263
+ def _redacted_basename(value: str) -> str:
264
+ candidate = value.replace("\\", "/").rsplit("/", maxsplit=1)[-1]
265
+ if candidate in {"", ".", ".."} or ":" in candidate:
266
+ return "artifact"
267
+ return candidate