@usions/sdk 2.24.2 → 3.0.0-next.7
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 +45 -277
- package/dist/browser.global.js +1972 -0
- package/dist/browser.global.js.map +1 -0
- package/dist/index.d.ts +337 -0
- package/dist/index.js +1955 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.d.ts +23 -0
- package/dist/testing.js +63 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-G075L8Nl.d.ts +83 -0
- package/package.json +25 -46
- package/src/browser.js +0 -6725
- package/src/index.js +0 -10
- package/src/modules/back-button.js +0 -26
- package/src/modules/backend-channel.js +0 -109
- package/src/modules/bot.js +0 -52
- package/src/modules/chat.js +0 -35
- package/src/modules/cloud.js +0 -67
- package/src/modules/core.js +0 -424
- package/src/modules/errors.js +0 -120
- package/src/modules/file-storage.js +0 -46
- package/src/modules/game-ack.js +0 -32
- package/src/modules/game-core.js +0 -278
- package/src/modules/game-direct.js +0 -267
- package/src/modules/game-methods.js +0 -782
- package/src/modules/game-netcode.js +0 -349
- package/src/modules/game-proxy.js +0 -184
- package/src/modules/game-reliability.js +0 -278
- package/src/modules/game-resilience.js +0 -245
- package/src/modules/game-socket.js +0 -214
- package/src/modules/index.js +0 -78
- package/src/modules/leaderboard.js +0 -46
- package/src/modules/lobby.js +0 -103
- package/src/modules/matchmaking.js +0 -140
- package/src/modules/misc.js +0 -152
- package/src/modules/netcode/binary.js +0 -113
- package/src/modules/netcode/delta.js +0 -236
- package/src/modules/netcode/index.js +0 -43
- package/src/modules/netcode/interest-grid.js +0 -227
- package/src/modules/netcode/interpolation.js +0 -235
- package/src/modules/netcode/lagcomp.js +0 -104
- package/src/modules/netcode/lockstep.js +0 -103
- package/src/modules/netcode/mesh-network.js +0 -103
- package/src/modules/netcode/mesh.js +0 -188
- package/src/modules/netcode/netsim.js +0 -77
- package/src/modules/netcode/ping.js +0 -69
- package/src/modules/netcode/prediction.js +0 -113
- package/src/modules/netcode/sender.js +0 -102
- package/src/modules/netcode/webtransport.js +0 -195
- package/src/modules/notify.js +0 -70
- package/src/modules/permissions.js +0 -157
- package/src/modules/results.js +0 -34
- package/src/modules/session.js +0 -62
- package/src/modules/storage.js +0 -64
- package/src/modules/ui.js +0 -111
- package/src/modules/user.js +0 -61
- package/src/modules/wallet.js +0 -253
- package/types/browser.d.ts +0 -5
- package/types/index.d.ts +0 -1308
|
@@ -1,349 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Game Netcode — convenience wiring of the netcode toolkit onto the
|
|
3
|
-
* game module. These helpers ride on the existing realtime/action channels, so
|
|
4
|
-
* they work in every connection mode with no host/backend change (the one
|
|
5
|
-
* exception is RTT measurement — see game.ping below).
|
|
6
|
-
*/
|
|
7
|
-
import { SnapshotInterpolation } from './netcode/interpolation.js';
|
|
8
|
-
import { Predictor } from './netcode/prediction.js';
|
|
9
|
-
import { Coalescer } from './netcode/sender.js';
|
|
10
|
-
import { PingMeter } from './netcode/ping.js';
|
|
11
|
-
import { MeshConnection } from './netcode/mesh.js';
|
|
12
|
-
import { MeshNetwork } from './netcode/mesh-network.js';
|
|
13
|
-
import { WebTransportConnection } from './netcode/webtransport.js';
|
|
14
|
-
import { NetworkSim } from './netcode/netsim.js';
|
|
15
|
-
import { Lockstep } from './netcode/lockstep.js';
|
|
16
|
-
import { LagCompensator } from './netcode/lagcomp.js';
|
|
17
|
-
import { diff, patch, quantize } from './netcode/delta.js';
|
|
18
|
-
import { encode, decode } from './netcode/binary.js';
|
|
19
|
-
import { createInterestGrid } from './netcode/interest-grid.js';
|
|
20
|
-
|
|
21
|
-
export function applyGameNetcode(game, Usion) {
|
|
22
|
-
game.diff = diff;
|
|
23
|
-
game.patch = patch;
|
|
24
|
-
game.quantize = quantize;
|
|
25
|
-
game.encode = encode;
|
|
26
|
-
game.decode = decode;
|
|
27
|
-
|
|
28
|
-
game.createInterpolation = function (opts) { return new SnapshotInterpolation(opts || {}); };
|
|
29
|
-
game.createPredictor = function (opts) { return new Predictor(opts || {}); };
|
|
30
|
-
game.createLagCompensator = function (opts) { return new LagCompensator(opts || {}); };
|
|
31
|
-
game.createLockstep = function (opts) { return new Lockstep(opts || {}); };
|
|
32
|
-
game.createInterestGrid = function (opts) { return createInterestGrid(opts || {}); };
|
|
33
|
-
|
|
34
|
-
// ── Realtime channel router ──────────────────────────────────────────────
|
|
35
|
-
// Multiplexes realtime by action_type so replicate / mesh / mesh-network and
|
|
36
|
-
// the game's own onRealtime can coexist. Also the inject point for the
|
|
37
|
-
// network simulator's inbound side.
|
|
38
|
-
game._channels = game._channels || {};
|
|
39
|
-
game._userRealtime = game._userRealtime || null;
|
|
40
|
-
game._inboundDispatch = null;
|
|
41
|
-
function dispatchRealtime(data) {
|
|
42
|
-
const at = data && data.action_type;
|
|
43
|
-
if (at && game._channels[at]) { game._channels[at](data && (data.action_data !== undefined ? data.action_data : data), data); return; }
|
|
44
|
-
if (game._userRealtime) game._userRealtime(data);
|
|
45
|
-
}
|
|
46
|
-
game._dispatchRealtime = dispatchRealtime;
|
|
47
|
-
game._installRealtimeRouter = function () {
|
|
48
|
-
if (game._routerInstalled) return;
|
|
49
|
-
if (game._eventHandlers.realtime && game._eventHandlers.realtime !== game._router) game._userRealtime = game._eventHandlers.realtime;
|
|
50
|
-
game._router = function (data) { (game._inboundDispatch || game._dispatchRealtime)(data); };
|
|
51
|
-
game._eventHandlers.realtime = game._router;
|
|
52
|
-
game._routerInstalled = true;
|
|
53
|
-
};
|
|
54
|
-
/** Register a handler for one realtime action_type. Returns an unsubscribe fn. */
|
|
55
|
-
game._onChannel = function (type, handler) { game._channels[type] = handler; game._installRealtimeRouter(); return function () { delete game._channels[type]; }; };
|
|
56
|
-
// Route onRealtime through the router so channels keep working.
|
|
57
|
-
game.onRealtime = function (cb) { game._userRealtime = cb; game._installRealtimeRouter(); };
|
|
58
|
-
|
|
59
|
-
/** Fixed-rate outbound sender (defaults to game.realtime). */
|
|
60
|
-
game.createSender = function (opts) {
|
|
61
|
-
opts = opts || {};
|
|
62
|
-
const self = this;
|
|
63
|
-
const send = opts.send || function (type, data) { self.realtime(type, data); };
|
|
64
|
-
return new Coalescer({
|
|
65
|
-
hz: opts.hz || 20,
|
|
66
|
-
autoStart: opts.autoStart !== false,
|
|
67
|
-
onFlush: function (entries) { for (let i = 0; i < entries.length; i++) send(entries[i].type, entries[i].data); },
|
|
68
|
-
});
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Coalesced, sequence-guarded, delta-compressed snapshot sender.
|
|
73
|
-
*
|
|
74
|
-
* Deltas are computed against the **last keyframe** (not the previous frame),
|
|
75
|
-
* so a single lost delta on an unreliable channel never desyncs — the next
|
|
76
|
-
* delta still applies to the keyframe the receiver holds. Each message
|
|
77
|
-
* carries a monotonic seq (`s`) and, for deltas, the keyframe seq it's based
|
|
78
|
-
* on (`b`); the receiver uses these to drop stale/out-of-order frames and to
|
|
79
|
-
* hold until it has the right keyframe. Optional float `precision`
|
|
80
|
-
* (quantization) and binary `encode` shrink the wire further.
|
|
81
|
-
*
|
|
82
|
-
* Pass `source` (a getter) to auto-read the state each tick — the basis for
|
|
83
|
-
* game.replicate(). Pair with game.createSnapshotReceiver().
|
|
84
|
-
*/
|
|
85
|
-
game.createSnapshotSender = function (opts) {
|
|
86
|
-
opts = opts || {};
|
|
87
|
-
const self = this;
|
|
88
|
-
const channel = opts.channel || 'state';
|
|
89
|
-
const useDelta = opts.delta !== false;
|
|
90
|
-
const keyframeEvery = opts.keyframeEvery != null ? opts.keyframeEvery : 30;
|
|
91
|
-
const precision = opts.precision;
|
|
92
|
-
const enc = opts.encode === true ? encode : (typeof opts.encode === 'function' ? opts.encode : null);
|
|
93
|
-
const send = opts.send || function (type, data) { self.realtime(type, data); };
|
|
94
|
-
const source = typeof opts.source === 'function' ? opts.source : null;
|
|
95
|
-
let keyframeState = null; // an immutable clone (deltas diff against this)
|
|
96
|
-
let keyframeSeq = 0;
|
|
97
|
-
let seq = 0;
|
|
98
|
-
let sinceKey = 0;
|
|
99
|
-
|
|
100
|
-
function snapshotClone(v) { return v == null ? v : JSON.parse(JSON.stringify(v)); }
|
|
101
|
-
|
|
102
|
-
function emit(raw) {
|
|
103
|
-
if (raw === undefined || raw === null) return;
|
|
104
|
-
const state = precision != null ? quantize(raw, precision) : raw;
|
|
105
|
-
let payload;
|
|
106
|
-
const wantKey = !useDelta || keyframeState === null || sinceKey >= keyframeEvery;
|
|
107
|
-
if (wantKey) {
|
|
108
|
-
seq += 1; keyframeState = snapshotClone(state); keyframeSeq = seq; sinceKey = 0;
|
|
109
|
-
payload = { s: seq, f: state };
|
|
110
|
-
} else {
|
|
111
|
-
const d = diff(keyframeState, state);
|
|
112
|
-
if (d === undefined) return; // nothing changed — don't burn a seq
|
|
113
|
-
seq += 1; sinceKey += 1;
|
|
114
|
-
payload = { s: seq, b: keyframeSeq, d: d };
|
|
115
|
-
}
|
|
116
|
-
send(channel, enc ? enc(payload) : payload);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Two drive modes: a `source` getter (read every tick) or queued send().
|
|
120
|
-
const hz = opts.hz || 20;
|
|
121
|
-
let queued;
|
|
122
|
-
const co = source ? null : new Coalescer({
|
|
123
|
-
hz: hz, autoStart: opts.autoStart !== false,
|
|
124
|
-
onFlush: function (entries) { for (let i = 0; i < entries.length; i++) if (entries[i].type === '__snap') queued = entries[i].data; emit(queued); },
|
|
125
|
-
});
|
|
126
|
-
let timer = null;
|
|
127
|
-
function start() {
|
|
128
|
-
if (co) { co.start(); return; }
|
|
129
|
-
if (timer || typeof setInterval === 'undefined') return;
|
|
130
|
-
timer = setInterval(function () { emit(source()); }, Math.max(1, Math.round(1000 / hz)));
|
|
131
|
-
}
|
|
132
|
-
function stop() { if (co) co.stop(); if (timer) { clearInterval(timer); timer = null; } }
|
|
133
|
-
if (source && opts.autoStart !== false) start();
|
|
134
|
-
|
|
135
|
-
return {
|
|
136
|
-
send: function (state) { if (co) co.queue('__snap', state); else emit(state); },
|
|
137
|
-
flush: function () { if (co) co.flush(); else if (source) emit(source()); },
|
|
138
|
-
start: start,
|
|
139
|
-
stop: stop,
|
|
140
|
-
reset: function () { keyframeState = null; keyframeSeq = 0; seq = 0; sinceKey = 0; },
|
|
141
|
-
};
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* Receiver for createSnapshotSender. Holds the keyframe baseline + last
|
|
146
|
-
* applied seq, so it safely drops stale/out-of-order frames and ignores
|
|
147
|
-
* deltas whose keyframe it missed (until the next keyframe arrives).
|
|
148
|
-
* @returns {{ receive:(msg:any)=>any, state:any, stats:object, reset:()=>void }}
|
|
149
|
-
*/
|
|
150
|
-
game.createSnapshotReceiver = function (opts) {
|
|
151
|
-
opts = opts || {};
|
|
152
|
-
const dec = opts.decode === true ? decode : (typeof opts.decode === 'function' ? opts.decode : null);
|
|
153
|
-
let base = null, baseSeq = -1, current = null, appliedSeq = -1, dropped = 0;
|
|
154
|
-
return {
|
|
155
|
-
receive: function (msg) {
|
|
156
|
-
if (dec && (msg instanceof ArrayBuffer || ArrayBuffer.isView(msg))) msg = dec(msg);
|
|
157
|
-
if (!msg) return current;
|
|
158
|
-
if (msg.f !== undefined) {
|
|
159
|
-
if (msg.s !== undefined && msg.s <= appliedSeq) { dropped += 1; return current; }
|
|
160
|
-
base = msg.f; baseSeq = msg.s !== undefined ? msg.s : 0; current = msg.f; appliedSeq = baseSeq;
|
|
161
|
-
return current;
|
|
162
|
-
}
|
|
163
|
-
if (msg.d !== undefined) {
|
|
164
|
-
if (msg.b !== undefined && msg.b !== baseSeq) { dropped += 1; return current; } // missed keyframe
|
|
165
|
-
if (msg.s !== undefined && msg.s <= appliedSeq) { dropped += 1; return current; } // stale/dup
|
|
166
|
-
current = patch(base, msg.d);
|
|
167
|
-
if (msg.s !== undefined) appliedSeq = msg.s;
|
|
168
|
-
return current;
|
|
169
|
-
}
|
|
170
|
-
return current;
|
|
171
|
-
},
|
|
172
|
-
get state() { return current; },
|
|
173
|
-
get stats() { return { appliedSeq: appliedSeq, baseSeq: baseSeq, dropped: dropped }; },
|
|
174
|
-
reset: function () { base = null; baseSeq = -1; current = null; appliedSeq = -1; dropped = 0; },
|
|
175
|
-
};
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Declarative state replication (host side). Mutate the plain object you pass
|
|
180
|
-
* in; the SDK auto-diffs and broadcasts it every tick (sequence-guarded,
|
|
181
|
-
* delta-compressed, optional quantize/binary). Clients read it with
|
|
182
|
-
* game.replica(). This is the ~40-lines-into-2 ergonomic.
|
|
183
|
-
* @returns {{ state:any, flush:()=>void, start:()=>void, stop:()=>void }}
|
|
184
|
-
*/
|
|
185
|
-
game.replicate = function (obj, opts) {
|
|
186
|
-
opts = opts || {};
|
|
187
|
-
let state = obj != null ? obj : {};
|
|
188
|
-
const sender = this.createSnapshotSender(Object.assign({}, opts, { source: function () { return state; } }));
|
|
189
|
-
return {
|
|
190
|
-
get state() { return state; },
|
|
191
|
-
set state(v) { state = v; },
|
|
192
|
-
flush: function () { sender.flush(); },
|
|
193
|
-
start: function () { sender.start(); },
|
|
194
|
-
stop: function () { sender.stop(); },
|
|
195
|
-
};
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Declarative state replication (client side). Receives what a host
|
|
200
|
-
* replicate()s on the same channel, drops stale/out-of-order frames, and
|
|
201
|
-
* (optionally) interpolates. Read `.state` for the latest authoritative state,
|
|
202
|
-
* or `.view()` for smoothed entities when `interpolate` keys are given.
|
|
203
|
-
* @returns {{ state:any, view:()=>any, onChange:(cb)=>void, stop:()=>void }}
|
|
204
|
-
*/
|
|
205
|
-
game.replica = function (opts) {
|
|
206
|
-
opts = opts || {};
|
|
207
|
-
const channel = opts.channel || 'state';
|
|
208
|
-
const rx = this.createSnapshotReceiver({ decode: opts.decode });
|
|
209
|
-
const interp = opts.interpolate ? this.createInterpolation(typeof opts.interpolate === 'object' ? opts.interpolate : {}) : null;
|
|
210
|
-
const keys = typeof opts.interpolate === 'string' ? opts.interpolate : (opts.keys || (opts.interpolate && opts.interpolate.keys));
|
|
211
|
-
const group = opts.group || (opts.interpolate && opts.interpolate.group);
|
|
212
|
-
let onChange = null;
|
|
213
|
-
const off = this._onChannel(channel, function (data) {
|
|
214
|
-
const next = rx.receive(data);
|
|
215
|
-
if (interp && next != null) interp.add(next);
|
|
216
|
-
if (onChange) onChange(next);
|
|
217
|
-
});
|
|
218
|
-
return {
|
|
219
|
-
get state() { return rx.state; },
|
|
220
|
-
view: function () { return interp ? interp.calc(keys || 'x y', group) : rx.state; },
|
|
221
|
-
onChange: function (cb) { onChange = cb; },
|
|
222
|
-
stop: function () { off(); },
|
|
223
|
-
};
|
|
224
|
-
};
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* One-line WebRTC peer-to-peer setup (2 peers). Signaling rides the realtime
|
|
228
|
-
* channel via the router; gameplay then flows directly peer-to-peer over UDP.
|
|
229
|
-
*/
|
|
230
|
-
game.createMesh = function (opts) {
|
|
231
|
-
opts = opts || {};
|
|
232
|
-
const self = this;
|
|
233
|
-
const channel = opts.signalChannel || 'signal';
|
|
234
|
-
const mesh = new MeshConnection(Object.assign({}, opts, {
|
|
235
|
-
sendSignal: function (payload) { self.realtime(channel, payload); },
|
|
236
|
-
}));
|
|
237
|
-
this._onChannel(channel, function (payload) { if (payload && payload.type) mesh.handleSignal(payload); });
|
|
238
|
-
return mesh;
|
|
239
|
-
};
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* N-peer full mesh. Signaling routed per-peer over the realtime channel (each
|
|
243
|
-
* message carries {to, from}); messages addressed to us are dispatched to the
|
|
244
|
-
* right peer connection. selfId defaults to the current user id.
|
|
245
|
-
* @returns {MeshNetwork}
|
|
246
|
-
*/
|
|
247
|
-
game.createMeshNetwork = function (opts) {
|
|
248
|
-
opts = opts || {};
|
|
249
|
-
const self = this;
|
|
250
|
-
const channel = opts.signalChannel || 'mesh';
|
|
251
|
-
const selfId = opts.selfId || (Usion.user && Usion.user.getId && Usion.user.getId());
|
|
252
|
-
const net = new MeshNetwork(Object.assign({}, opts, {
|
|
253
|
-
selfId: selfId,
|
|
254
|
-
sendSignal: function (toPeerId, payload) { self.realtime(channel, { to: toPeerId, from: selfId, payload: payload }); },
|
|
255
|
-
}));
|
|
256
|
-
this._onChannel(channel, function (ad) { if (ad && ad.to === selfId && ad.from) net.handleSignal(ad.from, ad.payload); });
|
|
257
|
-
return net;
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* Inject artificial latency / jitter / packet loss locally to test how the
|
|
262
|
-
* game feels on a bad network (every studio has this). Affects both outbound
|
|
263
|
-
* realtime sends and inbound realtime dispatch. Call with null/false to turn
|
|
264
|
-
* it off. No-op safety: realtime must exist on the game module.
|
|
265
|
-
* @param {{latencyMs?:number,jitterMs?:number,lossPct?:number,dupPct?:number}|null} opts
|
|
266
|
-
*/
|
|
267
|
-
game.simulateNetwork = function (opts) {
|
|
268
|
-
const self = this;
|
|
269
|
-
self._installRealtimeRouter();
|
|
270
|
-
if (!self._realtimeRaw && typeof self.realtime === 'function') self._realtimeRaw = self.realtime.bind(self);
|
|
271
|
-
if (!opts) {
|
|
272
|
-
if (self._realtimeRaw) self.realtime = self._realtimeRaw;
|
|
273
|
-
self._inboundDispatch = null;
|
|
274
|
-
if (self._sim) self._sim.flush();
|
|
275
|
-
self._sim = null;
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
if (!self._sim) self._sim = new NetworkSim(opts);
|
|
279
|
-
else self._sim.set(opts);
|
|
280
|
-
if (self._realtimeRaw) self.realtime = self._sim.wrap(self._realtimeRaw);
|
|
281
|
-
self._inboundDispatch = self._sim.wrap(self._dispatchRealtime);
|
|
282
|
-
return self._sim;
|
|
283
|
-
};
|
|
284
|
-
|
|
285
|
-
/**
|
|
286
|
-
* Create a WebTransport (HTTP/3) connection — the lowest-latency client-server
|
|
287
|
-
* path (UDP-like datagrams, no TCP head-of-line blocking). `url` defaults to
|
|
288
|
-
* Usion.config.webTransportUrl. Call `connect()`, then `send()` (datagram) /
|
|
289
|
-
* `sendReliable()`; feed `onMessage` into a snapshot receiver. Direct/standalone
|
|
290
|
-
* games only (the iframe/WebView proxy relay can't carry datagrams).
|
|
291
|
-
* @returns {WebTransportConnection}
|
|
292
|
-
*/
|
|
293
|
-
game.createWebTransport = function (opts) {
|
|
294
|
-
opts = opts || {};
|
|
295
|
-
const url = opts.url || (Usion.config && (Usion.config.webTransportUrl || Usion.config.wtUrl));
|
|
296
|
-
return new WebTransportConnection(Object.assign({}, opts, { url: url }));
|
|
297
|
-
};
|
|
298
|
-
|
|
299
|
-
/**
|
|
300
|
-
* Measure round-trip time once (single outstanding probe), updating the
|
|
301
|
-
* rolling estimate (game.getRtt). Direct mode uses the protocol ping/pong;
|
|
302
|
-
* platform mode uses a lightweight server ack. Resolves to ms, or null if
|
|
303
|
-
* unavailable (proxy mode, or not connected).
|
|
304
|
-
* @returns {Promise<number|null>}
|
|
305
|
-
*/
|
|
306
|
-
game.ping = function () {
|
|
307
|
-
const self = this;
|
|
308
|
-
if (!self._pingMeter) self._pingMeter = new PingMeter();
|
|
309
|
-
if (self._pingInFlight) return self._pingInFlight; // single outstanding probe
|
|
310
|
-
|
|
311
|
-
let promise;
|
|
312
|
-
if (self.directMode) {
|
|
313
|
-
if (!self.directSocket || self.directSocket.readyState !== 1) return Promise.resolve(null);
|
|
314
|
-
promise = new Promise(function (resolve) {
|
|
315
|
-
const id = self._pingMeter.begin();
|
|
316
|
-
let done = false;
|
|
317
|
-
const finish = function () { if (done) return; done = true; resolve(self._pingMeter.end(id)); };
|
|
318
|
-
finish.sentAt = Date.now(); // lets the pong pair feed getNetworkStats' EWMA too
|
|
319
|
-
self._pongWaiters.push(finish);
|
|
320
|
-
self._sendDirect('ping', { t: Date.now() });
|
|
321
|
-
setTimeout(function () {
|
|
322
|
-
if (done) return; done = true;
|
|
323
|
-
const idx = self._pongWaiters.indexOf(finish);
|
|
324
|
-
if (idx >= 0) self._pongWaiters.splice(idx, 1);
|
|
325
|
-
delete self._pingMeter._outstanding[id];
|
|
326
|
-
resolve(null);
|
|
327
|
-
}, 3000);
|
|
328
|
-
});
|
|
329
|
-
} else if (self.socket && self.connected && !self._useProxy) {
|
|
330
|
-
promise = new Promise(function (resolve) {
|
|
331
|
-
const start = Date.now();
|
|
332
|
-
let done = false;
|
|
333
|
-
try {
|
|
334
|
-
self.socket.emit('game:ping', { t: start }, function () { if (done) return; done = true; resolve(self._pingMeter.sample(Date.now() - start)); });
|
|
335
|
-
} catch (e) { resolve(null); return; }
|
|
336
|
-
setTimeout(function () { if (done) return; done = true; resolve(null); }, 3000);
|
|
337
|
-
});
|
|
338
|
-
} else {
|
|
339
|
-
return Promise.resolve(null); // proxy mode has no point-to-point ack
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
self._pingInFlight = promise;
|
|
343
|
-
promise.then(function () { self._pingInFlight = null; }, function () { self._pingInFlight = null; });
|
|
344
|
-
return promise;
|
|
345
|
-
};
|
|
346
|
-
|
|
347
|
-
/** Latest smoothed round-trip time in ms (null until first ping). */
|
|
348
|
-
game.getRtt = function () { return this._pingMeter ? this._pingMeter.rtt : null; };
|
|
349
|
-
}
|
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Game Proxy — postMessage relay through parent app
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { isTrustedMessageSource } from './core.js';
|
|
6
|
-
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Add proxy connection methods to game module
|
|
10
|
-
* @param {object} game - The game module object
|
|
11
|
-
* @param {object} Usion - Reference to the main Usion object
|
|
12
|
-
*/
|
|
13
|
-
export function applyGameProxy(game, Usion) {
|
|
14
|
-
/**
|
|
15
|
-
* Connect via parent app proxy (postMessage relay).
|
|
16
|
-
* Used when mixed content prevents direct socket connection.
|
|
17
|
-
* @private
|
|
18
|
-
*/
|
|
19
|
-
game._connectViaProxy = function() {
|
|
20
|
-
var self = this;
|
|
21
|
-
|
|
22
|
-
if (self._useProxy && self.connected) {
|
|
23
|
-
return Promise.resolve();
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
self._useProxy = true;
|
|
27
|
-
self._connecting = true;
|
|
28
|
-
self._setupProxyListener();
|
|
29
|
-
|
|
30
|
-
self._connectPromise = new Promise(function(resolve, reject) {
|
|
31
|
-
// Listen for GAME_CONNECTED from parent
|
|
32
|
-
self._proxyConnectResolve = function() {
|
|
33
|
-
self.connected = true;
|
|
34
|
-
self._connecting = false;
|
|
35
|
-
Usion.log('Game socket connected via parent proxy');
|
|
36
|
-
resolve();
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
// Send connect request to parent
|
|
40
|
-
Usion._post({ type: 'GAME_CONNECT' });
|
|
41
|
-
|
|
42
|
-
// Timeout after 10s
|
|
43
|
-
setTimeout(function() {
|
|
44
|
-
if (!self.connected) {
|
|
45
|
-
self._connecting = false;
|
|
46
|
-
reject(new UsionError(ERROR_CODES.CONNECT_TIMEOUT, 'Proxy connection timeout'));
|
|
47
|
-
}
|
|
48
|
-
}, 10000);
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
return self._connectPromise;
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Set up message listener for proxy game events from parent.
|
|
56
|
-
* @private
|
|
57
|
-
*/
|
|
58
|
-
game._setupProxyListener = function() {
|
|
59
|
-
var self = this;
|
|
60
|
-
if (self._proxyListenerSetup) return;
|
|
61
|
-
self._proxyListenerSetup = true;
|
|
62
|
-
|
|
63
|
-
window.addEventListener('message', function(event) {
|
|
64
|
-
if (!isTrustedMessageSource(event)) return;
|
|
65
|
-
|
|
66
|
-
var data;
|
|
67
|
-
try {
|
|
68
|
-
data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
|
|
69
|
-
} catch (e) {
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
if (!data || typeof data !== 'object' || !self._useProxy) return;
|
|
73
|
-
|
|
74
|
-
switch (data.type) {
|
|
75
|
-
case 'GAME_CONNECTED':
|
|
76
|
-
if (self._proxyConnectResolve) {
|
|
77
|
-
self._proxyConnectResolve();
|
|
78
|
-
self._proxyConnectResolve = null;
|
|
79
|
-
}
|
|
80
|
-
break;
|
|
81
|
-
|
|
82
|
-
case 'GAME_CONNECT_ERROR':
|
|
83
|
-
self.connected = false;
|
|
84
|
-
self._connecting = false;
|
|
85
|
-
break;
|
|
86
|
-
|
|
87
|
-
case 'GAME_DISCONNECTED':
|
|
88
|
-
// The host app's socket dropped; it will rejoin and resync for us.
|
|
89
|
-
self.connected = false;
|
|
90
|
-
self._dispatch('disconnect', data.reason || 'transport');
|
|
91
|
-
break;
|
|
92
|
-
|
|
93
|
-
case 'GAME_RECONNECTED':
|
|
94
|
-
self.connected = true;
|
|
95
|
-
self._dispatch('reconnect', data.attempts || 1);
|
|
96
|
-
break;
|
|
97
|
-
|
|
98
|
-
case 'GAME_PLAYER_CONNECTION':
|
|
99
|
-
self._dispatch('playerConnection', data);
|
|
100
|
-
break;
|
|
101
|
-
|
|
102
|
-
case 'GAME_JOINED':
|
|
103
|
-
self._joined = true;
|
|
104
|
-
if (data.sequence !== undefined) {
|
|
105
|
-
self._lastSequence = data.sequence;
|
|
106
|
-
self._lastActionApplied = Math.max(self._lastActionApplied, data.sequence);
|
|
107
|
-
}
|
|
108
|
-
if (self._proxyJoinResolve) {
|
|
109
|
-
self._proxyJoinResolve(data);
|
|
110
|
-
self._proxyJoinResolve = null;
|
|
111
|
-
}
|
|
112
|
-
self._proxyJoinReject = null;
|
|
113
|
-
self._dispatch('joined', data);
|
|
114
|
-
break;
|
|
115
|
-
|
|
116
|
-
case 'GAME_JOIN_ERROR':
|
|
117
|
-
self._joined = false;
|
|
118
|
-
if (self._proxyJoinReject) {
|
|
119
|
-
self._proxyJoinReject(toUsionError(data.message || 'Join failed'));
|
|
120
|
-
self._proxyJoinReject = null;
|
|
121
|
-
}
|
|
122
|
-
self._proxyJoinResolve = null;
|
|
123
|
-
break;
|
|
124
|
-
|
|
125
|
-
case 'GAME_PLAYER_JOINED':
|
|
126
|
-
self._dispatch('playerJoined', data);
|
|
127
|
-
break;
|
|
128
|
-
|
|
129
|
-
case 'GAME_PLAYER_LEFT':
|
|
130
|
-
self._dispatch('playerLeft', data);
|
|
131
|
-
break;
|
|
132
|
-
|
|
133
|
-
case 'GAME_STATE':
|
|
134
|
-
if (data.sequence !== undefined) self._lastSequence = Math.max(self._lastSequence, data.sequence);
|
|
135
|
-
self._dispatch('stateUpdate', data);
|
|
136
|
-
break;
|
|
137
|
-
|
|
138
|
-
case 'GAME_ACTION_DATA':
|
|
139
|
-
if (data.sequence !== undefined) {
|
|
140
|
-
// Drop duplicates: actions are delivered exactly once per
|
|
141
|
-
// sequence (live, sender echo, or replay after reconnect).
|
|
142
|
-
if (data.sequence <= self._lastActionApplied) break;
|
|
143
|
-
self._lastActionApplied = data.sequence;
|
|
144
|
-
self._lastSequence = Math.max(self._lastSequence, data.sequence);
|
|
145
|
-
}
|
|
146
|
-
self._dispatch('action', data);
|
|
147
|
-
break;
|
|
148
|
-
|
|
149
|
-
case 'GAME_REALTIME_DATA':
|
|
150
|
-
self._dispatch('realtime', data);
|
|
151
|
-
break;
|
|
152
|
-
|
|
153
|
-
case 'GAME_FINISHED':
|
|
154
|
-
if (data.sequence !== undefined) self._lastSequence = data.sequence;
|
|
155
|
-
self._dispatch('finished', data);
|
|
156
|
-
break;
|
|
157
|
-
|
|
158
|
-
case 'GAME_ERROR':
|
|
159
|
-
Usion.log('Game error via proxy: ' + (data.message || data.code));
|
|
160
|
-
self._dispatch('error', data);
|
|
161
|
-
break;
|
|
162
|
-
|
|
163
|
-
case 'GAME_RESTARTED':
|
|
164
|
-
self._lastSequence = 0;
|
|
165
|
-
self._lastActionApplied = 0;
|
|
166
|
-
self._dispatch('restarted', data);
|
|
167
|
-
break;
|
|
168
|
-
|
|
169
|
-
case 'GAME_REMATCH_REQUEST':
|
|
170
|
-
self._dispatch('rematchRequest', data);
|
|
171
|
-
break;
|
|
172
|
-
|
|
173
|
-
case 'GAME_SYNC':
|
|
174
|
-
if (data.sequence !== undefined) {
|
|
175
|
-
self._lastSequence = data.sequence;
|
|
176
|
-
self._lastActionApplied = Math.max(self._lastActionApplied, data.sequence);
|
|
177
|
-
}
|
|
178
|
-
self._dispatch('sync', data);
|
|
179
|
-
self._dispatch('stateUpdate', data);
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
};
|
|
184
|
-
}
|