Roller API Reference
Everything exported from @randsum/roller. Notation parsing is built in, so there is no separate package to install. The notation helpers (notationToOptions, optionsToNotation, tokenize, suggestNotationFix and the description functions) are covered in the Notation API Reference.
Functions
Section titled “Functions”roll(...args)
Section titled “roll(...args)”Roll dice. Accepts numbers, notation strings, options objects, or any combination. An optional RollConfig object can be passed as the last argument to customize the random function.
import { roll } from '@randsum/roller'
roll(20) // number: 1d20roll('4d6L') // notation stringroll({ sides: 6, quantity: 4, modifiers: { drop: { lowest: 1 } } })roll('1d20+5', '2d6+3') // multiple groupsroll('2d6', { randomFn: () => 0.5 }) // custom RNGroll('5d6W') // D6 System wild dieroll('g6') // geometric dieroll('3DD6') // draw dieroll('4d6Lx6') // repeat operatorroll('2d6+3[fire]') // annotationSignature:
function roll<T = string>(...args: RollArgument<T>[]): RollerRollResult<T>function roll<T = string>( ...args: [...RollArgument<T>[], RollConfig]): RollerRollResult<T>validateNotation(notation)
Section titled “validateNotation(notation)”Validate a dice notation string and return a detailed result with parsed structure or error.
import { validateNotation } from '@randsum/roller'
const result = validateNotation('4d6L')if (result.valid) {console.log(result.notation) // ['4d6L']: one DiceNotation per poolconsole.log(result.options) // [{ quantity: 4, sides: 6, ... }]: one options object per poolconsole.log(result.description) // [['Roll 4 6-sided dice', 'Drop lowest']]} else {console.log(result.error) // { message, argument, position? }}Signature:
function validateNotation(notation: string): ValidationResultisDiceNotation(value)
Section titled “isDiceNotation(value)”Type guard that checks whether a string is valid dice notation.
import { isDiceNotation } from '@randsum/roller'
if (isDiceNotation(userInput)) {// userInput is now typed as DiceNotationconst result = roll(userInput)}Signature:
function isDiceNotation(value: string): value is DiceNotationnotation(value)
Section titled “notation(value)”Assert a string is valid dice notation or throw NotationParseError. The error’s suggestion holds a corrected string when suggestNotationFix() can find one.
Signature:
function notation(value: string): DiceNotationValidation helpers
Section titled “Validation helpers”Validators for numeric input. Used by the roller engine and game packages. Each throws ValidationError on failure.
| Function | Description |
|---|---|
validateInteger(value, name) |
Asserts value is an integer |
validateRange(value, min, max, name) |
Asserts value is within [min, max] |
validateNonNegative(value, name) |
Asserts value is >= 0 |
validateFinite(value, name) |
Asserts value is finite |
Error classes
Section titled “Error classes”RandsumError extends Error and adds a code property and an optional context. NotationParseError, ValidationError, ModifierError and RollError all extend RandsumError.
| Class | Extends | Code | Thrown when |
|---|---|---|---|
RandsumError |
Error |
(varies) | Base class for roller errors |
ValidationError |
RandsumError |
VALIDATION_ERROR |
Invalid input: a string that is not notation, zero sides, a negative quantity |
ModifierError |
RandsumError |
MODIFIER_ERROR |
Modifier produces invalid state (e.g. dropping all dice) |
RollError |
RandsumError |
ROLL_ERROR |
General roll execution failure |
NotationParseError |
RandsumError |
INVALID_NOTATION |
notation() or notationToOptions() rejects a string, or a repeat (xN) exceeds its limit |
ERROR_CODES
Section titled “ERROR_CODES”Constant object with all error code strings:
const ERROR_CODES = { INVALID_NOTATION: 'INVALID_NOTATION', MODIFIER_ERROR: 'MODIFIER_ERROR', VALIDATION_ERROR: 'VALIDATION_ERROR', ROLL_ERROR: 'ROLL_ERROR'} as constResult types
Section titled “Result types”RollerRollResult<T>
Section titled “RollerRollResult<T>”Return type of roll().
| Property | Type | Description |
|---|---|---|
total |
number |
Combined total of all roll groups |
values |
(number | T)[] |
Every die value across all groups: numbers for numeric dice, faces for custom-faced dice |
rolls |
RollRecord<T>[] |
Full record for each roll group |
RollRecord<T>
Section titled “RollRecord<T>”Detailed record of a single roll group.
| Property | Type | Description |
|---|---|---|
argument |
RollArgument<T> |
Original input for this group |
notation |
DiceNotation |
Dice notation string |
description |
string[] |
Human-readable descriptions |
parameters |
RollParams<T> |
Fully resolved roll parameters |
rolls |
number[] |
Die values after modifiers |
initialRolls |
number[] |
Die values before modifiers |
modifierLogs |
ModifierLog[] |
Log of each modifier application |
appliedTotal |
number |
Total including arithmetic modifiers |
total |
number |
Final total for this group |
label |
string (optional) |
Annotation label from notation |
customResults |
T[] (optional) |
Custom face results for non-numeric dice |
Input types
Section titled “Input types”| Type | Description |
|---|---|
RollArgument<T> |
RollOptions<T> | DiceNotation | number |
RollOptions<T> |
Options object with sides, quantity, arithmetic, modifiers, key and label |
RollConfig |
{ randomFn?: RandomFn }, passed as the last argument to roll() |
RandomFn |
() => number, returning a number in [0, 1) |
DiceNotation |
Template literal type for notation strings (`${number}d${number}...`) |
Modifier types
Section titled “Modifier types”All modifier option types are exported from @randsum/roller.
| Type | Description |
|---|---|
ModifierOptions |
Top-level modifier configuration object |
ComparisonOptions |
Conditions like { greaterThan: 3, lessThan: 18 } |
DropOptions |
Extends ComparisonOptions with { lowest?, highest? } |
KeepOptions |
{ lowest?: number, highest?: number } |
RerollOptions |
Reroll conditions and limits |
ReplaceOptions |
Value replacement rules |
UniqueOptions |
Unique constraint config |
CountOptions |
Count dice that meet a condition (successes, failures, botches) |
Internal types
Section titled “Internal types”These appear inside result objects but are not exported.
| Type | Description |
|---|---|
RollParams<T> |
Fully resolved parameters (extends RollOptions, adds faces, argument, description, notation) |
RequiredNumericRollParameters |
{ quantity: number, sides: number } |
ModifierLog |
{ modifier, options, added, removed, replacements?, explosions? }: the log entry for one modifier; explosions lists each die that exploded and the dice its chain rolled |
NumericRollBonus |
{ rolls: number[], logs: ModifierLog[] }: intermediate modifier state |
Validation result types
Section titled “Validation result types”| Type | Description |
|---|---|
ValidationResult |
{ valid: true, argument, description, options, notation, error: null } or { valid: false, argument, error: ValidationErrorInfo } |
ValidationErrorInfo |
{ message: string, argument: string, position?: number, code?: ErrorCode } |
Subpath exports
Section titled “Subpath exports”@randsum/roller publishes several subpath exports for tree-shaking and specialized use cases.
| Import path | Exports | When to use |
|---|---|---|
@randsum/roller |
Full API: every function, type and error class | Default; use when bundle size is not a concern |
@randsum/roller/roll |
roll() only |
The game packages use this to avoid bundling the full notation toolkit |
@randsum/roller/validate |
validateNotation(), isDiceNotation(), notation(), validation helpers |
When you only need input validation without rolling |
@randsum/roller/errors |
RandsumError, ValidationError, ModifierError, RollError, NotationParseError, ERROR_CODES |
Error handling only, no roll logic |
@randsum/roller/random |
createSeededRandom(seed), createQueueRandom(options) |
Deterministic RandomFns for tests and replays: a seeded sequence, or fixed values played back |
@randsum/roller/tokenize |
tokenize() |
Low-level notation tokenization |
@randsum/roller/docs |
NOTATION_DOCS, MODIFIER_DOCS, DICE_DOCS and types NotationDoc, ModifierCategory |
Build-time docs generation, introspection tooling |
@randsum/roller/trace |
traceRoll(), formatAsMath() and type RollTraceStep |
Step-by-step roll debugging and math display |
/docs subpath
Section titled “/docs subpath”import { NOTATION_DOCS, MODIFIER_DOCS, DICE_DOCS } from '@randsum/roller/docs'import type { NotationDoc, ModifierCategory } from '@randsum/roller/docs'NOTATION_DOCS documents the full notation syntax. MODIFIER_DOCS lists each modifier with its category, syntax, and description. DICE_DOCS covers special die types (Fate, percentile, geometric, etc.). All three are structured data suitable for generating reference pages or powering autocomplete.
/trace subpath
Section titled “/trace subpath”import { traceRoll, formatAsMath } from '@randsum/roller/trace'import type { RollTraceStep } from '@randsum/roller/trace'traceRoll(record) takes a RollRecord (from result.rolls[n]) and returns readonly RollTraceStep[], a discriminated union with kind: 'rolls' | 'divider' | 'arithmetic' | 'finalRolls' that shows each stage of the roll. formatAsMath(rolls, delta?) takes a readonly number[] and optional numeric delta and returns a human-readable math string (e.g. "2 + 4 = 6"). Useful for verbose output displays and debugging.