@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
|
@@ -0,0 +1,1487 @@
|
|
|
1
|
+
// Helix.matchmaking + Helix.party (SPEC-U3, v1 scope): queues that open a ticketed room, and platform-level
|
|
2
|
+
// parties a world draws its own UI for.
|
|
3
|
+
//
|
|
4
|
+
// v1 is POLLING ONLY. These call the platform API directly with the world session — the same token and API
|
|
5
|
+
// base the join route uses — and are not `helix:request` bridge methods; there is no shell push. The SDK
|
|
6
|
+
// polls, and for a waiting queue ticket the poll IS the server heartbeat: the backend cancels a waiting
|
|
7
|
+
// ticket nobody polled for 15 s. So the queue poll keeps running while the tab is hidden, on a dedicated
|
|
8
|
+
// worker where the browser allows one (page timers in a hidden tab are throttled to once a minute after a
|
|
9
|
+
// few minutes; a worker's are not). A tab the browser fully suspends or discards cannot heartbeat at all
|
|
10
|
+
// and loses its place in the queue.
|
|
11
|
+
//
|
|
12
|
+
// Because the poll is a heartbeat, it is built not to stall: every request is abandoned after a bound, a
|
|
13
|
+
// poll that is still in flight only holds up polls of its own generation, failures back off, and once
|
|
14
|
+
// nothing has got through for as long as the server waits, subscribers are told the ticket is gone.
|
|
15
|
+
//
|
|
16
|
+
// Nothing here costs a world that never uses it: no timer, no listener and no request exists until the
|
|
17
|
+
// first matchmaking / party call, and all of them stop on helix:leave, page teardown and session loss.
|
|
18
|
+
import { epochMsOf } from './multiplayer.js';
|
|
19
|
+
import { ServerClock } from './server-clock.js';
|
|
20
|
+
/** The typed failure of every `Helix.matchmaking` promise. Branch on `code`; `status` is the HTTP status when there was one. */
|
|
21
|
+
export class HelixMatchmakingError extends Error {
|
|
22
|
+
code;
|
|
23
|
+
status;
|
|
24
|
+
/** The backend's own refusal code, verbatim, when the response carried one. */
|
|
25
|
+
backendCode;
|
|
26
|
+
/** With `already-matched`: the match the ticket was already in. */
|
|
27
|
+
match;
|
|
28
|
+
/** With `already-matched` from `enqueue()` and no `match`: the party member who holds the pending match. */
|
|
29
|
+
memberUserId;
|
|
30
|
+
constructor(code, message, status = null, backendCode = null, cause, match = null, memberUserId = null) {
|
|
31
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
32
|
+
this.name = 'HelixMatchmakingError';
|
|
33
|
+
this.code = code;
|
|
34
|
+
this.status = status;
|
|
35
|
+
this.backendCode = backendCode;
|
|
36
|
+
this.match = match;
|
|
37
|
+
this.memberUserId = memberUserId;
|
|
38
|
+
// Restore the prototype chain for ES5-targeted consumers, where `extends Error` loses it.
|
|
39
|
+
Object.setPrototypeOf(this, HelixMatchmakingError.prototype);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** The typed failure of every `Helix.party` promise. Branch on `code`; `status` is the HTTP status when there was one. */
|
|
43
|
+
export class HelixPartyError extends Error {
|
|
44
|
+
code;
|
|
45
|
+
status;
|
|
46
|
+
/** The backend's own refusal code, verbatim, when the response carried one. */
|
|
47
|
+
backendCode;
|
|
48
|
+
constructor(code, message, status = null, backendCode = null, cause) {
|
|
49
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
50
|
+
this.name = 'HelixPartyError';
|
|
51
|
+
this.code = code;
|
|
52
|
+
this.status = status;
|
|
53
|
+
this.backendCode = backendCode;
|
|
54
|
+
Object.setPrototypeOf(this, HelixPartyError.prototype);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const hostClocks = new WeakMap();
|
|
58
|
+
function clockOf(host) {
|
|
59
|
+
if (host.clock)
|
|
60
|
+
return host.clock;
|
|
61
|
+
let clock = hostClocks.get(host);
|
|
62
|
+
if (!clock)
|
|
63
|
+
hostClocks.set(host, (clock = new ServerClock()));
|
|
64
|
+
return clock;
|
|
65
|
+
}
|
|
66
|
+
/** While a queue ticket is waiting or matched. Also the server heartbeat (a waiting ticket unpolled for 15 s is cancelled). */
|
|
67
|
+
export const MATCHMAKING_POLL_MS = 3000;
|
|
68
|
+
/**
|
|
69
|
+
* While this player is in a party of two or more, is not queued, and the world listens to matchmaking: how
|
|
70
|
+
* often the SDK looks for a ticket the party's leader may have queued.
|
|
71
|
+
*/
|
|
72
|
+
export const MATCHMAKING_IDLE_POLL_MS = 5000;
|
|
73
|
+
/** While a world is subscribed to party changes or invites, or listens to matchmaking. */
|
|
74
|
+
export const PARTY_POLL_MS = 5000;
|
|
75
|
+
/** A platform request with no answer after this long is abandoned (and aborted), so it cannot stall a poll loop. */
|
|
76
|
+
export const PLATFORM_REQUEST_TIMEOUT_MS = 8000;
|
|
77
|
+
/**
|
|
78
|
+
* The bound for the queue STATUS POLL alone. Shorter than the general one because the poll is a heartbeat
|
|
79
|
+
* against a 15 s server limit: at 8 s one hung poll would leave an 11-12 s gap; at 5 s the next tick after it
|
|
80
|
+
* still lands with room to spare.
|
|
81
|
+
*/
|
|
82
|
+
export const MATCHMAKING_POLL_TIMEOUT_MS = 5000;
|
|
83
|
+
/** The server's patience: a waiting ticket not polled for this long has been cancelled. */
|
|
84
|
+
export const MATCHMAKING_HEARTBEAT_LOST_MS = 15_000;
|
|
85
|
+
/**
|
|
86
|
+
* How long the matchmaking loop may go without running before the page is taken to have been asleep (a
|
|
87
|
+
* suspended laptop, a frozen or heavily throttled tab). The loop runs at least every MATCHMAKING_IDLE_POLL_MS
|
|
88
|
+
* while awake, so a longer silence of its own means no poll COULD be sent — which is not the same as polls
|
|
89
|
+
* failing, and is not counted against the ticket: see HelixMatchmaking.woke().
|
|
90
|
+
*/
|
|
91
|
+
const MATCHMAKING_WAKE_GAP_MS = 2 * MATCHMAKING_POLL_MS;
|
|
92
|
+
/** The longest a failing poll loop waits between attempts. */
|
|
93
|
+
export const POLL_BACKOFF_MAX_MS = 30_000;
|
|
94
|
+
/** How often a request refused with `party-changed` (safe to retry) is sent again before the refusal is surfaced. */
|
|
95
|
+
export const PARTY_CHANGED_RETRIES = 2;
|
|
96
|
+
/** The pause before the first such retry; the second waits twice as long. */
|
|
97
|
+
export const PARTY_CHANGED_RETRY_MS = 250;
|
|
98
|
+
// The world-session scope guard answers every queue and party route with this exact, codeless 401 when the
|
|
99
|
+
// session lacks the `multiplayer` scope. No other 401 says that: an expired or missing token is a 401 too,
|
|
100
|
+
// and that one a refreshed session cures.
|
|
101
|
+
const MISSING_SCOPE_MESSAGE = 'Insufficient world scopes';
|
|
102
|
+
const TIMED_OUT = Symbol('timed out');
|
|
103
|
+
/** One namespace's way of reaching the platform: who may call, and how a refusal becomes its typed error. */
|
|
104
|
+
class PlatformLane {
|
|
105
|
+
host;
|
|
106
|
+
label;
|
|
107
|
+
guestCode;
|
|
108
|
+
refusalCodes;
|
|
109
|
+
makeError;
|
|
110
|
+
closed;
|
|
111
|
+
clock;
|
|
112
|
+
constructor(host, label, guestCode, refusalCodes, makeError,
|
|
113
|
+
// True once the world has been left: nothing may be sent again until a new session.
|
|
114
|
+
closed, clock) {
|
|
115
|
+
this.host = host;
|
|
116
|
+
this.label = label;
|
|
117
|
+
this.guestCode = guestCode;
|
|
118
|
+
this.refusalCodes = refusalCodes;
|
|
119
|
+
this.makeError = makeError;
|
|
120
|
+
this.closed = closed;
|
|
121
|
+
this.clock = clock;
|
|
122
|
+
}
|
|
123
|
+
fail(code, detail, status = null, backendCode = null, cause, body) {
|
|
124
|
+
return this.makeError(code, `${this.label}: ${detail}`, status, backendCode, cause, body);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Why a call cannot be sent right now, or null when it can. A guest is refused HERE with the code the
|
|
128
|
+
* server would answer — the server stays the authority; this only saves a request that cannot succeed.
|
|
129
|
+
*/
|
|
130
|
+
blocked() {
|
|
131
|
+
if (!this.host.isInitialized())
|
|
132
|
+
return this.fail('not-ready', 'call Helix.init() first');
|
|
133
|
+
if (this.closed())
|
|
134
|
+
return this.fail('not-ready', 'the world has been left');
|
|
135
|
+
const token = this.host.getToken();
|
|
136
|
+
if (!token)
|
|
137
|
+
return this.fail('not-ready', 'no world session');
|
|
138
|
+
if (isGuestSession(token))
|
|
139
|
+
return this.fail(this.guestCode, 'a guest session cannot do this — sign in first');
|
|
140
|
+
if (!this.host.resolveApiBase(token))
|
|
141
|
+
return this.fail('not-ready', 'could not resolve the platform API base');
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
ready() {
|
|
145
|
+
return this.blocked() === null;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* One authenticated request, bounded by PLATFORM_REQUEST_TIMEOUT_MS. Resolves the parsed JSON body (null
|
|
149
|
+
* for 204 / an empty body); rejects with this lane's typed error. The token is read fresh on every call,
|
|
150
|
+
* so a session the shell refreshed (it pushes `helix:session`; the SDK has no refresh of its own to
|
|
151
|
+
* trigger) is used by the very next request. `refine` lets a route read a refusal the way only it can.
|
|
152
|
+
*
|
|
153
|
+
* A `party-changed` refusal means the party moved under the request and nothing was done; the backend
|
|
154
|
+
* documents it as safe to retry, so it is retried here a couple of times before the caller sees it.
|
|
155
|
+
*/
|
|
156
|
+
async request(method, path, body, refine, timeoutMs = PLATFORM_REQUEST_TIMEOUT_MS) {
|
|
157
|
+
for (let attempt = 0;; attempt++) {
|
|
158
|
+
try {
|
|
159
|
+
return await this.send(method, path, body, refine, timeoutMs);
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
if (e.code !== 'party-changed' || attempt >= PARTY_CHANGED_RETRIES)
|
|
163
|
+
throw e;
|
|
164
|
+
await new Promise((resolve) => { setTimeout(resolve, PARTY_CHANGED_RETRY_MS * (attempt + 1)); });
|
|
165
|
+
if (this.blocked())
|
|
166
|
+
throw e; // the session ended or the world was left while waiting
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async send(method, path, body, refine, timeoutMs) {
|
|
171
|
+
const blocked = this.blocked();
|
|
172
|
+
if (blocked)
|
|
173
|
+
throw blocked;
|
|
174
|
+
const token = this.host.getToken();
|
|
175
|
+
const url = new URL(path, `${new URL(this.host.resolveApiBase(token)).origin}/`).toString();
|
|
176
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
177
|
+
// No body ⇒ no content-type, exactly like the default join request.
|
|
178
|
+
const init = body === undefined
|
|
179
|
+
? { method, headers: { authorization: `Bearer ${token}` } }
|
|
180
|
+
: { method, headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(body) };
|
|
181
|
+
if (controller)
|
|
182
|
+
init.signal = controller.signal;
|
|
183
|
+
// The answer is raced against the clock rather than left to the abort alone: a fetch that ignores its
|
|
184
|
+
// signal, or a body that never finishes arriving, must not be able to hang the caller either.
|
|
185
|
+
let timer;
|
|
186
|
+
const clock = new Promise((_resolve, reject) => {
|
|
187
|
+
timer = setTimeout(() => reject(TIMED_OUT), timeoutMs);
|
|
188
|
+
});
|
|
189
|
+
const exchange = (async () => {
|
|
190
|
+
const res = await fetch(url, init);
|
|
191
|
+
const receivedAt = Date.now();
|
|
192
|
+
return { res, detail: (await res.json().catch(() => null)), receivedAt };
|
|
193
|
+
})();
|
|
194
|
+
exchange.catch(() => undefined); // a late failure after the clock won is nobody's to handle
|
|
195
|
+
let res;
|
|
196
|
+
let detail;
|
|
197
|
+
let receivedAt;
|
|
198
|
+
try {
|
|
199
|
+
({ res, detail, receivedAt } = await Promise.race([exchange, clock]));
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
if (e === TIMED_OUT) {
|
|
203
|
+
try {
|
|
204
|
+
controller?.abort();
|
|
205
|
+
}
|
|
206
|
+
catch { /* nothing to abort */ }
|
|
207
|
+
throw this.fail('request-failed', `request failed — no answer within ${timeoutMs / 1000} s`, null, null, new Error('timeout'));
|
|
208
|
+
}
|
|
209
|
+
throw this.fail('request-failed', `request failed — ${e instanceof Error ? e.message : String(e)}`, null, null, e);
|
|
210
|
+
}
|
|
211
|
+
finally {
|
|
212
|
+
clearTimeout(timer);
|
|
213
|
+
}
|
|
214
|
+
// Any answer in time, accepted or refused, says what time the platform thinks it is — when the browser lets
|
|
215
|
+
// this page read the header (cross-origin, only if the API exposes `Date`).
|
|
216
|
+
try {
|
|
217
|
+
this.clock.observeHttpDate(res.headers?.get?.('date'), receivedAt);
|
|
218
|
+
}
|
|
219
|
+
catch { /* no readable headers: nothing learned */ }
|
|
220
|
+
if (res.ok)
|
|
221
|
+
return detail;
|
|
222
|
+
const backendCode = refusalCodeOf(detail);
|
|
223
|
+
const message = isRecord(detail) && typeof detail.message === 'string' && detail.message ? detail.message : `HTTP ${res.status}`;
|
|
224
|
+
const refusal = { status: res.status, backendCode, message, detail };
|
|
225
|
+
throw this.fail(this.classify(refusal, refine), `request failed — ${message}`, res.status, backendCode, undefined, detail);
|
|
226
|
+
}
|
|
227
|
+
// The backend's refusal code decides; the status alone only where it cannot mean anything else (429).
|
|
228
|
+
// A 404 with no code is NOT read as "the feature is off": "World not found" looks exactly the same.
|
|
229
|
+
classify(refusal, refine) {
|
|
230
|
+
const { backendCode, status, message } = refusal;
|
|
231
|
+
if (backendCode !== null && Object.prototype.hasOwnProperty.call(this.refusalCodes, backendCode))
|
|
232
|
+
return this.refusalCodes[backendCode];
|
|
233
|
+
if (backendCode === 'party-changed')
|
|
234
|
+
return 'party-changed';
|
|
235
|
+
if (status === 401 && backendCode === null && message === MISSING_SCOPE_MESSAGE)
|
|
236
|
+
return 'missing-permission';
|
|
237
|
+
if (status === 429)
|
|
238
|
+
return 'rate-limited';
|
|
239
|
+
return refine?.(refusal) ?? 'request-failed';
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
243
|
+
// Refusal bodies are `{ statusCode, code, message }`. `error` is read only as a courtesy to a body that
|
|
244
|
+
// carries the code there, and only when it looks like one: a framework's "Not Found" is not a refusal code.
|
|
245
|
+
function refusalCodeOf(detail) {
|
|
246
|
+
if (!isRecord(detail))
|
|
247
|
+
return null;
|
|
248
|
+
if (typeof detail.code === 'string' && detail.code.length > 0)
|
|
249
|
+
return detail.code;
|
|
250
|
+
return typeof detail.error === 'string' && /^[a-z][a-z0-9-]*$/.test(detail.error) ? detail.error : null;
|
|
251
|
+
}
|
|
252
|
+
// The world session's `guest: true` claim, read without verifying (verification is the server's job).
|
|
253
|
+
// A token that is not a decodable JWT is not known to be a guest, and the server decides.
|
|
254
|
+
function isGuestSession(token) {
|
|
255
|
+
const segment = token.split('.')[1];
|
|
256
|
+
if (!segment)
|
|
257
|
+
return false;
|
|
258
|
+
try {
|
|
259
|
+
return JSON.parse(atob(segment.replace(/-/g, '+').replace(/_/g, '/'))).guest === true;
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const text = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
|
|
266
|
+
// A count, whether the backend sent the number or the list it counted.
|
|
267
|
+
const count = (value) => Array.isArray(value) ? value.length : typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
268
|
+
// Every normalizer below builds its object in ONE fixed key order, so comparing two states by
|
|
269
|
+
// serialization is a stable deep compare no matter how the backend ordered its keys.
|
|
270
|
+
function matchOf(raw) {
|
|
271
|
+
if (!isRecord(raw))
|
|
272
|
+
return null;
|
|
273
|
+
const ticketId = text(raw.ticketId);
|
|
274
|
+
const instanceId = text(raw.instanceId);
|
|
275
|
+
const roomType = text(raw.roomType);
|
|
276
|
+
if (!ticketId || !instanceId || !roomType)
|
|
277
|
+
return null;
|
|
278
|
+
return { ticketId, instanceId, roomType, expiresAt: epochMsOf(raw.expiresAt) };
|
|
279
|
+
}
|
|
280
|
+
const SERVER_END_REASONS = new Set([
|
|
281
|
+
'cancelled', 'timeout', 'heartbeat-lapsed', 'member-absent', 'party-changed', 'build-changed', 'queue-removed', 'replaced',
|
|
282
|
+
// A matched ticket whose room ticket ran out, or whose instance closed, before the player redeemed it.
|
|
283
|
+
'match-expired',
|
|
284
|
+
]);
|
|
285
|
+
// `none` may say how the caller's ticket ended: `ended: { queueId, reason, at }`, for 60 s after it closed.
|
|
286
|
+
const endedOf = (raw) => isRecord(raw) && isRecord(raw.ended) && text(raw.ended.reason) ? raw.ended : null;
|
|
287
|
+
// What identifies one ending, so it is reported once however often the platform repeats it.
|
|
288
|
+
function endingKeyOf(raw) {
|
|
289
|
+
const ended = endedOf(raw);
|
|
290
|
+
return ended ? `${String(ended.queueId)}|${String(ended.reason)}|${String(ended.at)}` : null;
|
|
291
|
+
}
|
|
292
|
+
function queueStatusOf(raw) {
|
|
293
|
+
if (!isRecord(raw) || (raw.status !== 'waiting' && raw.status !== 'matched')) {
|
|
294
|
+
const ended = endedOf(raw);
|
|
295
|
+
if (!ended)
|
|
296
|
+
return { status: 'none' };
|
|
297
|
+
const queueId = text(ended.queueId);
|
|
298
|
+
const serverReason = ended.reason;
|
|
299
|
+
return {
|
|
300
|
+
status: 'none',
|
|
301
|
+
...(queueId ? { queueId } : {}),
|
|
302
|
+
reason: SERVER_END_REASONS.has(serverReason) ? serverReason : 'ended',
|
|
303
|
+
serverReason,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
const queueId = text(raw.queueId);
|
|
307
|
+
const status = { status: raw.status, ...(queueId ? { queueId } : {}) };
|
|
308
|
+
if (raw.status === 'waiting' && isRecord(raw.waiting)) {
|
|
309
|
+
status.waiting = { players: count(raw.waiting.players), needed: count(raw.waiting.needed) };
|
|
310
|
+
}
|
|
311
|
+
const match = raw.status === 'matched' ? matchOf(raw.match) : null;
|
|
312
|
+
if (match)
|
|
313
|
+
status.match = match;
|
|
314
|
+
return status;
|
|
315
|
+
}
|
|
316
|
+
function memberOf(raw) {
|
|
317
|
+
if (!isRecord(raw))
|
|
318
|
+
return null;
|
|
319
|
+
const userId = text(raw.userId);
|
|
320
|
+
return userId ? { userId, displayName: typeof raw.displayName === 'string' ? raw.displayName : '' } : null;
|
|
321
|
+
}
|
|
322
|
+
function partyCodeOf(raw) {
|
|
323
|
+
if (!isRecord(raw))
|
|
324
|
+
return null;
|
|
325
|
+
const code = text(raw.code);
|
|
326
|
+
return code ? { code, expiresAt: epochMsOf(raw.expiresAt) } : null;
|
|
327
|
+
}
|
|
328
|
+
function partyOf(raw) {
|
|
329
|
+
if (!isRecord(raw))
|
|
330
|
+
return null;
|
|
331
|
+
const id = text(raw.id);
|
|
332
|
+
const leaderId = text(raw.leaderId);
|
|
333
|
+
if (!id || !leaderId)
|
|
334
|
+
return null;
|
|
335
|
+
const members = (Array.isArray(raw.members) ? raw.members : []).map(memberOf).filter((m) => m !== null);
|
|
336
|
+
// `code` is `{ code, expiresAt } | null` on the wire and only the leader is given one; null is "absent".
|
|
337
|
+
const code = partyCodeOf(raw.code);
|
|
338
|
+
return { id, leaderId, maxSize: count(raw.maxSize), members, ...(code ? { code } : {}) };
|
|
339
|
+
}
|
|
340
|
+
function inviteOf(raw) {
|
|
341
|
+
if (!isRecord(raw))
|
|
342
|
+
return null;
|
|
343
|
+
const id = text(raw.id);
|
|
344
|
+
const from = memberOf(raw.from);
|
|
345
|
+
if (!id || !from)
|
|
346
|
+
return null;
|
|
347
|
+
return { id, partyId: text(raw.partyId) ?? '', from, expiresAt: epochMsOf(raw.expiresAt) };
|
|
348
|
+
}
|
|
349
|
+
function partyStateOf(raw) {
|
|
350
|
+
const body = isRecord(raw) ? raw : {};
|
|
351
|
+
return {
|
|
352
|
+
party: partyOf(body.party),
|
|
353
|
+
invites: (Array.isArray(body.invites) ? body.invites : []).map(inviteOf).filter((i) => i !== null),
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
// Listeners and callers get their own copy: a world mutating what it was handed must not rewrite the SDK's
|
|
357
|
+
// state. Not JSON — that would turn an unreadable expiry (NaN) into null.
|
|
358
|
+
const clone = (value) => (Array.isArray(value)
|
|
359
|
+
? value.map(clone)
|
|
360
|
+
: isRecord(value)
|
|
361
|
+
? Object.fromEntries(Object.entries(value).map(([key, child]) => [key, clone(child)]))
|
|
362
|
+
: value);
|
|
363
|
+
// Dispatch over a snapshot, so a listener may subscribe or unsubscribe freely — but a listener that an
|
|
364
|
+
// earlier one removed during this same dispatch is not called.
|
|
365
|
+
function dispatch(listeners, value) {
|
|
366
|
+
for (const listener of [...listeners]) {
|
|
367
|
+
if (!listeners.has(listener))
|
|
368
|
+
continue;
|
|
369
|
+
try {
|
|
370
|
+
listener(value());
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
/* one world's listener must never stop the poll, or the other listeners */
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const emit = (listeners, value) => dispatch(listeners, () => clone(value));
|
|
378
|
+
// ─────────────────────────── polling ───────────────────────────
|
|
379
|
+
// A repeating tick. With `heartbeat`, it comes from a dedicated worker when the page may create one: a
|
|
380
|
+
// hidden tab's own timers are throttled (≥ 1 s at once, once a MINUTE after about five minutes hidden),
|
|
381
|
+
// which would let a 15 s server heartbeat lapse, and a worker's timers are not. A page that cannot start
|
|
382
|
+
// the worker (no Worker, a CSP without `worker-src blob:`) falls back to an ordinary interval.
|
|
383
|
+
function startTicker(ms, onTick, heartbeat) {
|
|
384
|
+
let interval = null;
|
|
385
|
+
let worker = null;
|
|
386
|
+
let stopped = false;
|
|
387
|
+
const fallBack = () => {
|
|
388
|
+
if (worker) {
|
|
389
|
+
try {
|
|
390
|
+
worker.terminate();
|
|
391
|
+
}
|
|
392
|
+
catch { /* already gone */ }
|
|
393
|
+
worker = null;
|
|
394
|
+
}
|
|
395
|
+
if (!stopped && interval === null)
|
|
396
|
+
interval = setInterval(onTick, ms);
|
|
397
|
+
};
|
|
398
|
+
if (heartbeat && typeof Worker === 'function' && typeof Blob === 'function' && typeof URL?.createObjectURL === 'function') {
|
|
399
|
+
let url = null;
|
|
400
|
+
try {
|
|
401
|
+
url = URL.createObjectURL(new Blob([`setInterval(function(){postMessage(0)},${ms});`], { type: 'text/javascript' }));
|
|
402
|
+
worker = new Worker(url);
|
|
403
|
+
worker.onmessage = () => { if (!stopped)
|
|
404
|
+
onTick(); };
|
|
405
|
+
worker.onerror = fallBack;
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
worker = null;
|
|
409
|
+
}
|
|
410
|
+
finally {
|
|
411
|
+
// The worker has its script by now (or never will): the URL is released either way.
|
|
412
|
+
if (url !== null) {
|
|
413
|
+
try {
|
|
414
|
+
URL.revokeObjectURL?.(url);
|
|
415
|
+
}
|
|
416
|
+
catch { /* nothing to release */ }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (!worker)
|
|
421
|
+
fallBack();
|
|
422
|
+
return () => {
|
|
423
|
+
stopped = true;
|
|
424
|
+
if (interval !== null)
|
|
425
|
+
clearInterval(interval);
|
|
426
|
+
interval = null;
|
|
427
|
+
if (worker) {
|
|
428
|
+
try {
|
|
429
|
+
worker.terminate();
|
|
430
|
+
}
|
|
431
|
+
catch { /* already gone */ }
|
|
432
|
+
worker = null;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
// `pagehide` puts the whole PAGE to sleep, not one loop: until `pageshow`, no loop may start a ticker or send
|
|
437
|
+
// a poll — including a loop that is started (or restarted) by an answer that arrives on the unloading page.
|
|
438
|
+
// So the flag is module-level. It is set by whichever loop hears `pagehide`, and cleared on `pageshow` by a
|
|
439
|
+
// listener that exists only while the page is asleep (a page that never polls adds no listener at all).
|
|
440
|
+
let pageAsleep = false;
|
|
441
|
+
const pageShown = () => {
|
|
442
|
+
pageAsleep = false;
|
|
443
|
+
if (typeof window !== 'undefined')
|
|
444
|
+
window.removeEventListener('pageshow', pageShown);
|
|
445
|
+
};
|
|
446
|
+
const pageHidden = () => {
|
|
447
|
+
if (pageAsleep)
|
|
448
|
+
return;
|
|
449
|
+
pageAsleep = true;
|
|
450
|
+
if (typeof window !== 'undefined')
|
|
451
|
+
window.addEventListener('pageshow', pageShown);
|
|
452
|
+
};
|
|
453
|
+
/**
|
|
454
|
+
* One poll loop and the page events around it. `start` is idempotent. While started: `poll(false)` every
|
|
455
|
+
* `intervalMs`, and `poll(true)` at once when the tab changes visibility, the page is restored, or the
|
|
456
|
+
* network returns (a throttled or frozen tab may be long overdue). On `pagehide` the loop goes to sleep —
|
|
457
|
+
* a page being torn down holds no timer and starts nothing — and ONLY `pageshow` (a page restored from the
|
|
458
|
+
* back/forward cache) wakes it. `stop` removes everything.
|
|
459
|
+
*/
|
|
460
|
+
class Poller {
|
|
461
|
+
intervalMs;
|
|
462
|
+
heartbeat;
|
|
463
|
+
poll;
|
|
464
|
+
stopTicker = null;
|
|
465
|
+
listening = false;
|
|
466
|
+
constructor(intervalMs, heartbeat, poll) {
|
|
467
|
+
this.intervalMs = intervalMs;
|
|
468
|
+
this.heartbeat = heartbeat;
|
|
469
|
+
this.poll = poll;
|
|
470
|
+
}
|
|
471
|
+
get active() {
|
|
472
|
+
return this.listening;
|
|
473
|
+
}
|
|
474
|
+
start() {
|
|
475
|
+
if (!this.listening) {
|
|
476
|
+
this.listening = true;
|
|
477
|
+
if (typeof document !== 'undefined')
|
|
478
|
+
document.addEventListener('visibilitychange', this.wake);
|
|
479
|
+
if (typeof window !== 'undefined') {
|
|
480
|
+
window.addEventListener('pageshow', this.wake);
|
|
481
|
+
window.addEventListener('online', this.wake);
|
|
482
|
+
window.addEventListener('pagehide', this.sleep);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
// On a page that is asleep the loop is armed (it hears `pageshow`) but does not tick.
|
|
486
|
+
if (!pageAsleep)
|
|
487
|
+
this.stopTicker ??= startTicker(this.intervalMs, this.tick, this.heartbeat);
|
|
488
|
+
}
|
|
489
|
+
stop() {
|
|
490
|
+
this.stopTicker?.();
|
|
491
|
+
this.stopTicker = null;
|
|
492
|
+
if (!this.listening)
|
|
493
|
+
return;
|
|
494
|
+
this.listening = false;
|
|
495
|
+
if (typeof document !== 'undefined')
|
|
496
|
+
document.removeEventListener('visibilitychange', this.wake);
|
|
497
|
+
if (typeof window !== 'undefined') {
|
|
498
|
+
window.removeEventListener('pageshow', this.wake);
|
|
499
|
+
window.removeEventListener('online', this.wake);
|
|
500
|
+
window.removeEventListener('pagehide', this.sleep);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
tick = () => {
|
|
504
|
+
this.poll(false);
|
|
505
|
+
};
|
|
506
|
+
wake = (event) => {
|
|
507
|
+
if (!this.listening)
|
|
508
|
+
return;
|
|
509
|
+
if (event.type === 'pageshow')
|
|
510
|
+
pageShown();
|
|
511
|
+
if (pageAsleep)
|
|
512
|
+
return;
|
|
513
|
+
this.stopTicker ??= startTicker(this.intervalMs, this.tick, this.heartbeat);
|
|
514
|
+
this.poll(true);
|
|
515
|
+
};
|
|
516
|
+
sleep = () => {
|
|
517
|
+
pageHidden();
|
|
518
|
+
this.stopTicker?.();
|
|
519
|
+
this.stopTicker = null;
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
// Consecutive poll failures, and how long to hold off because of them. The first failure costs nothing
|
|
523
|
+
// (the next tick tries again); after that the gap grows 1×, 3×, 7×… the poll interval, up to the cap.
|
|
524
|
+
class Backoff {
|
|
525
|
+
intervalMs;
|
|
526
|
+
failures = 0;
|
|
527
|
+
notBefore = 0;
|
|
528
|
+
constructor(intervalMs) {
|
|
529
|
+
this.intervalMs = intervalMs;
|
|
530
|
+
}
|
|
531
|
+
ok() {
|
|
532
|
+
this.failures = 0;
|
|
533
|
+
this.notBefore = 0;
|
|
534
|
+
}
|
|
535
|
+
fail() {
|
|
536
|
+
this.failures++;
|
|
537
|
+
this.notBefore = Date.now() + Math.min(this.intervalMs * (2 ** (this.failures - 1) - 1), POLL_BACKOFF_MAX_MS);
|
|
538
|
+
}
|
|
539
|
+
get holding() {
|
|
540
|
+
return Date.now() < this.notBefore;
|
|
541
|
+
}
|
|
542
|
+
get failing() {
|
|
543
|
+
return this.failures > 0;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// A failure that says nothing about whether the request took effect: no answer at all, or a 5xx.
|
|
547
|
+
const isAmbiguous = (e) => {
|
|
548
|
+
const { code, status } = (e ?? {});
|
|
549
|
+
return code === 'request-failed' && (status === null || (typeof status === 'number' && status >= 500));
|
|
550
|
+
};
|
|
551
|
+
// What stops the party poll: the platform's own answer that parties cannot work for this world or session.
|
|
552
|
+
const isFinalPartyRefusal = (e) => {
|
|
553
|
+
if (!(e instanceof HelixPartyError))
|
|
554
|
+
return false;
|
|
555
|
+
return e.code === 'unavailable' || e.code === 'missing-permission' || e.code === 'guests-cannot-party';
|
|
556
|
+
};
|
|
557
|
+
// A refusal that will not change by asking again.
|
|
558
|
+
const isFinalRefusal = (e) => {
|
|
559
|
+
const code = e?.code;
|
|
560
|
+
return code === 'unavailable' || code === 'missing-permission' || code === 'not-ready'
|
|
561
|
+
|| code === 'guests-cannot-queue' || code === 'guests-cannot-party';
|
|
562
|
+
};
|
|
563
|
+
// ─────────────────────────── matchmaking ───────────────────────────
|
|
564
|
+
const MATCHMAKING_REFUSALS = {
|
|
565
|
+
'unknown-queue': 'unknown-queue',
|
|
566
|
+
'already-queued': 'already-queued',
|
|
567
|
+
'already-matched': 'already-matched',
|
|
568
|
+
'not-party-leader': 'not-party-leader',
|
|
569
|
+
'party-too-large': 'party-too-large',
|
|
570
|
+
'party-changed': 'party-changed',
|
|
571
|
+
'guests-cannot-queue': 'guests-cannot-queue',
|
|
572
|
+
'queue-rate-limit': 'rate-limited',
|
|
573
|
+
// Flag off (MATCHMAKING_ENABLED). The queue routes never answer `room-types-disabled`: that code belongs
|
|
574
|
+
// to the room-instance routes.
|
|
575
|
+
'matchmaking-disabled': 'unavailable',
|
|
576
|
+
};
|
|
577
|
+
const NOT_QUEUED = { status: 'none' };
|
|
578
|
+
export class HelixMatchmaking {
|
|
579
|
+
host;
|
|
580
|
+
party;
|
|
581
|
+
lane;
|
|
582
|
+
poller = new Poller(MATCHMAKING_POLL_MS, true, (urgent) => void this.poll(urgent));
|
|
583
|
+
// The backend counts a heartbeat PER PARTY MEMBER: a ticket is only matchable while every member has
|
|
584
|
+
// polled within 15 s, and only the leader enqueues. So a member with no ticket of their own looks for the
|
|
585
|
+
// leader's — this slower loop, which runs only for a player in a party of two or more whose world listens
|
|
586
|
+
// to matchmaking — and from the moment it finds one the heartbeat loop above takes over.
|
|
587
|
+
idle = new Poller(MATCHMAKING_IDLE_POLL_MS, false, (urgent) => void this.poll(urgent));
|
|
588
|
+
partyMembers = 0;
|
|
589
|
+
partyWatch = null;
|
|
590
|
+
// One ending is reported once. The platform repeats how a ticket ended for 60 s; this is the last such
|
|
591
|
+
// ending seen, and whether this page already told its listeners the queue was over by itself (its own
|
|
592
|
+
// cancel, a lost heartbeat, a transition it watched).
|
|
593
|
+
reportedEnding = null;
|
|
594
|
+
endedLocally = false;
|
|
595
|
+
// The platform refused the status route for good (feature off, no permission, guest): stop looking.
|
|
596
|
+
refused = false;
|
|
597
|
+
backoff = new Backoff(MATCHMAKING_POLL_MS);
|
|
598
|
+
statusListeners = new Set();
|
|
599
|
+
matchListeners = new Set();
|
|
600
|
+
last = NOT_QUEUED;
|
|
601
|
+
// Bumped by everything that changes what the truth is: when an enqueue / cancel STARTS, again when its
|
|
602
|
+
// result is applied (see `commit`), when the queue ends, on teardown. An answer asked for under an older
|
|
603
|
+
// generation is never applied: a slow poll must not resurrect a cancelled ticket, a GET the server answered
|
|
604
|
+
// before the POST committed must not stop the new ticket's heartbeat, and a late answer must not restart a
|
|
605
|
+
// heartbeat after the world was left.
|
|
606
|
+
generation = 0;
|
|
607
|
+
// The poll in flight, and the generation it was asked under. A poll only waits for a poll of its OWN
|
|
608
|
+
// generation, so a hung poll of a cancelled ticket cannot hold up the heartbeat of the next one. Dropped
|
|
609
|
+
// (not awaited, not counted) when the page wakes from a sleep: see woke().
|
|
610
|
+
flight = null;
|
|
611
|
+
// When the platform last answered about the ticket: what the 15 s heartbeat is measured from.
|
|
612
|
+
lastAnswerAt = 0;
|
|
613
|
+
// When this loop last ran (a tick, a wake event, a poll's failure, an answer), and when it last found it
|
|
614
|
+
// had not run for MATCHMAKING_WAKE_GAP_MS: the page was asleep until then.
|
|
615
|
+
lastRanAt = 0;
|
|
616
|
+
wokeAt = 0;
|
|
617
|
+
// Since the last answer: the page woke from a sleep; whether a poll has been sent since the latest wake;
|
|
618
|
+
// and how many EARLIER wakes sent a poll that was never answered. Null until a wake, cleared by every
|
|
619
|
+
// answer. It is what tells a page that keeps waking into silence from one that slept once: see woke().
|
|
620
|
+
wake = null;
|
|
621
|
+
// Requests of this namespace in flight; while there are any, `pagehide` is listened for (see request()).
|
|
622
|
+
requests = 0;
|
|
623
|
+
// Whether the backend has been asked what this player's ticket is. False on a fresh page, so the first
|
|
624
|
+
// use finds a ticket that outlived a reload.
|
|
625
|
+
resumed = false;
|
|
626
|
+
left = false;
|
|
627
|
+
// enqueue / cancel run one at a time, each seeing the previous one's outcome.
|
|
628
|
+
mutations = Promise.resolve();
|
|
629
|
+
seenMatches = new Set();
|
|
630
|
+
undelivered = null;
|
|
631
|
+
// The platform's clock: what a match's `expiresAt` is judged against (never the device clock alone).
|
|
632
|
+
clock;
|
|
633
|
+
constructor(host, party = null) {
|
|
634
|
+
this.host = host;
|
|
635
|
+
this.party = party;
|
|
636
|
+
this.clock = clockOf(host);
|
|
637
|
+
this.lane = new PlatformLane(host, 'Helix.matchmaking', 'guests-cannot-queue', MATCHMAKING_REFUSALS, (code, message, status, backendCode, cause, detail) => new HelixMatchmakingError(code, message, status, backendCode, cause, code === 'already-matched' && isRecord(detail) ? matchOf(detail.match) : null, code === 'already-matched' && isRecord(detail) ? text(detail.memberUserId) : null), () => this.left, this.clock);
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Join one of the world's declared queues (manifest `matchmaking.queues`). In a party, only the leader
|
|
641
|
+
* queues, and the whole party is queued together. Resolves `{ status: 'waiting', queueId, waiting? }` and
|
|
642
|
+
* starts the 3 s poll that keeps the ticket alive and drives `onStatus` / `onMatch`. Calls to `enqueue`
|
|
643
|
+
* and `cancel` are carried out one at a time, in the order they were made. While a match still stands
|
|
644
|
+
* unredeemed it rejects with `already-matched` (`error.match`), the status is `matched` and `onMatch`
|
|
645
|
+
* fires if that match was not delivered yet.
|
|
646
|
+
*/
|
|
647
|
+
enqueue(queueId) {
|
|
648
|
+
return this.exclusive(async () => {
|
|
649
|
+
if (typeof queueId !== 'string' || queueId.length === 0)
|
|
650
|
+
throw this.lane.fail('invalid-argument', 'enqueue needs a queue id');
|
|
651
|
+
const path = `${this.queuesPath()}/${encodeURIComponent(queueId)}/tickets`;
|
|
652
|
+
this.resumed = true;
|
|
653
|
+
const generation = ++this.generation;
|
|
654
|
+
let body;
|
|
655
|
+
try {
|
|
656
|
+
body = await this.request('POST', path);
|
|
657
|
+
}
|
|
658
|
+
catch (e) {
|
|
659
|
+
if (generation === this.generation) {
|
|
660
|
+
const code = e.code;
|
|
661
|
+
const match = e instanceof HelixMatchmakingError && code === 'already-matched' ? e.match : null;
|
|
662
|
+
if (match) {
|
|
663
|
+
// A match from the matcher still stands unredeemed (this player's, or a party member's): it is
|
|
664
|
+
// surfaced exactly as a late cancel() surfaces it, never queued over.
|
|
665
|
+
this.commit({ status: 'matched', queueId, match });
|
|
666
|
+
}
|
|
667
|
+
else if (code === 'already-queued' || code === 'already-matched' || isAmbiguous(e)) {
|
|
668
|
+
// A ticket already exists (queued from another tab, or before a reload) — or MAY exist: a POST
|
|
669
|
+
// that timed out, lost its connection or met a 5xx can have created the ticket all the same, and
|
|
670
|
+
// a ticket nobody heartbeats is a ticket that lapses. Ask, and pick its heartbeat up if it is there.
|
|
671
|
+
await this.refresh().catch(() => undefined);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
throw e;
|
|
675
|
+
}
|
|
676
|
+
const answered = queueStatusOf({ ...(isRecord(body) ? body : {}), status: 'waiting' });
|
|
677
|
+
const status = { ...answered, queueId: answered.queueId ?? queueId };
|
|
678
|
+
if (generation === this.generation)
|
|
679
|
+
this.commit(status);
|
|
680
|
+
return clone(status);
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Leave the queue. Idempotent: resolves whether a waiting ticket was cancelled or there was none. A party
|
|
685
|
+
* member cancelling cancels the whole party's ticket. If the ticket has ALREADY MATCHED it rejects with
|
|
686
|
+
* `already-matched` (`error.match` is the match), the status is `matched`, and `onMatch` fires — a match
|
|
687
|
+
* is never reported as `none`. If the request got no usable answer, the SDK asks the platform what
|
|
688
|
+
* happened before rejecting, so a match that formed meanwhile is still delivered.
|
|
689
|
+
*/
|
|
690
|
+
cancel() {
|
|
691
|
+
return this.exclusive(async () => {
|
|
692
|
+
const path = `${this.queuesPath()}/tickets/current`;
|
|
693
|
+
this.resumed = true;
|
|
694
|
+
const generation = ++this.generation;
|
|
695
|
+
try {
|
|
696
|
+
await this.request('DELETE', path);
|
|
697
|
+
}
|
|
698
|
+
catch (e) {
|
|
699
|
+
if (generation === this.generation) {
|
|
700
|
+
const match = e instanceof HelixMatchmakingError && e.code === 'already-matched' ? e.match : null;
|
|
701
|
+
if (match) {
|
|
702
|
+
const queueId = this.last.queueId;
|
|
703
|
+
this.commit({ status: 'matched', ...(queueId ? { queueId } : {}), match });
|
|
704
|
+
}
|
|
705
|
+
else if (!isFinalRefusal(e)) {
|
|
706
|
+
await this.refresh().catch(() => undefined);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
throw e;
|
|
710
|
+
}
|
|
711
|
+
if (generation === this.generation)
|
|
712
|
+
this.commit(NOT_QUEUED);
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Ask the platform where this player stands now. What it finds is treated exactly like a poll's answer:
|
|
717
|
+
* `onStatus` / `onMatch` fire if it is news, and polling starts or stops to match.
|
|
718
|
+
*/
|
|
719
|
+
async status() {
|
|
720
|
+
this.resumed = true;
|
|
721
|
+
try {
|
|
722
|
+
// An answer that an enqueue / cancel outdated while it was on its way is not handed to the caller:
|
|
723
|
+
// ask again (bounded — each retry needs yet another mutation to have landed in between).
|
|
724
|
+
for (let attempt = 0;; attempt++) {
|
|
725
|
+
const generation = this.generation;
|
|
726
|
+
const status = await this.refresh();
|
|
727
|
+
if (generation === this.generation || attempt >= 2)
|
|
728
|
+
return clone(status);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
catch (e) {
|
|
732
|
+
if (!isFinalRefusal(e))
|
|
733
|
+
this.resumed = false;
|
|
734
|
+
throw e;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Called whenever the queue status CHANGES (waiting counts, matched, back to none) — not once per poll.
|
|
739
|
+
* A `none` the SDK concluded by itself carries a `reason` (see QueueEndReason). Subscribing also checks,
|
|
740
|
+
* once per session, whether a ticket from before a reload is still alive.
|
|
741
|
+
*/
|
|
742
|
+
onStatus(cb) {
|
|
743
|
+
this.statusListeners.add(cb);
|
|
744
|
+
this.subscribed();
|
|
745
|
+
return () => {
|
|
746
|
+
this.statusListeners.delete(cb);
|
|
747
|
+
this.unsubscribed();
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Called exactly once per match (per room `ticketId`), however it was discovered: a poll, an explicit
|
|
752
|
+
* `status()`, a `cancel()` that came too late, or the first check after a reload. A match found while
|
|
753
|
+
* nobody was listening is handed to the first subscriber, unless it has expired or the status has since
|
|
754
|
+
* gone back to `none`. Redeem it with `Helix.multiplayer.switchRoom({ ticket: match.ticketId })`.
|
|
755
|
+
* Expiry is judged by the platform's clock (learned from a joined room's state and, where the browser
|
|
756
|
+
* exposes it, the `Date` header of platform answers), and by the device clock only when nothing is known.
|
|
757
|
+
*/
|
|
758
|
+
onMatch(cb) {
|
|
759
|
+
this.matchListeners.add(cb);
|
|
760
|
+
if (this.undelivered) {
|
|
761
|
+
void Promise.resolve().then(() => {
|
|
762
|
+
const held = this.undelivered;
|
|
763
|
+
if (!held || !this.matchListeners.has(cb))
|
|
764
|
+
return;
|
|
765
|
+
this.undelivered = null;
|
|
766
|
+
if (!this.clock.hasPassed(held.expiresAt))
|
|
767
|
+
emit(new Set([cb]), held);
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
this.subscribed();
|
|
771
|
+
return () => {
|
|
772
|
+
this.matchListeners.delete(cb);
|
|
773
|
+
this.unsubscribed();
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
/** @internal Helix.init() resolved: a world that subscribed before then is served now. */
|
|
777
|
+
ready() {
|
|
778
|
+
if (this.listeners === 0)
|
|
779
|
+
return;
|
|
780
|
+
this.resume();
|
|
781
|
+
this.syncIdle();
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* @internal helix:leave. Subscribers are told the queue is over (`reason: 'left'` — the ticket lapses with
|
|
785
|
+
* the heartbeat), every timer and listener stops, and nothing is sent again until a new session.
|
|
786
|
+
*/
|
|
787
|
+
teardown() {
|
|
788
|
+
this.end('left');
|
|
789
|
+
this.left = true;
|
|
790
|
+
this.idle.stop();
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* @internal The session ended or changed hands: nothing known about the old one applies. Subscribers are
|
|
794
|
+
* told (`reason: 'session-changed'`), and if there is a new session and someone is subscribed, its ticket
|
|
795
|
+
* is looked up.
|
|
796
|
+
*/
|
|
797
|
+
reset() {
|
|
798
|
+
// The old player's party is not this session's either; its size arrives again with the next party answer.
|
|
799
|
+
this.partyMembers = 0;
|
|
800
|
+
this.end('session-changed');
|
|
801
|
+
this.left = false;
|
|
802
|
+
this.refused = false;
|
|
803
|
+
this.reportedEnding = null;
|
|
804
|
+
this.endedLocally = false;
|
|
805
|
+
this.resumed = false;
|
|
806
|
+
this.seenMatches.clear();
|
|
807
|
+
this.ready();
|
|
808
|
+
}
|
|
809
|
+
get listeners() {
|
|
810
|
+
return this.statusListeners.size + this.matchListeners.size;
|
|
811
|
+
}
|
|
812
|
+
// A world listening to matchmaking is a world that can be matched. From the first listener the party's
|
|
813
|
+
// size is watched (which keeps the party poll alive, with or without a Helix.party subscriber), so a
|
|
814
|
+
// party member finds the ticket its leader queued.
|
|
815
|
+
subscribed() {
|
|
816
|
+
if (!this.partyWatch && this.party) {
|
|
817
|
+
this.partyWatch = this.party.watch((members) => {
|
|
818
|
+
this.partyMembers = members;
|
|
819
|
+
this.syncIdle();
|
|
820
|
+
},
|
|
821
|
+
// A waiting ticket may be a party's: keep knowing the party's size even in a hidden tab.
|
|
822
|
+
() => this.last.status === 'waiting');
|
|
823
|
+
}
|
|
824
|
+
this.resume();
|
|
825
|
+
this.syncIdle();
|
|
826
|
+
}
|
|
827
|
+
unsubscribed() {
|
|
828
|
+
if (this.listeners === 0) {
|
|
829
|
+
this.partyWatch?.stop();
|
|
830
|
+
this.partyWatch = null;
|
|
831
|
+
this.partyMembers = 0;
|
|
832
|
+
}
|
|
833
|
+
this.syncIdle();
|
|
834
|
+
}
|
|
835
|
+
// Look for the leader's ticket only while it can exist and someone wants to know: a party of two or more,
|
|
836
|
+
// no ticket known, a listener, a usable session. A solo player never runs this loop.
|
|
837
|
+
syncIdle() {
|
|
838
|
+
this.partyWatch?.update();
|
|
839
|
+
const wanted = this.listeners > 0 && this.partyMembers >= 2 && this.last.status === 'none'
|
|
840
|
+
&& !this.left && !this.refused && this.lane.ready() && this.host.getWorldId() !== null;
|
|
841
|
+
if (!wanted) {
|
|
842
|
+
this.idle.stop();
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
if (this.idle.active)
|
|
846
|
+
return;
|
|
847
|
+
this.idle.start();
|
|
848
|
+
void this.poll(true);
|
|
849
|
+
}
|
|
850
|
+
// Every request of this namespace. While one is in flight the page's `pagehide` is listened for, whether or
|
|
851
|
+
// not a poll loop is running yet: the answer to an enqueue (or to the first status look-up) is what STARTS
|
|
852
|
+
// the heartbeat, and on a page that began unloading meanwhile it must start nothing until `pageshow`. The
|
|
853
|
+
// loops listen for themselves once started; this covers the moment before. No request, no listener.
|
|
854
|
+
async request(method, path, timeoutMs = PLATFORM_REQUEST_TIMEOUT_MS) {
|
|
855
|
+
if (this.requests++ === 0 && typeof window !== 'undefined')
|
|
856
|
+
window.addEventListener('pagehide', pageHidden);
|
|
857
|
+
try {
|
|
858
|
+
return await this.lane.request(method, path, undefined, undefined, timeoutMs);
|
|
859
|
+
}
|
|
860
|
+
finally {
|
|
861
|
+
if (--this.requests === 0 && typeof window !== 'undefined')
|
|
862
|
+
window.removeEventListener('pagehide', pageHidden);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
exclusive(action) {
|
|
866
|
+
const run = this.mutations.then(action, action);
|
|
867
|
+
this.mutations = run.catch(() => undefined);
|
|
868
|
+
return run;
|
|
869
|
+
}
|
|
870
|
+
queuesPath() {
|
|
871
|
+
const blocked = this.lane.blocked();
|
|
872
|
+
if (blocked)
|
|
873
|
+
throw blocked;
|
|
874
|
+
const worldId = this.host.getWorldId();
|
|
875
|
+
if (!worldId)
|
|
876
|
+
throw this.lane.fail('not-ready', 'no world id');
|
|
877
|
+
return `/api/v1/instant-worlds/${encodeURIComponent(worldId)}/queues`;
|
|
878
|
+
}
|
|
879
|
+
// The result of an enqueue / cancel. It outdates every answer asked for before this moment, including a
|
|
880
|
+
// GET that was sent after the call started but that the server answered before the mutation committed.
|
|
881
|
+
commit(status) {
|
|
882
|
+
this.generation++;
|
|
883
|
+
this.apply(status);
|
|
884
|
+
}
|
|
885
|
+
async refresh(timeoutMs = PLATFORM_REQUEST_TIMEOUT_MS) {
|
|
886
|
+
const path = `${this.queuesPath()}/tickets/current`;
|
|
887
|
+
const generation = this.generation;
|
|
888
|
+
const body = await this.request('GET', path, timeoutMs);
|
|
889
|
+
const status = queueStatusOf(body);
|
|
890
|
+
if (generation === this.generation) {
|
|
891
|
+
this.apply(status, endingKeyOf(body));
|
|
892
|
+
}
|
|
893
|
+
else if (status.match && !this.seenMatches.has(status.match.ticketId)) {
|
|
894
|
+
// Out of date, so not applied — but it says there is a match nobody has been told about, and a match
|
|
895
|
+
// is never dropped on the strength of a stale answer. Ask again under the current generation.
|
|
896
|
+
void this.refresh().catch(() => undefined);
|
|
897
|
+
}
|
|
898
|
+
return status;
|
|
899
|
+
}
|
|
900
|
+
// First use for this session: a ticket may have outlived a reload. Silent — a world subscribing to events
|
|
901
|
+
// has asked for nothing that can fail — and retried on the next use if the question got no answer.
|
|
902
|
+
resume() {
|
|
903
|
+
if (this.resumed || !this.lane.ready() || !this.host.getWorldId())
|
|
904
|
+
return;
|
|
905
|
+
this.resumed = true;
|
|
906
|
+
void this.refresh().catch((e) => {
|
|
907
|
+
if (!isFinalRefusal(e))
|
|
908
|
+
this.resumed = false;
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
// Has the page just come back from a sleep? `heartbeat-lost` means "polls were sent for 15 s and none got
|
|
912
|
+
// through". A page that was not running sent none, so the time it was away proves nothing about the ticket:
|
|
913
|
+
// only the platform knows whether it survived. On waking, therefore, everything from before the sleep is
|
|
914
|
+
// set aside — the poll that was in flight then (its failure is not counted, and it is not waited for), and
|
|
915
|
+
// the failures already counted — and the 15 s are measured from now. The next poll goes out at once, its
|
|
916
|
+
// answer is believed, and `heartbeat-lost` is concluded only if nothing gets through for 15 s AWAKE.
|
|
917
|
+
//
|
|
918
|
+
// ONE SLEEP EXCUSES ONE SILENCE, NOT EVERY ONE. A loop that runs less often than the wake gap — a hidden
|
|
919
|
+
// tab with no worker, its timers throttled to once a minute — "wakes" on every run. If each of those wakes
|
|
920
|
+
// restarted the 15 s, a page that is offline as well would never conclude anything: each run sends one
|
|
921
|
+
// poll, it fails, and the next run forgives it. So a wake restarts the clock only when the wake before it
|
|
922
|
+
// was not already followed by a poll that got no answer. When it was, the 15 s keep running from the FIRST
|
|
923
|
+
// wake of the run of unanswered ones; this wake still sends its poll and still believes an answer (the
|
|
924
|
+
// backoff and the poll in flight are set aside as on any wake), but if that poll fails too the ticket is
|
|
925
|
+
// gone — and if it never even comes back, the wake after it concludes so (see poll()).
|
|
926
|
+
woke() {
|
|
927
|
+
const now = Date.now();
|
|
928
|
+
const slept = now - this.lastRanAt >= MATCHMAKING_WAKE_GAP_MS;
|
|
929
|
+
this.lastRanAt = now;
|
|
930
|
+
if (slept) {
|
|
931
|
+
const unanswered = (this.wake?.unanswered ?? 0) + (this.wake?.asked ? 1 : 0);
|
|
932
|
+
if (unanswered === 0)
|
|
933
|
+
this.wokeAt = now;
|
|
934
|
+
this.wake = { asked: false, unanswered };
|
|
935
|
+
this.flight = null;
|
|
936
|
+
this.backoff.ok();
|
|
937
|
+
}
|
|
938
|
+
return slept;
|
|
939
|
+
}
|
|
940
|
+
// The server's limit has passed with this page awake and no answer.
|
|
941
|
+
lapsed() {
|
|
942
|
+
return this.last.status === 'waiting'
|
|
943
|
+
&& Date.now() - Math.max(this.lastAnswerAt, this.wokeAt) >= MATCHMAKING_HEARTBEAT_LOST_MS;
|
|
944
|
+
}
|
|
945
|
+
// Two wakes in a row each sent a poll and neither was answered (the second may still be hanging: a poll
|
|
946
|
+
// older than the wake gap is past its own 5 s timeout, whether or not that timer has been allowed to run).
|
|
947
|
+
wokeIntoSilence() {
|
|
948
|
+
return (this.wake?.unanswered ?? 0) >= 2;
|
|
949
|
+
}
|
|
950
|
+
async poll(urgent) {
|
|
951
|
+
if (pageAsleep)
|
|
952
|
+
return;
|
|
953
|
+
this.woke();
|
|
954
|
+
const generation = this.generation;
|
|
955
|
+
const inFlight = this.flight?.generation === generation;
|
|
956
|
+
// The server's limit has passed and the polls since the last answer failed, or one is still hanging:
|
|
957
|
+
// nothing got through, so the ticket is gone. Concluded HERE, on the tick, rather than after yet another
|
|
958
|
+
// request has had time to fail — that is what made the conclusion land at 20 s instead of 15.
|
|
959
|
+
// Likewise when the page keeps waking into silence: there is no failure count or poll in flight to go by
|
|
960
|
+
// (each wake sets them aside), only the wakes themselves.
|
|
961
|
+
if (this.lapsed() && (this.backoff.failing || inFlight || this.wokeIntoSilence())) {
|
|
962
|
+
this.end('heartbeat-lost');
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
if (inFlight)
|
|
966
|
+
return;
|
|
967
|
+
// The poll goes out regardless of backoff for a match whose room ticket has run out (one last look, then
|
|
968
|
+
// stop). A page that slept needs no exception here: waking cleared the backoff.
|
|
969
|
+
const matchOver = this.last.status === 'matched' && this.last.match !== undefined && this.clock.hasPassed(this.last.match.expiresAt);
|
|
970
|
+
if (!urgent && !matchOver && this.backoff.holding)
|
|
971
|
+
return;
|
|
972
|
+
const flight = { generation };
|
|
973
|
+
this.flight = flight;
|
|
974
|
+
if (this.wake)
|
|
975
|
+
this.wake.asked = true;
|
|
976
|
+
try {
|
|
977
|
+
await this.refresh(MATCHMAKING_POLL_TIMEOUT_MS);
|
|
978
|
+
if (matchOver && generation === this.generation && this.last.status === 'matched')
|
|
979
|
+
this.end('match-expired');
|
|
980
|
+
}
|
|
981
|
+
catch (e) {
|
|
982
|
+
if (generation !== this.generation)
|
|
983
|
+
return;
|
|
984
|
+
// No answer, a 5xx, a 429, a 401 while the shell refreshes the session: none of it says the ticket is
|
|
985
|
+
// gone, so the heartbeat continues, backing off. Nothing getting through for 15 s does say so.
|
|
986
|
+
if (isFinalRefusal(e)) {
|
|
987
|
+
this.refused = true;
|
|
988
|
+
this.end('refused');
|
|
989
|
+
}
|
|
990
|
+
else if (matchOver)
|
|
991
|
+
this.end('match-expired');
|
|
992
|
+
// Asked before the page slept (the sleep is noticed here when this failure is the first thing to run
|
|
993
|
+
// after it): it says nothing about now, and the poll sent on waking is the one that counts.
|
|
994
|
+
else if (this.woke() || this.flight !== flight)
|
|
995
|
+
return;
|
|
996
|
+
else if (this.lapsed())
|
|
997
|
+
this.end('heartbeat-lost');
|
|
998
|
+
else
|
|
999
|
+
this.backoff.fail();
|
|
1000
|
+
}
|
|
1001
|
+
finally {
|
|
1002
|
+
if (this.flight === flight)
|
|
1003
|
+
this.flight = null;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
// The platform's answer about the ticket. `ending` identifies the ending a `none` describes, if it does.
|
|
1007
|
+
apply(next, ending = null) {
|
|
1008
|
+
if (this.left)
|
|
1009
|
+
return;
|
|
1010
|
+
this.lastAnswerAt = this.lastRanAt = Date.now();
|
|
1011
|
+
this.backoff.ok();
|
|
1012
|
+
this.wake = null;
|
|
1013
|
+
let changed;
|
|
1014
|
+
if (next.status === 'none') {
|
|
1015
|
+
// News when a ticket this page knew of is gone, or when the platform describes an ending this page
|
|
1016
|
+
// has neither seen nor concluded by itself (a reload, a ticket that closed while the tab slept).
|
|
1017
|
+
const wasQueued = this.last.status !== 'none';
|
|
1018
|
+
changed = wasQueued || (ending !== null && ending !== this.reportedEnding && !this.endedLocally);
|
|
1019
|
+
if (ending !== null)
|
|
1020
|
+
this.reportedEnding = ending;
|
|
1021
|
+
if (wasQueued)
|
|
1022
|
+
this.endedLocally = true;
|
|
1023
|
+
}
|
|
1024
|
+
else {
|
|
1025
|
+
changed = JSON.stringify(next) !== JSON.stringify(this.last);
|
|
1026
|
+
this.endedLocally = false;
|
|
1027
|
+
}
|
|
1028
|
+
// What is remembered for `none` is plain "not queued": the reason belongs to the one report.
|
|
1029
|
+
this.last = next.status === 'none' ? NOT_QUEUED : next;
|
|
1030
|
+
if (next.status === 'none') {
|
|
1031
|
+
this.poller.stop();
|
|
1032
|
+
this.undelivered = null;
|
|
1033
|
+
}
|
|
1034
|
+
else {
|
|
1035
|
+
this.poller.start();
|
|
1036
|
+
}
|
|
1037
|
+
this.syncIdle();
|
|
1038
|
+
if (changed)
|
|
1039
|
+
emit(this.statusListeners, next);
|
|
1040
|
+
const match = next.match;
|
|
1041
|
+
if (!match || this.seenMatches.has(match.ticketId))
|
|
1042
|
+
return;
|
|
1043
|
+
this.seenMatches.add(match.ticketId);
|
|
1044
|
+
if (this.clock.hasPassed(match.expiresAt))
|
|
1045
|
+
return;
|
|
1046
|
+
if (this.matchListeners.size > 0)
|
|
1047
|
+
emit(this.matchListeners, match);
|
|
1048
|
+
else
|
|
1049
|
+
this.undelivered = match;
|
|
1050
|
+
}
|
|
1051
|
+
// The SDK's own conclusion that the queue is over. Stops the loop, invalidates whatever is in flight, and
|
|
1052
|
+
// tells subscribers once — a world must not go on showing "searching…" for a ticket that no longer exists.
|
|
1053
|
+
end(reason) {
|
|
1054
|
+
this.generation++;
|
|
1055
|
+
this.poller.stop();
|
|
1056
|
+
this.backoff.ok();
|
|
1057
|
+
this.wake = null;
|
|
1058
|
+
this.undelivered = null;
|
|
1059
|
+
if (this.last.status === 'none') {
|
|
1060
|
+
this.syncIdle();
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
// The reason is for this one report. What is remembered is plain "not queued", so a later answer of
|
|
1064
|
+
// `none` from the platform is not mistaken for a change — nor is the platform's own account of this
|
|
1065
|
+
// same ending, which arrives too late to be preferred.
|
|
1066
|
+
this.last = NOT_QUEUED;
|
|
1067
|
+
this.endedLocally = true;
|
|
1068
|
+
this.syncIdle();
|
|
1069
|
+
emit(this.statusListeners, { status: 'none', reason });
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
// ─────────────────────────── parties ───────────────────────────
|
|
1073
|
+
const PARTY_REFUSALS = {
|
|
1074
|
+
'not-party-leader': 'not-party-leader',
|
|
1075
|
+
'cannot-invite': 'cannot-invite',
|
|
1076
|
+
'party-full': 'party-full',
|
|
1077
|
+
'too-many-invites': 'too-many-invites',
|
|
1078
|
+
'already-in-party': 'already-in-party',
|
|
1079
|
+
'party-changed': 'party-changed',
|
|
1080
|
+
'not-in-party': 'not-in-party',
|
|
1081
|
+
'unknown-party-member': 'unknown-party-member',
|
|
1082
|
+
'invite-rate-limit': 'rate-limited',
|
|
1083
|
+
'unknown-party-invite': 'invite-not-found',
|
|
1084
|
+
'party-invite-expired': 'invite-expired',
|
|
1085
|
+
'unknown-party-code': 'code-not-found',
|
|
1086
|
+
'party-code-rate-limit': 'rate-limited',
|
|
1087
|
+
'guests-cannot-party': 'guests-cannot-party',
|
|
1088
|
+
'guests-cannot-queue': 'guests-cannot-party',
|
|
1089
|
+
// Flag off (PARTIES_ENABLED).
|
|
1090
|
+
'parties-disabled': 'unavailable',
|
|
1091
|
+
};
|
|
1092
|
+
// The invite-answer routes are documented as "404 / 410: unknown or expired" without naming the codes. A
|
|
1093
|
+
// 410 there can only be the invite having run out. A 404 is the invite only when its code says so — an
|
|
1094
|
+
// unrelated coded 404 (the world, the party) stays a generic failure, and so does one with no code.
|
|
1095
|
+
const inviteRefusal = ({ status, backendCode }) => status === 410 ? 'invite-expired' : status === 404 && backendCode !== null && backendCode.includes('invite') ? 'invite-not-found' : null;
|
|
1096
|
+
// Invite ids already announced. Bounded so a very long session cannot grow it forever.
|
|
1097
|
+
const SEEN_INVITES_MAX = 512;
|
|
1098
|
+
const NO_PARTY = { party: null, invites: [] };
|
|
1099
|
+
const NO_PARTY_KEY = JSON.stringify(NO_PARTY);
|
|
1100
|
+
export class HelixParty {
|
|
1101
|
+
host;
|
|
1102
|
+
lane;
|
|
1103
|
+
// Internal watchers of the party's size (Helix.matchmaking). They keep the poll alive like a subscriber
|
|
1104
|
+
// does, but they are not a world's subscription: the onChange baseline ignores them.
|
|
1105
|
+
watchers = new Map();
|
|
1106
|
+
members = 0;
|
|
1107
|
+
followingVisibility = false;
|
|
1108
|
+
poller = new Poller(PARTY_POLL_MS, false, (urgent) => void this.poll(urgent));
|
|
1109
|
+
backoff = new Backoff(PARTY_POLL_MS);
|
|
1110
|
+
changeListeners = new Set();
|
|
1111
|
+
inviteListeners = new Set();
|
|
1112
|
+
errorListeners = new Set();
|
|
1113
|
+
// What subscribers currently believe. Null = no baseline yet (nobody subscribed, or just subscribed).
|
|
1114
|
+
baseline = null;
|
|
1115
|
+
seenInvites = new Set();
|
|
1116
|
+
// Bumped by every party action and by teardown: an answer asked for before it is not applied.
|
|
1117
|
+
generation = 0;
|
|
1118
|
+
pollingGeneration = null;
|
|
1119
|
+
// The final refusal that stopped the poll. Polling stays stopped until the session (or its token) changes,
|
|
1120
|
+
// or the platform answers a party call successfully.
|
|
1121
|
+
refusal = null;
|
|
1122
|
+
left = false;
|
|
1123
|
+
// The platform's clock: what an invite's `expiresAt` is judged against.
|
|
1124
|
+
clock;
|
|
1125
|
+
constructor(host) {
|
|
1126
|
+
this.host = host;
|
|
1127
|
+
this.clock = clockOf(host);
|
|
1128
|
+
this.lane = new PlatformLane(host, 'Helix.party', 'guests-cannot-party', PARTY_REFUSALS, (code, message, status, backendCode, cause) => new HelixPartyError(code, message, status, backendCode, cause), () => this.left, this.clock);
|
|
1129
|
+
}
|
|
1130
|
+
/** The player's party (null when in none) and their pending incoming invites, fresh from the platform. */
|
|
1131
|
+
async get() {
|
|
1132
|
+
return clone(await this.refresh());
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Called when the party state actually changed (a member joined or left, the leader changed, an invite
|
|
1136
|
+
* arrived or went away). The first answer after subscribing is the baseline, not a change — read it with
|
|
1137
|
+
* `get()`. The platform is polled every 5 s only while there is at least one `onChange` / `onInvite`
|
|
1138
|
+
* subscriber; when the last one unsubscribes the baseline is forgotten.
|
|
1139
|
+
*/
|
|
1140
|
+
onChange(cb) {
|
|
1141
|
+
this.changeListeners.add(cb);
|
|
1142
|
+
this.sync();
|
|
1143
|
+
return () => {
|
|
1144
|
+
this.changeListeners.delete(cb);
|
|
1145
|
+
this.unsubscribed();
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Called once per incoming invite id, including invites already pending when the world subscribed.
|
|
1150
|
+
* Invites are only ever announced from a fresh answer (subscribing asks for one), and never once expired
|
|
1151
|
+
* (by the platform's clock, as for a match).
|
|
1152
|
+
*/
|
|
1153
|
+
onInvite(cb) {
|
|
1154
|
+
this.inviteListeners.add(cb);
|
|
1155
|
+
if (this.poller.active)
|
|
1156
|
+
void this.poll(true);
|
|
1157
|
+
else
|
|
1158
|
+
this.sync();
|
|
1159
|
+
return () => {
|
|
1160
|
+
this.inviteListeners.delete(cb);
|
|
1161
|
+
this.unsubscribed();
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Called when the background poll behind `onChange` / `onInvite` meets a FINAL refusal and stops: the
|
|
1166
|
+
* world lacks the `multiplayer` permission (`missing-permission`), parties are not enabled (`unavailable`),
|
|
1167
|
+
* or the session is a guest (`guests-cannot-party`). Fires once per refusal; a subscriber added afterwards
|
|
1168
|
+
* is told too. The poll starts again by itself with a new or refreshed session, and as soon as any party
|
|
1169
|
+
* call of the world's own (`get()`, `invite()`, …) is answered successfully. Every other failure — no
|
|
1170
|
+
* answer, a 5xx, a 429, a 401 from an expired token, any other refusal — is retried with backoff (up to
|
|
1171
|
+
* POLL_BACKOFF_MAX_MS apart) and is not reported here; failures of calls the world makes itself reject
|
|
1172
|
+
* those calls.
|
|
1173
|
+
*/
|
|
1174
|
+
onError(cb) {
|
|
1175
|
+
this.errorListeners.add(cb);
|
|
1176
|
+
if (this.refusal) {
|
|
1177
|
+
void Promise.resolve().then(() => {
|
|
1178
|
+
const refusal = this.refusal;
|
|
1179
|
+
if (refusal && this.errorListeners.has(cb))
|
|
1180
|
+
dispatch(new Set([cb]), () => refusal);
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
return () => {
|
|
1184
|
+
this.errorListeners.delete(cb);
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* Invite an accepted friend, or any account with a live session in this same world. Creates the party
|
|
1189
|
+
* when the caller has none (they become its leader). The recipient must accept.
|
|
1190
|
+
*/
|
|
1191
|
+
async invite(userId) {
|
|
1192
|
+
const body = await this.act('POST', '/api/v1/parties/invites', { userId: this.id(userId, 'invite needs a user id') });
|
|
1193
|
+
const inviteId = isRecord(body) ? text(body.inviteId) : null;
|
|
1194
|
+
if (!inviteId)
|
|
1195
|
+
throw this.lane.fail('request-failed', 'the platform returned no invite id');
|
|
1196
|
+
return { inviteId, expiresAt: epochMsOf(body.expiresAt) };
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Accept an incoming invite and join that party. Resolves the party joined. From a party of one the
|
|
1200
|
+
* caller is moved into the new party; from a larger one it is `already-in-party`.
|
|
1201
|
+
*/
|
|
1202
|
+
async accept(inviteId) {
|
|
1203
|
+
const path = `/api/v1/parties/invites/${encodeURIComponent(this.id(inviteId, 'accept needs an invite id'))}/accept`;
|
|
1204
|
+
const party = this.partyFrom(await this.act('POST', path, undefined, inviteRefusal));
|
|
1205
|
+
this.tellWatchers(party.members.length); // known now, not at the next poll
|
|
1206
|
+
return party;
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Leader only: make a join code for the party — the way players who are not friends group up (an invite
|
|
1210
|
+
* to a non-friend only reaches a player whose presence is public). Creates a party of one when the caller
|
|
1211
|
+
* has none. The code also appears as `party.code` in the leader's `get()` / `onChange` state.
|
|
1212
|
+
*/
|
|
1213
|
+
async createCode() {
|
|
1214
|
+
const code = partyCodeOf(await this.act('POST', '/api/v1/parties/current/code'));
|
|
1215
|
+
if (!code)
|
|
1216
|
+
throw this.lane.fail('request-failed', 'the platform returned no party code');
|
|
1217
|
+
return code;
|
|
1218
|
+
}
|
|
1219
|
+
/** Leader only: withdraw the party's join code. Resolves whether or not there was one. */
|
|
1220
|
+
async revokeCode() {
|
|
1221
|
+
await this.act('DELETE', '/api/v1/parties/current/code');
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Join a party by its code. What the player typed is trimmed and upper-cased first; an empty code, one
|
|
1225
|
+
* containing whitespace or one longer than 64 characters is rejected locally (`invalid-argument`).
|
|
1226
|
+
* Resolves the party joined. From a party of one the caller is moved; from a larger one it is
|
|
1227
|
+
* `already-in-party`.
|
|
1228
|
+
*/
|
|
1229
|
+
async join(code) {
|
|
1230
|
+
const normalized = typeof code === 'string' ? code.trim().toUpperCase() : '';
|
|
1231
|
+
if (!/^\S{1,64}$/.test(normalized))
|
|
1232
|
+
throw this.lane.fail('invalid-argument', 'join needs a party code');
|
|
1233
|
+
const party = this.partyFrom(await this.act('POST', '/api/v1/parties/join', { code: normalized }));
|
|
1234
|
+
this.tellWatchers(party.members.length); // known now, not at the next poll
|
|
1235
|
+
return party;
|
|
1236
|
+
}
|
|
1237
|
+
/** Decline an incoming invite (or, as the leader, revoke one that was sent). */
|
|
1238
|
+
async decline(inviteId) {
|
|
1239
|
+
const path = `/api/v1/parties/invites/${encodeURIComponent(this.id(inviteId, 'decline needs an invite id'))}`;
|
|
1240
|
+
await this.act('DELETE', path, undefined, inviteRefusal);
|
|
1241
|
+
}
|
|
1242
|
+
/** Leave the party. The leader leaving promotes the longest-standing member; the last member leaving ends it. */
|
|
1243
|
+
async leave() {
|
|
1244
|
+
const blocked = this.lane.blocked();
|
|
1245
|
+
if (blocked)
|
|
1246
|
+
throw blocked;
|
|
1247
|
+
const self = this.host.getUserId();
|
|
1248
|
+
if (!self)
|
|
1249
|
+
throw this.lane.fail('not-ready', 'no signed-in user');
|
|
1250
|
+
await this.act('DELETE', `/api/v1/parties/current/members/${encodeURIComponent(self)}`);
|
|
1251
|
+
}
|
|
1252
|
+
/** Leader only: remove a member. */
|
|
1253
|
+
async kick(userId) {
|
|
1254
|
+
await this.act('DELETE', `/api/v1/parties/current/members/${encodeURIComponent(this.id(userId, 'kick needs a user id'))}`);
|
|
1255
|
+
}
|
|
1256
|
+
/** Leader only: hand leadership to another member. Resolves the party. */
|
|
1257
|
+
async promote(userId) {
|
|
1258
|
+
return this.partyFrom(await this.act('POST', '/api/v1/parties/current/leader', { userId: this.id(userId, 'promote needs a user id') }));
|
|
1259
|
+
}
|
|
1260
|
+
/** @internal See PartyWatch. Told the last known size at once when the poll is already running. */
|
|
1261
|
+
watch(cb, busy = () => false) {
|
|
1262
|
+
this.watchers.set(cb, busy);
|
|
1263
|
+
this.followVisibility();
|
|
1264
|
+
if (this.poller.active)
|
|
1265
|
+
cb(this.members);
|
|
1266
|
+
this.sync();
|
|
1267
|
+
return {
|
|
1268
|
+
stop: () => {
|
|
1269
|
+
this.watchers.delete(cb);
|
|
1270
|
+
this.followVisibility();
|
|
1271
|
+
this.sync();
|
|
1272
|
+
},
|
|
1273
|
+
update: () => this.sync(),
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
/** @internal Helix.init() resolved: a world that subscribed before then is served now. */
|
|
1277
|
+
ready() {
|
|
1278
|
+
this.sync();
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* @internal helix:leave. Every timer and listener stops and nothing is sent again until a new session.
|
|
1282
|
+
* No change is reported: a party is platform-level and outlives the world.
|
|
1283
|
+
*/
|
|
1284
|
+
teardown() {
|
|
1285
|
+
this.generation++;
|
|
1286
|
+
this.poller.stop();
|
|
1287
|
+
this.left = true;
|
|
1288
|
+
this.followVisibility();
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* @internal The session ended or changed hands. The old player's party is not this session's: subscribers
|
|
1292
|
+
* who knew of one are told there is none, and if there is a new session its party is polled and compared
|
|
1293
|
+
* against that.
|
|
1294
|
+
*/
|
|
1295
|
+
reset() {
|
|
1296
|
+
this.generation++;
|
|
1297
|
+
this.poller.stop();
|
|
1298
|
+
this.left = false;
|
|
1299
|
+
this.followVisibility();
|
|
1300
|
+
this.refusal = null;
|
|
1301
|
+
this.backoff.ok();
|
|
1302
|
+
this.seenInvites.clear();
|
|
1303
|
+
this.tellWatchers(0);
|
|
1304
|
+
if (this.baseline !== null && this.baseline !== NO_PARTY_KEY) {
|
|
1305
|
+
this.baseline = NO_PARTY_KEY;
|
|
1306
|
+
emit(this.changeListeners, NO_PARTY);
|
|
1307
|
+
}
|
|
1308
|
+
this.sync();
|
|
1309
|
+
}
|
|
1310
|
+
/** @internal The same player's session was refreshed (a new token): a poll that was refused gets another chance. */
|
|
1311
|
+
sessionRefreshed() {
|
|
1312
|
+
if (this.refusal) {
|
|
1313
|
+
this.recovered();
|
|
1314
|
+
}
|
|
1315
|
+
else if (this.backoff.failing && this.poller.active) {
|
|
1316
|
+
// Backing off, most likely from the 401s of the token that was just replaced: ask again now.
|
|
1317
|
+
this.backoff.ok();
|
|
1318
|
+
void this.poll(true);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
// The refusal no longer holds (a fresh session, or the platform just answered a party call): the poll, if
|
|
1322
|
+
// anything wants it, starts again. `pollNow` false when the caller already has (or is about to ask for) a
|
|
1323
|
+
// fresh answer, so that answer is not asked for twice.
|
|
1324
|
+
recovered(pollNow = true) {
|
|
1325
|
+
if (!this.refusal)
|
|
1326
|
+
return;
|
|
1327
|
+
this.refusal = null;
|
|
1328
|
+
this.backoff.ok();
|
|
1329
|
+
this.sync(pollNow);
|
|
1330
|
+
}
|
|
1331
|
+
// The world's own subscriptions: what the onChange baseline is kept for.
|
|
1332
|
+
get listeners() {
|
|
1333
|
+
return this.changeListeners.size + this.inviteListeners.size;
|
|
1334
|
+
}
|
|
1335
|
+
// Everything that needs the poll running.
|
|
1336
|
+
get subscribers() {
|
|
1337
|
+
return this.listeners + this.watchers.size;
|
|
1338
|
+
}
|
|
1339
|
+
tellWatchers(members) {
|
|
1340
|
+
this.members = members;
|
|
1341
|
+
for (const watcher of [...this.watchers.keys()]) {
|
|
1342
|
+
if (this.watchers.has(watcher))
|
|
1343
|
+
watcher(members);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
// While only internal watchers need the poll, it follows the tab's visibility (see `sync`). The listener
|
|
1347
|
+
// exists only while there is a watcher, so a world that uses neither namespace still adds none.
|
|
1348
|
+
followVisibility() {
|
|
1349
|
+
const wanted = this.watchers.size > 0 && !this.left && typeof document !== 'undefined';
|
|
1350
|
+
if (wanted === this.followingVisibility)
|
|
1351
|
+
return;
|
|
1352
|
+
this.followingVisibility = wanted;
|
|
1353
|
+
if (wanted)
|
|
1354
|
+
document.addEventListener('visibilitychange', this.visibilityChanged);
|
|
1355
|
+
else if (typeof document !== 'undefined')
|
|
1356
|
+
document.removeEventListener('visibilitychange', this.visibilityChanged);
|
|
1357
|
+
}
|
|
1358
|
+
visibilityChanged = () => {
|
|
1359
|
+
this.sync();
|
|
1360
|
+
};
|
|
1361
|
+
// A hidden tab whose only reason to poll is an internal watcher with nothing depending on it — no party
|
|
1362
|
+
// of two or more, no waiting ticket — rests until it is visible again.
|
|
1363
|
+
restingWhileHidden() {
|
|
1364
|
+
if (this.listeners > 0 || this.members >= 2)
|
|
1365
|
+
return false;
|
|
1366
|
+
if (typeof document === 'undefined' || document.visibilityState !== 'hidden')
|
|
1367
|
+
return false;
|
|
1368
|
+
return ![...this.watchers.values()].some((busy) => busy());
|
|
1369
|
+
}
|
|
1370
|
+
unsubscribed() {
|
|
1371
|
+
// With nobody subscribed nothing is tracked, so the next subscriber's first answer is a baseline again.
|
|
1372
|
+
if (this.listeners === 0)
|
|
1373
|
+
this.baseline = null;
|
|
1374
|
+
this.sync();
|
|
1375
|
+
}
|
|
1376
|
+
id(value, problem) {
|
|
1377
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
1378
|
+
throw this.lane.fail('invalid-argument', problem);
|
|
1379
|
+
return value;
|
|
1380
|
+
}
|
|
1381
|
+
partyFrom(body) {
|
|
1382
|
+
const party = partyOf(isRecord(body) && isRecord(body.party) ? body.party : body);
|
|
1383
|
+
if (!party)
|
|
1384
|
+
throw this.lane.fail('request-failed', 'the platform returned no party');
|
|
1385
|
+
return party;
|
|
1386
|
+
}
|
|
1387
|
+
// A party action. Whatever a poll asked BEFORE it no longer describes the party, so that answer is
|
|
1388
|
+
// dropped (the generation moves on both sides of the action), and when a world is subscribed a refresh
|
|
1389
|
+
// follows at once — its listeners hear the result now rather than up to five seconds from now.
|
|
1390
|
+
async act(method, path, body, refine) {
|
|
1391
|
+
this.generation++;
|
|
1392
|
+
let answered = false;
|
|
1393
|
+
try {
|
|
1394
|
+
const answer = await this.lane.request(method, path, body, refine);
|
|
1395
|
+
answered = true;
|
|
1396
|
+
return answer;
|
|
1397
|
+
}
|
|
1398
|
+
finally {
|
|
1399
|
+
this.generation++;
|
|
1400
|
+
if (answered)
|
|
1401
|
+
this.recovered(false); // the refresh just below asks
|
|
1402
|
+
if (this.poller.active)
|
|
1403
|
+
void this.poll(true);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
async refresh() {
|
|
1407
|
+
const generation = this.generation;
|
|
1408
|
+
const state = partyStateOf(await this.lane.request('GET', '/api/v1/parties/current'));
|
|
1409
|
+
this.recovered(false); // this answer is the fresh one
|
|
1410
|
+
if (generation === this.generation)
|
|
1411
|
+
this.apply(state);
|
|
1412
|
+
return state;
|
|
1413
|
+
}
|
|
1414
|
+
// Polling follows the subscribers: on with the first, off with the last, and never for a session that
|
|
1415
|
+
// cannot have a party (none, a guest), after a refusal, or once the world was left.
|
|
1416
|
+
sync(pollNow = true) {
|
|
1417
|
+
const wanted = this.subscribers > 0 && !this.left && this.refusal === null && this.lane.ready() && !this.restingWhileHidden();
|
|
1418
|
+
if (!wanted) {
|
|
1419
|
+
this.poller.stop();
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
if (this.poller.active)
|
|
1423
|
+
return;
|
|
1424
|
+
this.poller.start();
|
|
1425
|
+
if (pollNow)
|
|
1426
|
+
void this.poll(true);
|
|
1427
|
+
}
|
|
1428
|
+
async poll(urgent) {
|
|
1429
|
+
const generation = this.generation;
|
|
1430
|
+
// An answer of this generation is already on its way, and it is as fresh as another would be.
|
|
1431
|
+
if (pageAsleep || this.pollingGeneration === generation)
|
|
1432
|
+
return;
|
|
1433
|
+
if (!urgent && this.backoff.holding)
|
|
1434
|
+
return;
|
|
1435
|
+
this.pollingGeneration = generation;
|
|
1436
|
+
try {
|
|
1437
|
+
await this.refresh();
|
|
1438
|
+
this.backoff.ok();
|
|
1439
|
+
}
|
|
1440
|
+
catch (e) {
|
|
1441
|
+
if (generation === this.generation)
|
|
1442
|
+
this.pollFailed(e);
|
|
1443
|
+
}
|
|
1444
|
+
finally {
|
|
1445
|
+
if (this.pollingGeneration === generation)
|
|
1446
|
+
this.pollingGeneration = null;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
// Only a FINAL state stops the loop, and is surfaced once: the world lacks the permission, the feature is
|
|
1450
|
+
// off, a guest. Everything else backs off and keeps asking: no answer, a 5xx, a 429, a 401 — which, unless
|
|
1451
|
+
// it is the scope guard's (that one is `missing-permission`), is an expired or missing token that the
|
|
1452
|
+
// shell's next session push cures — and any other refusal (a codeless 403 / 404 from a gateway mid-deploy,
|
|
1453
|
+
// a code this SDK does not know): one answer is not proof that the next one will be the same.
|
|
1454
|
+
pollFailed(e) {
|
|
1455
|
+
if (!isFinalPartyRefusal(e)) {
|
|
1456
|
+
this.backoff.fail();
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
this.refusal = e;
|
|
1460
|
+
this.poller.stop();
|
|
1461
|
+
dispatch(this.errorListeners, () => e);
|
|
1462
|
+
}
|
|
1463
|
+
// A FRESH answer from the platform.
|
|
1464
|
+
apply(next) {
|
|
1465
|
+
if (this.left)
|
|
1466
|
+
return;
|
|
1467
|
+
const key = JSON.stringify(next);
|
|
1468
|
+
const changed = this.baseline !== null && key !== this.baseline;
|
|
1469
|
+
if (this.listeners > 0)
|
|
1470
|
+
this.baseline = key;
|
|
1471
|
+
this.tellWatchers(next.party ? next.party.members.length : 0);
|
|
1472
|
+
this.sync(); // the party's size is one of the things that decides whether a hidden tab keeps polling
|
|
1473
|
+
if (this.inviteListeners.size > 0) {
|
|
1474
|
+
for (const invite of next.invites) {
|
|
1475
|
+
if (this.seenInvites.has(invite.id) || this.clock.hasPassed(invite.expiresAt))
|
|
1476
|
+
continue;
|
|
1477
|
+
if (this.seenInvites.size >= SEEN_INVITES_MAX)
|
|
1478
|
+
this.seenInvites.delete(this.seenInvites.values().next().value);
|
|
1479
|
+
this.seenInvites.add(invite.id);
|
|
1480
|
+
emit(this.inviteListeners, invite);
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
if (changed)
|
|
1484
|
+
emit(this.changeListeners, next);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
//# sourceMappingURL=matchmaking.js.map
|