itself 0.2.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.
itself/_filesystem.py ADDED
@@ -0,0 +1,187 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Small filesystem primitives with explicit overwrite and durability semantics."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import ctypes
9
+ import errno
10
+ import os
11
+ import stat
12
+ import sys
13
+ from contextlib import suppress
14
+ from pathlib import Path
15
+
16
+ _AT_FDCWD = -100
17
+ _RENAME_NOREPLACE = 1
18
+ _RENAME_EXCL = 0x00000004
19
+
20
+
21
+ class AtomicPublishUnavailableError(OSError):
22
+ """Raised when a platform cannot atomically publish without replacement."""
23
+
24
+
25
+ def _require_private_directory(path: Path) -> None:
26
+ metadata = path.lstat()
27
+ if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode):
28
+ raise OSError(f"private path component is not a real directory: {path}")
29
+ if os.name == "posix" and stat.S_IMODE(metadata.st_mode) & (
30
+ stat.S_IRWXG | stat.S_IRWXO
31
+ ):
32
+ raise PermissionError(
33
+ f"private directory grants group or other permissions: {path}"
34
+ )
35
+
36
+
37
+ def ensure_private_directory(root: Path, path: Path) -> None:
38
+ """Create a private directory below an existing private boundary."""
39
+
40
+ root = Path(root)
41
+ path = Path(path)
42
+ try:
43
+ relative = path.relative_to(root)
44
+ except ValueError as error:
45
+ raise ValueError("private directory must remain below its boundary") from error
46
+ if any(part in {"", ".", ".."} for part in relative.parts):
47
+ raise ValueError("private directory must remain below its boundary")
48
+
49
+ _require_private_directory(root)
50
+ current = root
51
+ for part in relative.parts:
52
+ current /= part
53
+ with suppress(FileExistsError):
54
+ current.mkdir(mode=stat.S_IRWXU)
55
+ _require_private_directory(current)
56
+
57
+
58
+ def fsync_directory(path: Path) -> None:
59
+ """Synchronize a directory entry update on platforms that support it."""
60
+
61
+ if os.name != "posix":
62
+ return
63
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
64
+ descriptor = os.open(path, flags)
65
+ try:
66
+ os.fsync(descriptor)
67
+ finally:
68
+ os.close(descriptor)
69
+
70
+
71
+ def write_file_exclusive(
72
+ path: Path,
73
+ content: bytes,
74
+ *,
75
+ mode: int,
76
+ ) -> None:
77
+ """Create, synchronize, and close one file without replacing any path."""
78
+
79
+ descriptor = os.open(
80
+ path,
81
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,
82
+ mode,
83
+ )
84
+ try:
85
+ with os.fdopen(descriptor, "wb") as handle:
86
+ handle.write(content)
87
+ handle.flush()
88
+ os.fsync(handle.fileno())
89
+ except BaseException:
90
+ path.unlink(missing_ok=True)
91
+ raise
92
+
93
+
94
+ def write_private_file_exclusive(path: Path, content: bytes) -> None:
95
+ """Create one owner-readable file without replacing an existing path."""
96
+
97
+ write_file_exclusive(
98
+ path,
99
+ content,
100
+ mode=stat.S_IRUSR | stat.S_IWUSR,
101
+ )
102
+
103
+
104
+ def _raise_rename_error(error_number: int, destination: Path) -> None:
105
+ if error_number in {errno.EEXIST, errno.ENOTEMPTY}:
106
+ raise FileExistsError(
107
+ error_number,
108
+ os.strerror(error_number),
109
+ destination,
110
+ )
111
+ raise OSError(error_number, os.strerror(error_number), destination)
112
+
113
+
114
+ def _linux_rename_no_replace(source: Path, destination: Path) -> None:
115
+ library = ctypes.CDLL(None, use_errno=True)
116
+ try:
117
+ renameat2 = library.renameat2
118
+ except AttributeError as error:
119
+ raise AtomicPublishUnavailableError(
120
+ errno.ENOTSUP,
121
+ "libc does not expose renameat2 with RENAME_NOREPLACE",
122
+ ) from error
123
+ renameat2.argtypes = (
124
+ ctypes.c_int,
125
+ ctypes.c_char_p,
126
+ ctypes.c_int,
127
+ ctypes.c_char_p,
128
+ ctypes.c_uint,
129
+ )
130
+ renameat2.restype = ctypes.c_int
131
+ result = renameat2(
132
+ _AT_FDCWD,
133
+ os.fsencode(source),
134
+ _AT_FDCWD,
135
+ os.fsencode(destination),
136
+ _RENAME_NOREPLACE,
137
+ )
138
+ if result != 0:
139
+ _raise_rename_error(ctypes.get_errno(), destination)
140
+
141
+
142
+ def _darwin_rename_no_replace(source: Path, destination: Path) -> None:
143
+ library = ctypes.CDLL(None, use_errno=True)
144
+ try:
145
+ renamex_np = library.renamex_np
146
+ except AttributeError as error:
147
+ raise AtomicPublishUnavailableError(
148
+ errno.ENOTSUP,
149
+ "libc does not expose renamex_np with RENAME_EXCL",
150
+ ) from error
151
+ renamex_np.argtypes = (
152
+ ctypes.c_char_p,
153
+ ctypes.c_char_p,
154
+ ctypes.c_uint,
155
+ )
156
+ renamex_np.restype = ctypes.c_int
157
+ result = renamex_np(
158
+ os.fsencode(source),
159
+ os.fsencode(destination),
160
+ _RENAME_EXCL,
161
+ )
162
+ if result != 0:
163
+ _raise_rename_error(ctypes.get_errno(), destination)
164
+
165
+
166
+ def publish_path_no_replace(source: Path, destination: Path) -> None:
167
+ """Atomically rename a sibling path while refusing every existing target."""
168
+
169
+ source = Path(source)
170
+ destination = Path(destination)
171
+ if os.path.abspath(source.parent) != os.path.abspath(destination.parent):
172
+ raise ValueError("atomic publication requires sibling source and destination")
173
+ source_metadata = source.lstat()
174
+ if stat.S_ISLNK(source_metadata.st_mode):
175
+ raise OSError(f"publication source must not be a symbolic link: {source}")
176
+
177
+ if sys.platform.startswith("linux"):
178
+ _linux_rename_no_replace(source, destination)
179
+ elif sys.platform == "darwin":
180
+ _darwin_rename_no_replace(source, destination)
181
+ elif os.name == "nt":
182
+ os.rename(source, destination)
183
+ else:
184
+ raise AtomicPublishUnavailableError(
185
+ errno.ENOTSUP,
186
+ f"atomic no-replace publication is unsupported on {sys.platform}",
187
+ )
itself/_formats.py ADDED
@@ -0,0 +1,104 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """The JSON Schema format checker for Itself's own schemas."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from collections.abc import Callable
10
+ from typing import Final
11
+
12
+ from jsonschema import FormatChecker
13
+
14
+ # The URI-reference rule of RFC 3986, appendix A, one named rule at a time.
15
+ # The pattern uses only syntax that Python and JavaScript read the same way,
16
+ # so the JavaScript conformance runner can use it verbatim. ABNF strings are
17
+ # case-insensitive, so IPvFuture's "v" also matches "V".
18
+ _HEXDIG: Final = "0-9A-Fa-f"
19
+ _UNRESERVED: Final = "A-Za-z0-9._~\\-"
20
+ _SUB_DELIMS: Final = "!$&'()*+,;="
21
+ _PCT_ENCODED: Final = f"%[{_HEXDIG}]{{2}}"
22
+ _PCHAR: Final = f"(?:[{_UNRESERVED}{_SUB_DELIMS}:@]|{_PCT_ENCODED})"
23
+ _SEGMENT: Final = f"{_PCHAR}*"
24
+ _SEGMENT_NZ: Final = f"{_PCHAR}+"
25
+ _SEGMENT_NZ_NC: Final = f"(?:[{_UNRESERVED}{_SUB_DELIMS}@]|{_PCT_ENCODED})+"
26
+ _PATH_ABEMPTY: Final = f"(?:/{_SEGMENT})*"
27
+ _PATH_ABSOLUTE: Final = f"/(?:{_SEGMENT_NZ}(?:/{_SEGMENT})*)?"
28
+ _PATH_NOSCHEME: Final = f"{_SEGMENT_NZ_NC}(?:/{_SEGMENT})*"
29
+ _PATH_ROOTLESS: Final = f"{_SEGMENT_NZ}(?:/{_SEGMENT})*"
30
+ _H16: Final = f"[{_HEXDIG}]{{1,4}}"
31
+ _DEC_OCTET: Final = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])"
32
+ _IPV4ADDRESS: Final = f"{_DEC_OCTET}(?:\\.{_DEC_OCTET}){{3}}"
33
+ _LS32: Final = f"(?:{_H16}:{_H16}|{_IPV4ADDRESS})"
34
+ _IPV6ADDRESS: Final = (
35
+ "(?:"
36
+ + "|".join(
37
+ (
38
+ f"(?:{_H16}:){{6}}{_LS32}",
39
+ f"::(?:{_H16}:){{5}}{_LS32}",
40
+ f"(?:{_H16})?::(?:{_H16}:){{4}}{_LS32}",
41
+ f"(?:(?:{_H16}:){{0,1}}{_H16})?::(?:{_H16}:){{3}}{_LS32}",
42
+ f"(?:(?:{_H16}:){{0,2}}{_H16})?::(?:{_H16}:){{2}}{_LS32}",
43
+ f"(?:(?:{_H16}:){{0,3}}{_H16})?::{_H16}:{_LS32}",
44
+ f"(?:(?:{_H16}:){{0,4}}{_H16})?::{_LS32}",
45
+ f"(?:(?:{_H16}:){{0,5}}{_H16})?::{_H16}",
46
+ f"(?:(?:{_H16}:){{0,6}}{_H16})?::",
47
+ )
48
+ )
49
+ + ")"
50
+ )
51
+ _IPVFUTURE: Final = f"[Vv][{_HEXDIG}]+\\.[{_UNRESERVED}{_SUB_DELIMS}:]+"
52
+ _IP_LITERAL: Final = f"\\[(?:{_IPV6ADDRESS}|{_IPVFUTURE})\\]"
53
+ _REG_NAME: Final = f"(?:[{_UNRESERVED}{_SUB_DELIMS}]|{_PCT_ENCODED})*"
54
+ _HOST: Final = f"(?:{_IP_LITERAL}|{_IPV4ADDRESS}|{_REG_NAME})"
55
+ _USERINFO: Final = f"(?:[{_UNRESERVED}{_SUB_DELIMS}:]|{_PCT_ENCODED})*"
56
+ _AUTHORITY: Final = f"(?:{_USERINFO}@)?{_HOST}(?::[0-9]*)?"
57
+ _QUERY: Final = f"(?:{_PCHAR}|[/?])*"
58
+ _SCHEME: Final = "[A-Za-z][A-Za-z0-9+.\\-]*"
59
+ _HIER_PART: Final = (
60
+ f"(?://{_AUTHORITY}{_PATH_ABEMPTY}|{_PATH_ABSOLUTE}|{_PATH_ROOTLESS}|)"
61
+ )
62
+ _RELATIVE_PART: Final = (
63
+ f"(?://{_AUTHORITY}{_PATH_ABEMPTY}|{_PATH_ABSOLUTE}|{_PATH_NOSCHEME}|)"
64
+ )
65
+ _URI: Final = f"{_SCHEME}:{_HIER_PART}(?:\\?{_QUERY})?(?:#{_QUERY})?"
66
+ _RELATIVE_REF: Final = f"{_RELATIVE_PART}(?:\\?{_QUERY})?(?:#{_QUERY})?"
67
+
68
+ URI_REFERENCE_PATTERN: Final = f"(?:{_URI}|{_RELATIVE_REF})"
69
+ """RFC 3986 URI-reference, unanchored; it must match a whole string."""
70
+
71
+ _URI_REFERENCE: Final = re.compile(URI_REFERENCE_PATTERN)
72
+
73
+
74
+ def _is_uri_reference(instance: object) -> bool:
75
+ return (
76
+ not isinstance(instance, str) or _URI_REFERENCE.fullmatch(instance) is not None
77
+ )
78
+
79
+
80
+ def _without_final_line_break(
81
+ check: Callable[[object], bool],
82
+ ) -> Callable[[object], bool]:
83
+ def strict(instance: object) -> bool:
84
+ if isinstance(instance, str) and instance.endswith("\n"):
85
+ return False
86
+ return check(instance)
87
+
88
+ return strict
89
+
90
+
91
+ def schema_format_checker() -> FormatChecker:
92
+ """Return the format checker for Itself's schemas.
93
+
94
+ ``uri-reference`` is checked against RFC 3986 with the SDK's own pattern,
95
+ whichever URI library is installed. jsonschema checks ``date-time`` with
96
+ an anchored regular expression whose ``$`` also matches before a final
97
+ newline, so a timestamp followed by a newline is refused here.
98
+ """
99
+
100
+ checker = FormatChecker()
101
+ date_time, raises = checker.checkers["date-time"]
102
+ checker.checkers["date-time"] = (_without_final_line_break(date_time), raises)
103
+ checker.checkers["uri-reference"] = (_is_uri_reference, ())
104
+ return checker
itself/_json.py ADDED
@@ -0,0 +1,223 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Strict JSON decoding shared by every untrusted document boundary."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import math
10
+ from collections.abc import Iterable, Iterator
11
+ from typing import NoReturn, TypeAlias, cast
12
+
13
+ from .types import JsonObject, JsonValue
14
+
15
+ _MAX_SAFE_INTEGER = 2**53 - 1
16
+ _MIN_SAFE_INTEGER = -_MAX_SAFE_INTEGER
17
+ _MAX_NESTING_DEPTH = 128
18
+ _CONTAINERS: tuple[type[object], ...] = (list, dict)
19
+
20
+ _OpenValue: TypeAlias = tuple[Iterator[tuple[object, object]], bool]
21
+ """An open array or object: its member iterator and whether it has keys."""
22
+
23
+
24
+ class IJsonError(ValueError):
25
+ """Raised when a value cannot be represented unambiguously as I-JSON."""
26
+
27
+
28
+ def format_json_path(path: Iterable[object]) -> str:
29
+ """Render one jsonschema-style absolute path for a diagnostic."""
30
+
31
+ values = tuple(path)
32
+ if not values:
33
+ return "$"
34
+ return "$" + "".join(
35
+ f"[{item}]" if isinstance(item, int) else f".{item}" for item in values
36
+ )
37
+
38
+
39
+ def _reject_nonstandard_constant(value: str) -> NoReturn:
40
+ raise ValueError(f"non-standard JSON numeric constant {value!r}")
41
+
42
+
43
+ def _parse_integer(value: str) -> int:
44
+ parsed = int(value)
45
+ if value.startswith("-") and parsed == 0:
46
+ raise IJsonError("negative zero is not accepted")
47
+ if parsed < _MIN_SAFE_INTEGER or parsed > _MAX_SAFE_INTEGER:
48
+ raise IJsonError(
49
+ f"integer {value} exceeds the interoperable IEEE 754 safe range"
50
+ )
51
+ return parsed
52
+
53
+
54
+ def _parse_float(value: str) -> float:
55
+ parsed = float(value)
56
+ if not math.isfinite(parsed):
57
+ raise IJsonError(f"number {value} is not a finite IEEE 754 value")
58
+ if parsed == 0:
59
+ if value.startswith("-"):
60
+ raise IJsonError("negative zero is not accepted")
61
+ # A zero result from a nonzero mantissa underflowed. Reading the
62
+ # digits keeps any exponent JSON allows in range, which Decimal's is not.
63
+ mantissa = value.lower().partition("e")[0]
64
+ if any(digit in "123456789" for digit in mantissa):
65
+ raise IJsonError(f"number {value} underflows IEEE 754 binary64")
66
+ return parsed
67
+
68
+
69
+ def _object_without_duplicate_keys(
70
+ pairs: list[tuple[str, JsonValue]],
71
+ ) -> JsonObject:
72
+ value: JsonObject = {}
73
+ for key, item in pairs:
74
+ try:
75
+ key.encode("utf-8")
76
+ except UnicodeEncodeError as error:
77
+ raise IJsonError("object key contains a Unicode surrogate") from error
78
+ if key in value:
79
+ raise ValueError(f"duplicate JSON object key {key!r}")
80
+ value[key] = item
81
+ return value
82
+
83
+
84
+ def _scalar_violation(value: object) -> str | None:
85
+ """Return why a value other than an array or object is not I-JSON, or None."""
86
+
87
+ if value is None or isinstance(value, bool):
88
+ return None
89
+ if isinstance(value, int):
90
+ if value < _MIN_SAFE_INTEGER or value > _MAX_SAFE_INTEGER:
91
+ return "integer exceeds the interoperable IEEE 754 safe range"
92
+ return None
93
+ if isinstance(value, float):
94
+ if not math.isfinite(value):
95
+ return "number is not finite"
96
+ if not value and math.copysign(1.0, value) < 0:
97
+ return "negative zero is not accepted"
98
+ return None
99
+ if isinstance(value, str):
100
+ # An ASCII string cannot hold a surrogate, so only others are encoded.
101
+ if not value.isascii():
102
+ try:
103
+ value.encode("utf-8")
104
+ except UnicodeEncodeError:
105
+ return "string contains a Unicode surrogate"
106
+ return None
107
+ return f"{type(value).__name__} is not a JSON value"
108
+
109
+
110
+ def _object_key_violation(key: object) -> str | None:
111
+ """Return why an object key is not I-JSON, or None."""
112
+
113
+ if not isinstance(key, str):
114
+ return "object key is not a string"
115
+ if not key.isascii():
116
+ try:
117
+ key.encode("utf-8")
118
+ except UnicodeEncodeError:
119
+ return "object key contains a Unicode surrogate"
120
+ return None
121
+
122
+
123
+ def _opened(value: object) -> _OpenValue | None:
124
+ if isinstance(value, list):
125
+ return enumerate(cast(list[object], value)), False
126
+ if isinstance(value, dict):
127
+ return iter(cast(dict[object, object], value).items()), True
128
+ return None
129
+
130
+
131
+ def _segment(key: object, is_object: bool) -> str:
132
+ return f".{key}" if is_object else f"[{key}]"
133
+
134
+
135
+ def _require_i_json(value: object, path: str, max_depth: int) -> None:
136
+ opened = _opened(value)
137
+ if opened is None:
138
+ violation = _scalar_violation(value)
139
+ if violation is not None:
140
+ raise IJsonError(f"{path}: {violation}")
141
+ return
142
+ # The stack holds one member iterator per open array or object, so its
143
+ # height is the nesting depth. Each iterator resumes where it paused, which
144
+ # keeps checks in document order. Each level keeps only the path segment
145
+ # that leads to it, and a full path is rendered only for a violation, so
146
+ # memory grows linearly with depth. An open container that is reached
147
+ # again contains itself, and no finite JSON text can represent it.
148
+ open_values = [opened]
149
+ segments = [path]
150
+ open_ids = [id(value)]
151
+ while open_values:
152
+ members, is_object = open_values[-1]
153
+ for key, member in members:
154
+ if is_object:
155
+ key_violation = _object_key_violation(key)
156
+ if key_violation is not None:
157
+ raise IJsonError(f"{''.join(segments)}: {key_violation}")
158
+ nested = _opened(member)
159
+ if nested is not None:
160
+ if id(member) in open_ids:
161
+ raise IJsonError(
162
+ f"{''.join(segments)}{_segment(key, is_object)}: "
163
+ "value contains itself"
164
+ )
165
+ if len(open_values) >= max_depth:
166
+ raise IJsonError(f"JSON nesting exceeds {max_depth} levels")
167
+ open_values.append(nested)
168
+ segments.append(_segment(key, is_object))
169
+ open_ids.append(id(member))
170
+ break
171
+ violation = _scalar_violation(member)
172
+ if violation is not None:
173
+ raise IJsonError(
174
+ f"{''.join(segments)}{_segment(key, is_object)}: {violation}"
175
+ )
176
+ else:
177
+ open_values.pop()
178
+ segments.pop()
179
+ open_ids.pop()
180
+
181
+
182
+ def ensure_i_json(value: JsonValue, *, path: str = "$") -> None:
183
+ """Require the interoperable JSON value domain used by RFC 8785.
184
+
185
+ Values may nest at most 128 levels deep, the limit the strict reader
186
+ enforces, so every value that passes can be written and read back. The
187
+ walk keeps its own stack, so nesting cannot exhaust the interpreter's; it
188
+ refuses a value that contains itself and reports the first violation in
189
+ document order.
190
+ """
191
+
192
+ _require_i_json(value, path, _MAX_NESTING_DEPTH)
193
+
194
+
195
+ def strict_json_loads(source: str | bytes | bytearray) -> JsonValue:
196
+ """Decode unambiguous I-JSON with duplicate-key rejection.
197
+
198
+ Bytes must be UTF-8, as I-JSON requires, and a byte order mark is rejected
199
+ as it is in text. Values may nest at most 128 levels deep.
200
+ """
201
+
202
+ runtime_source = cast(object, source)
203
+ if isinstance(runtime_source, str):
204
+ text = runtime_source
205
+ elif isinstance(runtime_source, bytes | bytearray):
206
+ text = runtime_source.decode("utf-8")
207
+ else:
208
+ raise TypeError("JSON source must be str, bytes, or bytearray")
209
+ try:
210
+ value = cast(
211
+ JsonValue,
212
+ json.loads(
213
+ text,
214
+ object_pairs_hook=_object_without_duplicate_keys,
215
+ parse_constant=_reject_nonstandard_constant,
216
+ parse_float=_parse_float,
217
+ parse_int=_parse_integer,
218
+ ),
219
+ )
220
+ except RecursionError:
221
+ raise IJsonError("JSON nesting exceeds the supported depth") from None
222
+ _require_i_json(value, "$", _MAX_NESTING_DEPTH)
223
+ return value
itself/_version.py ADDED
@@ -0,0 +1,8 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Python distribution version."""
5
+
6
+ from typing import Final
7
+
8
+ __version__: Final = "0.2.0"