@hypersoniclabs/helix-sdk 0.1.2 → 0.1.9
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/README.md +859 -8
- package/dist/action-surface.d.ts +182 -0
- package/dist/action-surface.js +1032 -0
- package/dist/action-surface.js.map +1 -0
- package/dist/camera.d.ts +65 -1
- package/dist/camera.js +568 -0
- package/dist/camera.js.map +1 -1
- package/dist/dev-shell/criteria.d.ts +46 -0
- package/dist/dev-shell/criteria.js +98 -0
- package/dist/dev-shell/criteria.js.map +1 -0
- package/dist/dev-shell/index.d.ts +189 -0
- package/dist/dev-shell/index.js +287 -0
- package/dist/dev-shell/index.js.map +1 -0
- package/dist/dev-shell/keys.d.ts +14 -0
- package/dist/dev-shell/keys.js +78 -0
- package/dist/dev-shell/keys.js.map +1 -0
- package/dist/dev-shell/simulator.d.ts +436 -0
- package/dist/dev-shell/simulator.js +1634 -0
- package/dist/dev-shell/simulator.js.map +1 -0
- package/dist/dev-shell/state.d.ts +148 -0
- package/dist/dev-shell/state.js +196 -0
- package/dist/dev-shell/state.js.map +1 -0
- package/dist/device-definition-resolver.d.ts +34 -0
- package/dist/device-definition-resolver.js +172 -0
- package/dist/device-definition-resolver.js.map +1 -0
- package/dist/device-trial.d.ts +3 -0
- package/dist/device-trial.js +132 -0
- package/dist/device-trial.js.map +1 -0
- package/dist/devices.d.ts +228 -0
- package/dist/devices.js +198 -0
- package/dist/devices.js.map +1 -0
- package/dist/dreamerAudio.d.ts +126 -0
- package/dist/dreamerAudio.js +135 -0
- package/dist/dreamerAudio.js.map +1 -0
- package/dist/generated/runtime-contract.d.ts +15529 -0
- package/dist/generated/runtime-contract.js +20470 -0
- package/dist/generated/runtime-contract.js.map +1 -0
- package/dist/index.d.ts +272 -15
- package/dist/index.js +1401 -91
- package/dist/index.js.map +1 -1
- package/dist/interaction-mode.d.ts +172 -0
- package/dist/interaction-mode.js +553 -0
- package/dist/interaction-mode.js.map +1 -0
- package/dist/internal/avatar-pose.d.ts +25 -0
- package/dist/internal/avatar-pose.js +46 -0
- package/dist/internal/avatar-pose.js.map +1 -0
- package/dist/internal/keyed-collection.d.ts +2 -0
- package/dist/internal/keyed-collection.js +12 -0
- package/dist/internal/keyed-collection.js.map +1 -0
- package/dist/internal/vehicle-detach-action.d.ts +2 -0
- package/dist/internal/vehicle-detach-action.js +6 -0
- package/dist/internal/vehicle-detach-action.js.map +1 -0
- package/dist/matchmaking.d.ts +433 -0
- package/dist/matchmaking.js +1487 -0
- package/dist/matchmaking.js.map +1 -0
- package/dist/materials.d.ts +122 -0
- package/dist/materials.js +217 -0
- package/dist/materials.js.map +1 -0
- package/dist/multiplayer-accessors.d.ts +100 -0
- package/dist/multiplayer-accessors.js +200 -0
- package/dist/multiplayer-accessors.js.map +1 -0
- package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
- package/dist/multiplayer-contract/avatar-pose.js +250 -0
- package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
- package/dist/multiplayer-contract/credential.d.ts +38 -0
- package/dist/multiplayer-contract/final-rest.d.ts +66 -0
- package/dist/multiplayer-contract/final-rest.js +38 -0
- package/dist/multiplayer-contract/final-rest.js.map +1 -0
- package/dist/multiplayer-contract/index.d.ts +11 -5
- package/dist/multiplayer-contract/index.js +16 -5
- package/dist/multiplayer-contract/index.js.map +1 -1
- package/dist/multiplayer-contract/messages.d.ts +461 -14
- package/dist/multiplayer-contract/messages.js +141 -15
- package/dist/multiplayer-contract/messages.js.map +1 -1
- package/dist/multiplayer-contract/room.d.ts +55 -4
- package/dist/multiplayer-contract/state.d.ts +181 -1
- package/dist/multiplayer-contract/state.js.map +1 -1
- package/dist/multiplayer-final-rest.d.ts +32 -0
- package/dist/multiplayer-final-rest.js +217 -0
- package/dist/multiplayer-final-rest.js.map +1 -0
- package/dist/multiplayer.d.ts +507 -16
- package/dist/multiplayer.js +2242 -73
- package/dist/multiplayer.js.map +1 -1
- package/dist/package.json +3 -0
- package/dist/protocol.d.ts +668 -5
- package/dist/protocol.js +101 -1
- package/dist/protocol.js.map +1 -1
- package/dist/runtime-contract/index.d.ts +15 -0
- package/dist/runtime-contract/index.js +12 -0
- package/dist/runtime-contract/index.js.map +1 -0
- package/dist/server-clock.d.ts +25 -0
- package/dist/server-clock.js +88 -0
- package/dist/server-clock.js.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/universal-vehicles.d.ts +111 -0
- package/dist/universal-vehicles.js +2 -0
- package/dist/universal-vehicles.js.map +1 -0
- package/dist/vault.d.ts +562 -0
- package/dist/vault.js +365 -0
- package/dist/vault.js.map +1 -0
- package/dist/vehicle-specialty-placement.d.ts +28 -0
- package/dist/vehicle-specialty-placement.js +154 -0
- package/dist/vehicle-specialty-placement.js.map +1 -0
- package/dist/vehicle-specialty-transport.d.ts +78 -0
- package/dist/vehicle-specialty-transport.js +183 -0
- package/dist/vehicle-specialty-transport.js.map +1 -0
- package/dist/voice.d.ts +229 -0
- package/dist/voice.js +1348 -0
- package/dist/voice.js.map +1 -0
- package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
- package/generated/runtime-contract/known-answer.json +20471 -0
- package/generated/runtime-contract/known-answer.schema.json +630 -0
- package/generated/runtime-contract/runtime-contract.schema.json +607 -0
- package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
- package/package.json +32 -6
package/dist/multiplayer.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FinalRestClient, FINAL_REST_REPLY } from './multiplayer-final-rest.js';
|
|
2
|
+
import { MODULE_FINAL_REST_SNAPSHOT, DISTRIBUTION_CAPABILITY_MESSAGE, DISTRIBUTION_CAPABILITY_RESULT } from './multiplayer-contract/index.js';
|
|
1
3
|
// Helix.multiplayer — the client half of HELIX multiplayer (plan pillar D). Wraps the official
|
|
2
4
|
// Colyseus browser client (@colyseus/sdk, schema v4 — the renamed colyseus.js, paired with the 0.17
|
|
3
5
|
// room server) so world authors never import it directly. Flow: POST the platform
|
|
@@ -5,32 +7,342 @@
|
|
|
5
7
|
// → Client.joinOrCreate(token) → a curated HelixRoom handle. The engine NetworkDriver consumes the
|
|
6
8
|
// room state; this module owns the connect handshake, the throttled seq-tagged send path (D3), the
|
|
7
9
|
// reconciliation buffer (D4), and teardown/reconnection wiring (D5).
|
|
8
|
-
import { ClientMessageType, ServerMessageType, MESSAGE_RATE, CONTRACT_VERSION, } from './multiplayer-contract';
|
|
10
|
+
import { ClientMessageType, ServerMessageType, MESSAGE_RATE, CONTRACT_VERSION, RECEIPT_LIMITS, } from './multiplayer-contract/index.js';
|
|
11
|
+
import { AVATAR_POSE_VERSION, decodeInternalAvatarPoseReplica, encodeAvatarPose, installInternalAvatarPoseCapability, } from './internal/avatar-pose.js';
|
|
12
|
+
import { createRoomAccessors } from './multiplayer-accessors.js';
|
|
13
|
+
import { keyedCollectionEntry } from './internal/keyed-collection.js';
|
|
14
|
+
import { isVehicleDetachActionId } from './internal/vehicle-detach-action.js';
|
|
15
|
+
function plainSnapshot(value) {
|
|
16
|
+
if (!value || typeof value !== 'object')
|
|
17
|
+
return {};
|
|
18
|
+
const serializable = value;
|
|
19
|
+
const output = typeof serializable.toJSON === 'function'
|
|
20
|
+
? serializable.toJSON()
|
|
21
|
+
: value;
|
|
22
|
+
return output && typeof output === 'object' && !Array.isArray(output)
|
|
23
|
+
? { ...output }
|
|
24
|
+
: {};
|
|
25
|
+
}
|
|
26
|
+
function normalizedDynamicVars(value) {
|
|
27
|
+
if (!value || typeof value !== 'object')
|
|
28
|
+
return {};
|
|
29
|
+
const module = value;
|
|
30
|
+
const output = {};
|
|
31
|
+
const copy = (bag, accept) => {
|
|
32
|
+
if (!bag || typeof bag !== 'object')
|
|
33
|
+
return;
|
|
34
|
+
const each = bag.forEach;
|
|
35
|
+
if (typeof each === 'function') {
|
|
36
|
+
each.call(bag, (candidate, key) => { if (accept(candidate))
|
|
37
|
+
output[key] = candidate; });
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
for (const [key, candidate] of Object.entries(bag))
|
|
41
|
+
if (accept(candidate))
|
|
42
|
+
output[key] = candidate;
|
|
43
|
+
};
|
|
44
|
+
copy(module.booleans, (candidate) => typeof candidate === 'boolean');
|
|
45
|
+
copy(module.numbers, (candidate) => typeof candidate === 'number' && Number.isFinite(candidate));
|
|
46
|
+
copy(module.strings, (candidate) => typeof candidate === 'string');
|
|
47
|
+
return output;
|
|
48
|
+
}
|
|
49
|
+
function keyedEntries(value) {
|
|
50
|
+
if (!value || typeof value !== 'object')
|
|
51
|
+
return [];
|
|
52
|
+
const entries = [];
|
|
53
|
+
const each = value.forEach;
|
|
54
|
+
if (typeof each === 'function') {
|
|
55
|
+
each.call(value, (candidate, key) => entries.push([key, candidate]));
|
|
56
|
+
return entries;
|
|
57
|
+
}
|
|
58
|
+
return Object.entries(value);
|
|
59
|
+
}
|
|
60
|
+
function moduleStateSnapshots(state) {
|
|
61
|
+
const root = state;
|
|
62
|
+
const entries = [
|
|
63
|
+
...keyedEntries(root.modules).map(([key, raw]) => ({ key, raw, dynamic: false })),
|
|
64
|
+
...keyedEntries(root.dynamicModules).map(([key, raw]) => ({ key, raw, dynamic: true })),
|
|
65
|
+
];
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
return entries.flatMap(({ key, raw, dynamic }) => {
|
|
68
|
+
const module = raw;
|
|
69
|
+
const moduleId = key.startsWith('m:') ? key.slice(2) : key;
|
|
70
|
+
if (!moduleId || seen.has(moduleId))
|
|
71
|
+
return [];
|
|
72
|
+
seen.add(moduleId);
|
|
73
|
+
return [{
|
|
74
|
+
moduleId,
|
|
75
|
+
revision: Number.isSafeInteger(module.externalRevision)
|
|
76
|
+
? Number(module.externalRevision)
|
|
77
|
+
: 0,
|
|
78
|
+
phase: typeof module.phase === 'string' ? module.phase : '',
|
|
79
|
+
serverTick: Number.isSafeInteger(root.serverTick) ? Number(root.serverTick) : 0,
|
|
80
|
+
roomVars: dynamic ? normalizedDynamicVars(raw) : plainSnapshot(module.roomVars),
|
|
81
|
+
}];
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function validPrimitiveArgs(value) {
|
|
85
|
+
if (value === undefined)
|
|
86
|
+
return true;
|
|
87
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
88
|
+
return false;
|
|
89
|
+
return Object.values(value).every((arg) => typeof arg === 'string' || typeof arg === 'boolean' || (typeof arg === 'number' && Number.isFinite(arg)));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The typed failure of `joinRoom`'s platform request and of every `switchRoom` rejection. It IS an Error with
|
|
93
|
+
* the same `Helix.multiplayer: join failed — …` message earlier SDKs threw, so code that only reads `.message`
|
|
94
|
+
* is unaffected; `code` is what new code should branch on, `status` the HTTP status when there was one.
|
|
95
|
+
*/
|
|
96
|
+
export class HelixRoomJoinError extends Error {
|
|
97
|
+
code;
|
|
98
|
+
status;
|
|
99
|
+
constructor(code, message, status = null, cause) {
|
|
100
|
+
// `cause` keeps the original failure reachable when a transport error is rewrapped as `join-failed`.
|
|
101
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
102
|
+
this.name = 'HelixRoomJoinError';
|
|
103
|
+
this.code = code;
|
|
104
|
+
this.status = status;
|
|
105
|
+
// Restore the prototype chain for ES5-targeted consumers, where `extends Error` loses it.
|
|
106
|
+
Object.setPrototypeOf(this, HelixRoomJoinError.prototype);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// The close code Colyseus reports for a leave the client asked for (CloseCode.CONSENTED). Used when the SDK
|
|
110
|
+
// has to deliver the leave itself because the transport never will.
|
|
111
|
+
const CONSENTED_CLOSE_CODE = 4000;
|
|
112
|
+
/**
|
|
113
|
+
* How long ANY leave — `leave()`, the shell's helix:leave, a room hop — waits for the room's consented leave
|
|
114
|
+
* before detaching it by force. Colyseus only
|
|
115
|
+
* settles leave() when the socket's close arrives, a LEAVE written to an already-closed socket is silently
|
|
116
|
+
* lost, and a send while CONNECTING throws — so on a dropped or reconnecting room an unbounded await is a hop
|
|
117
|
+
* that never returns — and `isOpen` is no help, because a black-holed socket still reports open. 3 s is far
|
|
118
|
+
* beyond a healthy leave round-trip (tens of ms) and still short enough that a player watching a "joining
|
|
119
|
+
* match…" screen is not left wondering; past it the seat is the server's to reap through its ordinary
|
|
120
|
+
* drop/grace path.
|
|
121
|
+
*/
|
|
122
|
+
export const ROOM_LEAVE_TIMEOUT_MS = 3_000;
|
|
123
|
+
/** @deprecated The bound now covers every leave, not only a hop's — use ROOM_LEAVE_TIMEOUT_MS. */
|
|
124
|
+
export const ROOM_SWITCH_LEAVE_TIMEOUT_MS = ROOM_LEAVE_TIMEOUT_MS;
|
|
125
|
+
/**
|
|
126
|
+
* How long the room holds a dropped seat for its owner to reconnect, counted from when the SERVER notices the
|
|
127
|
+
* drop: the room server's reconnection grace (helix-colyseus-server `RECONNECT_GRACE_SEC`, 20 s; the room does
|
|
128
|
+
* not advertise it). See ROOM_RECONNECT_WINDOW_MS for what the SDK's automatic reconnect makes of it.
|
|
129
|
+
*/
|
|
130
|
+
export const ROOM_RECONNECT_GRACE_MS = 20_000;
|
|
131
|
+
/**
|
|
132
|
+
* How long after the CLIENT sees a drop the server may still not have noticed it, so that its grace has not
|
|
133
|
+
* even started. The common drops are client-first (a wifi switch, a network change, the browser going
|
|
134
|
+
* `offline`: Colyseus closes the socket at once), and the server only notices them on its ping timeout. The
|
|
135
|
+
* room server runs @colyseus/ws-transport with its defaults, a ping every 3 s and termination at the tick
|
|
136
|
+
* after 2 unanswered ones: up to 3 x 3 s = 9 s after the last answered ping.
|
|
137
|
+
*/
|
|
138
|
+
export const ROOM_SERVER_DROP_DETECTION_MS = 3_000 * (2 + 1);
|
|
139
|
+
/**
|
|
140
|
+
* How long the SDK's automatic reconnect keeps scheduling attempts after the drop it saw: the grace plus the
|
|
141
|
+
* server's detection time (29 s). A seat may be held until then, so giving up earlier loses players the room
|
|
142
|
+
* would still have taken back. Ending sooner when the seat really is gone is the server's job: it refuses a
|
|
143
|
+
* reconnection token it no longer holds with 4003, which ends the reconnect at once (`onLeave(4003)`).
|
|
144
|
+
*/
|
|
145
|
+
export const ROOM_RECONNECT_WINDOW_MS = ROOM_RECONNECT_GRACE_MS + ROOM_SERVER_DROP_DETECTION_MS;
|
|
146
|
+
/**
|
|
147
|
+
* An attempt still connecting when the window closes gets this much longer to finish its handshake; then it is
|
|
148
|
+
* closed and the reconnect gives up (`onLeave(4003, 'dropped')` at the latest 31 s after the drop).
|
|
149
|
+
*/
|
|
150
|
+
export const ROOM_RECONNECT_ATTEMPT_ALLOWANCE_MS = 2_000;
|
|
151
|
+
// Colyseus CloseCode.MAY_TRY_RECONNECT: the code its own `offline` listener closes a socket with. The transport
|
|
152
|
+
// delivers it at once (it does not wait for a close frame the dead network will never bring).
|
|
153
|
+
const MAY_TRY_RECONNECT_CLOSE_CODE = 4010;
|
|
154
|
+
// A clock that a change of the device's wall clock does not move (falls back to Date.now where there is none).
|
|
155
|
+
const monotonicNow = () => typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();
|
|
156
|
+
// The running grace watch of each room it was set up on, so a room left on purpose can stop it.
|
|
157
|
+
const graceWatches = new WeakMap();
|
|
158
|
+
/**
|
|
159
|
+
* Make Colyseus's automatic reconnection follow the room's grace instead of its own defaults. Left alone, a
|
|
160
|
+
* 0.17 Room (a) does not reconnect at all when the socket drops within 5 s of the join (`minUptime`): the seat
|
|
161
|
+
* is still held, but the world is told the room is gone; and (b) when the network stays down, retries 15 times
|
|
162
|
+
* with an exponential backoff capped at 5 s, about a minute, long after the seat is gone. (A server that is
|
|
163
|
+
* reachable already ends it sooner: it refuses a token whose seat it gave away with 4003, and that close is
|
|
164
|
+
* not one Colyseus retries.)
|
|
165
|
+
*
|
|
166
|
+
* So: any drop is reconnected, however soon after the join; retries keep Colyseus's own backoff, but none is
|
|
167
|
+
* scheduled past `windowMs` after the drop the client saw (ROOM_RECONNECT_WINDOW_MS: the grace plus the time
|
|
168
|
+
* the server may take to notice the drop); a retry that fails after the window ends the reconnect; and an
|
|
169
|
+
* attempt still connecting ROOM_RECONNECT_ATTEMPT_ALLOWANCE_MS after it is closed, which ends it too. The end
|
|
170
|
+
* is Colyseus's own: `onLeave` with 4003 (FAILED_TO_RECONNECT). The server's own 4003 refusal still ends it as
|
|
171
|
+
* soon as it arrives. Each new drop (after a successful reconnect) gets a fresh window. Times are measured on a
|
|
172
|
+
* monotonic clock. Only the Room's public `reconnection` config, `onDrop`, `onReconnect` and `onLeave` are
|
|
173
|
+
* used; a Room without that config is left as it is.
|
|
174
|
+
*/
|
|
175
|
+
export function followReconnectGrace(room, windowMs = ROOM_RECONNECT_WINDOW_MS) {
|
|
176
|
+
const reconnection = room.reconnection;
|
|
177
|
+
if (!reconnection)
|
|
178
|
+
return;
|
|
179
|
+
let deadline = null;
|
|
180
|
+
let watchdog = null;
|
|
181
|
+
const stop = () => {
|
|
182
|
+
deadline = null;
|
|
183
|
+
if (watchdog !== null)
|
|
184
|
+
clearTimeout(watchdog);
|
|
185
|
+
watchdog = null;
|
|
186
|
+
};
|
|
187
|
+
try {
|
|
188
|
+
reconnection.minUptime = 0;
|
|
189
|
+
const backoff = reconnection.backoff;
|
|
190
|
+
if (typeof backoff === 'function') {
|
|
191
|
+
reconnection.backoff = (attempt, delay) => {
|
|
192
|
+
const wanted = backoff(attempt, delay);
|
|
193
|
+
return deadline === null ? wanted : Math.min(wanted, Math.max(0, deadline - monotonicNow()));
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return; // a frozen/renamed colyseus shape: its own defaults stay
|
|
199
|
+
}
|
|
200
|
+
// Colyseus calls the room's onDrop listeners on every close it will try to recover from (the first drop and
|
|
201
|
+
// each failed retry) and only then decides whether to retry. `isReconnecting` is still false on the first.
|
|
202
|
+
room.onDrop(() => {
|
|
203
|
+
if (!reconnection.enabled)
|
|
204
|
+
return;
|
|
205
|
+
if (!reconnection.isReconnecting) {
|
|
206
|
+
stop();
|
|
207
|
+
deadline = monotonicNow() + windowMs;
|
|
208
|
+
watchdog = setTimeout(() => {
|
|
209
|
+
watchdog = null;
|
|
210
|
+
if (!reconnection.enabled || !reconnection.isReconnecting)
|
|
211
|
+
return;
|
|
212
|
+
// Still connecting past the window: close that attempt. Its close comes back through onDrop, below.
|
|
213
|
+
try {
|
|
214
|
+
room.connection?.close?.(MAY_TRY_RECONNECT_CLOSE_CODE);
|
|
215
|
+
}
|
|
216
|
+
catch { /* nothing open */ }
|
|
217
|
+
}, windowMs + ROOM_RECONNECT_ATTEMPT_ALLOWANCE_MS);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
// A retry failed after the window: the seat is gone. Colyseus gives up at its next retry decision.
|
|
221
|
+
if (deadline !== null && monotonicNow() >= deadline)
|
|
222
|
+
reconnection.retryCount = reconnection.maxRetries ?? 0;
|
|
223
|
+
});
|
|
224
|
+
room.onReconnect(stop);
|
|
225
|
+
room.onLeave(stop);
|
|
226
|
+
graceWatches.set(room, stop);
|
|
227
|
+
}
|
|
9
228
|
// ~12s of inputs at 10Hz — generous reconciliation window; bounded so a missing server ack can't grow it forever.
|
|
10
229
|
const INPUT_BUFFER_MAX = 120;
|
|
230
|
+
// The buy-then-join stash: receipts settled with no live room, re-forwarded on the next join. Capped at the
|
|
231
|
+
// receipt channel's burst (a bigger flush is over-rate-dropped by the room); the window mirrors the backend's
|
|
232
|
+
// ~10-minute receipt expiry — hygiene only, a stale forward is just rejected server-side.
|
|
233
|
+
const MAX_PENDING_RECEIPTS = 2;
|
|
234
|
+
const RECEIPT_REPLAY_WINDOW_MS = 10 * 60_000;
|
|
11
235
|
// sessionStorage key (per world) for the colyseus reconnectionToken + its wsUrl. sessionStorage is per-tab and
|
|
12
236
|
// SURVIVES A RELOAD but not a tab close — exactly the lifetime we want: a reload resumes the held seat; a new
|
|
13
237
|
// tab / post-close start does a fresh join. This is what makes a reload RECONNECT (bypassing the room's
|
|
14
238
|
// onAuth one-seat-per-account gate, which would otherwise reject the reload's fresh join during the grace
|
|
15
239
|
// window) instead of falling back to single-player.
|
|
16
|
-
|
|
240
|
+
//
|
|
241
|
+
// ROOM TYPES: the argument is a reconnect SCOPE, not always a bare world id. The default room keeps the
|
|
242
|
+
// historical key (scope === worldId), so nothing a pre-room-types bundle wrote is orphaned or re-read
|
|
243
|
+
// differently. A named room type gets ITS OWN slot (`${worldId}:rt:${roomType}`), because the two are
|
|
244
|
+
// governed by different rules: the shell's `?instance=` names a default-type room and may legitimately
|
|
245
|
+
// invalidate the DEFAULT slot, but it says nothing about a typed/ticketed room the player hopped into.
|
|
246
|
+
const RECONNECT_KEY = (scope) => `helix:mp:reconnect:${scope}`;
|
|
247
|
+
const reconnectScope = (worldId, roomType) => roomType ? `${worldId}:rt:${roomType}` : worldId;
|
|
248
|
+
// Which TYPED room this tab was last seated in — `{ roomType, instanceKey? }`, absent while the active room is
|
|
249
|
+
// the default one. It is what lets a plain `joinRoom()` after a reload find the right per-type slot, and it
|
|
250
|
+
// carries the instance id separately from the slot so a ticketed room can still be re-entered through the
|
|
251
|
+
// backend rejoin endpoint after the slot's reconnect token is gone.
|
|
252
|
+
const ACTIVE_ROOM_KEY = (worldId) => `${RECONNECT_KEY(worldId)}:active-room`;
|
|
253
|
+
const VEHICLE_ACTION_SEQ_KEY_PREFIX = (scope) => `${RECONNECT_KEY(scope)}:vehicle-action:`;
|
|
254
|
+
const VEHICLE_ACTION_SEQ_KEY = (scope, entityId) => `${VEHICLE_ACTION_SEQ_KEY_PREFIX(scope)}${entityId}`;
|
|
255
|
+
function sanitizedVehicleActionSeq(value) {
|
|
256
|
+
const entries = new Map();
|
|
257
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
258
|
+
return entries;
|
|
259
|
+
for (const [entityId, raw] of Object.entries(value)) {
|
|
260
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(entityId) || !raw || typeof raw !== 'object')
|
|
261
|
+
continue;
|
|
262
|
+
const { authorityEpoch, seq } = raw;
|
|
263
|
+
if (!Number.isSafeInteger(authorityEpoch) || authorityEpoch < 0)
|
|
264
|
+
continue;
|
|
265
|
+
if (!Number.isSafeInteger(seq) || seq < 1 || seq >= Number.MAX_SAFE_INTEGER)
|
|
266
|
+
continue;
|
|
267
|
+
entries.set(entityId, { authorityEpoch: authorityEpoch, seq: seq });
|
|
268
|
+
}
|
|
269
|
+
return entries;
|
|
270
|
+
}
|
|
271
|
+
/** How long a capability request waits for the room before giving up (the mint is one backend round trip). */
|
|
272
|
+
export const DISTRIBUTION_CAPABILITY_TIMEOUT_MS = 10_000;
|
|
17
273
|
export class HelixMultiplayer {
|
|
18
274
|
host;
|
|
275
|
+
finalRestClient = null;
|
|
19
276
|
apiBaseUrl = null;
|
|
277
|
+
shellApiBaseUrl = null;
|
|
20
278
|
room = null;
|
|
279
|
+
distributionCapabilitySeq = 0;
|
|
280
|
+
pendingDistributionCapabilities = new Map();
|
|
21
281
|
callbacks = null;
|
|
22
282
|
seq = 0;
|
|
283
|
+
// v27: the last teleport epoch adopted from a StateAck, stamped on every flushed frame. Adoption is ABSOLUTE
|
|
284
|
+
// (not max) — a reconnect resets the seat's epoch server-side and the client must follow it back down.
|
|
285
|
+
teleportSeq = 0;
|
|
23
286
|
entitySeq = {}; // per-entity monotonic upload seq (4.6c owner-entity channel)
|
|
24
287
|
entityBatchSeq = 0; // per-connection monotonic batch seq (4.10 owner-entity batch channel)
|
|
288
|
+
vehicleActionSeq = new Map();
|
|
289
|
+
vehicleActionReconnectBaseline = null;
|
|
290
|
+
retiredVehicleActionEpochs = new Map();
|
|
291
|
+
vehicleActionManifestPersistTimer = null;
|
|
292
|
+
reconnectCache = null;
|
|
293
|
+
// The in-memory mirror of the active-room pointer, for hosts without sessionStorage (same role as
|
|
294
|
+
// reconnectCache). Bound to the actor that wrote it, exactly like the stored pointer.
|
|
295
|
+
activeRoomCache = null;
|
|
296
|
+
// The World-session actor of the join in flight / the room joined (see reconnectIdentityOf). EVERY persisted
|
|
297
|
+
// way back into a room is bound to it — the default slot, each typed slot, and the active-room pointer.
|
|
298
|
+
sessionIdentity = null;
|
|
299
|
+
// The joinRoom() / switchRoom() in flight, if any. leave() marks it cancelled and waits for `done`: a leave
|
|
300
|
+
// that lands while a room is still being entered must end with the caller in no room, not be overtaken by it.
|
|
301
|
+
// If the call has not finished by the leave bound, leave() gives up on it (`giveUp`): whatever it is still
|
|
302
|
+
// waiting for is abandoned, so it rejects `cancelled` then and there — see abandonable().
|
|
303
|
+
entering = null;
|
|
304
|
+
// A public joinRoom() in flight. A second one is refused (it could relabel the first actor's seat), and a
|
|
305
|
+
// hop must not start underneath one (it would leave nothing, then race the join for the seat).
|
|
306
|
+
joining = false;
|
|
25
307
|
pendingInput = null;
|
|
308
|
+
// Engine-owned transport extension. Deliberately absent from ReplicaInput and HelixRoom; the non-enumerable
|
|
309
|
+
// internal room capability below is the only supported way for the humanoid runtime to set/read it.
|
|
310
|
+
internalAvatarPose = null;
|
|
26
311
|
flushTimer = null;
|
|
27
312
|
// The clamped player-seat flush cadence (Hz), set on join from JoinRoomOptions.uploadHz. Default = stateHz (10).
|
|
28
313
|
effectiveUploadHz = MESSAGE_RATE.stateHz;
|
|
29
314
|
inputBuffer = [];
|
|
30
|
-
worldId = null; // the joined world
|
|
315
|
+
worldId = null; // the joined world
|
|
316
|
+
// The joined room's reconnect SCOPE — the storage key for its token, manifest and vehicle high-waters. Equal to
|
|
317
|
+
// worldId in the default room (the historical key); `${worldId}:rt:${roomType}` in a typed room.
|
|
318
|
+
reconnectScope = null;
|
|
319
|
+
// The joined room's type (null = default) and, for a ticketed room, its instance id. Set from the reservation
|
|
320
|
+
// on a fresh join and from the persisted slot on a resume.
|
|
321
|
+
roomType = null;
|
|
322
|
+
instanceKey = null;
|
|
323
|
+
// The CURRENT room's context (see RoomContext) — the identity every per-room callback checks itself against.
|
|
324
|
+
ctx = null;
|
|
325
|
+
// A switchRoom hop in flight. joinRoom's "already in a room" guard cannot see one (the room is null between
|
|
326
|
+
// the leave and the join), and two overlapping hops would each seat a connection and leak one.
|
|
327
|
+
switching = false;
|
|
328
|
+
// Shell roster publishing (helix:multiplayer-state): the room's seat cap (credential maxPlayers, null when
|
|
329
|
+
// resumed without one) + the last published roster signature, so state patches only post on a REAL change.
|
|
330
|
+
roomMaxPlayers = null;
|
|
331
|
+
rosterSig = null;
|
|
332
|
+
// Receipts settled while no room was live — flushed into the next join (see sendPurchaseReceipt).
|
|
333
|
+
pendingReceipts = [];
|
|
31
334
|
// A2 (spec §9) engine consumers of the reconnection acks — set via the handle's onStateAck/onEntityStateAck.
|
|
32
335
|
onStateAckCb = null;
|
|
33
336
|
onEntityStateAckCb = null;
|
|
337
|
+
// S3 engagement authority is a distinct room lock from the local InputService lease. The SDK owns the
|
|
338
|
+
// request ids and epoch stamps so item data can name only declared actions, never authority tokens.
|
|
339
|
+
engagementRequestSeq = 0;
|
|
340
|
+
moduleEngagements = new Map();
|
|
341
|
+
moduleEngagementCbs = new Set();
|
|
342
|
+
// v23/v33 mid-session avatar refresh: engine subscribers (onPlayerAvatarChanged) + per-seat Colyseus schema
|
|
343
|
+
// listeners. A schema-instance callback runs once per patch, so avatarUrl + avatarRevision coalesce naturally.
|
|
344
|
+
avatarChangedCbs = new Set();
|
|
345
|
+
avatarListeners = new Map();
|
|
34
346
|
// Opt-in netlog accumulators (1 s windows) — the SOURCE cadence feeding the engine interpolators: the throttled
|
|
35
347
|
// upload (flush) rate and the server patch-arrival rate. Off unless globalThis.__HELIX_NETLOG__ is a sink fn.
|
|
36
348
|
nlSend = { last: 0, count: 0, win: 0, maxGap: 0 };
|
|
@@ -42,44 +354,643 @@ export class HelixMultiplayer {
|
|
|
42
354
|
configure(options) {
|
|
43
355
|
this.apiBaseUrl = options.apiBaseUrl.replace(/\/$/, '');
|
|
44
356
|
}
|
|
357
|
+
// The API base the SHELL announced in helix:init. Below an explicit configure(), above the token-`iss`
|
|
358
|
+
// guess — local-dev session JWTs carry no `iss`, and this is what keeps direct calls working there.
|
|
359
|
+
adoptShellApiBase(url) {
|
|
360
|
+
this.shellApiBaseUrl = url.replace(/\/$/, '');
|
|
361
|
+
}
|
|
362
|
+
// The joined room's instance id, or null when not in a room. The voice module pairs its LiveKit
|
|
363
|
+
// room to this (the backend namespaces the voice room v:{worldId}:{roomId}).
|
|
364
|
+
/**
|
|
365
|
+
* ADR-0003: ask the joined room for a one-time World acquisition capability (see HelixRoom's method of the same
|
|
366
|
+
* name). Also what the shell's Store/confirm flow reaches through `helix:distribution-capability-request`.
|
|
367
|
+
*/
|
|
368
|
+
requestDistributionCapability(ref, timeoutMs = DISTRIBUTION_CAPABILITY_TIMEOUT_MS) {
|
|
369
|
+
const room = this.room;
|
|
370
|
+
if (!room)
|
|
371
|
+
return Promise.reject(new Error('not_in_room'));
|
|
372
|
+
const requestId = `dc${++this.distributionCapabilitySeq}`;
|
|
373
|
+
return new Promise((resolve, reject) => {
|
|
374
|
+
const timer = setTimeout(() => {
|
|
375
|
+
this.pendingDistributionCapabilities.delete(requestId);
|
|
376
|
+
reject(new Error('timeout'));
|
|
377
|
+
}, timeoutMs);
|
|
378
|
+
this.pendingDistributionCapabilities.set(requestId, { resolve, reject, timer });
|
|
379
|
+
room.send(DISTRIBUTION_CAPABILITY_MESSAGE, { requestId, ref });
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
settleDistributionCapability(result) {
|
|
383
|
+
const pending = typeof result?.requestId === 'string' ? this.pendingDistributionCapabilities.get(result.requestId) : undefined;
|
|
384
|
+
if (!pending)
|
|
385
|
+
return;
|
|
386
|
+
this.pendingDistributionCapabilities.delete(result.requestId);
|
|
387
|
+
clearTimeout(pending.timer);
|
|
388
|
+
if ('capability' in result && typeof result.capability === 'string') {
|
|
389
|
+
pending.resolve({ capability: result.capability, expiresAt: result.expiresAt, ref: result.ref });
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
pending.reject(new Error('error' in result && typeof result.error === 'string' ? result.error : 'unavailable'));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
rejectDistributionCapabilities(reason) {
|
|
396
|
+
for (const [requestId, pending] of this.pendingDistributionCapabilities) {
|
|
397
|
+
clearTimeout(pending.timer);
|
|
398
|
+
pending.reject(new Error(reason));
|
|
399
|
+
this.pendingDistributionCapabilities.delete(requestId);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
currentRoomId() {
|
|
403
|
+
return this.room?.roomId ?? null;
|
|
404
|
+
}
|
|
405
|
+
// The locomotion pack THIS client's seat moves on (contract v34), straight off the replicated state: the room
|
|
406
|
+
// resolves it server-side from the equipped items, so the seat is the only place a client can honestly read it.
|
|
407
|
+
// null = there is no seat to read (not joined yet, or the room has not replicated this session's player);
|
|
408
|
+
// '' = a real answer, the seat moves on the platform locomotion set — which is also what a pre-v34 room, an
|
|
409
|
+
// unresolvable pack and an unservable URL all replicate, deliberately indistinguishable.
|
|
410
|
+
localLocomotionPack() {
|
|
411
|
+
const room = this.room;
|
|
412
|
+
if (!room)
|
|
413
|
+
return null;
|
|
414
|
+
const players = room.state?.players;
|
|
415
|
+
if (!players)
|
|
416
|
+
return null;
|
|
417
|
+
const seat = keyedCollectionEntry(players, room.sessionId);
|
|
418
|
+
if (seat === undefined)
|
|
419
|
+
return null;
|
|
420
|
+
return typeof seat.locomotionPack === 'string' ? seat.locomotionPack : '';
|
|
421
|
+
}
|
|
422
|
+
// Forward a settled purchase's backend receipt to the room (v22). Best-effort by design — no room, a closed
|
|
423
|
+
// socket, or an oversize receipt returns false instead of throwing, since a purchase must never fail on its
|
|
424
|
+
// multiplayer side effect. The closed socket needs the explicit isOpen check: colyseus auto-reconnect leaves
|
|
425
|
+
// `room` non-null and its send() buffers into a 10-slot drop-oldest ring that the 10–20 Hz state flush evicts
|
|
426
|
+
// within ~1 s. The JWT is opaque here; the room verifies it and its durable claim makes the event exactly-once,
|
|
427
|
+
// so re-forwarding is always safe. An undeliverable receipt is STASHED and replayed on the next join or in-place
|
|
428
|
+
// reconnect (buy from a lobby, then join) — see flushPendingReceipts.
|
|
429
|
+
sendPurchaseReceipt(receipt) {
|
|
430
|
+
if (receipt.length > RECEIPT_LIMITS.maxReceiptLength)
|
|
431
|
+
return false;
|
|
432
|
+
// `=== false`, not `!isOpen`: an absent `connection` (a colyseus shape change) counts as open and still delivers.
|
|
433
|
+
if (!this.room || this.room.connection?.isOpen === false) {
|
|
434
|
+
this.stashReceipt(receipt);
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
try {
|
|
438
|
+
this.room.send(ClientMessageType.PurchaseReceipt, { receipt });
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
this.stashReceipt(receipt);
|
|
443
|
+
return false;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
// Capped at the receipt channel's burst (2): a bigger flush would be over-rate-dropped by the room
|
|
447
|
+
// anyway. Oldest dropped first; kept across leave() so buy → rejoin still delivers.
|
|
448
|
+
stashReceipt(receipt) {
|
|
449
|
+
this.pendingReceipts.push({ receipt, storedAt: Date.now() });
|
|
450
|
+
while (this.pendingReceipts.length > MAX_PENDING_RECEIPTS)
|
|
451
|
+
this.pendingReceipts.shift();
|
|
452
|
+
}
|
|
453
|
+
// Replay stashed receipts into a freshly joined room, or into a resumed one on an in-place reconnect. A still-
|
|
454
|
+
// closed socket re-stashes through the same capped path. The TTL is hygiene, not correctness — the
|
|
455
|
+
// backend mints ~10-minute receipts and the room rejects a stale one; the durable claim already
|
|
456
|
+
// guarantees a replayed event fires at most once.
|
|
457
|
+
flushPendingReceipts() {
|
|
458
|
+
const fresh = this.pendingReceipts.filter((p) => Date.now() - p.storedAt < RECEIPT_REPLAY_WINDOW_MS);
|
|
459
|
+
this.pendingReceipts = [];
|
|
460
|
+
for (const p of fresh)
|
|
461
|
+
this.sendPurchaseReceipt(p.receipt);
|
|
462
|
+
}
|
|
463
|
+
// The shell told us this player re-arranged their emote wheel (helix:event 'emotes-changed', v28): hint the
|
|
464
|
+
// joined room to re-resolve OUR seat's set — the same empty-payload message the world-facing
|
|
465
|
+
// HelixRoom.sendEmoteRefresh sends, because a client may never name the clip URLs on its own seat. Best-effort
|
|
466
|
+
// like the receipt forward: no room / a closed socket needs no hint, since the next join resolves the set
|
|
467
|
+
// server-side anyway. Throttling is the room's per-seat cooldown, and the shell coalesces a wardrobe session
|
|
468
|
+
// into ONE cue before this is ever called.
|
|
469
|
+
sendEmoteRefresh() {
|
|
470
|
+
if (!this.room || this.room.connection?.isOpen === false)
|
|
471
|
+
return false;
|
|
472
|
+
try {
|
|
473
|
+
this.room.send(ClientMessageType.EmoteRefresh, {});
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
45
480
|
// The API base other SDK modules should use for direct platform calls (Helix.avatar): the pinned
|
|
46
|
-
// configure() value, else the
|
|
481
|
+
// configure() value, else the shell's helix:init announcement, else the world_session token's `iss`.
|
|
482
|
+
// Null → the caller treats it as "no API".
|
|
47
483
|
resolveApiBase(token) {
|
|
48
|
-
return this.apiBaseUrl ?? (token !== null ? issuerOf(token) : null);
|
|
484
|
+
return this.apiBaseUrl ?? this.shellApiBaseUrl ?? (token !== null ? issuerOf(token) : null);
|
|
49
485
|
}
|
|
50
|
-
// Join (or create) this world's room. worldId defaults to the current world.
|
|
51
|
-
//
|
|
486
|
+
// Join (or create) this world's room. worldId defaults to the current world.
|
|
487
|
+
//
|
|
488
|
+
// GUESTS JOIN. This comment used to read "multiplayer is logged-in only (single-player for
|
|
489
|
+
// guests)", on the premise that a guest has no world_session and cannot reach /join. Both halves
|
|
490
|
+
// stopped being true when guests got room credentials: a signed-out visitor is minted a real
|
|
491
|
+
// world_session (30-day cookie, stable subject per browser+world), the `multiplayer` scope is
|
|
492
|
+
// granted to guests by name, and `POST /api/v1/instant-worlds/:id/join` carries
|
|
493
|
+
// `@AllowGuestWorldSession()`. A world built against the old claim would offer a signed-out
|
|
494
|
+
// player a single-player fallback they do not need.
|
|
495
|
+
//
|
|
496
|
+
// What a guest still cannot do is everything that needs an ACCOUNT — voice, leaderboard
|
|
497
|
+
// submits, purchases, inventory. Those refuse individually, at the call that needs them; none of
|
|
498
|
+
// them is a reason to keep a player out of the room.
|
|
499
|
+
//
|
|
500
|
+
// Requires a world session, which is not the same thing as a login: `getToken()` is null outside
|
|
501
|
+
// a HELIX shell, or before the shell has announced one.
|
|
502
|
+
//
|
|
503
|
+
// ROOM TYPES (SPEC-U1). `options.roomType` joins an OPEN named room type, `options.ticket` redeems a
|
|
504
|
+
// ticket to a ticketed instance. With neither this is the world's default room and NOTHING changes: the
|
|
505
|
+
// request has no body and the join options are the same four keys, so a world that never opts in is
|
|
506
|
+
// byte-identical on the wire.
|
|
507
|
+
//
|
|
508
|
+
// • `?instance=` AND a typed/ticket join. The shell's instance id names a room of the DEFAULT type (it
|
|
509
|
+
// comes from the server browser, which lists default rooms only). So it governs default joins only: a
|
|
510
|
+
// typed or ticket join IGNORES it — no strict joinById, no helix:multiplayer-join-error — and it keeps
|
|
511
|
+
// applying, unchanged and strict, the next time this tab makes a first default join.
|
|
512
|
+
//
|
|
513
|
+
// • RESUME. A reload resumes the room the tab was IN, whatever its type: a plain `joinRoom()` first tries
|
|
514
|
+
// the typed room recorded as active (its own per-type reconnect slot), and only then the default slot.
|
|
515
|
+
// That is what lets a reload mid-match come back to the match even though the page URL's `?instance=`
|
|
516
|
+
// still names the lobby the player entered through — the strict "another room's record is dropped"
|
|
517
|
+
// rule is a DEFAULT-slot rule and never touches a typed slot. Read `room.roomType` to learn where you
|
|
518
|
+
// landed. `joinRoom({ roomType })` resumes only that type's slot; `joinRoom({ ticket })` never resumes.
|
|
519
|
+
//
|
|
520
|
+
// The exception is a NEW SERVER PICK: the typed room remembers the `?instance=` it was entered under, and
|
|
521
|
+
// a plain joinRoom() under a different one drops the typed resume and makes the strict default join.
|
|
522
|
+
//
|
|
523
|
+
// • A TICKETED room whose reconnect token is gone (grace expired, storage lost) is re-entered through the
|
|
524
|
+
// backend: POST …/room-instances/:instanceId/rejoin mints a fresh ticket, which is then redeemed like any
|
|
525
|
+
// other. The instance is remembered from the moment the reservation returns — BEFORE the socket connects —
|
|
526
|
+
// because the ticket is already spent by then: if the connect fails or the page unloads, rejoin is the
|
|
527
|
+
// only way back in. If rejoin is refused the join REJECTS with a HelixRoomJoinError instead of quietly
|
|
528
|
+
// seating the player in a default room: `instance-closed` (410, the match is over) and a 404 are final
|
|
529
|
+
// and the instance is forgotten, so the caller's NEXT joinRoom() is an ordinary join; a 5xx or a network
|
|
530
|
+
// failure is `rejoin-failed` with the instance KEPT, so the next joinRoom() asks again. To abandon a
|
|
531
|
+
// remembered instance on purpose, hop elsewhere (`switchRoom({})`).
|
|
532
|
+
// An OPEN typed room has no such handle; when its seat is gone the join just falls through to default.
|
|
533
|
+
//
|
|
534
|
+
// • A joinRoom() while a switchRoom hop is in flight is refused (`switch-in-progress`): the hop is already
|
|
535
|
+
// joining, and a second connection would fight it for the account's one seat.
|
|
536
|
+
//
|
|
537
|
+
// • After the player has left the world (the shell's Exit / Back, `Helix.hasLeft()`), every join is refused
|
|
538
|
+
// `left` before anything else is looked at — whether or not a room was held when the leave came.
|
|
52
539
|
async joinRoom(worldId, options = {}) {
|
|
540
|
+
this.refuseIfLeft('joinRoom');
|
|
541
|
+
if (this.switching) {
|
|
542
|
+
throw new HelixRoomJoinError('switch-in-progress', 'Helix.multiplayer: a room switch is in progress — it is already joining the next room');
|
|
543
|
+
}
|
|
544
|
+
if (!this.host.isInitialized())
|
|
545
|
+
throw new Error('Helix: call Helix.init() before Helix.multiplayer.joinRoom()');
|
|
546
|
+
if (this.room)
|
|
547
|
+
throw new Error('Helix.multiplayer: already in a room — call leave() first');
|
|
548
|
+
// One join at a time. Two overlapping joins share this object's actor binding, so the second could relabel
|
|
549
|
+
// the seat the first is about to persist. Refused rather than queued: nothing waits, so nothing can
|
|
550
|
+
// deadlock against a hop, and the caller decides whether to try again. The message is the platform's own;
|
|
551
|
+
// the type and code let a world branch on it like every other "nothing changed" refusal.
|
|
552
|
+
if (this.joining)
|
|
553
|
+
throw new HelixRoomJoinError('join-in-progress', 'Helix.multiplayer: a room join is already in progress');
|
|
554
|
+
this.joining = true;
|
|
555
|
+
const entering = this.beginEntering('joinRoom', worldId);
|
|
556
|
+
try {
|
|
557
|
+
const room = await this.joinRoomInternal(worldId, options, { resume: true, strictInstance: true, preferInstanceId: null });
|
|
558
|
+
if (entering.cancelled)
|
|
559
|
+
await this.abandonEntered('joinRoom');
|
|
560
|
+
return room;
|
|
561
|
+
}
|
|
562
|
+
catch (e) {
|
|
563
|
+
if (entering.cancelled)
|
|
564
|
+
this.forgetCancelledTarget(worldId);
|
|
565
|
+
throw e;
|
|
566
|
+
}
|
|
567
|
+
finally {
|
|
568
|
+
this.joining = false;
|
|
569
|
+
entering.finish();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// The player has left this world: no room may be entered again. Thrown synchronously from the async entry
|
|
573
|
+
// points, so it is their rejection, and it comes before every other check — `left` is final, every other
|
|
574
|
+
// refusal describes a moment.
|
|
575
|
+
refuseIfLeft(call) {
|
|
576
|
+
if (this.host.hasLeft?.()) {
|
|
577
|
+
throw new HelixRoomJoinError('left', `Helix.multiplayer: ${call} refused — the player has left this world`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
beginEntering(call, worldId) {
|
|
581
|
+
let finish;
|
|
582
|
+
let giveUp;
|
|
583
|
+
const entry = {
|
|
584
|
+
call,
|
|
585
|
+
worldId,
|
|
586
|
+
cancelled: false,
|
|
587
|
+
done: new Promise((resolve) => { finish = resolve; }),
|
|
588
|
+
abandoned: new Promise((resolve) => { giveUp = () => resolve(ABANDONED); }),
|
|
589
|
+
giveUp: () => giveUp(),
|
|
590
|
+
};
|
|
591
|
+
this.entering = entry;
|
|
592
|
+
return {
|
|
593
|
+
get cancelled() { return entry.cancelled; },
|
|
594
|
+
finish: () => {
|
|
595
|
+
if (this.entering === entry)
|
|
596
|
+
this.entering = null;
|
|
597
|
+
finish();
|
|
598
|
+
},
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
// leave() arrived while this join / hop was entering a room. Whatever seat it has taken by now is released
|
|
602
|
+
// (consented, bounded), nothing is left to resume into, and the call that was overtaken rejects.
|
|
603
|
+
async abandonEntered(call) {
|
|
604
|
+
if (this.ctx)
|
|
605
|
+
await this.leaveRoom(this.ctx);
|
|
606
|
+
throw new HelixRoomJoinError('cancelled', `Helix.multiplayer: ${call} was cancelled by leave()`);
|
|
607
|
+
}
|
|
608
|
+
// Wait for one step of the join in flight — the reservation request, the rejoin request, the room handshake —
|
|
609
|
+
// unless leave() gives up on the join first. None of those steps has a deadline of its own, and the requests
|
|
610
|
+
// cannot carry an abort signal without changing what a default join sends (its fetch init is exactly
|
|
611
|
+
// `{ method, headers }`, on every SDK version). So the step is raced instead: when the leave bound expires
|
|
612
|
+
// the join stops waiting and rejects `cancelled`, its join / hop guard is released, and nothing it was
|
|
613
|
+
// waiting for is used when it does arrive — a late answer is dropped, and a late SEAT is handed to
|
|
614
|
+
// `release`, which gives it back. For a join nobody gives up on this is the step itself, awaited.
|
|
615
|
+
async abandonable(step, release) {
|
|
616
|
+
const entering = this.entering;
|
|
617
|
+
if (!entering)
|
|
618
|
+
return step;
|
|
619
|
+
const outcome = await Promise.race([step, entering.abandoned]);
|
|
620
|
+
if (outcome !== ABANDONED)
|
|
621
|
+
return outcome;
|
|
622
|
+
step.then(release, () => undefined);
|
|
623
|
+
throw new HelixRoomJoinError('cancelled', `Helix.multiplayer: ${entering.call} was cancelled by leave()`);
|
|
624
|
+
}
|
|
625
|
+
// A room the transport delivered after the join that asked for it was given up on. It was never the current
|
|
626
|
+
// room and never will be: no reconnection, a consented leave (bounded, forced if unanswered) so the server
|
|
627
|
+
// frees the seat at once.
|
|
628
|
+
releaseLateRoom = (room) => {
|
|
629
|
+
this.abandonRoom(room);
|
|
630
|
+
void this.leaveBounded({ room, leaveReason: 'leave', released: false, leaveCbs: [], ticketCbs: new Set() });
|
|
631
|
+
};
|
|
632
|
+
// leave() overtook a join / hop that then FAILED, so there is no seat to release — but a ticketed room's
|
|
633
|
+
// active-room pointer is written at reservation time and deliberately survives a failed connect (it is the
|
|
634
|
+
// rejoin handle). The player left on purpose: without this the next plain joinRoom() would rejoin the very
|
|
635
|
+
// instance they walked away from. Same rule as leaving a typed room that was entered.
|
|
636
|
+
forgetCancelledTarget(worldId) {
|
|
637
|
+
const id = worldId ?? this.host.getWorldId();
|
|
638
|
+
if (id)
|
|
639
|
+
this.clearActiveRoom(id);
|
|
640
|
+
}
|
|
641
|
+
// Hop to another room of this world: a consented leave of the current room (the seat is freed at once, no
|
|
642
|
+
// reconnect grace), then a join of `target` — `{ ticket }` redeems a ticket, `{ roomType? }` matchmakes
|
|
643
|
+
// into an open type (omitted = the default room), and `preferInstanceId` tries one specific room first and
|
|
644
|
+
// falls back to the matchmaker when it is gone or full. Resolves the NEW room handle; every handle,
|
|
645
|
+
// subscription and engagement of the old room is dead.
|
|
646
|
+
//
|
|
647
|
+
// WHAT A REJECTION COSTS. Everything that can be checked is checked BEFORE anything is given up — the target
|
|
648
|
+
// shape, the session, the API base, another join or hop in flight — so an argument error or a signed-out
|
|
649
|
+
// session never costs the seat: `left`, `invalid-target`, `not-ready`, `switch-in-progress` and
|
|
650
|
+
// `join-in-progress` reject with the caller exactly where it was. Past that point the old seat is released before the new one
|
|
651
|
+
// is requested (an account holds one seat), so every OTHER rejection leaves the caller in NO room: there is
|
|
652
|
+
// no old room to fall back into, and pretending otherwise would leave a world rendering a room it is no
|
|
653
|
+
// longer in. `Helix.multiplayer.currentRoomId()` is the ground truth either way; the caller decides what
|
|
654
|
+
// next (typically `joinRoom()`).
|
|
655
|
+
//
|
|
656
|
+
// THE LEAVE IS BOUNDED. Colyseus settles leave() only when the socket's close arrives, so on a dropped or
|
|
657
|
+
// reconnecting room it may never settle (or throw). The hop waits ROOM_LEAVE_TIMEOUT_MS, then
|
|
658
|
+
// detaches the old room locally — listeners dropped, socket closed, its reconnect token already forgotten —
|
|
659
|
+
// and carries on. The old handle's onLeave fires exactly once either way, with reason `'switch'`, so a
|
|
660
|
+
// world can tell a hop it started from a room that died under it and must NOT auto-rejoin on it.
|
|
661
|
+
//
|
|
662
|
+
// `?instance=`: never strict here. For a default-type target with no `preferInstanceId`, the shell's
|
|
663
|
+
// instance is used as the PREFERRED room — "back to the server I picked" — with the same matchmaker
|
|
664
|
+
// fallback. Typed and ticket targets ignore it.
|
|
665
|
+
//
|
|
666
|
+
// VOICE follows the hop when it was following the room: it is detached before the leave — also when there
|
|
667
|
+
// is no room to leave, since voice may still be paired to a room that died — and re-joined against the new
|
|
668
|
+
// room with the same join options (the channel, mic mode and mutes survive a voice teardown by design).
|
|
669
|
+
// The new room handle is returned as soon as the ROOM is joined; voice re-joins in the background (it may
|
|
670
|
+
// sit behind a microphone prompt) and a voice failure is logged, never thrown. When the hop FAILS, voice
|
|
671
|
+
// stays left: a voice room is paired to a room instance, the caller is in no room, so there is nothing
|
|
672
|
+
// consistent to restore it to — `Helix.voice.join()` again after the next successful join.
|
|
673
|
+
//
|
|
674
|
+
// The shell sees helix:multiplayer-state go null, then the new room's state.
|
|
675
|
+
async switchRoom(target, options = {}) {
|
|
676
|
+
this.refuseIfLeft('switchRoom');
|
|
677
|
+
if (this.switching) {
|
|
678
|
+
throw new HelixRoomJoinError('switch-in-progress', 'Helix.multiplayer: a room switch is already in progress');
|
|
679
|
+
}
|
|
680
|
+
if (this.joining) {
|
|
681
|
+
throw new HelixRoomJoinError('join-in-progress', 'Helix.multiplayer: a joinRoom() is still in progress — wait for it before switching rooms');
|
|
682
|
+
}
|
|
683
|
+
// ── Everything below this line and above `switching = true` must be free of side effects. ──
|
|
684
|
+
const raw = (target ?? {});
|
|
685
|
+
const present = (value) => value !== undefined && value !== null;
|
|
686
|
+
const usable = (value) => typeof value === 'string' && value.length > 0;
|
|
687
|
+
if (typeof target !== 'object' || target === null ||
|
|
688
|
+
(present(raw.ticket) && !usable(raw.ticket)) ||
|
|
689
|
+
(present(raw.roomType) && !usable(raw.roomType)) ||
|
|
690
|
+
(present(raw.preferInstanceId) && !usable(raw.preferInstanceId)) ||
|
|
691
|
+
(present(raw.ticket) && (present(raw.roomType) || present(raw.preferInstanceId)))) {
|
|
692
|
+
throw new HelixRoomJoinError('invalid-target', 'Helix.multiplayer: switchRoom needs { ticket } or { roomType?, preferInstanceId? }');
|
|
693
|
+
}
|
|
694
|
+
const ticket = usable(raw.ticket) ? raw.ticket : undefined;
|
|
695
|
+
const roomType = usable(raw.roomType) ? raw.roomType : undefined;
|
|
696
|
+
const preferInstanceId = ticket !== undefined
|
|
697
|
+
? null
|
|
698
|
+
: usable(raw.preferInstanceId)
|
|
699
|
+
? raw.preferInstanceId
|
|
700
|
+
: roomType === undefined ? this.host.getInstanceId?.() ?? null : null;
|
|
701
|
+
const worldId = this.worldId ?? undefined; // captured now: the leave tears the world id down with the room
|
|
702
|
+
const id = worldId ?? this.host.getWorldId();
|
|
703
|
+
const token = this.host.isInitialized() ? this.host.getToken() : null;
|
|
704
|
+
const notReady = !this.host.isInitialized()
|
|
705
|
+
? 'call Helix.init() first'
|
|
706
|
+
: !token
|
|
707
|
+
? 'no world session'
|
|
708
|
+
: !id
|
|
709
|
+
? 'no world id'
|
|
710
|
+
: !(options.apiBaseUrl ?? this.resolveApiBase(token))
|
|
711
|
+
? 'cannot resolve the API base URL'
|
|
712
|
+
: null;
|
|
713
|
+
if (notReady !== null || !id) {
|
|
714
|
+
throw new HelixRoomJoinError('not-ready', `Helix.multiplayer: cannot switch rooms — ${notReady ?? 'no world id'}`);
|
|
715
|
+
}
|
|
716
|
+
this.switching = true;
|
|
717
|
+
const entering = this.beginEntering('switchRoom', id);
|
|
718
|
+
try {
|
|
719
|
+
// Voice first, and regardless of whether there is a room to leave: it may be paired to a room that died.
|
|
720
|
+
// BOUNDED like the leave below: a voice disconnect that never settles must not hold the hop lock for
|
|
721
|
+
// ever. Past the bound the hop goes on; the closure is still honoured if the detach settles later.
|
|
722
|
+
const detaching = this.host.detachVoice
|
|
723
|
+
? this.host.detachVoice().catch(() => null)
|
|
724
|
+
: Promise.resolve(null);
|
|
725
|
+
let detachTimer;
|
|
726
|
+
const detached = await Promise.race([
|
|
727
|
+
detaching.then((resume) => ({ resume })),
|
|
728
|
+
new Promise((resolve) => { detachTimer = setTimeout(() => resolve(null), ROOM_LEAVE_TIMEOUT_MS); }),
|
|
729
|
+
]);
|
|
730
|
+
if (detachTimer !== undefined)
|
|
731
|
+
clearTimeout(detachTimer);
|
|
732
|
+
if (entering.cancelled)
|
|
733
|
+
await this.abandonEntered('switchRoom');
|
|
734
|
+
const leaving = this.detachCurrentRoom('switch');
|
|
735
|
+
if (leaving)
|
|
736
|
+
await this.leaveBounded(leaving);
|
|
737
|
+
// Nothing persisted may pull the player back: not the room just left (already cleared), and not an
|
|
738
|
+
// older slot from before a reload. A hop goes where it was told, or nowhere.
|
|
739
|
+
this.forgetReconnectSlots(id);
|
|
740
|
+
if (entering.cancelled)
|
|
741
|
+
await this.abandonEntered('switchRoom');
|
|
742
|
+
const room = await this.joinRoomInternal(worldId, { ...options, roomType, ticket }, { resume: false, strictInstance: false, preferInstanceId });
|
|
743
|
+
if (entering.cancelled)
|
|
744
|
+
await this.abandonEntered('switchRoom');
|
|
745
|
+
// NOT awaited: the room is live and the handle is the caller's now. Voice may take seconds (or a
|
|
746
|
+
// permission prompt), and must hold neither the handle nor the hop lock. Re-joined only while the room
|
|
747
|
+
// this hop entered is still the current one.
|
|
748
|
+
const entered = this.ctx;
|
|
749
|
+
const rejoinVoice = (resumeVoice) => {
|
|
750
|
+
if (!resumeVoice || this.ctx !== entered)
|
|
751
|
+
return;
|
|
752
|
+
let voice;
|
|
753
|
+
try {
|
|
754
|
+
voice = resumeVoice();
|
|
755
|
+
}
|
|
756
|
+
catch (e) {
|
|
757
|
+
voice = Promise.reject(e);
|
|
758
|
+
}
|
|
759
|
+
void voice.catch((e) => console.warn('[Helix] multiplayer.switchRoom: voice did not re-join the new room —', e instanceof Error ? e.message : String(e)));
|
|
760
|
+
};
|
|
761
|
+
if (detached)
|
|
762
|
+
rejoinVoice(detached.resume);
|
|
763
|
+
else
|
|
764
|
+
void detaching.then(rejoinVoice);
|
|
765
|
+
return room;
|
|
766
|
+
}
|
|
767
|
+
catch (e) {
|
|
768
|
+
if (entering.cancelled)
|
|
769
|
+
this.forgetCancelledTarget(id);
|
|
770
|
+
throw e instanceof HelixRoomJoinError
|
|
771
|
+
? e
|
|
772
|
+
: new HelixRoomJoinError('join-failed', e instanceof Error ? e.message : String(e), null, e);
|
|
773
|
+
}
|
|
774
|
+
finally {
|
|
775
|
+
this.switching = false;
|
|
776
|
+
entering.finish();
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
async joinRoomInternal(worldId, options, plan) {
|
|
53
780
|
if (!this.host.isInitialized())
|
|
54
781
|
throw new Error('Helix: call Helix.init() before Helix.multiplayer.joinRoom()');
|
|
55
782
|
if (this.room)
|
|
56
783
|
throw new Error('Helix.multiplayer: already in a room — call leave() first');
|
|
57
784
|
const token = this.host.getToken();
|
|
785
|
+
// NOT "requires login": a guest has a world session and joins. Reaching here means there is no
|
|
786
|
+
// session AT ALL — running outside a HELIX shell, or before `helix:init` announced one.
|
|
58
787
|
if (!token)
|
|
59
|
-
throw new Error('Helix.multiplayer: multiplayer
|
|
788
|
+
throw new Error('Helix.multiplayer: no world session — multiplayer needs a session from the HELIX shell (signed in or guest)');
|
|
60
789
|
const id = worldId ?? this.host.getWorldId();
|
|
61
790
|
if (!id)
|
|
62
791
|
throw new Error('Helix.multiplayer: no world id — pass joinRoom(worldId) when running outside a HELIX shell');
|
|
63
792
|
const apiBase = options.apiBaseUrl?.replace(/\/$/, '') ?? this.resolveApiBase(token);
|
|
64
793
|
if (!apiBase)
|
|
65
794
|
throw new Error('Helix.multiplayer: cannot resolve the API base URL — call Helix.multiplayer.configure({ apiBaseUrl })');
|
|
795
|
+
// The join API has one row per body shape — default, { roomType }, { ticket } — and none for both.
|
|
796
|
+
if ((options.roomType !== undefined && (typeof options.roomType !== 'string' || !options.roomType)) ||
|
|
797
|
+
(options.ticket !== undefined && (typeof options.ticket !== 'string' || !options.ticket)) ||
|
|
798
|
+
(options.roomType !== undefined && options.ticket !== undefined)) {
|
|
799
|
+
throw new HelixRoomJoinError('invalid-target', 'Helix.multiplayer: pass a non-empty roomType OR a non-empty ticket, never both');
|
|
800
|
+
}
|
|
801
|
+
const requestedType = options.roomType ?? null;
|
|
802
|
+
let ticket = options.ticket ?? null;
|
|
803
|
+
// Resume bypasses the room's onAuth. A token from another account (or an
|
|
804
|
+
// old unbound record) must instead take the normal authenticated join.
|
|
805
|
+
// This one binding guards every resume below: the typed slot, the active-room pointer that selects it (and
|
|
806
|
+
// its ticketed rejoin), and the default slot. A hop (switchRoom) passes through here too.
|
|
807
|
+
this.sessionIdentity = reconnectIdentityOf(token);
|
|
66
808
|
const colyseus = (await import('@colyseus/sdk'));
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
//
|
|
70
|
-
|
|
809
|
+
const instanceId = this.host.getInstanceId?.() ?? null;
|
|
810
|
+
let room = null;
|
|
811
|
+
// The ticketed instance a rejoin ticket was minted for (resume path only) — so a redeem that then finds the
|
|
812
|
+
// instance closed can forget it.
|
|
813
|
+
let rejoinInstance = null;
|
|
814
|
+
if (plan.resume && ticket === null) {
|
|
815
|
+
// TYPED SLOT FIRST. The active-room pointer names the typed room this tab was last seated in; an
|
|
816
|
+
// explicit roomType narrows the resume to that type. The shell's instance id is deliberately NOT
|
|
817
|
+
// consulted here: it names a default-type room and has no say over a typed one.
|
|
818
|
+
let active = this.readActiveRoom(id);
|
|
819
|
+
// A NEW SERVER PICK outranks a remembered match. The pointer records the shell's `?instance=` at the time
|
|
820
|
+
// the typed room was entered; a reload keeps the URL, so the two agree and the typed room is resumed. If
|
|
821
|
+
// they differ on a PLAIN joinRoom(), the player chose another server from the shell since — drop the
|
|
822
|
+
// typed resume entirely and let the strict default join below honour that choice.
|
|
823
|
+
if (active && requestedType === null && active.shellInstance !== instanceId) {
|
|
824
|
+
this.clearReconnect(reconnectScope(id, active.roomType));
|
|
825
|
+
this.clearActiveRoom(id);
|
|
826
|
+
active = null;
|
|
827
|
+
}
|
|
828
|
+
const typed = requestedType === null
|
|
829
|
+
? active
|
|
830
|
+
: active?.roomType === requestedType ? active : { roomType: requestedType, instanceKey: null, shellInstance: instanceId };
|
|
831
|
+
if (typed) {
|
|
832
|
+
room = await this.tryReconnect(colyseus, reconnectScope(id, typed.roomType), null, typed);
|
|
833
|
+
if (!room) {
|
|
834
|
+
const pointed = active?.roomType === typed.roomType;
|
|
835
|
+
if (typed.instanceKey === null) {
|
|
836
|
+
// An OPEN type has no instance to come back to: its seat is gone, so is the memory of it.
|
|
837
|
+
if (pointed)
|
|
838
|
+
this.clearActiveRoom(id);
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
rejoinInstance = typed.instanceKey;
|
|
842
|
+
try {
|
|
843
|
+
ticket = await this.abandonable(this.requestRejoin(apiBase, id, token, typed.instanceKey));
|
|
844
|
+
}
|
|
845
|
+
catch (e) {
|
|
846
|
+
// Final answers (403 / 404 / 410: forbidden, not this player's instance, closed) forget the
|
|
847
|
+
// instance, so the next joinRoom() is an ordinary join and nothing is retried. Anything that says
|
|
848
|
+
// nothing about the match — no answer at all, 5xx, 429, or a 401 the session may refresh out of —
|
|
849
|
+
// keeps the pointer, so the caller's next joinRoom() simply asks again.
|
|
850
|
+
const retryable = e instanceof HelixRoomJoinError && isRetryableRejoinStatus(e.status);
|
|
851
|
+
if (pointed && !retryable)
|
|
852
|
+
this.clearActiveRoom(id);
|
|
853
|
+
throw e;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
// RESUME FIRST only when it is the SAME explicit room: on a reload, a seat persisted in sessionStorage is still held in the server's grace window —
|
|
859
|
+
// reconnect to it (resumes the same seat + its vars, bypassing onAuth) instead of a fresh join that onAuth
|
|
860
|
+
// would reject as a duplicate. On any failure (grace expired / clean despawn / new tab) fall back to /join.
|
|
861
|
+
if (!room && ticket === null && requestedType === null)
|
|
862
|
+
room = await this.tryReconnect(colyseus, id, instanceId, null);
|
|
863
|
+
}
|
|
864
|
+
const resumedSeat = room !== null;
|
|
71
865
|
if (!room) {
|
|
72
|
-
|
|
866
|
+
this.vehicleActionSeq = new Map();
|
|
867
|
+
const body = ticket !== null ? { ticket } : requestedType !== null ? { roomType: requestedType } : null;
|
|
868
|
+
let reservation;
|
|
869
|
+
try {
|
|
870
|
+
reservation = await this.abandonable(this.requestJoin(apiBase, id, token, options.reservationPath, body));
|
|
871
|
+
}
|
|
872
|
+
catch (e) {
|
|
873
|
+
// The rejoin endpoint said the instance was open, the redeem says it closed in between: same verdict.
|
|
874
|
+
if (rejoinInstance !== null && e instanceof HelixRoomJoinError && e.code === 'instance-closed')
|
|
875
|
+
this.clearActiveRoom(id);
|
|
876
|
+
throw e;
|
|
877
|
+
}
|
|
878
|
+
const joinedType = typeof reservation.roomType === 'string' && reservation.roomType ? reservation.roomType : null;
|
|
879
|
+
const joinedInstance = typeof reservation.instanceKey === 'string' && reservation.instanceKey ? reservation.instanceKey : null;
|
|
880
|
+
// A backend that predates room types ignores the body and reserves a DEFAULT room. Connecting anyway
|
|
881
|
+
// would seat the player somewhere they did not ask to be and report success — the same silent
|
|
882
|
+
// substitution the strict instance join exists to prevent — so a typed request must be echoed back
|
|
883
|
+
// (the room would reject a missing roomType/instanceKey option against its claims regardless).
|
|
884
|
+
if (ticket !== null ? joinedType === null || joinedInstance === null : requestedType !== null && joinedType !== requestedType) {
|
|
885
|
+
throw new HelixRoomJoinError('room-type-unavailable', 'Helix.multiplayer: join failed — the platform did not reserve the requested room type (room types may not be enabled for this world)');
|
|
886
|
+
}
|
|
887
|
+
// REMEMBER THE ROOM NOW, before connecting. For a ticketed room the ticket is already spent at this point:
|
|
888
|
+
// if the connect below fails, or the page unloads mid-handshake, the instance id is the only way back in
|
|
889
|
+
// (the rejoin endpoint) — losing it would lose the player's place in the match. It is cleared only when
|
|
890
|
+
// the instance is known closed, or the world leaves by choice.
|
|
891
|
+
if (joinedType !== null)
|
|
892
|
+
this.writeActiveRoom(id, { roomType: joinedType, instanceKey: joinedInstance, shellInstance: instanceId });
|
|
73
893
|
const client = new colyseus.Client(reservation.wsUrl);
|
|
74
894
|
// buildId is the matchmaking filter (room filterBy(['buildId'])) — it groups players per active build.
|
|
75
895
|
// The room re-validates it against the verified credential in onAuth, so a spoofed value can't cross builds.
|
|
76
896
|
// contractVersion is the wire-protocol version baked into THIS bundle's SDK — onAuth logs a mismatch against
|
|
77
897
|
// the room's version (diagnostics for cross-version play) but never rejects, since old bundles are frozen.
|
|
78
|
-
|
|
79
|
-
|
|
898
|
+
const joinOptions = {
|
|
899
|
+
token: reservation.credential,
|
|
900
|
+
buildId: reservation.buildId,
|
|
901
|
+
contractVersion: CONTRACT_VERSION,
|
|
902
|
+
// Colyseus only filters on option keys present in the matchmaking request. Omitting
|
|
903
|
+
// trialId for the ordinary cohort can therefore select an existing trial room with the
|
|
904
|
+
// same buildId, which the room correctly rejects during onAuth. Send the normalized empty
|
|
905
|
+
// cohort explicitly so base and trial sessions are partitioned before admission.
|
|
906
|
+
trialId: reservation.trialId ?? '',
|
|
907
|
+
// Room types: forwarded ONLY when the reservation carries them. Absent on both sides is how the client
|
|
908
|
+
// and the credential agree on "default type"; an empty-string placeholder (the trialId treatment above)
|
|
909
|
+
// would change the default join's wire bytes, which room types must not do. The room distrusts both
|
|
910
|
+
// values and rejects unless they equal the verified claims.
|
|
911
|
+
...(joinedType !== null ? { roomType: joinedType } : {}),
|
|
912
|
+
...(joinedInstance !== null ? { instanceKey: joinedInstance } : {}),
|
|
913
|
+
};
|
|
914
|
+
// Instance-scoped join: when the shell handed us a target roomId (?instance=), that room is the
|
|
915
|
+
// player's explicit choice — join EXACTLY it or fail LOUDLY (publishInstanceJoinError → the shell
|
|
916
|
+
// offers back / fresh-join). No matchmaker fallback: silently seating the player in a NEW room read
|
|
917
|
+
// as "I joined them" when they hadn't (the website Join button pre-validates, but a room can die in
|
|
918
|
+
// the seconds between that check and this join). A reconnect record only
|
|
919
|
+
// wins when it names this exact instance; another room is never resumed.
|
|
920
|
+
//
|
|
921
|
+
// Strict only for a DEFAULT first join (see the joinRoom header): a typed/ticket join ignores the shell's
|
|
922
|
+
// instance, and a switchRoom hop turns it into a preference with a matchmaker fallback.
|
|
923
|
+
if (plan.preferInstanceId) {
|
|
924
|
+
try {
|
|
925
|
+
room = await this.abandonable(client.joinById(plan.preferInstanceId, joinOptions), this.releaseLateRoom);
|
|
926
|
+
}
|
|
927
|
+
catch (e) {
|
|
928
|
+
if (isAbandonment(e))
|
|
929
|
+
throw e; // leave() gave up on this join: no second attempt
|
|
930
|
+
// Gone, full or locked. Non-strict by contract — matchmake into the same type instead, quietly: this
|
|
931
|
+
// was the SDK's (or the world's) preference, not a room the player explicitly asked the shell for.
|
|
932
|
+
room = await this.connectOrForget(id, joinedType, joinedInstance, () => this.abandonable(client.joinOrCreate(reservation.roomName, joinOptions), this.releaseLateRoom));
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
else if (instanceId && body === null && plan.strictInstance) {
|
|
936
|
+
try {
|
|
937
|
+
room = await this.abandonable(client.joinById(instanceId, joinOptions), this.releaseLateRoom);
|
|
938
|
+
}
|
|
939
|
+
catch (e) {
|
|
940
|
+
if (isAbandonment(e))
|
|
941
|
+
throw e; // not a refusal by the instance: nothing to tell the shell
|
|
942
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
943
|
+
this.host.publishInstanceJoinError?.(instanceId, reason);
|
|
944
|
+
// The platform's wording for the default path, unchanged; the SERVER's own reason rides in the
|
|
945
|
+
// parentheses (and reaches the shell verbatim through publishInstanceJoinError above).
|
|
946
|
+
throw new Error(`Helix.multiplayer: could not join instance ${instanceId} — it may be full, locked, or no longer exist (${reason})`);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
else {
|
|
950
|
+
room = await this.connectOrForget(id, joinedType, joinedInstance, () => this.abandonable(client.joinOrCreate(reservation.roomName, joinOptions), this.releaseLateRoom));
|
|
951
|
+
}
|
|
952
|
+
// The credential also tells US the room's seat cap — read it unverified for DISPLAY only (the shell
|
|
953
|
+
// roster panel); the room enforces the real cap server-side in onAuth.
|
|
954
|
+
this.roomMaxPlayers = maxPlayersOf(reservation.credential);
|
|
955
|
+
this.roomType = joinedType;
|
|
956
|
+
this.instanceKey = joinedInstance;
|
|
957
|
+
this.persistReconnect(reconnectScope(id, joinedType), reservation.wsUrl, room.reconnectionToken, room.roomId);
|
|
80
958
|
}
|
|
959
|
+
// Record which room a reload should come back to. A typed room names itself (with its instance, the rejoin
|
|
960
|
+
// handle); the default room is the absence of a pointer — so a world that never uses room types never
|
|
961
|
+
// writes this key at all.
|
|
962
|
+
if (this.roomType !== null)
|
|
963
|
+
this.writeActiveRoom(id, { roomType: this.roomType, instanceKey: this.instanceKey, shellInstance: instanceId });
|
|
964
|
+
else
|
|
965
|
+
this.clearActiveRoom(id);
|
|
966
|
+
// One typed room at a time: a slot left behind by ANOTHER type (a drop, an unload mid-hop) can only ever
|
|
967
|
+
// resume a seat the player is no longer in, so entering a room clears every other typed slot of this world.
|
|
968
|
+
this.clearOtherTypedSlots(id, this.roomType);
|
|
81
969
|
this.worldId = id;
|
|
970
|
+
this.reconnectScope = reconnectScope(id, this.roomType);
|
|
82
971
|
this.room = room;
|
|
972
|
+
// The automatic reconnect follows the room's grace: it also covers a drop right after the join, and it gives
|
|
973
|
+
// up once the seat can no longer be held (see followReconnectGrace).
|
|
974
|
+
followReconnectGrace(room);
|
|
975
|
+
const ctx = { room, leaveReason: null, released: false, leaveCbs: [], ticketCbs: new Set() };
|
|
976
|
+
this.ctx = ctx;
|
|
977
|
+
// Every callback registered on this room below is wrapped: it runs only while THIS room is the current one.
|
|
978
|
+
// An event that arrives after the SDK left the room (or hopped to another) is dropped on the floor.
|
|
979
|
+
const live = (fn) => (...args) => {
|
|
980
|
+
if (this.ctx === ctx)
|
|
981
|
+
fn(...args);
|
|
982
|
+
};
|
|
983
|
+
room.onMessage(DISTRIBUTION_CAPABILITY_RESULT, live((p) => this.settleDistributionCapability(p)));
|
|
984
|
+
const finalRest = new FinalRestClient((type, payload) => room.send(type, payload), () => ++this.entityBatchSeq);
|
|
985
|
+
this.finalRestClient = finalRest;
|
|
986
|
+
for (const type of ['moduleFused', 'moduleSleep'])
|
|
987
|
+
room.onMessage(type, live((p) => finalRest.invalidateModule(p.moduleId)));
|
|
988
|
+
room.onMessage('pong', live((p) => finalRest.capability(p)));
|
|
989
|
+
room.onMessage(FINAL_REST_REPLY, live((p) => finalRest.receive(p)));
|
|
990
|
+
room.onDrop(live(() => finalRest.drop()));
|
|
991
|
+
room.onLeave(() => finalRest.drop()); // unguarded on purpose: it only ends THIS room's own final-rest client
|
|
992
|
+
room.onReconnect(live(() => finalRest.reconnect()));
|
|
993
|
+
this.vehicleActionReconnectBaseline = resumedSeat ? new Map(this.vehicleActionSeq) : null;
|
|
83
994
|
this.callbacks = colyseus.getStateCallbacks(room);
|
|
84
995
|
// Resolve the player-seat upload cadence from the world's uploadHz tier, clamped to the contract's [10,20] range.
|
|
85
996
|
this.effectiveUploadHz = Math.max(MESSAGE_RATE.stateHz, Math.min(options.uploadHz ?? MESSAGE_RATE.stateHz, MESSAGE_RATE.maxUploadHz));
|
|
@@ -88,49 +999,426 @@ export class HelixMultiplayer {
|
|
|
88
999
|
// pruned through the accepted seq whether or not a consumer subscribed — then the divergence correction is
|
|
89
1000
|
// handed to the engine consumer (onStateAck/onEntityStateAck). Both fire only when the room's gate rejected
|
|
90
1001
|
// an upload, so they're silent in steady state.
|
|
91
|
-
room.onMessage(ServerMessageType.StateAck, (p) => {
|
|
1002
|
+
room.onMessage(ServerMessageType.StateAck, live((p) => {
|
|
92
1003
|
const ack = p;
|
|
1004
|
+
// v27 epoch adoption FIRST, before the consumer fires: the reconciler's snap callback may synchronously
|
|
1005
|
+
// sendState a fresh post-snap frame, which must survive. On a CHANGED epoch the coalesced pending frame
|
|
1006
|
+
// is dropped — it was sampled pre-snap, and stamping it with the new epoch would pass the room's fence
|
|
1007
|
+
// on a stale position. A same-epoch (plain reject) ack keeps the pending frame: it is legitimate input.
|
|
1008
|
+
if (ack.teleportSeq !== undefined && ack.teleportSeq !== this.teleportSeq) {
|
|
1009
|
+
this.teleportSeq = ack.teleportSeq;
|
|
1010
|
+
this.pendingInput = null;
|
|
1011
|
+
}
|
|
93
1012
|
this.inputBuffer = this.inputBuffer.filter((m) => m.seq > ack.seq);
|
|
94
1013
|
this.onStateAckCb?.(ack);
|
|
95
|
-
});
|
|
96
|
-
room.onMessage(ServerMessageType.EntityStateAck, (p) => this.onEntityStateAckCb?.(p));
|
|
1014
|
+
}));
|
|
1015
|
+
room.onMessage(ServerMessageType.EntityStateAck, live((p) => this.onEntityStateAckCb?.(p)));
|
|
1016
|
+
room.onMessage(ServerMessageType.ModuleEngagement, live((p) => this.adoptModuleEngagement(p)));
|
|
1017
|
+
room.onMessage(ServerMessageType.VehicleEntityRetired, live((p) => {
|
|
1018
|
+
const { entityId, authorityEpoch } = p ?? {};
|
|
1019
|
+
if (typeof entityId === 'string' &&
|
|
1020
|
+
/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(entityId) &&
|
|
1021
|
+
Number.isSafeInteger(authorityEpoch) &&
|
|
1022
|
+
authorityEpoch >= 0) {
|
|
1023
|
+
const entity = keyedCollectionEntry(room.state.entities, entityId);
|
|
1024
|
+
if (entity?.authorityEpoch === authorityEpoch) {
|
|
1025
|
+
this.retiredVehicleActionEpochs.set(entityId, authorityEpoch);
|
|
1026
|
+
}
|
|
1027
|
+
this.retireVehicleActionSequence(entityId, authorityEpoch);
|
|
1028
|
+
}
|
|
1029
|
+
}));
|
|
1030
|
+
room.onMessage(ServerMessageType.VehicleActionFences, live((p) => {
|
|
1031
|
+
this.adoptVehicleActionFences(p);
|
|
1032
|
+
}));
|
|
1033
|
+
// Room types: a ticket to a ticketed instance, sent privately by an `openRoom` rule. Registered for every
|
|
1034
|
+
// room (a default room is where tickets are usually handed out) and fanned out to room.onTicket subscribers.
|
|
1035
|
+
// Subscribers live on the room's own context, so a handle only ever hears ITS room's tickets. Each one is
|
|
1036
|
+
// called in isolation: a throwing world callback must not starve the others, and must not unwind into the
|
|
1037
|
+
// transport's message dispatcher.
|
|
1038
|
+
room.onMessage(ServerMessageType.RoomTicket, live((p) => {
|
|
1039
|
+
const ticket = roomTicketOf(p);
|
|
1040
|
+
if (!ticket)
|
|
1041
|
+
return;
|
|
1042
|
+
for (const cb of [...ctx.ticketCbs]) {
|
|
1043
|
+
try {
|
|
1044
|
+
cb(ticket);
|
|
1045
|
+
}
|
|
1046
|
+
catch (e) {
|
|
1047
|
+
console.error('[Helix] multiplayer: a room.onTicket subscriber threw', e);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}));
|
|
1051
|
+
// Player-collection wiring — per-seat avatarUrl listeners (v23 mid-session refresh) + the shell roster publish
|
|
1052
|
+
// (helix:multiplayer-state). onAdd (immediate) covers seats synced at join; connected flips ride plain patches.
|
|
1053
|
+
const players = this.callbacks(room.state)['players'];
|
|
1054
|
+
const entities = this.callbacks(room.state)['entities'];
|
|
1055
|
+
players.onAdd(live((player, id) => {
|
|
1056
|
+
this.watchAvatar(player, id);
|
|
1057
|
+
this.publishRoomState();
|
|
1058
|
+
}), true);
|
|
1059
|
+
players.onRemove(live((_player, id) => {
|
|
1060
|
+
this.unwatchAvatar(id);
|
|
1061
|
+
this.publishRoomState();
|
|
1062
|
+
}));
|
|
1063
|
+
entities.onRemove(live((_entity, id) => void this.retiredVehicleActionEpochs.delete(id)));
|
|
1064
|
+
this.publishRoomState(); // the shell learns roomId immediately, even before the first roster sync
|
|
97
1065
|
// netlog (opt-in): measure server patch-arrival cadence — the rate at which synced state changes feed the
|
|
98
1066
|
// engine interpolators. A jittery patch rate here is the upstream cause of an interp starve/lapse.
|
|
99
|
-
room.onStateChange(() =>
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
1067
|
+
room.onStateChange(live(() => {
|
|
1068
|
+
this.nlOnPatch();
|
|
1069
|
+
// Every patch carries the room server's clock: what the SDK judges platform expiries by (server-clock.ts).
|
|
1070
|
+
this.host.clock?.observe(room.state?.serverTimeMs, 'room');
|
|
1071
|
+
this.publishRoomState();
|
|
1072
|
+
}));
|
|
1073
|
+
// Keep the persisted token fresh as colyseus rotates it, and replay receipts stashed while the socket was down.
|
|
1074
|
+
// colyseus fires this from its JOIN_ROOM handler, i.e. the socket is already OPEN — the flush's send really goes out.
|
|
1075
|
+
room.onReconnect(live(() => {
|
|
1076
|
+
this.persistCurrentReconnect();
|
|
1077
|
+
this.flushPendingReceipts();
|
|
1078
|
+
}));
|
|
1079
|
+
// The room releases every engagement at the start of a transport drop, even while it keeps the player
|
|
1080
|
+
// seat for reconnection. Clear locally at the same edge; a resumed seat must request a fresh room epoch.
|
|
1081
|
+
room.onDrop(live(() => this.revokeModuleEngagements()));
|
|
1082
|
+
// The one event an OLD room still delivers: settleLeave tears down only if this room is still current, and
|
|
1083
|
+
// hands the leave to the handle's subscribers exactly once (see RoomContext).
|
|
1084
|
+
room.onLeave((code) => this.settleLeave(ctx, code));
|
|
1085
|
+
// Buy-then-join: deliver any receipt that settled while no room was live (the purchase rule fires
|
|
1086
|
+
// in THIS room — exactly once, the durable claim absorbs any earlier delivery). Not into a room that
|
|
1087
|
+
// leave() has already cancelled: it is released the moment this returns, and the stash is for the room
|
|
1088
|
+
// the player actually ends up in.
|
|
1089
|
+
if (!this.entering?.cancelled)
|
|
1090
|
+
this.flushPendingReceipts();
|
|
1091
|
+
return this.makeHandle(room, ctx);
|
|
1092
|
+
}
|
|
1093
|
+
// Connect a reserved seat. A failed connect of an OPEN typed room forgets the active-room pointer written at
|
|
1094
|
+
// reservation time (there is no instance to come back to); a ticketed one keeps it — that is its rejoin handle.
|
|
1095
|
+
async connectOrForget(worldId, roomType, instanceKey, connect) {
|
|
1096
|
+
try {
|
|
1097
|
+
return await connect();
|
|
1098
|
+
}
|
|
1099
|
+
catch (e) {
|
|
1100
|
+
if (roomType !== null && instanceKey === null)
|
|
1101
|
+
this.clearActiveRoom(worldId);
|
|
1102
|
+
throw e;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
// The room's leave, delivered once. Teardown only when it is still the current room — a late close of a room
|
|
1106
|
+
// already left (or hopped away from) must not touch its successor — then the handle's onLeave subscribers,
|
|
1107
|
+
// each isolated so one throwing callback cannot starve the rest or unwind into the transport.
|
|
1108
|
+
settleLeave(ctx, code) {
|
|
1109
|
+
if (ctx.released)
|
|
1110
|
+
return;
|
|
1111
|
+
ctx.released = true;
|
|
1112
|
+
if (this.ctx === ctx)
|
|
1113
|
+
this.teardown();
|
|
1114
|
+
const reason = ctx.leaveReason ?? 'dropped';
|
|
1115
|
+
for (const cb of ctx.leaveCbs.splice(0)) {
|
|
1116
|
+
try {
|
|
1117
|
+
cb(code, reason);
|
|
1118
|
+
}
|
|
1119
|
+
catch (e) {
|
|
1120
|
+
console.error('[Helix] multiplayer: a room.onLeave subscriber threw', e);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
ctx.ticketCbs.clear();
|
|
1124
|
+
}
|
|
1125
|
+
// Stop being in the current room, locally and at once: forget its reconnect slot (a room left on purpose is
|
|
1126
|
+
// never resumed, by any route), record why, and reset. Returns the context so the caller can close the
|
|
1127
|
+
// transport — leave() awaits it as it always did, a hop bounds it.
|
|
1128
|
+
detachCurrentRoom(reason) {
|
|
1129
|
+
const ctx = this.ctx;
|
|
1130
|
+
if (this.reconnectScope)
|
|
1131
|
+
this.clearReconnect(this.reconnectScope);
|
|
1132
|
+
// A typed room also drops the active-room pointer.
|
|
1133
|
+
if (this.worldId && this.roomType !== null)
|
|
1134
|
+
this.clearActiveRoom(this.worldId);
|
|
1135
|
+
if (ctx) {
|
|
1136
|
+
ctx.leaveReason = reason;
|
|
1137
|
+
this.abandonRoom(ctx.room);
|
|
1138
|
+
}
|
|
1139
|
+
this.teardown();
|
|
1140
|
+
return ctx;
|
|
1141
|
+
}
|
|
1142
|
+
// Every leave's transport half: consented, but never trusted to settle (see ROOM_LEAVE_TIMEOUT_MS). On a
|
|
1143
|
+
// healthy socket this is exactly the old behaviour — LEAVE is sent and the promise resolves when the server's
|
|
1144
|
+
// close arrives. If it rejects, throws or times out the old room is detached by force: the world's onLeave is delivered by the SDK, every
|
|
1145
|
+
// listener is dropped and the socket is closed, so nothing of the old room can fire into the new one.
|
|
1146
|
+
async leaveBounded(ctx) {
|
|
1147
|
+
let timer;
|
|
1148
|
+
const left = await Promise.race([
|
|
1149
|
+
(async () => {
|
|
1150
|
+
try {
|
|
1151
|
+
await ctx.room.leave(true);
|
|
1152
|
+
return true;
|
|
1153
|
+
}
|
|
1154
|
+
catch {
|
|
1155
|
+
return false;
|
|
1156
|
+
}
|
|
1157
|
+
})(),
|
|
1158
|
+
new Promise((resolve) => {
|
|
1159
|
+
timer = setTimeout(() => resolve(false), ROOM_LEAVE_TIMEOUT_MS);
|
|
1160
|
+
}),
|
|
1161
|
+
]);
|
|
1162
|
+
if (timer !== undefined)
|
|
1163
|
+
clearTimeout(timer);
|
|
1164
|
+
if (left)
|
|
1165
|
+
return;
|
|
1166
|
+
this.forceDetach(ctx);
|
|
1167
|
+
}
|
|
1168
|
+
// A room we have decided to leave must never come back. Colyseus auto-reconnects a dropped Room on its own —
|
|
1169
|
+
// from the connection's onclose handler, which is not a removable listener — so merely dropping our listeners
|
|
1170
|
+
// and closing the socket leaves a Room object that reconnects with its token seconds later: a ZOMBIE SEAT in
|
|
1171
|
+
// the room we left, and a second socket, long after the SDK moved on. So, the moment a leave is decided:
|
|
1172
|
+
// • `reconnection.enabled = false` — the Room's own documented switch; a later close then ends in onLeave
|
|
1173
|
+
// instead of a retry. `maxRetries = 0` backs it up for a retry chain already running.
|
|
1174
|
+
// • on a FORCED detach (the transport did not answer the leave) the reconnection token is blanked too, so
|
|
1175
|
+
// even a reconnect that got out could not claim the seat. A healthy consented leave does not need it —
|
|
1176
|
+
// the server frees the seat and closes the socket — and leaves the Room object as it found it.
|
|
1177
|
+
// • `connection.reconnect` is replaced with a no-op. A retry timer Colyseus has ALREADY scheduled re-checks
|
|
1178
|
+
// neither flag before calling it, and that call is what opens the new socket — this is the only way to
|
|
1179
|
+
// guarantee none is opened.
|
|
1180
|
+
// Harmless for a healthy consented leave (the server closes the socket and no reconnection is ever tried).
|
|
1181
|
+
abandonRoom(room, blankToken = false) {
|
|
1182
|
+
graceWatches.get(room)?.();
|
|
1183
|
+
try {
|
|
1184
|
+
const reconnection = room.reconnection;
|
|
1185
|
+
if (reconnection) {
|
|
1186
|
+
reconnection.enabled = false;
|
|
1187
|
+
reconnection.maxRetries = 0;
|
|
1188
|
+
reconnection.isReconnecting = false;
|
|
1189
|
+
}
|
|
1190
|
+
if (blankToken)
|
|
1191
|
+
room.reconnectionToken = '';
|
|
1192
|
+
if (room.connection?.reconnect)
|
|
1193
|
+
room.connection.reconnect = () => undefined;
|
|
1194
|
+
}
|
|
1195
|
+
catch { /* a frozen/renamed colyseus shape: closing the socket is still done by the caller */ }
|
|
1196
|
+
}
|
|
1197
|
+
// The transport will not (or did not) deliver this room's leave: deliver it ourselves, drop every listener,
|
|
1198
|
+
// and close the socket with the consented code so a server that does hear it frees the seat without grace.
|
|
1199
|
+
forceDetach(ctx) {
|
|
1200
|
+
this.abandonRoom(ctx.room, true);
|
|
1201
|
+
this.settleLeave(ctx, CONSENTED_CLOSE_CODE);
|
|
1202
|
+
try {
|
|
1203
|
+
ctx.room.removeAllListeners?.();
|
|
1204
|
+
}
|
|
1205
|
+
catch { /* the context guard already mutes them */ }
|
|
1206
|
+
try {
|
|
1207
|
+
ctx.room.connection?.close?.(CONSENTED_CLOSE_CODE);
|
|
1208
|
+
}
|
|
1209
|
+
catch { /* already closed */ }
|
|
1210
|
+
}
|
|
1211
|
+
async requestJoin(apiBase, worldId, token, reservationPath, body = null) {
|
|
1212
|
+
const path = reservationPath ?? `/api/v1/instant-worlds/${encodeURIComponent(worldId)}/join`;
|
|
1213
|
+
if (!path.startsWith('/api/v1/') || path.startsWith('//')) {
|
|
1214
|
+
throw new Error('Helix.multiplayer: reservationPath must be a same-origin /api/v1/ path');
|
|
1215
|
+
}
|
|
1216
|
+
const base = new URL(apiBase);
|
|
1217
|
+
const url = new URL(path, `${base.origin}/`);
|
|
1218
|
+
if (url.origin !== base.origin) {
|
|
1219
|
+
throw new Error('Helix.multiplayer: reservationPath must be same-origin with the platform API');
|
|
1220
|
+
}
|
|
1221
|
+
// The default join sends NO body and no content-type — the exact request every earlier SDK made. Only a
|
|
1222
|
+
// typed or ticket join carries JSON, so a world that never opts into room types is unchanged on the wire.
|
|
1223
|
+
const res = await fetch(url.toString(), body === null
|
|
1224
|
+
? {
|
|
1225
|
+
method: 'POST',
|
|
1226
|
+
headers: { authorization: `Bearer ${token}` },
|
|
1227
|
+
}
|
|
1228
|
+
: {
|
|
1229
|
+
method: 'POST',
|
|
1230
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
1231
|
+
body: JSON.stringify(body),
|
|
1232
|
+
});
|
|
110
1233
|
if (!res.ok) {
|
|
111
1234
|
const detail = await res.json().catch(() => null);
|
|
112
1235
|
const message = (detail && typeof detail.message === 'string' && detail.message) || `HTTP ${res.status}`;
|
|
113
|
-
throw new
|
|
1236
|
+
throw new HelixRoomJoinError(joinRefusalCode(detail), `Helix.multiplayer: join failed — ${message}`, res.status);
|
|
114
1237
|
}
|
|
115
1238
|
return (await res.json());
|
|
116
1239
|
}
|
|
117
|
-
|
|
1240
|
+
// A ticketed room's reconnect token is gone but the instance may still be running: ask the backend for a
|
|
1241
|
+
// fresh ticket (the first one is already redeemed). Granted only while the instance is open and this account
|
|
1242
|
+
// still holds a ticket row. A ticketed room closes its backend instance when it disposes — including on a
|
|
1243
|
+
// server deploy drain — so 410 is the ordinary "the match is over" answer, not an outage: typed, final, and
|
|
1244
|
+
// never retried. Always the canonical world route (a reservation adapter path has no rejoin twin).
|
|
1245
|
+
async requestRejoin(apiBase, worldId, token, instanceKey) {
|
|
1246
|
+
const url = new URL(`/api/v1/instant-worlds/${encodeURIComponent(worldId)}/room-instances/${encodeURIComponent(instanceKey)}/rejoin`, `${new URL(apiBase).origin}/`);
|
|
1247
|
+
let res;
|
|
1248
|
+
try {
|
|
1249
|
+
res = await fetch(url.toString(), {
|
|
1250
|
+
method: 'POST',
|
|
1251
|
+
headers: { authorization: `Bearer ${token}` },
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
catch (e) {
|
|
1255
|
+
// status null = the request never got an answer — retryable, the caller keeps the instance.
|
|
1256
|
+
throw new HelixRoomJoinError('rejoin-failed', `Helix.multiplayer: join failed — could not rejoin the room instance (${e instanceof Error ? e.message : String(e)})`, null, e);
|
|
1257
|
+
}
|
|
1258
|
+
const detail = (await res.json().catch(() => null));
|
|
1259
|
+
// On THIS endpoint a 410 can only mean the instance is closed; the code says so too (`room-instance-closed`).
|
|
1260
|
+
if (res.status === 410 || detail?.code === 'room-instance-closed') {
|
|
1261
|
+
throw new HelixRoomJoinError('instance-closed', 'Helix.multiplayer: join failed — the room instance has closed', res.status);
|
|
1262
|
+
}
|
|
1263
|
+
if (!res.ok || typeof detail?.ticketId !== 'string' || !detail.ticketId) {
|
|
1264
|
+
const message = (detail && typeof detail.message === 'string' && detail.message) || `HTTP ${res.status}`;
|
|
1265
|
+
throw new HelixRoomJoinError('rejoin-failed', `Helix.multiplayer: join failed — could not rejoin the room instance (${message})`, res.status);
|
|
1266
|
+
}
|
|
1267
|
+
return detail.ticketId;
|
|
1268
|
+
}
|
|
1269
|
+
makeHandle(room, ctx) {
|
|
1270
|
+
// World-facing subscriptions obey the same rule as the SDK's own: this handle goes quiet the moment its
|
|
1271
|
+
// room stops being the current one. Only onLeave outlives that — it is how the world learns the handle died.
|
|
1272
|
+
const live = (fn) => (...args) => {
|
|
1273
|
+
if (this.ctx === ctx)
|
|
1274
|
+
fn(...args);
|
|
1275
|
+
};
|
|
118
1276
|
const collection = (name) => {
|
|
119
1277
|
if (!this.callbacks)
|
|
120
1278
|
throw new Error('Helix.multiplayer: room not ready');
|
|
121
1279
|
return this.callbacks(room.state)[name];
|
|
122
1280
|
};
|
|
123
|
-
|
|
1281
|
+
const accessors = createRoomAccessors(room.sessionId, () => room.state);
|
|
1282
|
+
const isDynamicModule = (moduleId) => keyedCollectionEntry(room.state.dynamicModules, moduleId) !== undefined;
|
|
1283
|
+
const sendVehicleAction = (request) => {
|
|
1284
|
+
const { identity } = request;
|
|
1285
|
+
const dynamicModule = typeof identity?.moduleId === 'string' && isDynamicModule(identity.moduleId);
|
|
1286
|
+
const validItemInstanceId = typeof identity?.itemInstanceId === 'string' &&
|
|
1287
|
+
!!identity.itemInstanceId.trim() && identity.itemInstanceId.length <= 96;
|
|
1288
|
+
if (!identity ||
|
|
1289
|
+
(!dynamicModule && !validItemInstanceId) ||
|
|
1290
|
+
(identity.itemInstanceId !== undefined && !validItemInstanceId) ||
|
|
1291
|
+
typeof identity.moduleId !== 'string' ||
|
|
1292
|
+
!/^[a-z0-9.-]{1,32}$/.test(identity.moduleId) ||
|
|
1293
|
+
!/^[a-f0-9]{64}$/.test(identity.bundleChecksumSha256) ||
|
|
1294
|
+
!Number.isSafeInteger(identity.revision) ||
|
|
1295
|
+
identity.revision < 1 ||
|
|
1296
|
+
typeof request.entityId !== 'string' ||
|
|
1297
|
+
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(request.entityId) ||
|
|
1298
|
+
typeof request.action !== 'string' ||
|
|
1299
|
+
!/^[A-Za-z][A-Za-z0-9._:-]{0,63}$/.test(request.action) ||
|
|
1300
|
+
!validPrimitiveArgs(request.args) ||
|
|
1301
|
+
(request.targetBits !== undefined && (!Number.isSafeInteger(request.targetBits) ||
|
|
1302
|
+
request.targetBits < 0 ||
|
|
1303
|
+
request.targetBits > 0xffff)))
|
|
1304
|
+
return false;
|
|
1305
|
+
const entity = keyedCollectionEntry(room.state.entities, request.entityId);
|
|
1306
|
+
const authorityEpoch = entity?.authorityEpoch;
|
|
1307
|
+
const buildDigest = keyedCollectionEntry(entity?.vars, 'vBuild');
|
|
1308
|
+
if (!entity ||
|
|
1309
|
+
(typeof entity.id === 'string' && entity.id !== request.entityId) ||
|
|
1310
|
+
!Number.isSafeInteger(authorityEpoch) ||
|
|
1311
|
+
authorityEpoch < 0 ||
|
|
1312
|
+
typeof buildDigest !== 'string' ||
|
|
1313
|
+
!/^sha256:[0-9a-f]{64}$/.test(buildDigest))
|
|
1314
|
+
return false;
|
|
1315
|
+
const retiredEpoch = this.retiredVehicleActionEpochs.get(request.entityId);
|
|
1316
|
+
if (retiredEpoch === authorityEpoch)
|
|
1317
|
+
return false;
|
|
1318
|
+
if (retiredEpoch !== undefined)
|
|
1319
|
+
this.retiredVehicleActionEpochs.delete(request.entityId);
|
|
1320
|
+
if (room.connection?.isOpen === false)
|
|
1321
|
+
return false;
|
|
1322
|
+
const prior = this.vehicleActionSeq.get(request.entityId);
|
|
1323
|
+
const seq = prior && prior.authorityEpoch === authorityEpoch ? prior.seq + 1 : 1;
|
|
1324
|
+
if (!Number.isSafeInteger(seq) || seq >= Number.MAX_SAFE_INTEGER) {
|
|
1325
|
+
if (this.reconnectScope)
|
|
1326
|
+
this.clearReconnect(this.reconnectScope);
|
|
1327
|
+
return false;
|
|
1328
|
+
}
|
|
1329
|
+
const nextSequence = { authorityEpoch: authorityEpoch, seq };
|
|
1330
|
+
if (!this.persistVehicleActionSequence(request.entityId, nextSequence, prior === undefined))
|
|
1331
|
+
return false;
|
|
1332
|
+
room.send(ClientMessageType.Action, {
|
|
1333
|
+
moduleId: identity.moduleId,
|
|
1334
|
+
...(dynamicModule ? {} : { itemInstanceId: identity.itemInstanceId }),
|
|
1335
|
+
bundleChecksumSha256: identity.bundleChecksumSha256,
|
|
1336
|
+
moduleRevision: identity.revision,
|
|
1337
|
+
name: request.action,
|
|
1338
|
+
args: request.args,
|
|
1339
|
+
vehicleAction: {
|
|
1340
|
+
entityId: request.entityId,
|
|
1341
|
+
authorityEpoch: authorityEpoch,
|
|
1342
|
+
seq,
|
|
1343
|
+
buildDigest,
|
|
1344
|
+
...(request.targetBits === undefined ? {} : { targetBits: request.targetBits }),
|
|
1345
|
+
},
|
|
1346
|
+
});
|
|
1347
|
+
return true;
|
|
1348
|
+
};
|
|
1349
|
+
const finalRest = this.finalRestClient;
|
|
1350
|
+
const handle = {
|
|
1351
|
+
claimPhysicsGroup: async (action, group, args, scope) => {
|
|
1352
|
+
const grant = await finalRest.claim(action, group, args, scope, scope ? this.moduleEngagements.get(scope.moduleId)?.epoch : undefined);
|
|
1353
|
+
this.entityBatchSeq = Math.max(this.entityBatchSeq, ...Object.values(this.entitySeq));
|
|
1354
|
+
return grant;
|
|
1355
|
+
},
|
|
1356
|
+
commitPhysicsGroup: (transactionId, states) => finalRest.commit(transactionId, states),
|
|
1357
|
+
onPhysicsGroupRest: (group, callback, scope) => {
|
|
1358
|
+
const moduleId = scope?.moduleId;
|
|
1359
|
+
let generation = -1, sequence = -1;
|
|
1360
|
+
room.onMessage(moduleId === undefined ? ServerMessageType.GroupRestSnapshot : MODULE_FINAL_REST_SNAPSHOT, live((payload) => {
|
|
1361
|
+
const snapshot = payload;
|
|
1362
|
+
if (snapshot.group !== group || snapshot.scope?.moduleId !== moduleId || !finalRest.acceptSnapshot(snapshot))
|
|
1363
|
+
return;
|
|
1364
|
+
const nextGeneration = snapshot.scope?.generation ?? 0;
|
|
1365
|
+
if (nextGeneration < generation || (nextGeneration === generation && snapshot.seq <= sequence))
|
|
1366
|
+
return;
|
|
1367
|
+
generation = nextGeneration;
|
|
1368
|
+
sequence = snapshot.seq;
|
|
1369
|
+
callback(snapshot);
|
|
1370
|
+
}));
|
|
1371
|
+
},
|
|
124
1372
|
roomId: room.roomId,
|
|
125
1373
|
sessionId: room.sessionId,
|
|
1374
|
+
roomType: this.roomType,
|
|
1375
|
+
instanceKey: this.instanceKey,
|
|
1376
|
+
vars: accessors.vars,
|
|
1377
|
+
me: accessors.me,
|
|
1378
|
+
player: accessors.player,
|
|
1379
|
+
phase: accessors.phase,
|
|
1380
|
+
currentTurn: accessors.currentTurn,
|
|
1381
|
+
isMyTurn: accessors.isMyTurn,
|
|
1382
|
+
module: accessors.module,
|
|
126
1383
|
effectiveUploadHz: this.effectiveUploadHz,
|
|
127
1384
|
get state() {
|
|
128
1385
|
return room.state;
|
|
129
1386
|
},
|
|
130
|
-
onStateChange: (cb) =>
|
|
1387
|
+
onStateChange: (cb) => {
|
|
1388
|
+
const listener = live((state) => cb(state));
|
|
1389
|
+
room.onStateChange(listener);
|
|
1390
|
+
return () => room.onStateChange.remove(listener);
|
|
1391
|
+
},
|
|
131
1392
|
onAdd: (name, cb) => void collection(name).onAdd((v, k) => cb(v, k), true),
|
|
132
1393
|
onRemove: (name, cb) => void collection(name).onRemove((v, k) => cb(v, k)),
|
|
133
|
-
onMessage: (type, cb) =>
|
|
1394
|
+
onMessage: (type, cb) => {
|
|
1395
|
+
const unsubscribe = room.onMessage(type, live((payload) => cb(payload)));
|
|
1396
|
+
return typeof unsubscribe === 'function' ? unsubscribe : () => undefined;
|
|
1397
|
+
},
|
|
1398
|
+
onTicket: (cb) => {
|
|
1399
|
+
ctx.ticketCbs.add(cb);
|
|
1400
|
+
return () => void ctx.ticketCbs.delete(cb);
|
|
1401
|
+
},
|
|
1402
|
+
onModuleFused: (cb) => void room.onMessage(ServerMessageType.ModuleFused, live((p) => cb(p))),
|
|
1403
|
+
onModuleWake: (cb) => void room.onMessage(ServerMessageType.ModuleWake, live((p) => cb(p))),
|
|
1404
|
+
onModuleSleep: (cb) => void room.onMessage(ServerMessageType.ModuleSleep, live((p) => cb(p))),
|
|
1405
|
+
onModuleEngagement: (cb) => {
|
|
1406
|
+
this.moduleEngagementCbs.add(cb);
|
|
1407
|
+
return () => void this.moduleEngagementCbs.delete(cb);
|
|
1408
|
+
},
|
|
1409
|
+
onModuleState: (cb) => {
|
|
1410
|
+
const emit = (state) => {
|
|
1411
|
+
for (const snapshot of moduleStateSnapshots(state))
|
|
1412
|
+
cb(snapshot);
|
|
1413
|
+
};
|
|
1414
|
+
emit(room.state);
|
|
1415
|
+
void room.onStateChange(live((state) => emit(state)));
|
|
1416
|
+
},
|
|
1417
|
+
onModuleEffect: (cb) => void room.onMessage(ServerMessageType.ModuleEffect, live((payload) => cb(payload))),
|
|
1418
|
+
onPlayerAvatarChanged: (cb) => {
|
|
1419
|
+
this.avatarChangedCbs.add(cb);
|
|
1420
|
+
return () => void this.avatarChangedCbs.delete(cb);
|
|
1421
|
+
},
|
|
134
1422
|
onStateAck: (cb) => {
|
|
135
1423
|
this.onStateAckCb = cb;
|
|
136
1424
|
},
|
|
@@ -138,27 +1426,140 @@ export class HelixMultiplayer {
|
|
|
138
1426
|
this.onEntityStateAckCb = cb;
|
|
139
1427
|
},
|
|
140
1428
|
sendState: (input) => {
|
|
141
|
-
|
|
1429
|
+
// Capture source time HERE, beside the pose/body sample. Stamping at the later interval flush turns queue
|
|
1430
|
+
// delay into fake sender cadence and defeats source-time interpolation under a delayed timer.
|
|
1431
|
+
this.pendingInput = {
|
|
1432
|
+
input,
|
|
1433
|
+
sampledAtMs: performance.now(),
|
|
1434
|
+
compactPose: encodeAvatarPose(this.internalAvatarPose),
|
|
1435
|
+
};
|
|
142
1436
|
},
|
|
143
1437
|
sendAbility: (ability, active) => room.send(ClientMessageType.Ability, { ability, active }),
|
|
144
|
-
sendAction: (name, args) =>
|
|
145
|
-
|
|
146
|
-
|
|
1438
|
+
sendAction: (name, args, moduleId) => {
|
|
1439
|
+
const epoch = moduleId === undefined ? undefined : this.moduleEngagements.get(moduleId)?.epoch;
|
|
1440
|
+
room.send(ClientMessageType.Action, {
|
|
1441
|
+
name,
|
|
1442
|
+
args,
|
|
1443
|
+
...(moduleId === undefined ? {} : { moduleId }),
|
|
1444
|
+
...(epoch === undefined ? {} : { engagementEpoch: epoch }),
|
|
1445
|
+
});
|
|
1446
|
+
},
|
|
1447
|
+
sendModuleAction: (request) => {
|
|
1448
|
+
const { identity } = request;
|
|
1449
|
+
const dynamicModule = typeof identity?.moduleId === 'string' && isDynamicModule(identity.moduleId);
|
|
1450
|
+
const validItemInstanceId = typeof identity?.itemInstanceId === 'string' &&
|
|
1451
|
+
!!identity.itemInstanceId && identity.itemInstanceId.length <= 96;
|
|
1452
|
+
if (!identity ||
|
|
1453
|
+
(!dynamicModule && !validItemInstanceId) ||
|
|
1454
|
+
(identity.itemInstanceId !== undefined && !validItemInstanceId) ||
|
|
1455
|
+
typeof identity.moduleId !== 'string' ||
|
|
1456
|
+
!/^[a-z0-9.-]{1,32}$/.test(identity.moduleId) ||
|
|
1457
|
+
!/^[a-f0-9]{64}$/.test(identity.bundleChecksumSha256) ||
|
|
1458
|
+
!Number.isSafeInteger(identity.revision) ||
|
|
1459
|
+
identity.revision < 1 ||
|
|
1460
|
+
typeof request.action !== 'string' ||
|
|
1461
|
+
!request.action)
|
|
1462
|
+
return false;
|
|
1463
|
+
const base = {
|
|
1464
|
+
moduleId: identity.moduleId,
|
|
1465
|
+
...(dynamicModule ? {} : { itemInstanceId: identity.itemInstanceId }),
|
|
1466
|
+
bundleChecksumSha256: identity.bundleChecksumSha256,
|
|
1467
|
+
moduleRevision: identity.revision,
|
|
1468
|
+
name: request.action,
|
|
1469
|
+
args: request.args,
|
|
1470
|
+
};
|
|
1471
|
+
if (request.engagement === 'acquire') {
|
|
1472
|
+
room.send(ClientMessageType.Action, {
|
|
1473
|
+
...base,
|
|
1474
|
+
engagement: 'acquire',
|
|
1475
|
+
engagementRequestId: ++this.engagementRequestSeq,
|
|
1476
|
+
});
|
|
1477
|
+
return true;
|
|
1478
|
+
}
|
|
1479
|
+
if (request.engagement === 'release') {
|
|
1480
|
+
const current = this.moduleEngagements.get(identity.moduleId);
|
|
1481
|
+
if (!current)
|
|
1482
|
+
return false;
|
|
1483
|
+
room.send(ClientMessageType.Action, {
|
|
1484
|
+
...base,
|
|
1485
|
+
engagement: 'release',
|
|
1486
|
+
engagementRequestId: ++this.engagementRequestSeq,
|
|
1487
|
+
engagementEpoch: current.epoch,
|
|
1488
|
+
});
|
|
1489
|
+
return true;
|
|
1490
|
+
}
|
|
1491
|
+
const epoch = this.moduleEngagements.get(identity.moduleId)?.epoch;
|
|
1492
|
+
room.send(ClientMessageType.Action, {
|
|
1493
|
+
...base,
|
|
1494
|
+
...(epoch === undefined ? {} : { engagementEpoch: epoch }),
|
|
1495
|
+
});
|
|
1496
|
+
return true;
|
|
1497
|
+
},
|
|
1498
|
+
sendVehicleComponentAction: (request) => sendVehicleAction(request),
|
|
1499
|
+
sendVehicleDetachAction: (request) => (isVehicleDetachActionId(request.actionId)
|
|
1500
|
+
? sendVehicleAction({
|
|
1501
|
+
identity: request.identity,
|
|
1502
|
+
entityId: request.entityId,
|
|
1503
|
+
action: request.actionId,
|
|
1504
|
+
})
|
|
1505
|
+
: false),
|
|
1506
|
+
requestModuleEngagement: (moduleId, action, args) => room.send(ClientMessageType.Action, {
|
|
1507
|
+
moduleId,
|
|
1508
|
+
name: action,
|
|
1509
|
+
args,
|
|
1510
|
+
engagement: 'acquire',
|
|
1511
|
+
engagementRequestId: ++this.engagementRequestSeq,
|
|
1512
|
+
}),
|
|
1513
|
+
releaseModuleEngagement: (moduleId, action, args) => {
|
|
1514
|
+
const current = this.moduleEngagements.get(moduleId);
|
|
1515
|
+
if (!current)
|
|
1516
|
+
return false;
|
|
1517
|
+
finalRest.invalidateModule(moduleId);
|
|
1518
|
+
room.send(ClientMessageType.Action, {
|
|
1519
|
+
moduleId,
|
|
1520
|
+
name: action,
|
|
1521
|
+
args,
|
|
1522
|
+
engagement: 'release',
|
|
1523
|
+
engagementRequestId: ++this.engagementRequestSeq,
|
|
1524
|
+
engagementEpoch: current.epoch,
|
|
1525
|
+
});
|
|
1526
|
+
return true;
|
|
1527
|
+
},
|
|
1528
|
+
moduleEngagement: (moduleId) => {
|
|
1529
|
+
const current = this.moduleEngagements.get(moduleId);
|
|
1530
|
+
return current ? { ...current } : null;
|
|
1531
|
+
},
|
|
1532
|
+
sendGesture: (clip, play) => room.send(ClientMessageType.Gesture, { clip, play }),
|
|
1533
|
+
sendAttachments: (attachments) => room.send(ClientMessageType.Attachments, { attachments }),
|
|
1534
|
+
sendAvatarRefresh: () => room.send(ClientMessageType.AvatarRefresh, {}),
|
|
1535
|
+
sendEmoteRefresh: () => room.send(ClientMessageType.EmoteRefresh, {}),
|
|
1536
|
+
requestDistributionCapability: (ref) => this.requestDistributionCapability(ref),
|
|
1537
|
+
sendEmoteJoin: (initiator) => room.send(ClientMessageType.EmoteJoin, { initiator }),
|
|
1538
|
+
uploadEntity: (entityId, input, moduleId) => {
|
|
1539
|
+
const transactionId = finalRest.upload(entityId, moduleId);
|
|
1540
|
+
if (transactionId === null)
|
|
1541
|
+
return;
|
|
1542
|
+
const runtimeEntityId = moduleId === undefined ? entityId : `m:${moduleId}|${entityId}`;
|
|
1543
|
+
const seq = transactionId === undefined ? (this.entitySeq[runtimeEntityId] = (this.entitySeq[runtimeEntityId] ?? 0) + 1) : ++this.entityBatchSeq;
|
|
147
1544
|
// (P1.C1) forward the authority epoch (when the caller has it) so the server fence can drop a stale-era frame.
|
|
148
1545
|
// networked-physics: a physics kind also carries velocity/angularVelocity/orientation (omitted for kinematic).
|
|
149
1546
|
room.send(ClientMessageType.EntityState, {
|
|
1547
|
+
...(transactionId === undefined ? {} : { transactionId }),
|
|
150
1548
|
entity: entityId, seq, position: input.position, vars: input.vars,
|
|
1549
|
+
...(moduleId === undefined ? {} : { moduleId }),
|
|
151
1550
|
...(input.velocity !== undefined ? { velocity: input.velocity } : {}),
|
|
152
1551
|
...(input.angularVelocity !== undefined ? { angularVelocity: input.angularVelocity } : {}),
|
|
153
1552
|
...(input.orientation !== undefined ? { orientation: input.orientation } : {}),
|
|
154
1553
|
...(input.epoch !== undefined ? { epoch: input.epoch } : {}), tMs: performance.now(),
|
|
155
1554
|
});
|
|
156
1555
|
},
|
|
157
|
-
uploadEntities: (entities) => {
|
|
1556
|
+
uploadEntities: (entities, moduleId) => {
|
|
1557
|
+
entities = entities.filter(e => finalRest.upload(e.id, moduleId) !== null);
|
|
158
1558
|
if (entities.length === 0)
|
|
159
1559
|
return;
|
|
160
1560
|
const seq = ++this.entityBatchSeq;
|
|
161
1561
|
const states = entities.map((e) => ({
|
|
1562
|
+
...(finalRest.upload(e.id, moduleId) ? { transactionId: finalRest.upload(e.id, moduleId) } : {}),
|
|
162
1563
|
e: e.id,
|
|
163
1564
|
p: [e.position.x, e.position.y, e.position.z],
|
|
164
1565
|
// networked-physics: compact lv/av/q tuples for a physics kind (omitted when the caller passes none).
|
|
@@ -168,17 +1569,152 @@ export class HelixMultiplayer {
|
|
|
168
1569
|
...(e.vars !== undefined ? { v: e.vars } : {}),
|
|
169
1570
|
...(e.epoch !== undefined ? { ep: e.epoch } : {}),
|
|
170
1571
|
}));
|
|
171
|
-
room.send(ClientMessageType.EntityStateBatch, {
|
|
1572
|
+
room.send(ClientMessageType.EntityStateBatch, {
|
|
1573
|
+
seq,
|
|
1574
|
+
states,
|
|
1575
|
+
tMs: performance.now(),
|
|
1576
|
+
...(moduleId === undefined ? {} : { moduleId }),
|
|
1577
|
+
});
|
|
172
1578
|
},
|
|
173
1579
|
pendingInputs: () => this.inputBuffer.slice(),
|
|
174
1580
|
acknowledge: (seq) => {
|
|
175
1581
|
this.inputBuffer = this.inputBuffer.filter((m) => m.seq > seq);
|
|
176
1582
|
},
|
|
177
|
-
onDrop: (cb) => void room.onDrop(() => cb()),
|
|
178
|
-
onReconnect: (cb) => void room.onReconnect(() => cb()),
|
|
179
|
-
|
|
180
|
-
|
|
1583
|
+
onDrop: (cb) => void room.onDrop(live(() => cb())),
|
|
1584
|
+
onReconnect: (cb) => void room.onReconnect(live(() => cb())),
|
|
1585
|
+
// Delivered by settleLeave, exactly once and with the reason — not registered on the transport, so a hop
|
|
1586
|
+
// that has to detach the old room by force can still tell the world this handle is dead.
|
|
1587
|
+
onLeave: (cb) => {
|
|
1588
|
+
if (!ctx.released)
|
|
1589
|
+
ctx.leaveCbs.push(cb);
|
|
1590
|
+
},
|
|
1591
|
+
// THIS handle's room only — never "whatever room is current" (see the stale-handle guard below).
|
|
1592
|
+
leave: () => this.leaveRoom(ctx),
|
|
1593
|
+
};
|
|
1594
|
+
// STALE-HANDLE GUARD. The members above reach SDK state that belongs to the CURRENT room: the coalesced
|
|
1595
|
+
// state slot the flush timer sends, the sequence counters, the engagement map, the single-slot ack
|
|
1596
|
+
// consumers, the shared subscriber sets, `this.room` itself. Called through a handle whose room is no
|
|
1597
|
+
// longer current they would act on its SUCCESSOR — a stale `leave()` ejecting the player from the room
|
|
1598
|
+
// they just hopped to is the same bug as a stale `sendState` riding the new room's flush. So each of them
|
|
1599
|
+
// is replaced by a wrapper that runs the real member only while this handle's room is the current one and
|
|
1600
|
+
// otherwise returns the inert answer listed here (documented on HelixRoom). Deliberately NOT in the table,
|
|
1601
|
+
// because they touch nothing shared: the read-only members (ids, the state snapshot, the accessors),
|
|
1602
|
+
// onLeave/onDrop/onReconnect, and the plain pass-through senders (sendAbility, sendGesture, sendAttachments,
|
|
1603
|
+
// sendAvatarRefresh, sendEmoteRefresh, sendEmoteJoin), which only write to this handle's own captured
|
|
1604
|
+
// room — their "handed to the captured room after leave, never a throw" behaviour is pinned by tests.
|
|
1605
|
+
const nothing = () => undefined;
|
|
1606
|
+
const refused = () => false;
|
|
1607
|
+
const unsubscribed = () => nothing;
|
|
1608
|
+
const notInRoom = () => Promise.reject(new Error('not_in_room'));
|
|
1609
|
+
const whenStale = {
|
|
1610
|
+
leave: () => Promise.resolve(),
|
|
1611
|
+
sendState: nothing, sendAction: nothing,
|
|
1612
|
+
uploadEntity: nothing, uploadEntities: nothing, requestModuleEngagement: nothing, acknowledge: nothing,
|
|
1613
|
+
sendModuleAction: refused, sendVehicleComponentAction: refused, sendVehicleDetachAction: refused,
|
|
1614
|
+
releaseModuleEngagement: refused,
|
|
1615
|
+
moduleEngagement: () => null,
|
|
1616
|
+
pendingInputs: () => [],
|
|
1617
|
+
claimPhysicsGroup: notInRoom, commitPhysicsGroup: notInRoom, requestDistributionCapability: notInRoom,
|
|
1618
|
+
onStateAck: nothing, onEntityStateAck: nothing, onAdd: nothing, onRemove: nothing,
|
|
1619
|
+
onModuleFused: nothing, onModuleWake: nothing, onModuleSleep: nothing, onModuleState: nothing,
|
|
1620
|
+
onModuleEffect: nothing, onPhysicsGroupRest: nothing,
|
|
1621
|
+
onMessage: unsubscribed, onTicket: unsubscribed, onStateChange: unsubscribed,
|
|
1622
|
+
onModuleEngagement: unsubscribed, onPlayerAvatarChanged: unsubscribed,
|
|
181
1623
|
};
|
|
1624
|
+
const members = handle;
|
|
1625
|
+
for (const [name, inert] of Object.entries(whenStale)) {
|
|
1626
|
+
const member = members[name];
|
|
1627
|
+
members[name] = (...args) => (this.ctx === ctx ? member(...args) : inert());
|
|
1628
|
+
}
|
|
1629
|
+
installInternalAvatarPoseCapability(handle, Object.freeze({
|
|
1630
|
+
version: AVATAR_POSE_VERSION,
|
|
1631
|
+
setLocalPose: (pose) => {
|
|
1632
|
+
if (this.ctx !== ctx)
|
|
1633
|
+
return; // a stale handle's pose must not ride the new room's uploads
|
|
1634
|
+
this.internalAvatarPose = pose;
|
|
1635
|
+
},
|
|
1636
|
+
decodeReplica: decodeInternalAvatarPoseReplica,
|
|
1637
|
+
}));
|
|
1638
|
+
return handle;
|
|
1639
|
+
}
|
|
1640
|
+
// v23/v33: watch one seat's avatar identity. Schema onChange fires once per changed instance per patch, so a room
|
|
1641
|
+
// update containing BOTH avatarUrl and avatarRevision emits exactly once. Cache the initial state without firing:
|
|
1642
|
+
// the value at spawn is already read while the replica is built. Older rooms omit avatarRevision, which means 0.
|
|
1643
|
+
watchAvatar(player, playerId) {
|
|
1644
|
+
if (!this.callbacks || this.avatarListeners.has(playerId))
|
|
1645
|
+
return;
|
|
1646
|
+
let previousUrl = avatarUrlOfPlayerState(player);
|
|
1647
|
+
let previousRevision = avatarRevisionOfPlayerState(player);
|
|
1648
|
+
const detach = this.callbacks(player).onChange(() => {
|
|
1649
|
+
const url = avatarUrlOfPlayerState(player);
|
|
1650
|
+
const revision = avatarRevisionOfPlayerState(player);
|
|
1651
|
+
if (url === previousUrl && revision === previousRevision)
|
|
1652
|
+
return;
|
|
1653
|
+
previousUrl = url;
|
|
1654
|
+
previousRevision = revision;
|
|
1655
|
+
for (const cb of this.avatarChangedCbs)
|
|
1656
|
+
cb(playerId, url);
|
|
1657
|
+
this.publishRoomState();
|
|
1658
|
+
});
|
|
1659
|
+
this.avatarListeners.set(playerId, detach);
|
|
1660
|
+
}
|
|
1661
|
+
unwatchAvatar(playerId) {
|
|
1662
|
+
this.avatarListeners.get(playerId)?.();
|
|
1663
|
+
this.avatarListeners.delete(playerId);
|
|
1664
|
+
}
|
|
1665
|
+
adoptModuleEngagement(event) {
|
|
1666
|
+
if (event.status === 'granted' && event.epoch !== undefined) {
|
|
1667
|
+
this.moduleEngagements.set(event.moduleId, {
|
|
1668
|
+
moduleId: event.moduleId,
|
|
1669
|
+
action: event.action,
|
|
1670
|
+
epoch: event.epoch,
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
1673
|
+
else if ((event.status === 'released' || event.status === 'revoked') && event.epoch !== undefined) {
|
|
1674
|
+
const current = this.moduleEngagements.get(event.moduleId);
|
|
1675
|
+
if (current?.epoch === event.epoch) {
|
|
1676
|
+
this.finalRestClient?.invalidateModule(event.moduleId);
|
|
1677
|
+
this.moduleEngagements.delete(event.moduleId);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
for (const cb of this.moduleEngagementCbs)
|
|
1681
|
+
cb(event);
|
|
1682
|
+
}
|
|
1683
|
+
revokeModuleEngagements() {
|
|
1684
|
+
const active = [...this.moduleEngagements.values()];
|
|
1685
|
+
this.moduleEngagements.clear();
|
|
1686
|
+
for (const lease of active) {
|
|
1687
|
+
const event = {
|
|
1688
|
+
moduleId: lease.moduleId,
|
|
1689
|
+
action: lease.action,
|
|
1690
|
+
status: 'revoked',
|
|
1691
|
+
epoch: lease.epoch,
|
|
1692
|
+
};
|
|
1693
|
+
for (const cb of this.moduleEngagementCbs)
|
|
1694
|
+
cb(event);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
// Build + publish the current room status to the host (→ the shell's helix:multiplayer-state). Signature-
|
|
1698
|
+
// guarded: state patches arrive at up to 20 Hz, but a post only goes out when the roster actually changed.
|
|
1699
|
+
publishRoomState() {
|
|
1700
|
+
if (!this.host.publishRoomState || !this.room)
|
|
1701
|
+
return;
|
|
1702
|
+
const players = rosterOf(this.room.state, this.room.sessionId);
|
|
1703
|
+
// The room's kind cannot change under a roomId, so the roster signature needs nothing more.
|
|
1704
|
+
const sig = `${this.room.roomId}\n` + players.map((p) => `${p.sessionId}|${p.userId}|${p.displayName}|${p.avatarUrl}|${p.connected}`).join('\n');
|
|
1705
|
+
if (sig === this.rosterSig)
|
|
1706
|
+
return;
|
|
1707
|
+
this.rosterSig = sig;
|
|
1708
|
+
this.host.publishRoomState({
|
|
1709
|
+
roomId: this.room.roomId,
|
|
1710
|
+
sessionId: this.room.sessionId,
|
|
1711
|
+
playerCount: players.length,
|
|
1712
|
+
maxPlayers: this.roomMaxPlayers,
|
|
1713
|
+
players,
|
|
1714
|
+
// Absent for the default room: the message existing worlds publish is unchanged.
|
|
1715
|
+
...(this.roomType !== null ? { roomType: this.roomType } : {}),
|
|
1716
|
+
...(this.instanceKey !== null ? { ticketed: true } : {}),
|
|
1717
|
+
});
|
|
182
1718
|
}
|
|
183
1719
|
// D3: coalesce per-frame sendState calls and flush the latest at most stateHz times/second, tagging a
|
|
184
1720
|
// monotonic seq. D4: buffer each sent state (bounded) so the engine can replay the unacknowledged tail.
|
|
@@ -189,10 +1725,19 @@ export class HelixMultiplayer {
|
|
|
189
1725
|
flush() {
|
|
190
1726
|
if (!this.pendingInput || !this.room)
|
|
191
1727
|
return;
|
|
192
|
-
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
const
|
|
1728
|
+
const { input, sampledAtMs, compactPose } = this.pendingInput;
|
|
1729
|
+
// Strip an unsupported same-realm injection if JavaScript bypassed ReplicaInput's public type. Only the
|
|
1730
|
+
// internal capability's current sample may enter the transport extension.
|
|
1731
|
+
const { avatarPose: _unsupportedAvatarPose, ...base } = input;
|
|
1732
|
+
// tMs is the SAMPLE timestamp captured by sendState, not the later timer-flush time. The pose and body therefore
|
|
1733
|
+
// share one source-time keyframe even when the interval callback itself is delayed.
|
|
1734
|
+
const message = {
|
|
1735
|
+
...base,
|
|
1736
|
+
...(compactPose ? { avatarPose: compactPose } : {}),
|
|
1737
|
+
seq: ++this.seq,
|
|
1738
|
+
teleportSeq: this.teleportSeq,
|
|
1739
|
+
tMs: sampledAtMs,
|
|
1740
|
+
};
|
|
196
1741
|
this.pendingInput = null;
|
|
197
1742
|
this.room.send(ClientMessageType.State, message);
|
|
198
1743
|
this.inputBuffer.push(message);
|
|
@@ -231,80 +1776,561 @@ export class HelixMultiplayer {
|
|
|
231
1776
|
// letting the socket drop holds the seat in the server's grace window so a reload can RECONNECT to it (and
|
|
232
1777
|
// keep its vars), instead of a fresh join that the room's one-seat-per-account onAuth gate would reject. A
|
|
233
1778
|
// genuine close just lets the grace window expire (the seat despawns after RECONNECT_GRACE_SEC).
|
|
234
|
-
persistReconnect(
|
|
235
|
-
if (
|
|
236
|
-
|
|
1779
|
+
persistReconnect(scope, wsUrl, reconnectionToken, roomId) {
|
|
1780
|
+
if (!wsUrl || !reconnectionToken || !this.sessionIdentity) {
|
|
1781
|
+
this.clearReconnect(scope);
|
|
1782
|
+
return false;
|
|
1783
|
+
}
|
|
1784
|
+
// maxPlayers and the seat-lifetime semantic-action manifest ride along so a reload-resume keeps the roster
|
|
1785
|
+
// cap and cannot restart a component sequence hidden only by recipient-side interest filtering.
|
|
1786
|
+
const record = {
|
|
1787
|
+
sessionIdentity: this.sessionIdentity,
|
|
1788
|
+
wsUrl,
|
|
1789
|
+
reconnectionToken,
|
|
1790
|
+
roomId,
|
|
1791
|
+
maxPlayers: this.roomMaxPlayers,
|
|
1792
|
+
roomType: this.roomType,
|
|
1793
|
+
instanceKey: this.instanceKey,
|
|
1794
|
+
vehicleActionSeq: this.vehicleActionSeq,
|
|
1795
|
+
legacyVehicleActionSeq: false,
|
|
1796
|
+
};
|
|
1797
|
+
this.reconnectCache = { scope, record };
|
|
1798
|
+
if (typeof sessionStorage === 'undefined')
|
|
1799
|
+
return true;
|
|
237
1800
|
try {
|
|
238
|
-
sessionStorage.setItem(RECONNECT_KEY(
|
|
1801
|
+
sessionStorage.setItem(RECONNECT_KEY(scope), JSON.stringify({
|
|
1802
|
+
sessionIdentity: this.sessionIdentity,
|
|
1803
|
+
wsUrl,
|
|
1804
|
+
reconnectionToken,
|
|
1805
|
+
roomId,
|
|
1806
|
+
maxPlayers: this.roomMaxPlayers,
|
|
1807
|
+
vehicleActionEntities: [...this.vehicleActionSeq.keys()],
|
|
1808
|
+
// Typed rooms only — the default room's record keeps its exact pre-room-types shape.
|
|
1809
|
+
...(this.roomType !== null ? { roomType: this.roomType } : {}),
|
|
1810
|
+
...(this.instanceKey !== null ? { instanceKey: this.instanceKey } : {}),
|
|
1811
|
+
}));
|
|
1812
|
+
return true;
|
|
1813
|
+
}
|
|
1814
|
+
catch {
|
|
1815
|
+
return false;
|
|
239
1816
|
}
|
|
240
|
-
catch { /* storage unavailable */ }
|
|
241
1817
|
}
|
|
242
|
-
readReconnect(
|
|
1818
|
+
readReconnect(scope) {
|
|
1819
|
+
if (this.reconnectCache?.scope === scope)
|
|
1820
|
+
return this.reconnectCache.record;
|
|
243
1821
|
if (typeof sessionStorage === 'undefined')
|
|
244
1822
|
return null;
|
|
245
1823
|
try {
|
|
246
|
-
const raw = sessionStorage.getItem(RECONNECT_KEY(
|
|
1824
|
+
const raw = sessionStorage.getItem(RECONNECT_KEY(scope));
|
|
1825
|
+
if (!raw) {
|
|
1826
|
+
// Without the token metadata, split high-waters cannot belong to a resumable server seat. Remove them
|
|
1827
|
+
// before a fresh join so an interrupted metadata write cannot strand quota forever.
|
|
1828
|
+
this.clearReconnect(scope);
|
|
1829
|
+
return null;
|
|
1830
|
+
}
|
|
247
1831
|
const v = raw ? JSON.parse(raw) : null;
|
|
248
|
-
|
|
1832
|
+
if (typeof v?.sessionIdentity !== 'string' || !v.sessionIdentity ||
|
|
1833
|
+
typeof v.wsUrl !== 'string' || !v.wsUrl || typeof v.reconnectionToken !== 'string' || !v.reconnectionToken) {
|
|
1834
|
+
throw new Error('invalid reconnect metadata');
|
|
1835
|
+
}
|
|
1836
|
+
const legacyVehicleActionSeq = sanitizedVehicleActionSeq(v.vehicleActionSeq);
|
|
1837
|
+
if (v.vehicleActionSeq !== undefined) {
|
|
1838
|
+
if (!v.vehicleActionSeq || typeof v.vehicleActionSeq !== 'object' || Array.isArray(v.vehicleActionSeq)) {
|
|
1839
|
+
throw new Error('invalid legacy vehicle action sequences');
|
|
1840
|
+
}
|
|
1841
|
+
if (Object.keys(v.vehicleActionSeq).length !== legacyVehicleActionSeq.size) {
|
|
1842
|
+
throw new Error('invalid legacy vehicle action sequence');
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
const rawEntities = v.vehicleActionEntities;
|
|
1846
|
+
let vehicleActionSeq = legacyVehicleActionSeq;
|
|
1847
|
+
if (rawEntities !== undefined) {
|
|
1848
|
+
if (!Array.isArray(rawEntities))
|
|
1849
|
+
throw new Error('invalid vehicle action entity manifest');
|
|
1850
|
+
vehicleActionSeq = new Map();
|
|
1851
|
+
const seen = new Set();
|
|
1852
|
+
for (const entityId of rawEntities) {
|
|
1853
|
+
if (typeof entityId !== 'string' ||
|
|
1854
|
+
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(entityId) ||
|
|
1855
|
+
seen.has(entityId))
|
|
1856
|
+
throw new Error('invalid vehicle action entity manifest');
|
|
1857
|
+
seen.add(entityId);
|
|
1858
|
+
const rawSequence = sessionStorage.getItem(VEHICLE_ACTION_SEQ_KEY(scope, entityId));
|
|
1859
|
+
if (!rawSequence)
|
|
1860
|
+
throw new Error('missing vehicle action sequence');
|
|
1861
|
+
const sequence = sanitizedVehicleActionSeq({ [entityId]: JSON.parse(rawSequence) }).get(entityId);
|
|
1862
|
+
if (!sequence)
|
|
1863
|
+
throw new Error('invalid vehicle action sequence');
|
|
1864
|
+
vehicleActionSeq.set(entityId, sequence);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
else if (v.vehicleActionSeq === undefined) {
|
|
1868
|
+
// One-time migration for 0.1.5 builds that split each high-water into its own key before the durable
|
|
1869
|
+
// entity manifest existed. Scan only on reconnect load, validate every discovered record strictly, and
|
|
1870
|
+
// let the successful reconnect rewrite the constant metadata record with an explicit manifest.
|
|
1871
|
+
vehicleActionSeq = new Map();
|
|
1872
|
+
const prefix = VEHICLE_ACTION_SEQ_KEY_PREFIX(scope);
|
|
1873
|
+
for (let index = 0; index < sessionStorage.length; index++) {
|
|
1874
|
+
const key = sessionStorage.key(index);
|
|
1875
|
+
if (!key?.startsWith(prefix))
|
|
1876
|
+
continue;
|
|
1877
|
+
const entityId = key.slice(prefix.length);
|
|
1878
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(entityId)) {
|
|
1879
|
+
throw new Error('invalid split vehicle action entity');
|
|
1880
|
+
}
|
|
1881
|
+
const rawSequence = sessionStorage.getItem(key);
|
|
1882
|
+
if (!rawSequence)
|
|
1883
|
+
throw new Error('missing split vehicle action sequence');
|
|
1884
|
+
const sequence = sanitizedVehicleActionSeq({ [entityId]: JSON.parse(rawSequence) }).get(entityId);
|
|
1885
|
+
if (!sequence)
|
|
1886
|
+
throw new Error('invalid split vehicle action sequence');
|
|
1887
|
+
vehicleActionSeq.set(entityId, sequence);
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
const record = {
|
|
1891
|
+
sessionIdentity: v.sessionIdentity,
|
|
1892
|
+
wsUrl: v.wsUrl,
|
|
1893
|
+
reconnectionToken: v.reconnectionToken,
|
|
1894
|
+
roomId: typeof v.roomId === 'string' ? v.roomId : null,
|
|
1895
|
+
maxPlayers: typeof v.maxPlayers === 'number' ? v.maxPlayers : null,
|
|
1896
|
+
roomType: typeof v.roomType === 'string' && v.roomType ? v.roomType : null,
|
|
1897
|
+
instanceKey: typeof v.instanceKey === 'string' && v.instanceKey ? v.instanceKey : null,
|
|
1898
|
+
vehicleActionSeq,
|
|
1899
|
+
legacyVehicleActionSeq: legacyVehicleActionSeq.size > 0 && rawEntities === undefined,
|
|
1900
|
+
};
|
|
1901
|
+
this.reconnectCache = { scope, record };
|
|
1902
|
+
return record;
|
|
249
1903
|
}
|
|
250
1904
|
catch {
|
|
1905
|
+
this.clearReconnect(scope);
|
|
251
1906
|
return null;
|
|
252
1907
|
}
|
|
253
1908
|
}
|
|
254
|
-
|
|
255
|
-
|
|
1909
|
+
persistCurrentReconnect() {
|
|
1910
|
+
if (!this.reconnectScope || !this.room)
|
|
1911
|
+
return false;
|
|
1912
|
+
const wsUrl = this.readReconnect(this.reconnectScope)?.wsUrl ?? '';
|
|
1913
|
+
return this.persistReconnect(this.reconnectScope, wsUrl, this.room.reconnectionToken, this.room.roomId);
|
|
1914
|
+
}
|
|
1915
|
+
persistVehicleActionSequence(entityId, sequence, newEntity) {
|
|
1916
|
+
if (!this.reconnectScope || typeof sessionStorage === 'undefined') {
|
|
1917
|
+
this.vehicleActionSeq.set(entityId, sequence);
|
|
1918
|
+
return true;
|
|
1919
|
+
}
|
|
1920
|
+
const prior = this.vehicleActionSeq.get(entityId);
|
|
1921
|
+
const key = VEHICLE_ACTION_SEQ_KEY(this.reconnectScope, entityId);
|
|
1922
|
+
try {
|
|
1923
|
+
sessionStorage.setItem(key, JSON.stringify(sequence));
|
|
1924
|
+
this.vehicleActionSeq.set(entityId, sequence);
|
|
1925
|
+
if (!newEntity || this.persistCurrentReconnect())
|
|
1926
|
+
return true;
|
|
1927
|
+
}
|
|
1928
|
+
catch { /* rollback below */ }
|
|
1929
|
+
if (prior)
|
|
1930
|
+
this.vehicleActionSeq.set(entityId, prior);
|
|
1931
|
+
else
|
|
1932
|
+
this.vehicleActionSeq.delete(entityId);
|
|
1933
|
+
try {
|
|
1934
|
+
sessionStorage.removeItem(key);
|
|
1935
|
+
}
|
|
1936
|
+
catch { /* stale token remains safe at its old high-water */ }
|
|
1937
|
+
return false;
|
|
256
1938
|
}
|
|
257
|
-
|
|
1939
|
+
retireVehicleActionSequence(entityId, authorityEpoch) {
|
|
1940
|
+
const current = this.vehicleActionSeq.get(entityId);
|
|
1941
|
+
if (!current || current.authorityEpoch !== authorityEpoch)
|
|
1942
|
+
return;
|
|
1943
|
+
this.vehicleActionSeq.delete(entityId);
|
|
1944
|
+
if (this.reconnectScope && typeof sessionStorage !== 'undefined') {
|
|
1945
|
+
try {
|
|
1946
|
+
sessionStorage.removeItem(VEHICLE_ACTION_SEQ_KEY(this.reconnectScope, entityId));
|
|
1947
|
+
}
|
|
1948
|
+
catch { /* manifest rewrite stays safe */ }
|
|
1949
|
+
}
|
|
1950
|
+
// WebSocket messages arrive as separate tasks, so a microtask would still rewrite the full shrinking
|
|
1951
|
+
// manifest once per retirement. Debounce across the burst while keeping the final durable rewrite bounded.
|
|
1952
|
+
if (this.vehicleActionManifestPersistTimer)
|
|
1953
|
+
clearTimeout(this.vehicleActionManifestPersistTimer);
|
|
1954
|
+
this.vehicleActionManifestPersistTimer = setTimeout(() => this.flushVehicleActionManifest(), 25);
|
|
1955
|
+
}
|
|
1956
|
+
/** Adopt the server's exact accepted fences for the reconnect baseline without clobbering actions submitted
|
|
1957
|
+
* after this connection opened. This repairs retirements missed while the seat was disconnected. */
|
|
1958
|
+
adoptVehicleActionFences(payload) {
|
|
1959
|
+
const baseline = this.vehicleActionReconnectBaseline;
|
|
1960
|
+
if (!baseline || !Array.isArray(payload.entries) || payload.entries.length > 4096)
|
|
1961
|
+
return;
|
|
1962
|
+
const authoritative = new Map();
|
|
1963
|
+
for (const entry of payload.entries) {
|
|
1964
|
+
if (!entry ||
|
|
1965
|
+
typeof entry.entityId !== 'string' ||
|
|
1966
|
+
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(entry.entityId) ||
|
|
1967
|
+
authoritative.has(entry.entityId) ||
|
|
1968
|
+
!Number.isSafeInteger(entry.authorityEpoch) ||
|
|
1969
|
+
entry.authorityEpoch < 0 ||
|
|
1970
|
+
!Number.isSafeInteger(entry.seq) ||
|
|
1971
|
+
entry.seq < 1 ||
|
|
1972
|
+
entry.seq >= Number.MAX_SAFE_INTEGER)
|
|
1973
|
+
return;
|
|
1974
|
+
authoritative.set(entry.entityId, { authorityEpoch: entry.authorityEpoch, seq: entry.seq });
|
|
1975
|
+
}
|
|
1976
|
+
for (const [entityId, atReconnect] of baseline) {
|
|
1977
|
+
const current = this.vehicleActionSeq.get(entityId);
|
|
1978
|
+
if (!current || current.authorityEpoch !== atReconnect.authorityEpoch || current.seq !== atReconnect.seq)
|
|
1979
|
+
continue;
|
|
1980
|
+
const server = authoritative.get(entityId);
|
|
1981
|
+
if (server)
|
|
1982
|
+
this.vehicleActionSeq.set(entityId, server);
|
|
1983
|
+
else
|
|
1984
|
+
this.vehicleActionSeq.delete(entityId);
|
|
1985
|
+
}
|
|
1986
|
+
for (const [entityId, server] of authoritative) {
|
|
1987
|
+
if (!this.vehicleActionSeq.has(entityId))
|
|
1988
|
+
this.vehicleActionSeq.set(entityId, server);
|
|
1989
|
+
}
|
|
1990
|
+
this.vehicleActionReconnectBaseline = null;
|
|
1991
|
+
if (this.vehicleActionManifestPersistTimer)
|
|
1992
|
+
clearTimeout(this.vehicleActionManifestPersistTimer);
|
|
1993
|
+
this.vehicleActionManifestPersistTimer = null;
|
|
1994
|
+
if (!this.reconnectScope || typeof sessionStorage === 'undefined')
|
|
1995
|
+
return;
|
|
1996
|
+
try {
|
|
1997
|
+
const prefix = VEHICLE_ACTION_SEQ_KEY_PREFIX(this.reconnectScope);
|
|
1998
|
+
for (let index = sessionStorage.length - 1; index >= 0; index--) {
|
|
1999
|
+
const key = sessionStorage.key(index);
|
|
2000
|
+
if (key?.startsWith(prefix) && !this.vehicleActionSeq.has(key.slice(prefix.length))) {
|
|
2001
|
+
sessionStorage.removeItem(key);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
for (const [entityId, sequence] of this.vehicleActionSeq) {
|
|
2005
|
+
sessionStorage.setItem(VEHICLE_ACTION_SEQ_KEY(this.reconnectScope, entityId), JSON.stringify(sequence));
|
|
2006
|
+
}
|
|
2007
|
+
if (this.persistCurrentReconnect())
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
catch { /* invalidate durable resume below */ }
|
|
2011
|
+
this.removePersistedReconnectMetadata(this.reconnectScope);
|
|
2012
|
+
}
|
|
2013
|
+
flushVehicleActionManifest() {
|
|
2014
|
+
this.vehicleActionManifestPersistTimer = null;
|
|
2015
|
+
if (this.persistCurrentReconnect() || !this.reconnectScope)
|
|
2016
|
+
return;
|
|
2017
|
+
this.removePersistedReconnectMetadata(this.reconnectScope);
|
|
2018
|
+
}
|
|
2019
|
+
migrateLegacyVehicleActionSequences(scope, record) {
|
|
2020
|
+
if (!record.legacyVehicleActionSeq || typeof sessionStorage === 'undefined')
|
|
2021
|
+
return true;
|
|
2022
|
+
for (const [entityId, sequence] of record.vehicleActionSeq) {
|
|
2023
|
+
try {
|
|
2024
|
+
sessionStorage.setItem(VEHICLE_ACTION_SEQ_KEY(scope, entityId), JSON.stringify(sequence));
|
|
2025
|
+
}
|
|
2026
|
+
catch {
|
|
2027
|
+
return false;
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
return true;
|
|
2031
|
+
}
|
|
2032
|
+
clearReconnect(scope) {
|
|
2033
|
+
if (this.reconnectCache?.scope === scope)
|
|
2034
|
+
this.reconnectCache = null;
|
|
258
2035
|
if (typeof sessionStorage === 'undefined')
|
|
259
2036
|
return;
|
|
260
2037
|
try {
|
|
261
|
-
|
|
2038
|
+
this.removePersistedReconnectMetadata(scope);
|
|
2039
|
+
const prefix = VEHICLE_ACTION_SEQ_KEY_PREFIX(scope);
|
|
2040
|
+
for (let index = sessionStorage.length - 1; index >= 0; index--) {
|
|
2041
|
+
const key = sessionStorage.key(index);
|
|
2042
|
+
if (key?.startsWith(prefix))
|
|
2043
|
+
sessionStorage.removeItem(key);
|
|
2044
|
+
}
|
|
262
2045
|
}
|
|
263
2046
|
catch { /* ignore */ }
|
|
264
2047
|
}
|
|
2048
|
+
removePersistedReconnectMetadata(scope) {
|
|
2049
|
+
if (typeof sessionStorage === 'undefined')
|
|
2050
|
+
return;
|
|
2051
|
+
try {
|
|
2052
|
+
sessionStorage.removeItem(RECONNECT_KEY(scope));
|
|
2053
|
+
}
|
|
2054
|
+
catch { /* stale/rotated token will fail closed */ }
|
|
2055
|
+
}
|
|
2056
|
+
// Room types: the active-room pointer (see ACTIVE_ROOM_KEY). Read / write / clear, each mirrored in memory
|
|
2057
|
+
// for hosts without sessionStorage. A malformed pointer is dropped — it can only ever cost one resume.
|
|
2058
|
+
// ACTOR-BOUND, like the reconnect slots. The pointer is what selects a typed slot and what names a ticketed
|
|
2059
|
+
// instance for the rejoin endpoint, so following another actor's pointer would be resuming their room by
|
|
2060
|
+
// another door. A pointer written by a different World-session actor, an unbound one from before the
|
|
2061
|
+
// binding existed, or any pointer when the current credential has no readable identity, is not followed:
|
|
2062
|
+
// it is removed together with the typed slot it names, and the join proceeds as if it had never been there.
|
|
2063
|
+
readActiveRoom(worldId) {
|
|
2064
|
+
if (this.activeRoomCache?.worldId === worldId) {
|
|
2065
|
+
const cached = this.activeRoomCache;
|
|
2066
|
+
if (this.sessionIdentity && cached.sessionIdentity === this.sessionIdentity)
|
|
2067
|
+
return cached.pointer;
|
|
2068
|
+
this.clearReconnect(reconnectScope(worldId, cached.pointer.roomType));
|
|
2069
|
+
this.clearActiveRoom(worldId, true);
|
|
2070
|
+
return null;
|
|
2071
|
+
}
|
|
2072
|
+
if (typeof sessionStorage === 'undefined')
|
|
2073
|
+
return null;
|
|
2074
|
+
try {
|
|
2075
|
+
const raw = sessionStorage.getItem(ACTIVE_ROOM_KEY(worldId));
|
|
2076
|
+
if (!raw)
|
|
2077
|
+
return null;
|
|
2078
|
+
const v = JSON.parse(raw);
|
|
2079
|
+
if (typeof v?.roomType !== 'string' || !v.roomType)
|
|
2080
|
+
throw new Error('invalid active room');
|
|
2081
|
+
if (!this.sessionIdentity || v.sessionIdentity !== this.sessionIdentity) {
|
|
2082
|
+
this.clearReconnect(reconnectScope(worldId, v.roomType));
|
|
2083
|
+
throw new Error('active room belongs to another actor');
|
|
2084
|
+
}
|
|
2085
|
+
return {
|
|
2086
|
+
roomType: v.roomType,
|
|
2087
|
+
instanceKey: typeof v.instanceKey === 'string' && v.instanceKey ? v.instanceKey : null,
|
|
2088
|
+
shellInstance: typeof v.shellInstance === 'string' && v.shellInstance ? v.shellInstance : null,
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
catch {
|
|
2092
|
+
this.clearActiveRoom(worldId, true);
|
|
2093
|
+
return null;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
writeActiveRoom(worldId, pointer) {
|
|
2097
|
+
// Only a join / hop writes the pointer, and one that leave() has cancelled is on its way out of whatever
|
|
2098
|
+
// room it reaches: the player left, so nothing may lead a reload back there. Not written, and not kept.
|
|
2099
|
+
if (this.entering?.cancelled) {
|
|
2100
|
+
this.clearActiveRoom(worldId);
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
// No readable identity, no pointer — the same rule persistReconnect applies to a slot. An unbound way back
|
|
2104
|
+
// into a room is exactly what the actor binding exists to prevent.
|
|
2105
|
+
if (!this.sessionIdentity) {
|
|
2106
|
+
this.clearActiveRoom(worldId, true);
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
2109
|
+
this.activeRoomCache = { worldId, sessionIdentity: this.sessionIdentity, pointer };
|
|
2110
|
+
if (typeof sessionStorage === 'undefined')
|
|
2111
|
+
return;
|
|
2112
|
+
try {
|
|
2113
|
+
sessionStorage.setItem(ACTIVE_ROOM_KEY(worldId), JSON.stringify({
|
|
2114
|
+
sessionIdentity: this.sessionIdentity,
|
|
2115
|
+
roomType: pointer.roomType,
|
|
2116
|
+
...(pointer.instanceKey !== null ? { instanceKey: pointer.instanceKey } : {}),
|
|
2117
|
+
...(pointer.shellInstance !== null ? { shellInstance: pointer.shellInstance } : {}),
|
|
2118
|
+
}));
|
|
2119
|
+
}
|
|
2120
|
+
catch { /* an unwritable pointer only costs the typed resume; the join itself is live */ }
|
|
2121
|
+
}
|
|
2122
|
+
// `force` skips the existence probe (used when the stored value is known-bad). Otherwise storage is only
|
|
2123
|
+
// touched when a pointer is actually there, so the default-only path performs no extra writes.
|
|
2124
|
+
clearActiveRoom(worldId, force = false) {
|
|
2125
|
+
if (this.activeRoomCache?.worldId === worldId)
|
|
2126
|
+
this.activeRoomCache = null;
|
|
2127
|
+
if (typeof sessionStorage === 'undefined')
|
|
2128
|
+
return;
|
|
2129
|
+
try {
|
|
2130
|
+
const key = ACTIVE_ROOM_KEY(worldId);
|
|
2131
|
+
if (force || sessionStorage.getItem(key) !== null)
|
|
2132
|
+
sessionStorage.removeItem(key);
|
|
2133
|
+
}
|
|
2134
|
+
catch { /* ignore */ }
|
|
2135
|
+
}
|
|
2136
|
+
// Remove every typed reconnect slot of this world except `keepType`'s (null = keep none): the slot record
|
|
2137
|
+
// and its per-entity vehicle high-waters share the `…:rt:<type>` prefix. Room-type names cannot contain ':'
|
|
2138
|
+
// (manifest grammar), so `<kept>:` cannot be a prefix of another type's keys. Read-only unless something is
|
|
2139
|
+
// actually orphaned — a world that never uses room types never has such a key.
|
|
2140
|
+
clearOtherTypedSlots(worldId, keepType) {
|
|
2141
|
+
const keepScope = keepType !== null ? reconnectScope(worldId, keepType) : null;
|
|
2142
|
+
if (this.reconnectCache && this.reconnectCache.scope.startsWith(`${worldId}:rt:`) && this.reconnectCache.scope !== keepScope) {
|
|
2143
|
+
this.reconnectCache = null;
|
|
2144
|
+
}
|
|
2145
|
+
if (typeof sessionStorage === 'undefined')
|
|
2146
|
+
return;
|
|
2147
|
+
try {
|
|
2148
|
+
const prefix = `${RECONNECT_KEY(worldId)}:rt:`;
|
|
2149
|
+
const keep = keepScope !== null ? RECONNECT_KEY(keepScope) : null;
|
|
2150
|
+
for (let index = sessionStorage.length - 1; index >= 0; index--) {
|
|
2151
|
+
const key = sessionStorage.key(index);
|
|
2152
|
+
if (!key?.startsWith(prefix))
|
|
2153
|
+
continue;
|
|
2154
|
+
if (keep !== null && (key === keep || key.startsWith(`${keep}:`)))
|
|
2155
|
+
continue;
|
|
2156
|
+
sessionStorage.removeItem(key);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
catch { /* ignore */ }
|
|
2160
|
+
}
|
|
2161
|
+
// A hop must not be undone by a later reload-resume: drop every slot this world could resume into — the
|
|
2162
|
+
// default one and the active typed one — together with the pointer.
|
|
2163
|
+
forgetReconnectSlots(worldId) {
|
|
2164
|
+
this.clearActiveRoom(worldId);
|
|
2165
|
+
this.clearOtherTypedSlots(worldId, null);
|
|
2166
|
+
this.clearReconnect(worldId);
|
|
2167
|
+
}
|
|
265
2168
|
// Resume a grace-held seat (a reload). Returns the resumed room, or null to fall through to a fresh join
|
|
266
2169
|
// (no saved token / grace expired / seat despawned / stale wsUrl — reconnect() rejects and we drop the token).
|
|
267
|
-
|
|
268
|
-
|
|
2170
|
+
//
|
|
2171
|
+
// `scope` selects the slot: the bare world id for the default room, the per-type scope for a typed one.
|
|
2172
|
+
// `strictInstanceId` is the shell's `?instance=` and is passed for the DEFAULT slot only — there, a record
|
|
2173
|
+
// for a different room is dropped so it can never bypass the exact joinById. A typed slot is exempt (the
|
|
2174
|
+
// caller passes null): the shell's instance names a default-type room and has no bearing on it. `typed`
|
|
2175
|
+
// carries the room type (and the pointer's instance id) the resumed seat belongs to; null = default.
|
|
2176
|
+
async tryReconnect(colyseus, scope, strictInstanceId, typed) {
|
|
2177
|
+
const saved = this.readReconnect(scope);
|
|
269
2178
|
if (!saved)
|
|
270
2179
|
return null;
|
|
2180
|
+
// The actor fence applies to whichever slot this is — default or typed.
|
|
2181
|
+
if (!this.sessionIdentity || saved.sessionIdentity !== this.sessionIdentity) {
|
|
2182
|
+
this.clearReconnect(scope);
|
|
2183
|
+
return null;
|
|
2184
|
+
}
|
|
2185
|
+
if (strictInstanceId && saved.roomId !== strictInstanceId) {
|
|
2186
|
+
this.clearReconnect(scope);
|
|
2187
|
+
return null;
|
|
2188
|
+
}
|
|
2189
|
+
if (!this.migrateLegacyVehicleActionSequences(scope, saved)) {
|
|
2190
|
+
this.clearReconnect(scope);
|
|
2191
|
+
return null;
|
|
2192
|
+
}
|
|
271
2193
|
try {
|
|
272
2194
|
const client = new colyseus.Client(saved.wsUrl);
|
|
273
|
-
const room = await client.reconnect(saved.reconnectionToken);
|
|
274
|
-
this.
|
|
2195
|
+
const room = await this.abandonable(client.reconnect(saved.reconnectionToken), this.releaseLateRoom);
|
|
2196
|
+
this.roomMaxPlayers = saved.maxPlayers; // no fresh credential on a resume — restore the persisted cap
|
|
2197
|
+
this.roomType = typed?.roomType ?? null;
|
|
2198
|
+
this.instanceKey = typed ? saved.instanceKey ?? typed.instanceKey : null;
|
|
2199
|
+
this.vehicleActionSeq = saved.vehicleActionSeq;
|
|
2200
|
+
// The token may rotate on resume. If metadata persistence fails, invalidate reload-resume but keep this
|
|
2201
|
+
// already-live connection usable; no future action can restart against the held seat after a reload.
|
|
2202
|
+
if (!this.persistReconnect(scope, saved.wsUrl, room.reconnectionToken, room.roomId)) {
|
|
2203
|
+
// Keep the rotated token/wsUrl in memory for this live room so a later successful manifest write can
|
|
2204
|
+
// restore durable resume. Remove only the unsafe persisted metadata; per-entity high-waters remain.
|
|
2205
|
+
this.removePersistedReconnectMetadata(scope);
|
|
2206
|
+
}
|
|
275
2207
|
return room;
|
|
276
2208
|
}
|
|
277
|
-
catch {
|
|
278
|
-
this.clearReconnect(
|
|
2209
|
+
catch (e) {
|
|
2210
|
+
this.clearReconnect(scope);
|
|
2211
|
+
if (isAbandonment(e))
|
|
2212
|
+
throw e; // leave() gave up on this join: no fresh join in its place
|
|
279
2213
|
return null;
|
|
280
2214
|
}
|
|
281
2215
|
}
|
|
282
2216
|
// Leave for good: consented (frees the seat immediately, no grace) + drop the saved token so we don't try to
|
|
283
|
-
// resume a seat we deliberately left. (A reload does NOT call this — it just unloads.)
|
|
2217
|
+
// resume a seat we deliberately left. (A reload does NOT call this — it just unloads.) Public: the room
|
|
2218
|
+
// handle's leave() and the shell's helix:leave (Exit button / browser Back) both land here.
|
|
2219
|
+
//
|
|
2220
|
+
//
|
|
2221
|
+
// EVERY leave resolves. On a healthy socket nothing changed: the consented LEAVE is sent and this resolves
|
|
2222
|
+
// when the server's close arrives (onLeave: 4000, 'leave'). But two kinds of socket never answer:
|
|
2223
|
+
// • a DROPPED one (not open) cannot be told anything — a LEAVE written to it is lost. It is detached locally
|
|
2224
|
+
// at once (no reconnection, socket closed); the server reaps the seat through its ordinary drop grace.
|
|
2225
|
+
// • a BLACK-HOLED one still reports open, so there is nothing to test for: the LEAVE is sent and simply
|
|
2226
|
+
// never answered. The wait is therefore bounded (ROOM_LEAVE_TIMEOUT_MS), then the same local detach.
|
|
2227
|
+
// Either way the room can no longer auto-reconnect behind the SDK's back and keep the seat this method
|
|
2228
|
+
// "left". A transport that throws or rejects is treated the same way instead of rejecting the leave — the
|
|
2229
|
+
// room is gone from the caller's point of view in every case, which is what leave() promises.
|
|
2230
|
+
//
|
|
2231
|
+
// A leave during a joinRoom() / switchRoom() CANCELS it. The room being entered is not this.ctx yet, so
|
|
2232
|
+
// leaving "the current room" alone would be overtaken a moment later by the join landing — the caller would
|
|
2233
|
+
// end up seated in a room right after leaving. Instead the call in flight is told, releases whatever seat it
|
|
2234
|
+
// takes, and rejects with `cancelled`; this resolves once that is over, with the caller in no room.
|
|
2235
|
+
//
|
|
2236
|
+
// THAT WAIT IS BOUNDED TOO. The join's reservation request and the room handshake have no deadline of their
|
|
2237
|
+
// own, so a join that never gets an answer never finishes — and a leave that waited for it would never
|
|
2238
|
+
// resolve either. Past ROOM_LEAVE_TIMEOUT_MS this resolves regardless, with the caller in no room, and the
|
|
2239
|
+
// call in flight is GIVEN UP ON: it stops waiting for whatever has not answered and rejects `cancelled`
|
|
2240
|
+
// at that moment (see abandonable()), which releases its join / hop guard — the caller can join again as
|
|
2241
|
+
// soon as this resolves. A seat the abandoned handshake delivers later is released, never entered. A join
|
|
2242
|
+
// that settles inside the bound is waited for as before, and no timer outlives it.
|
|
2243
|
+
//
|
|
2244
|
+
// THE WAY BACK GOES WITH THE LEAVE. A ticketed room's active-room pointer is what makes a reload's plain
|
|
2245
|
+
// joinRoom() rejoin the instance, so a leave that cancels a join forgets it at once, and the cancelled join
|
|
2246
|
+
// can no longer write it (see writeActiveRoom) — not during the wait, and not after the bound.
|
|
284
2247
|
async leave() {
|
|
285
|
-
const
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
2248
|
+
const entering = this.entering;
|
|
2249
|
+
if (entering) {
|
|
2250
|
+
entering.cancelled = true;
|
|
2251
|
+
this.forgetCancelledTarget(entering.worldId);
|
|
2252
|
+
}
|
|
2253
|
+
if (this.ctx)
|
|
2254
|
+
await this.leaveRoom(this.ctx);
|
|
2255
|
+
if (!entering)
|
|
2256
|
+
return;
|
|
2257
|
+
let timer;
|
|
2258
|
+
let expired = false;
|
|
2259
|
+
await Promise.race([
|
|
2260
|
+
entering.done,
|
|
2261
|
+
new Promise((resolve) => { timer = setTimeout(() => { expired = true; resolve(); }, ROOM_LEAVE_TIMEOUT_MS); }),
|
|
2262
|
+
]);
|
|
2263
|
+
if (timer !== undefined)
|
|
2264
|
+
clearTimeout(timer);
|
|
2265
|
+
if (!expired)
|
|
2266
|
+
return;
|
|
2267
|
+
entering.giveUp();
|
|
2268
|
+
this.forgetCancelledTarget(entering.worldId);
|
|
2269
|
+
// The abandoned call now unwinds in a few microtasks; wait for that, so the guard is free when this
|
|
2270
|
+
// resolves. One macrotask at most: a call stuck somewhere abandonable() does not reach cannot hold the leave.
|
|
2271
|
+
await Promise.race([
|
|
2272
|
+
entering.done,
|
|
2273
|
+
new Promise((resolve) => { timer = setTimeout(resolve, 0); }),
|
|
2274
|
+
]);
|
|
2275
|
+
clearTimeout(timer);
|
|
2276
|
+
}
|
|
2277
|
+
// Leave ONE specific room — the room a handle belongs to. A room that is no longer the current one is not
|
|
2278
|
+
// ours to leave any more (it was left, or hopped away from, and may have a successor): resolve as a no-op,
|
|
2279
|
+
// so a stale handle's leave() can never eject the player from the room they are in NOW.
|
|
2280
|
+
async leaveRoom(ctx) {
|
|
2281
|
+
if (this.ctx !== ctx)
|
|
2282
|
+
return;
|
|
2283
|
+
this.detachCurrentRoom('leave');
|
|
2284
|
+
// `=== false`, not `!isOpen`: an absent `connection` (a colyseus shape change) counts as open.
|
|
2285
|
+
if (ctx.room.connection?.isOpen === false) {
|
|
2286
|
+
this.forceDetach(ctx);
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
await this.leaveBounded(ctx);
|
|
291
2290
|
}
|
|
292
2291
|
// Reset in-memory state. Called on a drop too (onLeave) — it does NOT clear the saved reconnect token, so a
|
|
293
2292
|
// later reload can still resume the grace-held seat.
|
|
294
2293
|
teardown() {
|
|
2294
|
+
this.revokeModuleEngagements();
|
|
2295
|
+
if (this.room)
|
|
2296
|
+
this.host.publishRoomState?.(null); // tell the shell the room is gone (roster panel clears)
|
|
2297
|
+
this.rosterSig = null;
|
|
2298
|
+
this.roomMaxPlayers = null;
|
|
295
2299
|
if (this.flushTimer)
|
|
296
2300
|
clearInterval(this.flushTimer);
|
|
297
2301
|
this.flushTimer = null;
|
|
2302
|
+
if (this.vehicleActionManifestPersistTimer) {
|
|
2303
|
+
clearTimeout(this.vehicleActionManifestPersistTimer);
|
|
2304
|
+
// An unexpected drop still owns a grace-held seat. Persist the already-removed split keys before clearing
|
|
2305
|
+
// live room/cache state, or invalidate metadata rather than leave a manifest that cannot be resumed.
|
|
2306
|
+
this.flushVehicleActionManifest();
|
|
2307
|
+
}
|
|
2308
|
+
this.rejectDistributionCapabilities('not_in_room');
|
|
298
2309
|
this.room = null;
|
|
299
2310
|
this.callbacks = null;
|
|
300
2311
|
this.pendingInput = null;
|
|
2312
|
+
this.internalAvatarPose = null;
|
|
301
2313
|
this.inputBuffer = [];
|
|
302
2314
|
this.worldId = null;
|
|
2315
|
+
this.reconnectScope = null;
|
|
2316
|
+
this.roomType = null;
|
|
2317
|
+
this.instanceKey = null;
|
|
2318
|
+
this.ctx = null; // every callback of the room just left is now a no-op (its onLeave is still delivered)
|
|
303
2319
|
this.seq = 0;
|
|
2320
|
+
this.teleportSeq = 0;
|
|
304
2321
|
this.entitySeq = {};
|
|
305
2322
|
this.entityBatchSeq = 0;
|
|
2323
|
+
this.vehicleActionSeq = new Map();
|
|
2324
|
+
this.vehicleActionReconnectBaseline = null;
|
|
2325
|
+
this.retiredVehicleActionEpochs.clear();
|
|
306
2326
|
this.onStateAckCb = null;
|
|
307
2327
|
this.onEntityStateAckCb = null;
|
|
2328
|
+
this.engagementRequestSeq = 0;
|
|
2329
|
+
this.moduleEngagementCbs.clear();
|
|
2330
|
+
for (const detach of this.avatarListeners.values())
|
|
2331
|
+
detach();
|
|
2332
|
+
this.avatarListeners.clear();
|
|
2333
|
+
this.avatarChangedCbs.clear();
|
|
308
2334
|
}
|
|
309
2335
|
}
|
|
310
2336
|
// netlog sink lookup (opt-in): the host installs globalThis.__HELIX_NETLOG__ = (msg) => ... to turn on the
|
|
@@ -314,6 +2340,131 @@ function netSink() {
|
|
|
314
2340
|
const s = globalThis.__HELIX_NETLOG__;
|
|
315
2341
|
return typeof s === 'function' ? s : undefined;
|
|
316
2342
|
}
|
|
2343
|
+
// Avatar state reads tolerate older rooms (no revision) and malformed values without breaking a room patch.
|
|
2344
|
+
function avatarUrlOfPlayerState(player) {
|
|
2345
|
+
if (!player || typeof player !== 'object')
|
|
2346
|
+
return '';
|
|
2347
|
+
const value = player.avatarUrl;
|
|
2348
|
+
return typeof value === 'string' ? value : '';
|
|
2349
|
+
}
|
|
2350
|
+
function avatarRevisionOfPlayerState(player) {
|
|
2351
|
+
if (!player || typeof player !== 'object')
|
|
2352
|
+
return 0;
|
|
2353
|
+
const value = player.avatarRevision;
|
|
2354
|
+
return Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff
|
|
2355
|
+
? value
|
|
2356
|
+
: 0;
|
|
2357
|
+
}
|
|
2358
|
+
// Roster extraction for the shell publish, tolerant of both runtime shapes: a live colyseus MapSchema
|
|
2359
|
+
// (Map-like forEach) and the plain object used in tests/tooling. Field reads are defensive — a pre-v18
|
|
2360
|
+
// room replicates no userId (→ ''), and a malformed seat must never break the publish path.
|
|
2361
|
+
function rosterOf(state, selfId) {
|
|
2362
|
+
const players = state?.players;
|
|
2363
|
+
const entries = [];
|
|
2364
|
+
const push = (value, key) => {
|
|
2365
|
+
const p = (value ?? {});
|
|
2366
|
+
entries.push({
|
|
2367
|
+
sessionId: key,
|
|
2368
|
+
userId: typeof p.userId === 'string' ? p.userId : '',
|
|
2369
|
+
displayName: typeof p.displayName === 'string' ? p.displayName : '',
|
|
2370
|
+
avatarUrl: typeof p.avatarUrl === 'string' ? p.avatarUrl : '',
|
|
2371
|
+
isSelf: key === selfId,
|
|
2372
|
+
connected: p.connected !== false,
|
|
2373
|
+
});
|
|
2374
|
+
};
|
|
2375
|
+
const mapLike = players;
|
|
2376
|
+
if (mapLike && typeof mapLike.forEach === 'function')
|
|
2377
|
+
mapLike.forEach(push);
|
|
2378
|
+
else if (players && typeof players === 'object')
|
|
2379
|
+
for (const [k, v] of Object.entries(players))
|
|
2380
|
+
push(v, k);
|
|
2381
|
+
return entries;
|
|
2382
|
+
}
|
|
2383
|
+
// Map a refused join to a stable code by the backend's own refusal `code` (bodies are
|
|
2384
|
+
// `{ statusCode, code, message }`), NEVER by HTTP status alone: a 404 can just as well be "world not found",
|
|
2385
|
+
// and calling that a bad ticket would send a world down the wrong recovery path. `error` / `message` are
|
|
2386
|
+
// checked for the same exact strings only as a courtesy to a body that carries the code there.
|
|
2387
|
+
const JOIN_REFUSAL_CODES = {
|
|
2388
|
+
'unknown-room-type': 'unknown-room-type',
|
|
2389
|
+
'ticket-required': 'ticket-required',
|
|
2390
|
+
'unknown-room-ticket': 'ticket-invalid',
|
|
2391
|
+
'room-ticket-expired': 'ticket-invalid',
|
|
2392
|
+
'room-ticket-used': 'ticket-invalid',
|
|
2393
|
+
// The ticket itself was fine; the match it led to has ended. That is not the player's ticket being bad.
|
|
2394
|
+
'room-instance-closed': 'instance-closed',
|
|
2395
|
+
};
|
|
2396
|
+
function joinRefusalCode(detail) {
|
|
2397
|
+
const fields = detail && typeof detail === 'object'
|
|
2398
|
+
? [detail.code, detail.error, detail.message]
|
|
2399
|
+
: [];
|
|
2400
|
+
for (const field of fields) {
|
|
2401
|
+
if (typeof field === 'string' && Object.prototype.hasOwnProperty.call(JOIN_REFUSAL_CODES, field))
|
|
2402
|
+
return JOIN_REFUSAL_CODES[field];
|
|
2403
|
+
}
|
|
2404
|
+
return 'join-failed';
|
|
2405
|
+
}
|
|
2406
|
+
// Which rejoin failures leave the question open. No status = the request never got an answer; 5xx = the
|
|
2407
|
+
// backend is unwell; 429 = asked too fast; 401 = the world session expired and the shell may refresh it. None
|
|
2408
|
+
// of them says anything about the match, so the instance is kept. 403 / 404 / 410 are answers.
|
|
2409
|
+
// What entering.abandoned resolves with when leave() gives up on the join in flight.
|
|
2410
|
+
const ABANDONED = Symbol('abandoned');
|
|
2411
|
+
// The rejection abandonable() raises. Inside joinRoomInternal `cancelled` has no other source.
|
|
2412
|
+
function isAbandonment(e) {
|
|
2413
|
+
return e instanceof HelixRoomJoinError && e.code === 'cancelled';
|
|
2414
|
+
}
|
|
2415
|
+
function isRetryableRejoinStatus(status) {
|
|
2416
|
+
return status === null || status >= 500 || status === 429 || status === 401;
|
|
2417
|
+
}
|
|
2418
|
+
// Whatever the backend called a ticket's expiry → Unix epoch milliseconds, or NaN. Deliberately strict about
|
|
2419
|
+
// what counts as a timestamp, because a wrong finite number is worse than NaN (a world would trust it):
|
|
2420
|
+
// • a positive finite number: below 1e12 it is epoch SECONDS (1e12 ms is 2001-09-09 — no ticket is that old —
|
|
2421
|
+
// and 1e12 s is the year 33658), otherwise already milliseconds. Zero and negatives are not timestamps.
|
|
2422
|
+
// • a numeric string is an epoch only with 9+ integer digits; anything shorter is NOT handed to Date.parse,
|
|
2423
|
+
// which would happily read "2030" as midnight on 1 January 2030.
|
|
2424
|
+
// • any other string is parsed as a date (ISO-8601 is what the backend sends).
|
|
2425
|
+
export function epochMsOf(raw) {
|
|
2426
|
+
if (typeof raw === 'number')
|
|
2427
|
+
return Number.isFinite(raw) && raw > 0 ? (raw < 1e12 ? raw * 1000 : raw) : Number.NaN;
|
|
2428
|
+
if (typeof raw !== 'string')
|
|
2429
|
+
return Number.NaN;
|
|
2430
|
+
const text = raw.trim();
|
|
2431
|
+
if (/^[+-]?\d+(\.\d+)?$/.test(text))
|
|
2432
|
+
return /^\d{9,}(\.\d+)?$/.test(text) ? epochMsOf(Number(text)) : Number.NaN;
|
|
2433
|
+
const parsed = Date.parse(text);
|
|
2434
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : Number.NaN;
|
|
2435
|
+
}
|
|
2436
|
+
// `helix:room-ticket` wire payload → the RoomTicket a world receives. The three ids must be usable strings or
|
|
2437
|
+
// the ticket is dropped (there is nothing to redeem). `expiresAt` is whatever the backend returned, forwarded
|
|
2438
|
+
// verbatim by the room, so it is normalised HERE (epochMsOf). Unparseable ⇒ NaN, never a dropped ticket:
|
|
2439
|
+
// redemption decides expiry.
|
|
2440
|
+
function roomTicketOf(payload) {
|
|
2441
|
+
const p = payload;
|
|
2442
|
+
if (!p || typeof p !== 'object')
|
|
2443
|
+
return null;
|
|
2444
|
+
if (typeof p.roomType !== 'string' || !p.roomType)
|
|
2445
|
+
return null;
|
|
2446
|
+
if (typeof p.ticketId !== 'string' || !p.ticketId)
|
|
2447
|
+
return null;
|
|
2448
|
+
if (typeof p.instanceId !== 'string' || !p.instanceId)
|
|
2449
|
+
return null;
|
|
2450
|
+
return { roomType: p.roomType, ticketId: p.ticketId, instanceId: p.instanceId, expiresAt: epochMsOf(p.expiresAt) };
|
|
2451
|
+
}
|
|
2452
|
+
// Read the `maxPlayers` claim from the room credential without verifying — DISPLAY only (the shell roster
|
|
2453
|
+
// panel's "n / max"); the room enforces the real cap in onAuth. Null when the credential isn't a decodable
|
|
2454
|
+
// JWT or lacks the claim.
|
|
2455
|
+
function maxPlayersOf(credential) {
|
|
2456
|
+
const segment = credential.split('.')[1];
|
|
2457
|
+
if (!segment)
|
|
2458
|
+
return null;
|
|
2459
|
+
try {
|
|
2460
|
+
const json = atob(segment.replace(/-/g, '+').replace(/_/g, '/'));
|
|
2461
|
+
const v = JSON.parse(json).maxPlayers;
|
|
2462
|
+
return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null;
|
|
2463
|
+
}
|
|
2464
|
+
catch {
|
|
2465
|
+
return null;
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
317
2468
|
// Read the `iss` claim from a JWT without verifying (the world_session issuer is the platform API
|
|
318
2469
|
// origin — the backend sets iss = PUBLIC_API_BASE_URL on every world_session). Verification isn't this
|
|
319
2470
|
// side's job; the room verifies the credential against JWKS. Returns null if there's no usable http(s)
|
|
@@ -331,4 +2482,22 @@ function issuerOf(token) {
|
|
|
331
2482
|
return null;
|
|
332
2483
|
}
|
|
333
2484
|
}
|
|
2485
|
+
// This is a resume-selection fence, never token verification or admission.
|
|
2486
|
+
// A same-actor token refresh keeps its binding; the backend still authenticates
|
|
2487
|
+
// every fresh /join. Missing identity must never inherit a cached room seat.
|
|
2488
|
+
function reconnectIdentityOf(token) {
|
|
2489
|
+
try {
|
|
2490
|
+
const segment = token.split('.')[1];
|
|
2491
|
+
if (!segment)
|
|
2492
|
+
return null;
|
|
2493
|
+
const { type, sub, wid, iss, guest } = JSON.parse(atob(segment.replace(/-/g, '+').replace(/_/g, '/')));
|
|
2494
|
+
if (type !== 'world_session' || typeof sub !== 'string' || !sub ||
|
|
2495
|
+
typeof wid !== 'string' || !wid || typeof iss !== 'string' || !/^https?:\/\//.test(iss))
|
|
2496
|
+
return null;
|
|
2497
|
+
return JSON.stringify([iss.replace(/\/$/, ''), sub, wid, guest === true]);
|
|
2498
|
+
}
|
|
2499
|
+
catch {
|
|
2500
|
+
return null;
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
334
2503
|
//# sourceMappingURL=multiplayer.js.map
|