@zaisma/game-server 1.38.0 → 1.40.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.
@@ -15,7 +15,11 @@ export const KEPT_SCRIPT_SOURCE = `try { new BroadcastChannel("zaisma").postMess
15
15
  var keptPlayerNumber = Number(new URL(document.currentScript.src).searchParams.get("player")) || 0;
16
16
  setTimeout(function () {
17
17
  if (window.opener) window.close();
18
- else location.replace(keptPlayerNumber ? "/?player=" + keptPlayerNumber : "/");
18
+ else {
19
+ // The dev page's own query (kept by the dev script for this tab) goes back with the player.
20
+ var rest = ""; try { rest = sessionStorage.getItem("zaisma-bench:query") || ""; } catch (error) {}
21
+ location.replace(keptPlayerNumber ? "/?player=" + keptPlayerNumber + (rest ? "&" + rest : "") : "/" + (rest ? "?" + rest : ""));
22
+ }
19
23
  }, 800);
20
24
  `;
21
25
 
@@ -23,10 +27,12 @@ setTimeout(function () {
23
27
  export const ARRIVE_SCRIPT_SOURCE = `(function () {
24
28
  var kept = null;
25
29
  try { kept = Number(sessionStorage.getItem("zaisma-bench:player")) || null; } catch (error) {}
26
- var room = /^[A-Z0-9]{6}$/.test(new URLSearchParams(location.search).get("room") || "") ? new URLSearchParams(location.search).get("room") : null;
30
+ // The page's own query goes through with the player (a room code only when it's a real one).
31
+ var rest = new URLSearchParams(location.search); rest.delete("player");
32
+ if (!/^[A-Z0-9]{6}$/.test(rest.get("room") || "")) rest.delete("room");
27
33
  fetch("/bench/claim", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ keptPlayerNumber: kept }) })
28
34
  .then(function (response) { return response.json(); })
29
- .then(function (answer) { location.replace("/?player=" + answer.playerNumber + (room ? "&room=" + room : "")); });
35
+ .then(function (answer) { location.replace("/?player=" + answer.playerNumber + (rest.toString() ? "&" + rest.toString() : "")); });
30
36
  })();
31
37
  `;
32
38
 
@@ -38,7 +44,12 @@ function devScript() {
38
44
  try {
39
45
  // The Players page a sign-in opened knows its player from the tab (a tab opened by a page starts with a copy of the page's storage).
40
46
  if (isPage && !playerNumber) playerNumber = Number(sessionStorage.getItem("zaisma-bench:player")) || 0;
41
- else sessionStorage.setItem("zaisma-bench:player", String(playerNumber));
47
+ else {
48
+ sessionStorage.setItem("zaisma-bench:player", String(playerNumber));
49
+ // The page's own query, besides the player, for the way back from a sign-in (KEPT_SCRIPT_SOURCE).
50
+ const rest = new URLSearchParams(location.search); rest.delete("player");
51
+ if (!isPage) sessionStorage.setItem("zaisma-bench:query", rest.toString());
52
+ }
42
53
  } catch {
43
54
  // Storage off: the tab is a new player each time it comes to /.
44
55
  }
package/bin/local-play.js CHANGED
@@ -1152,7 +1152,10 @@ export async function startLocalPlay(givenOptions) {
1152
1152
  // Back from a sign-in that left the page: into the room the player was in, while it's still going.
1153
1153
  const lastRoom = lastRoomCodes.get(givenNumber);
1154
1154
  if (!room && lastRoom && roomsTracked.has(lastRoom)) room = lastRoom;
1155
- const framePath = `/p/${givenNumber}/g/${gameSlug}${room ? `?room=${room}` : "?play"}`;
1155
+ // The page's own query goes on to the player's game page, as it would on zaisma.com.
1156
+ const rest = new URLSearchParams(url.searchParams);
1157
+ for (const name of ["player", "room", "play"]) rest.delete(name);
1158
+ const framePath = `/p/${givenNumber}/g/${gameSlug}${room ? `?room=${room}` : "?play"}${rest.size ? `&${rest}` : ""}`;
1156
1159
  return sendPage(response, await glass.devPage(placesFor(request), devViewFor(givenNumber), { path: framePath, allow: FRAME_ALLOW }));
1157
1160
  }
1158
1161
  if (url.pathname.startsWith("/bench/") && !/^\/bench\/(kept\.js|panel|api)(\/|$)/.test(url.pathname)) return await answerBench(request, response, url);
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@zaisma/game-server",
3
- "version": "1.38.0",
3
+ "version": "1.40.0",
4
4
  "description": "Run your Zaisma game server: the same rooms on Zaisma or on your own server.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "git+https://github.com/zaisma/zaisma.git",
9
+ "url": "git+https://github.com/zaisma/zaisma-sdk.git",
10
10
  "directory": "packages/game-server"
11
11
  },
12
- "bugs": "https://github.com/zaisma/zaisma/issues",
12
+ "bugs": "https://zaisma.com/forum",
13
13
  "keywords": [
14
14
  "zaisma",
15
15
  "games",
package/sdk/saves.js CHANGED
@@ -699,7 +699,7 @@
699
699
  if (/\/_zaisma\/restore$/.test(location.pathname)) {
700
700
  // The game starts at its root, with the query the game page passed (like ?room=ABC234).
701
701
  var query = decodeURIComponent(location.hash.slice(1));
702
- var target = new URL("../" + (/^\?[\w=&%-]*$/.test(query) ? query : ""), location.href).href;
702
+ var target = new URL("../" + (/^\?[\w=&%+.*~-]*$/.test(query) ? query : ""), location.href).href;
703
703
  var go = function () {
704
704
  location.replace(target);
705
705
  };
package/sdk/zaisma.d.ts CHANGED
@@ -918,7 +918,21 @@ declare namespace Zaisma {
918
918
  * @example
919
919
  * const room = await Zaisma.joinRoom({ isSpectator: Zaisma.rooms.isLinkedAsSpectator });
920
920
  */
921
- isSpectator?: boolean;
921
+ isSpectator?: boolean; /**
922
+ * true (the default): what the game sends at once (in one frame of its loop, say) goes to the room as one
923
+ * message of up to 8, and sends keep under the room's 30 a second by themselves: past that, they wait a few
924
+ * milliseconds and go together instead of coming back "too_fast". Each still reaches the game server's
925
+ * onMessage on its own, in order. A room is billed for each message it gets, so this costs the game less.
926
+ * Rooms on your own server combine only when their game server says it can (game server 1.40 and later).
927
+ * false: every send goes alone and at once, as it's made.
928
+ */
929
+ sendCombiningEnabled?: boolean;
930
+ /**
931
+ * true (the default): a { delivery: "latest_only" } send that's the same as the last one with its latestKey
932
+ * isn't sent, since the room already has it; the first after a reconnect always goes. Reliable sends always go.
933
+ * false: send every one, as when the game server expects a steady stream.
934
+ */
935
+ unchangedSkippingEnabled?: boolean;
922
936
  }
923
937
 
924
938
  /**
@@ -1177,7 +1191,9 @@ declare namespace Zaisma {
1177
1191
  * 30 a second at most. Send input when it changes, not every frame. While connectionStatus isn't "open"
1178
1192
  * or the player is away, reliable sends wait and go in order once the room is back, up to 60: past that
1179
1193
  * the oldest is dropped, and an "error" event says "send_queue_full" once. With
1180
- * { delivery: "latest_only", latestKey }, a message may be dropped for a newer one (SendOptions). A
1194
+ * { delivery: "latest_only", latestKey }, a message may be dropped for a newer one (SendOptions), and one
1195
+ * the same as the last with its latestKey isn't sent (JoinOptions.unchangedSkippingEnabled). What the game
1196
+ * sends at once goes as one message (JoinOptions.sendCombiningEnabled). A
1181
1197
  * spectator can't send: it throws error.code "spectator_cannot_send". Returns false only when the room
1182
1198
  * is gone (ended, kicked or left), so nothing will ever send.
1183
1199
  *
@@ -1759,8 +1775,9 @@ declare namespace Zaisma {
1759
1775
 
1760
1776
  /**
1761
1777
  * The codes the SDK's errors have: a room's ({@link RoomErrorCode}), and:
1762
- * - unchecked: no player pass, because the game isn't played on its zaisma.com page, Zaisma couldn't check the browser, or it's a preview
1763
- * of a version players don't have yet (its message says so: test online play with play-locally or a tester link).
1778
+ * - unchecked: no player pass, because the game isn't played on its zaisma.com page or Zaisma couldn't check the browser.
1779
+ * - no_online_play_in_preview: no player pass, because the game is a preview of a version players don't have yet, so a test build never
1780
+ * reaches live rooms. Test online play with `npx @zaisma/cli play-locally`, or publish the version and play it through a tester link.
1764
1781
  * - unknown_option, unknown_event: a call the SDK doesn't take; the message lists what it does.
1765
1782
  * - slow_down: too many calls; try again in a minute.
1766
1783
  * - zaisma_rooms_not_used: the game doesn't use Zaisma rooms.
@@ -1801,6 +1818,7 @@ declare namespace Zaisma {
1801
1818
  | "chat_too_fast"
1802
1819
  | "chat_not_here"
1803
1820
  | "unchecked"
1821
+ | "no_online_play_in_preview"
1804
1822
  | "unknown_option"
1805
1823
  | "unknown_event"
1806
1824
  | "slow_down"
package/sdk/zaisma.js CHANGED
@@ -22,9 +22,9 @@
22
22
 
23
23
  // What each call takes. Anything else is refused, so a misspelled or old option never goes quietly unused.
24
24
  var SET_UP_OFF_ZAISMA_OPTIONS = ["gameSlug", "playerToken"];
25
- var JOIN_OPTIONS = ["roomCode", "serverUrl", "transport", "isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "isSpectator"];
25
+ var JOIN_OPTIONS = ["roomCode", "serverUrl", "transport", "isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "isSpectator", "sendCombiningEnabled", "unchangedSkippingEnabled"];
26
26
  // quickJoin finds Zaisma rooms, so it takes no serverUrl.
27
- var QUICK_JOIN_OPTIONS = ["isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "region"];
27
+ var QUICK_JOIN_OPTIONS = ["isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "sendCombiningEnabled", "unchangedSkippingEnabled", "region"];
28
28
  var LIST_OPTIONS = ["region", "labels"];
29
29
  // move.join joins the room the move names, on this room's server and over its transport, as a player: the game server moves only players.
30
30
  var MOVE_JOIN_OPTIONS = JOIN_OPTIONS.filter(function (name) { return name !== "roomCode" && name !== "serverUrl" && name !== "transport" && name !== "isSpectator"; });
@@ -70,6 +70,20 @@
70
70
  var VERSION_UPDATE_CLOSE_CODE = 4004;
71
71
  /** A real-time room's ping from this on shows as a weak connection beside the game. */
72
72
  var WEAK_PING_MS = 150;
73
+ /**
74
+ * Combining (joinRoom's sendCombiningEnabled, on unless the game turns it off, in a room whose welcome says
75
+ * canCombineMessages): what a game sends at once leaves as one frame of up to this many messages, and frames
76
+ * keep under the room's 30 a second with a burst of 60, here 25 with a burst of 40, leaving room for Zaisma's own.
77
+ * Past it, sends wait and go combined in the next frame instead of coming back too_fast.
78
+ */
79
+ var MAXIMUM_COMBINED_MESSAGE_COUNT = 8;
80
+ var PACED_FRAMES_PER_SEC = 25;
81
+ var PACED_FRAME_BURST_COUNT = 40;
82
+ /** The messages inside those frames, under the room's 120 a second with a burst of 240. */
83
+ var PACED_MESSAGES_PER_SEC = 100;
84
+ var PACED_MESSAGE_BURST_COUNT = 200;
85
+ /** An unchanged latest-only send still goes as a datagram this often on the fast lane, since a datagram can be lost. */
86
+ var UNCHANGED_DATAGRAM_INTERVAL_MS = 250;
73
87
  /** A latest-only send waits while the socket holds this much not yet sent, checked every LATEST_CHECK_MS. */
74
88
  var BACKED_UP_SIZE_BYTES = 64 * 1024;
75
89
  var LATEST_CHECK_MS = 50;
@@ -192,6 +206,7 @@
192
206
  var passPromise = null;
193
207
  var keyPromise = null;
194
208
  var UNCHECKED = "Zaisma couldn't check this browser, so it can't play online. Reload the game to try again.";
209
+ var NO_ONLINE_PLAY_IN_PREVIEW = "Online play is off in a preview of a version players don't have yet. Test online play with npx @zaisma/cli play-locally, or publish the version and play it through a tester link.";
195
210
 
196
211
  /**
197
212
  * The game page's key to player passes, as { key, playerKind }: whose passes it gives, the signed-in
@@ -202,6 +217,7 @@
202
217
  if (!keyPromise) {
203
218
  keyPromise = new Promise(function (resolve, reject) {
204
219
  function fail(message) { reject(codedError("unchecked", message)); }
220
+ function failInPreview(message) { reject(codedError("no_online_play_in_preview", message)); }
205
221
  if (!config.site || window.parent === window) return fail("Online play works when the game is played on Zaisma.");
206
222
  // The check usually answers in a second or two, or asks the player to tap a box.
207
223
  var timer = setTimeout(function () { removeEventListener("message", onMessage); fail(UNCHECKED); }, 30000);
@@ -210,8 +226,9 @@
210
226
  removeEventListener("message", onMessage);
211
227
  clearTimeout(timer);
212
228
  if (typeof event.data.key === "string") resolve({ key: event.data.key, playerKind: event.data.playerKind === "account" ? "account" : "guest" });
213
- // The page may say why it has no key (a preview of a version players don't have yet), instead of the browser check.
214
- else fail(typeof event.data.message === "string" && event.data.message ? event.data.message.slice(0, 300) : UNCHECKED);
229
+ // A preview of a version players don't have yet has no key on purpose, and the page says so, instead of the browser check.
230
+ else if (event.data.code === "no_online_play_in_preview") failInPreview(typeof event.data.message === "string" && event.data.message ? event.data.message.slice(0, 300) : NO_ONLINE_PLAY_IN_PREVIEW);
231
+ else fail(UNCHECKED);
215
232
  }
216
233
  addEventListener("message", onMessage);
217
234
  window.parent.postMessage({ type: "zaisma:room-key" }, config.site);
@@ -559,6 +576,19 @@
559
576
  // Latest-only sends waiting for the socket to drain, by "<kind>:<latestKey>", least recently replaced first.
560
577
  this._slots = new Map();
561
578
  this._slotTimer = null;
579
+ // Combining: whether the game left it on, whether this connection's room takes combined frames (from welcome),
580
+ // the game messages waiting for the end of this task or for the pace ({ dataText, latestKey }), and the pace's bucket.
581
+ this._sendCombiningEnabled = setup.sendCombiningEnabled !== false;
582
+ this._canCombine = false;
583
+ this._outbox = [];
584
+ this._isOutboxDue = false;
585
+ this._outboxTimer = null;
586
+ this._paceTokenCount = PACED_FRAME_BURST_COUNT;
587
+ this._messageTokenCount = PACED_MESSAGE_BURST_COUNT;
588
+ this._pacedAtMs = Date.now();
589
+ // Unchanged latest-only sends are skipped (unchangedSkippingEnabled): the last one given for each slot on this connection.
590
+ this._unchangedSkippingEnabled = setup.unchangedSkippingEnabled !== false;
591
+ this._lastLatest = new Map();
562
592
  // Reliable sends waiting for the connection, in order, and whether this outage already said some were dropped.
563
593
  this._queue = [];
564
594
  this._flushTimer = null;
@@ -738,6 +768,8 @@
738
768
 
739
769
  /** Send a message to the room if the connection is open. */
740
770
  Room.prototype._say = function (message) {
771
+ // Game messages waiting in the outbox go first, so the room hears everything in the order it was said.
772
+ if (this._isWelcomed) this._flushOutbox(true);
741
773
  if (!this._ws || this._ws.readyState !== 1) return;
742
774
  this._ws.send(JSON.stringify(message));
743
775
  this._sentAtMs = Date.now();
@@ -820,6 +852,10 @@
820
852
  room._probeIntervalSec = typeof message.probeIntervalSec === "number" ? message.probeIntervalSec : null;
821
853
  room.spectatorCount = typeof message.spectatorCount === "number" ? message.spectatorCount : 0;
822
854
  room.canChat = message.canChat === true && !room.isSpectator;
855
+ // A room that doesn't say so (an older game server of the game's own) gets one message a frame, as before.
856
+ room._canCombine = message.canCombineMessages === true;
857
+ // A new connection: the first latest-only send of each kind goes, whatever went before.
858
+ room._lastLatest = new Map();
823
859
  room._away = room._gone = room._idleSent = room._coming = room._offered = room._isReloadingForVersion = false;
824
860
  room.awayReason = null;
825
861
  room._isQueueFullSaid = false;
@@ -1036,19 +1072,158 @@
1036
1072
  /**
1037
1073
  * Send a message to the game server. Plain JSON, up to 16 KB. Send input when it changes, not every frame.
1038
1074
  * While the connection isn't open or the player is away, reliable sends wait, in order (up to 60).
1039
- * { delivery: "latest_only", latestKey } may drop it for a newer one with the same latestKey. False once the room is gone.
1075
+ * { delivery: "latest_only", latestKey } may drop it for a newer one with the same latestKey, and one the same as
1076
+ * the last for its latestKey isn't sent (joinRoom's unchangedSkippingEnabled). What the game sends at once goes in
1077
+ * one frame, kept under the room's limit (joinRoom's sendCombiningEnabled). False once the room is gone.
1040
1078
  */
1041
1079
  Room.prototype.send = function (message, sendOptions) {
1042
1080
  if (this.isSpectator) throw spectatorCannotSend();
1043
1081
  var latestKey = readDelivery(sendOptions, "room.send");
1044
- var payload = JSON.stringify({ type: "message", data: message });
1082
+ var dataText = JSON.stringify(message);
1083
+ var payload = dataText === undefined ? JSON.stringify({ type: "message" }) : '{"type":"message","data":' + dataText + "}";
1045
1084
  checkSendSize(payload);
1046
1085
  if (this._done) return false;
1047
- if (latestKey !== null) this._sendLatest("message:" + latestKey, payload);
1086
+ var isCombined = dataText !== undefined && this._combines();
1087
+ if (latestKey !== null) {
1088
+ var slotKey = "message:" + latestKey;
1089
+ if (this._isUnchanged(slotKey, payload)) return true;
1090
+ // On the fast lane a latest-only send goes as a datagram, which is never held for a frame.
1091
+ if (isCombined && !this._ws.sendDatagram) this._putInOutbox(dataText, latestKey);
1092
+ else this._sendLatest(slotKey, payload);
1093
+ } else if (isCombined) this._putInOutbox(dataText, null);
1048
1094
  else this._sendReliable(payload);
1049
1095
  return true;
1050
1096
  };
1051
1097
 
1098
+ /** Whether a game message goes through the outbox now: combining on, the room takes it, and nothing waiting for the connection. */
1099
+ Room.prototype._combines = function () {
1100
+ return this._sendCombiningEnabled && this._canCombine && this._canSend() && !this._queue.length;
1101
+ };
1102
+
1103
+ /**
1104
+ * Whether a latest-only send is the same as the last one given for its slot on this connection, so it needn't go.
1105
+ * Noted either way: what was given last is what goes, now or from its slot. A datagram may be lost, so one repeats now and then.
1106
+ */
1107
+ Room.prototype._isUnchanged = function (slotKey, sentValue) {
1108
+ if (!this._unchangedSkippingEnabled) return false;
1109
+ var nowMs = Date.now();
1110
+ var last = this._lastLatest.get(slotKey);
1111
+ var isDatagram = Boolean(this._ws && this._ws.sendDatagram);
1112
+ if (last && sameValue(last.sentValue, sentValue) && !(last.isDatagram && nowMs - last.givenAtMs >= UNCHANGED_DATAGRAM_INTERVAL_MS)) return true;
1113
+ this._lastLatest.set(slotKey, { sentValue: sentValue, givenAtMs: nowMs, isDatagram: isDatagram });
1114
+ return false;
1115
+ };
1116
+ /** Text or bytes, the same. */
1117
+ function sameValue(first, second) {
1118
+ if (typeof first === "string" || typeof second === "string") return first === second;
1119
+ if (first.byteLength !== second.byteLength) return false;
1120
+ var firstBytes = new Uint8Array(first);
1121
+ var secondBytes = new Uint8Array(second);
1122
+ for (var i = 0; i < firstBytes.length; i++) if (firstBytes[i] !== secondBytes[i]) return false;
1123
+ return true;
1124
+ }
1125
+
1126
+ /** The pace's tokens now, refilled at PACED_FRAMES_PER_SEC up to PACED_FRAME_BURST_COUNT. */
1127
+ Room.prototype._paceTokens = function () {
1128
+ var nowMs = Date.now();
1129
+ var elapsedSec = (nowMs - this._pacedAtMs) / 1000;
1130
+ this._paceTokenCount = Math.min(PACED_FRAME_BURST_COUNT, this._paceTokenCount + elapsedSec * PACED_FRAMES_PER_SEC);
1131
+ this._messageTokenCount = Math.min(PACED_MESSAGE_BURST_COUNT, this._messageTokenCount + elapsedSec * PACED_MESSAGES_PER_SEC);
1132
+ this._pacedAtMs = nowMs;
1133
+ return this._paceTokenCount;
1134
+ };
1135
+ /**
1136
+ * Frames that went, combined or not, and the messages in them: they count against the pace, so bytes and JSON together keep
1137
+ * under the room's limit. Never below empty: what went without waiting (bytes, datagrams) doesn't hold the outbox back for long.
1138
+ */
1139
+ Room.prototype._spendPace = function (frameCount, messageCount) {
1140
+ this._paceTokens();
1141
+ this._paceTokenCount = Math.max(0, this._paceTokenCount - frameCount);
1142
+ this._messageTokenCount = Math.max(0, this._messageTokenCount - (messageCount || 0));
1143
+ };
1144
+
1145
+ /** A game message into the outbox: a latest-only one replaces a waiting one with its latestKey, and reliable ones wait up to 60. */
1146
+ Room.prototype._putInOutbox = function (dataText, latestKey) {
1147
+ var waiting = latestKey === null ? null : this._outbox.filter(function (entry) { return entry.latestKey === latestKey; })[0];
1148
+ if (waiting) waiting.dataText = dataText;
1149
+ else this._outbox.push({ dataText: dataText, latestKey: latestKey });
1150
+ var reliable = this._outbox.filter(function (entry) { return entry.latestKey === null; });
1151
+ if (reliable.length > MAXIMUM_QUEUED_SEND_COUNT) {
1152
+ this._outbox.splice(this._outbox.indexOf(reliable[0]), 1);
1153
+ if (!this._isQueueFullSaid) {
1154
+ this._isQueueFullSaid = true;
1155
+ this._emit("error", { code: "send_queue_full", message: "Up to " + MAXIMUM_QUEUED_SEND_COUNT + " sends wait to go; older ones were dropped. Send less often." });
1156
+ }
1157
+ }
1158
+ if (this._isOutboxDue || this._outboxTimer !== null) return;
1159
+ this._isOutboxDue = true;
1160
+ var room = this;
1161
+ queueMicrotask(function () {
1162
+ room._isOutboxDue = false;
1163
+ room._flushOutbox(false);
1164
+ });
1165
+ };
1166
+
1167
+ /**
1168
+ * The outbox goes: combined into frames of up to 8 messages and 16 KB, as many frames as the pace allows, the rest at its
1169
+ * next token. Forced (before a send that isn't combined, to keep the order), all of it now. With the connection gone,
1170
+ * its messages wait as uncombined sends do.
1171
+ */
1172
+ Room.prototype._flushOutbox = function (isForced) {
1173
+ if (!this._outbox.length) return;
1174
+ var entries;
1175
+ var room = this;
1176
+ if (this._done || !this._canSend() || this._queue.length) {
1177
+ entries = this._outbox;
1178
+ this._outbox = [];
1179
+ this._clearOutboxTimer();
1180
+ if (this._done) return;
1181
+ entries.forEach(function (entry) {
1182
+ var payload = '{"type":"message","data":' + entry.dataText + "}";
1183
+ if (entry.latestKey === null) room._sendReliable(payload);
1184
+ else room._slotLatest("message:" + entry.latestKey, payload);
1185
+ });
1186
+ return;
1187
+ }
1188
+ // Latest-only messages wait in their slots while the socket is backed up, as uncombined ones do.
1189
+ if (this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES) {
1190
+ this._outbox = this._outbox.filter(function (entry) {
1191
+ if (entry.latestKey === null) return true;
1192
+ room._slotLatest("message:" + entry.latestKey, '{"type":"message","data":' + entry.dataText + "}");
1193
+ return false;
1194
+ });
1195
+ }
1196
+ while (this._outbox.length && (isForced || (this._paceTokens() >= 1 && this._messageTokenCount >= 1))) {
1197
+ var frame = [];
1198
+ var frameSizeBytes = '{"type":"messages","data":[]}'.length;
1199
+ var maximumMessageCount = isForced ? MAXIMUM_COMBINED_MESSAGE_COUNT : Math.min(MAXIMUM_COMBINED_MESSAGE_COUNT, Math.floor(this._messageTokenCount));
1200
+ while (this._outbox.length && frame.length < maximumMessageCount) {
1201
+ var sizeBytes = utf8SizeOf(this._outbox[0].dataText) + 1;
1202
+ if (frame.length && frameSizeBytes + sizeBytes > MAXIMUM_SEND_SIZE_BYTES) break;
1203
+ frame.push(this._outbox.shift().dataText);
1204
+ frameSizeBytes += sizeBytes;
1205
+ }
1206
+ this._ws.send(frame.length === 1 ? '{"type":"message","data":' + frame[0] + "}" : '{"type":"messages","data":[' + frame.join(",") + "]}");
1207
+ this._spendPace(1, frame.length);
1208
+ this._sentAtMs = Date.now();
1209
+ }
1210
+ this._clearOutboxTimer();
1211
+ if (!this._outbox.length) return;
1212
+ this._outboxTimer = setTimeout(function () {
1213
+ room._outboxTimer = null;
1214
+ room._flushOutbox(false);
1215
+ }, Math.max(1, Math.ceil(Math.max((1 - this._paceTokenCount) / PACED_FRAMES_PER_SEC, (1 - this._messageTokenCount) / PACED_MESSAGES_PER_SEC) * 1000)));
1216
+ };
1217
+ Room.prototype._clearOutboxTimer = function () {
1218
+ if (this._outboxTimer === null) return;
1219
+ clearTimeout(this._outboxTimer);
1220
+ this._outboxTimer = null;
1221
+ };
1222
+ /** Text's size in UTF-8, measured only when it could matter. */
1223
+ function utf8SizeOf(text) {
1224
+ return text.length * 3 <= 1024 ? text.length * 3 : new TextEncoder().encode(text).length;
1225
+ }
1226
+
1052
1227
  /**
1053
1228
  * Send bytes to the game server (its onBytes), like a compact input: an ArrayBuffer or any typed array,
1054
1229
  * up to 16 KB, counted with messages (30 a second). Takes the same sendOptions as room.send.
@@ -1061,8 +1236,10 @@
1061
1236
  if (this._done) return false;
1062
1237
  // A copy: the game may reuse its buffer while this one waits.
1063
1238
  var copy = ArrayBuffer.isView(bytes) ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) : bytes.slice(0);
1064
- if (latestKey !== null) this._sendLatest("bytes:" + latestKey, copy);
1065
- else this._sendReliable(copy);
1239
+ if (latestKey !== null) {
1240
+ if (this._isUnchanged("bytes:" + latestKey, copy)) return true;
1241
+ this._sendLatest("bytes:" + latestKey, copy);
1242
+ } else this._sendReliable(copy);
1066
1243
  return true;
1067
1244
  };
1068
1245
 
@@ -1078,8 +1255,11 @@
1078
1255
 
1079
1256
  /** A reliable send: now, or in order once the connection is open again, dropping the oldest past 60. */
1080
1257
  Room.prototype._sendReliable = function (payload) {
1258
+ // Game messages waiting in the outbox go first, so everything keeps its order.
1259
+ this._flushOutbox(true);
1081
1260
  if (this._canSend() && !this._queue.length) {
1082
1261
  this._ws.send(payload);
1262
+ this._spendPace(1);
1083
1263
  this._sentAtMs = Date.now();
1084
1264
  return;
1085
1265
  }
@@ -1096,7 +1276,9 @@
1096
1276
  var room = this;
1097
1277
  var ws = this._ws;
1098
1278
  function send(sendCount) {
1099
- room._queue.splice(0, sendCount).forEach(function (payload) { ws.send(payload); });
1279
+ var sent = room._queue.splice(0, sendCount);
1280
+ sent.forEach(function (payload) { ws.send(payload); });
1281
+ room._spendPace(sent.length);
1100
1282
  room._sentAtMs = Date.now();
1101
1283
  }
1102
1284
  send(FLUSH_NOW_COUNT);
@@ -1127,20 +1309,32 @@
1127
1309
 
1128
1310
  /** A latest-only send: now, after anything still waiting, or into its slot while the socket is backed up. */
1129
1311
  Room.prototype._sendLatest = function (slotKey, payload) {
1312
+ this._flushOutbox(true);
1130
1313
  // On the fast lane, a datagram: a late one is lost rather than waited for, so it skips the slots.
1131
1314
  if (this._canSend() && !this._queue.length && this._ws.sendDatagram && this._ws.sendDatagram(payload)) {
1315
+ this._spendPace(1);
1132
1316
  this._sentAtMs = Date.now();
1133
1317
  return;
1134
1318
  }
1135
1319
  if (this._canSend() && !this._queue.length && !(this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES)) {
1136
1320
  this._sendWaiting();
1137
1321
  this._ws.send(payload);
1322
+ this._spendPace(1);
1138
1323
  this._sentAtMs = Date.now();
1139
1324
  return;
1140
1325
  }
1326
+ this._slotLatest(slotKey, payload);
1327
+ };
1328
+ /** A latest-only send into its slot, to go once the socket drains: the slot keeps only the newest. */
1329
+ Room.prototype._slotLatest = function (slotKey, payload) {
1141
1330
  this._slots.delete(slotKey);
1142
1331
  this._slots.set(slotKey, payload);
1143
- if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT) this._slots.delete(this._slots.keys().next().value);
1332
+ if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT) {
1333
+ var evictedKey = this._slots.keys().next().value;
1334
+ this._slots.delete(evictedKey);
1335
+ // It never went: the next send with its latestKey goes, the same or not.
1336
+ this._lastLatest.delete(evictedKey);
1337
+ }
1144
1338
  if (this._slotTimer === null) {
1145
1339
  var room = this;
1146
1340
  this._slotTimer = setInterval(function () {
@@ -1155,6 +1349,7 @@
1155
1349
  if (!this._slots.size || !this._canSend() || this._queue.length) return;
1156
1350
  var ws = this._ws;
1157
1351
  this._slots.forEach(function (payload) { ws.send(payload); });
1352
+ this._spendPace(this._slots.size);
1158
1353
  this._slots.clear();
1159
1354
  this._sentAtMs = Date.now();
1160
1355
  };
@@ -1343,6 +1538,8 @@
1343
1538
  this._views = [];
1344
1539
  this._slots.clear();
1345
1540
  this._queue = [];
1541
+ this._outbox = [];
1542
+ this._clearOutboxTimer();
1346
1543
  this._sayRoomToPage();
1347
1544
  this._setConnectionStatus("connecting");
1348
1545
  this._emit("moved", { roomCode: roomCode, fromRoomCode: fromRoomCode });
@@ -1615,6 +1812,8 @@
1615
1812
  if (!this._done) left(this);
1616
1813
  this._done = true;
1617
1814
  this._queue = [];
1815
+ this._outbox = [];
1816
+ this._clearOutboxTimer();
1618
1817
  this._failChats();
1619
1818
  if (this._ws) this._ws.close(1000, "Left");
1620
1819
  };
@@ -1634,6 +1833,8 @@
1634
1833
  var isOffZaisma = !config.rooms;
1635
1834
  var idleTimeoutSec = joinOptions.idleTimeoutSec;
1636
1835
  if (idleTimeoutSec !== undefined && !(typeof idleTimeoutSec === "number" && idleTimeoutSec >= MINIMUM_IDLE_TIMEOUT_SEC && idleTimeoutSec <= MAXIMUM_IDLE_TIMEOUT_SEC)) return Promise.reject(codedError("bad_idle_timeout", "idleTimeoutSec runs from " + MINIMUM_IDLE_TIMEOUT_SEC + " to " + MAXIMUM_IDLE_TIMEOUT_SEC + "."));
1836
+ var badSwitch = ["sendCombiningEnabled", "unchangedSkippingEnabled"].filter(function (name) { return joinOptions[name] !== undefined && typeof joinOptions[name] !== "boolean"; })[0];
1837
+ if (badSwitch) return Promise.reject(codedError("unknown_option", badSwitch + " is " + JSON.stringify(joinOptions[badSwitch]) + ". Give true (the default) or false."));
1637
1838
  if (serverUrl && !SERVER_URL.test(serverUrl)) return Promise.reject(codedError("bad_server_url", "serverUrl takes a full address starting with wss://, ws://, https:// or http://, like \"wss://play.example.com\"."));
1638
1839
  if (joinOptions.transport !== undefined && TRANSPORTS.indexOf(joinOptions.transport) === -1) return Promise.reject(codedError("bad_transport", "transport is " + JSON.stringify(joinOptions.transport) + '. Give "websocket" (the default) or "webtransport" (the fast lane to your own server).'));
1639
1840
  if (roomCode && !ROOM_CODE.test(roomCode)) return Promise.reject(codedError("bad_room_code", JSON.stringify(roomCode) + " isn't a room code: room codes are six characters like \"K7Q2MX\", from 2 to 9 and A to Z without I or O."));
@@ -1660,6 +1861,8 @@
1660
1861
  labels: joinOptions.labels,
1661
1862
  joinData: joinOptions.joinData,
1662
1863
  clientIdle: clientIdle(joinOptions),
1864
+ sendCombiningEnabled: joinOptions.sendCombiningEnabled,
1865
+ unchangedSkippingEnabled: joinOptions.unchangedSkippingEnabled,
1663
1866
  serverUrl: serverUrl,
1664
1867
  isSpectator: joinOptions.isSpectator === true,
1665
1868
  });
package/src/room.d.ts CHANGED
@@ -823,7 +823,7 @@ export declare const GAME_SERVER_LIMITS: {
823
823
  readonly maximumMemorySizeBytes: number;
824
824
  };
825
825
  export declare const ROOM_LIMITS: {
826
- /** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
826
+ /** Players in one room: what one room carries at 60 ticks a second in the local test (test/load/room-load.test.ts); in the first runs on Cloudflare, a room held 60 up to about 50 players and made about 40 past 70. */
827
827
  readonly maximumPlayerCount: 100;
828
828
  readonly defaultMaximumPlayerCount: 8;
829
829
  /** Spectators in one room: each send costs the room time, so its audience is bounded like its players. Bigger audiences are a stream. */
@@ -850,6 +850,11 @@ export declare const ROOM_LIMITS: {
850
850
  */
851
851
  readonly maximumGameMessagesPerSec: 30;
852
852
  readonly maximumGameMessageBurstCount: 60;
853
+ /** Game messages one combined frame ({ type: "messages" }) carries at most: the frame takes one of the 30 a second. */
854
+ readonly maximumCombinedMessageCount: 8;
855
+ /** The messages inside combined frames, per second per player, with a burst: what bounds a player's onMessage calls. */
856
+ readonly maximumCombinedGameMessagesPerSec: 120;
857
+ readonly maximumCombinedGameMessageBurstCount: 240;
853
858
  /** The idle check's default and range (idleTimeoutSec, joinRoom({ idleTimeoutSec })). */
854
859
  readonly defaultIdleTimeoutSec: 600;
855
860
  readonly minimumIdleTimeoutSec: 30;
@@ -948,7 +953,9 @@ export interface RoomSettings {
948
953
  * Clients send {type: "hello", protocolVersionNumber, pass, joinData?, room?: {isListed?, friendJoinsEnabled?, name?, labels?}, idleTimeoutSec?,
949
954
  * idleCheckEnabled?} first (ClientMessage; joinData is for canJoin and onJoin; the room's settings only count from
950
955
  * the player who makes it, and a room is listed only when its first player's hello says isListed: true;
951
- * the idle fields only where the game server's idleCheck is "client"), then {type: "message", data}.
956
+ * the idle fields only where the game server's idleCheck is "client"), then {type: "message", data}, or, where
957
+ * welcome says canCombineMessages, {type: "messages", data: [2 to 8 messages]}: what the game sent at once, each
958
+ * reaching onMessage in order, the frame counting once toward the 30 a second and each message toward 120 a second.
952
959
  * With hostControlsEnabled, the host may also send {type: "room", room: {isListed?, isOpen?,
953
960
  * friendJoinsEnabled?, name?, labels?}} and {type: "kick", playerId, keepOut?}. hostPlayerId is null without host controls.
954
961
  *
@@ -1033,6 +1040,8 @@ export type ServerMessage = {
1033
1040
  probeIntervalSec: number | null;
1034
1041
  protocolVersionNumber: number;
1035
1042
  canChat: boolean;
1043
+ /** The room takes { type: "messages", data: [...] }: the SDK combines what a game sends at once only where this says so. */
1044
+ canCombineMessages: boolean;
1036
1045
  } | {
1037
1046
  type: "probe";
1038
1047
  probeNumber: number;
@@ -1456,6 +1465,7 @@ export declare const ROOM_MESSAGE_DOORS: {
1456
1465
  readonly shown: DoorContract;
1457
1466
  readonly back: DoorContract;
1458
1467
  readonly message: DoorContract;
1468
+ readonly messages: DoorContract;
1459
1469
  readonly bytes: {
1460
1470
  readonly whoMayCall: "room_player";
1461
1471
  readonly reaches: "room";
@@ -1610,6 +1620,7 @@ export declare class RoomCore<S = any> {
1610
1620
  /** When this room took room messages, within the last second (ROOM_MESSAGE_LIMITS.maximumReceivedRoomMessagesPerSec). */
1611
1621
  private roomReceivedAtMs;
1612
1622
  private buckets;
1623
+ private combinedBuckets;
1613
1624
  /** Probes this room has sent, to every player: each probe's number. */
1614
1625
  private probeCount;
1615
1626
  /** What each player was last sent of the state (stateSyncEnabled), unless the game server runs state sync itself (SYNCS_STATE). */
@@ -1883,6 +1894,12 @@ export declare class RoomCore<S = any> {
1883
1894
  * game has been hidden too long in a real-time room, walk away; held seats that ran out are freed,
1884
1895
  * and those players' connections close.
1885
1896
  */
1897
+ /**
1898
+ * When sweep next has something to do, in epoch milliseconds, or null: the earliest idle walk-away, held or
1899
+ * expected seat running out, probe answer timing out or reconnect running out. A host that sleeps between
1900
+ * sweeps (Zaisma's rooms) wakes for this instead of on a fixed timer. A stale ping waits for the next wake.
1901
+ */
1902
+ nextSweepAtMs(): number | null;
1886
1903
  sweep(): void;
1887
1904
  /** A raw text message from a client. Returns an error code if it was refused. */
1888
1905
  receive(playerId: string, text: string): RoomErrorCode | null;
@@ -2060,6 +2077,8 @@ export declare class RoomCore<S = any> {
2060
2077
  */
2061
2078
  private dropBehind;
2062
2079
  /** Token bucket per player: a short burst is fine, a flood is dropped. */
2080
+ /** The second bucket, for the messages inside combined frames: each takes one, so combining never lifts how often onMessage runs past its own limit. */
2081
+ private takeCombined;
2063
2082
  private take;
2064
2083
  /** A handler's answer becomes the state if it is one (a plain object or an array); nothing keeps the state, and anything else is a mistake that leaves it. */
2065
2084
  private keepAnswer;