rpg-engine 0.4.1 → 0.5.0

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.
Files changed (80) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/ask.d.ts +37 -2
  3. package/dist/commands/ask.js +46 -17
  4. package/dist/commands/config.js +4 -2
  5. package/dist/commands/game-extension-list.js +12 -0
  6. package/dist/commands/game-extensions.d.ts +1 -1
  7. package/dist/commands/game-extensions.js +242 -17
  8. package/dist/commands/game-system-code.d.ts +9 -1
  9. package/dist/commands/game-system-code.js +27 -11
  10. package/dist/commands/game-widgets.d.ts +6 -1
  11. package/dist/commands/game-widgets.js +52 -4
  12. package/dist/commands/game-world.d.ts +15 -3
  13. package/dist/commands/game-world.js +45 -14
  14. package/dist/commands/package.d.ts +7 -1
  15. package/dist/commands/package.js +17 -2
  16. package/dist/commands/scene.d.ts +1 -1
  17. package/dist/commands/view.d.ts +4 -0
  18. package/dist/commands/view.js +5 -3
  19. package/dist/core/context.d.ts +19 -0
  20. package/dist/core/files.d.ts +2 -0
  21. package/dist/core/files.js +10 -1
  22. package/dist/core/registry.d.ts +2 -0
  23. package/dist/dashboard/api.js +11 -3
  24. package/dist/dashboard/app.js +88 -8
  25. package/dist/dashboard/ask-card.js +118 -0
  26. package/dist/dashboard/dice/tray.js +5 -3
  27. package/dist/dashboard/extension-widgets.js +35 -9
  28. package/dist/dashboard/faces.js +6 -4
  29. package/dist/dashboard/help.js +10 -3
  30. package/dist/dashboard/i18n/ar.json +9 -0
  31. package/dist/dashboard/i18n/cs.json +9 -0
  32. package/dist/dashboard/i18n/da.json +9 -0
  33. package/dist/dashboard/i18n/de.json +9 -0
  34. package/dist/dashboard/i18n/el.json +9 -0
  35. package/dist/dashboard/i18n/es.json +9 -0
  36. package/dist/dashboard/i18n/fi.json +9 -0
  37. package/dist/dashboard/i18n/fr.json +9 -0
  38. package/dist/dashboard/i18n/he.json +9 -0
  39. package/dist/dashboard/i18n/hi.json +9 -0
  40. package/dist/dashboard/i18n/hu.json +9 -0
  41. package/dist/dashboard/i18n/is.json +9 -0
  42. package/dist/dashboard/i18n/it.json +9 -0
  43. package/dist/dashboard/i18n/ja.json +9 -0
  44. package/dist/dashboard/i18n/ko.json +9 -0
  45. package/dist/dashboard/i18n/nb.json +9 -0
  46. package/dist/dashboard/i18n/nl.json +9 -0
  47. package/dist/dashboard/i18n/pl.json +9 -0
  48. package/dist/dashboard/i18n/pt.json +9 -0
  49. package/dist/dashboard/i18n/ro.json +9 -0
  50. package/dist/dashboard/i18n/ru.json +9 -0
  51. package/dist/dashboard/i18n/sv.json +9 -0
  52. package/dist/dashboard/i18n/tr.json +9 -0
  53. package/dist/dashboard/i18n/uk.json +9 -0
  54. package/dist/dashboard/i18n/zh.json +9 -0
  55. package/dist/dashboard/pack-card.js +92 -0
  56. package/dist/dashboard/packages.js +11 -4
  57. package/dist/dashboard/rolls.js +2 -2
  58. package/dist/dashboard/style.css +521 -3
  59. package/dist/dashboard-server.js +57 -1
  60. package/dist/extensions/api.d.ts +148 -17
  61. package/dist/extensions/extension.d.ts +10 -3
  62. package/dist/extensions/extension.js +16 -3
  63. package/dist/extensions/index.d.ts +3 -3
  64. package/dist/extensions/index.js +2 -2
  65. package/dist/extensions/packages.d.ts +8 -0
  66. package/dist/extensions/packages.js +48 -1
  67. package/dist/extensions/words.d.ts +2 -1
  68. package/dist/extensions/words.js +5 -4
  69. package/dist/index.d.ts +1 -1
  70. package/dist/mcp-server.js +1 -1
  71. package/dist/pages/index.d.ts +1 -1
  72. package/dist/pages/index.js +1 -1
  73. package/dist/pages/standard-fields.d.ts +2 -0
  74. package/dist/pages/standard-fields.js +8 -1
  75. package/dist/systems/game-system.d.ts +14 -9
  76. package/dist/systems/game-system.js +29 -19
  77. package/dist/systems/index.d.ts +1 -1
  78. package/dist/testing.d.ts +61 -0
  79. package/dist/testing.js +162 -0
  80. package/package.json +7 -2
package/README.md CHANGED
@@ -85,7 +85,7 @@ The code is under the [MIT](https://github.com/stefanocaronia/rpg-engine/blob/ma
85
85
 
86
86
  The 5e system, in `systems/5e/`, is under the Creative Commons Attribution 4.0 International License ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/systems/5e/LICENSE.md)): This work includes material taken from the System Reference Document 5.1 ("SRD 5.1") by Wizards of the Coast LLC and available at https://dnd.wizards.com/resources/systems-reference-document. The SRD 5.1 is licensed under the Creative Commons Attribution 4.0 International License available at https://creativecommons.org/licenses/by/4.0/legalcode. Its creatures' icons are from game-icons.net, under the Creative Commons Attribution 3.0 Unported License, by the authors its license names. rpg-engine is compatible with fifth edition.
87
87
 
88
- The weather extension, in `extensions/weather/` and published apart as `@rpgengine/weather`, is Weather by the climate score, by Stefano Caronia, CC BY 4.0, with its code under MIT ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/extensions/weather/LICENSE.md)).
88
+ Our extensions are packages of their own, installed only when a campaign wants them: [weather](https://github.com/stefanocaronia/rpg-engine-weather) (`@rpgengine/weather`), Weather by the climate score, and [lockpicking](https://github.com/stefanocaronia/rpg-engine-lockpicking) (`@rpgengine/lockpicking`), Lockpicking by complexity, both by Stefano Caronia under CC BY 4.0, with their code under MIT; each repo has its license.
89
89
 
90
90
  rpg-engine ships only original or open-licensed content: for fifth edition, the SRD 5.1 under CC BY 4.0. Anything else that appears in your game is written by your AI or by you, as pages of your campaign on your computer: it is not part of rpg-engine, and we do not distribute it.
91
91
 
@@ -1,16 +1,18 @@
1
1
  import { z } from "zod";
2
- import type { Context, Rows, Said } from "../core/context.ts";
2
+ import type { CardAsked, Context, Rows, Said } from "../core/context.ts";
3
3
  type InWords = {
4
4
  kind: "unanswered" | "unavailable" | "absent" | "physical" | "dice in words";
5
5
  asked: string;
6
6
  };
7
- type AskResult = {
7
+ /** What the player answered, or the question to ask them in words. */
8
+ export type AskResult = {
8
9
  kind: "roll";
9
10
  id: string;
10
11
  who: string;
11
12
  check: string;
12
13
  text: string;
13
14
  total: number;
15
+ faces: number[];
14
16
  notes?: string[];
15
17
  } | {
16
18
  kind: "changed";
@@ -36,6 +38,39 @@ export declare const ask: import("../core/registry.ts").Command<z.ZodObject<{
36
38
  square: z.ZodOptional<z.ZodBoolean>;
37
39
  recipe: z.ZodOptional<z.ZodString>;
38
40
  }, z.core.$strip>, AskResult>;
41
+ /**
42
+ * A roll of the player's character asked with buttons (ASK-3, ASK-8, ASK-12): for ask, and for an extension's code (D-505). With physical dice it is the question
43
+ * to ask in words; a call stopped logs nothing (ASK-9).
44
+ */
45
+ export declare function askedRoll(root: string, context: Context, question: string, checks: {
46
+ label: string;
47
+ notation?: string;
48
+ }[], given: string | undefined, told?: Told): Promise<AskResult>;
49
+ /** What an extension's roll asked tells in its own words (D-505): the button that turns it down, and what the faces mean, logged in place of the total. */
50
+ export interface Told {
51
+ /** The roll's button in place of the core's words, with a note under it. */
52
+ roll?: Button;
53
+ /** The button that turns it down, renamed; false for none, when the roll is forced (D-507). */
54
+ decline?: Button | false;
55
+ /** The rule under the buttons, in a line. */
56
+ rule?: string;
57
+ /** The card of a widget the page asks it in (D-507). */
58
+ card?: CardAsked;
59
+ says?: (faces: number[]) => string;
60
+ /** How each die turned out, by its face in order: kept in the roll's line only when there is one for each, good, bad or none. */
61
+ tones?: (faces: number[]) => unknown[];
62
+ }
63
+ /** A button's name, and the note under it. */
64
+ export interface Button {
65
+ name: string;
66
+ note?: string;
67
+ }
68
+ /** How the dice turned out, for the roll's line: one for each face, good, bad or none; nothing for any other list, which a package gave wrong. */
69
+ export declare function tonesOf(given: unknown[] | undefined, faces: number[]): {
70
+ tones?: ("good" | "bad" | null)[];
71
+ };
72
+ /** Whether a text is the dice of a check, as 1d20+5 or 1d20+athletics (ASK-2, ASK-12). */
73
+ export declare function isCheckDice(text: string): boolean;
39
74
  /**
40
75
  * The player's answer, on the dashboard's page and in the host's form at once, where both are (ASK-13, D-455): the first answer wins and takes the other
41
76
  * away; one that never showed, a page not open or a form the host does not show, leaves the other to answer. Neither shown is absent: the master asks in words.
@@ -75,7 +75,7 @@ export const ask = defineCommand({
75
75
  throw new Error("The player cannot be asked with buttons here: ask them in words, without a word about buttons, and stop.");
76
76
  }
77
77
  const question = input.question.trim();
78
- const words = buttonWords[(readSettings(root).language ?? "en").split("-")[0]] ?? buttonWords.en;
78
+ const words = buttonWordsOf(root);
79
79
  if (question === "") {
80
80
  throw new Error("Give the question: for a roll, what is at stake either way; for a choice, what the player chooses.");
81
81
  }
@@ -103,13 +103,7 @@ export const ask = defineCommand({
103
103
  if (checks.length < options.length) {
104
104
  throw new Error(`Give every check its dice, such as Atletica 1d20+5; for a choice, give only the answers, such as Sì and No. A roll already has its button to change one's mind (${words.change}): leave out an answer such as No.`);
105
105
  }
106
- const who = playerCharacter(loadWorld(root), input.who);
107
- const worked = sheetChecks(root, context, checks, who);
108
- // The player rolls their own dice: a roll is asked in words, and they tell the values (ASK-8).
109
- if (readSettings(root).dice === "physical") {
110
- return { kind: "physical", asked: askedText(question, "checks", worked) };
111
- }
112
- return rollChosen(root, context, question, worked, who, words);
106
+ return askedRoll(root, context, question, checks, input.who);
113
107
  },
114
108
  format(result) {
115
109
  switch (result.kind) {
@@ -140,18 +134,51 @@ export const ask = defineCommand({
140
134
  }
141
135
  },
142
136
  });
137
+ /**
138
+ * A roll of the player's character asked with buttons (ASK-3, ASK-8, ASK-12): for ask, and for an extension's code (D-505). With physical dice it is the question
139
+ * to ask in words; a call stopped logs nothing (ASK-9).
140
+ */
141
+ export async function askedRoll(root, context, question, checks, given, told = {}) {
142
+ const who = playerCharacter(loadWorld(root), given);
143
+ const worked = sheetChecks(root, context, checks, who);
144
+ // The player rolls their own dice: a roll is asked in words, and they tell the values (ASK-8).
145
+ if (readSettings(root).dice === "physical") {
146
+ return { kind: "physical", asked: askedText(question, "checks", worked) };
147
+ }
148
+ return rollChosen(root, context, question, worked, who, buttonWordsOf(root), told);
149
+ }
150
+ /** How the dice turned out, for the roll's line: one for each face, good, bad or none; nothing for any other list, which a package gave wrong. */
151
+ export function tonesOf(given, faces) {
152
+ const known = (tone) => tone === "good" || tone === "bad" || tone === undefined || tone === null;
153
+ return given === undefined || !Array.isArray(given) || given.length !== faces.length || !given.every(known) || given.every((tone) => tone === undefined || tone === null)
154
+ ? {}
155
+ : { tones: given.map((tone) => (tone === "good" || tone === "bad" ? tone : null)) };
156
+ }
157
+ /** Whether a text is the dice of a check, as 1d20+5 or 1d20+athletics (ASK-2, ASK-12). */
158
+ export function isCheckDice(text) {
159
+ return isDice(namesAsZero(text));
160
+ }
161
+ /** The words of the buttons in the campaign's language (ASK-7). */
162
+ function buttonWordsOf(root) {
163
+ return buttonWords[(readSettings(root).language ?? "en").split("-")[0]] ?? buttonWords.en;
164
+ }
143
165
  /**
144
166
  * The buttons of a roll: the checks and a change of mind (ASK-3, ASK-4); a death save, only its check, as no one turns it down (D-460). The chosen check is
145
167
  * rolled with the engine's dice and logged as the player's roll.
146
168
  */
147
- async function rollChosen(root, context, question, checks, who, words) {
169
+ async function rollChosen(root, context, question, checks, who, words, told = {}) {
148
170
  const system = campaignSystem(root, context);
149
171
  const save = systemAsking(root, context, { who, notations: checks.map((check) => check.notation ?? "") });
150
- const change = save === undefined ? [words.change] : [];
172
+ const decline = told.decline === false ? undefined : told.decline?.name ?? words.change;
173
+ const change = save === undefined && decline !== undefined ? [decline] : [];
151
174
  const labels = [...checks.map((check) => `${words.roll}: ${check.label} (${check.notation})`), ...change];
152
175
  const language = readSettings(root).language ?? system?.language ?? "en";
153
- const shown = [...checks.map((check) => formLabel(check, (dice) => (system === undefined ? undefined : rollName(system, dice, language)))), ...change];
154
- const rows = { who, fields: [...checks.map((check) => check.field ?? null), ...change.map(() => null)], ...(save === undefined ? {} : { save }) };
176
+ const formed = (check) => told.roll?.name ?? formLabel(check, (dice) => (system === undefined ? undefined : rollName(system, dice, language)));
177
+ const shown = [...checks.map(formed), ...change];
178
+ // A package's words for its buttons, its rule and its card, for the page (D-507).
179
+ const buttons = told.roll === undefined && typeof told.decline !== "object" ? {} : { buttons: [...checks.map(() => told.roll ?? null), ...change.map(() => (typeof told.decline === "object" ? told.decline : null))] };
180
+ const own = { ...buttons, ...(told.rule === undefined ? {} : { rule: told.rule }), ...(told.card === undefined ? {} : { card: told.card }) };
181
+ const rows = { who, fields: [...checks.map((check) => check.field ?? null), ...change.map(() => null)], ...(save === undefined ? {} : { save }), ...own };
155
182
  const chosen = await chooseAnswer(context, question, words.roll, labels, rows, shown);
156
183
  const asked = askedText(question, "checks", checks);
157
184
  // A call the user stopped logs nothing (ASK-9).
@@ -167,16 +194,18 @@ async function rollChosen(root, context, question, checks, who, words) {
167
194
  }
168
195
  const check = chosen === undefined ? undefined : checks[chosen];
169
196
  if (check?.notation === undefined) {
170
- logAnswer(root, context, question, labels, chosen === checks.length ? words.change : undefined);
197
+ logAnswer(root, context, question, labels, chosen === checks.length ? decline : undefined);
171
198
  return chosen === checks.length ? { kind: "changed" } : { kind: "unanswered", asked };
172
199
  }
173
200
  const diceRoll = rollDice(check.notation, { random: context.random });
174
- const data = { notation: diceRoll.notation, total: diceRoll.total, result: diceRoll.text, why: `${check.label}: ${question}`, check: check.label, who, physical: false, dice: diceRoll.dice };
201
+ const says = told.says === undefined ? {} : { says: told.says(diceRoll.faces) };
202
+ const tones = tonesOf(told.tones?.(diceRoll.faces), diceRoll.faces);
203
+ const data = { notation: diceRoll.notation, total: diceRoll.total, result: diceRoll.text, ...says, ...tones, why: `${check.label}: ${question}`, check: check.label, who, physical: false, dice: diceRoll.dice };
175
204
  const entry = newDatedLogEntry(root, { ...context, actor: "player" }, "roll", "public", data);
176
205
  appendLogEntry(root, entry);
177
206
  // A check of a dying character is their death save, which the engine writes (DIE-4, D-460).
178
207
  const notes = allSaid(systemRolled(root, context, { who, notation: diceRoll.notation, total: diceRoll.total, dice: diceRoll.dice }));
179
- return { kind: "roll", id: entry.id, who, check: check.label, text: diceRoll.text, total: diceRoll.total, ...(notes.length === 0 ? {} : { notes }) };
208
+ return { kind: "roll", id: entry.id, who, check: check.label, text: diceRoll.text, total: diceRoll.total, faces: diceRoll.faces, ...(notes.length === 0 ? {} : { notes }) };
180
209
  }
181
210
  /**
182
211
  * Where the player's character moves on the map of its place (ASK-11): only the page can show the map; the square touched moves it, as move with at, and the
@@ -250,7 +279,7 @@ async function diceSpent(root, context, question, recipeName, given, words) {
250
279
  if (context.page?.spendDice === undefined) {
251
280
  return { kind: "dice in words", asked: inWords };
252
281
  }
253
- const fieldWords = systemWordsOf(system, settings.language ?? system.language ?? "en", context)?.fields ?? {};
282
+ const fieldWords = systemWordsOf(root, system, settings.language ?? system.language ?? "en", context)?.fields ?? {};
254
283
  const label = (field) => String(valueNamed(fieldWords, field) ?? field);
255
284
  const from = counterOn(world, who, gives)?.value ?? 0;
256
285
  const rolls = [];
@@ -454,7 +483,7 @@ function readOption(text) {
454
483
  // The dice from the first word that is a die, so that 1d20+athletics - 1 and 1d20 + athletics are dice too; else the last word.
455
484
  const spaced = /^(.+?)\s+(\d*d(?:\d+|%|F)\S*(?:\s*[+-]\s*\S+)*)$/i.exec(text);
456
485
  const last = /^(.+?)\s+(\S+)$/.exec(text);
457
- const match = [spaced, last].find((candidate) => candidate !== null && isDice(namesAsZero(candidate[2])));
486
+ const match = [spaced, last].find((candidate) => candidate !== null && isCheckDice(candidate[2]));
458
487
  return match === undefined || match === null ? { label: text } : { label: match[1].trim(), notation: match[2] };
459
488
  }
460
489
  /**
@@ -19,7 +19,7 @@ import { campaignCoins, coinsShown } from "./game-money.js";
19
19
  import { readOpenScene } from "./game-scene.js";
20
20
  import { campaignCalendar, newDatedLogEntry } from "./game-time.js";
21
21
  import { checkWidgetSpots } from "./game-widgets.js";
22
- import { campaignSystem, campaignWorld, countedByGame, installedSystemName, systemSetting, systemSettingValue, valuesText } from "./game-world.js";
22
+ import { campaignSystem, campaignWorld, countedByGame, installedSystemName, systemLayers, systemSetting, systemSettingValue, valuesText } from "./game-world.js";
23
23
  import { mentorPart, stylePart } from "./parts.js";
24
24
  // A use whose maximum reads what gives it, in quotes for its commas (CAM-1).
25
25
  const counterExample = 'bulwark-dice: {max: "4 * has(features, Bulwark)", refill: short rest}';
@@ -665,7 +665,9 @@ function checkAdditions(root, context, setting, change) {
665
665
  const held = data[setting] !== null && typeof data[setting] === "object" && !Array.isArray(data[setting]) ? data[setting] : {};
666
666
  const dropped = [...(change.remove ?? []), ...Object.keys(change.set ?? {})];
667
667
  const entries = { ...Object.fromEntries(Object.entries(held).filter(([name]) => !dropped.some((other) => comparableText(other) === comparableText(name)))), ...change.set };
668
- const problem = findCampaignSystem(context.systemFolders, system, { ...data, [setting]: entries }).problem;
668
+ // Over what the campaign's extensions add, as the campaign plays it (CAM-2).
669
+ const layers = systemLayers(root, context, { ...data, [setting]: entries });
670
+ const problem = findCampaignSystem(context.systemFolders, system, layers).refused.find((layer) => layer.from === layers.at(-1)?.from)?.problem;
669
671
  if (problem !== undefined) {
670
672
  throw new Error(`With this, the system ${system} would not read: ${problem} Nothing changed.`);
671
673
  }
@@ -5,6 +5,7 @@ import { campaignFileName, readOneSetting, readTextSetting } from "../campaign/i
5
5
  import { files, isInside } from "../core/store.js";
6
6
  import { comparableText } from "../core/text.js";
7
7
  import { findExtension, isVerified } from "../extensions/index.js";
8
+ import { isCoreField } from "../pages/index.js";
8
9
  /**
9
10
  * The extensions campaign.yaml lists (D-27), each as installed on this computer, in the order written: the nearest layer last. One not installed, that does not
10
11
  * read, that needs another game system or has the name of another is left out, with its problem: the campaign plays without it.
@@ -54,6 +55,10 @@ export function extensionsLine(root, context) {
54
55
  const { extensions } = campaignExtensions(root, context);
55
56
  return extensions.length === 0 ? "" : `Extensions: ${extensions.map((extension) => `${extension.name} (${extension.about})`).join("; ")}.`;
56
57
  }
58
+ /** The fields of the core an extension declares among its fields or counters, which no extension may write (D-505). */
59
+ function coreFieldsOf(extension) {
60
+ return [...Object.keys(extension.adds.fields ?? {}), ...Object.keys(extension.adds.counters ?? {})].filter(isCoreField);
61
+ }
57
62
  function readCampaignExtensions(root, context) {
58
63
  const extensions = [];
59
64
  const problems = [];
@@ -77,6 +82,13 @@ function readCampaignExtensions(root, context) {
77
82
  fix: `take it away with package remove ${extension.name}`,
78
83
  });
79
84
  }
85
+ else if (coreFieldsOf(extension).length > 0) {
86
+ problems.push({
87
+ path: campaignFileName,
88
+ message: `The extension ${name} declares ${coreFieldsOf(extension).join(", ")}, which the engine's own pages hold: it is left out.`,
89
+ fix: `install another version of it with package install ${extension.name}, or take it away with package remove ${extension.name}`,
90
+ });
91
+ }
80
92
  else if (extensions.some((other) => other.name === extension.name)) {
81
93
  problems.push({
82
94
  path: campaignFileName,
@@ -30,5 +30,5 @@ export declare function timePassedLines(root: string, context: Context, from: Ga
30
30
  * an extension that ships its source too is loaded from it.
31
31
  */
32
32
  export declare function extensionCode(extension: Extension): Promise<ExtensionCode | undefined>;
33
- /** The game as a widget of an extension reads it (D-502): the game its commands reach, without the dice, the log or writing. */
33
+ /** The game as a widget of an extension reads it (D-502, D-505): the time, where the party is and who is in it, a page, the scene and the extension's state. */
34
34
  export declare function gameViewOf(root: string, context: Context, extension: Extension): GameView;
@@ -12,15 +12,27 @@ import { pathToFileURL } from "node:url";
12
12
  import { parse, stringify } from "yaml";
13
13
  import { z } from "zod";
14
14
  import { campaignFileName, readTextSetting, requireCampaign } from "../campaign/index.js";
15
+ import { realPath } from "../core/files.js";
16
+ import { parseFormula } from "../core/formula.js";
15
17
  import { appendLogEntry } from "../core/log.js";
16
18
  import { defineCommand } from "../core/registry.js";
17
19
  import { files } from "../core/store.js";
20
+ import { sameName, valueNamed } from "../core/text.js";
18
21
  import { rollDice } from "../dice/index.js";
19
- import { environmentAt, isInParty, locate, playerCharacters } from "../pages/index.js";
22
+ import { extensionWords, wordIn } from "../extensions/index.js";
23
+ import { environmentAt, isCoreField, isInParty, isPlayerCharacter, locate, pagesWithNameOrAlias, playerCharacters } from "../pages/index.js";
24
+ import { findSystem } from "../systems/index.js";
20
25
  import { formatGameDate } from "../time/index.js";
26
+ import { askedRoll, isCheckDice, tonesOf } from "./ask.js";
27
+ import { effectiveFields } from "./effect-layer.js";
21
28
  import { campaignExtensions, runsCode } from "./game-extension-list.js";
29
+ import { behindTheScreen, sealHiddenRoll } from "./game-master-rolls.js";
30
+ import { readOpenScene } from "./game-scene.js";
31
+ import { setFields, systemPage } from "./game-system-code.js";
22
32
  import { calendarDayOf, newDatedLogEntry, presentDate } from "./game-time.js";
23
- import { campaignWorld } from "./game-world.js";
33
+ import { widgetCard } from "./game-widgets.js";
34
+ import { campaignWorld, extensionLayer, playedLayers } from "./game-world.js";
35
+ import { formulaValue } from "./worked-out.js";
24
36
  /** The folder of the campaign where an extension keeps its own files, its state among them (D-433, D-436). */
25
37
  export const extensionsFolderName = "extensions";
26
38
  /** The longest description a command of an extension may give the master, in words (D-441): it is read in every chat. */
@@ -105,9 +117,19 @@ function asCommand(extension, command, taken) {
105
117
  input: command.input,
106
118
  readOnly: command.readOnly,
107
119
  positionals: command.positionals,
120
+ waitsForPlayer: command.needsPlayer,
108
121
  async run(input, called) {
109
122
  const campaign = requireCampaign(called.folder);
110
- return { text: await command.run(input, gameOf(campaign, called, extension)) };
123
+ const asked = {};
124
+ try {
125
+ return { text: await command.run(input, gameOf(campaign, called, extension, asked)) };
126
+ }
127
+ finally {
128
+ // The card of its last question, as it is after the dice, read once the call ends, however it ends (D-507).
129
+ if (asked.card !== undefined) {
130
+ called.page?.cardEnded?.(asked.card);
131
+ }
132
+ }
111
133
  },
112
134
  format: (result) => result.text,
113
135
  });
@@ -125,7 +147,8 @@ export function extensionCode(extension) {
125
147
  if (entry === undefined) {
126
148
  return Promise.resolve(undefined);
127
149
  }
128
- const url = `${pathToFileURL(entry).href}?v=${encodeURIComponent(extension.version)}&installs=${installs}`;
150
+ // By its real path, as Node would resolve it: a package linked from a folder of the player's is read from that folder, its own settings beside it.
151
+ const url = `${pathToFileURL(realPath(entry)).href}?v=${encodeURIComponent(extension.version)}&installs=${installs}`;
129
152
  const code = loaded.get(url) ?? import(__rewriteRelativeImportExtension(url)).then((module) => {
130
153
  if (typeof module.default !== "function") {
131
154
  throw new Error(`its code, ${entry}, has no default export that gives its commands`);
@@ -135,14 +158,54 @@ export function extensionCode(extension) {
135
158
  loaded.set(url, code);
136
159
  return code;
137
160
  }
138
- /** The game as an extension's code reaches it (D-436): the dice, the time, where the party is, its own state and the log; nothing else is written. */
139
- function gameOf(root, context, extension) {
140
- const statePath = join(root, extensionsFolderName, extension.name, "state.yaml");
161
+ /**
162
+ * The game as an extension's code reaches it (D-436, D-505): what a widget reads, the dice, asking the player, its own state, the fields it adds and the log;
163
+ * nothing else is written, and nothing once the call is stopped (ASK-9).
164
+ */
165
+ function gameOf(root, context, extension, asked = {}) {
166
+ const view = gameViewOf(root, context, extension);
167
+ const live = () => {
168
+ if (context.signal?.aborted === true) {
169
+ throw new Error("The call was stopped: nothing more is written.");
170
+ }
171
+ };
141
172
  return {
142
- roll: (notation) => {
173
+ ...view,
174
+ roll: (notation, by) => {
175
+ if (by !== undefined) {
176
+ live();
177
+ return rollFor(root, context, notation, by, (text) => extensionText(root, extension, text));
178
+ }
143
179
  const rolled = rollDice(notation, { random: context.random });
144
180
  return { total: rolled.total, faces: rolled.faces, text: rolled.text };
145
181
  },
182
+ set: (page, values, why) => {
183
+ live();
184
+ setOwnFields(root, context, extension, page, values, why);
185
+ },
186
+ ask: async (wanted) => {
187
+ live();
188
+ const { who, question, check, notation } = wanted;
189
+ const told = toldOf(root, context, extension, wanted);
190
+ asked.card = told.card ?? asked.card;
191
+ return askedOf(await askedRoll(root, context, askedQuestion(extensionText(root, extension, question), check, notation), [{ label: check.trim(), notation }], who, told));
192
+ },
193
+ state: {
194
+ read: view.state.read,
195
+ write: (value) => {
196
+ live();
197
+ files().write(statePath(root, extension), `# The state of the extension ${extension.package}, kept by its code.\n${stringify(value, { lineWidth: 0 })}`);
198
+ },
199
+ },
200
+ log: (text, visibility = "hidden") => {
201
+ live();
202
+ appendLogEntry(root, newDatedLogEntry(root, context, "extension", visibility, { extension: extension.name, text }));
203
+ },
204
+ };
205
+ }
206
+ /** The game as a widget of an extension reads it (D-502, D-505): the time, where the party is and who is in it, a page, the scene and the extension's state. */
207
+ export function gameViewOf(root, context, extension) {
208
+ return {
146
209
  now: () => {
147
210
  const now = presentDate(root);
148
211
  return now === undefined ? undefined : momentOf(root, context, now);
@@ -157,25 +220,187 @@ function gameOf(root, context, extension) {
157
220
  : {
158
221
  places: locate(world, player).chain.filter((page) => page.type === "place").map((page) => page.name),
159
222
  environment: Object.fromEntries(environmentAt(world, player).map(({ entry }) => [entry.name, entry.value])),
223
+ members: world.pages.filter(isInParty).map((page) => ({ name: page.name, pc: isPlayerCharacter(page) })),
160
224
  };
161
225
  },
162
- state: {
163
- read: () => parse(files().text(statePath) ?? "null"),
164
- write: (value) => files().write(statePath, `# The state of the extension ${extension.package}, kept by its code.\n${stringify(value, { lineWidth: 0 })}`),
226
+ page: (name) => {
227
+ const world = campaignWorld(root, context);
228
+ const found = pagesWithNameOrAlias(world, name);
229
+ return found.length === 1 ? gamePage(world, found[0]) : undefined;
230
+ },
231
+ scene: () => {
232
+ const scene = readOpenScene(root).scene;
233
+ return scene === undefined ? undefined : {
234
+ title: scene.title,
235
+ ...(scene.opened === undefined ? {} : { opened: scene.opened }),
236
+ ...(scene.round === undefined ? {} : { round: scene.round }),
237
+ ...(scene.turn === undefined ? {} : { turn: scene.turn }),
238
+ };
165
239
  },
166
- log: (text, visibility = "hidden") => appendLogEntry(root, newDatedLogEntry(root, context, "extension", visibility, { extension: extension.name, text })),
240
+ state: { read: () => parse(files().text(statePath(root, extension)) ?? "null") },
167
241
  };
168
242
  }
169
- /** The game as a widget of an extension reads it (D-502): the game its commands reach, without the dice, the log or writing. */
170
- export function gameViewOf(root, context, extension) {
171
- const { now, calendarDay, units, party, state } = gameOf(root, context, extension);
172
- return { now, calendarDay, units, party, state: { read: state.read } };
173
- }
174
243
  /** A game date as the API gives it: as written, its day and minute, and its day of the calendar. */
175
244
  function momentOf(root, context, date) {
176
245
  const calendar = calendarDayOf(root, context, date.day);
177
246
  return { date: formatGameDate(date), day: date.day, ...(date.minute === undefined ? {} : { minute: date.minute }), ...(calendar === undefined ? {} : { calendar }) };
178
247
  }
248
+ function statePath(root, extension) {
249
+ return join(root, extensionsFolderName, extension.name, "state.yaml");
250
+ }
251
+ /** A page as an extension reads it (D-505): as a system's code does, with its fields as show gives them, effects and what the system works out included. */
252
+ function gamePage(world, page) {
253
+ const fields = effectiveFields(world, page);
254
+ return {
255
+ ...systemPage(world, page),
256
+ value: (field) => plainValue(valueNamed(fields, field)),
257
+ formula: (text) => {
258
+ let formula;
259
+ try {
260
+ formula = parseFormula(text);
261
+ }
262
+ catch (error) {
263
+ throw new Error(`The formula ${text} does not read: ${error instanceof Error ? error.message : String(error)} Write it as the game system's computed fields are written.`);
264
+ }
265
+ return formulaValue(world, fields, formula);
266
+ },
267
+ };
268
+ }
269
+ /** A field's value as the API gives it: a number, text, or a list as text; undefined for anything else, as a map. */
270
+ function plainValue(value) {
271
+ if (typeof value === "number" || typeof value === "string") {
272
+ return value;
273
+ }
274
+ if (typeof value === "boolean") {
275
+ return String(value);
276
+ }
277
+ return Array.isArray(value) ? value.map((item) => (typeof item === "object" && item !== null ? JSON.stringify(item) : String(item))) : undefined;
278
+ }
279
+ /**
280
+ * Sets on a page only the fields an extension adds to the game system, as fields or counters, under their own names (D-505): another is refused with the names
281
+ * of its own, as one the core, the system, an extension below it or the campaign declares too, so that no package reaches what another keeps, such as hit
282
+ * points; and all of them while its additions are left out (CAM-3).
283
+ */
284
+ function setOwnFields(root, context, extension, name, values, why) {
285
+ const { kept, refused } = playedLayers(root, context);
286
+ const layer = extensionLayer(extension.name);
287
+ if (refused.includes(layer)) {
288
+ throw new Error(`What the extension ${extension.name} adds to the game system does not read, so the campaign plays without it and it sets none of its fields: validate says why. Nothing changed.`);
289
+ }
290
+ const below = kept.filter((other, index) => other.from === campaignFileName || index < kept.findIndex((mine) => mine.from === layer));
291
+ const taken = [...Object.keys(findSystem(context.systemFolders, readTextSetting(root, "system") ?? "")?.fields ?? {}), ...below.flatMap((other) => declaredFields(other.data))];
292
+ const declared = declaredFields(extension.adds);
293
+ const own = declared.filter((field, index) => sameName(declared.slice(0, index), field) === undefined && sameName(taken, field) === undefined && !isCoreField(field));
294
+ const others = Object.keys(values).filter((field) => sameName(own, field) === undefined);
295
+ const odd = Object.entries(values).find(([, value]) => typeof value !== "string" && (typeof value !== "number" || !Number.isFinite(value)));
296
+ if (others.length > 0) {
297
+ const its = own.length === 0 ? "it adds none in its extension.yaml" : `its own are ${own.join(", ")}`;
298
+ throw new Error(`The extension ${extension.name} sets only the fields it adds to the game system, and ${others.join(", ")} is not one of them: ${its}. Add it to fields or counters in its extension.yaml. Nothing changed.`);
299
+ }
300
+ if (odd !== undefined) {
301
+ throw new Error(`The extension ${extension.name} gave ${odd[0]} the value ${String(odd[1])}: give a number or text. Nothing changed.`);
302
+ }
303
+ const world = campaignWorld(root, context);
304
+ const found = pagesWithNameOrAlias(world, name);
305
+ if (found.length !== 1) {
306
+ throw new Error(`${found.length === 0 ? `No page alone is named ${name}` : `${found.length} pages are named ${name}`}: give the name of one page of the campaign. Nothing changed.`);
307
+ }
308
+ // Each under the name its extension.yaml gives it, whatever the case it came in.
309
+ setFields(root, context, world, found[0], Object.fromEntries(Object.entries(values).map(([field, value]) => [sameName(own, field) ?? field, value])), why);
310
+ }
311
+ /** The fields and counters a layer of additions declares. */
312
+ function declaredFields(data) {
313
+ const names = (map) => (typeof map === "object" && map !== null && !Array.isArray(map) ? Object.keys(map) : []);
314
+ return [...names(data.fields), ...names(data.counters)];
315
+ }
316
+ /**
317
+ * A roll for who, as the master's for them (D-287, D-505): a line in the log, in view for the party and behind the screen for anyone else as master-rolls says;
318
+ * the player's physical dice, given as their faces, always in view.
319
+ */
320
+ function rollFor(root, context, notation, by, words) {
321
+ const rolled = rollDice(notation, by.values === undefined ? { random: context.random } : { values: by.values });
322
+ const physical = by.values !== undefined;
323
+ const hidden = !physical && behindTheScreen(root, context, by.who);
324
+ const checked = by.check === undefined ? {} : { check: by.check };
325
+ const says = by.says === undefined ? {} : { says: words(by.says(rolled.faces)) };
326
+ const tones = tonesOf(by.tones?.(rolled.faces), rolled.faces);
327
+ const entry = newDatedLogEntry(root, context, "roll", hidden ? "hidden" : "public", {
328
+ notation: rolled.notation,
329
+ total: rolled.total,
330
+ result: rolled.text,
331
+ ...says,
332
+ ...tones,
333
+ why: by.why,
334
+ who: by.who,
335
+ ...checked,
336
+ physical,
337
+ dice: rolled.dice,
338
+ });
339
+ if (hidden) {
340
+ sealHiddenRoll(entry, rolled.text, context);
341
+ }
342
+ appendLogEntry(root, entry);
343
+ return { total: rolled.total, faces: rolled.faces, text: rolled.text, id: entry.id, hidden };
344
+ }
345
+ /**
346
+ * What a roll an extension asks tells the page in its own words (D-507): its buttons and its rule translated, what its faces mean and how they turned out, and
347
+ * the card of its widget, refused when the extension has no widget by that name.
348
+ */
349
+ function toldOf(root, context, extension, wanted) {
350
+ const words = (text) => extensionText(root, extension, text);
351
+ const button = (given) => (typeof given === "object" && "label" in given ? { name: words(given.label), note: words(given.note) } : { name: words(given) });
352
+ const { roll, decline, rule, card, says, tones } = wanted;
353
+ if (card !== undefined && !extension.widgets.some((widget) => widget.name === card.widget)) {
354
+ const its = extension.widgets.length === 0 ? "it declares none in its extension.yaml" : `its own are ${extension.widgets.map((widget) => widget.name).join(", ")}`;
355
+ throw new Error(`The extension ${extension.name} asks in the card of a widget ${card.widget} it does not have: ${its}. Nothing was asked.`);
356
+ }
357
+ return {
358
+ ...(roll === undefined ? {} : { roll: button(roll) }),
359
+ ...(decline === undefined ? {} : { decline: decline === false ? false : button(decline) }),
360
+ ...(rule === undefined ? {} : { rule: words(rule) }),
361
+ ...(card === undefined ? {} : { card: { widget: `${extension.name}.${card.widget}`, key: card.key, shows: () => widgetCard(root, context, extension, card.widget, card.key) } }),
362
+ ...(says === undefined ? {} : { says: (faces) => words(says(faces)) }),
363
+ ...(tones === undefined ? {} : { tones }),
364
+ };
365
+ }
366
+ /** Words of an extension in the campaign's language, by its words as a widget's are, with their {names} filled; as written where its words lack them. */
367
+ function extensionText(root, extension, text) {
368
+ let words;
369
+ try {
370
+ words = extensionWords(extension.folder, readTextSetting(root, "language") ?? extension.language);
371
+ }
372
+ catch {
373
+ // Words that do not read leave the text as written, as validate says.
374
+ }
375
+ const { text: written, values } = typeof text === "string" ? { text, values: {} } : text;
376
+ return wordIn(words, written).replace(/\{(\w+)\}/g, (whole, name) => (Object.hasOwn(values, name) ? valueText(values[name]) : whole));
377
+ }
378
+ /** A value as plain text in a line of the log. */
379
+ function valueText(value) {
380
+ const unit = (given) => (given === undefined ? "" : ` ${given}`);
381
+ return typeof value === "number" || typeof value === "string" ? String(value) : "number" in value ? `${value.number}${unit(value.unit)}` : `${value.from}–${value.to}${unit(value.unit)}`;
382
+ }
383
+ /** The question of a roll asked, refused without words, a check's name or dice (ASK-2). */
384
+ function askedQuestion(question, check, notation) {
385
+ if (question.trim() === "" || check.trim() === "" || !isCheckDice(notation)) {
386
+ const dice = isCheckDice(notation) ? "" : `: ${notation} are no dice`;
387
+ throw new Error(`Give ask the question, what is at stake either way, the check's name, such as Stealth, and its dice, such as 1d20+5${dice}. Nothing was asked.`);
388
+ }
389
+ return question.trim();
390
+ }
391
+ /** What ask answered, as an extension's code gets it. */
392
+ function askedOf(result) {
393
+ switch (result.kind) {
394
+ case "roll":
395
+ return { rolled: { id: result.id, total: result.total, faces: result.faces, text: result.text } };
396
+ case "changed":
397
+ return { declined: true };
398
+ case "said":
399
+ return { said: result.words };
400
+ default:
401
+ return { inWords: "asked" in result ? result.asked : "", physical: result.kind === "physical" || result.kind === "dice in words" };
402
+ }
403
+ }
179
404
  function codeProblem(extension, error) {
180
405
  const why = error instanceof Error ? error.message : String(error);
181
406
  return { path: campaignFileName, message: `The code of the extension ${extension.package} cannot be used: ${why}. Its commands are left out.`, fix: `install it again, or another version, with package install ${extension.name}` };
@@ -1,5 +1,6 @@
1
1
  import type { Context, SaveAsked } from "../core/context.ts";
2
- import type { CounterChange, RollMade } from "../systems/index.ts";
2
+ import { type Page, type World } from "../pages/index.ts";
3
+ import type { CounterChange, RollMade, SystemPage } from "../systems/index.ts";
3
4
  /** What a system's code said after a command's change, and apart why it did not run or failed, which the caller adds to its notes, never deciding by it. */
4
5
  export interface SystemSaid {
5
6
  lines: string[];
@@ -23,3 +24,10 @@ export declare function systemAsking(root: string, context: Context, question: {
23
24
  who: string;
24
25
  notations: string[];
25
26
  }): SaveAsked | undefined;
27
+ /** A page as a system's code reads it: in the party or not, the player's or not, its counters with what its effects give, its effects. */
28
+ export declare function systemPage(world: World, page: Page): SystemPage;
29
+ /**
30
+ * Sets fields on a page, numbers or text, a counter only numbers, keeping its maximum, each with its line in the log, public when the page concerns the player:
31
+ * for a system's code and an extension's (D-505).
32
+ */
33
+ export declare function setFields(root: string, context: Context, world: World, page: Page, values: Record<string, number | string>, why: string): void;