Skip to content

ClientScripts and Channel

import { ClientScripts, Channel } from "@sagl/server";

ClientScripts

server.clientScripts: JavaScript every player's game runs, in a sandbox. See Client API for what scripts can do.

Scripts run in the order they were first added. Replacing or removing one runs them all again from scratch.

set(name, code)

set(name: string, code: string): this

Adds a script, or replaces the one with that name, for everyone now and as they join.

Parameter Type Description
name string 1-64 characters.
code string JavaScript, up to 1 MB.

Throws RangeError for a bad name.

server.clientScripts.set("hello.js", `sagl.log("Hello from player", sagl.player.id);`);

setFile(path, name?)

setFile(path: string, name?: string): this

Adds a script from a file on the server. It's sent to each player as they join; prefer useClientFile for anything big.

Parameter Type Description
path string A file on the server.
name string Default: the file's name.
server.clientScripts.setFile("./client-src/hud.js");

useClientFile(path)

useClientFile(path: string): this

Uses a client file as a script, named after its path. Players already have it, so only the name is sent.

Parameter Type Description
path string The client file's path.

Throws Error if there's no such client file.

server.clientScripts.useClientFile("scripts/hud.js").useClientFile("scripts/shop.js");

delete(name), has(name), names

delete(name: string): boolean
has(name: string): boolean
readonly names: string[]

Removes a script from everyone's game; whether one exists; and every script's name in the order they run.

if (server.clientScripts.has("event.js")) server.clientScripts.delete("event.js");

Channel

server.channel(name): a named channel to and from client scripts, carrying anything JSON can hold (up to 256 KB a message). In client scripts it's sagl.on(name, fn) and sagl.emit(name, data).

on(handler)

on(handler: (player: Player, data: unknown) => void): this

Handles what players' client scripts send on this channel.

Parameter Type Description
handler function Gets the player and the parsed data.
server.channel("shop").on((player, data) => {
  const { buy } = data as { buy: string };
  if (buy === "armour" && player.money >= 100) {
    player.giveMoney(-100);
    player.armour = 100;
  }
});

off(handler)

off(handler: (player: Player, data: unknown) => void): this

send(player, data?)

send(player: Player, data?: unknown): void

To one player's client scripts.

Parameter Type Description
player Player Who to.
data unknown JSON-serialisable.

Throws TypeError if data can't be serialised.

server.channel("notify").send(player, { text: "Payday: $500" });

broadcast(data?)

broadcast(data?: unknown): void

To every player's client scripts.

setInterval(() => server.channel("clock").broadcast({ now: Date.now() }), 1000);