Skip to content

Server globals serverside ​

Everything available to serverside scripts, weapon server halves, classes and serverside NPC code (globals.d.ts).

Source

Generated from templates/server/data/scripts/globals.d.ts. To change this page, edit the JSDoc in that file.

Overview ​

Ambient declarations for host functions injected by the ClearScript V8 runtime (see GServer). These are available to every script in this folder without needing an import.

Fire-and-forget host calls (like echo) are batched: they queue JS-side and are delivered to the server in one batch at the next flush point (end of the current server tick at the latest, 50ms at 20 TPS). Ordering between batched calls is preserved, but their arguments must be JSON-serializable and they cannot return values. Calls that return values or take callbacks (sleep, setTimeout, ...) reach the server directly instead.

Declarations ​

echo function ​

ts
declare function echo(msg: string): void

Prints a message to the server console. Batched: delivered at the next flush point (end of the current server tick at the latest). The argument must be JSON-serializable.

sleep function ​

ts
declare function sleep(seconds: number): Promise<void>

Cooperatively pauses the calling (async) script for the given number of seconds. Other scripts keep running while this one is suspended. Resolution is tied to server ticks, so resume timing is rounded up to the next tick (50ms at 20 TPS).

setTimeout function ​

ts
declare function setTimeout(handler: (...args: any[]) => void, ms?: number, ...args: any[]): number

Runs handler once after ms milliseconds (rounded up to the next server tick). Returns an id usable with clearTimeout. Extra args are forwarded to the handler.

clearTimeout function ​

ts
declare function clearTimeout(id: number | null | undefined): void

Cancels a pending setTimeout by id. null, undefined or an unknown id is a no-op.

setInterval function ​

ts
declare function setInterval(handler: (...args: any[]) => void, ms?: number, ...args: any[]): number

Runs handler repeatedly every ms milliseconds (fires at most once per server tick). Returns an id usable with clearInterval. Extra args are forwarded to the handler.

clearInterval function ​

ts
declare function clearInterval(id: number | null | undefined): void

Cancels a running setInterval by id. null, undefined or an unknown id is a no-op.

triggerClient function ​

ts
declare function triggerClient(scriptType: 'weapon', scriptName: string, ...params: any[]): void

Sends an action to the CURRENT player's client, invoking onActionClientSide(...params) on their copy of the named weapon. Batched; params must be JSON-serializable.

"Current player" is the player whose event is being handled — valid inside onActionServerSide, onPlayerJoined and onPlayerLeft. There is no current player after an await or inside timer callbacks; calls made there are dropped (with a server-console log). scriptType is "weapon" for now (clients run nothing else); scriptName is the weapon's name — in a weapon's serverside half, this.name reaches its own clientside half:

ts
export function onActionServerSide(this: ScriptThis, player: Player, action: string) {
    triggerClient('weapon', this.name, 'reply', 'hi ' + player.account)
}

sendPM function ​

ts
declare function sendPM(target: string | Player, text: string): void

Sends a SYSTEM private message to a player on any server, via GSocial. The client receives it as onPMReceived({ account: <this server's name>, server: <this server's name>, system: true }, text). Online-only: dropped if they aren't connected anywhere. Text max 200 characters. Accepts an account name or a Player. Unlike triggerClient, needs no player context.

ts
sendPM(player, 'Welcome back!')
sendPM('SomeAccount', 'Server restarts in 5 minutes')

findplayer function ​

ts
declare function findplayer(account: string): Player | null

The online player logged in with this account name (case-insensitive) — a full Player object, client./clientr. flag bags included — or null when they aren't connected to THIS server. Needs no player context, so it works from timers, onInitialized and async continuations. Like every Player, x/y/level are a snapshot taken by this call.

ts
const p = findplayer('SomeAccount')
if (p) p.clientr.gold = (p.clientr.gold ?? 0) + 10

allplayers global ​

ts
declare const allplayers: readonly Player[]

Every player online on THIS server, in connection order — full Player objects, client./clientr. flag bags included. Needs no player context. Each read builds a fresh snapshot array (x/y/level as of that read), so read it once into a local rather than indexing it in a loop, and compare players by account or id, not ===.

ts
const online = allplayers
for (const p of online) sendPM(p, 'Server restarts in 5 minutes')

createlevel function ​

ts
declare function createlevel(name: string, fillTile: number, width?: number, height?: number): string

Creates a new blank level named <name>.glvl, width x height tiles (8-512 per side, default 64x64), filled with fillTile on layer 0 (65535 = empty). Names are 1-32 characters (letters, digits, _ or -) WITHOUT extension; creation fails if any level (saved or unsaved) already uses the name. The level lives in server memory and is served to players immediately, but its .glvl file is only written when someone saves it (findlevel(name).savelevel() or "update level") — unsaved levels vanish on server restart. Returns '' on success or a player-presentable error message. Direct call: the result is available immediately.

copylevel function ​

ts
declare function copylevel(original: string, newName: string): string

Copies a level to a new .glvl file in the same folder as the original. The copy takes the original's current state, including unsaved in-game edits: tiles, collision, NPCs, links and tileset. It's written to disk right away, so no savelevel is needed. original is a level file name such as 'town.glvl' (not a gmap). newName follows the createlevel rules (1-32 letters, digits, _ or -), with or without '.glvl', and the copy fails if any level (saved or unsaved) already uses it. Returns '' on success or a player-presentable error message. Direct call.

ts
const error = copylevel('arena.glvl', 'arena_' + player.account)

deletelevel function ​

ts
declare function deletelevel(name: string): string

Deletes a level for good: its .glvl file and any unsaved in-memory copy. Everyone in the level, in the shared world or in an instance of it, is warped to the server's start position first. Then the level's NPCs, local ones included, are unloaded and their timers stop. Refuses gmaps, gmap members and the server's start level. Returns '' on success or a player-presentable error message. Direct call. Don't call it from an NPC in the level being deleted, because that NPC is unloaded too.

ts
deletelevel('arena_' + player.account + '.glvl')

findlevel function ​

ts
declare function findlevel(name: string): ServerLevel | null

A level object for a level or gmap by file name — findlevel('town.glvl') or findlevel('world.gmap') — with the same API as player.level. Works for any level, whether or not anyone is in it, including unsaved levels made with createlevel. Returns null when no such level or gmap exists. Direct call.

ts
const town = findlevel('town.glvl')
town?.setleveltiletype(10, 4, 22)

LevelNpcInfo interface ​

ts
interface LevelNpcInfo

A baked level NPC as stored in the level file (see LevelEditor.getlevelnpcs).

LevelNpcInfo.index ​

ts
index: number

Position in the level's NPC list; shifts down when an earlier NPC is removed.

LevelNpcInfo.x ​

ts
x: number

X position in tiles (fractions allowed).

LevelNpcInfo.y ​

ts
y: number

Y position in tiles (fractions allowed).

LevelNpcInfo.image ​

ts
image: string

Image asset path ('' = none).

LevelNpcInfo.serverscript ​

ts
serverscript: string

TypeScript source of the serverside half ('' = none).

LevelNpcInfo.clientscript ​

ts
clientscript: string

TypeScript source of the clientside half ('' = none).

LevelNpcPatch interface ​

ts
interface LevelNpcPatch

Fields to set on a baked level NPC (addlevelnpc / setlevelnpc); omitted fields keep their value ('' / 0 for a new NPC).

LevelNpcPatch.x ​

ts
x?: number

X position in tiles.

LevelNpcPatch.y ​

ts
y?: number

Y position in tiles.

LevelNpcPatch.image ​

ts
image?: string

Image asset path ('' = none).

LevelNpcPatch.serverscript ​

ts
serverscript?: string

TypeScript source of the serverside half.

LevelNpcPatch.clientscript ​

ts
clientscript?: string

TypeScript source of the clientside half.

LevelLinkInfo interface ​

ts
interface LevelLinkInfo

A level link as stored in the level file (see LevelEditor.getlevellinks).

LevelLinkInfo.index ​

ts
index: number

Position in the level's link list; shifts down when an earlier link is removed.

LevelLinkInfo.x ​

ts
x: number

Trigger rect left edge, whole tiles.

LevelLinkInfo.y ​

ts
y: number

Trigger rect top edge, whole tiles.

LevelLinkInfo.w ​

ts
w: number

Trigger rect width in tiles (at least 1).

LevelLinkInfo.h ​

ts
h: number

Trigger rect height in tiles (at least 1).

LevelLinkInfo.destlevel ​

ts
destlevel: string

Destination level (or gmap) file name, e.g. "house.glvl".

LevelLinkInfo.destx ​

ts
destx: number

Arrival x in the destination, tiles (ignored when keepx).

LevelLinkInfo.desty ​

ts
desty: number

Arrival y in the destination, tiles (ignored when keepy).

LevelLinkInfo.keepx ​

ts
keepx: boolean

Keep the player's current x instead of destx (Graal "playerx"), for seamless edge links.

LevelLinkInfo.keepy ​

ts
keepy: boolean

Keep the player's current y instead of desty (Graal "playery").

LevelLinkPatch interface ​

ts
interface LevelLinkPatch

Fields to set on a level link (addlevellink / setlevellink); omitted fields keep their value (0 / '' / false for a new link). The result must be a valid link: a destination, w and h >= 1, the rect inside the level.

LevelLinkPatch.x ​

ts
x?: number

Trigger rect left edge, whole tiles.

LevelLinkPatch.y ​

ts
y?: number

Trigger rect top edge, whole tiles.

LevelLinkPatch.w ​

ts
w?: number

Trigger rect width in tiles.

LevelLinkPatch.h ​

ts
h?: number

Trigger rect height in tiles.

LevelLinkPatch.destlevel ​

ts
destlevel?: string

Destination level (or gmap) file name.

LevelLinkPatch.destx ​

ts
destx?: number

Arrival x in the destination, tiles.

LevelLinkPatch.desty ​

ts
desty?: number

Arrival y in the destination, tiles.

LevelLinkPatch.keepx ​

ts
keepx?: boolean

Keep the player's current x instead of destx.

LevelLinkPatch.keepy ​

ts
keepy?: boolean

Keep the player's current y instead of desty.

LevelEditor interface ​

ts
interface LevelEditor

Online-editing methods shared by every serverside level object — player.level, findlevel(), the player-scoped global level and an NPC's this.level. All edits go into the server's in-memory copy of the level: tile, tile-type and link changes reach players immediately, NPC edits are staged until reloadlevel(), and nothing touches the .glvl file until savelevel().

Coordinates are whole tiles in the object's own space: on a gmap object, gmap-global tiles that route to the member level underneath; in an NPC's this.level, member-local. NPC and link editing need a single level, so on a gmap object the *levelnpc* and *levellink* methods fail — use findlevel(memberName). Objects for an instance read the shared template but every edit fails. None of these check staff rights: gate them in your script (player.hasstaffright('leveleditor')).

LevelEditor.setleveltile ​

ts
setleveltile(layer: number, x: number, y: number, tileId: number): boolean

Sets one tile: tileId is a row-major tileset index (65535 = empty/erase). Every player who sees the level — the initiating player included — receives the change immediately. No-op repaints don't broadcast. Returns false for out-of-range arguments (including a layer the level doesn't have).

LevelEditor.getleveltile ​

ts
getleveltile(layer: number, x: number, y: number): number

The tile id at (x, y) on layer in the level's current server state, unsaved edits included (65535 = empty); -1 when out of range.

LevelEditor.getleveltiletype ​

ts
getleveltiletype(x: number, y: number): number

The collision tile type at (x, y) in the level's current server state (1 = walkable, 22 = blocking, 11 water, 12 lava, ...); -1 when out of range.

LevelEditor.setleveltiletype ​

ts
setleveltiletype(x: number, y: number, type: number): boolean

Sets the collision tile type (1-255; 22 blocks movement) of one tile. Every player who sees the level gets it immediately — walls block (or stop blocking) at once. Returns false for out-of-range arguments.

LevelEditor.setleveltiletypes ​

ts
setleveltiletypes(x: number, y: number, w: number, h: number, types: number | number[]): boolean

Sets the collision tile types of a w x h rect at (x, y): types is one type for the whole rect or a row-major array of exactly w * h types (each 1-255). The rect must lie inside the level (on a gmap it may cross member seams, but not holes). All-or-nothing: any invalid value fails the whole call and changes nothing. Sent to players as one update per level touched.

ts
player.level?.setleveltiletypes(10, 4, 6, 1, 22)   // a wall segment

LevelEditor.getlevelnpcs ​

ts
getlevelnpcs(): LevelNpcInfo[] | null

The level's baked NPCs in its current server state (staged edits included), in index order — positions and full script sources. Local NPCs (putnpc) aren't part of the level and are never listed. Null on gmap objects.

LevelEditor.addlevelnpc ​

ts
addlevelnpc(data: LevelNpcPatch, live?: boolean): number

Appends a baked NPC and returns its index (-1 on a gmap object, an instance, or invalid fields). Staged: running NPCs don't change until reloadlevel() — unless live is true, which also spawns the new NPC in the running level right away (like reloadlevelnpc(index)).

ts
const town = findlevel('town.glvl')
const index = town?.addlevelnpc({ x: 30, y: 20, image: 'images/sign.png',
    serverscript: "export function onCreated() { this.chat = 'Hi' }" }, true)

@param data The new NPC's fields; omitted ones are '' / 0. @param live True to spawn it in the running level now; omitted/false stages it.

LevelEditor.setlevelnpc ​

ts
setlevelnpc(index: number, patch: LevelNpcPatch, live?: boolean): boolean

Changes fields of the baked NPC at index — staged until reloadlevel(), or with live true applied at once by restarting just that NPC (like reloadlevelnpc(index)). A wrongly typed field fails the whole call. Returns false for bad indices and on gmap objects.

@param index The NPC's position in getlevelnpcs(). @param patch The fields to change; omitted ones keep their value. @param live True to restart the running NPC with the change now; omitted/false stages it.

LevelEditor.removelevelnpc ​

ts
removelevelnpc(index: number, live?: boolean): boolean

Removes the baked NPC at index. Staged: the running NPC keeps running until reloadlevel() — unless live is true, which removes it from the level right away (its timers die, players stop seeing it). Every later NPC's index shifts down by one — re-read getlevelnpcs() after removing. Returns false for bad indices and on gmap objects.

@param index The NPC's position in getlevelnpcs(). @param live True to remove the running NPC now; omitted/false stages it.

LevelEditor.reloadlevelnpc ​

ts
reloadlevelnpc(index: number): boolean

Restarts just the baked NPC at index from the level's current server state (staged edits to it included) — the per-NPC reloadlevel(). The running NPC is torn down (its timers die) and recreated: onCreated fires, then onPlayerEnters for every player who sees the level, and players get the fresh NPC — clientside script included — without reloading the level. An NPC just added with addlevelnpc spawns. Other NPCs, putnpc locals and the level's shared state (this.level.<key>) are untouched. Instanced copies of the level restart it too. A level nobody has entered yet just picks the change up when it activates. The first compile of a new script blocks the server briefly. An NPC that reloads itself ends its own script (onCreated runs again on the fresh copy, so guard against loops). Returns false for bad indices, on gmap objects and on instance objects.

ts
town?.setlevelnpc(3, { serverscript: source })
town?.reloadlevelnpc(3)

@param index The NPC's position in getlevelnpcs().

ts
getlevellinks(): LevelLinkInfo[] | null

The level's links (warp rects) in its current server state, in index order. Null on gmap objects.

ts
addlevellink(data: LevelLinkPatch): number

Appends a link and returns its index, or -1 when the result isn't a valid link (no destlevel, an empty rect, a rect outside the level), on a gmap object or an instance. Live: every player who sees the level gets the new link list immediately — a link that appears under a player only fires once they step out and back in. The destination isn't checked; a link to a missing level does nothing when touched.

ts
player.level?.addlevellink({ x: 30, y: 0, w: 4, h: 1,
    destlevel: 'north.glvl', destx: 0, desty: 62, keepx: true })
ts
setlevellink(index: number, patch: LevelLinkPatch): boolean

Changes fields of the link at index (live, like addlevellink). The whole call fails if a field is wrongly typed or the changed link isn't valid. Returns false for bad indices and on gmap objects.

ts
removelevellink(index: number): boolean

Removes the link at index (live). Every later link's index shifts down by one — re-read getlevellinks() after removing. Returns false for bad indices and on gmap objects.

LevelEditor.savelevel ​

ts
savelevel(): boolean

Writes the in-memory copy — tile, tile type, NPC and link edits, or a level made with createlevel — to the .glvl file; on a gmap object, every member with unsaved edits. Running state isn't touched (reloadlevel() or reloadlevelnpc() applies staged NPC edits). Saved NPC scripts are type-checked in the background; errors go to the server log. True when there was nothing to save; false for a failed write (the edits stay in memory).

LevelEditor.reloadlevel ​

ts
reloadlevel(): boolean

Applies the level's current server state to everything running: its NPCs are recreated from its NPC list (onCreated fires again; putnpc locals survive) and every player who sees it reloads it in place. The way to make all staged NPC edits live at once (reloadlevelnpc() does one NPC). On a gmap object, reloads every member with staged changes.

LevelEditor.resetlevel ​

ts
resetlevel(): boolean

Discards all unsaved edits (tiles, tile types, NPCs, links) and reloads from the .glvl file like reloadlevel(); on a gmap object, every edited member. False for a createlevel level that was never saved — it has no file to return to.

gmaptolevel function ​

ts
declare function gmaptolevel(gmapName: string, gx: number, gy: number): { level: string; x: number; y: number } | null

Converts gmap-global tile coordinates to the member level under them and its member-local coordinates. Null when the gmap doesn't exist or (gx, gy) is outside its grid. On a gmap, player.x/y are already gmap-global, so gmaptolevel(player.level, player.x, player.y) tells you which member level a player is standing in. Direct call: reads live data.

leveltogmap function ​

ts
declare function leveltogmap(levelName: string, x: number, y: number): { gmap: string; x: number; y: number } | null

Converts member-level-local tile coordinates to gmap-global. Null when the level belongs to no gmap. Warps already auto-translate member destinations; use this when you need the numbers yourself. Direct call: reads live data.

ScriptThis interface ​

ts
interface ScriptThis

Every handler in a server script runs with this bound to the script's own object: this.name is the script's name (file name without .ts; a weapon's serverside half gets the bare weapon name, matching its clientside this.name). Scripts may stash extra state on this between calls. Only function declarations see it — arrow functions ignore this.

export is optional: every top-level function is exported by the build (so function onCreated() is a handler), and the script's own functions and joined class exports are callable on this too. Inside a top-level function this is always the script: a bare helper(...) call from a handler falls back to the running script's self instead of JS's undefined.

this types as any in handlers (noImplicitThis is off in tsconfig.json); annotate a handler with this: ScriptThis if you want it typed:

ts
export function onActionServerSide(this: ScriptThis, player: Player) { ... }

ScriptThis.name ​

ts
name: string

The script's name, e.g. "test" for test.ts or weapons/test.ts.

ScriptThis.join ​

ts
join(name: string): boolean

Joins this script to a class (scripts/classes/<name>.ts): the class's exported handlers fire after this script's own, its exported helpers become callable on this, and its onCreated runs now with this script as this. A serverside join also joins the class's clientside half (<name>.client.ts, when one exists) on every client. Re-joining re-checks the class version and re-fires its onCreated. Returns false when the class doesn't exist.

ScriptThis.leave ​

ts
leave(name: string): boolean

Removes a joined class's handlers from this script.

ScriptThis.joinedclasses ​

ts
readonly joinedclasses: readonly string[]

Currently joined class names, in join order.

ScriptThis.[key] ​

ts
[key: string]: any

Scripts may keep arbitrary state on this.

serverOptions global ​

ts
declare const serverOptions: { … }

The server's configuration from serveroptions.json (next to the server binary), available from onInitialized onward. Beyond the typed options below, every extra top-level key an admin adds to the file shows up here verbatim — e.g. a "motd": "..." line is read as serverOptions.motd. The object is deep-frozen; writes are silently ignored.

serverOptions.name ​

ts
readonly name: string

Display name of the server.

serverOptions.startLevel ​

ts
readonly startLevel: string

Level new accounts start in; returning players resume their saved level.

serverOptions.startX ​

ts
readonly startX: number

Start position for new accounts, in tiles.

serverOptions.startY ​

ts
readonly startY: number

Start position for new accounts, in tiles.

serverOptions.maxPlayers ​

ts
readonly maxPlayers: number

Maximum simultaneous logged-in players; 0 or less means unlimited.

serverOptions.[key] ​

ts
readonly [key: string]: any

Admin-defined custom properties.

server global ​

ts
declare const server: Record<string, any>

Server-only global flags, persisted in data/flags.json across restarts. Values can be anything JSON-serializable (strings, numbers, booleans, arrays, plain objects); flag names are 1-128 characters, values up to 8192 characters of JSON. Assigning null or undefined deletes a flag, as does delete server.foo. Reads return a fresh copy per access — mutating a nested value does NOT store it; reassign to write:

ts
const inv = server.inventory ?? []; inv.push('sword');
server.inventory = inv;

Direct calls (not batched): a write is readable back immediately. Never sent to clients — for server-visible state, see serverr.

serverr global ​

ts
declare const serverr: Record<string, any>

Global flags mirrored to EVERY client, persisted in data/flags.json. Same value rules and reassign-to-write caveat as server. Each write (or delete) is broadcast immediately and readable in clientside scripts as serverr.foo (read-only there); clients also get the full set at login.

Player interface ​

ts
interface Player

Snapshot of a player's state at the moment an event fired (backed by ScriptPlayer on the host side). chat is live rather than a snapshot: reads see the player's current chat bubble, and assigning it sets the bubble for everyone in their level (the player's own client included). client and clientr are the player's live flag bags.

Player.id ​

ts
id: number

Server-assigned player id, unique per login.

Player.account ​

ts
account: string

Account name the player logged in with.

Player.nick ​

ts
nick: string

Display name rendered under the player, for everyone in their level. Defaults to the account name; players change it with the setnick chat command. Assigning '' resets it to the account name. Sanitized like chat and trimmed to 40 chars.

Player.nickcolor ​

ts
nickcolor: string

Name tag text color as 'r,g,b' (default '255,255,255'), for everyone in the player's level. Only scripts can change it — there is no chat command — and it's saved in the account file. Invalid values are ignored.

ts
player.nickcolor = '255,215,0'   // gold

Player.nickshadow ​

ts
nickshadow: boolean

Whether the name tag has a 1px drop shadow (default true). Script-only; saved in the account file.

Player.nickshadowcolor ​

ts
nickshadowcolor: string

Name tag shadow color as 'r,g,b' (default '0,0,0'). Script-only; saved in the account file. Invalid values are ignored.

Player.level ​

ts
level: ServerLevel | null

The level (or gmap) the player is in, as a level object — use player.level.name for the file name, player.level.putnpc(...) etc. to act on it. Null until they enter their first level. Inside an instance this is the instanced copy, but name is still the plain file name.

Player.instance ​

ts
readonly instance: Instance | null

The instance the player is in, or null in the shared world. Live (not a snapshot): reflects the instance they're in right now.

Player.x ​

ts
x: number

Position in tiles. Read-only in practice: move players with warpto.

Player.y ​

ts
y: number

Position in tiles. Read-only in practice: move players with warpto.

Player.chat ​

ts
chat: string

Chat bubble above the player's head. Assigning shows it to everyone in their level ('' clears it); it fades 5s after the player moves. Text is trimmed to 200 chars and control characters become spaces.

Player.setAni ​

ts
setAni(name: string, ...params: any[]): void

Plays a .gan animation on the player, visible to everyone in their level. Pass the animation name without the extension, e.g. player.setAni('sword'). Values after the name are the animation's params: PARAM sprites draw the image named at their (0-based) slot, and the gani script reads them as params, e.g. player.setAni('carry', 'pot.png'). At most 16 JSON-serializable values (2048 characters of JSON). Every call replaces the previous params.

Player.ani ​

ts
ani: string

Current animation name (without the .gan extension). Assigning plays it like setAni(name) with no params.

Player.aniParams ​

ts
readonly aniParams: readonly any[]

The current animation's setAni params ([] when none). Read-only, deep-frozen.

Player.head ​

ts
head: string

Head image, e.g. 'head0.png'. '' means the client default.

Player.body ​

ts
body: string

Body image, e.g. 'body.png'. '' means the client default.

Player.colors ​

ts
colors: string[]

Body colors as 'r,g,b' strings, recoloring the body's reserved key colors: [0] skin, [1] coat, [2] sleeves, [3] shoes, [4] belt. Always five entries. Assigning an index (player.colors[1] = '255,0,0') updates everyone in the level and persists; invalid indices or values are ignored. Assigning an array sets each slot it provides.

Player.hasright ​

ts
hasright(mode: 'r' | 'w' | 'rw', path: string): boolean

Whether this player's staff rights grant folder access on a data/-relative path: mode 'r' (read), 'w' (write) or 'rw' (requires both), e.g. player.hasright('w', 'levels/town.glvl'). Staff-list accounts with no rights record have full access; everyone else without a record has none. Serverside only.

Player.hasstaffright ​

ts
hasstaffright(name: string): boolean

Whether this player's staff rights include a named right from the rights catalog — e.g. player.hasstaffright('leveleditor') to gate an online level/NPC editor. Resolved like hasright: staff-list accounts with no rights record hold every right. Serverside only.

Player.warpto ​

ts
warpto(level: string, x: number, y: number, options?: WarpOptions): boolean

Warps this player to a level (or gmap) at tile (x, y) — the same path link touches and RC warps take, so warps to a gmap member land on the gmap with translated coordinates. The client transitions once it has fully downloaded the destination. Serverside only; false when the level doesn't exist.

Instances: with no options (or no instance key) the warp inherits — it stays in the player's current instance when the level is one of its members and lands in the shared world otherwise (exactly like links). { instance: inst } warps into that instance (false when the level isn't one of its members or it was destroyed); { instance: null } always lands in the shared world.

Player.addWeapon ​

ts
addWeapon(name: string): boolean

Grants a weapon (scripts/weapons/<name>) to this player; their client downloads and runs its clientside half immediately. No-op if they already have it. Serverside only; false when no such weapon exists.

Player.removeWeapon ​

ts
removeWeapon(name: string): boolean

Takes a weapon away from this player; their client unloads it immediately. Serverside only; false (and a no-op) when they don't have it.

Player.hasWeapon ​

ts
hasWeapon(name: string): boolean

Whether this player currently has the named weapon. (Clientside scripts have the same check on their local player.)

Player.client ​

ts
client: Record<string, any>

Per-player flags, readable AND writable both here and in the player's clientside scripts (as client.foo there); persisted in the account file. Values must be JSON-serializable; names 1-128 chars, values up to 8192 chars of JSON. Assigning null/undefined (or delete) removes a flag. Server writes sync to the client immediately; reads return a fresh copy per access, so mutate-then-reassign nested values.

Player.clientr ​

ts
clientr: Record<string, any>

Per-player flags only the server can write; the player's clientside scripts see them read-only (as clientr.foo). Persisted in the account file. Same value rules and reassign-to-write caveat as client.

Player.attr ​

ts
attr: Record<string, any>

Player attributes: public per-player values only the server can write. Every client that can see this player — the player's own included — reads them (read-only) as .attr.foo on its player handles (player.attr, players[i].attr, findplayer(acc).attr), e.g. to draw a healthbar. Persisted in the account file. Names 1-128 chars, values up to 8192 chars of JSON, and at most 16384 chars per player in total (names + values). Assigning null/undefined (or delete) removes an attribute; assigning an unchanged value sends nothing. Each change is broadcast immediately, so mutate-then-reassign nested values and avoid writing every tick.

ts
player.attr.health = 100
player.attr.team = 'red'

An ATTR sprite in the player's animation draws the image held by the attribute it names, so player.attr.hat = 'hat1.png' dresses every gani with an ATTR "hat" sprite (non-string values draw nothing).

A value naming a .gan attaches that gani's script to the player on every client that sees them, without changing their animation: a string ending in ".gan", or an array whose first element is one (the rest become the script's params array). Changing the value restarts the script; removing it stops it.

ts
player.attr.light = ['light.gan', 255, 0, 0]   // params = [255, 0, 0]

Event handlers. Scripts subscribe by exporting a function with the matching name; the server invokes it on every script that exports one:

  • export function onCreated(): void
    Fired every time the script loads: at server startup and again on every hot reload (RC script update). Put (re)initialization here — including this.join() calls, which must be re-made after an update.

  • export function onInitialized(): void
    Fired once at server startup, after onCreated. NOT re-fired when the script is updated — use it for boot-only work.

  • export function onPlayerJoined(player: Player): void
    Fired when a player logs in to the server.

  • export function onPlayerLeft(player: Player): void
    Fired when a logged-in player disconnects from the server.

  • export function onActionServerSide(player: Player, ...params: any[]): void
    Fired when a client calls triggerServer targeting this script. player is the triggering player; the client's params follow (JSON round-tripped). triggerClient inside answers that same player.

  • export function onPlayerEntersInstance(player: Player, instance: Instance): void
    Fired when a player enters an instance (arriving from the shared world or from another instance). triggerClient inside answers that player.

  • export function onPlayerLeavesInstance(player: Player, instance: Instance): void
    Fired when a player leaves an instance: a warp/link out, a warp into a different instance, a disconnect, or being evicted by destroy().

  • export function onInstanceDestroyed(instance: Instance): void
    Fired when an instance is destroyed (by script, RC, or destroyWhenEmpty), BEFORE its players are moved out and its NPCs unloaded — the shared state is still readable here, so save results now.

ServerLevel interface ​

ts
interface ServerLevel extends LevelEditor

A reference to a specific level (or gmap) — what player.level and findlevel() return. Includes the LevelEditor methods. Same API shape as an NPC script's this.level, but bound to the named level-or-gmap context: on a gmap, all coordinates are gmap-global tiles. Snapshot semantics: taken when the event fired; a player kept across an await may have moved on.

ServerLevel.name ​

ts
readonly name: string

The level's file name, e.g. "start.glvl" (or "world.gmap").

ServerLevel.players ​

ts
readonly players: Player[]

Snapshots of the players in this level — on a gmap, everyone anywhere on it (gmap-global x/y). Full Player objects, client./clientr. flag bags included. A fresh array on every read.

ServerLevel.findPlayersCircle ​

ts
findPlayersCircle(x: number, y: number, radius: number): Player[]

Players whose 2x2 body center (player.x + 1, player.y + 1) is within radius tiles of (x, y), nearest first. On a gmap the whole gmap is searched and (x, y) are gmap-global. Empty on bad arguments.

ServerLevel.findPlayersRect ​

ts
findPlayersRect(x: number, y: number, w: number, h: number): Player[]

Players whose 2x2 body overlaps the rect [x, x+w) × [y, y+h), tile units (negative w/h extend left/up). On a gmap the whole gmap is searched and coordinates are gmap-global. Empty on bad arguments.

ServerLevel.findPath ​

ts
findPath(x1: number, y1: number, x2: number, y2: number, options?: FindPathOptions): PathPoint[] | null

A* path from (x1, y1) to (x2, y2) around blocking tiles and (by default) blocking NPCs — see FindPathOptions. Coordinates are floored to whole tiles and name the TOP-LEFT of the mover's footprint. Returns the turning points from start to goal (straight runs collapsed), or null when the goal is blocked, unreachable, or the search budget runs out. On a gmap paths cross member seams; coordinates are gmap-global.

ServerLevel.putnpc ​

ts
putnpc(x: number, y: number, serverScript: string, clientScript?: string): NpcThis | null

Spawns a LOCAL NPC at (x, y) in this level. The script arguments are inline TypeScript SOURCE strings (Graal putnpc2-style); the first compile of a novel script briefly blocks the server tick, identical sources are cached. Never saved to the level file: lives until destroy() or server restart, surviving hot reloads (/clearnpcs in RC clears strays). On a gmap, (x, y) are gmap-global and the NPC lands in the member level under them. Returns the NPC's full this-style handle, or null when the level can't be resolved.

ServerLevel.onwall ​

ts
onwall(x: number, y: number, w?: number, h?: number): boolean

True when a blocking collision tile intersects [x, x+w) × [y, y+h), in tile units (fractions allowed). Omit w/h to test the single tile containing (x, y). Tiles outside the level count as blocked, and so do blocking NPCs (see NpcThis.dontblock); players don't.

ServerLevel.tiletype ​

ts
tiletype(x: number, y: number): number

Collision type of the tile containing (x, y); -1 when out of range.

ServerLevel.shoot ​

ts
shoot(x: number, y: number, gan: string, angle: number, speed: number,
          lifetime: number, data?: any): Projectile | null

Spawns a projectile with its CENTER at (x, y) in this level's space — same semantics and arguments as the player-scoped level.shoot. Returns null on bad arguments.

PathPoint interface ​

ts
interface PathPoint

A waypoint returned by findPath: a whole-tile footprint top-left.

PathPoint.x ​

ts
x: number

Tile x (the footprint's left edge).

PathPoint.y ​

ts
y: number

Tile y (the footprint's top edge).

FindPathOptions interface ​

ts
interface FindPathOptions

Options for findPath. Every cell the mover steps into is tested as a width x height rect anchored at the cell's top-left, like onwall. A player walking with the lower-body idiom uses { width: 2, height: 1 } with start/goal at (player.x, player.y + 1).

FindPathOptions.width ​

ts
width?: number

Footprint width in tiles (default 1, max 16).

FindPathOptions.height ​

ts
height?: number

Footprint height in tiles (default 1, max 16).

FindPathOptions.diagonal ​

ts
diagonal?: boolean

Allow 8-directional steps (default true). Diagonals never cut wall corners.

FindPathOptions.npcs ​

ts
npcs?: boolean

Treat blocking NPCs as walls (default true). Inside an NPC script the NPC itself never blocks its own path.

FindPathOptions.players ​

ts
players?: boolean

Treat players' lower bodies (x, y+1, 2, 1) as walls (default false).

FindPathOptions.maxNodes ​

ts
maxNodes?: number

Search budget: cells expanded before giving up and returning null (default 4000, max 20000). The search runs on the server tick, so keep long searches rare.

WarpOptions interface ​

ts
interface WarpOptions

Options for {@link Player.warpto}.

WarpOptions.instance ​

ts
instance?: Instance | null

Instance destination: an Instance warps into it (the level must be a member), null lands in the shared world. Omitted = inherit (stay in the current instance when the level is a member, else shared world).

InstanceOptions interface ​

ts
interface InstanceOptions

Options for {@link instances.create}.

InstanceOptions.name ​

ts
name: string

Type label, 1-64 chars, e.g. 'goblin-cave'. Not unique: many instances can share a name. Shown by the RC /instances command and filterable with instances.list(name).

InstanceOptions.levels ​

ts
levels: string[]

Member levels and gmaps: file names with optional * and ? wildcards, case-insensitive (e.g. ['cave_*.glvl', 'cave.gmap']). A gmap brings all of its member levels with it. Links and inheriting warps to a member stay inside the instance; links to anything else exit it.

InstanceOptions.exit ​

ts
exit?: { level: string, x: number, y: number }

Where players go when the instance is destroyed (or when they log in after it's gone). Omitted = back to where each player entered it from.

InstanceOptions.destroyWhenEmpty ​

ts
destroyWhenEmpty?: number

Auto-destroy after the instance has been empty this many seconds (counted from creation until someone arrives, so leave time to warp players in). Omitted = persist until destroy() is called.

Instance interface ​

ts
interface Instance

A live instance: a private copy of a set of member levels/gmaps with its own NPCs, level state and players. Instances are memory-only — gone on server restart. Every property other than the built-ins below is shared state (like an NPC's this.level, but one bag for the WHOLE instance): inst.kills = 3 is readable as this.instance.kills by every NPC in every member level, and by any script holding the handle. Live JS values, never persisted; cleared when the instance is destroyed.

Instance.[key] ​

ts
[key: string]: any

Shared instance state: any key that isn't a built-in.

Instance.id ​

ts
readonly id: string

Unique id, e.g. 'k3f9a2c1'. Stable for the instance's lifetime.

Instance.name ​

ts
readonly name: string

The type label given to instances.create.

Instance.levels ​

ts
readonly levels: string[]

The member patterns given to instances.create (a fresh copy per read).

Instance.players ​

ts
readonly players: Player[]

Players in the instance (including any mid-warp into it).

Instance.alive ​

ts
readonly alive: boolean

False once destroy() has started; the handle is inert afterwards.

Instance.destroy ​

ts
destroy(): boolean

Destroys the instance: fires onInstanceDestroyed, warps everyone in it to their exit, unloads its NPCs (timers stop) and projectiles, and clears its state. Returns false when it was already destroyed.

instances global ​

ts
declare const instances: { … }

Creates and finds instances — private, replayable copies of levels and gmaps (quests, dungeons, arenas). Serverside only.

ts
const inst = instances.create({ name: 'goblin-cave', levels: ['cave\_\*.glvl'], destroyWhenEmpty: 60 })
player.warpto('cave\_1.glvl', 30, 30, { instance: inst })

instances.create ​

ts
create(options: InstanceOptions): Instance

Creates an instance (persisting until destroy() unless destroyWhenEmpty is set). Throws on an empty name, no member levels, or a non-positive destroyWhenEmpty.

instances.get ​

ts
get(id: string): Instance | null

A live instance by id, or null.

instances.list ​

ts
list(name?: string): Instance[]

Live instances, oldest first — only those with this name when given.

Projectile interface ​

ts
interface Projectile

A live projectile spawned by level.shoot.

Projectile.id ​

ts
readonly id: number

Unique id for this server run.

Projectile.destroy ​

ts
destroy(): boolean

Removes the projectile mid-flight, silently: no onShotAt/onShot fires anywhere. Safe to call after it already stopped (returns false then).

level global ​

ts
declare const level: LevelEditor & {
    /** The current player's level (or gmap) name; '' outside a player-scoped handler. */
    readonly name: string

    /**
     * Players in the current player's level (on a gmap, anywhere on it, with
     * gmap-global x/y), as full Player objects with client./clientr. bags.
     * Empty outside a player-scoped handler.
     */
    readonly players: Player[]

    /**
     * Players whose 2x2 body center is within `radius` tiles of (x, y) in the
     * current player's coordinate space, nearest first — see
     * ServerLevel.findPlayersCircle. Empty outside a player-scoped handler.
     */
    findPlayersCircle(x: number, y: number, radius: number): Player[]

    /**
     * Players whose 2x2 body overlaps [x, x+w) × [y, y+h) in the current
     * player's coordinate space — see ServerLevel.findPlayersRect. Empty
     * outside a player-scoped handler.
     */
    findPlayersRect(x: number, y: number, w: number, h: number): Player[]

    /**
     * A* path in the current player's level (gmap-global on gmaps) — see
     * ServerLevel.findPath. Null outside a player-scoped handler.
     */
    findPath(x1: number, y1: number, x2: number, y2: number, options?: FindPathOptions): PathPoint[] | null

    /**
     * Spawns a projectile with its CENTER at (x, y), in the current player's
     * coordinate space: level tiles, or gmap-global tiles when they are on a
     * gmap (where it crosses member seams). `gan` is the animation it renders
     * (e.g. 'arrow'; the flight angle picks the gani direction). `angle` is
     * radians, Graal-style: 0=right, PI/2=up, PI=left, 3*PI/2=down. `speed`
     * is tiles/sec (max 100), `lifetime` seconds (max 60). `data` is any
     * JSON-serializable payload, delivered to every callback.
     *
     * The projectile stops on the first blocking tile (onShotAt on clientside
     * scripts and the level's serverside NPCs), on lifetime expiry (same), on
     * an NPC shape (onShot(data) on that NPC, server + client) or on a player
     * (onShot(data) on the HIT player's clientside weapon scripts). Returns
     * null outside a player-scoped handler or on bad arguments.
     */
    shoot(x: number, y: number, gan: string, angle: number, speed: number,
          lifetime: number, data?: any): Projectile | null

    /**
     * Spawns a LOCAL NPC at (x, y) in the current player's coordinate space:
     * level tiles, or gmap-global tiles when they are on a gmap (the NPC
     * lands in the member level under the point; off-grid returns null). The
     * script arguments are inline TypeScript SOURCE strings (Graal
     * putnpc2-style), compiled like level NPC scripts — the first compile of
     * a novel script briefly blocks the server tick; identical sources are
     * cached.
     *
     * The NPC is never saved to the level file: it lives until destroy() or
     * server restart, surviving level hot reloads (/clearnpcs <level> in RC
     * clears strays). Returns the NPC's full `this`-style handle (see
     * NpcThis) or null — like shoot, also null outside a player-scoped
     * handler.
     */
    putnpc(x: number, y: number, serverScript: string, clientScript?: string): NpcThis | null
}

The CURRENT player's level. Like triggerClient, "current player" only exists synchronously inside a player-scoped handler (onActionServerSide, onPlayerJoined, ...) — after an await or inside timer callbacks there is none, and level.name is '' / level.shoot returns null.

NPC scripts: use this.level instead — it is the NPC's own level and also accepts member-local coordinates; this global is player-scoped. A bare level inside an NPC script is THIS global, not this.level.

SqlRow type ​

ts
type SqlRow = Record<string, number | string | null | { $blob: string }>

A row returned by Database.query: column name -> value. SQLite INTEGERs arrive as JS numbers (values beyond 2^53 lose precision), REALs as numbers, TEXT as strings, NULL as null, and BLOBs wrapped as { $blob: base64 }. Duplicate column names collide in the object form — use AS aliases.

SqlParam type ​

ts
type SqlParam = number | string | boolean | null

A value bindable to a ? placeholder. Booleans store as SQLite's 1/0.

Database interface ​

ts
interface Database

A server-side SQLite database handle from opendatabase(). The database file is created lazily on the first query/exec. All SQL runs serialized on one server-wide worker thread; each statement is atomic (no cross-statement transaction API). Multi-statement SQL is allowed — all statements execute and the last result set with columns is returned.

Database.name ​

ts
readonly name: string

The database name this handle was opened with.

Database.query ​

ts
query(sql: string, params?: SqlParam[]): Promise<SqlRow[]>

Runs SQL and resolves with its rows. Parameters bind to bare ? placeholders in order.

Database.exec ​

ts
exec(sql: string, params?: SqlParam[]): Promise<{ rowsAffected: number; lastInsertRowId: number }>

Runs SQL and resolves with change counts: rowsAffected (rows inserted/updated/deleted) and lastInsertRowId (this connection's most recent INSERT rowid).

opendatabase function ​

ts
declare function opendatabase(name: string): Database

Opens a named server-side SQLite database (data/databases/<name>.db), creating it on first use. Names: 1-64 chars of letters, digits, _ and -; an invalid name throws synchronously. Pending queries of an unloaded script park unresolved across a hot reload, like cancelled sleeps.

Headers class ​

ts
declare class Headers implements Iterable<[string, string]>

A case-insensitive HTTP header list, as in the web Fetch API. Names are stored lower-cased; iteration yields [name, value] pairs sorted by name, and a repeated name's values are joined with ", ".

Headers.constructor ​

ts
constructor(init?: HeadersInit)

Builds a header list from a name→value object, [name, value] pairs, or another Headers.

Headers.append ​

ts
append(name: string, value: string): void

Adds a value, joining it onto any existing value for that name with ", ".

Headers.set ​

ts
set(name: string, value: string): void

Replaces every value for that name.

Headers.get ​

ts
get(name: string): string | null

The (joined) value for that name, or null when absent.

Headers.has ​

ts
has(name: string): boolean

Whether the header is present.

Headers.delete ​

ts
delete(name: string): void

Removes the header.

Headers.forEach ​

ts
forEach(cb: (value: string, name: string, headers: Headers) => void, thisArg?: unknown): void

Calls cb(value, name, headers) for every header, sorted by name.

Headers.entries ​

ts
entries(): IterableIterator<[string, string]>

[name, value] pairs sorted by name.

Headers.keys ​

ts
keys(): IterableIterator<string>

Header names (lower-cased), sorted.

Headers.values ​

ts
values(): IterableIterator<string>

Header values, in name order.

Headers.[Symbol.iterator] ​

ts
[Symbol.iterator](): IterableIterator<[string, string]>

Same as entries().

HeadersInit type ​

ts
type HeadersInit = Headers | Record<string, string> | [string, string][]

Anything fetch() and new Headers() accept as headers.

FetchInit interface ​

ts
interface FetchInit

Options for fetch(). A subset of the web RequestInit plus a timeout.

FetchInit.method ​

ts
method?: string

HTTP method: GET (default), POST, PUT, PATCH, DELETE, HEAD or OPTIONS. Case-insensitive.

FetchInit.headers ​

ts
headers?: HeadersInit

Request headers. A body without a Content-Type is sent as text/plain;charset=UTF-8.

FetchInit.body ​

ts
body?: string | null

Request body, sent as UTF-8 (max 4 MB). Strings only — use JSON.stringify(...) for JSON (and set Content-Type: application/json). GET and HEAD requests cannot have a body.

FetchInit.timeout ​

ts
timeout?: number

Non-standard: give up after this many milliseconds. Default 15000, max 60000.

Response interface ​

ts
interface Response

The response to a fetch(). The body is fully buffered before the promise resolves.

Response.status ​

ts
readonly status: number

HTTP status code.

Response.statusText ​

ts
readonly statusText: string

HTTP reason phrase, e.g. "OK" or "Not Found".

Response.ok ​

ts
readonly ok: boolean

True for a 2xx status. fetch() still resolves for 4xx/5xx — check this.

Response.url ​

ts
readonly url: string

The final URL, after any redirects.

Response.redirected ​

ts
readonly redirected: boolean

Whether redirects were followed to reach url.

Response.headers ​

ts
readonly headers: Headers

Response headers.

Response.bodyUsed ​

ts
readonly bodyUsed: boolean

Whether text()/json()/arrayBuffer() has been called; the body can only be read once.

Response.text ​

ts
text(): Promise<string>

The body as text (decoded with the response charset, UTF-8 by default).

Response.json ​

ts
json(): Promise<any>

The body parsed as JSON; rejects on invalid JSON.

Response.arrayBuffer ​

ts
arrayBuffer(): Promise<ArrayBuffer>

The raw body bytes.

fetch function ​

ts
declare function fetch(input: string | { url: string }, init?: FetchInit): Promise<Response>

Makes an outbound HTTP(S) request, like the web Fetch API. The request runs off the server tick, so awaiting it never stalls the game; the promise settles on a later tick. It resolves for any HTTP status (check res.ok) and rejects with a TypeError on network errors, timeouts, an invalid URL/method, or a blocked address.

Limits: http/https only; 15 s default timeout (init.timeout, max 60 s); 4 MB request and response bodies; at most 5 redirects; 16 requests in flight server-wide (more queue, beyond 256 they reject). Loopback, private, link-local and other reserved addresses are refused unless serveroptions.json sets fetchAllowPrivate. No streaming and no AbortSignal. Pending fetches of an unloaded script park unresolved across a hot reload, like cancelled sleeps.

WebSocketOptions interface ​

ts
interface WebSocketOptions

Non-standard extra options for new WebSocket().

WebSocketOptions.headers ​

ts
headers?: HeadersInit

Extra HTTP headers for the opening handshake, for services that authenticate it (browsers can't send these; Discord's gateway doesn't need any). Handshake-reserved headers (Upgrade, Sec-WebSocket-*) throw.

WebSocketEvent interface ​

ts
interface WebSocketEvent

The event passed to WebSocket open and error handlers.

WebSocketEvent.type ​

ts
readonly type: string

"open" or "error".

WebSocketEvent.target ​

ts
readonly target: WebSocket

The socket the event is for.

WebSocketEvent.message ​

ts
readonly message?: string

Non-standard, error events only: why the connection failed.

WebSocketMessageEvent interface ​

ts
interface WebSocketMessageEvent

The event passed to WebSocket message handlers.

WebSocketMessageEvent.type ​

ts
readonly type: 'message'

Always "message".

WebSocketMessageEvent.target ​

ts
readonly target: WebSocket

The socket the message arrived on.

WebSocketMessageEvent.data ​

ts
readonly data: string | ArrayBuffer

A text frame's string, or a binary frame's bytes.

WebSocketCloseEvent interface ​

ts
interface WebSocketCloseEvent

The event passed to WebSocket close handlers. Always the socket's last event.

WebSocketCloseEvent.type ​

ts
readonly type: 'close'

Always "close".

WebSocketCloseEvent.target ​

ts
readonly target: WebSocket

The socket that closed.

WebSocketCloseEvent.code ​

ts
readonly code: number

The close code: the peer's code on a clean close, 1005 if it sent none, 1006 when the connection failed or dropped, 1009 when an incoming message exceeded 16 MB.

WebSocketCloseEvent.reason ​

ts
readonly reason: string

The peer's close reason ("" if none).

WebSocketCloseEvent.wasClean ​

ts
readonly wasClean: boolean

Whether the closing handshake completed.

WebSocket class ​

ts
declare class WebSocket

An outbound WebSocket connection, like the browser WebSocket class. Connecting, sending and receiving run off the server tick; handlers fire on a later tick in the context of the script that created the socket. Every socket ends with exactly one close event (preceded by an error event when the connection failed).

The socket belongs to the script that constructed it: unloading or hot-reloading that script aborts it silently (no close event), so (re)connect from onCreated. Limits: ws/wss only; 32 open sockets server-wide; 16 MB per incoming message and 16 MB of unsent data (beyond it the socket fails). The same private-address policy as fetch applies (fetchAllowPrivate). No permessage-deflate compression.

WebSocket.CONNECTING ​

ts
static readonly CONNECTING: 0

readyState: connecting.

WebSocket.OPEN ​

ts
static readonly OPEN: 1

readyState: open — send() works.

WebSocket.CLOSING ​

ts
static readonly CLOSING: 2

readyState: close() called, waiting for the closing handshake.

WebSocket.CLOSED ​

ts
static readonly CLOSED: 3

readyState: closed; the socket is finished.

WebSocket.constructor ​

ts
constructor(url: string, protocols?: string | string[], options?: WebSocketOptions)

Starts connecting to a ws:// or wss:// URL. Throws a SyntaxError for an invalid URL, subprotocol or header, or when 32 sockets are already open. @param protocols subprotocols to offer; the server's pick lands in protocol.

WebSocket.url ​

ts
readonly url: string

The URL passed to the constructor.

WebSocket.readyState ​

ts
readonly readyState: number

0 connecting, 1 open, 2 closing, 3 closed — compare with WebSocket.OPEN etc.

WebSocket.protocol ​

ts
readonly protocol: string

The subprotocol the server selected ("" if none), set once open.

WebSocket.extensions ​

ts
readonly extensions: string

Always "" (no extensions are negotiated).

WebSocket.bufferedAmount ​

ts
readonly bufferedAmount: number

Bytes queued by send() that haven't reached the network yet.

WebSocket.binaryType ​

ts
binaryType: 'arraybuffer'

Binary messages always arrive as ArrayBuffer; assigning anything else throws.

WebSocket.onopen ​

ts
onopen: ((event: WebSocketEvent) => void) | null

Fires once the connection is established.

WebSocket.onmessage ​

ts
onmessage: ((event: WebSocketMessageEvent) => void) | null

Fires for each complete incoming message.

WebSocket.onerror ​

ts
onerror: ((event: WebSocketEvent) => void) | null

Fires when the connection fails (just before close); event.message says why.

WebSocket.onclose ​

ts
onclose: ((event: WebSocketCloseEvent) => void) | null

Fires once when the socket is finished, cleanly or not.

WebSocket.send ​

ts
send(data: string | ArrayBuffer | ArrayBufferView): void

Queues a message: a string is sent as a text frame, an ArrayBuffer or typed array as a binary frame. Throws an InvalidStateError while still connecting; ignored once closing or closed.

WebSocket.close ​

ts
close(code?: number, reason?: string): void

Starts the closing handshake after already-queued messages. code must be 1000 (default) or 3000-4999 and reason at most 123 UTF-8 bytes, else it throws. A server that doesn't answer within 5 s gets dropped (unclean close).

WebSocket.addEventListener ​

ts
addEventListener(type: 'open' | 'error', listener: (event: WebSocketEvent) => void, options?: { once?: boolean }): void
addEventListener(type: 'message', listener: (event: WebSocketMessageEvent) => void, options?: { once?: boolean }): void
addEventListener(type: 'close', listener: (event: WebSocketCloseEvent) => void, options?: { once?: boolean }): void

Adds a listener; once removes it after the first call.

WebSocket.removeEventListener ​

ts
removeEventListener(type: 'open' | 'message' | 'error' | 'close', listener: (event: any) => void): void

Removes a listener added with addEventListener.

FileErrorCode type ​

ts
type FileErrorCode = 'ENOENT' | 'EEXIST' | 'EACCES' | 'EISDIR' | 'ENOTDIR' | 'ENOTEMPTY' | 'EINVAL' | 'EFBIG' | 'EIO'

Why a files call failed, Node-style: ENOENT (no such file/folder), EEXIST (target exists and overwrite wasn't set), EACCES (protected or read-only path), EISDIR / ENOTDIR (folder where a file was expected, or the reverse), ENOTEMPTY (folder delete without recursive), EINVAL (bad path, bad argument or invalid JSON), EFBIG (over the 16 MB file or 10,000-entry listing limit), EIO (any other disk error).

FileError interface ​

ts
interface FileError extends Error

The Error a rejected files call rejects with: a message plus its code.

FileError.code ​

ts
code: FileErrorCode

What went wrong — branch on this, not the message.

FileStat interface ​

ts
interface FileStat

One file or folder, from files.stat() or files.list().

FileStat.name ​

ts
name: string

The bare name, e.g. 'shop.json'.

FileStat.path ​

ts
path: string

The data/-relative path with forward slashes, e.g. 'config/shop.json'.

FileStat.isDirectory ​

ts
isDirectory: boolean

True for folders.

FileStat.size ​

ts
size: number

Size in bytes (0 for folders).

FileStat.modified ​

ts
modified: number

Last modification time, in milliseconds since the Unix epoch.

files global ​

ts
declare const files: { … }

Reads and writes files in the server's data folder — the same tree the GRC File Browser shows. Paths are relative to it with forward slashes ('config/shop.json'); '..' can't climb out, and symbolic links are refused. Engine-owned folders are protected: accounts/, databases/ and the compile caches can't be touched at all (they're also hidden from list()), while scripts/, flags.json and collections.json are read-only.

Every call is async and runs on one server-wide background worker, so a script's operations complete in the order it issued them and never stall the game loop. Failures reject with a {@link FileError}. Single reads and writes are capped at 16 MB. Writing a level file hot-reloads it for players inside, exactly like saving it from GRC. Pending calls of an unloaded script park unresolved across a hot reload, like cancelled sleeps.

files.readText ​

ts
readText(path: string): Promise<string>

Reads a UTF-8 text file (a leading byte-order mark is dropped).

files.writeText ​

ts
writeText(path: string, text: string): Promise<void>

Writes a UTF-8 text file, replacing it if present and creating missing parent folders. The replace is atomic: readers see the old or the new contents, never half a file.

files.appendText ​

ts
appendText(path: string, text: string): Promise<void>

Appends text to a file, creating it (and its parent folders) if missing — handy for logs.

files.readJson ​

ts
readJson<T = any>(path: string): Promise<T>

Reads and parses a JSON file. Invalid JSON rejects with code EINVAL.

files.writeJson ​

ts
writeJson(path: string, value: any, indent?: number): Promise<void>

Writes a value as JSON (pretty-printed with indent spaces, default 2; pass 0 for compact), atomically like writeText.

files.readBytes ​

ts
readBytes(path: string): Promise<Uint8Array>

Reads a file's raw bytes.

files.writeBytes ​

ts
writeBytes(path: string, data: Uint8Array | ArrayBuffer): Promise<void>

Writes raw bytes, atomically like writeText.

files.exists ​

ts
exists(path: string): Promise<boolean>

Whether a file or folder exists. Protected paths still reject with EACCES.

files.stat ​

ts
stat(path: string): Promise<FileStat>

Details of one file or folder; rejects with ENOENT when missing.

files.list ​

ts
list(path?: string, options?: { recursive?: boolean }): Promise<FileStat[]>

A folder's entries sorted by path — the data folder itself when path is omitted. With recursive, every file and folder beneath it. Protected folders and symbolic links are left out.

files.mkdir ​

ts
mkdir(path: string): Promise<void>

Creates a folder and any missing parents. Already existing is fine.

files.delete ​

ts
delete(path: string, options?: { recursive?: boolean }): Promise<void>

Deletes a file or folder. A folder that isn't empty needs { recursive: true }, which deletes everything inside it.

files.rename ​

ts
rename(from: string, to: string, options?: { overwrite?: boolean }): Promise<void>

Moves or renames a file or folder, creating the target's parent folders. An existing target file rejects with EEXIST unless { overwrite: true }; an existing target folder always does.

files.copy ​

ts
copy(from: string, to: string, options?: { overwrite?: boolean }): Promise<void>

Copies a file (folders aren't supported). An existing target rejects with EEXIST unless { overwrite: true }.

CollectionQueryRow interface ​

ts
interface CollectionQueryRow

A record's replicated query() result row.

CollectionQueryRow.key ​

ts
key: string

CollectionQueryRow.record ​

ts
record: any

CollectionBag interface ​

ts
interface CollectionBag

One scope's records of a collection: key → JSON value. Reads and writes are synchronous against server memory; changes are delta-synced to the audience once per tick and persisted in the background. Record keys are 1-128 chars, record values up to 64 KB of JSON. Collections flagged read-only in RC's Collections tool reject set/patch/delete with a throw — their records are edited in RC (item catalogs); reads and query() still work. A collection may also carry a record SCHEMA (defined in RC): writes must then be objects with every required field present, matching types, and no fields outside the schema — violations throw with a precise message (patch is judged by the record it produces, not the fields passed).

CollectionBag.get ​

ts
get(key: string): any

The record's parsed value, or undefined. Returns a fresh copy — reassign via set/patch to write.

CollectionBag.keys ​

ts
keys(): string[]

All record keys, sorted.

CollectionBag.set ​

ts
set(key: string, value: any): void

Stores a record (whole-value replacement).

CollectionBag.patch ​

ts
patch(key: string, fields: Record<string, any>): void

Shallow-merges fields into the record — a targeted server-side op with no read-modify-write race. Patching a missing (or non-object) record replaces it wholesale.

CollectionBag.delete ​

ts
delete(key: string): void

Removes a record. Removing a missing key is a no-op.

CollectionBag.query ​

ts
query(opts?: { where?: string; params?: SqlParam[]; limit?: number; offset?: number }):
        Promise<CollectionQueryRow[]>

Paged SELECT against the collection's table (sql backing only). where addresses record fields by (dotted) name — 'itemId = ?' or 'ench.level > ?' — with params bound to ? in order. Default limit 100, max 1000. Pending writes flush first, so the query sees them.

Collection interface ​

ts
interface Collection extends CollectionBag

A collection handle. Global collections expose the record methods directly; account/level/group collections require .for(target) to pick the scope. The handle is stateless and resolves at use time.

Collection.name ​

ts
readonly name: string

Collection.for ​

ts
for(target: Player | string): CollectionBag

One scope's record set. The target depends on the collection's scope axis: a Player or bare account name (account — works for offline accounts), a member-level name (level), or a group id string (group).

Collection.subscribe ​

ts
subscribe(player: Player, scope?: string): void

Delivers a replica to an online player: for LAZY owner/all collections ("nothing ships until a script subscribes"), and for GROUP collections of either timing — there, subscription IS membership, so this is how a player joins a guild/party/trade audience. scope is required for group collections and must be omitted otherwise. Idempotent. The delivery is a snapshot, or a cheap catch-up when the client still has a cached copy. Throws for eager owner/all (delivered at login), level replicas (managed by level presence), audience 'none', and replicate 'cache' (clients pull records per-key with the clientside fetch()).

Collection.unsubscribe ​

ts
unsubscribe(player: Player, scope?: string): void

Revokes a subscribed replica: the client's mirror empties (its cached copy is kept for a later catch-up). No-op when not subscribed.

collection function ​

ts
declare function collection(name: string): Collection

A stateless handle on a collection: a server-authoritative, delta-synced, keyed record store. Collections are DEFINED BY STAFF in RC's Collections tool (persisted in data/collections.json, loaded at boot) — scripts can read and write records but deliberately cannot create collections or change their scope/audience/backing. Using an undefined collection throws at the call site, not here.

WeaponHandle interface ​

ts
interface WeaponHandle

A handle on another loaded weapon script, from findweapon().

WeaponHandle.name ​

ts
readonly name: string

The weapon's bare name, e.g. "gun".

WeaponHandle.trigger ​

ts
trigger(event: string, ...params: any[]): boolean

Invokes the named exported handler on that script RIGHT NOW (its own export, then any joined classes), with this bound to that script and the params passed as live values — a Player object arrives intact, no JSON round trip. The triggerClient player context is inherited. Returns false when the script has since unloaded or its handler threw (the error is logged); true otherwise, including when it exports no such handler.

findweapon function ​

ts
declare function findweapon(name: string): WeaponHandle | null

Finds the LOADED serverside half of a weapon (scripts/weapons/<name>.ts) so one script can call into another — the item system uses it to deliver onEquipped / onUnequipped / onItemUsed to an item's weapon script:

ts
findweapon('gun')?.trigger('onEquipped', player, entry)

null when no such weapon script is loaded. Names never contain '/'.

findWeapon function ​

ts
declare function findWeapon(name: string): WeaponHandle | null

Alias of findweapon.

GRC plugins (rcplugins) ​

RcWidgetBase interface ​

ts
interface RcWidgetBase

Props every plugin widget accepts.

RcWidgetBase.id ​

ts
id?: string

Names the widget so the script can patch it (win.patch), read its value (win.values) and receive its events (win.on). Unique within a window.

RcWidgetBase.disabled ​

ts
disabled?: boolean

Greys the widget out; buttons and inputs stop accepting input.

RcWidgetBase.hidden ​

ts
hidden?: boolean

Leaves the widget out of the layout entirely.

RcWidgetBase.flex ​

ts
flex?: number

Flex grow factor inside a row/column (e.g. 1 to take the free space).

RcWidgetBase.width ​

ts
width?: number | string

Fixed width: pixels, or a CSS length like '40%'.

RcWidgetBase.height ​

ts
height?: number | string

Fixed height: pixels, or a CSS length.

RcWidgetBase.tooltip ​

ts
tooltip?: string

Text shown when hovering the widget.

RcWidgetBase.title ​

ts
title?: string

A tab's label when this widget is a direct child of a tabs widget.

RcStackWidget interface ​

ts
interface RcStackWidget extends RcWidgetBase

Lays its children out vertically ('column') or horizontally ('row', wraps when narrow).

RcStackWidget.type ​

ts
type: 'column' | 'row'

RcStackWidget.children ​

ts
children?: RcWidget[]

RcStackWidget.gap ​

ts
gap?: number

Space between children in pixels (default 8).

RcStackWidget.padding ​

ts
padding?: number

Inner padding in pixels.

RcStackWidget.align ​

ts
align?: 'start' | 'center' | 'end' | 'stretch'

Cross-axis alignment of the children.

RcStackWidget.scroll ​

ts
scroll?: boolean

Scrolls when the children don't fit.

RcSplitWidget interface ​

ts
interface RcSplitWidget extends RcWidgetBase

Two panes with a draggable divider between them. Only the first two children are shown.

RcSplitWidget.type ​

ts
type: 'split'

RcSplitWidget.children ​

ts
children?: RcWidget[]

RcSplitWidget.direction ​

ts
direction?: 'horizontal' | 'vertical'

'horizontal' (default) puts the panes side by side; 'vertical' stacks them.

RcSplitWidget.size ​

ts
size?: number | string

The first pane's starting size: pixels, or a CSS length (default '40%').

RcTabsWidget interface ​

ts
interface RcTabsWidget extends RcWidgetBase

A tab strip: each child is one tab, labelled by its title. Fires 'tab' when the staff member switches.

RcTabsWidget.type ​

ts
type: 'tabs'

RcTabsWidget.children ​

ts
children?: RcWidget[]

RcTabsWidget.selected ​

ts
selected?: number

The tab to show (0-based). Patch it to switch tabs from the script.

RcGroupWidget interface ​

ts
interface RcGroupWidget extends RcWidgetBase

A titled box around its children (stacked vertically).

RcGroupWidget.type ​

ts
type: 'group'

RcGroupWidget.title ​

ts
title?: string

RcGroupWidget.children ​

ts
children?: RcWidget[]

RcHeadingWidget interface ​

ts
interface RcHeadingWidget extends RcWidgetBase

A heading line.

RcHeadingWidget.type ​

ts
type: 'heading'

RcHeadingWidget.text ​

ts
text: string

RcHeadingWidget.level ​

ts
level?: 1 | 2 | 3

1 (largest) to 3; default 2.

RcTextWidget interface ​

ts
interface RcTextWidget extends RcWidgetBase

Plain text. Newlines are kept; staff can select and copy it.

RcTextWidget.type ​

ts
type: 'text'

RcTextWidget.text ​

ts
text: string

RcTextWidget.muted ​

ts
muted?: boolean

Dimmed, for hints and secondary information.

RcTextWidget.monospace ​

ts
monospace?: boolean

Monospaced, for ids, paths and code.

RcSeparatorWidget interface ​

ts
interface RcSeparatorWidget extends RcWidgetBase

A horizontal rule.

RcSeparatorWidget.type ​

ts
type: 'separator'

RcButtonWidget interface ​

ts
interface RcButtonWidget extends RcWidgetBase

A button. Fires 'click' (it needs an id to be clickable).

RcButtonWidget.type ​

ts
type: 'button'

RcButtonWidget.text ​

ts
text: string

RcButtonWidget.variant ​

ts
variant?: 'default' | 'primary' | 'danger'

'primary' for the main action, 'danger' for destructive ones.

RcInputWidget interface ​

ts
interface RcInputWidget extends RcWidgetBase

A single-line input. Its value is a string, or a number (null when empty) for inputType 'number'. Fires 'change'; Enter inside a form fires the form's 'submit'.

RcInputWidget.type ​

ts
type: 'input'

RcInputWidget.inputType ​

ts
inputType?: 'text' | 'number' | 'password'

'text' (default), 'number' or 'password'.

RcInputWidget.label ​

ts
label?: string

Label shown above the input.

RcInputWidget.value ​

ts
value?: string | number | null

Label shown above the input.

RcInputWidget.placeholder ​

ts
placeholder?: string

Label shown above the input.

RcInputWidget.readonly ​

ts
readonly?: boolean

Shows the value but blocks editing.

RcInputWidget.min ​

ts
min?: number

Bounds and step for inputType 'number'.

RcInputWidget.max ​

ts
max?: number

Upper bound for inputType 'number'.

RcInputWidget.step ​

ts
step?: number

Step for inputType 'number'.

RcTextAreaWidget interface ​

ts
interface RcTextAreaWidget extends RcWidgetBase

A multi-line text input (string value). Fires 'change'.

RcTextAreaWidget.type ​

ts
type: 'textarea'

RcTextAreaWidget.label ​

ts
label?: string

RcTextAreaWidget.value ​

ts
value?: string

RcTextAreaWidget.placeholder ​

ts
placeholder?: string

RcTextAreaWidget.rows ​

ts
rows?: number

Visible lines (default 4).

RcTextAreaWidget.readonly ​

ts
readonly?: boolean

Visible lines (default 4).

RcCheckboxWidget interface ​

ts
interface RcCheckboxWidget extends RcWidgetBase

A checkbox (boolean value). Fires 'change'.

RcCheckboxWidget.type ​

ts
type: 'checkbox'

RcCheckboxWidget.label ​

ts
label?: string

RcCheckboxWidget.value ​

ts
value?: boolean

RcCheckboxWidget.readonly ​

ts
readonly?: boolean

RcSelectOption type ​

ts
type RcSelectOption = string | { value: string; label?: string }

One select choice: a plain string, or a value with a different display label.

RcSelectWidget interface ​

ts
interface RcSelectWidget extends RcWidgetBase

A dropdown (string value: the chosen option's value; defaults to the first option). Fires 'change'.

RcSelectWidget.type ​

ts
type: 'select'

RcSelectWidget.label ​

ts
label?: string

RcSelectWidget.options ​

ts
options: RcSelectOption[]

RcSelectWidget.value ​

ts
value?: string

RcSelectWidget.readonly ​

ts
readonly?: boolean

RcCodeWidget interface ​

ts
interface RcCodeWidget extends RcWidgetBase

A code editor (GRC's Monaco editor, string value). Fires 'change'.

RcCodeWidget.type ​

ts
type: 'code'

RcCodeWidget.label ​

ts
label?: string

RcCodeWidget.value ​

ts
value?: string

RcCodeWidget.language ​

ts
language?: string

Monaco language id: 'json', 'typescript', 'sql', 'plaintext' (default)...

RcCodeWidget.readonly ​

ts
readonly?: boolean

Monaco language id: 'json', 'typescript', 'sql', 'plaintext' (default)...

RcImageSource type ​

ts
type RcImageSource = string | { src: string; rect?: string | [number, number, number, number] }

An image to show: an asset name resolved like a game client's request ('items.png', 'icons/sword.png'), or a data:image/... URL. The object form crops it to rect — 'left,top,width,height' or [left, top, width, height] in source pixels — e.g. one icon from a sheet, like an item's imagerect.

RcImageWidget interface ​

ts
interface RcImageWidget extends RcWidgetBase

An image, or a rect of one. Plugin windows can show any image the game serves to players, whatever the staff member's folder rights; names the server doesn't host fall back to the Login Server's default assets. Up to about 960 KB per image. With an id, clicking it fires 'click' with the point in source pixels ({@link RcPluginImageClickEvent}) — handy for picking an icon from a sheet.

RcImageWidget.type ​

ts
type: 'image'

RcImageWidget.src ​

ts
src: string

Asset name or data:image URL.

RcImageWidget.rect ​

ts
rect?: string | [number, number, number, number]

Crop: 'left,top,width,height' or [left, top, width, height] in source pixels.

RcImageWidget.scale ​

ts
scale?: number

Zoom when width/height aren't given (default 1). With width and/or height (pixels), the image is fitted inside them, keeping its aspect.

RcImageWidget.smooth ​

ts
smooth?: boolean

Smooth scaling. Default off: pixel art stays crisp when zoomed.

RcTableColumn type ​

ts
type RcTableColumn = string | { key: string; title?: string; width?: number | string; image?: boolean | number }

A table column: a row key, with an optional header and width. A bare string is the key and header. With image, the cells hold {@link RcImageSource}s drawn as thumbnails (true = 24 px tall, or a height).

RcTableWidget interface ​

ts
interface RcTableWidget extends RcWidgetBase

A table of rows (plain objects). Clicking a row selects it and fires 'select'; double-clicking fires 'activate' — both with the row and its index.

RcTableWidget.type ​

ts
type: 'table'

RcTableWidget.columns ​

ts
columns?: RcTableColumn[]

Which row keys to show, in order. Omitted: every key of the first row.

RcTableWidget.rows ​

ts
rows: Record<string, any>[]

Which row keys to show, in order. Omitted: every key of the first row.

RcTableWidget.selectable ​

ts
selectable?: boolean

Rows can be selected (default true).

RcTableWidget.selected ​

ts
selected?: number

The highlighted row index (-1 for none). Patch it to select from the script.

RcTableWidget.empty ​

ts
empty?: string

Text shown when there are no rows.

RcListItem type ​

ts
type RcListItem = string | { value?: string; label: string; detail?: string; icon?: RcImageSource }

One list entry: a plain string, or a label with an optional value, right-aligned detail and icon.

RcListWidget interface ​

ts
interface RcListWidget extends RcWidgetBase

A clickable list. Fires 'select' and 'activate' (double-click) with the item and its index.

RcListWidget.type ​

ts
type: 'list'

RcListWidget.items ​

ts
items: RcListItem[]

RcListWidget.selected ​

ts
selected?: number

The highlighted item index (-1 for none).

RcListWidget.empty ​

ts
empty?: string

Text shown when the list is empty.

RcListWidget.iconSize ​

ts
iconSize?: number

Height of item icons in pixels (default 20).

RcFormField interface ​

ts
interface RcFormField

One field of a form widget. Fields are inputs in their own right: their id keys their value in win.values(), and they fire 'change' like the standalone inputs (as the field's own id). They can be patched by id too.

RcFormField.id ​

ts
id: string

RcFormField.type ​

ts
type?: 'text' | 'number' | 'password' | 'textarea' | 'checkbox' | 'select'

The input kind (default 'text').

RcFormField.label ​

ts
label?: string

The label left of the input (default: the id).

RcFormField.value ​

ts
value?: string | number | boolean | null

The label left of the input (default: the id).

RcFormField.placeholder ​

ts
placeholder?: string

The label left of the input (default: the id).

RcFormField.options ​

ts
options?: RcSelectOption[]

Choices for type 'select'.

RcFormField.disabled ​

ts
disabled?: boolean

Choices for type 'select'.

RcFormField.readonly ​

ts
readonly?: boolean

Choices for type 'select'.

RcFormField.hidden ​

ts
hidden?: boolean

Choices for type 'select'.

RcFormField.min ​

ts
min?: number

Number bounds and step.

RcFormField.max ​

ts
max?: number

Upper bound for type 'number'.

RcFormField.step ​

ts
step?: number

Step for type 'number'.

RcFormField.rows ​

ts
rows?: number

Visible lines for type 'textarea'.

RcFormWidget interface ​

ts
interface RcFormWidget extends RcWidgetBase

Labelled fields in a two-column grid — the quick way to build an editor. Enter in a field fires the form's 'submit'. win.values(formId) returns { fieldId: value } for its fields; patch { values: {...} } fills them in.

RcFormWidget.type ​

ts
type: 'form'

RcFormWidget.fields ​

ts
fields: RcFormField[]

RcFormWidget.values ​

ts
values?: Record<string, any>

Field values by field id (overrides each field's own value).

RcWidget type ​

ts
type RcWidget =
    | RcStackWidget | RcSplitWidget | RcTabsWidget | RcGroupWidget
    | RcHeadingWidget | RcTextWidget | RcSeparatorWidget | RcButtonWidget
    | RcInputWidget | RcTextAreaWidget | RcCheckboxWidget | RcSelectWidget | RcCodeWidget
    | RcTableWidget | RcListWidget | RcFormWidget | RcImageWidget

Any plugin widget — the shape win.set() and win.patch(id, { children }) take.

RcPluginEvent interface ​

ts
interface RcPluginEvent

What every plugin event handler receives.

RcPluginEvent.type ​

ts
type: string

The event name ('click', 'change', ...).

RcPluginEvent.widget ​

ts
widget: string

The id of the widget (or form field) that fired it.

RcPluginEvent.values ​

ts
values: Record<string, any>

Every input value in the window at the time of the event (same as win.values()).

RcPluginChangeEvent interface ​

ts
interface RcPluginChangeEvent extends RcPluginEvent

A 'change' event: an input's new value. Text inputs report after a short typing pause.

RcPluginChangeEvent.value ​

ts
value: any

RcPluginSelectEvent interface ​

ts
interface RcPluginSelectEvent extends RcPluginEvent

A table or list 'select' / 'activate' event.

RcPluginSelectEvent.index ​

ts
index: number

The row or item's position.

RcPluginSelectEvent.row ​

ts
row?: Record<string, any>

The table row object (tables only).

RcPluginSelectEvent.item ​

ts
item?: RcListItem

The list item (lists only).

RcPluginImageClickEvent interface ​

ts
interface RcPluginImageClickEvent extends RcPluginEvent

A 'click' on an image widget: the point clicked, in source-image pixels (rect offset included).

RcPluginImageClickEvent.x ​

ts
x: number

RcPluginImageClickEvent.y ​

ts
y: number

RcPluginTabEvent interface ​

ts
interface RcPluginTabEvent extends RcPluginEvent

A tabs widget's 'tab' event.

RcPluginTabEvent.index ​

ts
index: number

RcPluginTabEvent.title ​

ts
title: string

RcStaff interface ​

ts
interface RcStaff

The staff member a plugin window belongs to.

RcStaff.account ​

ts
readonly account: string

Their account name.

RcStaff.hasRight ​

ts
hasRight(name: string): boolean

Whether they hold a named staff right (catalog or plugin-declared), checked live.

RcStaff.hasFolderRight ​

ts
hasFolderRight(mode: 'r' | 'w' | 'rw', path: string): boolean

Whether their folder rights grant 'r', 'w' or 'rw' on a data/-relative file path.

RcDialogOptions interface ​

ts
interface RcDialogOptions

Options for win.confirm().

RcDialogOptions.title ​

ts
title?: string

Dialog heading.

RcDialogOptions.okText ​

ts
okText?: string

OK button text (default 'OK').

RcDialogOptions.cancelText ​

ts
cancelText?: string

Cancel button text (default 'Cancel').

RcPromptOptions interface ​

ts
interface RcPromptOptions extends RcDialogOptions

Options for win.prompt().

RcPromptOptions.value ​

ts
value?: string

The text the input starts with.

RcPromptOptions.placeholder ​

ts
placeholder?: string

Hint shown in the empty input.

RcPluginWindow interface ​

ts
interface RcPluginWindow

One open plugin window in a staff member's GRC. Everything the window shows comes from win.set / win.patch; every interaction arrives through win.on handlers. Calls after the window closed are ignored.

RcPluginWindow.id ​

ts
readonly id: number

A server-unique id for this window, e.g. to key per-window state in a Map.

RcPluginWindow.pluginId ​

ts
readonly pluginId: string

The plugin's id.

RcPluginWindow.isOpen ​

ts
readonly isOpen: boolean

False once the staff member (or the script) closed it, or they disconnected.

RcPluginWindow.staff ​

ts
readonly staff: RcStaff

Who the window belongs to.

RcPluginWindow.set ​

ts
set(root: RcWidget): void

Replaces the whole widget tree (and resets every input to the values in it).

RcPluginWindow.patch ​

ts
patch(id: string, props: Record<string, any>): void

Merges props into one widget or form field by id: new rows for a table, { disabled: true }, { text: 'Saved' }, { value: 3 } for an input, { values: {...} } for a form, { children: [...] } for a container.

RcPluginWindow.values ​

ts
values(): Record<string, any>
values(id: string): any

Input values by widget id. With an id: that input's value, or for a form/container an object of the input values inside it.

RcPluginWindow.on ​

ts
on(event: 'click', id: string, handler: (e: RcPluginEvent & Partial<RcPluginImageClickEvent>) => void | Promise<void>): RcPluginWindow
on(event: 'change', id: string, handler: (e: RcPluginChangeEvent) => void | Promise<void>): RcPluginWindow
on(event: 'select' | 'activate', id: string, handler: (e: RcPluginSelectEvent) => void | Promise<void>): RcPluginWindow
on(event: 'submit', id: string, handler: (e: RcPluginEvent) => void | Promise<void>): RcPluginWindow
on(event: 'tab', id: string, handler: (e: RcPluginTabEvent) => void | Promise<void>): RcPluginWindow

Runs when a button is clicked, or an image (with x/y: see RcPluginImageClickEvent).

RcPluginWindow.off ​

ts
off(event: string, id: string, handler?: Function): RcPluginWindow

Removes one handler, or every handler for that event and widget.

RcPluginWindow.toast ​

ts
toast(message: string, kind?: 'info' | 'success' | 'warning' | 'error'): void

Shows a short notification in the corner of the window.

RcPluginWindow.setTitle ​

ts
setTitle(title: string): void

Changes the window title.

RcPluginWindow.confirm ​

ts
confirm(message: string, options?: RcDialogOptions): Promise<boolean>

Asks a yes/no question; resolves true for OK, false for Cancel or a closed window.

RcPluginWindow.prompt ​

ts
prompt(message: string, options?: RcPromptOptions): Promise<string | null>

Asks for a line of text; resolves the text, or null when cancelled or closed.

RcPluginWindow.close ​

ts
close(): void

Closes the window (onClose still runs).

RcPluginOptions interface ​

ts
interface RcPluginOptions

What rcplugins.register() takes.

RcPluginOptions.title ​

ts
title: string

The toolbar button and window title (1-64 characters).

RcPluginOptions.right ​

ts
right?: string

A staff right needed to see and use the plugin: an existing one like 'sql', or a new name (lowercase letters, digits, '_') that then appears in the Staff Rights editor. Omitted: every staff member can use it.

RcPluginOptions.width ​

ts
width?: number

Starting window width in pixels (default 800).

RcPluginOptions.height ​

ts
height?: number

Starting window height in pixels (default 600).

RcPluginOptions.onOpen ​

ts
onOpen(win: RcPluginWindow, staff: RcStaff): void | Promise<void>

Builds a newly opened window: call win.set() and register win.on() handlers.

RcPluginOptions.onClose ​

ts
onClose?(win: RcPluginWindow, staff: RcStaff): void | Promise<void>

Runs after a window closed (by the staff member, the script, or a disconnect).

rcplugins global ​

ts
declare const rcplugins: { … }

GRC plugins: a server script adds a button to every (allowed) staff member's GRC toolbar; clicking it opens a window whose UI and logic live in the script — item editors, report viewers, moderation panels. The script describes the window as a tree of widgets (forms, tables, lists, tabs, buttons...) that GRC renders natively, and handles the staff member's clicks and edits as events.

A registration belongs to the script that made it and goes away when that script unloads. On a hot reload, open windows of a plugin the new version registers again are rebuilt in place (onOpen runs again).

rcplugins.register ​

ts
register(id: string, options: RcPluginOptions): void

Registers (or updates) a plugin. Throws on a bad id or one another script owns.

rcplugins.unregister ​

ts
unregister(id: string): void

Removes a plugin; its open windows close.

rcplugins.list ​

ts
list(): string[]

The ids this server's scripts have registered.