From af91983bc733e545ba3515f40677c85e7f6cada7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 19 Sep 2026 20:31:47 +0200 Subject: [PATCH] feat: add player backups and craft fixtures --- Jenkinsfile | 5 +- README.md | 49 ++++++++-- TASKS.md | 4 + docs/macros.md | 27 +++++- docs/ravenous-craft-v1.schema.json | 2 +- roll20_mod/ravenous_character_io.js | 140 +++++++++++++++++++++------- scripts/build.sh | 19 +++- tests/test_build.py | 18 +++- tests/test_character_io.mjs | 57 +++++++++++ tests/test_craft_generator.py | 27 ++++++ tests/test_craft_import.mjs | 16 ++++ tools/build.py | 3 +- tools/generate_crafts.py | 79 ++++++++++++++++ 13 files changed, 398 insertions(+), 48 deletions(-) create mode 100644 tests/test_craft_generator.py create mode 100644 tools/generate_crafts.py diff --git a/Jenkinsfile b/Jenkinsfile index 3984a59..addce34 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -85,8 +85,9 @@ pipeline { uv run python -m unittest discover -s tests -v if command -v node >/dev/null 2>&1; then RAVENOUS_CHARACTER_JSON="${BUILD_DIR}/example-character.json" node tests/test_character_io.mjs + node tests/test_craft_import.mjs else - echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator test.' + echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator tests.' fi ./scripts/build.sh --check @@ -96,6 +97,8 @@ pipeline { test -f "${BUILD_DIR}/sheet.json" test -f "${BUILD_DIR}/build-info.json" test -f "${BUILD_DIR}/example-character.json" + test -f "${BUILD_DIR}/example-craft-forge.json" + test -f "${BUILD_DIR}/example-craft-alchemy.json" echo "Roll20 sheet build complete:" ls -lh "${BUILD_DIR}" diff --git a/README.md b/README.md index a158b48..0e8d79e 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,15 @@ Pour afficher les identifiants disponibles : ./scripts/build.sh --list-themes ``` +Pour produire un bundle dont le thème initial et de secours couvre aussi les +contrôles et boîtes d'interface situés hors de la zone recolorée, utilisez +`--theme-ui`. Tous les thèmes restent ensuite disponibles dans **Apparence** : + +```sh +./scripts/build.sh --theme-ui steel --output-dir build-steel +./scripts/build.sh --theme-ui steel --output-dir build-steel --check +``` + La limite des tiers d'école vient directement de `ravenous_typst/data/config/build.yaml` : seuls les tiers strictement inférieurs à `build.max_tier_exclusive` sont proposés par la feuille. Les trigrammes affichés @@ -112,11 +121,11 @@ 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. +`roll20_mod/ravenous_character_io.js` est le script Mod d'échange de personnages. +Installez-le comme **New Script** dans une partie avec la feuille Ravenous. Il +utilise le format JSON versionné `ravenous-roll20-character`. Un MJ peut créer un +nouveau personnage ; un joueur peut exporter un personnage qu'il contrôle et le +remplacer en place à partir d'un handout auquel il a accès. Dans le chat, en tant que MJ : @@ -127,8 +136,23 @@ Dans le chat, en tant que MJ : !ravenous-import {"format":"ravenous-roll20-character","version":1,"name":"Ariane","attributes":[]} ``` +Pour un joueur, sélectionnez un token lié à son personnage : + +```text +!ravenous-export +!ravenous-import --replace --handout ID_DU_HANDOUT +``` + +L'export joueur crée un handout contrôlé par ce joueur et place le JSON dans ses +**Notes** visibles. Le remplacement conserve l'objet personnage, son ID, ses +tokens liés, son avatar, ses droits et ses notes MJ ; il remplace son nom, sa bio, +ses attributs de feuille et ses capacités. Le JSON est entièrement validé avant +la suppression des anciennes lignes. Un joueur ne peut cibler qu'un personnage +qu'il contrôle ni lire un handout auquel il n'a pas accès. Le MJ peut aussi faire +un remplacement avec `--replace`, éventuellement suivi de `--id ID_DU_PERSONNAGE`. + Sans ID, sélectionnez exactement un token lié au personnage avant la commande. -Utilisez `--id` si vous ne disposez pas d'un token lié. L'export crée un handout +Utilisez `--id` si vous ne disposez pas d'un token lié. L'export MJ 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 @@ -160,6 +184,19 @@ l'agent ; l'absence de ce runtime n'empêche pas la construction de la feuille. Le script `./scripts/build.sh` génère automatiquement ce même exemple dans son dossier de sortie, et `./scripts/build.sh --check` vérifie également son contenu. +Le build génère aussi deux charges utiles prêtes à importer : +`build/example-craft-forge.json` (attaque et protection) et +`build/example-craft-alchemy.json` (consommable et effet temporaire). Copiez le +contenu d'un fichier dans les GM Notes d'un handout privé, puis sélectionnez un +token lié au personnage et lancez : + +```text +!ravenous-import-craft --handout ID_DU_HANDOUT +``` + +Ces exemples couvrent les quatre sections répétables prises en charge par +l'importeur et sont régénérés et vérifiés de façon déterministe par la CI. + 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 diff --git a/TASKS.md b/TASKS.md index f15b623..1878ccd 100644 --- a/TASKS.md +++ b/TASKS.md @@ -22,6 +22,8 @@ parser, browser, or chat. - [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. +- [x] Allow players to export controlled characters and restore them in place + without changing character IDs, token links, ownership, or GM-only notes. - [x] Define the versioned craft JSON interface and add a GM-only Mod importer for weapons, protections, consumables, and temporary effects. Validate all destinations, handout input, and invalid payloads locally. @@ -31,6 +33,8 @@ parser, browser, or chat. - [x] Generate, validate, and archive a deterministic randomized character JSON fixture covering all repeating sections in Jenkins. Import it through the Mod simulator when Node is available on the build agent. +- [x] Generate and archive deterministic forge and alchemy craft fixtures that + exercise all four destinations supported by the Roll20 craft importer. ## Next: Roll20 smoke test diff --git a/docs/macros.md b/docs/macros.md index 1ea2680..0b80a2c 100644 --- a/docs/macros.md +++ b/docs/macros.md @@ -19,10 +19,33 @@ Players cannot import into another player's character or read an unshared handout through the script. A GM can use the same macro with any character and handout. +## Player character backup and replacement + +Select one token linked to a character the player controls. Export creates a +handout controlled by that player, with JSON in its visible Notes. + +**Name:** `Ravenous — Sauvegarder le personnage` + +```text +!ravenous-export +``` + +To restore that JSON into the same Roll20 character while preserving its ID, +linked tokens, ownership, avatar, and GM Notes: + +**Name:** `Ravenous — Restaurer le personnage` + +```text +!ravenous-import --replace --handout ?{ID du handout personnage} +``` + +Replacement deletes the destination's existing sheet attributes and abilities. +The player must control both the selected character and the source handout. + ## GM character import -Character import creates a new journal character and remains GM-only. Put the -export JSON in a private handout's GM Notes. +Character creation remains GM-only. Put the export JSON in a private handout's +GM Notes. **Name:** `Ravenous — Importer un personnage` diff --git a/docs/ravenous-craft-v1.schema.json b/docs/ravenous-craft-v1.schema.json index 8d5b0bb..f5027e5 100644 --- a/docs/ravenous-craft-v1.schema.json +++ b/docs/ravenous-craft-v1.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://books.dandaedre.com/ravenous_sheet/ravenous-craft-v1.schema.json", + "$id": "https://books.dandaedre.com/RPG/ravenous_sheet/ravenous-craft-v1.schema.json", "title": "Ravenous Roll20 craft exchange", "type": "object", "additionalProperties": false, diff --git a/roll20_mod/ravenous_character_io.js b/roll20_mod/ravenous_character_io.js index beefc8e..5ec81ef 100644 --- a/roll20_mod/ravenous_character_io.js +++ b/roll20_mod/ravenous_character_io.js @@ -1,16 +1,32 @@ -/* Ravenous character exchange for Roll20 Mod. GM commands: +/* Ravenous character exchange for Roll20 Mod. Commands: * !ravenous-export (selected token's character) * !ravenous-export --id 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. + * !ravenous-import --replace [--id CHARACTER_ID] --handout HANDOUT_ID + * Players may export and replace characters they control. New-character import is GM-only. */ (function () { 'use strict'; var FORMAT = 'ravenous-roll20-character'; var VERSION = 1; - function whisper(message) { sendChat('Ravenous IO', '/w gm ' + message); } + function whisper(playerId, message) { + if (playerIsGM(playerId)) return sendChat('Ravenous IO', '/w gm ' + message); + var player = getObj('player', playerId); + var name = String(player && player.get('_displayname') || 'player').replace(/"/g, ''); + sendChat('Ravenous IO', '/w "' + name + '" ' + message); + } + function grantsAccess(list, playerId) { + return String(list || '').split(',').some(function (id) { return id === 'all' || id === playerId; }); + } + function canControl(character, playerId) { + return playerIsGM(playerId) || grantsAccess(character && character.get('controlledby'), playerId); + } + function canReadHandout(handout, playerId) { + return playerIsGM(playerId) || grantsAccess(handout && handout.get('controlledby'), playerId) || + grantsAccess(handout && handout.get('inplayerjournals'), playerId); + } function validText(value) { return typeof value === 'string' && value.length <= 200000; } function validPayload(data) { if (!data || Array.isArray(data) || typeof data !== 'object' || @@ -41,13 +57,25 @@ .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); + function readHandout(handout, isGM, callback) { + if (!isGM) return handout.get('notes', callback); + handout.get('gmnotes', function (gmnotes) { + if (String(gmnotes || '').trim()) return callback(gmnotes); + handout.get('notes', callback); + }); + } + function populateCharacter(character, data, replace, isGM, playerId) { + if (replace) { + findObjs({ type: 'attribute', characterid: character.id }).forEach(function (item) { item.remove(); }); + findObjs({ type: 'ability', characterid: character.id }).forEach(function (item) { item.remove(); }); + } + character.set('name', data.name.trim()); + character.set('bio', data.bio || ''); + if (isGM) { + character.set('gmnotes', data.gmnotes || ''); + character.set('controlledby', data.controlledby || ''); + character.set('inplayerjournals', data.inplayerjournals || ''); + } data.attributes.forEach(function (item) { createObj('attribute', { characterid: character.id, name: item.name, current: item.current, max: item.max }); @@ -56,11 +84,28 @@ createObj('ability', { characterid: character.id, name: item.name, action: item.action, istokenaction: item.istokenaction }); }); - whisper('Imported ' + data.attributes.length + ' attributes into character ' + character.id + '.'); + whisper(playerId, (replace ? 'Replaced ' : 'Imported ') + data.attributes.length + + ' attributes in character ' + character.id + '.'); } - function exportCharacter(id) { + function importCharacter(data, playerId, targetId) { + if (!validPayload(data)) return whisper(playerId, 'Invalid or unsupported Ravenous character JSON.'); + if (targetId) { + var target = getObj('character', targetId); + if (!target) return whisper(playerId, 'Character not found.'); + if (!canControl(target, playerId)) return whisper(playerId, 'Permission denied for that character.'); + return populateCharacter(target, data, true, playerIsGM(playerId), playerId); + } + if (!playerIsGM(playerId)) return whisper(playerId, 'Only a GM can create a new character. Use --replace on a character you control.'); + var character = createObj('character', { name: data.name.trim(), + controlledby: data.controlledby || '', inplayerjournals: data.inplayerjournals || '' }); + if (!character) return whisper(playerId, 'Roll20 could not create the character.'); + populateCharacter(character, data, false, true, playerId); + } + function exportCharacter(id, playerId) { var character = getObj('character', id); - if (!character) return whisper('Character not found. Use its Roll20 character ID.'); + if (!character) return whisper(playerId, 'Character not found. Use its Roll20 character ID.'); + if (!canControl(character, playerId)) return whisper(playerId, 'Permission denied for that character.'); + var isGM = playerIsGM(playerId); character.get('bio', function (bio) { character.get('gmnotes', function (gmnotes) { var attributes = findObjs({ type: 'attribute', characterid: id }).map(function (item) { @@ -76,53 +121,84 @@ var data = { format: FORMAT, version: VERSION, name: character.get('name'), controlledby: character.get('controlledby') || '', inplayerjournals: character.get('inplayerjournals') || '', - bio: bio || '', gmnotes: gmnotes || '', attributes: attributes, + bio: bio || '', gmnotes: isGM ? 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.'); + inplayerjournals: isGM ? '' : playerId, controlledby: isGM ? '' : playerId }); + if (!handout) return whisper(playerId, '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 + '.'); + handout.set(isGM ? 'gmnotes' : 'notes', '
' + readable + '
'); + whisper(playerId, 'Exported ' + attributes.length + ' attributes to handout ' + handout.id + '.'); }); }); } function selectedCharacterId(message) { var selected = message.selected || []; if (selected.length !== 1 || selected[0]._type !== 'graphic') { - whisper('Select one token representing a character, or use !ravenous-export --id CHARACTER_ID.'); + whisper(message.playerid, 'Select one token representing a character, or use --id CHARACTER_ID.'); return ''; } var token = getObj('graphic', selected[0]._id); var id = token && token.get('represents'); - if (!id) whisper('The selected token does not represent a character.'); + if (!id) whisper(message.playerid, 'The selected token does not represent a character.'); return id || ''; } + function importArguments(input) { + var result = { replace: false, id: '', handout: '', json: '' }; + var rest = input.trim(); + while (rest.indexOf('--') === 0) { + var flag = rest.match(/^--replace(?:\s+|$)/); + if (flag) { + if (result.replace) return null; + result.replace = true; + rest = rest.slice(flag[0].length); + continue; + } + var option = rest.match(/^--(id|handout)\s+(\S+)\s*/); + if (!option || result[option[1]]) return null; + result[option[1]] = option[2]; + rest = rest.slice(option[0].length); + } + result.json = rest; + if (!!result.handout === !!result.json || (!result.replace && result.id)) return null; + return result; + } on('chat:message', function (message) { - if (message.type !== 'api' || !playerIsGM(message.playerid)) return; + if (message.type !== 'api') return; var content = message.content.trim(); if (content === '!ravenous-export') { var selectedId = selectedCharacterId(message); - if (selectedId) return exportCharacter(selectedId); + if (selectedId) return exportCharacter(selectedId, message.playerid); return; } if (content.indexOf('!ravenous-export ') === 0) { var argument = content.slice('!ravenous-export '.length).trim(); if (argument.indexOf('--id ') === 0) argument = argument.slice('--id '.length).trim(); - return exportCharacter(argument); + return exportCharacter(argument, message.playerid); } 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.'); } + var args = importArguments(content.slice('!ravenous-import '.length)); + if (!args) return whisper(message.playerid, 'Invalid import command.'); + if (!playerIsGM(message.playerid) && !args.replace) + return whisper(message.playerid, 'Only a GM can create a new character. Use --replace.'); + var targetId = ''; + if (args.replace) { + targetId = args.id || selectedCharacterId(message); + if (!targetId) return; + if (!canControl(getObj('character', targetId), message.playerid)) + return whisper(message.playerid, 'Permission denied for that character.'); + } + if (args.handout) { + var handout = getObj('handout', args.handout); + if (!handout) return whisper(message.playerid, 'Handout not found.'); + if (!canReadHandout(handout, message.playerid)) return whisper(message.playerid, 'Permission denied for that handout.'); + return readHandout(handout, playerIsGM(message.playerid), function (notes) { + try { importCharacter(decodeHandout(notes), message.playerid, targetId); } + catch (error) { whisper(message.playerid, 'Handout does not contain valid Ravenous JSON.'); } }); } - try { importCharacter(JSON.parse(input)); } - catch (error) { whisper('Invalid JSON.'); } + try { importCharacter(JSON.parse(args.json), message.playerid, targetId); } + catch (error) { whisper(message.playerid, 'Invalid JSON.'); } }); }()); diff --git a/scripts/build.sh b/scripts/build.sh index a5dceea..17cb87a 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -33,14 +33,25 @@ done [ "$list_themes" -eq 1 ] && exit 0 example="$output_dir/example-character.json" +craft_forge="$output_dir/example-craft-forge.json" +craft_alchemy="$output_dir/example-craft-alchemy.json" if [ "$check" -eq 1 ]; then - temporary=$(mktemp) - trap 'rm -f "$temporary"' EXIT HUP INT TERM - uv run python tools/generate_character.py --seed 20260919 --output "$temporary" >/dev/null - if ! cmp -s "$temporary" "$example"; then + temporary_dir=$(mktemp -d) + trap 'rm -rf "$temporary_dir"' EXIT HUP INT TERM + uv run python tools/generate_character.py --seed 20260919 --output "$temporary_dir/example-character.json" >/dev/null + uv run python tools/generate_crafts.py --output-dir "$temporary_dir" >/dev/null + if ! cmp -s "$temporary_dir/example-character.json" "$example"; then echo "$example is missing or differs from the seeded character fixture" >&2 exit 1 fi + for craft in "$craft_forge" "$craft_alchemy"; do + name=${craft##*/} + if ! cmp -s "$temporary_dir/$name" "$craft"; then + echo "$craft is missing or differs from the generated craft fixture" >&2 + exit 1 + fi + done else uv run python tools/generate_character.py --seed 20260919 --output "$example" + uv run python tools/generate_crafts.py --output-dir "$output_dir" fi diff --git a/tests/test_build.py b/tests/test_build.py index 2737063..dc5005d 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -1,5 +1,6 @@ import json import subprocess +import tempfile import unittest from pathlib import Path @@ -16,7 +17,9 @@ class BuildTests(unittest.TestCase): expected = {"ravenous.html", "ravenous.css", "translation.json", "sheet.json", "build-info.json"} actual = {path.name for path in (ROOT / "build").iterdir()} self.assertTrue(expected.issubset(actual)) - self.assertLessEqual(actual - expected, {"example-character.json"}) + self.assertLessEqual(actual - expected, { + "example-character.json", "example-craft-forge.json", "example-craft-alchemy.json" + }) def test_source_data_was_imported(self): info = json.loads((ROOT / "build/build-info.json").read_text()) @@ -245,6 +248,19 @@ class BuildTests(unittest.TestCase): self.assertNotIn("{{THEME_VARS}}", css) self.assertNotIn("{{THEME_CSS}}", css) + def test_export_can_choose_initial_ui_theme(self): + with tempfile.TemporaryDirectory() as directory: + command = ["python", "tools/build.py", "--theme-ui", "steel", "--output-dir", directory] + subprocess.run(command, cwd=ROOT, check=True, capture_output=True) + sheet = (Path(directory) / "ravenous.html").read_text() + css = (Path(directory) / "ravenous.css").read_text() + info = json.loads((Path(directory) / "build-info.json").read_text()) + self.assertIn('