statepatch 0.2.2__py3-none-any.whl → 0.3.1__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.
statepatch/__init__.py CHANGED
@@ -7,7 +7,7 @@ stream at that path; removing it detaches it, live and reusable.
7
7
  """
8
8
 
9
9
  from ._core import Observable, Proxy, append, observable
10
- from ._wire import Listener, Op, Path, Segment, plain, snapshot
10
+ from ._wire import Listener, Op, Path, Segment, WireEncodingError, plain, snapshot
11
11
 
12
12
  __all__ = [
13
13
  "observable",
@@ -20,4 +20,5 @@ __all__ = [
20
20
  "Path",
21
21
  "Segment",
22
22
  "Listener",
23
+ "WireEncodingError",
23
24
  ]
statepatch/_wire.py CHANGED
@@ -21,6 +21,10 @@ _MAX_SAFE_INT = 2**53 - 1
21
21
  _MISSING: Any = object()
22
22
 
23
23
 
24
+ class WireEncodingError(ValueError):
25
+ """A value failed Statepatch's wire validation."""
26
+
27
+
24
28
  def _snapshot(node: Any) -> Any:
25
29
  from ._core import Observable, Proxy
26
30
 
@@ -59,6 +63,7 @@ def _adopt(value: Any, base: Path) -> tuple[Any, list[tuple[Path, "Observable"]]
59
63
  from ._core import Observable, Proxy
60
64
 
61
65
  mounts: list[tuple[Path, Observable]] = []
66
+ ancestors: set[int] = set()
62
67
 
63
68
  def walk(value: Any, path: Path) -> Any:
64
69
  if isinstance(value, Observable):
@@ -69,33 +74,51 @@ def _adopt(value: Any, base: Path) -> tuple[Any, list[tuple[Path, "Observable"]]
69
74
  if isinstance(value, bool) or value is None or isinstance(value, str):
70
75
  return value
71
76
  if isinstance(value, float):
77
+ # As JSON.stringify writes them.
72
78
  if math.isnan(value) or math.isinf(value):
73
- raise ValueError(f"{value!r} is not wire-encodable; floats must be finite")
79
+ return None
80
+ if value.is_integer() and abs(value) > _MAX_SAFE_INT:
81
+ raise WireEncodingError(
82
+ f"the number {value} at {_at(path)} is past the JS safe integer range; send it as a string"
83
+ )
74
84
  return value
75
85
  if isinstance(value, int):
76
86
  if abs(value) > _MAX_SAFE_INT:
77
- raise ValueError(
78
- f"integer {value} exceeds the JS safe range (|n| <= 2**53-1); send it as a string"
87
+ raise WireEncodingError(
88
+ f"the number {value} at {_at(path)} is past the JS safe integer range; send it as a string"
79
89
  )
80
90
  return value
81
91
  if isinstance(value, datetime):
82
92
  if value.tzinfo is None or value.tzinfo.utcoffset(value) is None:
83
- raise ValueError("naive datetime is not wire-encodable; attach a timezone")
93
+ raise WireEncodingError(f"a naive datetime at {_at(path)} is not wire-encodable; attach a timezone")
84
94
  return value
85
- if isinstance(value, (list, tuple)):
86
- return [walk(item, path + (i,)) for i, item in enumerate(value)]
87
- if isinstance(value, dict):
88
- out: dict[str, Any] = {}
89
- for key, item in value.items():
90
- if not isinstance(key, str):
91
- raise TypeError(f"object keys must be strings, got {type(key).__name__}")
92
- out[key] = walk(item, path + (key,))
93
- return out
94
- raise TypeError(f"{type(value).__name__} is not wire-encodable")
95
+ if isinstance(value, (list, tuple, dict)):
96
+ if id(value) in ancestors:
97
+ raise WireEncodingError(f"a cycle at {_at(path)} is not wire-encodable")
98
+ ancestors.add(id(value))
99
+ try:
100
+ if not isinstance(value, dict):
101
+ return [walk(item, path + (i,)) for i, item in enumerate(value)]
102
+ out: dict[str, Any] = {}
103
+ for key, item in value.items():
104
+ if not isinstance(key, str):
105
+ raise TypeError(f"object keys must be strings, got {type(key).__name__} at {_at(path)}")
106
+ out[key] = walk(item, path + (key,))
107
+ return out
108
+ finally:
109
+ ancestors.discard(id(value))
110
+ raise TypeError(f"a {type(value).__name__} at {_at(path)} is not wire-encodable")
95
111
 
96
112
  return walk(value, base), mounts
97
113
 
98
114
 
115
+ def _at(path: Path) -> str:
116
+ out = ""
117
+ for key in path:
118
+ out += f"[{key}]" if isinstance(key, int) else (f".{key}" if out else str(key))
119
+ return out or "the root"
120
+
121
+
99
122
  def _index(container: Any, key: Any) -> Any:
100
123
  if isinstance(container, list) and isinstance(key, int) and key < 0:
101
124
  return key + len(container)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: statepatch
3
- Version: 0.2.2
3
+ Version: 0.3.1
4
4
  Summary: Immer-style ops over a plain JSON tree: observables that emit every mutation as an op
5
5
  Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
6
6
  License-Expression: MIT
@@ -9,7 +9,7 @@ Description-Content-Type: text/markdown
9
9
 
10
10
  # statepatch
11
11
 
12
- Immer-style ops over a plain JSON tree: `observable(initial)` wraps one value, `.value` reads it, and every mutation emits the matching `replace` / `add` / `remove` op to subscribers. Observables compose: one stored inside another mounts its op stream at that path. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), under `statewire` and `pinned`.
12
+ Immer-style ops over a plain JSON tree: `observable(initial)` wraps one value, `.value` reads it, and every mutation emits the matching `replace` / `add` / `remove` op to subscribers. Observables compose: one stored inside another mounts its op stream at that path. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), under `statewire` and Pinboard.
13
13
 
14
14
  ## Install
15
15
 
@@ -31,8 +31,12 @@ run["queue"].append({"id": "q1"}) # forwarded as add at ["runs", 0, "queue", 0]
31
31
  state["runs"].pop(0) # remove op; run is detached and reusable
32
32
  ```
33
33
 
34
+ ## Validation
35
+
36
+ `from statepatch import WireEncodingError` exposes the `ValueError` subclass for invalid wire values.
37
+
34
38
  ## Docs
35
39
 
36
- - Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/reference/packages/page.mdx
37
- - Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/guides/statewire/host/page.mdx
38
- - Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/spec/statewire-protocol/statepatch/page.mdx
40
+ - Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/docs/reference/packages/page.mdx
41
+ - Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/guides/statewire/host/page.mdx
42
+ - Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/src/app/statewire/docs/spec/statewire-protocol/statepatch/page.mdx
@@ -0,0 +1,6 @@
1
+ statepatch/__init__.py,sha256=XoHpDb8Kj8pq2ThmMTdfOHO31ughbii-pdW-LXx5R4I,661
2
+ statepatch/_core.py,sha256=lP_EJmpxp0oYkBIA43MsmVsevDScpxleatkiIQC-RWE,16563
3
+ statepatch/_wire.py,sha256=pyl5Ogajm6CTPM-NMYpAeGE-qn08yC8cRPvEi9y3_QI,4460
4
+ statepatch-0.3.1.dist-info/METADATA,sha256=SFjrUr9MlflIccXSLE6YYSoHlvNXytIAF4kzlt-4RpM,1619
5
+ statepatch-0.3.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ statepatch-0.3.1.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.0
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,6 +0,0 @@
1
- statepatch/__init__.py,sha256=feJjPX5yyOk0xCHx0mvXK1goVjzHgyM4yNax0RVzIOA,617
2
- statepatch/_core.py,sha256=lP_EJmpxp0oYkBIA43MsmVsevDScpxleatkiIQC-RWE,16563
3
- statepatch/_wire.py,sha256=tWYFXl5J6EiE5VHMUV5W1mrVABXBY-offNigZhbGZ70,3564
4
- statepatch-0.2.2.dist-info/METADATA,sha256=AWtW9dl8Q7-1Q0vDKtS34Tz1ftq3vFbs-3dkoGmDv9g,1469
5
- statepatch-0.2.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
6
- statepatch-0.2.2.dist-info/RECORD,,