### Usage Examples Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/static_loader.md Examples demonstrating how to use StaticLoader for synchronous lookup and error handling. ```APIDOC ## Usage Examples ### Description Examples demonstrating how to use StaticLoader for synchronous lookup and error handling. ### Example: Basic Usage ```ts import StaticLoader from 'bcdice/lib/loader/static_loader'; const loader = new StaticLoader(); // Everything is already loaded at import time: console.log(loader.listLoadedGameSystems().length); // full catalog size // No await needed to obtain a class handle: const GameSystem = loader.getGameSystemClass('SwordWorld2.5'); console.log(GameSystem?.eval('K20')?.text); // KeyNo.20c[10] > ... // dynamicLoad still works (hook no-ops + wrapping): loader.dynamicLoad('Cthulhu7th').then(GS => console.log(GS.NAME)); ``` ### Example: Error Handling ```ts import StaticLoader from 'bcdice/lib/loader/static_loader'; const loader = new StaticLoader(); try { loader.getGameSystemClass('NeverLoadedSystem'); } catch (e) { console.log(e.message); // "GameSystem NeverLoadedSystem is not loaded" } ``` ``` -------------------------------- ### Install bcdice with npm Source: https://github.com/bcdice/bcdice-js/blob/master/README.md Install the bcdice package as a dependency using npm. ```bash $ npm install --save bcdice ``` -------------------------------- ### Loader Usage Example Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Usage example for the Loader class, showing how to enumerate, resolve, load, and evaluate game systems. ```APIDOC ## Loader Usage Example ### Description Demonstrates the pattern used by concrete loaders: enumerate available systems, resolve names, load, and evaluate. ### Example ```ts import Loader from 'bcdice/lib/loader/loader'; import { DynamicLoader } from 'bcdice'; async function exercise(loader: Loader): Promise { // 1. Enumerate the catalog const ids = loader.listAvailableGameSystems().map(info => info.id); console.log(ids.length); // 2. Resolve an id from a display name const name = ids.length > 0 ? loader.getGameSystemInfo(ids[0]).name : ''; const id = loader.getGameSystemIdByName(name); // 3. Load (concrete loaders implement dynamicLoad) const GameSystem = await loader.dynamicLoad(id); console.log(GameSystem.ID, GameSystem.NAME); // 4. Use the already-loaded class const loaded = loader.getGameSystemClass(id); console.log(loaded?.eval('2D6')?.text); } exercise(new DynamicLoader()).catch(console.error); ``` ``` -------------------------------- ### Clone and set up bcdice-js development environment Source: https://github.com/bcdice/bcdice-js/blob/master/README.md Clones the repository, initializes submodules, installs Ruby and npm dependencies. Requires Node.js >= v14 and Ruby >= 2.7. ```bash $ git clone https://github.com/bcdice/bcdice-js.git $ cd bcdice-js $ git submodule update --init $ bundle install $ npm install ``` -------------------------------- ### Loader usage pattern example Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Shows the pattern used by concrete loaders: enumerate available systems, resolve names, load, and evaluate. ```TypeScript import Loader from 'bcdice/lib/loader/loader'; import { DynamicLoader } from 'bcdice'; async function exercise(loader: Loader): Promise { // 1. Enumerate the catalog const ids = loader.listAvailableGameSystems().map(info => info.id); console.log(ids.length); // 2. Resolve an id from a display name (names come from the catalog; // pick any info.name from listAvailableGameSystems()) const name = ids.length > 0 ? loader.getGameSystemInfo(ids[0]).name : ''; const id = loader.getGameSystemIdByName(name); // 3. Load (concrete loaders implement dynamicLoad) const GameSystem = await loader.dynamicLoad(id); console.log(GameSystem.ID, GameSystem.NAME); // 4. Use the already-loaded class const loaded = loader.getGameSystemClass(id); console.log(loaded?.eval('2D6')?.text); } exercise(new DynamicLoader()).catch(console.error); ``` -------------------------------- ### Basic usage example Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/dynamic_loader.md Basic usage from examples/ts/basic.ts: creates a DynamicLoader, lists available game systems, loads Cthulhu7th, and evaluates a dice roll. ```typescript import { DynamicLoader, Version } from 'bcdice'; async function main(): Promise { console.log('BCDice Version:', Version); const loader = new DynamicLoader(); console.log(loader.listAvailableGameSystems().map(info => info.id)); const GameSystem = await loader.dynamicLoad('Cthulhu7th'); console.log(GameSystem.NAME); console.log(GameSystem.HELP_MESSAGE); const result = GameSystem.eval('CC<=54'); console.log(result?.text); } main(); ``` -------------------------------- ### StaticLoader usage example Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/static_loader.md Shows how to use StaticLoader for synchronous lookup of game systems and class handles. All systems are loaded at import time, so no await is needed for getGameSystemClass. dynamicLoad still works as a no-op wrapper. ```typescript import StaticLoader from 'bcdice/lib/loader/static_loader'; const loader = new StaticLoader(); // Everything is already loaded at import time: console.log(loader.listLoadedGameSystems().length); // full catalog size // No await needed to obtain a class handle: const GameSystem = loader.getGameSystemClass('SwordWorld2.5'); console.log(GameSystem?.eval('K20')?.text); // KeyNo.20c[10] > ... // dynamicLoad still works (hook no-ops + wrapping): loader.dynamicLoad('Cthulhu7th').then(GS => console.log(GS.NAME)); ``` -------------------------------- ### Print BCDice core version Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/version.md Basic usage that prints the internal BCDice core version to the console. The comment shows an example output value. ```ts import { Version } from 'bcdice'; console.log('BCDice Version:', Version); // e.g. 3.7.0 ``` -------------------------------- ### StaticLoader error handling example Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/static_loader.md Shows that runtime errors are lookup errors from the base class because loading happened at import time. Attempting to get a non-loaded system throws an error with the message 'GameSystem NeverLoadedSystem is not loaded'. ```typescript import StaticLoader from 'bcdice/lib/loader/static_loader'; const loader = new StaticLoader(); try { loader.getGameSystemClass('NeverLoadedSystem'); } catch (e) { console.log(e.message); // "GameSystem NeverLoadedSystem is not loaded" } ``` -------------------------------- ### Error handling examples for Loader lookups Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Every lookup failure throws a plain Error with a distinct message. Shows messages for getGameSystemInfo, getGameSystemClass, and dynamicLoad. ```TypeScript const loader = new DynamicLoader(); try { loader.getGameSystemInfo('NoSuchSystem'); } catch (e) { console.log(e.message); // "GameSystem is not found" } try { loader.getGameSystemClass('NotLoaded'); // not loaded yet } catch (e) { console.log(e.message); // "GameSystem NotLoaded is not loaded" } await loader.dynamicLoad('invalid id!').catch(e => { console.log(e.message); // "Invalid id" }); ``` -------------------------------- ### Error Handling Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Error handling examples for the Loader class, showing distinct error messages for different failure cases. ```APIDOC ## Error Handling ### Description Every lookup failure throws a plain `Error` with a distinct message. ### Example ```ts const loader = new DynamicLoader(); try { loader.getGameSystemInfo('NoSuchSystem'); } catch (e) { console.log(e.message); // "GameSystem is not found" } try { loader.getGameSystemClass('NotLoaded'); // not loaded yet } catch (e) { console.log(e.message); // "GameSystem NotLoaded is not loaded" } await loader.dynamicLoad('invalid id!').catch(e => { console.log(e.message); // "Invalid id" }); ``` ``` -------------------------------- ### Loader class definition (exact source) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md The full source of the Loader abstract base class. It includes methods for resolving game system IDs, getting info and class, loading i18n translations, and dynamic loading. The dynamicImport and dynamicImportI18n hooks throw Error('Not implemented') and must be overridden. Note the typo in listAvailabletI18nInfoList() is intentional. ```typescript export default class Loader { getGameSystemIdByName(name: string): string { const id = this.listAvailableGameSystems().find(info => info.name === name)?.id; if (!id) throw new Error(`GameSystem named ${name} does not exists`); return id; } getGameSystemInfo(id: string): GameSystemInfo { const info = this.listAvailableGameSystems().find(info => info.id === id); if (!info) throw new Error('GameSystem is not found'); return info; } getGameSystemClass(id: string): GameSystemClass { const gameSystem = this.listLoadedGameSystems().find(a => a.ID === id); if (!gameSystem) throw new Error(`GameSystem ${id} is not loaded`); return gameSystem; } getI18nInfos(className: string): I18nInfo[] { const baseClassName = className.replace(/_[^0-9].*$/g, ''); const i18n = this.listAvailabletI18nInfoList().find(i18n => i18n.baseClassName === baseClassName || i18n.baseClassName === className); const i18ns = i18n ? [i18n] : []; const info = this.listAvailableGameSystems().find(info => info.className === className); return info ? Array.from(new Set(this.getI18nInfos(info.superClassName).concat(i18ns))) : i18ns; } listLoadedGameSystems(): GameSystemClass[] { return BCDice.GameSystem ?.$constants() ?.map(className => getGameSystemClass(BCDice.GameSystem[className])) ?? []; } listAvailableGameSystems(): GameSystemInfo[] { return GameSystemList.gameSystems; } listAvailabletI18nInfoList(): I18nInfo[] { return I18nList.i18nList; } async dynamicLoad(id: string): Promise { const info = this.getGameSystemInfo(id); const className = info?.className ?? id; if (!className.match(/^[A-Z]\w*$/)) throw new Error('Invalid id'); const i18nInfos = this.getI18nInfos(className); for (const i18nInfo of i18nInfos) { const locales = i18nInfo.locales.filter(locale => locale === info.locale || locale === I18n.$default_locale()); for (const locale of locales) { const json = JSON.stringify(await this.dynamicImportI18n(i18nInfo.baseClassName, locale)); I18n.$load_translation(json); } } await this.dynamicImport(className); const gameSystemClass = BCDice.GameSystem.$const_get(className); if (!gameSystemClass) throw new Error('Failed to load game system'); return getGameSystemClass(gameSystemClass); } // eslint-disable-next-line @typescript-eslint/no-unused-vars dynamicImportI18n(baseClassName: string, locale: string): Promise { throw new Error('Not implemented'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars dynamicImport(className: string): Promise { throw new Error('Not implemented'); } } ``` -------------------------------- ### listAvailableGameSystems(): GameSystemInfo[] Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Lists all available game systems from the build-generated `game_system_list.json`. ```APIDOC ## `listAvailableGameSystems(): GameSystemInfo[]` ### Description Lists all available game systems from the build-generated `game_system_list.json`. ### Method `listAvailableGameSystems` ### Returns - **GameSystemInfo[]** - An array of available game system metadata objects. ``` -------------------------------- ### Use internal modules to inspect config, enumerate game systems, and manage translations Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/internal.md Imports internal modules and demonstrates inspecting Opal.config, enumerating registered game systems via BCDice.GameSystem.$constants(), and managing translation state with I18n methods. Caution: these singletons are process-wide; clearing translations affects all systems, and invalid arguments may raise errors. ```typescript import { Opal, BCDice, I18n } from 'bcdice/lib/internal'; import { nilToNull } from 'bcdice/lib/internal/opal'; // Inspect the runtime configuration set by the library: console.log(Opal.config); // { unsupported_features_severity: 'ignore', ... } // Enumerate registered game system classes directly: console.log(BCDice.GameSystem?.$constants()); // e.g. ['Cthulhu7th', 'SwordWorld2.5', ...] // Manage translation state: I18n.$clear_translate_table(); const defaultLocale = I18n.$default_locale(); // locale used by Loader.dynamicLoad I18n.$load_translation(JSON.stringify({ [defaultLocale]: { key: 'value' } })); ``` -------------------------------- ### Base#randomizer Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Gets the underlying Ruby randomizer handle of this instance, used to inject deterministic random values in tests. ```APIDOC ## GET /Base#randomizer ### Description Returns the underlying Ruby randomizer handle of this instance. Used to inject deterministic random values in tests. ### Method GET ### Endpoint `Base#randomizer` ### Returns - **RandomizerInstance** - The underlying Ruby randomizer handle of this instance. ``` -------------------------------- ### Use UserDefinedDiceTable in TypeScript Source: https://github.com/bcdice/bcdice-js/blob/master/README.md TypeScript version of the UserDefinedDiceTable example. Creates a custom dice table and rolls it, printing the result text. ```typescript import { UserDefinedDiceTable } from 'bcdice'; const table = new UserDefinedDiceTable(`テスト表 1D6 1:いち 2:に 3:さん 4:し 5:ご 6:ろく`); console.log(table.roll()?.text); ``` -------------------------------- ### listLoadedGameSystems(): GameSystemClass[] Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Lists all game system classes that are currently loaded in the `BCDice.GameSystem` namespace. ```APIDOC ## `listLoadedGameSystems(): GameSystemClass[]` ### Description Lists all game system classes that are currently loaded in the `BCDice.GameSystem` namespace. ### Method `listLoadedGameSystems` ### Returns - **GameSystemClass[]** - An array of loaded game system classes. ``` -------------------------------- ### constructor(text: string, internal?: UserDefinedDiceTableInstance) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/user_defined_dice_table.md Creates a new UserDefinedDiceTable instance with the given table definition text. An optional internal Ruby instance handle can be provided for advanced use. ```APIDOC ## constructor(text: string, internal?: UserDefinedDiceTableInstance) ### Description Creates a new UserDefinedDiceTable instance with the given table definition text. An optional internal Ruby instance handle can be provided for advanced use. ### Parameters - **text** (string) - Required - Table definition text (see format below). - **internal** (UserDefinedDiceTableInstance) - Optional - Existing Ruby instance handle (advanced/injection use). ### Table Text Format ``` : ... ``` The dice expression is one of `1D6`, `3D4`, `D66`, `D66a` (ascending sort), or `D66d` (descending sort). Rows are `sum: text` pairs; for `D66` dice the sums are two-digit combinations (11–66). ``` -------------------------------- ### Build and test bcdice-js Source: https://github.com/bcdice/bcdice-js/blob/master/README.md Runs the build and test commands for the project. ```bash $ npm run build $ npm test ``` -------------------------------- ### Use Version for semver checks and display Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/version.md Shows using Version to branch behavior with semver.satisfies and to display the core version after dynamically loading a system. Requires the semver package. ```ts import { Version, DynamicLoader } from 'bcdice'; import { satisfies } from 'semver'; // The internal core version is semver-comparable: if (satisfies(Version, '>=3.0.0')) { console.log(`Core ${Version} supports modern command syntax`); } const loader = new DynamicLoader(); await loader.dynamicLoad('Cthulhu7th'); console.log(`bcdice-js with BCDice core ${Version}`); ``` -------------------------------- ### dynamicLoad(id: string): Promise Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Dynamically loads a game system by its ID, including loading its i18n translations and the game system class. Throws an error if the ID is invalid or the game system fails to load. ```APIDOC ## `dynamicLoad(id: string): Promise` ### Description Dynamically loads a game system by its ID, including loading its i18n translations and the game system class. Throws an error if the ID is invalid or the game system fails to load. ### Method `dynamicLoad` ### Parameters - **id** (string) - Required - The ID of the game system to load. ### Returns - **Promise** - A promise that resolves to the loaded game system class. ### Errors - Throws `Error` if the ID is invalid or the game system fails to load. ``` -------------------------------- ### Loader.getGameSystemInfo(id) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Synchronously retrieves information for a game system by its ID. Throws an Error with message 'GameSystem is not found' if no catalog entry exists for the given id. ```APIDOC ## Loader.getGameSystemInfo(id) ### Description Synchronously retrieves information for a game system by its ID. Throws an Error with message 'GameSystem is not found' if no catalog entry exists for the given id. ### Method Synchronous method call ### Parameters - **id** (string) - Required - The ID of the game system to retrieve. ### Throws - **Error** - Message: `GameSystem is not found` - Thrown when no catalog entry with the given id exists. ### Example ```ts import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); try { loader.getGameSystemInfo('ghost'); } catch (e) { console.error(e.message); // "GameSystem is not found" } ``` ``` -------------------------------- ### Import UserDefinedDiceTable Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/user_defined_dice_table.md Import the UserDefinedDiceTable class from the package entry point or from the lib path. The lib import loads the Opal-compiled Ruby class. ```ts import { UserDefinedDiceTable } from 'bcdice'; // or import UserDefinedDiceTable from 'bcdice/lib/user_defined_dice_table'; ``` -------------------------------- ### Import Version from bcdice Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/version.md Shows the two ways to import the Version constant from the bcdice package. The first imports from the top-level entry point, the second from the lib/version subpath. ```ts import { Version } from 'bcdice'; // or import Version from 'bcdice/lib/version'; ``` -------------------------------- ### constructor(command: string, internal?: BaseInstance) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Creates a new Base instance with a dice command expression. Optionally accepts an existing Ruby instance handle for advanced injection use. ```APIDOC ## constructor(command: string, internal?: BaseInstance) ### Description Creates a new Base instance with a dice command expression. Optionally accepts an existing Ruby instance handle for advanced injection use. ### Signature ```ts constructor(command: string, internal?: BaseInstance) ``` ### Parameters - **command** (string) - Required - The dice command expression to evaluate, e.g. `'2D6>=2'`, `'CC<=54'`, `'K12'`. - **internal** (BaseInstance) - Optional - An existing Ruby instance handle (advanced/injection use; see types.md). Defaults to created via `BCDice.Base.$new(command)`. ### Throws/rejects The constructor may throw if `command` is not a valid command string accepted by the Ruby-side `BCDice::Base.$new` — the exact condition depends on the Ruby implementation and is not specified in this TypeScript source. ``` -------------------------------- ### listAvailabletI18nInfoList(): I18nInfo[] Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Lists all available i18n information from the build-generated i18n list. Note the method name contains the literal typo "Availablet" and must be used as-is. ```APIDOC ## `listAvailabletI18nInfoList(): I18nInfo[]` ### Description Lists all available i18n information from the build-generated i18n list. Note the method name contains the literal typo "Availablet" and must be used as-is. ### Method `listAvailabletI18nInfoList` ### Returns - **I18nInfo[]** - An array of i18n information objects. ``` -------------------------------- ### Import DynamicLoader from 'bcdice' Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/dynamic_loader.md Shows two ways to import DynamicLoader: from the top-level package entry point or from the specific module path. ```typescript import { DynamicLoader } from 'bcdice'; // or import DynamicLoader from 'bcdice/lib/loader/dynamic_loader'; ``` -------------------------------- ### Import Base from bcdice Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Shows two ways to import the Base class from the bcdice package: the top-level entry point and the lib/base subpath. ```typescript import { Base } from 'bcdice'; // or import Base from 'bcdice/lib/base'; ``` -------------------------------- ### getGameSystemClass(gameSystemClass) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Documentation for the standalone `getGameSystemClass` function exported from `ts/loader/loader.ts`. ```APIDOC ## getGameSystemClass(gameSystemClass) ### Description Returns an anonymous class extending `Base` for the given Ruby-side game system class handle. The returned class provides static members (`ID`, `NAME`, `SORT_KEY`, `HELP_MESSAGE`, `COMMAND_PATTERN`) and an `eval` method. ### Method Function ### Signature ```ts export function getGameSystemClass(gameSystemClass: BaseClass): GameSystemClass ``` ### Parameters - `gameSystemClass` (BaseClass) - Required - A Ruby-side game system class handle (see types.md). ### Returns - `GameSystemClass` - An anonymous class extending `Base` with static members and an `eval` method. ### Example ```ts const GameSystem = getGameSystemClass(gameSystemClass); console.log(GameSystem.ID, GameSystem.NAME); const result = GameSystem.eval('2D6'); ``` ``` -------------------------------- ### Loader.getGameSystemIdByName(name) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Synchronously looks up a game system ID by its name. Throws an Error with message 'GameSystem named ${name} does not exists' if no available system matches. ```APIDOC ## Loader.getGameSystemIdByName(name) ### Description Synchronously looks up a game system ID by its name. Throws an Error with message 'GameSystem named ${name} does not exists' if no available system matches. ### Method Synchronous method call ### Parameters - **name** (string) - Required - The name of the game system to look up. ### Throws - **Error** - Message: `GameSystem named ${name} does not exists` - Thrown when no available system's name equals the argument. ### Example ```ts import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); try { loader.getGameSystemIdByName('No Such Game'); } catch (e) { if (e instanceof Error && e.message.includes('does not exists')) { // handle unknown name } } ``` ``` -------------------------------- ### Loader.dynamicLoad(id) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Asynchronously loads a game system by its ID. Rejects with an Error message 'Invalid id' if the derived class name does not match the pattern, or 'Failed to load game system' if the module does not register the expected class. Also rejects on module-not-found or invalid i18n JSON. ```APIDOC ## Loader.dynamicLoad(id) ### Description Asynchronously loads a game system by its ID. Rejects with an Error message 'Invalid id' if the derived class name does not match the pattern, or 'Failed to load game system' if the module does not register the expected class. Also rejects on module-not-found or invalid i18n JSON. ### Method Async method call (returns Promise) ### Parameters - **id** (string) - Required - The ID of the game system to load. ### Rejections - **Error** - Message: `Invalid id` - Thrown when the derived class name does not match `/^[A-Z]\w*$/`. - **Error** - Message: `Failed to load game system` - Thrown when the imported module does not register the expected class. - **Module-not-found** - Rejects with runtime/bundler resolution error (e.g., `MODULE_NOT_FOUND`) if the module file does not exist. - **Invalid i18n JSON** - Rejects with an opaque exception from the Ruby side if translation loading fails. ### Example ```ts import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); try { await loader.dynamicLoad('Cthulhu7th'); } catch (e) { // "Invalid id" | "Failed to load game system" | module resolution error console.error(e); } ``` ### Recommended Guard ```ts const GameSystem = await loader.dynamicLoad('Cthulhu7th').catch(() => null); if (!GameSystem) { // fall back to a default system or report the id as unknown } ``` ``` -------------------------------- ### Loading multiple systems and caching Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/dynamic_loader.md Loads SwordWorld2.5, evaluates a command, then shows that getGameSystemClass returns the same class without re-importing. ```typescript import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); async function run(): Promise { const SwordWorld = await loader.dynamicLoad('SwordWorld2.5'); console.log(SwordWorld.eval('K12')?.text); // KeyNo.12c[10] > ... // Already loaded — no network/module work, same class identity: const again = loader.getGameSystemClass('SwordWorld2.5'); console.log(again === SwordWorld); // true } run(); ``` -------------------------------- ### bcdice/lib/internal Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md Deep subpath import for internal modules BCDice, I18n, and Opal. ```APIDOC ## bcdice/lib/internal ### Description Deep subpath import for internal modules BCDice, I18n, and Opal. ### Import ```ts import { BCDice, I18n, Opal } from 'bcdice/lib/internal'; ``` ### Exports - **BCDice** (named) - BCDice internal module. - **I18n** (named) - Internationalization module. - **Opal** (named) - Opal runtime module. ``` -------------------------------- ### Main entry point exports (lib/index.js) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md The main entry point of the bcdice package exports exactly four symbols: Base, DynamicLoader, UserDefinedDiceTable, and Version. ```TypeScript export { default as Base } from './base'; export { default as DynamicLoader } from './loader/dynamic_loader'; export { default as UserDefinedDiceTable } from './user_defined_dice_table'; export { default as Version } from './version'; ``` -------------------------------- ### BaseInstance and BaseClass interfaces Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/types.md Internal types for the Ruby Base instance and class. Used by the Base constructor, getGameSystemClass, BCDiceModule.Base, and GameSystemClass.new. $command_pattern backs GameSystemClass.COMMAND_PATTERN. ```typescript export interface BaseInstance { $eval(): Result; randomizer: RandomizerInstance; } export interface BaseClass extends Function, RubyObject { $new(command: string): BaseInstance; $eval(command: string): Result; $command_pattern(): RegExp; } ``` -------------------------------- ### new UserDefinedDiceTable(tableText) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/user_defined_dice_table.md Creates a new UserDefinedDiceTable instance from a text definition. The text format includes a table name, a dice expression (e.g., 1D6), and lines mapping results to text entries. ```APIDOC ## new UserDefinedDiceTable(tableText) ### Description Creates a new UserDefinedDiceTable instance from a text definition. The text format includes a table name, a dice expression (e.g., 1D6), and lines mapping results to text entries. ### Constructor `new UserDefinedDiceTable(tableText: string)` ### Parameters - **tableText** (string) - Required - The table definition text. Format: first line is the table name, second line is the dice expression (e.g., `1D6`), and subsequent lines map each possible result to a text entry (e.g., `1:いち`). ### Example ```ts const table = new UserDefinedDiceTable(`テスト表 1D6 1:いち 2:に 3:さん 4:し 5:ご 6:ろく`); ``` ``` -------------------------------- ### bcdice/lib/game_system Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md Deep subpath import for the GameSystemClass type. ```APIDOC ## bcdice/lib/game_system ### Description Deep subpath import for the GameSystemClass type. ### Import ```ts import GameSystemClass from 'bcdice/lib/game_system'; ``` ### Exports - **GameSystemClass** (default type) - Game system class type. ``` -------------------------------- ### Loader.getGameSystemClass(id) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Synchronously retrieves the class for a loaded game system by its ID. Throws an Error with message 'GameSystem ${id} is not loaded' if no loaded class matches. ```APIDOC ## Loader.getGameSystemClass(id) ### Description Synchronously retrieves the class for a loaded game system by its ID. Throws an Error with message 'GameSystem ${id} is not loaded' if no loaded class matches. ### Method Synchronous method call ### Parameters - **id** (string) - Required - The ID of the game system class to retrieve. ### Throws - **Error** - Message: `GameSystem ${id} is not loaded` - Thrown when no loaded class with `ID === id` exists in `listLoadedGameSystems()`. ### Example ```ts import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); try { loader.getGameSystemClass('Cthulhu7th'); } catch (e) { console.error(e.message); } ``` ``` -------------------------------- ### Instance evaluation with mocked randomizer and null handling Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Creates a Base instance, injects a stubbed randomizer via mockedRandomizer, and evaluates. Shows that non-matching commands return null instead of throwing. The randomizer getter exposes the injected handle. ```typescript import { Base } from 'bcdice'; import { mockedRandomizer } from 'bcdice/lib/test/randomizer'; // test-time helper const base = new Base('2D6>=2'); const [, $random] = mockedRandomizer(); // stubbed $random $random.onCall(0).returns(1); $random.onCall(1).returns(2); const result = base.eval(); console.log(result?.text); // (2D6>=2) > 3[1,2] > 3 > 成功 console.log(base.randomizer); // the RandomizerInstance used by this instance // Commands that match no pattern resolve to null, not throw: const nothing = new Base('not a command').eval(); console.log(nothing); // null ``` -------------------------------- ### getGameSystemIdByName(name: string): string Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Resolves a game system ID from its display name. Throws an error if no game system with the given name exists. ```APIDOC ## `getGameSystemIdByName(name: string): string` ### Description Resolves a game system ID from its display name. Throws an error if no game system with the given name exists. ### Method `getGameSystemIdByName` ### Parameters - **name** (string) - Required - The display name of the game system. ### Returns - **string** - The ID of the matching game system. ### Errors - Throws `Error` if no game system with the given name exists. ``` -------------------------------- ### new Base(command, internal?) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Constructor that creates a Base instance for a single dice command. Optionally accepts an internal BaseInstance for advanced use. ```APIDOC ## new Base(command, internal?) ### Description Constructor that creates a Base instance for a single dice command. Optionally accepts an internal BaseInstance for advanced use. ### Method constructor ### Parameters - **command** (string) - Required - The dice command string to evaluate. - **internal** (BaseInstance) - Optional - An internal BaseInstance to use instead of creating a new one. ### Example ```ts import { Base } from 'bcdice'; const base = new Base('2d6'); ``` ``` -------------------------------- ### Basic roll with UserDefinedDiceTable Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/user_defined_dice_table.md Basic usage of UserDefinedDiceTable from 'bcdice'. Creates a table with a 1D6 roll and six entries, then rolls it and logs the result text. ```ts import { UserDefinedDiceTable } from 'bcdice'; const table = new UserDefinedDiceTable(`テスト表 1D6 1:いち 2:に 3:さん 4:し 5:ご 6:ろく`); console.log(table.roll()?.text); // e.g. テスト表(1) > いち ``` -------------------------------- ### getGameSystemInfo(id: string): GameSystemInfo Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Retrieves the metadata information for a game system by its ID. Throws an error if the game system is not found. ```APIDOC ## `getGameSystemInfo(id: string): GameSystemInfo` ### Description Retrieves the metadata information for a game system by its ID. Throws an error if the game system is not found. ### Method `getGameSystemInfo` ### Parameters - **id** (string) - Required - The ID of the game system. ### Returns - **GameSystemInfo** - The metadata object for the game system. ### Errors - Throws `Error` if the game system is not found. ``` -------------------------------- ### bcdice Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md Main entry point of the bcdice package. Exports Base, DynamicLoader, UserDefinedDiceTable, and Version. ```APIDOC ## bcdice ### Description Main entry point of the bcdice package. Exports Base, DynamicLoader, UserDefinedDiceTable, and Version. ### Import ```ts import { Base, DynamicLoader, UserDefinedDiceTable, Version } from 'bcdice'; ``` ### Exports - **Base** (default) - Base class for dice rolling. - **DynamicLoader** (default) - Loader for dynamically loading game systems. - **UserDefinedDiceTable** (default) - Class for user-defined dice tables. - **Version** (default) - Version information. ``` -------------------------------- ### Base#eval (instance) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/base.md Evaluates the command associated with this instance and returns a Result object or null if the command does not match any pattern. ```APIDOC ## POST /Base#eval ### Description Evaluates the command associated with this instance and returns a Result object or null if the command does not match any pattern. ### Method POST ### Endpoint `Base#eval()` ### Parameters None. ### Request Example ```ts import { Base } from 'bcdice'; import { mockedRandomizer } from 'bcdice/lib/test/randomizer'; // test-time helper const base = new Base('2D6>=2'); const [, $random] = mockedRandomizer(); // stubbed $random $random.onCall(0).returns(1); $random.onCall(1).returns(2); const result = base.eval(); console.log(result?.text); // (2D6>=2) > 3[1,2] > 3 > 成功 ``` ### Response #### Success Response (200) - **text** (string) - Renderable result string. - **rands** (array) - `[value, sides][]` history. - **detailedRands** (array) - Per-roll `{ kind, sides, value }`. - **secret** (boolean) - Whether the result is secret. - **success** (boolean) - Whether the roll succeeded. - **failure** (boolean) - Whether the roll failed. - **critical** (boolean) - Whether the roll was critical. - **fumble** (boolean) - Whether the roll was a fumble. #### Response Example ```ts const result = base.eval(); console.log(result?.text); // (2D6>=2) > 3[1,2] > 3 > 成功 console.log(base.randomizer); // the RandomizerInstance used by this instance // Commands that match no pattern resolve to null, not throw: const nothing = new Base('not a command').eval(); console.log(nothing); // null ``` ### Error Handling - Returns `null` if the command does not match any pattern. Does not throw. ``` -------------------------------- ### bcdice/lib/version Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md Deep subpath import for the Version class. ```APIDOC ## bcdice/lib/version ### Description Deep subpath import for the Version class. ### Import ```ts import Version from 'bcdice/lib/version'; ``` ### Exports - **Version** (default) - Version information. ``` -------------------------------- ### dynamicImport(className: string): Promise Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Abstract hook for dynamically importing a game system class. The base implementation throws `Error('Not implemented')`; concrete subclasses must override this method. ```APIDOC ## `dynamicImport(className: string): Promise` ### Description Abstract hook for dynamically importing a game system class. The base implementation throws `Error('Not implemented')`; concrete subclasses must override this method. ### Method `dynamicImport` ### Parameters - **className** (string) - Required - The class name of the game system to import. ### Returns - **Promise** - A promise that resolves when the import is complete. ### Errors - Throws `Error('Not implemented')` in the base implementation. ``` -------------------------------- ### UserDefinedDiceTable constructor signature Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/user_defined_dice_table.md Constructor signature. The text parameter is the table definition; the optional internal parameter is an existing Ruby instance handle for advanced use. ```ts constructor(text: string, internal?: UserDefinedDiceTableInstance) ``` -------------------------------- ### getI18nInfos(className: string): I18nInfo[] Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/loader.md Returns the i18n (translation) information list for a given game system class name, including inherited i18n info from superclasses. ```APIDOC ## `getI18nInfos(className: string): I18nInfo[]` ### Description Returns the i18n (translation) information list for a given game system class name, including inherited i18n info from superclasses. ### Method `getI18nInfos` ### Parameters - **className** (string) - Required - The class name of the game system. ### Returns - **I18nInfo[]** - An array of i18n information objects. ``` -------------------------------- ### Catch loader errors by message string Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Shows how to catch the plain Error instances thrown by the TypeScript layer. Synchronous lookups (getGameSystemIdByName, getGameSystemInfo) throw directly; dynamicLoad is async and rejects, so await it inside try/catch. Match on message strings like 'does not exists' or 'GameSystem is not found'. ```typescript import { DynamicLoader } from 'bcdice'; const loader = new DynamicLoader(); // Synchronous lookups: try { loader.getGameSystemIdByName('No Such Game'); } catch (e) { if (e instanceof Error && e.message.includes('does not exists')) { // handle unknown name } } try { loader.getGameSystemInfo('ghost'); // async context not needed } catch (e) { console.error(e.message); // "GameSystem is not found" } // Async loading: try { await loader.dynamicLoad('Cthulhu7th'); } catch (e) { // "Invalid id" | "Failed to load game system" | module resolution error console.error(e); } ``` -------------------------------- ### dynamicImportI18n(baseClassName, locale) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/dynamic_loader.md Dynamically imports a translation JSON file for a given game system base class name and locale. Returns a promise that resolves to the JSON object's default export. ```APIDOC ## dynamicImportI18n(baseClassName, locale) ### Description Dynamically imports a translation JSON file for a given game system base class name and locale. Returns a promise that resolves to the JSON object's default export. ### Method async ### Signature async dynamicImportI18n(baseClassName: string, locale: string): Promise ### Parameters - **baseClassName** (string) - Required - Ruby class base name; interpolated into the import path. - **locale** (string) - Required - Locale code, e.g. 'ja_jp'; interpolated into the import path. ### Returns - **Promise** - The `.default` export of `../../lib/bcdice/i18n/${baseClassName}.${locale}.json`. ### Errors - Rejects with the bundler/runtime module-resolution error if the JSON file for that baseClassName/locale pair does not exist. ``` -------------------------------- ### Loader.dynamicImportI18n(...) and Loader.dynamicImport(...) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/errors.md Abstract hooks in the base Loader class. Calling them directly on a Loader instance throws an Error with message 'Not implemented'. ```APIDOC ## Loader.dynamicImportI18n(...) and Loader.dynamicImport(...) ### Description Abstract hooks in the base Loader class. Calling them directly on a Loader instance throws an Error with message 'Not implemented'. ### Method Synchronous method call (throws) ### Parameters - **...args** - Required - Arguments passed to the hook. ### Throws - **Error** - Message: `Not implemented` - Thrown when called on a base Loader instance. ### Example ```ts import { Loader } from 'bcdice'; const loader = new Loader(); try { loader.dynamicImport('Cthulhu7th'); } catch (e) { console.error(e.message); // "Not implemented" } ``` ``` -------------------------------- ### bcdice/lib/loader/loader Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/index.md Deep subpath import for the Loader class and getGameSystemClass function. ```APIDOC ## bcdice/lib/loader/loader ### Description Deep subpath import for the Loader class and getGameSystemClass function. ### Import ```ts import Loader, { getGameSystemClass } from 'bcdice/lib/loader/loader'; ``` ### Exports - **Loader** (default) - Loader class. - **getGameSystemClass** (named) - Function to get a game system class. ``` -------------------------------- ### Version (constant) Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/version.md A constant string holding the version of the internal BCDice core. It is exported from the top-level package entry point and can be imported directly. Use it to display or branch behavior based on the core version. ```APIDOC ## Version (constant) ### Description A constant string holding the version of the internal (Ruby) BCDice core compiled into this package. It is read from the `BCDice.VERSION` namespace at module load, not from the npm package version. ### Type - **Type**: `string` — the internal BCDice version string. ### Import ```ts import { Version } from 'bcdice'; // or import Version from 'bcdice/lib/version'; ``` ### Usage Examples Basic usage (printing the internal core version): ```ts import { Version } from 'bcdice'; console.log('BCDice Version:', Version); // e.g. 3.7.0 ``` Using the version to branch behavior or display in an application: ```ts import { Version, DynamicLoader } from 'bcdice'; import { satisfies } from 'semver'; // The internal core version is semver-comparable: if (satisfies(Version, '>=3.0.0')) { console.log(`Core ${Version} supports modern command syntax`); } const loader = new DynamicLoader(); await loader.dynamicLoad('Cthulhu7th'); console.log(`bcdice-js with BCDice core ${Version}`); ``` ### Semantics - The value is whatever `BCDice.VERSION` holds after `lib/bcdice/version` is loaded. - The test suite (`ts/version.test.ts`) asserts the value is a valid semver string (`semver.valid(Version)` is not `null`). - The README maps bcdice-js releases to internal BCDice versions (e.g. bcdice-js 3.1.0 ↔ BCDice Ver3.1.1). The exact mapping for 4.x is determined by the pinned `BCDice` submodule at build time; the constant itself reflects the compiled-in core. ### Notes - There is no API to obtain the bcdice-js (npm) package version at runtime from this module; `Version` always refers to the internal BCDice core. ``` -------------------------------- ### Import internal modules from bcdice/lib/internal Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/internal.md Use this import to access the Opal runtime, BCDice namespace, and I18n namespace from the internal module. These are not re-exported from the top-level entry point. ```typescript import { Opal, BCDice, I18n } from 'bcdice/lib/internal'; ``` -------------------------------- ### dynamicImport method signature Source: https://github.com/bcdice/bcdice-js/blob/master/_autodocs/api-reference/static_loader.md Async method that resolves immediately without performing any import. Overridden because all game systems are already loaded. ```typescript async dynamicImport(className: string): Promise ```