@zaisma/game-server 1.32.0 → 1.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bench/brand/README.md +2 -1
- package/bench/brand/cover-guide/brick-brawl-blocky.webp +0 -0
- package/bench/brand/cover-guide/emberfall-painted.webp +0 -0
- package/bench/brand/developer-page/game-blocks.webp +0 -0
- package/bench/brand/developer-page/game-cells-match.webp +0 -0
- package/bench/brand/developer-page/game-dark-fantasy-boss.webp +0 -0
- package/bench/brand/developer-page/game-neon-city.webp +0 -0
- package/bench/brand/share-card-letters.png +0 -0
- package/bench/brand/share-card-person-light.png +0 -0
- package/bench/glass.js +4584 -3987
- package/bin/local-play-runner.js +2 -0
- package/bin/local-play.js +3 -2
- package/bin/node-parts.js +36 -2
- package/bin/node.d.ts +2 -0
- package/bin/node.js +13 -7
- package/package.json +1 -1
- package/sdk/zaisma.d.ts +11 -0
- package/sdk/zaisma.js +25 -1
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/requests.d.ts +2 -0
- package/src/room-calls.d.ts +5 -0
- package/src/room-calls.js +12 -1
- package/src/room.d.ts +36 -1
- package/src/room.js +25 -0
- package/bench/brand/cover-guide/gem-grid-cover.webp +0 -0
package/bin/local-play-runner.js
CHANGED
|
@@ -27,6 +27,8 @@ try {
|
|
|
27
27
|
issuerUrl: config.issuerUrl,
|
|
28
28
|
database: localDatabase(config.databaseFile),
|
|
29
29
|
roomStateFile: config.roomStateFile,
|
|
30
|
+
// room.readDataFile reads the game server's data files from its folder, as on Zaisma's rooms.
|
|
31
|
+
dataFolder: config.dataFolder,
|
|
30
32
|
// onPurchase and onRefund hear purchases through the stand-in developer API on the bench's rooms.
|
|
31
33
|
zaismaKey: config.zaismaKey,
|
|
32
34
|
developerApiUrl: config.developerApiUrl,
|
package/bin/local-play.js
CHANGED
|
@@ -193,7 +193,8 @@ function sourceOf(gameFolder) {
|
|
|
193
193
|
const folder = join(gameFolder, "zaisma-server");
|
|
194
194
|
if (existsSync(folder)) walk(folder);
|
|
195
195
|
if (existsSync(join(gameFolder, "zaisma-server.js"))) found.push(join(gameFolder, "zaisma-server.js"));
|
|
196
|
-
|
|
196
|
+
// Code by its text; a data file by its size and time, so a big one isn't read again on every change (any change restarts the runner).
|
|
197
|
+
return found.map((path) => (/\.(js|json|wasm)$/.test(path) ? readFileSync(path, "utf8") : `${path} ${statSync(path).size} ${statSync(path).mtimeMs}`)).join("\n");
|
|
197
198
|
}
|
|
198
199
|
|
|
199
200
|
/** The first non-internal IPv4 addresses of this computer, for a phone on the same Wi-Fi. */
|
|
@@ -1484,7 +1485,7 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1484
1485
|
saveState();
|
|
1485
1486
|
tell("reload");
|
|
1486
1487
|
}
|
|
1487
|
-
const config = { entry: entry(), gameSlug, port: ports.runner, origin: localhostOrigin(ports.game), issuerUrl: roomsAddress(), databaseFile: join(localFolder, "database.sqlite"), roomStateFile: join(localFolder, "room-states.sqlite"), developerApiUrl: `${roomsAddress()}/api/dev`, zaismaKey: LOCAL_RUNNER_KEY };
|
|
1488
|
+
const config = { entry: entry(), gameSlug, port: ports.runner, origin: localhostOrigin(ports.game), issuerUrl: roomsAddress(), databaseFile: join(localFolder, "database.sqlite"), roomStateFile: join(localFolder, "room-states.sqlite"), dataFolder: join(gameFolder, "zaisma-server"), developerApiUrl: `${roomsAddress()}/api/dev`, zaismaKey: LOCAL_RUNNER_KEY };
|
|
1488
1489
|
const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", runnerFile, JSON.stringify(config)], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env } });
|
|
1489
1490
|
let isReady = false;
|
|
1490
1491
|
const timeout = setTimeout(() => {
|
package/bin/node-parts.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// profiles, its local SQLite files, and the checks on its options. Nothing here is part of the
|
|
3
3
|
// public package: tests reach it by path.
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { existsSync } from "node:fs";
|
|
5
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
+
import { resolve, sep } from "node:path";
|
|
6
7
|
import { DATABASE_LIMITS, GameServerError, answerDatabase, checkBatch, checkPlayerId, checkStatement, checkedRow, eraseRefused, eraseStatements, readDatabaseAnswer, tablesFromColumns, tooManyRows, TABLE_COLUMNS_SQL } from "../src/internal.js";
|
|
7
8
|
|
|
8
9
|
/** How long the pass keys and the profiles of accounts are kept before they're fetched again. */
|
|
@@ -366,7 +367,7 @@ export function secretsFromEnvironment() {
|
|
|
366
367
|
const WORLD_COPIES_DURATION_MS = 30 * 86_400_000;
|
|
367
368
|
const WORLD_COPY_MINUTES_DURATION_MS = 86_400_000;
|
|
368
369
|
|
|
369
|
-
const OPTION_NAMES = ["gameServer", "gameSlug", "port", "origins", "issuerUrl", "loadPassKeys", "loadReceiptKeys", "loadProfile", "database", "secrets", "webhookSigningSecret", "roomStateFile", "zaismaKey", "developerApiUrl", "webtransportPort", "certificatePath", "certificateKeyPath", "identifyPlayer", "outsideGuestsEnabled"];
|
|
370
|
+
const OPTION_NAMES = ["gameServer", "gameSlug", "port", "origins", "issuerUrl", "loadPassKeys", "loadReceiptKeys", "loadProfile", "database", "secrets", "webhookSigningSecret", "roomStateFile", "zaismaKey", "developerApiUrl", "webtransportPort", "certificatePath", "certificateKeyPath", "identifyPlayer", "outsideGuestsEnabled", "dataFolder"];
|
|
370
371
|
|
|
371
372
|
/**
|
|
372
373
|
* Check what startServer was given: unknown options and options of the wrong kind are a GameServerError,
|
|
@@ -404,6 +405,8 @@ export function checkedStartServerOptions(given, issuerUrlDefault) {
|
|
|
404
405
|
if (options.developerApiUrl !== undefined && (!isText(options.developerApiUrl) || !URL.canParse(options.developerApiUrl))) throw bad("developerApiUrl", "a URL", 'Give the address of Zaisma\'s developer API, like "https://zaisma.com/api/dev".');
|
|
405
406
|
// Players from outside Zaisma (games played off their Zaisma page): who a playerToken is, and whether players with none come in as guests.
|
|
406
407
|
if (options.identifyPlayer !== undefined && !isFunction(options.identifyPlayer)) throw bad("identifyPlayer", "a function", "Give async (playerToken, { origin }) => ({ id, name }) or null, like signInWithZaismaPlayers({ signInAppIds }) makes.");
|
|
408
|
+
options.dataFolder ??= "zaisma-server";
|
|
409
|
+
if (!isText(options.dataFolder)) throw bad("dataFolder", "a folder path", 'Give the folder room.readDataFile reads from, like "zaisma-server": the game server\'s own folder.');
|
|
407
410
|
options.outsideGuestsEnabled ??= false;
|
|
408
411
|
if (typeof options.outsideGuestsEnabled !== "boolean") throw bad("outsideGuestsEnabled", "true or false", "Give true to let players with no playerToken in as guests, or false (the default).");
|
|
409
412
|
// The fast lane (WebTransport): its UDP port and the certificate it holds itself, all three or none.
|
|
@@ -416,3 +419,34 @@ export function checkedStartServerOptions(given, issuerUrlDefault) {
|
|
|
416
419
|
}
|
|
417
420
|
return options;
|
|
418
421
|
}
|
|
422
|
+
|
|
423
|
+
/** Files in the game server's folder that are code, imported rather than read: the same kinds as on Zaisma's rooms. */
|
|
424
|
+
const CODE_FILE = /\.(js|json|wasm)$/;
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* room.readDataFile and server.readDataFile on your own server: a data file from the folder by its path there (each
|
|
428
|
+
* read once, then the same ArrayBuffer), or null for no such file, a code file, or a path outside the folder.
|
|
429
|
+
*/
|
|
430
|
+
export function dataFilesFrom(dataFolder) {
|
|
431
|
+
const folder = resolve(dataFolder);
|
|
432
|
+
const read = new Map();
|
|
433
|
+
return (dataFilePath) => {
|
|
434
|
+
if (read.has(dataFilePath)) return read.get(dataFilePath);
|
|
435
|
+
const path = resolve(folder, dataFilePath);
|
|
436
|
+
let found = null;
|
|
437
|
+
if (path.startsWith(folder + sep) && !CODE_FILE.test(path)) {
|
|
438
|
+
try {
|
|
439
|
+
// A link that leads out of the folder isn't one of its files.
|
|
440
|
+
if (realpathSync(path).startsWith(realpathSync(folder) + sep) && statSync(path).isFile()) {
|
|
441
|
+
const bytes = readFileSync(path);
|
|
442
|
+
found = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
443
|
+
}
|
|
444
|
+
} catch {
|
|
445
|
+
found = null;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// Found files are kept; a missing one is looked for again, so a file added while the server runs is read.
|
|
449
|
+
if (found !== null) read.set(dataFilePath, found);
|
|
450
|
+
return found;
|
|
451
|
+
};
|
|
452
|
+
}
|
package/bin/node.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface StartServerOptions {
|
|
|
27
27
|
webhookSigningSecret?: string;
|
|
28
28
|
/** Where rooms save their states, so a restart brings matches back. Default zaisma-room-states.sqlite; null keeps none. */
|
|
29
29
|
roomStateFile?: string | null;
|
|
30
|
+
/** Where room.readDataFile and server.readDataFile read data files from. Default: zaisma-server, the game server's own folder. */
|
|
31
|
+
dataFolder?: string;
|
|
30
32
|
/** An API key with purchase_access write for this game, which onPurchase and onRefund need. Default: the ZAISMA_KEY environment variable. */
|
|
31
33
|
zaismaKey?: string;
|
|
32
34
|
/** Zaisma's developer API, which marks purchases handled. Default: https://zaisma.com/api/dev. */
|
package/bin/node.js
CHANGED
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
import { WebSocketServer } from "ws";
|
|
25
25
|
import { createServer } from "node:http";
|
|
26
26
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
27
|
-
import { resolve } from "node:path";
|
|
27
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
28
28
|
import { readFileSync, realpathSync } from "node:fs";
|
|
29
29
|
import { roomMessageProblem, BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, ERROR_TEXT, NO_ANSWER_CLOSE_CODE, PASS_ISSUER_URL, OUTSIDE_ZAISMA_CHAT_SETTINGS, PassError, ReceiptError, REMOVED_CLOSE_CODE, REQUEST_ERROR_HTTP_STATUS, REQUEST_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_TUNING, WEBHOOK_LIMITS, GameServerError, RoomCore, chatSettingsOf, checkChat, readChatMessage, restoreInfoOf, passesAreFriends, passesHaveBlockBetween, answerRequest, startSchedules, checkRoomData, checkedOutsidePlayer, clientIdle, defineGameServer, errorMessage, guestPlayer, newServer, isPlayerToken, isRoomCode, readRequestBody, relay, requestError, runWebhook, tidyRoomInfo, verifyPass, verifyReceipt, verifyWebhook } from "../src/internal.js";
|
|
30
30
|
import { OutsideCallError } from "../src/outside-calls.js";
|
|
31
31
|
import { startFastLane } from "./fast-lane.js";
|
|
32
|
-
import { checkedStartServerOptions, localDatabase, localRoomStates, passKeysFrom, profilesFrom, receiptKeysFrom, secretsFromEnvironment } from "./node-parts.js";
|
|
32
|
+
import { checkedStartServerOptions, dataFilesFrom, localDatabase, localRoomStates, passKeysFrom, profilesFrom, receiptKeysFrom, secretsFromEnvironment } from "./node-parts.js";
|
|
33
33
|
|
|
34
34
|
// Code that names OutsideCallError, as Zaisma's sandbox lets it, moves unchanged: nothing here refuses a call, so instanceof is simply false.
|
|
35
35
|
globalThis.OutsideCallError ??= OutsideCallError;
|
|
@@ -79,12 +79,14 @@ const CATCH_UP_MS = 50;
|
|
|
79
79
|
* identifyPlayer (async (playerToken, { origin }) => ({ id, name }) or null; none by default) says who a player from
|
|
80
80
|
* outside Zaisma is by the playerToken their game sent (signInWithZaismaPlayers makes one for Sign in with Zaisma),
|
|
81
81
|
* and outsideGuestsEnabled (false by default) lets players with no token (playerToken: null) in as guests (guestPlayer).
|
|
82
|
-
* Both join with kind "outside_zaisma".
|
|
82
|
+
* Both join with kind "outside_zaisma". dataFolder (by default zaisma-server, as uploads lay it out) is where
|
|
83
|
+
* room.readDataFile and server.readDataFile read data files from.
|
|
83
84
|
* Answers { close(), httpServer, fastLaneReady }: close() saves every room first and finishes once the server
|
|
84
85
|
* has stopped; fastLaneReady settles once the fast lane listens (at once without one), or rejects saying why it can't.
|
|
85
86
|
*/
|
|
86
87
|
export function startServer(options) {
|
|
87
|
-
const { gameServer, gameSlug, port: portNumber, origins, issuerUrl, loadPassKeys = passKeysFrom(`${issuerUrl}/v1/pass-keys/${gameSlug}`), loadReceiptKeys = receiptKeysFrom(`${issuerUrl}/.well-known/receipt-jwks.json`), loadProfile = profilesFrom(issuerUrl), database = localDatabase("zaisma-database.sqlite"), secrets = secretsFromEnvironment(), webhookSigningSecret = process.env.ZAISMA_WEBHOOK_SIGNING_SECRET, roomStateFile = "zaisma-room-states.sqlite", zaismaKey = process.env.ZAISMA_KEY, developerApiUrl = "https://zaisma.com/api/dev", webtransportPort, certificatePath, certificateKeyPath, identifyPlayer, outsideGuestsEnabled } = checkedStartServerOptions(options, PASS_ISSUER_URL);
|
|
88
|
+
const { gameServer, gameSlug, port: portNumber, origins, issuerUrl, loadPassKeys = passKeysFrom(`${issuerUrl}/v1/pass-keys/${gameSlug}`), loadReceiptKeys = receiptKeysFrom(`${issuerUrl}/.well-known/receipt-jwks.json`), loadProfile = profilesFrom(issuerUrl), database = localDatabase("zaisma-database.sqlite"), secrets = secretsFromEnvironment(), webhookSigningSecret = process.env.ZAISMA_WEBHOOK_SIGNING_SECRET, roomStateFile = "zaisma-room-states.sqlite", zaismaKey = process.env.ZAISMA_KEY, developerApiUrl = "https://zaisma.com/api/dev", webtransportPort, certificatePath, certificateKeyPath, identifyPlayer, outsideGuestsEnabled, dataFolder } = checkedStartServerOptions(options, PASS_ISSUER_URL);
|
|
89
|
+
const findDataFile = dataFilesFrom(dataFolder);
|
|
88
90
|
const definition = defineGameServer(gameServer);
|
|
89
91
|
// Exactly once needs Zaisma's record of what's handled: without a key, purchases would come twice, so it doesn't start.
|
|
90
92
|
if ((definition.onPurchase || definition.onRefund) && !zaismaKey) {
|
|
@@ -105,7 +107,7 @@ export function startServer(options) {
|
|
|
105
107
|
const stateSaveIntervalMs = (definition.stateSaveIntervalSec ?? ROOM_LIMITS.defaultStateSaveIntervalSec) * 1000;
|
|
106
108
|
// Schedules run while this server is up; one that's down when a run is due misses that run.
|
|
107
109
|
// What onRequest, onSchedule and onWebhook get: the game's database, secrets, receipt checks and this server's rooms.
|
|
108
|
-
const server = newServer({ database, secrets, verifyReceipt: receiptClaims }, roomReachFrom(null));
|
|
110
|
+
const server = newServer({ database, secrets, verifyReceipt: receiptClaims, findDataFile }, roomReachFrom(null));
|
|
109
111
|
const schedules = startSchedules(definition, server, (run, failure) => console.error(`Game server error in onSchedule ("${run.name}", due ${run.scheduledAt}):`, failure));
|
|
110
112
|
const rooms = new Map(); // code -> { core, sockets: Map<playerId, ws>, timer }
|
|
111
113
|
// When the game last sent to every room, within the last minute (ROOM_MESSAGE_LIMITS.maximumEveryRoomSendsPerMin).
|
|
@@ -312,6 +314,7 @@ export function startServer(options) {
|
|
|
312
314
|
roomCode: code,
|
|
313
315
|
database,
|
|
314
316
|
secrets,
|
|
317
|
+
findDataFile,
|
|
315
318
|
verifyReceipt: receiptClaims,
|
|
316
319
|
purchaseHandling,
|
|
317
320
|
roomReach: roomReachFrom(code),
|
|
@@ -903,8 +906,8 @@ function binaryBytes(received) {
|
|
|
903
906
|
return new Uint8Array(received.buffer.slice(received.byteOffset, received.byteOffset + received.byteLength));
|
|
904
907
|
}
|
|
905
908
|
|
|
906
|
-
const USAGE = "Usage: zaisma-game-server <server.ts | relay> --game <slug> [--port 8080] [--origin <url>,<url>] [--issuer-url https://rooms.zaisma.com] [--database-file zaisma-database.sqlite] [--room-state-file zaisma-room-states.sqlite] [--webtransport-port 443 --certificate-path fullchain.pem --certificate-key-path privkey.pem]\n or: zaisma-game-server play-locally [folder] [--port 4800] [--game <slug>] [--on-network] [--no-open] [--json]";
|
|
907
|
-
const FLAGS = ["game", "port", "origin", "issuer-url", "database-file", "room-state-file", "webtransport-port", "certificate-path", "certificate-key-path"];
|
|
909
|
+
const USAGE = "Usage: zaisma-game-server <server.ts | relay> --game <slug> [--port 8080] [--origin <url>,<url>] [--issuer-url https://rooms.zaisma.com] [--database-file zaisma-database.sqlite] [--room-state-file zaisma-room-states.sqlite] [--data-folder <folder>] [--webtransport-port 443 --certificate-path fullchain.pem --certificate-key-path privkey.pem]\n or: zaisma-game-server play-locally [folder] [--port 4800] [--game <slug>] [--on-network] [--no-open] [--json]";
|
|
910
|
+
const FLAGS = ["game", "port", "origin", "issuer-url", "database-file", "room-state-file", "data-folder", "webtransport-port", "certificate-path", "certificate-key-path"];
|
|
908
911
|
/** The fast lane's flags: all three or none. */
|
|
909
912
|
const FAST_LANE_FLAGS = ["webtransport-port", "certificate-path", "certificate-key-path"];
|
|
910
913
|
|
|
@@ -1009,6 +1012,9 @@ async function runCommand() {
|
|
|
1009
1012
|
...(flags["issuer-url"] !== undefined ? { issuerUrl: flags["issuer-url"] } : {}),
|
|
1010
1013
|
...(flags["database-file"] !== undefined ? { database: localDatabase(resolve(flags["database-file"])) } : {}),
|
|
1011
1014
|
roomStateFile: resolve(flags["room-state-file"] ?? "zaisma-room-states.sqlite"),
|
|
1015
|
+
// Data files sit beside the game server's code: zaisma-server/index.js reads zaisma-server/maps/docks.bin.
|
|
1016
|
+
// The game server's own folder, never the project's: a lone server file reads from zaisma-server/ beside it.
|
|
1017
|
+
dataFolder: resolve(flags["data-folder"] ?? (file === "relay" ? "zaisma-server" : basename(dirname(resolve(file))) === "zaisma-server" ? dirname(resolve(file)) : join(dirname(resolve(file)), "zaisma-server"))),
|
|
1012
1018
|
...(flags["webtransport-port"] !== undefined ? { webtransportPort: Number(flags["webtransport-port"]), certificatePath: resolve(flags["certificate-path"]), certificateKeyPath: resolve(flags["certificate-key-path"]) } : {}),
|
|
1013
1019
|
});
|
|
1014
1020
|
} catch (error) {
|
package/package.json
CHANGED
package/sdk/zaisma.d.ts
CHANGED
|
@@ -9,6 +9,11 @@
|
|
|
9
9
|
* v1 only gains things: calls, options, fields and values are added, never renamed or removed. Page
|
|
10
10
|
* messages, storage keys and members whose names start with `_` are not part of v1.
|
|
11
11
|
*
|
|
12
|
+
* `Zaisma` is locked once the SDK loads: it, every namespace and every call under it can't be replaced,
|
|
13
|
+
* redefined, deleted or added to, so a call by Zaisma's name is always Zaisma's own. Include the SDK once,
|
|
14
|
+
* and never declare a `Zaisma` of your own at the top of a script (`const Zaisma = …`, `function Zaisma`):
|
|
15
|
+
* the browser refuses that script. Use the global `Zaisma` as it is.
|
|
16
|
+
*
|
|
12
17
|
* For editor and compiler checks, save this file beside your game's folder, not in it, since uploads
|
|
13
18
|
* take no .ts files. On Zaisma it's served beside the SDK as _zaisma/v1.d.ts; in Zaisma's repository
|
|
14
19
|
* it's packages/sdk/zaisma.d.ts. Then put `/// <reference path="../zaisma.d.ts" />` (and in JavaScript,
|
|
@@ -24,6 +29,12 @@
|
|
|
24
29
|
* Within v1, codes and events only grow: handle unknown ones (a `default` branch), and a new code or event
|
|
25
30
|
* never breaks your game.
|
|
26
31
|
*
|
|
32
|
+
* The Zaisma button shares your game's screen: while it plays on Zaisma, the button sits in the top right
|
|
33
|
+
* corner of the game's frame, over the game, about 64 by 60 CSS px past the phone's safe area. On phones and
|
|
34
|
+
* touch screens it's always there; with a mouse it slides in when the pointer reaches that corner. Keep your
|
|
35
|
+
* own buttons, score and words out of that corner. The developer API's preview_game_page pictures the game
|
|
36
|
+
* playing with the button in place, on a laptop and a phone.
|
|
37
|
+
*
|
|
27
38
|
* Player passes, for rooms and your own servers, need the game played on its zaisma.com page, which
|
|
28
39
|
* checks the browser on Play: joining fails with `error.code` "unchecked" when it couldn't, or when the
|
|
29
40
|
* game was opened anywhere else. A game played off Zaisma (exported, on another site, wrapped for a store)
|
package/sdk/zaisma.js
CHANGED
|
@@ -2684,5 +2684,29 @@
|
|
|
2684
2684
|
});
|
|
2685
2685
|
|
|
2686
2686
|
var friends = { list: listFriends, setRoom: setOwnRoom, sendRequest: sendFriendRequest };
|
|
2687
|
-
|
|
2687
|
+
var zaisma = { sdkVersionNumber: 1, gameSlug: config.game || null, player: player, setUpOffZaisma: setUpOffZaisma, joinRoom: joinRoom, rooms: rooms, server: server, invite: invite, checkChat: checkChat, links: links, items: items, friends: friends, saves: saves, versions: versions, page: zaismaPage };
|
|
2688
|
+
|
|
2689
|
+
/**
|
|
2690
|
+
* Locked once loaded: window.Zaisma, every namespace and every call under it can't be replaced, redefined,
|
|
2691
|
+
* deleted or added to, so a call by Zaisma's name is always Zaisma's own. Each object and function is frozen,
|
|
2692
|
+
* through its getters and setters too, without calling them.
|
|
2693
|
+
*/
|
|
2694
|
+
function lockDeep(part, lockedParts) {
|
|
2695
|
+
if ((typeof part !== "object" && typeof part !== "function") || part === null || lockedParts.has(part)) return;
|
|
2696
|
+
lockedParts.add(part);
|
|
2697
|
+
Reflect.ownKeys(part).forEach(function (key) {
|
|
2698
|
+
var described = Object.getOwnPropertyDescriptor(part, key);
|
|
2699
|
+
if ("value" in described) lockDeep(described.value, lockedParts);
|
|
2700
|
+
lockDeep(described.get, lockedParts);
|
|
2701
|
+
lockDeep(described.set, lockedParts);
|
|
2702
|
+
});
|
|
2703
|
+
Object.freeze(part);
|
|
2704
|
+
}
|
|
2705
|
+
lockDeep(zaisma, new WeakSet());
|
|
2706
|
+
// Something already holding the name for good (a second copy of the SDK, or the game's own) keeps it, and the console says so.
|
|
2707
|
+
try {
|
|
2708
|
+
Object.defineProperty(window, "Zaisma", { value: zaisma, writable: false, enumerable: true, configurable: false });
|
|
2709
|
+
} catch (refused) {
|
|
2710
|
+
console.warn("Zaisma: window.Zaisma is already locked on this page, so this copy of the SDK isn't set up. Include _zaisma/v1.js once, before any script that uses Zaisma.");
|
|
2711
|
+
}
|
|
2688
2712
|
})();
|
package/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, type Audience, type AwayInfo, type AwayMode, type AwayReason, type BroadcastOptions, type Delivery, type GameServer, type GameServerErrorCode, type HandlerResult, type IdleCheck, type JoinAnswer, type ChatAnswer, type ChatInfo, type JoinInfo, type KickOptions, type LiveRoom, type LeaveInfo, type LeaveReason, type MoveOptions, type MoveResult, type Player, type Purchase, type Refusal, type ReserveOptions, type KeptRoomRestoreInfo, type RestoreInfo, type Room, type RoomErrorCode, type RoomInfo, type RoomMessage, type RoomMessageSenderKind, type RoomPlayer, type RoomSelection, type SendOptions, type VersionUpdate, } from "./room.ts";
|
|
1
|
+
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, GAME_SERVER_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, type Audience, type AwayInfo, type AwayMode, type AwayReason, type BroadcastOptions, type Delivery, type GameServer, type GameServerErrorCode, type HandlerResult, type IdleCheck, type JoinAnswer, type ChatAnswer, type ChatInfo, type JoinInfo, type KickOptions, type LiveRoom, type LeaveInfo, type LeaveReason, type MoveOptions, type MoveResult, type Player, type Purchase, type Refusal, type ReserveOptions, type KeptRoomRestoreInfo, type RestoreInfo, type Room, type RoomErrorCode, type RoomInfo, type RoomMessage, type RoomMessageSenderKind, type RoomPlayer, type RoomSelection, type SendOptions, type VersionUpdate, } from "./room.ts";
|
|
2
2
|
export { REQUEST_LIMITS, type RequestErrorCode, type Server } from "./requests.ts";
|
|
3
3
|
export { SCHEDULE_LIMITS, type Schedule, type ScheduledRun } from "./schedules.ts";
|
|
4
4
|
export { WEBHOOK_LIMITS, verifyWebhook, type WebhookError, type WebhookErrorCode, type WebhookEvent, type WebhookEventKind, type WebhookHeaders } from "./webhooks.ts";
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// What @zaisma/game-server gives developers, named one by one: from v1 it only grows (test/contracts).
|
|
2
2
|
// Zaisma's own parts of the package, never locked, are in ./internal.
|
|
3
|
-
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, } from "./room.js";
|
|
3
|
+
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, GAME_SERVER_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, } from "./room.js";
|
|
4
4
|
export { REQUEST_LIMITS } from "./requests.js";
|
|
5
5
|
export { SCHEDULE_LIMITS } from "./schedules.js";
|
|
6
6
|
export { WEBHOOK_LIMITS, verifyWebhook } from "./webhooks.js";
|
package/src/requests.d.ts
CHANGED
|
@@ -25,6 +25,8 @@ export interface Server {
|
|
|
25
25
|
* (set_secret) and never shown again, or the environment variables on your own server.
|
|
26
26
|
*/
|
|
27
27
|
secrets: Readonly<Record<string, string>>;
|
|
28
|
+
/** A data file the game server ships beside its code, by its path from the zaisma-server/ folder, as room.readDataFile reads it. */
|
|
29
|
+
readDataFile(path: string): ArrayBuffer;
|
|
28
30
|
/** Check a purchase's receipt, as room.verifyReceipt does: the runtime fills in Zaisma's keys and this game. */
|
|
29
31
|
verifyReceipt(receipt: string): Promise<ReceiptClaims>;
|
|
30
32
|
/** Send a message to one of the game's live rooms by its code, as room.sendToRoom does. isDelivered is false when no such room is running or it's busy. */
|
package/src/room-calls.d.ts
CHANGED
|
@@ -132,6 +132,11 @@ export interface RoomCallChecks {
|
|
|
132
132
|
} | {
|
|
133
133
|
isValid: false;
|
|
134
134
|
};
|
|
135
|
+
/**
|
|
136
|
+
* room.readDataFile and server.readDataFile: a data file of the game server's folder, by its path from zaisma-server/ (like
|
|
137
|
+
* "maps/docks.bin"), as find answers it, or a bad_room_call naming the path when find has none.
|
|
138
|
+
*/
|
|
139
|
+
readDataFile(path: unknown, find: (dataFilePath: string) => ArrayBuffer | null, call: string): ArrayBuffer;
|
|
135
140
|
}
|
|
136
141
|
/** The checks for a runtime: pass its GameServerError class and the room limits. */
|
|
137
142
|
export declare function roomCallChecks(ErrorClass: RoomCallErrorClass, limits: RoomCallLimits): RoomCallChecks;
|
package/src/room-calls.js
CHANGED
|
@@ -241,7 +241,18 @@ function roomCallChecksParts() {
|
|
|
241
241
|
return { toRoomCode, message: readRoomMessage(message, call) };
|
|
242
242
|
};
|
|
243
243
|
const checkSendToEveryRoom = (message, roomSelection, call) => ({ message: readRoomMessage(message, call), ...checkRoomSelection(roomSelection, call) });
|
|
244
|
-
|
|
244
|
+
const readDataFile = (path, find, call) => {
|
|
245
|
+
const example = 'Give its path from the zaisma-server/ folder, like "maps/docks.bin".';
|
|
246
|
+
if (typeof path !== "string" || !path)
|
|
247
|
+
throw mistake(call, `${call} needs a data file's path.`, example);
|
|
248
|
+
// "./maps/docks.bin" and "maps/docks.bin" are the same file; nothing outside the folder is one.
|
|
249
|
+
const dataFilePath = path.replace(/^(\.\/)+/, "");
|
|
250
|
+
const found = dataFilePath.split("/").some((part) => part === "" || part === "." || part === "..") ? null : find(dataFilePath);
|
|
251
|
+
if (found === null)
|
|
252
|
+
throw mistake(call, `${call} found no data file at ${JSON.stringify(path.slice(0, 200))}.`, `Put the file in the upload's zaisma-server/ folder. ${example} .js, .json and .wasm files there are code: import them instead.`);
|
|
253
|
+
return found;
|
|
254
|
+
};
|
|
255
|
+
return { checkBroadcast, checkSend, checkBroadcastBytes, checkSendBytes, checkKick, checkReserve, checkMoveTo, checkSetInfo, checkEnd, checkRestoreToAt, checkKeptRoomRestoreId, keptRoomRestoreOf, keptRoomRestoreListOf, checkSendToRoom, checkSendToEveryRoom, checkRoomSelection, tidy, tidyRoomInfo, checkRoomData, readDataFile };
|
|
245
256
|
}
|
|
246
257
|
return { checksFor };
|
|
247
258
|
}
|
package/src/room.d.ts
CHANGED
|
@@ -191,6 +191,16 @@ export interface Room {
|
|
|
191
191
|
* game_server_allowed_hosts, and anything else throws an OutsideCallError.
|
|
192
192
|
*/
|
|
193
193
|
readonly secrets: Readonly<Record<string, string>>;
|
|
194
|
+
/**
|
|
195
|
+
* A data file the game server ships beside its code, by its path from the zaisma-server/ folder, like
|
|
196
|
+
* room.readDataFile("maps/docks.bin"): every file there that isn't .js, .json or .wasm, at any size the game
|
|
197
|
+
* server's limit allows (GAME_SERVER_LIMITS). The same ArrayBuffer every time, shared by every room of the
|
|
198
|
+
* version that runs in the same place, so read it, never change it. Reading costs nothing: the file comes with
|
|
199
|
+
* the code. A real-time room's first tick has a start's CPU (GAME_SERVER_LIMITS.maximumStartCpuDurationMs) to
|
|
200
|
+
* build from it once. On your own server it's read from dataFolder (startServer). A path with no data file
|
|
201
|
+
* throws a bad_room_call.
|
|
202
|
+
*/
|
|
203
|
+
readDataFile(path: string): ArrayBuffer;
|
|
194
204
|
/**
|
|
195
205
|
* Check a purchase's receipt, as the game sent it, before delivering: its claims, or an error named
|
|
196
206
|
* ReceiptError with a code (wrong_game, bad_signature, ...); check error.name, not instanceof, since in
|
|
@@ -786,6 +796,27 @@ export declare function readJoinAnswer(answer: unknown): {
|
|
|
786
796
|
};
|
|
787
797
|
/** Everything a game server object may have, in the order the docs give them. Anything else is refused. */
|
|
788
798
|
export declare const GAME_SERVER_OPTIONS: readonly ["maximumPlayerCount", "maximumSpectatorCount", "ticksPerSec", "hostControlsEnabled", "idleCheck", "idleTimeoutSec", "awayMode", "seatHoldDurationSec", "stateSyncEnabled", "adultChatFilterEnabled", "reconnectTimeoutSec", "maximumRoomCountPerPlayer", "stateSaveIntervalSec", "setup", "onJoin", "canJoin", "onChat", "onMoved", "onLeave", "onSpectatorJoin", "onSpectatorLeave", "onAway", "onBack", "onMessage", "onBytes", "onPurchase", "onRefund", "onTick", "onEnding", "onEndingCancelled", "onRestored", "stateView", "onVersionUpdate", "onRoomMessage", "onRequest", "schedules", "onSchedule", "onWebhook"];
|
|
799
|
+
/**
|
|
800
|
+
* What a game server on Zaisma's rooms can be and use. Each is Cloudflare's own limit or what keeps a room responsive,
|
|
801
|
+
* never a judgement of the game: a call's CPU is the work between two ticks, a start's is the one-time work before a match.
|
|
802
|
+
*/
|
|
803
|
+
export declare const GAME_SERVER_LIMITS: {
|
|
804
|
+
/**
|
|
805
|
+
* Every file of the game server together, code and data files. Cloudflare takes a Worker of 64 MB, but a room holds the
|
|
806
|
+
* files in memory (128 MB, shared) while it hands them to the sandbox, so half of that is what a room can carry safely.
|
|
807
|
+
*/
|
|
808
|
+
readonly maximumSizeBytes: number;
|
|
809
|
+
/** Files in the zaisma-server/ folder: each is read once whenever a copy of the game server loads. */
|
|
810
|
+
readonly maximumFileCount: 500;
|
|
811
|
+
/** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
|
|
812
|
+
readonly maximumCallCpuDurationMs: 50;
|
|
813
|
+
/** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after either. */
|
|
814
|
+
readonly maximumStartCpuDurationMs: 5000;
|
|
815
|
+
/** CPU for the game server's top-level code (outside its handlers) as it loads: Cloudflare's own limit. Heavy work goes in the first tick. */
|
|
816
|
+
readonly maximumLoadCpuDurationMs: 1000;
|
|
817
|
+
/** Memory of one copy of the game server, which every room of the version running in the same place shares: Cloudflare's own limit. */
|
|
818
|
+
readonly maximumMemorySizeBytes: number;
|
|
819
|
+
};
|
|
789
820
|
export declare const ROOM_LIMITS: {
|
|
790
821
|
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
791
822
|
readonly maximumPlayerCount: 100;
|
|
@@ -1230,6 +1261,8 @@ export interface Transport {
|
|
|
1230
1261
|
database?: GameDatabase;
|
|
1231
1262
|
/** The game's secrets, as room.secrets. Without them, there are none. */
|
|
1232
1263
|
secrets?: Readonly<Record<string, string>>;
|
|
1264
|
+
/** A data file by its path from the game server's folder, as room.readDataFile answers it, or null. Without it, there are none. */
|
|
1265
|
+
findDataFile?(dataFilePath: string): ArrayBuffer | null;
|
|
1233
1266
|
/** room.verifyReceipt, with Zaisma's keys and this game filled in. Without it, it throws, saying so. */
|
|
1234
1267
|
verifyReceipt?(receipt: string): Promise<ReceiptClaims>;
|
|
1235
1268
|
/** room.applyVersionUpdate(): switch to the version coming now. Without it (your own server), it does nothing. */
|
|
@@ -1245,9 +1278,11 @@ export interface Transport {
|
|
|
1245
1278
|
* The game server's server (onRequest, onSchedule, onWebhook) from what the runtime gives it: its calls to the game's
|
|
1246
1279
|
* rooms checked as a room's are, then made through roomReach, or throwing room_call_unavailable without one.
|
|
1247
1280
|
*/
|
|
1248
|
-
export declare function newServer(serverParts: Pick<Server, "database" | "secrets" | "verifyReceipt">, roomReach?: ServerRoomReach): Server;
|
|
1281
|
+
export declare function newServer(serverParts: Pick<Server, "database" | "secrets" | "verifyReceipt"> & Pick<Transport, "findDataFile">, roomReach?: ServerRoomReach): Server;
|
|
1249
1282
|
/** room.secrets and server.secrets where a game has none. */
|
|
1250
1283
|
export declare const NO_SECRETS: Readonly<Record<string, string>>;
|
|
1284
|
+
/** No data files: room.readDataFile and server.readDataFile find none. */
|
|
1285
|
+
export declare const NO_DATA_FILES: () => ArrayBuffer | null;
|
|
1251
1286
|
/** room.verifyReceipt and server.verifyReceipt where the runtime has no receipt keys. */
|
|
1252
1287
|
export declare const NO_RECEIPT_CHECK: () => Promise<ReceiptClaims>;
|
|
1253
1288
|
/**
|
package/src/room.js
CHANGED
|
@@ -135,6 +135,27 @@ export const GAME_SERVER_OPTIONS = [
|
|
|
135
135
|
"onSchedule",
|
|
136
136
|
"onWebhook",
|
|
137
137
|
];
|
|
138
|
+
/**
|
|
139
|
+
* What a game server on Zaisma's rooms can be and use. Each is Cloudflare's own limit or what keeps a room responsive,
|
|
140
|
+
* never a judgement of the game: a call's CPU is the work between two ticks, a start's is the one-time work before a match.
|
|
141
|
+
*/
|
|
142
|
+
export const GAME_SERVER_LIMITS = {
|
|
143
|
+
/**
|
|
144
|
+
* Every file of the game server together, code and data files. Cloudflare takes a Worker of 64 MB, but a room holds the
|
|
145
|
+
* files in memory (128 MB, shared) while it hands them to the sandbox, so half of that is what a room can carry safely.
|
|
146
|
+
*/
|
|
147
|
+
maximumSizeBytes: 32 * 1024 * 1024,
|
|
148
|
+
/** Files in the zaisma-server/ folder: each is read once whenever a copy of the game server loads. */
|
|
149
|
+
maximumFileCount: 500,
|
|
150
|
+
/** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
|
|
151
|
+
maximumCallCpuDurationMs: 50,
|
|
152
|
+
/** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after either. */
|
|
153
|
+
maximumStartCpuDurationMs: 5000,
|
|
154
|
+
/** CPU for the game server's top-level code (outside its handlers) as it loads: Cloudflare's own limit. Heavy work goes in the first tick. */
|
|
155
|
+
maximumLoadCpuDurationMs: 1000,
|
|
156
|
+
/** Memory of one copy of the game server, which every room of the version running in the same place shares: Cloudflare's own limit. */
|
|
157
|
+
maximumMemorySizeBytes: 128 * 1024 * 1024,
|
|
158
|
+
};
|
|
138
159
|
export const ROOM_LIMITS = {
|
|
139
160
|
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
140
161
|
maximumPlayerCount: 100,
|
|
@@ -376,6 +397,7 @@ export function newServer(serverParts, roomReach) {
|
|
|
376
397
|
return {
|
|
377
398
|
database: serverParts.database,
|
|
378
399
|
secrets: serverParts.secrets,
|
|
400
|
+
readDataFile: (path) => checks.readDataFile(path, serverParts.findDataFile ?? NO_DATA_FILES, "server.readDataFile"),
|
|
379
401
|
verifyReceipt: serverParts.verifyReceipt,
|
|
380
402
|
sendToRoom: (roomCode, message) => {
|
|
381
403
|
const reach = reachFor("server.sendToRoom");
|
|
@@ -418,6 +440,8 @@ export function newServer(serverParts, roomReach) {
|
|
|
418
440
|
}
|
|
419
441
|
/** room.secrets and server.secrets where a game has none. */
|
|
420
442
|
export const NO_SECRETS = Object.freeze({});
|
|
443
|
+
/** No data files: room.readDataFile and server.readDataFile find none. */
|
|
444
|
+
export const NO_DATA_FILES = () => null;
|
|
421
445
|
/** room.verifyReceipt and server.verifyReceipt where the runtime has no receipt keys. */
|
|
422
446
|
export const NO_RECEIPT_CHECK = () => Promise.reject(new Error("Receipts can't be checked here: run the game server in Zaisma rooms or with the Node runner (npx @zaisma/game-server), or call verifyReceipt with the keys from https://rooms.zaisma.com/.well-known/receipt-jwks.json and issuer https://rooms.zaisma.com/receipts."));
|
|
423
447
|
/** room.database where the room has no database: every call fails, saying so. */
|
|
@@ -1040,6 +1064,7 @@ export class RoomCore {
|
|
|
1040
1064
|
listRooms: (roomSelection) => this.roomReachFor("room.listRooms").listRooms(checks.checkRoomSelection(roomSelection, "room.listRooms").labels),
|
|
1041
1065
|
database: transport.database ?? NO_DATABASE,
|
|
1042
1066
|
secrets: transport.secrets ?? NO_SECRETS,
|
|
1067
|
+
readDataFile: (path) => checks.readDataFile(path, transport.findDataFile ?? NO_DATA_FILES, "room.readDataFile"),
|
|
1043
1068
|
verifyReceipt: transport.verifyReceipt ?? NO_RECEIPT_CHECK,
|
|
1044
1069
|
hasBlockBetween: (firstPlayerId, secondPlayerId) => this.hasBlockBetween(firstPlayerId, secondPlayerId),
|
|
1045
1070
|
areFriends: (firstPlayerId, secondPlayerId) => this.areFriends(firstPlayerId, secondPlayerId),
|
|
Binary file
|