sprigpy 0.1.0.dev1__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.
sprig/codegen/cli.py ADDED
@@ -0,0 +1,212 @@
1
+ """``sprig`` command line: generate code from specs, check specs.
2
+
3
+ sprig generate [--check] [--config sprig.toml]
4
+ sprig check SPEC...
5
+ sprig manifest SPEC # print the normalized manifest
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import difflib
12
+ import json
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import tomllib
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ from ..spec import SpecError, load_spec
22
+ from .render import render_bonsai, render_python, sgen_schema
23
+
24
+
25
+ @dataclass
26
+ class Target:
27
+ spec: Path
28
+ python: Path | None
29
+ bonsai: Path | None
30
+ namespace: str | None
31
+
32
+
33
+ def read_config(path: Path) -> list[Target]:
34
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
35
+ root = path.parent
36
+ targets = []
37
+ for entry in data.get("protocol", []):
38
+ targets.append(
39
+ Target(
40
+ spec=root / entry["spec"],
41
+ python=root / entry["python"] if "python" in entry else None,
42
+ bonsai=root / entry["bonsai"] if "bonsai" in entry else None,
43
+ namespace=entry.get("namespace"),
44
+ )
45
+ )
46
+ return targets
47
+
48
+
49
+ def _relative(path: Path, root: Path) -> str:
50
+ try:
51
+ return path.resolve().relative_to(root.resolve()).as_posix()
52
+ except ValueError:
53
+ return path.as_posix()
54
+
55
+
56
+ SGEN_VERSION = "0.9.0"
57
+ """The bonsai.sgen version sprig's generated C# is tested with."""
58
+
59
+ SGEN_SETUP = f"""\
60
+ bonsai.sgen writes the C# payload classes. To install it:
61
+ 1. Install the .NET 8 SDK or newer: https://dotnet.microsoft.com/download
62
+ 2. Then, in this repository (pins the version for everyone who clones it):
63
+ dotnet new tool-manifest
64
+ dotnet tool install bonsai.sgen --version {SGEN_VERSION}
65
+ or once per machine:
66
+ dotnet tool install --global bonsai.sgen --version {SGEN_VERSION}"""
67
+
68
+
69
+ @dataclass
70
+ class Sgen:
71
+ command: list[str]
72
+ version: str
73
+
74
+
75
+ def _listed_sgen_version(args: list[str], cwd: Path) -> str | None:
76
+ """bonsai.sgen's version in a ``dotnet tool list`` table, or None."""
77
+ result = subprocess.run(
78
+ check=False, args=["dotnet", "tool", "list", *args], cwd=cwd, capture_output=True, text=True
79
+ )
80
+ for line in result.stdout.splitlines():
81
+ cells = line.split()
82
+ if len(cells) >= 2 and cells[0].lower() == "bonsai.sgen":
83
+ return cells[1]
84
+ return None
85
+
86
+
87
+ def find_sgen(root: Path) -> Sgen | str:
88
+ """bonsai.sgen from the repository's tool manifest, else a global install; or why it is missing."""
89
+ if shutil.which("dotnet") is None:
90
+ return "the .NET SDK (dotnet) is not installed"
91
+ if (root / ".config" / "dotnet-tools.json").exists() or (root / "dotnet-tools.json").exists():
92
+ subprocess.run(check=False, args=["dotnet", "tool", "restore"], cwd=root, capture_output=True)
93
+ version = _listed_sgen_version([], root)
94
+ if version:
95
+ return Sgen(["dotnet", "tool", "run", "bonsai.sgen"], version)
96
+ version = _listed_sgen_version(["--global"], root)
97
+ if version:
98
+ return Sgen([shutil.which("bonsai.sgen") or "bonsai.sgen"], version)
99
+ return "bonsai.sgen is not installed"
100
+
101
+
102
+ def outputs(target: Target, root: Path, work: Path, sgen: Sgen | None) -> dict[Path, str]:
103
+ """Every file a target generates, as {path: text}; Bonsai files only with ``sgen``. sgen runs in ``work``."""
104
+ spec = load_spec(target.spec)
105
+ source = _relative(target.spec, root)
106
+ files: dict[Path, str] = {}
107
+ if target.python:
108
+ files[target.python] = render_python(spec, source)
109
+ if target.bonsai and sgen:
110
+ if not target.namespace:
111
+ raise SystemExit(f"{target.spec}: a bonsai target needs a namespace")
112
+ stem = spec.class_name
113
+ files[target.bonsai / f"{stem}.Operators.Generated.cs"] = render_bonsai(spec, target.namespace, source)
114
+ files[target.bonsai / f"{stem}.Types.Generated.cs"] = run_sgen(sgen, spec, target.namespace, stem, work)
115
+ return files
116
+
117
+
118
+ def run_sgen(sgen: Sgen, spec: object, namespace: str, stem: str, work: Path) -> str:
119
+ """Payload classes from bonsai.sgen."""
120
+ schema = work / f"{stem}.Types.json"
121
+ schema.write_text(json.dumps(sgen_schema(spec), indent=2), encoding="utf-8") # type: ignore[arg-type]
122
+ out = work / f"sgen-{stem}"
123
+ out.mkdir(exist_ok=True)
124
+ command = [*sgen.command, str(schema), "-o", str(out), "-n", f"{stem}.Types.Generated.cs"]
125
+ command += ["--namespace", namespace, "--serializer", "json"]
126
+ result = subprocess.run(check=False, args=command, capture_output=True, text=True)
127
+ produced = sorted(out.glob("*.cs"))
128
+ if result.returncode != 0 or len(produced) != 1:
129
+ raise SystemExit(f"bonsai.sgen failed for {stem}:\n{result.stdout}{result.stderr}")
130
+ return produced[0].read_text(encoding="utf-8")
131
+
132
+
133
+ def generate(config: Path, check: bool) -> int:
134
+ root = config.parent
135
+ targets = read_config(config)
136
+ stale: list[str] = []
137
+ sgen: Sgen | None = None
138
+ bonsai = [t for t in targets if t.bonsai]
139
+ if bonsai:
140
+ found = find_sgen(root)
141
+ if isinstance(found, str):
142
+ names = ", ".join(_relative(t.spec, root) for t in bonsai)
143
+ level = "error" if check else "warning"
144
+ print(f"{level}: {found}; skipped the Bonsai code for {names}.\n{SGEN_SETUP}", file=sys.stderr)
145
+ if check:
146
+ return 1 # cannot tell whether the C# is up to date
147
+ else:
148
+ sgen = found
149
+ if sgen.version.split("+")[0] != SGEN_VERSION:
150
+ print(
151
+ f"warning: bonsai.sgen {sgen.version} found; sprig is tested with {SGEN_VERSION}, "
152
+ f"so the generated C# may differ. To pin it: dotnet tool install bonsai.sgen --version {SGEN_VERSION}",
153
+ file=sys.stderr,
154
+ )
155
+ with tempfile.TemporaryDirectory() as tmp:
156
+ for target in targets:
157
+ for path, text in outputs(target, root, Path(tmp), sgen).items():
158
+ current = path.read_text(encoding="utf-8") if path.exists() else None
159
+ if current == text:
160
+ continue
161
+ rel = _relative(path, root)
162
+ if check:
163
+ stale.append(rel)
164
+ diff = difflib.unified_diff(
165
+ (current or "").splitlines(keepends=True),
166
+ text.splitlines(keepends=True),
167
+ rel,
168
+ rel + " (generated)",
169
+ n=1,
170
+ )
171
+ sys.stdout.writelines(list(diff)[:60])
172
+ else:
173
+ path.parent.mkdir(parents=True, exist_ok=True)
174
+ path.write_text(text, encoding="utf-8", newline="\n")
175
+ print(f"wrote {rel}")
176
+ if stale:
177
+ print(f"\n{len(stale)} generated file(s) out of date; run `sprig generate`:", *stale, sep="\n ")
178
+ return 1
179
+ return 0
180
+
181
+
182
+ def main(argv: list[str] | None = None) -> int:
183
+ parser = argparse.ArgumentParser(prog="sprig", description="Generate code from sprig protocol specs.")
184
+ sub = parser.add_subparsers(dest="command", required=True)
185
+ gen = sub.add_parser("generate", help="write every target listed in sprig.toml")
186
+ gen.add_argument("--config", type=Path, default=Path("sprig.toml"))
187
+ gen.add_argument("--check", action="store_true", help="write nothing; exit 1 if generated files are stale")
188
+ chk = sub.add_parser("check", help="load and check specs")
189
+ chk.add_argument("specs", nargs="+", type=Path)
190
+ man = sub.add_parser("manifest", help="print a spec's normalized manifest as YAML")
191
+ man.add_argument("spec", type=Path)
192
+ args = parser.parse_args(argv)
193
+
194
+ try:
195
+ if args.command == "generate":
196
+ return generate(args.config, args.check)
197
+ if args.command == "check":
198
+ for path in args.specs:
199
+ spec = load_spec(path)
200
+ print(
201
+ f"{path}: {spec.protocol} {spec.version}, {len(spec.operations)} operations, {len(spec.channels)} channels"
202
+ )
203
+ return 0
204
+ print(load_spec(args.spec).to_yaml(), end="")
205
+ return 0
206
+ except SpecError as e:
207
+ print(f"error: {e}", file=sys.stderr)
208
+ return 2
209
+
210
+
211
+ if __name__ == "__main__":
212
+ sys.exit(main())
@@ -0,0 +1,237 @@
1
+ """Spec -> the data the Python template renders: enums, models (in dependency order), operations, channels.
2
+
3
+ The same output serves the static module (``sprig generate``) and the runtime one (``sprig.load``).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import typing as t
10
+ from dataclasses import dataclass, field
11
+
12
+ from ..spec import BASE_CHANNELS, BUILTIN_TYPES, Spec, snake_case
13
+
14
+ # Types the sprig runtime ships; generated modules import them instead of redefining them.
15
+ RUNTIME_TYPES = {
16
+ "Empty": "sprig",
17
+ "Heartbeat": "sprig",
18
+ "HeartbeatCode": "sprig",
19
+ "Lifecycle": "sprig",
20
+ "LifecycleState": "sprig",
21
+ }
22
+
23
+ _CONSTRAINTS = {
24
+ "minimum": "ge",
25
+ "maximum": "le",
26
+ "exclusiveMinimum": "gt",
27
+ "exclusiveMaximum": "lt",
28
+ "minLength": "min_length",
29
+ "maxLength": "max_length",
30
+ "minItems": "min_length",
31
+ "maxItems": "max_length",
32
+ "pattern": "pattern",
33
+ }
34
+
35
+
36
+ @dataclass
37
+ class EnumMember:
38
+ name: str
39
+ value: str # Python literal
40
+
41
+
42
+ @dataclass
43
+ class EnumClass:
44
+ name: str
45
+ base: str # enum.StrEnum | enum.IntEnum | enum.Enum
46
+ members: list[EnumMember]
47
+ description: str | None
48
+
49
+
50
+ @dataclass
51
+ class ModelField:
52
+ name: str
53
+ annotation: str
54
+ default: str | None # Python expression after "=", or None when required without Field()
55
+
56
+
57
+ @dataclass
58
+ class ModelClass:
59
+ name: str
60
+ description: str | None
61
+ fields: list[ModelField] = field(default_factory=list)
62
+
63
+
64
+ @dataclass
65
+ class PythonModule:
66
+ enums: list[EnumClass]
67
+ models: list[ModelClass]
68
+ imports: list[str]
69
+
70
+
71
+ def build(spec: Spec) -> PythonModule:
72
+ types = spec.user_types
73
+ enums: list[EnumClass] = []
74
+ models: list[ModelClass] = []
75
+ for name in _dependency_order(types):
76
+ schema = types[name]
77
+ if "enum" in schema:
78
+ enums.append(_enum(name, schema))
79
+ else:
80
+ models.append(_model(name, schema, types))
81
+ imports = sorted({n for n in _referenced(spec) if n in RUNTIME_TYPES})
82
+ return PythonModule(enums=enums, models=models, imports=imports)
83
+
84
+
85
+ def _referenced(spec: Spec) -> set[str]:
86
+ names: set[str] = set()
87
+ for op in spec.operations.values():
88
+ names.update([op.request, op.reply, *op.errors])
89
+ for name, ch in spec.channels.items():
90
+ if name not in BASE_CHANNELS: # inherited from BaseProtocol
91
+ names.add(ch.payload)
92
+ for schema in spec.user_types.values():
93
+ names.update(_refs(schema))
94
+ return names
95
+
96
+
97
+ def _refs(schema: t.Any) -> set[str]:
98
+ found: set[str] = set()
99
+ if isinstance(schema, dict):
100
+ ref = schema.get("$ref")
101
+ if isinstance(ref, str):
102
+ found.add(ref.removeprefix("#/$defs/"))
103
+ for value in schema.values():
104
+ found |= _refs(value)
105
+ elif isinstance(schema, list):
106
+ for value in schema:
107
+ found |= _refs(value)
108
+ return found
109
+
110
+
111
+ def _dependency_order(types: dict[str, dict[str, t.Any]]) -> list[str]:
112
+ """Each type after the types it refers to (cycles keep declaration order; pydantic resolves them late)."""
113
+ order: list[str] = []
114
+ state: dict[str, int] = {}
115
+
116
+ def visit(name: str) -> None:
117
+ if state.get(name) == 2 or name not in types:
118
+ return
119
+ if state.get(name) == 1:
120
+ return # cycle
121
+ state[name] = 1
122
+ for dep in sorted(_refs(types[name])):
123
+ visit(dep)
124
+ state[name] = 2
125
+ order.append(name)
126
+
127
+ for name in types:
128
+ visit(name)
129
+ return order
130
+
131
+
132
+ def _member_name(value: t.Any) -> str:
133
+ name = re.sub(r"\W+", "_", str(value)).strip("_").upper() or "VALUE"
134
+ return f"V_{name}" if name[0].isdigit() else name
135
+
136
+
137
+ def _enum(name: str, schema: dict[str, t.Any]) -> EnumClass:
138
+ values = schema["enum"]
139
+ names = schema.get("x-enumNames")
140
+ if all(isinstance(v, str) for v in values):
141
+ base = "enum.StrEnum"
142
+ elif all(isinstance(v, int) for v in values):
143
+ base = "enum.IntEnum"
144
+ else:
145
+ base = "enum.Enum"
146
+ members = [
147
+ EnumMember(name=_member_name(names[i]) if names else _member_name(v), value=repr(v))
148
+ for i, v in enumerate(values)
149
+ ]
150
+ return EnumClass(name=name, base=base, members=members, description=schema.get("description"))
151
+
152
+
153
+ def _model(name: str, schema: dict[str, t.Any], types: dict[str, dict[str, t.Any]]) -> ModelClass:
154
+ model = ModelClass(name=name, description=schema.get("description"))
155
+ required = set(schema.get("required", []))
156
+ for prop, sub in schema.get("properties", {}).items():
157
+ model.fields.append(_field(snake_case(prop), sub, prop in required, types))
158
+ return model
159
+
160
+
161
+ def annotation(schema: dict[str, t.Any]) -> str:
162
+ """The Python type of a property, item or union member schema."""
163
+ if "$ref" in schema:
164
+ return str(schema["$ref"]).removeprefix("#/$defs/")
165
+ if "oneOf" in schema:
166
+ return " | ".join(dict.fromkeys(_constrained(s) for s in schema["oneOf"]))
167
+ kind = schema.get("type")
168
+ if isinstance(kind, list):
169
+ parts = [annotation({**schema, "type": k}) for k in kind if k != "null"]
170
+ joined = " | ".join(dict.fromkeys(parts)) or "None"
171
+ return f"{joined} | None" if "null" in kind else joined
172
+ if kind == "string":
173
+ if "enum" in schema:
174
+ return "t.Literal[" + ", ".join(repr(v) for v in schema["enum"]) + "]"
175
+ return {"byte": "Bytes", "date-time": "datetime"}.get(schema.get("format", ""), "str")
176
+ if kind == "number":
177
+ return "float"
178
+ if kind == "integer":
179
+ return "int"
180
+ if kind == "boolean":
181
+ return "bool"
182
+ if kind == "null":
183
+ return "None"
184
+ if kind == "array":
185
+ items = schema.get("items")
186
+ return f"list[{_constrained(items)}]" if isinstance(items, dict) else "list[t.Any]"
187
+ if kind == "object":
188
+ extra = schema.get("additionalProperties")
189
+ return f"dict[str, {_constrained(extra)}]" if isinstance(extra, dict) else "dict[str, t.Any]"
190
+ return "t.Any"
191
+
192
+
193
+ def _constraint_args(schema: dict[str, t.Any]) -> list[str]:
194
+ return [f"{arg}={schema[key]!r}" for key, arg in _CONSTRAINTS.items() if key in schema]
195
+
196
+
197
+ def _constrained(schema: dict[str, t.Any]) -> str:
198
+ """An item or map value type, with its own constraints (``list[Annotated[float, Field(ge=0)]]``)."""
199
+ args = _constraint_args(schema)
200
+ inner = annotation(schema)
201
+ return f"t.Annotated[{inner}, Field({', '.join(args)})]" if args else inner
202
+
203
+
204
+ def _default_expr(value: t.Any, schema: dict[str, t.Any], types: dict[str, dict[str, t.Any]]) -> str:
205
+ ref = schema.get("$ref", "").removeprefix("#/$defs/")
206
+ target = types.get(ref) or BUILTIN_TYPES.get(ref)
207
+ if target is not None and "enum" in target:
208
+ return f"{ref}({value!r})" # a member, not the raw value
209
+ return repr(value)
210
+
211
+
212
+ def _field(name: str, schema: dict[str, t.Any], required: bool, types: dict[str, dict[str, t.Any]]) -> ModelField:
213
+ ann = annotation(schema)
214
+ kwargs: list[str] = []
215
+ has_default = "default" in schema
216
+ if has_default:
217
+ value = schema["default"]
218
+ expr = _default_expr(value, schema, types)
219
+ if isinstance(value, list | dict):
220
+ kwargs.append(f"default_factory=lambda: {expr}")
221
+ else:
222
+ kwargs.append(f"default={expr}")
223
+ elif not required:
224
+ if "None" not in ann:
225
+ ann = f"{ann} | None"
226
+ kwargs.append("default=None")
227
+ kwargs.extend(_constraint_args(schema))
228
+ if schema.get("description"):
229
+ kwargs.append(f"description={schema['description']!r}")
230
+ if not kwargs:
231
+ return ModelField(name=name, annotation=ann, default=None)
232
+ only_default = len(kwargs) == 1 and kwargs[0].startswith("default=")
233
+ return ModelField(
234
+ name=name,
235
+ annotation=ann,
236
+ default=kwargs[0][len("default=") :] if only_default else f"Field({', '.join(kwargs)})",
237
+ )
@@ -0,0 +1,165 @@
1
+ """Render a spec to source code. One Jinja environment, one ``Spec``, every target."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import typing as t
7
+ from functools import cache
8
+
9
+ import jinja2
10
+
11
+ from ..spec import BASE_CHANNELS, BUILTIN_TYPES, Direction, Spec, snake_case, spec_text
12
+ from . import python
13
+
14
+ TEMPLATES = jinja2.PackageLoader("sprig.codegen", "templates")
15
+
16
+
17
+ def _pyrepr(value: t.Any) -> str:
18
+ return repr(value)
19
+
20
+
21
+ def _pyblock(value: str) -> str:
22
+ """A multi-line string as a readable raw triple-quoted literal when that is exact, else repr."""
23
+ if '"""' not in value and "\\" not in value and not value.endswith('"') and "\r" not in value:
24
+ return 'r"""' + value + '"""'
25
+ return repr(value)
26
+
27
+
28
+ def _verbatim(value: str) -> str:
29
+ """A C# verbatim string literal."""
30
+ return '@"' + value.replace('"', '""') + '"'
31
+
32
+
33
+ def _docstring(value: str) -> str:
34
+ return value.replace('"""', "'''").replace("\\", "\\\\").strip()
35
+
36
+
37
+ @cache
38
+ def environment() -> jinja2.Environment:
39
+ env = jinja2.Environment(
40
+ loader=TEMPLATES,
41
+ undefined=jinja2.StrictUndefined,
42
+ keep_trailing_newline=True,
43
+ trim_blocks=False,
44
+ lstrip_blocks=False,
45
+ autoescape=False, # source code, not HTML
46
+ )
47
+ env.filters["pyrepr"] = _pyrepr
48
+ env.filters["pyblock"] = _pyblock
49
+ env.filters["verbatim"] = _verbatim
50
+ env.filters["docstring"] = _docstring
51
+ return env
52
+
53
+
54
+ def _user_members(spec: Spec, kind: str) -> list[tuple[str, t.Any]]:
55
+ members = spec.operations if kind == "operations" else spec.channels
56
+ return [(snake_case(n), m) for n, m in members.items() if n not in BASE_CHANNELS]
57
+
58
+
59
+ def render_python(spec: Spec, source: str) -> str:
60
+ """The Python module: models, enums and the protocol class."""
61
+ text = (
62
+ environment()
63
+ .get_template("python/protocol.py.j2")
64
+ .render(
65
+ spec=spec,
66
+ source=source,
67
+ spec_text=spec_text(spec),
68
+ module=python.build(spec),
69
+ operations=_user_members(spec, "operations"),
70
+ channels=_user_members(spec, "channels"),
71
+ )
72
+ )
73
+ return _tidy(text)
74
+
75
+
76
+ def cs_type(spec: Spec, name: str) -> str:
77
+ """C# name of a payload type: runtime types are shipped once in Sprig."""
78
+ return f"global::Sprig.{name}" if name in BUILTIN_TYPES else name
79
+
80
+
81
+ def render_bonsai(spec: Spec, namespace: str, source: str) -> str:
82
+ """The Bonsai operators, call classes, endpoint classes and protocol table (payload types come from sgen)."""
83
+ operations = [
84
+ {
85
+ "name": name,
86
+ "member": name,
87
+ "request": cs_type(spec, op.request),
88
+ "reply": cs_type(spec, op.reply),
89
+ "errors": [cs_type(spec, e) for e in op.errors],
90
+ }
91
+ for name, op in spec.operations.items()
92
+ ]
93
+ channels = [
94
+ {
95
+ "name": name,
96
+ "member": name,
97
+ "payload": cs_type(spec, ch.payload),
98
+ "server_to_client": "true" if ch.direction is Direction.SERVER_TO_CLIENT else "false",
99
+ "retain_last": "true" if ch.retain_last else "false",
100
+ }
101
+ for name, ch in spec.channels.items()
102
+ ]
103
+ timeout = {"name": "Timeout", "doc": "How long a request may wait for its reply. Zero waits forever."}
104
+ heartbeat = {
105
+ "name": "HeartbeatPeriod",
106
+ "doc": "How often the heartbeat status is re-sent. Clients report the server lost after 3 missed. Zero: never.",
107
+ }
108
+ sides = [
109
+ {
110
+ "name": "Server",
111
+ "lower": "server",
112
+ "base": "RpcServer",
113
+ "server": True,
114
+ "host": "*",
115
+ "timespans": [timeout, heartbeat],
116
+ "doc": f"Serves {spec.protocol} {spec.version} over ZeroMQ. Emits the server once; keep it in a ResourceSubject.",
117
+ },
118
+ {
119
+ "name": "Client",
120
+ "lower": "client",
121
+ "base": "RpcClient",
122
+ "server": False,
123
+ "host": "localhost",
124
+ "timespans": [timeout],
125
+ "doc": f"Connects to a {spec.protocol} server over ZeroMQ. Emits the client once; keep it in a ResourceSubject.",
126
+ },
127
+ ]
128
+ text = (
129
+ environment()
130
+ .get_template("bonsai/operators.cs.j2")
131
+ .render(
132
+ spec=spec,
133
+ source=source,
134
+ namespace=namespace,
135
+ cls=spec.class_name,
136
+ manifest_json=json.dumps(spec.manifest(), separators=(", ", ": ")),
137
+ spec_text=spec_text(spec),
138
+ operations=operations,
139
+ channels=channels,
140
+ sides=sides,
141
+ )
142
+ )
143
+ return text.rstrip("\n") + "\n" # no _tidy: SpecYaml must keep the spec's exact text
144
+
145
+
146
+ def sgen_schema(spec: Spec) -> dict[str, t.Any]:
147
+ """The JSON Schema bonsai.sgen generates C# payload classes from: the spec's own types."""
148
+ return {"$defs": spec.user_types}
149
+
150
+
151
+ def _tidy(text: str) -> str:
152
+ """Collapse runs of blank lines left by template branches; end with one newline."""
153
+ lines: list[str] = []
154
+ blank = 0
155
+ for line in text.splitlines():
156
+ if line.strip():
157
+ blank = 0
158
+ lines.append(line.rstrip())
159
+ else:
160
+ blank += 1
161
+ if blank <= 2:
162
+ lines.append("")
163
+ while lines and not lines[-1]:
164
+ lines.pop()
165
+ return "\n".join(lines) + "\n"