Using the Longshot API
The API a script mod uses is a set of modules, all shaped by a few shared ideas: events are values, handles end, the
game’s objects answer null once they are gone, parts of the API may be missing from a game build, and everything runs
at fixed points of the frame, within a budget, with the player’s permission. This page is a tour of the modules and of
those ideas, each with a short example and a link to where it is explained in full. Start with
your first mod if you have not made one yet; every function, event and type is in
the reference.
A mod needs no build: the game compiles its TypeScript itself as it loads it
(how TypeScript runs). To test and check a mod you need its tools, which run on
Node: install mise, then in your mod’s folder mise use node@26 (any Node 22 or later you
have works too). TypeScript 7, the type checker, comes per mod through npm, pinned in its package.json
("typescript": "7.0.2"), not through mise (your first mod).
Contents: The modules · Events are values · Handles · Game objects · Features · Filters and drafts · Data rules · Claims · The frame’s order · Budgets and faults · Permissions · Multiplayer · Errors
The modules
Every module has named exports and a default export, its namespace object: import log from "longshot/log"; log.info(...)
and import { info } from "longshot/log"; info(...) are the same function. There is no global: what a module does not
import, it cannot reach.
| Module | What it is | Guide |
|---|---|---|
longshot |
The API itself: version, has(), the error classes and the shared types |
Features, Errors |
longshot/game |
The game: state(), its flags, the frame’s events (frame, update), its moments (mapLoaded, saveWriting, flagChanged, paused), pause() and game-time after() |
Scripting, The game’s moments, Writes |
longshot/player |
Link: state() (position, velocity, life, rupees), set(), setPosition(), setAge() |
Scripting, Writes |
longshot/log |
The mod’s log: debug, info, warn, error |
Scripting |
longshot/storage |
The mod’s own data, in three scopes: global, profile, save |
Storage |
longshot/items |
The places Link checks, the items that reach him, and items a mod gives | Items |
longshot/actors |
The game’s live actors: a frozen list each frame, handles, their events, writes, actors a mod spawns or attaches to another’s bone, and answers to their behaviour’s questions | Actors |
longshot/rules |
Data rules: damage taken and dealt, an actor’s life at spawn, what a chest gives, cutscenes skipped | Rules |
longshot/input |
The controller: the mod’s actions, the pad as the game reads it, a filter on it, presses, rumble, the mouse | Input |
longshot/camera |
The camera: its view each frame, and an override | Camera |
longshot/ui |
The mod’s UI in TSX: the HUD, windows, a settings page, labels over the world, slots | Mods’ UI |
longshot/settings |
The settings mod.json declares: get, set, changed |
Settings |
longshot/permissions |
What the player granted, and asking for an optional permission | Permissions |
longshot/time |
Real-time timers: after, every, and when the game started (gameStarted) |
Dev mode |
longshot/dev |
Values kept across a hot reload, and reloading |
Dev mode |
longshot/lifecycle |
stopping, before the player’s switch stops the mod |
Lifecycle |
longshot/mods |
Other mods: their exports, events between mods, registries, claims | Mods together |
longshot/net |
WebSockets and HTTPS to the servers mod.json declares and the player grants |
The network |
longshot/worker |
Heavy work on a thread of its own, by messages | Workers |
longshot/gfx |
Screen effects (GLSL shaders) and shapes drawn inside the 3D scene | Screen effects, World drawing |
longshot/content |
What a mod adds to the game (items, actors, models, placements, texts, flags, behaviour trees), declared once at the start, and the game’s data read back (read) |
Content |
longshot/behaviour |
Scripted components: a behaviour of your own for each actor of a type, with its own state | Behaviour |
longshot/audio |
The mod’s own sounds, played as they are or placed in the world | Audio |
longshot/world |
The maps Link can be taken to (destinations(), travel()), the world’s state by name (states(), state(), setState()), and a ray against the game’s own collision (not in any game build yet: has("world.ray") is false) |
Writes, Reference |
longshot/memory, longshot/romfs, longshot/hooks |
The unsafe tier: the game’s memory by address, its files, and a mod’s own hook sites | Unsafe mods |
longshot/native |
Calling a native mod’s own C or C++ | Native source mods |
longshot/ipc |
Another program’s local socket or named pipe, ones mod.json declares (system mods only for now: the Discord status) |
Local IPC |
The table generated from the API’s schema, with every module’s exports and permissions, is in the author’s guide.
Events are values
An event is an object you subscribe to with on(). It returns a subscription: off() ends it, and so does the end
of a using block. A mod’s subscriptions all end when it stops.
import { update, mapLoaded } from "longshot/game";import log from "longshot/log";
const sub = update.on(({ frame, dt }) => { if (frame > 600) sub.off(); // ten seconds at 60 frames, then no more calls});
{ using watch = mapLoaded.on((e) => log.info("map loaded", e)); // ...} // off() here, however the block is leftSome events take a filter as their second argument, and call the listener only for what it names:
spawned.on(fn, { type: "Enemy_Octorok" }) of longshot/actors. A few tell a listener only what its filter asks for,
and nothing without one, so the game watches only what someone listens to:
flagChanged.on(fn, { flag: "PlayerStatus.Life" }). More: scripting,
the game’s moments.
Handles: release and StaleHandleError
A handle is something the mod holds by reference: an object with methods and no data of its own. Handles of the
mod’s own resources (an input action, a camera override, a pause, a pointer capture, a world shape) have release(),
which ends them, as does the end of a using block or the mod’s stop. Releasing twice does nothing; anything else asked
of a released handle throws StaleHandleError, because touching it then is a bug in the mod.
import camera from "longshot/camera";import { StaleHandleError } from "longshot";
const view = camera.override(); // the claim "camera", and the view is the mod'sview.setFov(40);view.release(); // the game's camera is back the next frame
try { view.setFov(50);} catch (e) { if (!(e instanceof StaleHandleError)) throw e;}A data rule (rules.damageTaken.add(...)) is ended by remove(), and by using too. More:
the schema’s handles.
Game objects answer null once gone
A handle to one of the game’s objects, an Actor, has no release(): the game removes it when it wants, between
two frames. Asking about one that is gone is normal, so it never throws: info() answers null and alive() answers
false. The same holds for state: player.state() is null when there is no Link, and a field the game build lacks
reads null. Nothing is a made-up 0.
import type { Actor } from "longshot";import { spawned } from "longshot/actors";import { update } from "longshot/game";
const watched = new Map<string, Actor>();spawned.on(({ actor, key }) => watched.set(key, actor), { type: "Enemy_Octorok" });
update.on(() => { for (const [key, actor] of watched) { const info = actor.info(); // this frame's snapshot, or null once it is gone if (!info) watched.delete(key); }});Snapshots are frozen copies: within one frame state() gives the same object, the next frame a new one. Handles are not
compared with ===: compare their key. More: actors.
Features: has() and NotAvailableError
Parts of the API that depend on a hook into the game’s code can be missing from a game build. Each such part is a
feature, named by its path (player.state.rupees, game.flags.get, world.ray). The modules are the same on every
build: a function whose feature is missing is still there, and throws NotAvailableError when called, and a record field
whose feature is missing reads null.
import { has, NotAvailableError } from "longshot";import world from "longshot/world";import log from "longshot/log";
const from = { x: 0, y: 2, z: 0 }, to = { x: 0, y: -10, z: 0 };if (has("world.ray")) { const hit = world.ray(from, to);}
try { world.ray(from, to);} catch (e) { if (e instanceof NotAvailableError) log.warn(`no ${e.feature} in this game build`); else throw e;}A feature the mod cannot do without goes in mod.json’s requires: on a build without it the mod stays off and says
why, and longshot-mod types tells TypeScript that its fields are never null. has() takes any text and answers
false for a name this API does not have, so a mod written for a newer API asks rather than throws. More:
supporting several game builds.
Filters and drafts
A filter changes what the game reads or shows, at a fixed point of the frame. It is handed a draft of a record:
change its fields and the game uses what is left. Filters of several mods chain in the mods’ load order; fixed fields
cannot be written, no field can be added, and cancel() gives the game nothing this time.
import { pad } from "longshot/input";
pad.intercept((draft) => { if (draft.buttons.l && draft.buttons.r) { // L+R is ZL draft.buttons.l = draft.buttons.r = false; draft.buttons.zl = true; }});A filter returns a subscription. With { exclusive: true } it takes a claim and runs last. More:
input, the schema’s filters.
Data rules
The game updates its world on threads where no script may run. To change what happens there (the damage of a hit, what a chest gives, an actor’s life at spawn), a mod sets a data rule ahead of time: a value the game applies itself, in C, at every match. No code of the mod runs then.
import { damageTaken, damageDealt } from "longshot/rules";
damageTaken.add({ scale: 0.5 }); // Link takes halfconst cap = damageDealt.add({ max: 8, where: { target: "Enemy_Octorok" } });cap.remove(); // until it is removedThe rules of every mod combine the same way every time (the scales, then the additions, then the limits). They need
state.write. More: rules.
Claims
Some things only one mod can have at a time: the camera, the controller taken whole, the reward table. A mod claims
them. An API call that needs a claim takes it (camera.override(), an exclusive pad.intercept), and another mod’s call
then throws ClaimError, naming the claim and its holder. It is given back when the handle is released or the mod
stops. A mod that always takes one says so in mod.json, so that two such mods are found to conflict before the game
starts:
"claims": ["camera"]claimant(claim) of longshot/mods says which mod holds or declares a claim. More:
mods together.
The frame’s order
A script never runs on the game’s own threads. It runs only at the frame’s serial point, on the main thread, one callback at a time, in the same order every frame: no locks, and no mod can race another or the game. In each game frame (in play, menus, pauses, loading and movies; frames the renderer generates do not count):
frame, then the save slot’sloaded, then the timers that are due;update, then the items’, the actors’ and the settings’ and permissions’ events, then input (actions and filters);- calls and events between mods, the network and workers;
- the UI’s changes, then the frame’s writes to the game (
player.set,flags.set, the actors’), attachments, the sounds and the data rules; - reloads and the Mods tab’s switches (
stopping), then the game’s moments (mapLoaded,saveWriting,flagChanged,paused).
Within an event, mods are called in load order and each mod’s listeners in the order it subscribed. A write is made
after every mod’s update, so reads within a frame see that frame’s state. Promises settle at the same serial point.
More: phases and threads,
the frame’s order.
Budgets and faults
Every mod has its own interpreter and its own budget, counted in the CPU time its script ran:
| Limit | Past it |
|---|---|
| 5 ms a callback | Interrupted: a fault |
| 2 ms of one mod in a frame | A warning in the log |
| 8 ms of one mod in a frame | A fault |
| 64 MB of heap | Out of memory: the callback faults |
| 1,024 subscriptions | LimitError |
| 100 log lines a second | The rest are dropped and counted |
A fault is a callback that threw, ran out of time or memory, or left a rejected promise unhandled. One fault does not stop the mod; three in a minute stop it for the session, and the Mods tab and the log say why. A fault’s line says where the time went (the API’s calls, the garbage collector, the mod’s own JavaScript), so a slow script can be told from a busy PC:
script runtime: local/enemy-names: fault in longshot/game update listener: it ran 6.1 ms of CPU, over the 5 ms a callback may (...)Ask the API for less rather than filtering in script: actors.list({ typePrefix: "Enemy_", limit: 8 }) makes 8 objects,
not 500. The mod inspector (F8) shows each mod’s time against its budget. More:
the limits.
Permissions and optional permissions
A call without its permission throws PermissionError, whose permission names it. mod.json lists what the mod needs
(permissions: the player is asked for these when turning it on) and what it may ask for while it runs
(optionalPermissions: asked only when a feature of the mod needs it).
"permissions": ["state.read"],"optionalPermissions": ["ui.hud"]import permissions from "longshot/permissions";import { mount, Hud, Text } from "longshot/ui";
async function showBadge() { if (!permissions.has("ui.hud") && !(await permissions.request("ui.hud"))) return; // the player said no mount(<Hud region="top-right"><Text>Hello</Text></Hud>);}showBadge();permissions.changed.on(({ permission, granted }) => { /* taken back in the Mods tab, or granted */ });request() shows the game’s prompt and settles at a later frame with the player’s answer; the player can take an
optional permission back at any time on the mod’s Permissions page. Logging, has, version, the frame event,
settings, longshot/permissions, longshot/dev, longshot/time and longshot/lifecycle need no permission. Ask for as little as you can:
longshot-mod lint warns about a permission declared and never used. More: scripting,
the permission table.
Multiplayer modes
mod.json’s multiplayer says who in a co-op room needs the mod:
multiplayer |
Means | For |
|---|---|---|
"local" (the default) |
Each player’s own choice | A HUD, a timer, a tracker |
"all" |
Every player, at the same version | A mod that changes the game or adds to it |
"host" |
Only the host |
A mod with state.write, items.grant, content.add or actors.spawn changes the world everyone shares, so it cannot be "local":
the game refuses such a manifest, and longshot-mod lint says so first. Co-op itself is not in Longshot yet
(#68), and how a room compares its players’ mods comes with
it. More: the manifest.
Errors
The API’s errors are classes of longshot, each extending LongshotError, so a mod tells them apart with instanceof:
ArgumentError (a wrong argument, never clamped), PermissionError, NotAvailableError, UnknownNameError (a flag or
a map the build’s list does not have), ClaimError, StaleHandleError, LimitError, QuotaError and the others in
the error table. A refusal that only means “not now” is not an error: player.set() outside play
returns false. HostError is a bug in Longshot, not in your mod: report it.
