# Writing plugins

## Commands (`./commands`)

Commands are written as `CommandDefinition` tables. This one table gives both the spec (the checks in `lim check`, completion and `lim reference`) and
what runs at play time. Conversion from .ks tags isn't written here ([Import](../plugins.md#取り込みimport)).

```ts
const stamp: CommandDefinition = {
  name: "stamp",                 // the command name in .lim (lowercase letters, digits and -)
  summary: "Press a stamp on the screen",
  positional: ["image"],         // unnamed parameters (they can't be written with a name)
  params: {
    image: t.required(t.asset("image", "Stamp image")),
    x: t.number("Horizontal center (px)", "640"),
    wait: t.bool("Wait until the stamp is pressed before continuing", true),
  },
  example: "@stamp stamps/ok.png x=900",
  waits: true,
  apply(args, extra) { /* rewrite stage.extra */ },
};
```

- **Parameter types**: `t.string` `t.number` `t.int` `t.bool` `t.duration` `t.color` `t.enum` `t.asset(folder)`,
  `t.variable` (a variable to store a value in, `game.x`), `t.target` (a jump target; `lim check` checks that the label and file exist, and Studio suggests candidates), `t.cast` (a character; for a parameter that acts on a character whose sprite is on screen, use `t.cast(description, default, { shown: true })`, described below),
  `t.condition` (a condition; written as a `(…)` expression, and the truth value evaluated at run time is passed), and `t.dataKey(file, path, description)` (a name inside project data:
  with `t.dataKey("stamps.json", "books", "Stamp book")`, a key of `books` in `data/stamps.json`, or an item's `id` if it's a list. The path is separated with `/`. `lim check` checks that it exists (`unknown-data-key`),
  and Studio's right panel suggests the names). For a number range, use `t.number(description, default, { min, max })` (the same for `t.int`; `lim check` reports values outside it, and Studio's field uses that range too).
  For sprite sets, variants and positions, use `{ type: { kind: "appearance" | "variant" | "position" } }`.
  `asset` checks that the asset exists before export, and is also used to preload each page.
- **Characters on screen**: for a parameter that only makes sense for a character whose sprite is on screen (hiding, moving, shaking, adding an emote and so on),
  use `t.cast("Character to shake", undefined, { shown: true })` (as a type, `{ kind: "cast", shown: true }`). Studio's completion lists the characters shown on that line first
  (the other characters stay in the list; `lim check` and the game don't change). Among the built-in and standard commands, `@chara-hide`, `@chara-move`, `@chara-shake`, `@emote`, `@emote-off`, `@dof`, `@tone`
  and `hide-who` of `@scene-change` have it, and `@chara` (a character you're about to show) and `@face` don't. The mark was added in API version 7; earlier engines don't read it and simply don't list the characters on screen first.
  For a character parameter of a `@define` macro, the characters on screen go first when the first command in the body (in written order) that the parameter is passed to as is (`(who)`) has this mark on that parameter
  (a macro that passes it to `@chara` first is also used for characters not yet shown, so it doesn't).
- **Translatable text**: write text shown to players (chapter titles, on-screen captions, dialog text and so on) with `t.text`, not `t.string`. In a multilingual project,
  the values written in the scenario are listed as command text in the `lim i18n` translation files, and at play time the translation for the language being played is passed to the command instead
  (if the translation is empty, the original is used). Write people's names (speakers, the person being addressed) with `t.name`, and they're listed under `speakers` in the translation files. Names are also used for matching, so
  the runtime doesn't replace them. Translate them when you display them, with `ctx.runtime.translator?.speaker(name) ?? name`.
  Text from project settings, such as the title in `ctx.runtime.chapter`, is passed already translated into the language being played.
  A command that leaves translated text in `stage.extra` gets the origin of the original text with `argOrigin(args, "parameterName")` (`@liminalia/sdk`),
  and puts `i18n: { field: origin }` next to the text. When the language is changed, or a save is loaded in another language, the runtime rewrites that field in the current language.
  To rewrite elements already on screen, use `extensions.relocalizers` (the same shape as `restorers`) to replace the text starting from the already-rewritten state.
- **Default values**: if the command is imported from a .ks tag, make them the same as that tag's value when the parameter is left out. Import writes out only values that differ from the default.
- **bare** is the name of a parameter that takes one unnamed value after the unnamed parameters (`positional`) are filled (it can also be written with its name).
  Use it for the time of a command that takes no target (with `bare: "time"`, `@stamp-off 300ms` is the same as `time=300ms`). The field was added in 0.6.0 with the API version still 6,
  so engines 0.4.0 to 0.5.x don't read it and treat the unnamed value as an extra parameter (`too-many-positional`). To support those engines, write the name in examples and docs.
- **waits** is whether to wait for the effect to end before moving on (a written `wait` takes precedence). For a command with a `wait` parameter, leaving out `waits` makes it follow that parameter's default.
  For commands written with `run`, make it match the wait passed to `ctx.present()`. Studio's "Timeline" and `lim reference` read it.
- **variables** (optional) on a plugin (`defineCommandPlugin`) are the variables that the plugin's commands store values in (`"game.x"`; ending with `.*`, like `"game.codex.*"`, covers every name under it).
  `lim check` and Studio's check report variables that are only read and never set anywhere as possible misspellings (`unset-variable`), so list here the variables you set with `ctx.runtime.setVariable` and the like.
  Flags set through the project data shape declaration (`data`) don't need to be listed.
- **replaces** (optional) is set to `true` when a command deliberately replaces a built-in command or a command with the same name from a plugin loaded earlier (such as the standard commands).
  The command from the plugin loaded later is used. If you make a command with the same name without it, `lim check` and Studio's check warn (`plugin-replaces-command`;
  this is so that you notice when a new version of the engine adds a standard command whose name collides with a command in the project's plugin).
- **category** (optional) is the section of Studio's parts panel (`screen`, `sprite`, `sound`, `motion`, `flow`, `system`). If you leave it out, the command is listed under "Custom commands".
- **keywords** (optional) are words for what you want to do (`["shake", "impact"]` and so on). They let a search in the parts panel find the command even if you don't know its name or description.
- **English** (optional): if you write `summaryEn` (the summary), `docEn` on parameters (the description), `keywordsEn` (words for what you want to do) and `exampleEn` (the example),
  Studio and VS Code in English, `lim reference --lang en` and `lim reference --json` show the English. Where they're missing, the English display shows the main (usually Japanese) text.
  Write `exampleEn` when the example contains a character's name or text that's shown (such as `@chara ユイ` or `@notify 鍵を手に入れた`), with those in English
  (it isn't needed for an example that has only asset names and setting values). For parameters,
  add it like `{ ...t.bool("押し終わるまで次に進まない", true), docEn: "Wait until the stamp is pressed before continuing" }`.
  With many commands, you can also overlay a table keyed by command name with `withEnglish` (`@liminalia/sdk`) (the built-in and standard commands use this form).
  For each name, the table holds `summary`, `params`, `keywords` and `example` (the English example).

  ```ts
  commands: withEnglish([stamp], {
    stamp: { summary: "Press a stamp on the screen", params: { image: "Stamp image", x: "Horizontal center (px)" }, keywords: ["stamp"] },
  }),
  ```
- **State** is written to `stage.extra` in `apply(args, extra)`. It goes into saves, so use only plain values that can be turned into JSON,
  and prefix keys with the plugin's name (`"stamp.list"`). Deleting the whole key when it becomes empty keeps save data small.
  To read and write it with a type, create it once with `defineState<Type>(key, initial)` (`@liminalia/sdk`) and use the same one on both the command side and the rendering side
  (no need to write `as unknown as Value`; `read` returns a copy, `update(extra, (v) => { … })` rewrites it and puts it in, and `clear` removes the whole key)
  ```ts
  interface Stamps { list: { image: string; x: number }[] }
  export const stamps = defineState<Stamps>("stamp.list", () => ({ list: [] }));
  // command: apply(args, extra) { stamps.update(extra, (s) => void s.list.push({ image: String(args.image), x: Number(args.x) })); }
  // rendering: restorers: [async (ctx, stage) => draw(ctx, stamps.read(stage.extra))]
  ```
- Commands that need more than a state update, such as storing a result in a variable, jumping or waiting for a click, are written in full with `run(args, ctx)`
  (`ctx.runtime.jump()` / `setVariable()` / `waitClick()`, and `ctx.present()` to pass things to the rendering side).
  For a command that shows UI and waits, calling `ctx.resumeHere()` before waiting makes saves made in the meantime resume from this command.
  Calling `ctx.atSceneBreak(args)` instead of `ctx.present(args, false)` holds off passing it to the rendering side until the next scene break (`@scene-change`, `@bg` with a different image, `@mask`,
  `@jump` to another file, and choices), and passes it before the next text or choices after the break (`@notify when=scene-break`; while it waits, it goes into saves.
  See "Scene breaks" in section 5 of [format.md](../design/format.md)).
  Set variables with `setVariable()` (so the change reaches watchers such as the codex's). If you rewrite `ctx.state.game` or similar directly,
  report it with `ctx.runtime.variablesChanged("game.x")`. To receive changes, use `runtime.onVariableChange(path => …)` (the returned function removes it).
  To make a picture the command showed itself (such as a temporary picture of an investigation spot) a CG in Extras, unlock it with `ctx.unlockCg(image)` (the same as `@cg-unlock`; don't rewrite system variables directly).
- Completion rates (`{ done, total }` for read text, endings, CGs, scene replays, music, movies and achievements, and the overall rate `rate`)
  can be read with `completion()` on the `system` received in `ready` (on extras screens the project makes, `ExtraScreenApi.completion()`; for the current count of a counting achievement, `achievementProgress(achievement)`).
- Commands such as chapter title cards and chapter endings can read the number and title from `ctx.runtime.chapter` (the current chapter from `chapters` in liminalia.json: `{ id, title, number, subtitle, … }` or `null`).
  If the command uses the chapter information when parameters are left out, you don't have to write the same values for every chapter (see “Chapters” in section 10 of [format.md](../design/format.md)).
  Before play starts (at the time of `ready`, on the title screen, in Extras), `system.runtime` is null, so read from `system.chapters` on the `system` received in `ready`
  (all of `chapters`; titles, numbers and subtitles are translated into the language being played; empty if there are none) and `system.chapterOf("file")`
  (the chapter of that scenario file, decided the same way as `runtime.chapter`; `null` if there's none). You can also use these to show the chapter for a save slot's position
  ```ts
  ready({ system }) {
    const titles = (system.chapters ?? []).map((c) => c.number ?? c.title); // the chapter list on the title screen
    const first = system.chapterOf?.("chapter1_1"); // the chapter of that file
  }
  ```
- A command that lets players choose where to go on its own screen (a map, investigation spots and so on) builds one list of the possible outcomes (label, jump target, value) and
  decides the result with `await ctx.pick(outcomes, answer)`. The answer is what the rendering side returned, interpreted by the command; if there is one, it becomes the result.
  When the rendering side doesn't return an answer (when running without a screen: Studio's route search, the all-routes test, `lim trace`), the engine offers the list as choices as is,
  so the search and the all-routes test can try every destination (the first item in the list is the default pick). If you include jump targets (`"file"` or `"file#label"`),
  the search tries destinations closer to its goal first
  ```ts
  const outcomes = spots.map((s) => ({ label: s.name, target: `${file}#${s.label}`, value: s.id }));
  const spot = await ctx.pick(outcomes, readAnswer(await ctx.present(args, true)));
  ```
  If you leave a destination out of the list, play without a screen can never go there, and it stays "Unreached" in Studio. If you build `targets` and `run`
  from the same function that makes the list, nothing is left out. (You can also choose with `ctx.choose(options, targets)`, but then you keep two lists.)
- **How automated checks go on** (`autoplay`): for a command that shows a screen waiting for the player (a map, investigation spots, a minigame) or a long effect that should be skipped,
  write `autoplay(args, ctx)`. When nobody is playing (`lim playtest`, `lim shot`, the desktop app's playthrough check, the all-routes test, `lim trace`),
  `ctx.present()` doesn't let the rendering side (`renderers`) draw; it calls this and uses the returned value in place of the rendering side's answer (`args` is what was passed to `ctx.present()`).
  If it returns nothing, there's no answer, and a command that chooses a destination with `ctx.pick` above gets its list offered as choices by the engine. `lim playtest` picks them
  differently on each run like other choices, and `--choose` can pick them too. If an answer is needed, such as the result of a minigame, return it
  ```ts
  const map: CommandDefinition = {
    name: "door-select",
    // …
    async run(args, ctx) {
      const outcomes = doorOutcomes(await ctx.data("doors"));                  // the list of destinations (made by the same function as targets)
      const picked = await ctx.pick(outcomes, readAnswer(await ctx.present(args, true)));
      if (picked) await ctx.runtime.jump(picked.target);
    },
    autoplay: () => undefined,                                                  // no screen; the list becomes choices
  };
  const puzzle: CommandDefinition = { name: "puzzle", /* … */ autoplay: () => ({ solved: true }) }; // goes on as if solved
  ```
  A screen of a command without `autoplay` doesn't advance just by clicking, so `lim playtest` reports it as stuck. Among the standard commands, `@investigate` offers its spots as choices,
  `@movie` doesn't play, `@codex` and `@open-screen` don't open, `@text-input` keeps its initial value, and `@dialog` answers OK.
  For an example, see `@stamp-pick` in `examples/stamp-plugin` (choosing a stamp on a screen). In the player, `?autoplay=1`,
  or a tool that sets `window.__liminalia.host.automated = true`, turns on automated checking.
  `lim shot` turns on automated checking only until it reaches the place to capture (`?autoplay=shot`). The screens of commands with `autoplay` that appear between the start position and the first page (when `--skip` is 1 or less)
  are drawn by their renderers without using `autoplay`, and captured once they've been shown for 0.5 seconds (choices too are captured once they appear).
  With `--skip` 2 or more, such screens before page N go on through `autoplay` as before, and if a choice comes up on the way, the capture doesn't choose, so it fails
  without waiting for the time limit. To capture your own command's screen, put a label right before it and capture with `lim shot <file#label>`
- **How recordings go on** (`ctx.offer`): unlike `autoplay`, a recording (`lim shot --video`) keeps the screen on. While a renderer (`renderers`) shows a screen that waits for the player,
  it tells what can be chosen with `ctx.offer(…)`. The recording shows the screen for `--read`, then picks one the same way as ordinary choices
  (`--choose`, `--avoid-choice`, `--avoid-ending`, and the next one each time it comes back to the same screen). There are two ways to tell it:
  - `{ buttons }`: the elements that can be pressed. It presses the picked one (the text is the element's text, `aria-label` or an image's `alt`, in that order; `disabled` or `aria-disabled="true"` elements aren't picked)
  - `{ options, choose(i) }`: the text of each option (`null` for ones that can't be picked) and a function that picks the i-th one. Steps inside the screen, such as showing a description before deciding or pressing twice to confirm, go here

  Both can also have `targets` (where each one jumps, `file#label`; `--avoid-ending` uses them when known) and `proceed` (always go on with this number instead of picking;
  for screens that only close or boxes with only OK). `ctx.offer` returns a function that withdraws it, so call it when the screen closes (in `finally`). Older engines don't have it, so write `ctx.offer?.(…)`
  ```ts
  renderers: {
    "door-select": async (ctx, args) => {
      const screen = buildDoorSelect(ctx, args);                                   // a screen with a button per destination (pressing one resolves picked)
      ctx.layers.overlay.append(screen.el);
      const withdraw = ctx.offer?.({ buttons: screen.buttons, targets: screen.targets });
      try {
        return await screen.picked;                                              // returns the destination to the command's run
      } finally {
        withdraw?.();
        screen.el.remove();
      }
    },
    "card-game": async (ctx, args) => {
      const game = startCardGame(ctx, args);
      // after picking, the screen plays the card and goes on to the result (the screen returns the answer)
      const withdraw = ctx.offer?.({ options: game.hand.map((c) => c.name), choose: (i) => game.play(i) });
      try {
        return await game.result;
      } finally {
        withdraw?.();
      }
    },
  }
  ```
  A screen that tells nothing doesn't advance just by clicking, so the recording stops there as stuck after `--stuck` seconds (default 60). Among the standard ones, ordinary choices,
  `@investigate` (points at the spot and shows its description before pressing it), `@map-choice` (selects a spot, shows its description, then presses the decide button), `@text-input` (keeps its initial value),
  `@dialog` (OK), and `@codex`, `@open-screen` and `@item-select` (closed) tell it. The recording reads `window.__liminalia.host.offered()` (what's offered now) and picks with `host.chooseOffered(id, i)`
- For commands whose jump targets depend on project data (letting players choose an investigation spot, choosing a destination on a map and so on), returning
  the places they may jump to (`#label`, `file#label`) from `targets(args, data)` makes Studio's flowchart draw those arrows.
  `args` are the values as written in the scenario (unnamed parameters can also be looked up by name), and `data(name)` loads project data (`data/*.json`).
  A command that always jumps somewhere and never moves on to the next line returns `leaves: true` (`{ targets: […], leaves: true }`).
  The all-routes test (`lim coverage`, Studio's check) warns (`target-never-offered`) about destinations returned by `targets` of a command it passed through that were never
  offered as a choice when running without a screen. Don't put destinations that are never chosen from that command on that line into `targets`
- **Checking the whole project**: `check` in `defineCommandPlugin({ name, commands, check(project) { … } })` loads the whole project and returns an array of diagnostics ([below](../plugins.md#作品全体のチェックcheck))
- **Checking each command**: a command's `validate(args, ctx)` is called for each line of that command in the scenario (`lim check`, `lim build`, Studio's check). The engine checks parameter types, required parameters and that assets exist
  from the spec, so write checks here for combinations of parameters and for matching against data. `args` is the text as written (unnamed parameters can also be looked up by name; parameters written as expressions aren't included),
  and `ctx` has `file`, `line`, `data(name)`, `assetExists(folder, path)`, `isCast(name)` and `targetExists(target)`. If you leave out `file` and `line` in a returned diagnostic, it points to that line,
  and you can write fixes in `fix` and `fixes` ([below](../plugins.md#作品全体のチェックcheck)). Write it as a synchronous function; throwing doesn't stop the check
  ```ts
  validate(args, ctx) {
    if (args.x !== undefined && args.at !== undefined)
      return [{ severity: "warning", code: "stamp-both", message: "Don't write x and at together", fix: { kind: "replace", find: ` x=${args.x}`, with: "" } }];
  }
  ```
- **Expression functions**: `defineCommandPlugin({ …, functions: { name: { args, doc, docEn, usage, run(args, env) } } })` adds functions that can be called from the scenario's expressions (`@if`, `@set`, `{…}`, condition expressions).
  `args` is the number of arguments (a number or `[min, max]`), and `run` receives copies of the evaluated values and returns a value (a number, string, boolean, `null`, array or object). For random numbers, use `env.random()`
  (it follows the project's random seed, so loading gives the same values). `lim check` knows the added functions and checks the number of arguments, and they also appear in the table of expression functions in `lim reference`.
  Names of built-in functions can't be used (`plugin-function-clash`; the built-in one is used)
  ```ts
  functions: { rank: { args: 1, doc: "Rank from a score (S, A, B)", run: ([score]) => (Number(score) >= 90 ? "S" : Number(score) >= 70 ? "A" : "B") } },
  ```
- **Loading project data**: inside `run`, use `await ctx.data("items")` (`data/items.json`; the extension can be left out; `undefined` if it's missing). It's loaded only once within the same play.
  The player reads the data included in the export, and `lim coverage` and Studio's search read the project folder
- **Calling a scene and returning automatically**: `await ctx.runtime.callScene("#label", again)` returns when that scene reaches the next label or the end of the file,
  without writing `@return` (it doesn't return if the scene uses `@jump`). With `again`, this command runs once more after returning (to show the investigation screen again, for example)
- **The source of expressions**: `ctx.sources` holds the text inside the parentheses of parameters written as expressions (`(…)`) (parameter name → text). The values in `args` are already evaluated, so for things that should be evaluated again whenever a variable changes
  (`show-if=` of `@hud-button` and so on), keep this text in the state and evaluate it on the rendering side with `parseExpr` and `runtime.eval`
- **State attached to a sprite**: `extra` in a sprite's state (`ctx.state.stage.sprites[character].extra`; prefix keys with the plugin's name) stays when `@chara` changes the sprite
  and goes away when the sprite is hidden (std's `@emote` uses it for manga symbols)
- **Leaving the screen covered at the end of an effect**: use `leaveParam("none")` from `@liminalia/sdk/std` as the parameter `leave`, and call `presentLeaving(args, ctx, wait)` in `run`;
  with `leave=mask`, the cover (`stage.mask`) remains after waiting. The rendering side covers the screen at the end with `ctx.mask.cover("#000000")` (the same as std's `@chapter-end`)
- **Unlocking CGs from data**: `ctx.runtime.unlockCgImage("bgimage", path)` unlocks the image as a CG if it's in extra.cg. Mark that field as a CG in the data shape declaration ([below](../plugins.md#作品のデータの形data))
- Commands that end the play (returning to the title, quitting the game and so on) set `ends: true`. Studio's flowchart puts an end mark on scenes that end with this command
  and doesn't draw a line to the next label (so bad endings show up as separate branches). If the command has an `ending` parameter (and `title`),
  it's read as the kind of ending (the same as `@title-screen ending=bad`; "The end of a playthrough" in [format.md](../design/format.md)) and used for the mark, avoiding endings, `lim coverage` and achievements

### Checking the whole project (`check`)

Rules that a single command can't tell, such as mismatches between project data and the scenario, are reported by `check` in `./commands`. `lim check`, `lim build` (its check along the way) and Studio's check call it, and in Studio the results go into the "Plugins" category.

```ts
export default defineCommandPlugin({
  name: "stamp",
  commands: [stamp, stampClear],
  check(project) {
    const memos = (project.data("stamps.json") ?? {}) as Record<string, string>;
    return Object.keys(memos)
      .filter((image) => !project.assetExists("image", image))
      .map((image) => ({
        severity: "warning" as const,
        code: "stamp-memo-orphan",
        message: `スタンプ帳のメモの画像 ${image} が素材にありません`,
        messageEn: `The image ${image} of a stamp memo isn't in the assets`,
        file: "data/stamps.json",
      }));
  },
});
```

- **`project`** (`PluginCheckProject`): `root` (the project folder), `config` (liminalia.json), `scripts` (file → syntax tree), `text(file)` (the scenario's text), `cast`, `speakers`, `registry` (the command specs), `data(name)` (`data/*.json`; `undefined` if it's missing), `assetExists(folder, path)`
- **What to return** (`PluginDiagnostic`): `severity` (`error`, `warning`, `info`), `code` and `message` are required. Optionally `file` (defaults to `liminalia.json`), `line` (defaults to 1), `column` and `hint`. If `file` is a scenario (a name without the extension), clicking the result in Studio goes to that line
- **Fixes**: write fixes that can be applied mechanically in `fix` (one) or `fixes` (a list in order of preference), and "Fix" appears in Studio's check and in the editor.
  `{ kind: "replace", find, with }` (replaces `find` on that line), `{ kind: "delete-line", text }` (deletes that line), `{ kind: "add-speaker", name }` (adds it to the speakers),
  `{ kind: "add-label", file, label }` (adds a label at the end of the scenario). Fixes in the wrong shape are dropped.
  With a `column`, `replace` applies only to a `find` that contains the character at that column or starts inside the word that starts there (up to a space or `}` outside `"…"` and `(…)`), and isn't applied if there's none.
  Without a `column`, it applies to the first `find` on the line. When the same text can appear twice on a line (such as the parameters of `{@…}` in text), give a `column`
- **English display**: if you have translations, put them in `messageEn` and `hintEn`. If not, the English display shows `message` and `hint` as they are
- **Write it as a synchronous function**. It's also called on every save, so avoid heavy work. Returning an `error` stops `lim build`
- **Throwing doesn't stop anything**: exceptions (as well as return values that aren't arrays and malformed diagnostics) don't stop the whole check. They're reported as errors of that plugin (`plugin-check-failed`, `plugin-check-invalid`)
- `./commands` is also included in the exported game (the game doesn't call `check`), so don't import Node modules for `check`. Read files with the functions on `project`

### Project data shapes (`data`)

Declare the shape of the project data a plugin reads (`data/*.json`) in `data` in `./commands`. This one declaration gives you the following.

- `lim check` and Studio's check: checks the shape (types, required fields, duplicate names in lists), that assets exist, characters, jump target files and labels, and expressions, and shows the JSON line (`data-*`)
- Matching flags: a variable the data reads (in a condition expression, or as a flag it reads) that no scenario's `@set` and no data sets gets a warning (`data-flag-unset`),
  and a variable the data sets (that the plugin sets) that nothing reads gets an info (`data-flag-unread`). Variables with an initial value in `variables` in liminalia.json are skipped
- The check for CGs that are never shown (`unshown-cg`): images in fields marked as CGs (`d.asset(…, { cg: true })`) count as shown
- Studio: under "Data" in the left panel of the "Plugins" tab, an automatic form appears for each declaration (assets are picked from a list, lists can be reordered, in lists that hold rectangle fields you add and move rectangles by dragging on the background, and point fields are placed where you click or drag on the picture. The list of an asset field also has the assets in its `also` folders.
  Changes are saved automatically after a short pause, and if the file was changed elsewhere, the changes are merged three ways and saved again. A missing file is made with "Create")
- Renaming: when you rename a scene, file, asset, variable or character in Studio, references in declared data are updated too (the change history is kept in `.liminalia/history/@data/`)

```ts
import { d, defineCommandPlugin } from "@liminalia/sdk";

export default defineCommandPlugin({
  name: "stamp",
  commands: [stamp, stampClear],
  data: [
    {
      file: "stamps.json",
      title: "スタンプ帳",
      titleEn: "Stamp book",
      root: d.map(d.record({ image: d.required(d.asset("image", "Image", { cg: true })), memo: d.text("Memo"), when: d.expr("Condition to show it"), next: d.scene("Jump to when pressed") })),
    },
  ],
});
```

| Form | Contents |
|---|---|
| `d.string` `d.text` `d.number` `d.int` `d.bool` `d.enum([…])` | Text (one line, several lines), a number, true or false, a choice from a list. `d.string(label, { translate: true })` and `d.text(label, { translate: true })` are text shown to the player, and `lim i18n` lists them in the translation file. When drawing, `dataText(file, source)` from `@liminalia/sdk/web` gives the translation for the current language (the source if there's none) |
| `d.asset(folder, label, { cg, also })` | An asset path. With `cg`, the plugin unlocks this image as a CG. `also` lists other folders to look in when it isn't in the folder (for a field whose folder changed, so assets in the old place still pass; the rendering side should look in the same order) |
| `d.flag("set" \| "read")` | A flag (`game.x` or `x`). Whether the plugin sets it or reads it, based on the data |
| `d.expr()` | A condition expression (the variables in it count as flags that are read) |
| `d.cast()` `d.file()` | A character ID, a scenario file |
| `d.scene(label, { base, bare })` | A jump target. `base` is the name of the outer field that holds the file for `#label`; with `bare`, write only the label, without `#` |
| `d.ref("/entries")` | A name within the same data (the `id` of a list item, or a dictionary key) |
| `d.rect(label, { image })` | A rectangle in game-screen px (`x` `y` `width` `height`). `image` is the name of the background asset field (Studio lets you draw the rectangle by dragging on that image) |
| `d.point(label, { image, unit, keys })` | A point on a picture (`{ x, y }`). With `unit` `percent` (the default), a percentage from the top left of the picture (0 to 100); with `px`, game-screen px. `image` is the name of the background asset field; `ref field>asset field` (`category>map`) means the asset field of the item the ref field points to. With `keys` (`["x", "y"]`), the value isn't grouped but goes in two fields of the same record (Studio shows the picture and places the point where you click) |
| `d.list(item, label, { sortable, key })` `d.record({…}, label, { title })` `d.map(value)` `d.json()` | A list (`key` is the field that tells items apart), a record (`title` is the field used as its heading in lists), a dictionary, a value of any shape |
| `d.required(field)` | Makes the field required |

Labels are text or `{ label, labelEn, doc, docEn }`. Write declarations with plain values that can be turned into JSON (they're sent to Studio as is). If two plugins declare the same file, the later one wins.
The standard commands also declare investigation spots (`data/investigation.json`) and the codex (`data/codex.json`) in this form (`packages/std/src/commands/investigate.ts`, `codex.ts`).
