nat20-bridge 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.
- nat20_bridge/__init__.py +3 -0
- nat20_bridge/app.py +257 -0
- nat20_bridge/cli.py +25 -0
- nat20_bridge/forge.py +94 -0
- nat20_bridge/homebrew.py +148 -0
- nat20_bridge/models.py +82 -0
- nat20_bridge/narrate.py +172 -0
- nat20_bridge/overlay.py +89 -0
- nat20_bridge/routes_combat.py +411 -0
- nat20_bridge/routes_content.py +168 -0
- nat20_bridge/sheet.py +105 -0
- nat20_bridge/slots.py +126 -0
- nat20_bridge/state.py +47 -0
- nat20_bridge-0.3.1.dist-info/METADATA +39 -0
- nat20_bridge-0.3.1.dist-info/RECORD +18 -0
- nat20_bridge-0.3.1.dist-info/WHEEL +4 -0
- nat20_bridge-0.3.1.dist-info/entry_points.txt +2 -0
- nat20_bridge-0.3.1.dist-info/licenses/LICENSE +21 -0
nat20_bridge/__init__.py
ADDED
nat20_bridge/app.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import random
|
|
5
|
+
from importlib.metadata import version
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from dnd5e_engine import (
|
|
9
|
+
CheckSpec,
|
|
10
|
+
HitDicePool,
|
|
11
|
+
configure_lib_loader,
|
|
12
|
+
make_build_spec,
|
|
13
|
+
resolve_check,
|
|
14
|
+
resolve_long_rest,
|
|
15
|
+
resolve_short_rest,
|
|
16
|
+
roll_dice_str,
|
|
17
|
+
)
|
|
18
|
+
from dnd5e_srd_data.loader import BundledAssetLoader
|
|
19
|
+
from fastapi import FastAPI, HTTPException
|
|
20
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
21
|
+
from pydantic import BaseModel, Field
|
|
22
|
+
|
|
23
|
+
from nat20_bridge import __version__
|
|
24
|
+
from nat20_bridge.homebrew import HomebrewStore
|
|
25
|
+
from nat20_bridge.models import (
|
|
26
|
+
ABILITY_ALIASES,
|
|
27
|
+
AbilityScoresModel,
|
|
28
|
+
PartyValidateRequest,
|
|
29
|
+
full_ability,
|
|
30
|
+
resolve_seed,
|
|
31
|
+
slugify,
|
|
32
|
+
)
|
|
33
|
+
from nat20_bridge.overlay import OverlayAssetLoader
|
|
34
|
+
from nat20_bridge.routes_combat import build_combat_router
|
|
35
|
+
from nat20_bridge.routes_content import build_content_router
|
|
36
|
+
from nat20_bridge.sheet import derive_sheet
|
|
37
|
+
from nat20_bridge.state import BridgeState
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _do_roll(req: _RollRequest) -> dict[str, Any]:
|
|
41
|
+
seed = resolve_seed(req.seed)
|
|
42
|
+
# `roll_dice_str` is the engine's standalone narrator-time dice seam
|
|
43
|
+
# (rules/effects.py) — it draws from the stdlib global `random` module
|
|
44
|
+
# by design ("Public test seam: callers monkeypatch this symbol (or
|
|
45
|
+
# random.randint) for determinism"), not an injectable `random.Random`.
|
|
46
|
+
# Seeding the global module is the sanctioned way to make this call
|
|
47
|
+
# reproducible.
|
|
48
|
+
random.seed(seed)
|
|
49
|
+
try:
|
|
50
|
+
total = roll_dice_str(req.dice)
|
|
51
|
+
except ValueError as exc:
|
|
52
|
+
raise HTTPException(
|
|
53
|
+
status_code=422, detail=f"invalid dice expression {req.dice!r}: {exc}"
|
|
54
|
+
) from exc
|
|
55
|
+
return {"total": total, "dice": req.dice, "seed": seed}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _check_summary(result: Any) -> str:
|
|
59
|
+
label = result.skill or result.ability
|
|
60
|
+
if result.dc is None:
|
|
61
|
+
return f"{label} check: {result.roll_total}"
|
|
62
|
+
outcome = "success" if result.success else "failure"
|
|
63
|
+
return f"{label} check: {result.roll_total} vs DC {result.dc} -> {outcome}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _do_check(req: _CheckRequest) -> dict[str, Any]:
|
|
67
|
+
seed = resolve_seed(req.seed)
|
|
68
|
+
short_scores = req.ability_scores.model_dump(by_alias=True)
|
|
69
|
+
ability_scores = {full: short_scores[short] for short, full in ABILITY_ALIASES.items()}
|
|
70
|
+
spec = CheckSpec(
|
|
71
|
+
kind=req.kind,
|
|
72
|
+
ability_scores=ability_scores,
|
|
73
|
+
proficient_skills=req.proficient_skills,
|
|
74
|
+
proficient_saves=tuple(full_ability(s) for s in req.proficient_saves),
|
|
75
|
+
proficiency_bonus=req.proficiency_bonus,
|
|
76
|
+
skill=req.skill,
|
|
77
|
+
ability=full_ability(req.ability) if req.ability else None,
|
|
78
|
+
dc=req.dc,
|
|
79
|
+
advantage=req.advantage,
|
|
80
|
+
disadvantage=req.disadvantage,
|
|
81
|
+
)
|
|
82
|
+
random.seed(seed)
|
|
83
|
+
try:
|
|
84
|
+
result = resolve_check(spec)
|
|
85
|
+
except ValueError as exc:
|
|
86
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
87
|
+
|
|
88
|
+
body = dataclasses.asdict(result)
|
|
89
|
+
body["seed"] = seed
|
|
90
|
+
body["summary"] = _check_summary(result)
|
|
91
|
+
return body
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _do_rest_short(req: _ShortRestRequest) -> dict[str, Any]:
|
|
95
|
+
seed = resolve_seed(req.seed)
|
|
96
|
+
pool = HitDicePool(
|
|
97
|
+
hit_die_size=req.hit_die_size,
|
|
98
|
+
dice_remaining=req.dice_remaining,
|
|
99
|
+
dice_total=req.dice_total,
|
|
100
|
+
)
|
|
101
|
+
rng = random.Random(seed)
|
|
102
|
+
try:
|
|
103
|
+
outcome = resolve_short_rest(pool, req.dice_to_spend, req.con_modifier, rng=rng)
|
|
104
|
+
except ValueError as exc:
|
|
105
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
106
|
+
|
|
107
|
+
hp_current = min(req.hp_current + outcome.healed, req.hp_max)
|
|
108
|
+
return {
|
|
109
|
+
"healed": outcome.healed,
|
|
110
|
+
"dice_spent": outcome.dice_spent,
|
|
111
|
+
"hp_current": hp_current,
|
|
112
|
+
"dice_remaining": outcome.dice_remaining,
|
|
113
|
+
"seed": seed,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _do_rest_long(req: _LongRestRequest) -> dict[str, Any]:
|
|
118
|
+
seed = resolve_seed(req.seed)
|
|
119
|
+
pool = HitDicePool(
|
|
120
|
+
hit_die_size=req.hit_die_size,
|
|
121
|
+
dice_remaining=req.dice_remaining,
|
|
122
|
+
dice_total=req.dice_total,
|
|
123
|
+
)
|
|
124
|
+
outcome = resolve_long_rest(pool, req.hp_current, req.hp_max)
|
|
125
|
+
return {
|
|
126
|
+
"healed": outcome.healed,
|
|
127
|
+
"dice_spent": outcome.dice_spent,
|
|
128
|
+
"hp_current": outcome.hp_current,
|
|
129
|
+
"dice_remaining": outcome.dice_remaining,
|
|
130
|
+
"seed": seed,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class _RollRequest(BaseModel):
|
|
135
|
+
dice: str
|
|
136
|
+
seed: int | None = None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _CheckRequest(BaseModel):
|
|
140
|
+
kind: Literal["skill", "ability", "saving_throw"]
|
|
141
|
+
ability: str | None = None
|
|
142
|
+
skill: str | None = None
|
|
143
|
+
dc: int | None = None
|
|
144
|
+
ability_scores: AbilityScoresModel = Field(default_factory=lambda: AbilityScoresModel())
|
|
145
|
+
proficient_skills: tuple[str, ...] = ()
|
|
146
|
+
proficient_saves: tuple[str, ...] = ()
|
|
147
|
+
proficiency_bonus: int = 0
|
|
148
|
+
advantage: bool = False
|
|
149
|
+
disadvantage: bool = False
|
|
150
|
+
seed: int | None = None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _ShortRestRequest(BaseModel):
|
|
154
|
+
hit_die_size: int
|
|
155
|
+
dice_remaining: int
|
|
156
|
+
dice_total: int
|
|
157
|
+
dice_to_spend: int
|
|
158
|
+
con_modifier: int
|
|
159
|
+
hp_current: int
|
|
160
|
+
hp_max: int
|
|
161
|
+
seed: int | None = None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class _LongRestRequest(BaseModel):
|
|
165
|
+
hit_die_size: int
|
|
166
|
+
dice_remaining: int
|
|
167
|
+
dice_total: int
|
|
168
|
+
hp_current: int
|
|
169
|
+
hp_max: int
|
|
170
|
+
seed: int | None = None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def create_app(state: BridgeState) -> FastAPI:
|
|
174
|
+
app = FastAPI(title="nat20-bridge", version=__version__)
|
|
175
|
+
# The ST extension fetches cross-origin from the SillyTavern page; the
|
|
176
|
+
# bridge binds loopback so permissive CORS is acceptable here.
|
|
177
|
+
app.add_middleware(
|
|
178
|
+
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# Homebrew overlay is installed ONCE here, at app creation, over the
|
|
182
|
+
# engine's module-global lib loader singleton (`configure_lib_loader`).
|
|
183
|
+
# `combat` routes (routes_combat.py) resolve monsters/spells/weapons
|
|
184
|
+
# through this same overlay via `state.loader`; Task 10's homebrew
|
|
185
|
+
# mutation routes call `state.refresh_loader()` to rebuild the overlay's
|
|
186
|
+
# in-memory layer after an add/remove without restarting the process.
|
|
187
|
+
store = HomebrewStore(state.homebrew_path)
|
|
188
|
+
state.homebrew_store = store
|
|
189
|
+
|
|
190
|
+
def _refresh_loader() -> None:
|
|
191
|
+
loader = OverlayAssetLoader(base=BundledAssetLoader(), overlay=store.as_memory_loader())
|
|
192
|
+
state.loader = loader
|
|
193
|
+
configure_lib_loader(loader)
|
|
194
|
+
|
|
195
|
+
state.refresh_loader = _refresh_loader
|
|
196
|
+
_refresh_loader()
|
|
197
|
+
|
|
198
|
+
@app.get("/v1/health")
|
|
199
|
+
def health() -> dict[str, str]:
|
|
200
|
+
return {
|
|
201
|
+
"bridge": __version__,
|
|
202
|
+
"engine": version("dnd5e-engine"),
|
|
203
|
+
"data": version("dnd5e-srd-data"),
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
@app.post("/v1/party/validate")
|
|
207
|
+
def party_validate(req: PartyValidateRequest) -> dict[str, Any]:
|
|
208
|
+
entity_id = req.entity_id or f"char:{slugify(req.name)}"
|
|
209
|
+
assert state.loader is not None
|
|
210
|
+
try:
|
|
211
|
+
build_spec = make_build_spec(
|
|
212
|
+
species_slug=req.build.species_slug,
|
|
213
|
+
class_slug=req.build.class_slug,
|
|
214
|
+
level=req.build.level,
|
|
215
|
+
subclass_slug=req.build.subclass_slug,
|
|
216
|
+
ability_scores=req.build.ability_scores.model_dump(by_alias=True),
|
|
217
|
+
equipment=req.build.equipment,
|
|
218
|
+
)
|
|
219
|
+
member = derive_sheet(
|
|
220
|
+
build_spec,
|
|
221
|
+
name=req.name,
|
|
222
|
+
entity_id=entity_id,
|
|
223
|
+
loader=state.loader,
|
|
224
|
+
hp_current=req.hp_current,
|
|
225
|
+
spells_known=req.spells_known,
|
|
226
|
+
)
|
|
227
|
+
except ValueError as exc:
|
|
228
|
+
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
229
|
+
|
|
230
|
+
slots = ",".join(f"{lvl}:{count}" for lvl, count in member.spell_slots.items())
|
|
231
|
+
summary = (
|
|
232
|
+
f"{member.name} — lvl {member.character_level} {member.species_slug} "
|
|
233
|
+
f"{member.class_slug}, HP {member.hp_current}/{member.hp_max}, "
|
|
234
|
+
f"AC {member.ac}, slots {{{slots}}}"
|
|
235
|
+
)
|
|
236
|
+
return {"member": member.model_dump(), "summary": summary}
|
|
237
|
+
|
|
238
|
+
@app.post("/v1/roll")
|
|
239
|
+
def roll(req: _RollRequest) -> dict[str, Any]:
|
|
240
|
+
return _do_roll(req)
|
|
241
|
+
|
|
242
|
+
@app.post("/v1/check")
|
|
243
|
+
def check(req: _CheckRequest) -> dict[str, Any]:
|
|
244
|
+
return _do_check(req)
|
|
245
|
+
|
|
246
|
+
@app.post("/v1/rest/short")
|
|
247
|
+
def rest_short(req: _ShortRestRequest) -> dict[str, Any]:
|
|
248
|
+
return _do_rest_short(req)
|
|
249
|
+
|
|
250
|
+
@app.post("/v1/rest/long")
|
|
251
|
+
def rest_long(req: _LongRestRequest) -> dict[str, Any]:
|
|
252
|
+
return _do_rest_long(req)
|
|
253
|
+
|
|
254
|
+
app.include_router(build_combat_router(state))
|
|
255
|
+
app.include_router(build_content_router(state))
|
|
256
|
+
|
|
257
|
+
return app
|
nat20_bridge/cli.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import uvicorn
|
|
7
|
+
|
|
8
|
+
from nat20_bridge.app import create_app
|
|
9
|
+
from nat20_bridge.state import BridgeState
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> None:
|
|
13
|
+
parser = argparse.ArgumentParser(prog="nat20-bridge")
|
|
14
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
15
|
+
parser.add_argument("--port", type=int, default=8020)
|
|
16
|
+
parser.add_argument(
|
|
17
|
+
"--data-dir",
|
|
18
|
+
type=Path,
|
|
19
|
+
default=Path.home() / ".nat20-bridge",
|
|
20
|
+
help="where homebrew.json persists",
|
|
21
|
+
)
|
|
22
|
+
args = parser.parse_args()
|
|
23
|
+
args.data_dir.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
app = create_app(BridgeState(homebrew_path=args.data_dir / "homebrew.json"))
|
|
25
|
+
uvicorn.run(app, host=args.host, port=args.port) # pragma: no cover
|
nat20_bridge/forge.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""forge_item — compact weapon recipes → schema-valid, round-trippable raw dicts.
|
|
2
|
+
|
|
3
|
+
Takes a canonical weapon base slug plus a small set of overrides (name,
|
|
4
|
+
magical bonus, one extra damage part) and produces a raw dict shaped exactly
|
|
5
|
+
like the ones :class:`~nat20_bridge.homebrew.HomebrewStore` persists — i.e.
|
|
6
|
+
``json.loads(Weapon.model_dump_json())`` — so callers can hand the result
|
|
7
|
+
straight to ``HomebrewStore.add("items", raw)``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
from dnd5e_srd_data.schema.common import DamagePart
|
|
17
|
+
from dnd5e_srd_data.schema.item import Weapon
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from dnd5e_srd_data.loader import AssetLoader
|
|
22
|
+
|
|
23
|
+
_EXTRA_DAMAGE_RE = re.compile(r"^(\d+d\d+(?:[+-]\d+)?):([a-z]+)$")
|
|
24
|
+
|
|
25
|
+
_SLUG_SANITIZE_RE = re.compile(r"[^a-z0-9]+")
|
|
26
|
+
|
|
27
|
+
_HB_PREFIX = "hb-"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ForgeError(Exception):
|
|
31
|
+
"""Raised when a forge recipe is invalid (unknown base, malformed damage, ...)."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _slugify(name: str) -> str:
|
|
35
|
+
sanitized = _SLUG_SANITIZE_RE.sub("-", name.strip().lower()).strip("-")
|
|
36
|
+
if not sanitized:
|
|
37
|
+
raise ForgeError(f"name {name!r} does not yield a usable slug")
|
|
38
|
+
return f"{_HB_PREFIX}{sanitized}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _parse_extra_damage(extra_damage: str) -> DamagePart:
|
|
42
|
+
match = _EXTRA_DAMAGE_RE.match(extra_damage)
|
|
43
|
+
if match is None:
|
|
44
|
+
raise ForgeError(
|
|
45
|
+
f"malformed extra_damage {extra_damage!r}; expected format 'NdM[+/-B]:type'"
|
|
46
|
+
)
|
|
47
|
+
dice, damage_type = match.groups()
|
|
48
|
+
return DamagePart(dice=dice, damage_type=damage_type)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def forge_item(
|
|
52
|
+
*,
|
|
53
|
+
name: str,
|
|
54
|
+
base: str,
|
|
55
|
+
loader: AssetLoader,
|
|
56
|
+
bonus: int = 0,
|
|
57
|
+
extra_damage: str | None = None,
|
|
58
|
+
) -> dict[str, Any]:
|
|
59
|
+
"""Build a raw, schema-valid weapon dict from a canonical base weapon.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ForgeError: ``base`` is not a known weapon slug, or ``extra_damage``
|
|
63
|
+
doesn't match the ``"NdM[+/-B]:type"`` format.
|
|
64
|
+
"""
|
|
65
|
+
weapon = loader.get_weapon(base)
|
|
66
|
+
if weapon is None:
|
|
67
|
+
raise ForgeError(f"unknown weapon base slug {base!r}")
|
|
68
|
+
|
|
69
|
+
damage_parts = list(weapon.damage_parts)
|
|
70
|
+
if extra_damage is not None:
|
|
71
|
+
damage_parts.append(_parse_extra_damage(extra_damage))
|
|
72
|
+
|
|
73
|
+
slug = _slugify(name)
|
|
74
|
+
try:
|
|
75
|
+
new_weapon = weapon.model_copy(
|
|
76
|
+
update={
|
|
77
|
+
"slug": slug,
|
|
78
|
+
"name": name,
|
|
79
|
+
"magical_bonus": weapon.magical_bonus + bonus,
|
|
80
|
+
"damage_parts": damage_parts,
|
|
81
|
+
}
|
|
82
|
+
)
|
|
83
|
+
dumped: dict[str, Any] = json.loads(new_weapon.model_dump_json())
|
|
84
|
+
# ``model_copy(update=...)`` and ``model_dump_json`` don't re-validate
|
|
85
|
+
# constrained fields (e.g. ``magical_bonus: NonNegativeInt``), so a
|
|
86
|
+
# negative ``bonus`` would otherwise silently produce an
|
|
87
|
+
# out-of-schema dict that only blows up later (as an uncaught
|
|
88
|
+
# ``ValidationError`` -> 500) when ``HomebrewStore.add`` validates
|
|
89
|
+
# it. Re-validate here so bad recipes fail as ``ForgeError`` (-> 422)
|
|
90
|
+
# at the source.
|
|
91
|
+
Weapon.model_validate(dumped)
|
|
92
|
+
except ValidationError as exc:
|
|
93
|
+
raise ForgeError(f"invalid forged item: {exc}") from exc
|
|
94
|
+
return dumped
|
nat20_bridge/homebrew.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""HomebrewStore — validated, persisted homebrew content overlay.
|
|
2
|
+
|
|
3
|
+
Homebrew entries are stored as raw dicts on disk (keyed by slug), re-parsed
|
|
4
|
+
through the same Pydantic schema models the canonical dataset uses, and
|
|
5
|
+
exposed as a :class:`~dnd5e_srd_data.loader.MemoryAssetLoader` so they can be
|
|
6
|
+
layered under :class:`~nat20_bridge.overlay.OverlayAssetLoader`.
|
|
7
|
+
|
|
8
|
+
Every homebrew slug is forced to carry an ``hb-`` prefix. Since no canonical
|
|
9
|
+
SRD slug starts with ``hb-``, this guarantees homebrew content can never
|
|
10
|
+
collide with (and therefore never shadow) canonical content.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from dnd5e_srd_data.loader import Category, MemoryAssetLoader
|
|
22
|
+
from dnd5e_srd_data.schema.background import Background
|
|
23
|
+
from dnd5e_srd_data.schema.class_ import Class, Subclass
|
|
24
|
+
from dnd5e_srd_data.schema.feat import Feat
|
|
25
|
+
from dnd5e_srd_data.schema.feature import Feature
|
|
26
|
+
from dnd5e_srd_data.schema.item import Armor, Item, MagicItem, Weapon
|
|
27
|
+
from dnd5e_srd_data.schema.monster import Monster
|
|
28
|
+
from dnd5e_srd_data.schema.species import Species
|
|
29
|
+
from dnd5e_srd_data.schema.spell import Spell
|
|
30
|
+
from pydantic import BaseModel, ValidationError
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
_HB_PREFIX = "hb-"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class HomebrewValidationError(Exception):
|
|
38
|
+
"""Raised when a homebrew entry fails schema validation."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _parse_item(raw: dict[str, Any]) -> Item | Weapon | Armor | MagicItem:
|
|
42
|
+
kind = raw.get("item_kind", "item")
|
|
43
|
+
if kind == "weapon":
|
|
44
|
+
return Weapon.model_validate(raw)
|
|
45
|
+
if kind == "armor":
|
|
46
|
+
return Armor.model_validate(raw)
|
|
47
|
+
if kind == "magic_item":
|
|
48
|
+
return MagicItem.model_validate(raw)
|
|
49
|
+
return Item.model_validate(raw)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_PARSERS: dict[str, Any] = {
|
|
53
|
+
"items": _parse_item,
|
|
54
|
+
"monsters": Monster.model_validate,
|
|
55
|
+
"spells": Spell.model_validate,
|
|
56
|
+
"species": Species.model_validate,
|
|
57
|
+
"classes": Class.model_validate,
|
|
58
|
+
"subclasses": Subclass.model_validate,
|
|
59
|
+
"backgrounds": Background.model_validate,
|
|
60
|
+
"feats": Feat.model_validate,
|
|
61
|
+
"features": Feature.model_validate,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _normalize_slug(raw: dict[str, Any]) -> str:
|
|
66
|
+
slug = str(raw.get("slug", ""))
|
|
67
|
+
if not slug.startswith(_HB_PREFIX):
|
|
68
|
+
slug = f"{_HB_PREFIX}{slug}"
|
|
69
|
+
return slug
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class HomebrewStore:
|
|
73
|
+
"""Validated, disk-persisted homebrew content store."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, path: Path) -> None:
|
|
76
|
+
self._path = path
|
|
77
|
+
self._entries: dict[str, dict[str, Any]] = {}
|
|
78
|
+
self._load()
|
|
79
|
+
|
|
80
|
+
def _load(self) -> None:
|
|
81
|
+
if not self._path.is_file():
|
|
82
|
+
return
|
|
83
|
+
try:
|
|
84
|
+
raw_file = json.loads(self._path.read_text(encoding="utf-8"))
|
|
85
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
86
|
+
logger.warning("Failed to read homebrew store %s: %s", self._path, exc)
|
|
87
|
+
return
|
|
88
|
+
if not isinstance(raw_file, dict):
|
|
89
|
+
logger.warning("Homebrew store %s is malformed (not an object)", self._path)
|
|
90
|
+
return
|
|
91
|
+
for slug, entry in raw_file.items():
|
|
92
|
+
try:
|
|
93
|
+
category = entry["category"]
|
|
94
|
+
raw = entry["raw"]
|
|
95
|
+
parser = _PARSERS[category]
|
|
96
|
+
parser(raw)
|
|
97
|
+
except (KeyError, ValidationError, TypeError) as exc:
|
|
98
|
+
logger.warning("Dropping invalid homebrew entry %r: %s", slug, exc)
|
|
99
|
+
continue
|
|
100
|
+
self._entries[slug] = {"category": category, "raw": raw}
|
|
101
|
+
|
|
102
|
+
def _persist(self) -> None:
|
|
103
|
+
tmp_path = self._path.with_suffix(".tmp")
|
|
104
|
+
tmp_path.parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
tmp_path.write_text(json.dumps(self._entries, indent=2), encoding="utf-8")
|
|
106
|
+
os.replace(tmp_path, self._path)
|
|
107
|
+
|
|
108
|
+
def add(self, category: Category, raw: dict[str, Any]) -> str:
|
|
109
|
+
parser = _PARSERS[category]
|
|
110
|
+
slug = _normalize_slug(raw)
|
|
111
|
+
raw = {**raw, "slug": slug}
|
|
112
|
+
try:
|
|
113
|
+
model = parser(raw)
|
|
114
|
+
except ValidationError as exc:
|
|
115
|
+
raise HomebrewValidationError(str(exc)) from exc
|
|
116
|
+
if isinstance(model, BaseModel):
|
|
117
|
+
raw = json.loads(model.model_dump_json())
|
|
118
|
+
self._entries[slug] = {"category": category, "raw": raw}
|
|
119
|
+
self._persist()
|
|
120
|
+
return slug
|
|
121
|
+
|
|
122
|
+
def remove(self, slug: str) -> bool:
|
|
123
|
+
if slug not in self._entries:
|
|
124
|
+
return False
|
|
125
|
+
del self._entries[slug]
|
|
126
|
+
self._persist()
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
def entries(self) -> dict[str, dict[str, Any]]:
|
|
130
|
+
return dict(self._entries)
|
|
131
|
+
|
|
132
|
+
def as_memory_loader(self) -> MemoryAssetLoader:
|
|
133
|
+
grouped: dict[str, list[Any]] = {category: [] for category in _PARSERS}
|
|
134
|
+
for entry in self._entries.values():
|
|
135
|
+
category = entry["category"]
|
|
136
|
+
parser = _PARSERS[category]
|
|
137
|
+
grouped[category].append(parser(entry["raw"]))
|
|
138
|
+
return MemoryAssetLoader(
|
|
139
|
+
items=grouped["items"],
|
|
140
|
+
monsters=grouped["monsters"],
|
|
141
|
+
spells=grouped["spells"],
|
|
142
|
+
species=grouped["species"],
|
|
143
|
+
classes=grouped["classes"],
|
|
144
|
+
subclasses=grouped["subclasses"],
|
|
145
|
+
backgrounds=grouped["backgrounds"],
|
|
146
|
+
feats=grouped["feats"],
|
|
147
|
+
features=grouped["features"],
|
|
148
|
+
)
|
nat20_bridge/models.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Shared request models + small helpers used by both ``app.py`` and
|
|
2
|
+
``routes_combat.py``.
|
|
3
|
+
|
|
4
|
+
Split out so the two route modules can import the same party-member wire
|
|
5
|
+
shape (``PartyValidateRequest``) without creating an import cycle between
|
|
6
|
+
them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import secrets
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
|
|
16
|
+
_SLUG_RE = re.compile(r"[^a-z0-9]+")
|
|
17
|
+
|
|
18
|
+
# Short-form -> canonical ability name. `resolve_check`'s underlying skill /
|
|
19
|
+
# ability / saving-throw resolvers key `ability_scores` (and match
|
|
20
|
+
# `proficient_saves` / the derived-from-skill ability) by the long form, so
|
|
21
|
+
# any abbreviated input from a route body is normalized before it reaches
|
|
22
|
+
# the engine.
|
|
23
|
+
ABILITY_ALIASES = {
|
|
24
|
+
"str": "strength",
|
|
25
|
+
"dex": "dexterity",
|
|
26
|
+
"con": "constitution",
|
|
27
|
+
"int": "intelligence",
|
|
28
|
+
"wis": "wisdom",
|
|
29
|
+
"cha": "charisma",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def slugify(name: str) -> str:
|
|
34
|
+
return _SLUG_RE.sub("-", name.strip().lower()).strip("-")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def full_ability(name: str) -> str:
|
|
38
|
+
lowered = name.strip().lower()
|
|
39
|
+
return ABILITY_ALIASES.get(lowered, lowered)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def resolve_seed(seed: int | None) -> int:
|
|
43
|
+
return seed if seed is not None else secrets.randbits(32)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AbilityScoresModel(BaseModel):
|
|
47
|
+
str_: int = Field(default=10, alias="str")
|
|
48
|
+
dex: int = 10
|
|
49
|
+
con: int = 10
|
|
50
|
+
int_: int = Field(default=10, alias="int")
|
|
51
|
+
wis: int = 10
|
|
52
|
+
cha: int = 10
|
|
53
|
+
|
|
54
|
+
model_config = {"populate_by_name": True}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class BuildRequest(BaseModel):
|
|
58
|
+
species_slug: str
|
|
59
|
+
class_slug: str
|
|
60
|
+
subclass_slug: str | None = None
|
|
61
|
+
level: int = 1
|
|
62
|
+
ability_scores: AbilityScoresModel = Field(default_factory=lambda: AbilityScoresModel())
|
|
63
|
+
equipment: tuple[str, ...] = ()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class PartyValidateRequest(BaseModel):
|
|
67
|
+
name: str
|
|
68
|
+
entity_id: str | None = None
|
|
69
|
+
build: BuildRequest
|
|
70
|
+
spells_known: list[str] | None = None
|
|
71
|
+
hp_current: int | None = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
__all__ = [
|
|
75
|
+
"ABILITY_ALIASES",
|
|
76
|
+
"AbilityScoresModel",
|
|
77
|
+
"BuildRequest",
|
|
78
|
+
"PartyValidateRequest",
|
|
79
|
+
"full_ability",
|
|
80
|
+
"resolve_seed",
|
|
81
|
+
"slugify",
|
|
82
|
+
]
|