Craft

The game API

A script reads and changes the world through game, the second argument of run and of a card's actions. Each entry below is one call or value, with its signature and the shapes it takes and returns, as the world's declarations write them.

export default defineScript({
  description: "Equips an item, unequipping whatever uses the same slots.",
  beforeNarrationTrigger: "A character puts on, wields or swaps equipment.",
  input: {
    character: { type: "string", description: "The character's slug or name" },
    item: { type: "string", description: "The item's slug or name" },
  },
  async run({ character, item }, { game }) {
    const hero = await game.files("Character").get(character, { include: ["inventory"] });
    if (!hero) throw new Error("No character " + character);
    const gloves = await game.files("Item").get(item);
    if (!gloves) throw new Error("No item " + item);
    // One object per file: the gloves looked up are the ones in the inventory.
    const carried = hero.inventory.map((entry) => entry.item).filter(Boolean);
    if (!carried.includes(gloves)) throw new Error(hero.$name + " isn't carrying " + gloves.$name);
    for (const file of carried) {
      if (file !== gloves && file.equipped && file.slots.some((slot) => gloves.slots.includes(slot))) {
        await file.update({ equipped: false });
      }
    }
    await gloves.update({ equipped: true });
    return { equipped: gloves.$name };
  },
});

await every call. A call that fails throws where it was made, with error.code, error.file and error.field, so a mistake is never silent. A script can catch an error with try { await … } catch (error) { … } and carry on; the codes are at the end. A .catch() written on a game call never runs, because the call throws before it returns anything to chain on, so version 2 refuses one. get() answers null for a file that isn't there without one.

Names. The keys the calls take and return are camelCase (game.playerCharacter(), succeedsOn), values of more than one word are snake_case (succeedsOn: "or_lower"), and the error codes are constants in capitals (NOT_IN_CURRENT_STATE). The world's own words, such as slugs, names and field names, keep their spelling. See API conventions.

What scripts reach. A script reads and changes the files of the world or game it runs in, and only those. Files of fields can be read and changed. Markdown pages can be read (name, description, image, content) but not changed. Scripts never reach other scripts or the Game Start file, and a place's map isn't part of what they read. Files hidden from the GM, by their own visibility or their type's, aren't found either.

File types

game.files

A file type by name, slug or id: game.files("Item").get("rope"). Throws FILE_TYPE_NOT_FOUND when the world has no such type.

files(type: string): FileType
const items = game.files("Item");
const rope = await items.get("rope");

Name types as the world has them: a script naming a type the world doesn't have is invalid when it is saved, and the GM skips it.

game.fileTypes().get

A file type by name, slug or id, or null when there is none.

get(type: string): Promise<FileType | null>

A file type (FileTypeInfo):

Field Type What it is
$id string The file type's id.
name string The type's name ("Character").
slug string The type's slug ("character"), as file names and references use it.
contentType "json" | "markdown" "json" for files of fields, which scripts read and change; "markdown" for pages of prose, which they only read.
fields readonly FieldInfo[] Its top-level fields, name, description and image included.

Each of its fields (FieldInfo):

Field Type What it is
name string The field's name, as files store it.
type string The JSON Schema type ("string", "number", "array"…), or "reference" for a reference field.
required boolean Whether every file must have it, and create() needs it.
computed boolean Worked out from other fields: read it, never set it.
enum? readonly (string | number | boolean)[] The only values it takes, when it has a fixed list.
references? readonly string[] The file type slugs a reference (or a list of them) may point to.

game.fileTypes().list

Every file type scripts can reach.

list(): Promise<FileType[]>

Files

fileType.get

A file of this type by slug, name or id, or null when there is none. include names reference fields to load with it (true: all of them); an included reference reads as the file itself.

get(slugOrId: FileLookup, options?: { include?: true | readonly string[] }): Promise<File | null>

What every file carries (FileMeta):

Field Type What it is
$id string The file's id: pass it to get(), or list it on a card.
$referenceId string The id references and the current state name the file by (person.file.referenceId): compare with it to tell the person in the scene is this file.
$slug string The file's slug, as references store it.
$name string The file's name, as players see it.
$path string Where the file sits, like "/Heroes/Kael.character.json".
$fileTypeSlug Slug The slug of the file's type.
const hero = await game.files("Character").get("Kael", { include: ["inventory"] });
if (!hero) throw new Error("No character Kael");
hero.inventory[0].item.slots; // the item itself, loaded by include
  • Check for null. No match is null, never an error. A name two files share throws AMBIGUOUS_NAME: pass an id then.
  • Take names or slugs, never compare them yourself. get matches an id, a slug, a name, a stored reference or a file, and a slug that differs only in hyphens ("ka-cha" for Ka'Cha) still finds the one file it can mean. Look up both sides and compare files (carried.includes(gloves)).
  • Include is one level deep. An included file's own references stay stored references, which you can pass to another get. A missing referenced file reads as null.
  • A file's fields are read-only and flat, computed fields included. Change them with update.

fileType.getMany

get() for a list, in one call: the files in the keys' order, null where a key names none. At most 100 keys.

getMany(slugsOrIds: readonly FileLookup[], options?: { include?: true | readonly string[] }): Promise<readonly (File | null)[]>
const [rope, torch, lantern] = await game.files("Item").getMany(["rope", "torch", "Storm Lantern"]);
const stock = (await game.files("Item").getMany(shop.stock)).filter(Boolean);
  • Use it wherever a loop would call get. The whole list is read at once, where a get per key reads them one after another and slows the turn.
  • The answer keeps the keys' order, with null where a key names no file. Each key is matched the way get matches it, and takes the same include.
  • Each key counts as a lookup, and one call takes at most 100 keys.

fileType.create

Creates a file of this type; it saves when the run ends.

create(fields: Create, options?: CreateOptions): Promise<File>

Options (CreateOptions):

Field Type What it is
folder? string The folder path for the new file, made when the run saves if it doesn't exist. Default: the folder holding most files of its type.
const rope = await game.files("Item").create({ name: "Rope", weight: 5 }, { folder: "/World/Items" });
await hero.update({ inventory: [...hero.inventory, { item: rope, quantity: 1 }] });

Give every required field. A reference field takes a file from get or create, or a slug, so a file made earlier in the run can be referenced at once. Without a folder, the file goes in the folder that holds most files of its type. A folder that doesn't exist yet is made when the run saves, so a world whose files of a kind are all made in play needn't ship an empty folder for them.

file.update

Changes top-level fields; the change saves when the run ends. Computed fields can't be set.

update(changes: { [field: string]: unknown }): Promise<AnyFile>
await file.update({ stats: { ...file.stats, hp: 5 } });

Only the top-level fields you pass change. To change part of a list or an object, send the whole new one. To add to a list, find the entry that is already there (compare files: entry.item === rope), raise its quantity and write the whole list back. The file shows its new values at once, computed fields worked out again.

game.currentLocation

The file of the place the scene is in, or null while the party is on the way somewhere, at a place with no file, or outside a game.

currentLocation(options?: { include?: true | readonly string[] }): Promise<AnyFile | null>

game.playerCharacter

The character of whoever caused this run: who tapped the card's Button, or whose message started the GM's turn. Null with no one (a test run with no character picked), so check it.

playerCharacter(options?: { include?: true | readonly string[] }): Promise<AnyFile | null>
const me = await game.playerCharacter();
if (!me) throw new Error("Pick a character to test as.");

In the GM's run it is the character of the player whose message started the turn; in a card's action, the character of whoever pressed. A test run with no character picked gets null.

The current state

game.currentState.get

The current state as it stands, with this run's changes so far.

get(): Promise<CurrentState>

The current state (CurrentState):

Field Type What it is
place { readonly name: string; readonly file: CurrentStateFileRef | null } | null Where the scene is, with the place's file when it has one; null while the party travels.
travel { readonly from: string | null; readonly to: string; readonly via: string | null } | null Where the party is going while it travels, and from where and by which way; null otherwise.
time string | null The time in the world's own words; null in a game that keeps no time.
purpose string What the scene is about now.
people readonly CurrentStatePerson[] Everyone and everything in the scene.
trackers readonly CurrentStateTracker[] The scene's trackers: a turn order, a clock, the objectives.

Each person (CurrentStatePerson):

Field Type What it is
name string The name every change names them by.
file CurrentStateFileRef | null Their own file; null for an extra, who lives only in the current state.
of CurrentStateFileRef | null For an instance ("Goblin 2"), the kind's file it is one of.
isPlayer boolean Whether they are the player's character.
what string | null What they are, in a few words ("a goblin archer").
area string | null The part of the place they are in.
side CurrentStateSide | null Whose side they are on: "ally", "enemy" or "neutral".
out string | null Out of action in the story's words ("unconscious"), or null.
hidden CurrentStateHidden | null How they are hidden from the player ("unseen", "sensed" or "disguised", and as what), or null.
details { readonly [detail: string]: string | number | boolean } An extra's own state (hp, conditions); someone with a file keeps theirs in it.
square string | null The map square(s) they stand on ("M13", "J9–K10"); null off a grid or with no token.
distances { readonly [name: string]: number } | null Feet to everyone else here with a token, by name, as the map measures it; null off a map.

Each tracker (CurrentStateTracker):

Field Type What it is
name string The tracker's name, as changes name it ("Fight").
fields CurrentStateTrackerField[] What it tracks, in order: numbers, lists, a turn order, text, records (at most 8).
for? string | null Someone in the current state it is about.
hidden? boolean | null The GM's alone: players never see it.
lasts? "here" | "game" | null "here" (the default) ends when the party leaves the place; "game" stays.

A tracker's field kinds: count, clock, scale, list, text, order, ref, records, links. One field of a tracker: a number, a list, a turn order, a short text, a file or person it points at, records (one per person or file, each with fields of its own) or links (one per pair of them, with fields between the two). show names live values drawn beside each person a field names: a stat the current state shows ("HP") or "where".

const scene = await game.currentState.get();
const foes = scene.people.filter((person) => person.side === "enemy" && !person.out);

Someone with a file keeps their state in it: read it with game.files(person.file.fileTypeSlug).get(person.file). Outside a game (a test run) the current state is empty. More on trackers and their fields: Trackers.

game.currentState.turnOrder

The turn order as it stands, with this run's changes so far; null when none runs.

turnOrder(): Promise<CurrentStateTurnOrder | null>

The turn order (CurrentStateTurnOrder):

Field Type What it is
tracker string The tracker it is in ("Fight").
round number The round, from 1.
current string | null Whose turn it is, by their name in the order; null before the first turn.
next string | null Whose turn comes next: the next in the order who isn't out of action, the first again after the last.
entries readonly CurrentStateTurnOrderEntry[] Everyone in the order, in turn.

Each entry (CurrentStateTurnOrderEntry):

Field Type What it is
name string Their name in the order.
score number | null Their initiative or speed, when the game rolled for the order.
person CurrentStatePerson | null Them in the current state; null for an entry nobody in it is called (a group: "Goblins").

A change to it (CurrentStateTurnOrderChange):

Field Type What it is
remove? string[] Who leaves the order, by name. When it's their turn, the turn passes to the next, and advance doesn't move it again.
add? { name: string; score?: number | null }[] Who joins the order, placed by score (highest first, after anyone with the same); without one, last. At most 20 in all.
round? number The round, from 1.
current? string Whose turn it is now, by name. Not with advance.
advance? boolean true passes the turn to whoever is next, and the round goes up when it comes round to the first again.
const order = await game.currentState.turnOrder();
// { tracker: "Fight", round: 2, current: "Kael", next: "Goblin 2",
//   entries: [{ name: "Kael", score: 17, person: { … } }, …] }, or null

The turn order of the fight that's on, whichever tracker it is in, with the round, whose turn it is and whose turn comes next. Someone out of action is passed over for next. An entry's person is them in the current state; it is null for a name nobody in it has, such as a group ("Wolves"). It is null when no turn order runs.

Change it with turnOrder in an update:

// Goblin 2 falls on its own turn: the turn passes to whoever follows it.
await game.currentState.update({
  people: { "Goblin 2": { out: "dead" } },
  turnOrder: { remove: ["Goblin 2"], advance: true },
});
  • advance: true passes the turn to whoever is next. The round goes up when the turn comes round to the top of the order.
  • remove takes people out of the order by name. When it's their turn, the turn passes to the next, and advance doesn't move it again.
  • add puts people in by score, highest first; someone without a score goes last.
  • current names whose turn it is, and round sets the round. current doesn't go with advance.
  • They apply in this order: remove, add, round, current, advance. Anyone out of action, or leaving in the same change, is passed over.
  • turnOrder: null ends the tracker the order is in. Don't change that tracker in trackers in the same update.

game.currentState.update

Checks the change (an error says what's wrong, with error.code) and returns the current state with it. options.show is where what it makes shows (an HP change's row, someone going down): see Show.

update(change: CurrentStateChange, options?: { show?: Show }): Promise<CurrentState>

A change (CurrentStateChange):

Field Type What it is
arrive? CurrentStateArrival[] Who comes into the scene.
leave? string[] Who leaves, by name. The player's character never does.
people? { [name: string]: { details?: { [detail: string]: string | number | boolean | null }; out?: string | null; side?: CurrentStateSide; hidden?: { how: "unseen" | "sensed" | "disguised"; as?: string } | null; }; } Changes to people already here, by name.
trackers? { [name: string]: Omit<CurrentStateTracker, "name"> | null } Trackers by name: the whole tracker starts or replaces one, null ends it.
turnOrder? CurrentStateTurnOrderChange | null The turn order (see turnOrder()); null ends the tracker it is in. Not with a change to that tracker in trackers.
time? string The time now, in the world's own words.
purpose? string What the scene is about now.

Someone arriving (CurrentStateArrival):

Field Type What it is
name? string A name of their own ("Goblin 3"). Someone with a file is in the current state by the file's name: leave it out.
file? FileMeta | CurrentStateFileRef Their own file, when they have one: from game.files(…).get(…), or the file of someone in the current state.
of? FileMeta | CurrentStateFileRef | string The kind an instance is one of ("Goblin"); not with a file.
what? string What they are, in a few words; left out, the kind's name or their own.
area? string The part of the place they arrive in.
side? CurrentStateSide Whose side they are on: "ally", "enemy" or "neutral".
details? { [detail: string]: string | number | boolean } An extra's or an instance's own state; someone with a file keeps theirs in it.
hidden? { how: "unseen" | "sensed" | "disguised"; as?: string } Hidden from the player: "unseen", "sensed" or "disguised" (as what).
await game.currentState.update({
  arrive: [{ name: "Goblin 1", of: "Goblin", side: "enemy", details: { hp: 7 } }],
  trackers: {
    "The watch arrives": { hidden: true, fields: [{ kind: "clock", value: 1, max: 6, at: { "6": "The guards come" } }] },
  },
});
  • Names match ignoring case. Give each newcomer a name of their own ("Goblin 1"). Someone with a file arrives with file, by the file's name, with no of or details.
  • details are only for someone without a file, and null removes one. out: null is back in action. The player's character never leaves and is never hidden.
  • A tracker is written whole: copy the one you read and change what moves. null ends it. Change a turn order with turnOrder (above) rather than rewriting its tracker.
  • Text is short: a tracker's text field, a list item and its note hold at most 160 characters, a tracker's or someone's name 60, and a label

    Longer text fails the whole run with SCHEMA_VALIDATION, so cut or summarise it before you write it.

  • time sets the game's clock, in the world's own words; in a game that keeps no time, it changes nothing.
  • A change that names someone not in the current state, a name that is taken or a tracker that doesn't fit throws before anything changes.
  • Changes land when the run ends, after its file changes save, and only if the run succeeds. They place people on the map and play there as the GM's own changes do.
  • { show: "map" } as the second argument keeps the rows a change makes (an HP change, someone going down) off the story, for a card that tells them. See Rolls and effects.

game.currentTurn

This turn's number, as the chat shows it on the turn's message; 0 outside a game.

currentTurn: number

Reading it costs nothing. Use it to stamp when something happened (lastRested: game.currentTurn).

The game's messages

game.messages

The game's chat as its players saw it, oldest first: in a GM turn, every message since the game's latest compaction, up to the reply being written; none anywhere else (a card's action, a test run). It takes no arguments.

messages(): Promise<readonly GameMessage[]>

Each message (GameMessage):

Field Type What it is
id string The message's id, which a replay of the turn keeps. Opaque: compare it, never read its form.
turn number The message's number in the game, counting up: every message has its own, so a player's message and the GM's reply to it have two. It numbers messages, not exchanges.
role "player" | "gm" Who wrote it: a player, or the Game Master.
character string | null The name of the character a player message was written as; null for the GM.
text string What players saw: the GM's story without its hidden notes, links as their words, shown components left out.
createdAt string When it was sent (ISO).
truncated? true true when text was cut at 2000 characters.
// A "Previously on…" card from the game's chat.
const said = (await game.messages()).slice(-8);
return { lines: said.map((message) => `${message.character ?? "GM"}: ${message.text}`) };
// In an afterNarrationTrigger script: did the player say the password?
const [latest] = (await game.messages())
  .filter((message) => message.role === "player")
  .slice(-1);
if (latest && /moonlit thistle/i.test(latest.text)) {
  await (await game.files("Location").get("vault-door")).update({ isOpen: true });
}
  • The text is what players saw: the GM's story without its hidden notes, its links as their words and the components it showed left out; a player's message as they typed it. Long texts are cut and marked truncated.
  • It reads the messages since the game last folded its older play into its memory, the same ones the GM reads. Older turns live in the game's memory, not as messages.
  • turn numbers messages, not exchanges: every message has its own number, counting up, so a player's message and the GM's reply to it have two (10 and 11, say). To pair them, go by their order.
  • id is opaque: compare ids, never read meaning into their form, which differs between messages the game made in different ways.
  • It works in the GM's run: everything before the reply being written, the player message that started the turn included. A card's action and a test run read none.
  • It takes no options and hands over all of them, oldest first. Return what you picked, not every message: a long game's chat can be more than a run may hand back.

Rolls, effects and reactions

game.roll

Rolls dice and shows the roll on the map and in the story, with its dice card, where the script made it: game.roll("1d20+5", { by: "Goblin 1", at: "Riven", reason: "Scimitar attack", against: { value: 14, label: "AC 14" } }).

roll(dice: string, options?: RollOptions): Promise<RollResult>
const hit = await game.roll("1d20+4", {
  by: "Goblin 1", at: "Riven", reason: "Scimitar attack",
  against: { value: 15, label: "AC 15" },
  kind: "attack", delivery: "strike",
});
if (hit.success) {
  // the scimitar lands; hit.natural === 20 for a natural 20
}

Use it instead of Math.random() for any roll players should see. It answers with the dice and whether the roll met its number: success (true with no number). Its options, the words for how it looks and where it shows are in Rolls and effects.

game.askPlayerToRoll

Asks the player to roll for their own character, and answers with their dice as roll() does: game.askPlayerToRoll("1d20+5", { by: "Riven", at: "Goblin 1", reason: "Longsword attack", against: { value: 13, label: "AC 13" } }). In a game the run stops here and the GM's reply ends with the dice in front of the player; once they roll, the run starts over with the same input, its earlier roll() calls give back the same dice, and this call answers with the player's roll. Nothing the run did before it is kept until then. Let a WAITING_FOR_PLAYER error through a catch. Where no player is asked (a test run, the assistant) the dice are rolled for them.

askPlayerToRoll(dice: string, options?: RollOptions): Promise<RollResult>

If the script catches errors, let one with error.code === "WAITING_FOR_PLAYER" through. See Rolls and effects.

game.effect

Shows something landing on people with no roll: an auto-hit, a hazard, a spell's effect.

effect(options: EffectOptions): Promise<void>
await game.effect({
  by: "Ash Wyrm", at: ["Riven", "Tarlik"], what: "Fire breath",
  delivery: "spray", element: "fire",
});

Works in diceless games too. See Rolls and effects.

game.react

Shows someone reacting: a bead over their head.

react(options: ReactOptions): Promise<void>
await game.react({ by: "Tarlik", as: "fear" });

See Rolls and effects.

Other scripts and logs

scripts

The world's other scripts, by name: const loot = await scripts.rollLoot({ tier: 2 }).

console.log

console output shows in test runs; the Game Master never sees it.

Output shows in test runs, never to the GM or players.

Errors a game call throws

FILE_TYPE_NOT_FOUND

game.files() named a file type the world doesn't have.

AMBIGUOUS_NAME

get() was given a name two or more files share; the error lists their paths, so pass an id.

SCHEMA_VALIDATION

A create, update, current-state change, roll, effect or reaction doesn't fit: an unknown field, a value of the wrong kind, a look word not on the list, dice it can't read.

The error's message says what didn't fit, and error.field names the field.

READ_ONLY_FIELD

A change tried to set a computed field or a $ field, which nothing can set.

READ_ONLY_FILE

A create or update named a markdown file type: scripts read those files but never create or change them.

REFERENCE_NOT_FOUND

A reference field was given something that matches no file of the types it points to.

CONFLICT

Someone else saved a file this run changed while it ran, so nothing the run changed was saved.

Rare. Running the script again usually works.

LIMIT_EXCEEDED

The run went past one of its limits (lookups, writes, current-state changes, moments, the server's time).

NOT_AVAILABLE

This run has no game to call: it can't read or change files.

NOT_IN_CURRENT_STATE

A current-state change, roll, effect or reaction named someone who isn't in the current state; the error lists who is.

WAITING_FOR_PLAYER

askPlayerToRoll() stopped the run to wait on the player's roll: the run goes on, from the start, once they roll. Let it through.

SERVER_ERROR

The server failed answering the call; nothing about the script caused it.

The message is general on purpose. Try again; if it keeps happening, it isn't the script.