From 2c50e1b98e7bf150d55755c63792a57b3ea0724e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 17 Sep 2026 20:04:51 +0200 Subject: [PATCH] Add Ravenous character exchange and monster conversion --- AGENTS.md | 9 ++ README.md | 54 ++++++++++++ TASKS.md | 7 ++ roll20_mod/ravenous_character_io.js | 109 ++++++++++++++++++++++++ tests/test_character_io.mjs | 106 ++++++++++++++++++++++++ tests/test_monster_export.py | 46 +++++++++++ tools/export_monsters.py | 124 ++++++++++++++++++++++++++++ 7 files changed, 455 insertions(+) create mode 100644 roll20_mod/ravenous_character_io.js create mode 100644 tests/test_character_io.mjs create mode 100644 tests/test_monster_export.py create mode 100644 tools/export_monsters.py diff --git a/AGENTS.md b/AGENTS.md index fa7746e..b517dd2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,8 @@ infer a game rule from a field label or an existing formula without checking it. | `ravenous_typst/` | Git submodule containing the book and source game data. Avoid editing it as part of a sheet-only change. | | `tests/test_build.py` | Build and generated-output assertions; mostly structural checks. | | `roll20_mod/ravenous_import_name.js` | Optional Mod proof of concept: create a character from a JSON name. It is installed separately from the sheet. | +| `roll20_mod/ravenous_character_io.js` | GM Mod script for versioned JSON character export/import via private handouts. | +| `tools/export_monsters.py` | Converts the pinned SQLite monster database to that JSON format. | | `build/` | Generated output for Roll20. Do not hand edit it; it is currently ignored by Git. | The main inputs are `ravenous_typst/data/src/character_sheet.yaml`, @@ -26,6 +28,9 @@ The main inputs are `ravenous_typst/data/src/character_sheet.yaml`, `ravenous_typst/data/config/build.yaml`. Only school tiers below `build.max_tier_exclusive` are imported. At the pinned submodule revision the build reports 141 skills and 275 techniques across 11 schools. +The monster database is a nested submodule at +`ravenous_typst/data/src/db/monsters.db`; initialize it with +`git -C ravenous_typst submodule update --init data/src/db` before converter tests. ## Build and verify @@ -37,6 +42,7 @@ git submodule update --init --recursive uv run python -m unittest discover -s tests -v node tests/test_worker.mjs node tests/test_mod_import.mjs +node tests/test_character_io.mjs ./scripts/build.sh --check ``` @@ -85,6 +91,9 @@ the attack card's **Défendre** and **Subir** actions. - Origin powers are generated from YAML and added in batches by stage for the selected origin. Existing imported and custom powers remain if the origin changes. Source keys prevent duplicate import. +- Character JSON export preserves sheet attributes, abilities, bio, GM notes, + and access lists. Monster conversion maps compatible fields and keeps all + raw database rows in GM notes; monster attack dice and damage need GM review. ## Change workflow diff --git a/README.md b/README.md index 1fa5b0d..2f1457c 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,60 @@ tests locaux de ce prototype : node tests/test_mod_import.mjs ``` +## Sauvegarde et import de personnages et de créatures + +`roll20_mod/ravenous_character_io.js` est le script Mod destiné aux MJ. Installez-le +comme **New Script** dans une partie avec la feuille Ravenous. Il utilise le format +JSON versionné `ravenous-roll20-character` et crée toujours un nouveau personnage +à l'import. Les attributs (y compris les lignes répétables), les capacités Roll20, +la bio, les notes MJ et les droits de consultation/contrôle sont conservés. + +Dans le chat, en tant que MJ : + +```text +!ravenous-export ID_DU_PERSONNAGE +!ravenous-import --handout ID_DU_HANDOUT +!ravenous-import {"format":"ravenous-roll20-character","version":1,"name":"Ariane","attributes":[]} +``` + +L'export crée un handout réservé au MJ, dont les **GM Notes** contiennent le JSON +lisible. Copiez ce JSON dans un fichier pour le stocker hors de Roll20. Pour +importer un fichier volumineux, créez un handout, collez le JSON dans ses GM +Notes, puis utilisez `--handout` avec son ID. La commande directe convient aux +petits JSON. Gardez les handouts d'export privés : ils contiennent les notes MJ. +Les IDs sont visibles dans l'URL des objets Roll20. Après import, ouvrez le +personnage pour laisser les sheet workers recalculer les valeurs dérivées. + +Pour créer un JSON depuis la base SQLite du livre du MJ : + +```sh +git -C ravenous_typst submodule update --init data/src/db +python tools/export_monsters.py --id 1 --output /tmp/monster-1.json +python tools/export_monsters.py --all --output /tmp/ravenous-monsters +``` + +Le convertisseur reprend les caractéristiques directement compatibles, les +localisations en lignes répétables, les capacités avec dégâts en attaques, et +les autres capacités en pouvoirs. Leurs descriptions et valeurs de dégâts +restent dans les notes des lignes. La base complète de la créature, y compris +les phases et les valeurs sans équivalent fidèle dans la feuille de chasseur, +est conservée en JSON dans les GM Notes du personnage. Les champs de jet +inconnus sont laissés à zéro : le MJ doit régler dés, seuils et dégâts avant +d'utiliser les boutons d'attaque. Les sheet workers de la feuille de chasseur +recalculent certaines valeurs dérivées à l'ouverture. + +Vérification locale : + +```sh +uv run python -m unittest discover -s tests -v +python tools/export_monsters.py --id 1 --output /tmp/ravenous-monster-test.json +RAVENOUS_MONSTER_JSON=/tmp/ravenous-monster-test.json node tests/test_character_io.mjs +``` + +Ces tests simulent l'API Mod et valident le format avec la base épinglée. Un +essai dans une partie Roll20 reste nécessaire pour confirmer l'affichage et +les limites des GM Notes. + ## Mise à jour depuis le livre ```sh diff --git a/TASKS.md b/TASKS.md index b830e9b..f575393 100644 --- a/TASKS.md +++ b/TASKS.md @@ -19,12 +19,19 @@ parser, browser, or chat. character from a JSON `name`; test valid and invalid commands locally. - [x] Add origin powers from the pinned book data stage by stage in an editable Powers tab, while preserving custom rows and preventing duplicate imports. +- [x] Add a GM-only character JSON export/import Mod script and a monster + database converter. Verify round trips, repeating rows, invalid input, and + all master-visible monsters locally. ## Next: Roll20 smoke test - [ ] Install `roll20_mod/ravenous_import_name.js` as a New Script in a test game, run `!ravenous-import-name {"name":"Ariane"}` as GM, and confirm a single new character appears in the journal. Record the date and result. +- [ ] Install `roll20_mod/ravenous_character_io.js` in a test game. Export an + edited sheet, save its JSON outside Roll20, import it from a GM handout, and + compare notes, abilities, attributes, and repeating rows. Import one converted + monster and check each mapped row and any worker recalculations. - [ ] Load `build/ravenous.html`, `build/ravenous.css`, and `build/translation.json` into a Custom Sheet Sandbox with Legacy Sanitization disabled. Record the date, browser, and any console or worker errors. diff --git a/roll20_mod/ravenous_character_io.js b/roll20_mod/ravenous_character_io.js new file mode 100644 index 0000000..d896206 --- /dev/null +++ b/roll20_mod/ravenous_character_io.js @@ -0,0 +1,109 @@ +/* Ravenous character exchange for Roll20 Mod. GM commands: + * !ravenous-export CHARACTER_ID + * !ravenous-import {"format":"ravenous-roll20-character",...} + * !ravenous-import --handout HANDOUT_ID + * Exports are stored in a GM-only handout. Each import creates a new character. + */ +(function () { + 'use strict'; + var FORMAT = 'ravenous-roll20-character'; + var VERSION = 1; + + function whisper(message) { sendChat('Ravenous IO', '/w gm ' + message); } + function validText(value) { return typeof value === 'string' && value.length <= 200000; } + function validPayload(data) { + if (!data || Array.isArray(data) || typeof data !== 'object' || + data.format !== FORMAT || data.version !== VERSION || + typeof data.name !== 'string' || !data.name.trim() || data.name.length > 100 || + !Array.isArray(data.attributes) || data.attributes.length > 5000 || + (data.abilities !== undefined && (!Array.isArray(data.abilities) || data.abilities.length > 1000)) || + !validText(data.bio || '') || !validText(data.gmnotes || '') || + !validText(data.controlledby || '') || !validText(data.inplayerjournals || '')) return false; + return data.attributes.every(function (item) { + if (!item || Array.isArray(item) || typeof item !== 'object' || + typeof item.name !== 'string' || !item.name.trim() || item.name.length > 150 || + !validText(item.current) || !validText(item.max)) return false; + return true; + }) && (data.abilities || []).every(function (item) { + return item && typeof item.name === 'string' && item.name.length <= 150 && + validText(item.action) && typeof item.istokenaction === 'boolean'; + }); + } + function decodeHandout(raw) { + var text = String(raw || ''); + text = text.replace(//gi, '\n').replace(/<\/(?:p|div)>/gi, '\n') + .replace(/<[^>]*>/g, '').replace(/"/g, '"').replace(/'/g, "'") + .replace(/</g, '<').replace(/>/g, '>') + .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, decimal) { + return String.fromCodePoint(parseInt(hex || decimal, hex ? 16 : 10)); + }).replace(/&/g, '&') + .replace(/ /g, ' ').trim(); + return JSON.parse(text); + } + function importCharacter(data) { + if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous character JSON.'); + var character = createObj('character', { name: data.name.trim(), + controlledby: data.controlledby || '', inplayerjournals: data.inplayerjournals || '' }); + if (!character) return whisper('Roll20 could not create the character.'); + if (data.bio) character.set('bio', data.bio); + if (data.gmnotes) character.set('gmnotes', data.gmnotes); + data.attributes.forEach(function (item) { + createObj('attribute', { characterid: character.id, name: item.name, + current: item.current, max: item.max }); + }); + (data.abilities || []).forEach(function (item) { + createObj('ability', { characterid: character.id, name: item.name, + action: item.action, istokenaction: item.istokenaction }); + }); + whisper('Imported ' + data.attributes.length + ' attributes into character ' + character.id + '.'); + } + function exportCharacter(id) { + var character = getObj('character', id); + if (!character) return whisper('Character not found. Use its Roll20 character ID.'); + character.get('bio', function (bio) { + character.get('gmnotes', function (gmnotes) { + var attributes = findObjs({ type: 'attribute', characterid: id }).map(function (item) { + var current = item.get('current'); + var max = item.get('max'); + return { name: item.get('name'), current: current == null ? '' : String(current), + max: max == null ? '' : String(max) }; + }).sort(function (a, b) { return a.name.localeCompare(b.name); }); + var abilities = findObjs({ type: 'ability', characterid: id }).map(function (item) { + return { name: item.get('name'), action: item.get('action') || '', + istokenaction: item.get('istokenaction') === true || item.get('istokenaction') === 'true' }; + }); + var data = { format: FORMAT, version: VERSION, name: character.get('name'), + controlledby: character.get('controlledby') || '', + inplayerjournals: character.get('inplayerjournals') || '', + bio: bio || '', gmnotes: gmnotes || '', attributes: attributes, + abilities: abilities }; + var handout = createObj('handout', { name: 'Ravenous export - ' + data.name, + inplayerjournals: '', controlledby: '' }); + if (!handout) return whisper('Roll20 could not create the export handout.'); + var readable = JSON.stringify(data, null, 2).replace(/&/g, '&') + .replace(//g, '>'); + handout.set('gmnotes', '
' + readable + '
'); + whisper('Exported ' + attributes.length + ' attributes to GM handout ' + handout.id + '.'); + }); + }); + } + on('chat:message', function (message) { + if (message.type !== 'api' || !playerIsGM(message.playerid)) return; + var content = message.content.trim(); + if (content.indexOf('!ravenous-export ') === 0) { + return exportCharacter(content.slice('!ravenous-export '.length).trim()); + } + if (content.indexOf('!ravenous-import ') !== 0) return; + var input = content.slice('!ravenous-import '.length).trim(); + if (input.indexOf('--handout ') === 0) { + var handout = getObj('handout', input.slice('--handout '.length).trim()); + if (!handout) return whisper('Handout not found.'); + return handout.get('gmnotes', function (notes) { + try { importCharacter(decodeHandout(notes)); } + catch (error) { whisper('Handout does not contain valid Ravenous JSON.'); } + }); + } + try { importCharacter(JSON.parse(input)); } + catch (error) { whisper('Invalid JSON.'); } + }); +}()); diff --git a/tests/test_character_io.mjs b/tests/test_character_io.mjs new file mode 100644 index 0000000..2e3ab41 --- /dev/null +++ b/tests/test_character_io.mjs @@ -0,0 +1,106 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import vm from 'node:vm'; + +const script = readFileSync(new URL('../roll20_mod/ravenous_character_io.js', import.meta.url), 'utf8'); + +function session() { + const objects = new Map(); + const chat = []; + let nextId = 0; + let handler; + const createObj = (type, fields) => { + const data = { ...fields }; + const object = { + id: `id${++nextId}`, + type, + get(key, callback) { const value = data[key] ?? ''; if (callback) callback(value); else return value; }, + set(key, value) { data[key] = value; }, + data, + }; + objects.set(object.id, object); + return object; + }; + vm.runInNewContext(script, { + on(event, callback) { assert.equal(event, 'chat:message'); handler = callback; }, + playerIsGM: id => id === 'gm', + createObj, + getObj: (type, id) => objects.get(id)?.type === type ? objects.get(id) : undefined, + findObjs: query => [...objects.values()].filter(obj => obj.type === query.type && + obj.get('characterid') === query.characterid), + sendChat: (speaker, content) => chat.push({ speaker, content }), + encodeURIComponent, + decodeURIComponent, + }); + const send = (content, playerid = 'gm') => handler({ type: 'api', playerid, content }); + return { createObj, objects, chat, send }; +} + +test('export handout and import preserve notes and repeating attributes', () => { + const game = session(); + const original = game.createObj('character', { name: 'Arangar', bio: 'Bio é', + gmnotes: 'GM only', controlledby: 'player1', inplayerjournals: 'player1' }); + game.createObj('attribute', { characterid: original.id, name: 'force', current: '10', max: '' }); + game.createObj('attribute', { characterid: original.id, name: 'repeating_attacks_row1_name', current: 'Griffe', max: '' }); + game.createObj('attribute', { characterid: original.id, name: 'hp', current: '0', max: '20' }); + game.createObj('ability', { characterid: original.id, name: 'Roar', action: '/em Roars', istokenaction: true }); + game.send(`!ravenous-export ${original.id}`); + const handout = [...game.objects.values()].find(obj => obj.type === 'handout'); + assert.ok(handout); + assert.equal(handout.get('inplayerjournals'), ''); + assert.match(handout.get('gmnotes'), /"format": "ravenous-roll20-character"/); + game.send(`!ravenous-import --handout ${handout.id}`); + const characters = [...game.objects.values()].filter(obj => obj.type === 'character'); + assert.equal(characters.length, 2); + const imported = characters[1]; + assert.equal(imported.get('name'), 'Arangar'); + assert.equal(imported.get('bio'), 'Bio é'); + assert.equal(imported.get('gmnotes'), 'GM only'); + assert.equal(imported.get('controlledby'), 'player1'); + const attrs = [...game.objects.values()].filter(obj => obj.type === 'attribute' && obj.get('characterid') === imported.id); + assert.deepEqual(attrs.map(obj => [obj.get('name'), obj.get('current'), obj.get('max')]), [ + ['force', '10', ''], ['hp', '0', '20'], ['repeating_attacks_row1_name', 'Griffe', ''], + ]); + const ability = [...game.objects.values()].find(obj => obj.type === 'ability' && obj.get('characterid') === imported.id); + assert.equal(ability.get('action'), '/em Roars'); +}); + +test('inline JSON imports a character, while non-GM and invalid input do not', () => { + const game = session(); + const json = JSON.stringify({ format: 'ravenous-roll20-character', version: 1, + name: 'Creature', attributes: [{ name: 'force', current: '5', max: '' }] }); + game.send(`!ravenous-import ${json}`, 'player'); + game.send('!ravenous-import {bad}'); + game.send('!ravenous-import {"format":"wrong","name":"Bad","attributes":[]}'); + assert.equal(game.objects.size, 0); + game.send(`!ravenous-import ${json}`); + assert.equal([...game.objects.values()].filter(obj => obj.type === 'character').length, 1); + assert.match(game.chat.at(-1).content, /Imported 1 attributes/); +}); + +test('a GM can import JSON pasted into a handout and HTML escaped by Roll20', () => { + const game = session(); + const json = JSON.stringify({ format: 'ravenous-roll20-character', version: 1, + name: 'A & B', bio: 'Test', attributes: [] }); + const handout = game.createObj('handout', { gmnotes: `

${json.replace(/&/g, '&').replace(//g, '>')}

` }); + game.send(`!ravenous-import --handout ${handout.id}`); + const character = [...game.objects.values()].find(obj => obj.type === 'character'); + assert.equal(character.get('name'), 'A & B'); + assert.equal(character.get('bio'), 'Test'); +}); + +test('a converted database monster imports with its body parts and abilities', + { skip: !process.env.RAVENOUS_MONSTER_JSON }, () => { + const data = JSON.parse(readFileSync(process.env.RAVENOUS_MONSTER_JSON, 'utf8')); + const game = session(); + const handout = game.createObj('handout', { gmnotes: `
${JSON.stringify(data).replace(/&/g, '&').replace(//g, '>')}
` }); + game.send(`!ravenous-import --handout ${handout.id}`); + const character = [...game.objects.values()].find(obj => obj.type === 'character'); + assert.equal(character.get('name'), 'Arangar'); + const attrs = [...game.objects.values()].filter(obj => obj.type === 'attribute' && obj.get('characterid') === character.id); + assert.equal(attrs.length, data.attributes.length); + assert.ok(attrs.some(obj => obj.get('name') === 'repeating_locations_dbpart1_name' && obj.get('current') === 'Tête')); + assert.ok(attrs.some(obj => obj.get('name') === 'repeating_attacks_dbability5_name')); + assert.ok(attrs.some(obj => obj.get('name') === 'repeating_powers_dbability1_name')); +}); diff --git a/tests/test_monster_export.py b/tests/test_monster_export.py new file mode 100644 index 0000000..fd7d993 --- /dev/null +++ b/tests/test_monster_export.py @@ -0,0 +1,46 @@ +import json +import sqlite3 +import unittest + +from tools.export_monsters import DEFAULT_DB, convert + + +class MonsterExportTests(unittest.TestCase): + def setUp(self): + self.assertTrue(DEFAULT_DB.is_file(), "initialize the nested monster database submodule") + self.db = sqlite3.connect(DEFAULT_DB) + self.db.row_factory = sqlite3.Row + + def tearDown(self): + self.db.close() + + def test_master_creatures_have_importable_json_and_complete_source(self): + ids = [row[0] for row in self.db.execute( + "SELECT id FROM creature WHERE show_to_master = 1 ORDER BY id")] + self.assertEqual(len(ids), 21) + for creature_id in ids: + with self.subTest(creature_id=creature_id): + data = convert(self.db, creature_id) + self.assertEqual(data["format"], "ravenous-roll20-character") + self.assertEqual(data["version"], 1) + self.assertTrue(data["name"]) + attrs = {item["name"]: item["current"] for item in data["attributes"]} + self.assertEqual(len(attrs), len(data["attributes"])) + self.assertTrue(any(name.startswith("repeating_locations_") for name in attrs)) + source = json.loads(data["gmnotes"]) + self.assertEqual(source["database_creature_id"], creature_id) + self.assertEqual(len(source["body_parts"]), + sum(name.endswith("_hp") for name in attrs)) + self.assertEqual(len(source["abilities"]), + sum(name.endswith("_notes") and name.startswith("repeating_attacks_") + for name in attrs) + + sum(name.endswith("_description") and name.startswith("repeating_powers_") + for name in attrs)) + + def test_missing_creature_fails(self): + with self.assertRaisesRegex(ValueError, "No creature"): + convert(self.db, -1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/export_monsters.py b/tools/export_monsters.py new file mode 100644 index 0000000..efc0113 --- /dev/null +++ b/tools/export_monsters.py @@ -0,0 +1,124 @@ +"""Convert the pinned Ravenous monster SQLite database to Roll20 import JSON. + +The sheet uses hunter formulas, so monster values without a faithful sheet field +remain in GM notes alongside the complete source rows. +""" +import argparse +import json +import sqlite3 +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_DB = ROOT / "ravenous_typst/data/src/db/monsters.db" + + +def rows(db: sqlite3.Connection, table: str, creature_id: int) -> list[dict]: + order = {"creature_stats": "stats_id", "creature_body_parts": "body_part_id", + "creature_abilities": "attack_id", "creature_rewards": "reward_id"}[table] + return [dict(row) for row in db.execute( + f"SELECT * FROM {table} WHERE creature_id = ? ORDER BY {order}", (creature_id,))] + + +def text(value: object) -> str: + return "" if value is None else str(value) + + +def convert(db: sqlite3.Connection, creature_id: int) -> dict: + core_row = db.execute("SELECT * FROM creature WHERE id = ?", (creature_id,)).fetchone() + if core_row is None: + raise ValueError(f"No creature with ID {creature_id}") + core = dict(core_row) + stats_rows = rows(db, "creature_stats", creature_id) + if len(stats_rows) != 1: + raise ValueError(f"Expected one stats row for creature {creature_id}") + stats = stats_rows[0] + parts = rows(db, "creature_body_parts", creature_id) + abilities = rows(db, "creature_abilities", creature_id) + rewards = rows(db, "creature_rewards", creature_id) + attrs: dict[str, dict] = {} + + def add(name: str, value: object, maximum: object = "") -> None: + attrs[name] = {"name": name, "current": text(value), "max": text(maximum)} + + add("character_name", core["name"]) + add("force", stats["strength"]) + add("perception", stats["perception"]) + add("volonte", stats["willpower"]) + add("fatigue", stats["fatigue"]) + add("sang", stats["blood_base"]) + add("sang_max", stats["blood_base"]) + add("resist_transcendental", stats["resistance_transcendentale"]) + add("resist_alterations", stats["alteration_resistance"]) + + # Every body part is repeating: fixed hunter HP maxima would be recalculated. + for part in parts: + prefix = f"repeating_locations_dbpart{part['body_part_id']}_" + add(prefix + "name", part["body_part_name"]) + add(prefix + "hp", part["life_points_p1"]) + add(prefix + "hp_max", part["life_points_p1"]) + add(prefix + "protection", part["protection_p1"]) + add(prefix + "armor", part["integrity_p1"]) + add(prefix + "armor_max", part["integrity_p1"]) + + for ability in abilities: + ident = f"dbability{ability['attack_id']}" + description = "\n".join(filter(None, [ + f"Phase: {text(ability['phase'])}", + f"Type: {text(ability['attack_type'])}", + f"Dégâts: {text(ability['damage_regular'])}", + f"Succès: {text(ability['success'])}", + text(ability["description_all"]), text(ability["effects"]), + ])) + if ability["damage_regular"]: + prefix = f"repeating_attacks_{ident}_" + add(prefix + "name", ability["name"]) + add(prefix + "dice", 0) # The database does not specify the hunter roll pool. + add(prefix + "base_damage", 0) # Damage may be phase dependent or Typst markup. + add(prefix + "break_damage", ability["armor_break"] or 0) + add(prefix + "parry_threshold", ability["threshold_parry"] or 0) + add(prefix + "dodge_threshold", ability["threshold_dodge"] or 0) + add(prefix + "reposition_threshold", ability["threshold_repositionning"] or 0) + add(prefix + "notes", description) + else: + prefix = f"repeating_powers_{ident}_" + add(prefix + "name", ability["name"]) + add(prefix + "origin", core["name"]) + add(prefix + "stage", 0) + add(prefix + "type", ability["attack_type"]) + add(prefix + "description", description) + + source = {"database_creature_id": creature_id, "creature": core, + "stats": stats, "body_parts": parts, "abilities": abilities, + "rewards": rewards} + return {"format": "ravenous-roll20-character", "version": 1, + "name": core["name"], "bio": text(core["description"]), + "gmnotes": json.dumps(source, ensure_ascii=False), + "attributes": list(attrs.values())} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--id", type=int, help="database creature ID") + group.add_argument("--all", action="store_true", help="export all master-visible creatures") + parser.add_argument("--output", type=Path, required=True, + help="JSON file for --id, directory for --all") + parser.add_argument("--database", type=Path, default=DEFAULT_DB) + args = parser.parse_args() + if not args.database.is_file(): + parser.error("monster database missing; run git -C ravenous_typst submodule update --init data/src/db") + with sqlite3.connect(f"file:{args.database}?mode=ro", uri=True) as db: + db.row_factory = sqlite3.Row + ids = ([args.id] if args.id is not None else [row[0] for row in db.execute( + "SELECT id FROM creature WHERE show_to_master = 1 ORDER BY sort_id, id")]) + if args.all: + args.output.mkdir(parents=True, exist_ok=True) + for creature_id in ids: + data = convert(db, creature_id) + path = args.output / f"monster-{creature_id}.json" if args.all else args.output + path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(f"{creature_id}: {data['name']} -> {path}") + + +if __name__ == "__main__": + main()