acid-cat-catalog 0.1.0__tar.gz

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.
@@ -0,0 +1,12 @@
1
+ node_modules/
2
+ dist/
3
+ .out/
4
+ .moon/cache/
5
+ .moon/docker/
6
+
7
+ # Private working notes and tools, kept out of the repository.
8
+ .local/
9
+ CLAUDE.local.md
10
+
11
+ # Task worktrees, one for each branch.
12
+ .worktrees/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hebilicious
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: acid-cat-catalog
3
+ Version: 0.1.0
4
+ Summary: Write an AcidCat catalog in Python and render it in canonical form.
5
+ Project-URL: Homepage, https://github.com/Hebilicious/acidcat/tree/main/packages/catalog/python#readme
6
+ Project-URL: Repository, https://github.com/Hebilicious/acidcat
7
+ Project-URL: Issues, https://github.com/Hebilicious/acidcat/issues
8
+ Author: Hebilicious
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: acidcat,catalog
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+
17
+ # acid-cat-catalog
18
+
19
+ The AcidCat catalog library for Python. PyPI package: `acid-cat-catalog`.
20
+
21
+ Write a catalog in Python, and write it in canonical form. The library uses only the standard library. Use it at build time to write `acidcat.catalog.json`.
22
+
23
+ ```sh
24
+ pip install acid-cat-catalog
25
+ ```
26
+
27
+ ```python
28
+ from pathlib import Path
29
+ from acid_cat_catalog import Catalog
30
+
31
+ catalog = Catalog(title="Living-room air conditioner")
32
+ catalog.target("cli", bindings=["cli"])
33
+ offline = catalog.type("Offline", {"type": "object"})
34
+ catalog.capability(
35
+ "aircon.power.set",
36
+ description="Turn the unit on or off.",
37
+ audience=["cli"],
38
+ input={"type": "object", "required": ["on"], "properties": {"on": {"type": "boolean"}}},
39
+ failures={"Offline": offline},
40
+ )
41
+
42
+ Path("acidcat.catalog.json").write_text(catalog.render())
43
+ ```
44
+
45
+ `validate()` lists the rules a catalog breaks, and `render()` raises `CatalogError` for one that breaks any. The full example is [`examples/aircon.py`](examples/aircon.py). Test with `moon run catalog-python:test`.
@@ -0,0 +1,29 @@
1
+ # acid-cat-catalog
2
+
3
+ The AcidCat catalog library for Python. PyPI package: `acid-cat-catalog`.
4
+
5
+ Write a catalog in Python, and write it in canonical form. The library uses only the standard library. Use it at build time to write `acidcat.catalog.json`.
6
+
7
+ ```sh
8
+ pip install acid-cat-catalog
9
+ ```
10
+
11
+ ```python
12
+ from pathlib import Path
13
+ from acid_cat_catalog import Catalog
14
+
15
+ catalog = Catalog(title="Living-room air conditioner")
16
+ catalog.target("cli", bindings=["cli"])
17
+ offline = catalog.type("Offline", {"type": "object"})
18
+ catalog.capability(
19
+ "aircon.power.set",
20
+ description="Turn the unit on or off.",
21
+ audience=["cli"],
22
+ input={"type": "object", "required": ["on"], "properties": {"on": {"type": "boolean"}}},
23
+ failures={"Offline": offline},
24
+ )
25
+
26
+ Path("acidcat.catalog.json").write_text(catalog.render())
27
+ ```
28
+
29
+ `validate()` lists the rules a catalog breaks, and `render()` raises `CatalogError` for one that breaks any. The full example is [`examples/aircon.py`](examples/aircon.py). Test with `moon run catalog-python:test`.
@@ -0,0 +1,162 @@
1
+ """Write an AcidCat catalog in Python, and render it to the JSON document the toolchain checks.
2
+
3
+ This is an authoring library, not a runtime: a program uses it to produce `acidcat.catalog.json`, and nothing reads
4
+ the catalog through it at runtime. See spec/catalog.md.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any, Mapping, Sequence
11
+
12
+ from .canonical import canonical_text
13
+
14
+ __all__ = ["Catalog", "CatalogError", "Schema", "canonical_text"]
15
+
16
+ Schema = dict[str, Any]
17
+ """A JSON Schema 2020-12 schema, written as a plain dict."""
18
+
19
+ _ID = re.compile(r"[a-z][a-z0-9]*(-[a-z0-9]+)*(\.[a-z][a-z0-9]*(-[a-z0-9]+)*)+")
20
+ _NAME = re.compile(r"[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)?")
21
+ _TYPE_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
22
+ _REFERENCE = re.compile(r"#/\$defs/([A-Za-z][A-Za-z0-9_]*)")
23
+
24
+
25
+ class CatalogError(ValueError):
26
+ """A catalog breaks a rule of the specification."""
27
+
28
+
29
+ class Catalog:
30
+ def __init__(self, title: str | None = None, description: str | None = None) -> None:
31
+ self._title = title
32
+ self._description = description
33
+ self._targets: dict[str, dict[str, Any]] = {}
34
+ self._types: dict[str, Schema] = {}
35
+ self._capabilities: dict[str, dict[str, Any]] = {}
36
+
37
+ def target(
38
+ self,
39
+ name: str,
40
+ bindings: Sequence[str],
41
+ description: str | None = None,
42
+ options: Mapping[str, Any] | None = None,
43
+ ) -> Catalog:
44
+ """Declare a target, served by `bindings` such as "typescript" and "webmcp"."""
45
+ if name in self._targets:
46
+ raise CatalogError(f"The target {name} is declared twice")
47
+ self._targets[name] = {"bindings": list(bindings), "description": description, "options": options}
48
+ return self
49
+
50
+ def type(self, name: str, schema: Schema) -> Schema:
51
+ """Declare a shared type, and get the schema that references it."""
52
+ if name in self._types:
53
+ raise CatalogError(f"The type {name} is declared twice")
54
+ self._types[name] = schema
55
+ return {"$ref": f"#/$defs/{name}"}
56
+
57
+ def capability(
58
+ self,
59
+ id: str,
60
+ description: str,
61
+ audience: Sequence[str] = (),
62
+ input: Schema | None = None,
63
+ output: Schema | None = None,
64
+ failures: Mapping[str, Schema] | None = None,
65
+ read_only: bool | None = None,
66
+ state: Schema | None = None,
67
+ ) -> Catalog:
68
+ """Declare a capability. A capability with no audience reaches no target."""
69
+ if id in self._capabilities:
70
+ raise CatalogError(f"The capability {id} is declared twice")
71
+ self._capabilities[id] = {
72
+ "description": description,
73
+ "audience": list(audience),
74
+ "input": input,
75
+ "output": output,
76
+ "failures": dict(failures) if failures else None,
77
+ "readOnly": read_only,
78
+ "state": state,
79
+ }
80
+ return self
81
+
82
+ def validate(self) -> list[str]:
83
+ """The catalog rules this catalog breaks. Empty when it conforms."""
84
+ problems: list[str] = []
85
+ for name, target in self._targets.items():
86
+ bindings = target["bindings"]
87
+ if not _NAME.fullmatch(name):
88
+ problems.append(f"the target name {name} is malformed")
89
+ if not bindings:
90
+ problems.append(f"the target {name} has no bindings")
91
+ if len(set(bindings)) != len(bindings):
92
+ problems.append(f"the target {name} repeats a binding")
93
+ problems += [f"the target {name} names the malformed binding {b}" for b in bindings if not _NAME.fullmatch(b)]
94
+ for name, schema in self._types.items():
95
+ if not _TYPE_NAME.fullmatch(name):
96
+ problems.append(f"the type name {name} is malformed")
97
+ problems += [f"the type {name} {problem}" for problem in self._reference_problems(schema)]
98
+ for id, capability in self._capabilities.items():
99
+ audience = capability["audience"]
100
+ if len(id) > 128 or not _ID.fullmatch(id):
101
+ problems.append(f"the id {id} is malformed")
102
+ if not capability["description"].strip():
103
+ problems.append(f"{id} has no description")
104
+ if len(set(audience)) != len(audience):
105
+ problems.append(f"{id} repeats a target in its audience")
106
+ problems += [f"{id} names the undeclared target {t}" for t in audience if t not in self._targets]
107
+ if capability["input"] is not None and self._resolve(capability["input"]).get("type") != "object":
108
+ problems.append(f"{id} input does not describe an object")
109
+ schemas = [capability["input"], capability["output"], capability["state"], *(capability["failures"] or {}).values()]
110
+ for schema in schemas:
111
+ if schema is not None:
112
+ problems += [f"{id} {problem}" for problem in self._reference_problems(schema)]
113
+ return problems
114
+
115
+ def to_json(self) -> dict[str, Any]:
116
+ """The catalog as a JSON value. Raises CatalogError when the catalog breaks a rule."""
117
+ problems = self.validate()
118
+ if problems:
119
+ raise CatalogError("The catalog does not conform:\n" + "\n".join(problems))
120
+ return _compact(
121
+ {
122
+ "acidcat": "0.1",
123
+ "title": self._title,
124
+ "description": self._description,
125
+ "targets": {name: _compact(target) for name, target in self._targets.items()},
126
+ "$defs": dict(self._types) or None,
127
+ "capabilities": {id: _compact(capability) for id, capability in self._capabilities.items()},
128
+ }
129
+ )
130
+
131
+ def render(self) -> str:
132
+ """The catalog as JSON text in canonical form, ready to write to `acidcat.catalog.json`."""
133
+ return canonical_text(self.to_json())
134
+
135
+ def _resolve(self, schema: Schema) -> Schema:
136
+ match = _REFERENCE.fullmatch(str(schema.get("$ref", "")))
137
+ return self._types.get(match.group(1), schema) if match else schema
138
+
139
+ def _reference_problems(self, schema: Any) -> list[str]:
140
+ problems: list[str] = []
141
+ for node in _objects(schema):
142
+ if "$defs" in node:
143
+ problems.append("carries its own $defs; declare shared types with type()")
144
+ if "$ref" in node:
145
+ match = _REFERENCE.fullmatch(str(node["$ref"]))
146
+ if not match or match.group(1) not in self._types:
147
+ problems.append(f"references {node['$ref']}, which is not a type")
148
+ return problems
149
+
150
+
151
+ def _compact(value: dict[str, Any]) -> dict[str, Any]:
152
+ return {key: member for key, member in value.items() if member is not None}
153
+
154
+
155
+ def _objects(value: Any):
156
+ if isinstance(value, list):
157
+ for item in value:
158
+ yield from _objects(item)
159
+ elif isinstance(value, dict):
160
+ yield value
161
+ for item in value.values():
162
+ yield from _objects(item)
@@ -0,0 +1,111 @@
1
+ """The canonical form of a catalog (spec/catalog.md#canonical-form).
2
+
3
+ The one way to write a catalog as text, so that every tool and every catalog library produces the same bytes for the same catalog.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import math
10
+ from decimal import Decimal
11
+ from typing import Any, Callable
12
+
13
+ _CATALOG_ORDER = ["acidcat", "title", "description", "targets", "$defs", "capabilities"]
14
+ _TARGET_ORDER = ["bindings", "description", "options"]
15
+ _CAPABILITY_ORDER = ["description", "audience", "input", "output", "failures", "readOnly", "state"]
16
+
17
+
18
+ def canonical_text(catalog: dict[str, Any]) -> str:
19
+ """A catalog in canonical form, as text."""
20
+ return _write(_catalog(catalog), "") + "\n"
21
+
22
+
23
+ def _catalog(catalog: dict[str, Any]) -> dict[str, Any]:
24
+ def member(key: str, value: Any) -> Any:
25
+ if key == "targets":
26
+ return _by_key(value, lambda target: _ordered(target, _TARGET_ORDER, lambda _, inner: _sorted(inner)))
27
+ if key == "$defs":
28
+ return _by_key(value, _sorted)
29
+ if key == "capabilities":
30
+ return _by_key(value, lambda capability: _ordered(capability, _CAPABILITY_ORDER, _capability_member))
31
+ return _sorted(value)
32
+
33
+ return _ordered(catalog, _CATALOG_ORDER, member)
34
+
35
+
36
+ def _capability_member(key: str, value: Any) -> Any:
37
+ return _by_key(value, _sorted) if key == "failures" else _sorted(value)
38
+
39
+
40
+ def _ordered(value: dict[str, Any], order: list[str], each: Callable[[str, Any], Any]) -> dict[str, Any]:
41
+ known = [key for key in order if key in value]
42
+ others = sorted(key for key in value if key not in order)
43
+ return {key: each(key, value[key]) for key in known + others}
44
+
45
+
46
+ def _by_key(value: dict[str, Any], each: Callable[[Any], Any]) -> dict[str, Any]:
47
+ return {key: each(value[key]) for key in sorted(value)}
48
+
49
+
50
+ def _sorted(value: Any) -> Any:
51
+ if isinstance(value, list):
52
+ return [_sorted(item) for item in value]
53
+ if isinstance(value, dict):
54
+ return _by_key(value, _sorted)
55
+ return value
56
+
57
+
58
+ def _write(value: Any, indent: str) -> str:
59
+ inner = indent + " "
60
+ if isinstance(value, dict):
61
+ if not value:
62
+ return "{}"
63
+ members = [f"{inner}{_string(key)}: {_write(item, inner)}" for key, item in value.items()]
64
+ return "{\n" + ",\n".join(members) + "\n" + indent + "}"
65
+ if isinstance(value, list):
66
+ if not value:
67
+ return "[]"
68
+ return "[\n" + ",\n".join(inner + _write(item, inner) for item in value) + "\n" + indent + "]"
69
+ if value is None:
70
+ return "null"
71
+ if value is True:
72
+ return "true"
73
+ if value is False:
74
+ return "false"
75
+ if isinstance(value, int):
76
+ return str(value)
77
+ if isinstance(value, float):
78
+ return _number(value)
79
+ if isinstance(value, str):
80
+ return _string(value)
81
+ raise TypeError(f"A catalog holds only JSON values, not {type(value).__name__}")
82
+
83
+
84
+ def _string(text: str) -> str:
85
+ return json.dumps(text, ensure_ascii=False)
86
+
87
+
88
+ def _number(value: float) -> str:
89
+ """Write a number the way ECMAScript's Number::toString does, from its shortest round-trip digits."""
90
+ if not math.isfinite(value):
91
+ raise ValueError("A catalog holds only finite numbers")
92
+ if value == 0:
93
+ return "0"
94
+ sign, digit_tuple, exponent = Decimal(repr(abs(value))).as_tuple()
95
+ digits = "".join(map(str, digit_tuple)).rstrip("0")
96
+ exponent += len(digit_tuple) - len(digits)
97
+ return ("-" if value < 0 else "") + _layout(digits, exponent + len(digits))
98
+
99
+
100
+ def _layout(digits: str, n: int) -> str:
101
+ """Lay out `0.<digits> × 10^n` as ECMAScript does."""
102
+ k = len(digits)
103
+ if k <= n <= 21:
104
+ return digits + "0" * (n - k)
105
+ if 0 < n <= 21:
106
+ return digits[:n] + "." + digits[n:]
107
+ if -6 < n <= 0:
108
+ return "0." + "0" * -n + digits
109
+ e = n - 1
110
+ mantissa = digits[0] + ("." + digits[1:] if k > 1 else "")
111
+ return f"{mantissa}e{'+' if e > 0 else '-'}{abs(e)}"
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "acid-cat-catalog"
3
+ version = "0.1.0"
4
+ description = "Write an AcidCat catalog in Python and render it in canonical form."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Hebilicious" }]
9
+ keywords = ["acidcat", "catalog"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Programming Language :: Python :: 3",
13
+ ]
14
+ requires-python = ">=3.11"
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/Hebilicious/acidcat/tree/main/packages/catalog/python#readme"
18
+ Repository = "https://github.com/Hebilicious/acidcat"
19
+ Issues = "https://github.com/Hebilicious/acidcat/issues"
20
+
21
+ [build-system]
22
+ requires = ["hatchling>=1.27"]
23
+ build-backend = "hatchling.build"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["acid_cat_catalog"]
27
+
28
+ [tool.hatch.build.targets.sdist]
29
+ include = ["acid_cat_catalog", "README.md", "LICENSE"]