@super-line/plugin-multiplayer 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
3
3
  Generated from conventional commits by [git-cliff](https://git-cliff.org) —
4
4
  run `pnpm changelog` rather than editing by hand.
5
5
 
6
+ ## [plugin-multiplayer-v0.2.0] — 2026-11-30
7
+
8
+ ### Features
9
+
10
+ - **plugin-multiplayer:** Patch frames, world seeding, worlds.run and removeSeat ([c790a00])
11
+
6
12
  ## [plugin-multiplayer-v0.1.0] — 2026-11-29
7
13
 
8
14
  ### Features
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @super-line/plugin-multiplayer
2
2
 
3
3
  Server-run game worlds for super-line. A **world** is one JSON state that only the game's own functions change
4
- (join, leave, command, tick). The server runs them, ticks the world on a fixed clock and sends the whole state to
5
- every seated player. Clients predict their own player and draw everyone else smoothly a moment behind. The same
4
+ (join, leave, command, tick). The server runs them, ticks the world on a fixed clock and sends the state to every
5
+ seated player: the whole state, or only what changed. Clients predict their own player and draw everyone else smoothly a moment behind. The same
6
6
  code runs in one Node process, which hosts many worlds, and on Cloudflare, with one Durable Object per world.
7
7
 
8
8
  ```bash
@@ -146,9 +146,12 @@ The server kit's options:
146
146
  | `seatGraceMs` | how long a dropped player's seat is held, default 30 000; `0` leaves at once |
147
147
  | `saveEveryMs` | how often a ticking world saves, default 5 000 |
148
148
  | `stats` | measure each world, default `false`. See [Stats](#stats). |
149
+ | `frames` | `'whole'` (default) sends the whole state in every frame; `'patch'` sends only what changed since the previous frame. See [Patch frames](#patch-frames). |
150
+ | `initialState` | `(world) => state`, may be async. Builds a new world's state from outside the game, for example from a database. See [Server-side control](#server-side-control). |
149
151
 
150
- The kit also has `worlds.get(id)`, `worlds.list()` and `worlds.delete(id)`. Deleting is the only way a world ends:
151
- the row goes, and every seated client gets `closed` with `deleted`.
152
+ The kit also has `worlds.get(id)`, `worlds.list()`, `worlds.delete(id)`, `worlds.run(id, fn)` and
153
+ `worlds.removeSeat(id, player, opts?)`. Deleting is the only way a world ends: the row goes, and every seated client
154
+ gets `closed` with `deleted`. See [Server-side control](#server-side-control).
152
155
 
153
156
  ### The world handle
154
157
 
@@ -157,7 +160,8 @@ commands re-applied and the tick run forward. `world.at(id)` is the entity to dr
157
160
  prediction, glided over one tick so a correction bends instead of jumping, and everyone else's from a buffer of
158
161
  recent states, a little in the past. At 30 ticks and 10 sends a second that is about 133 ms plus the network delay
159
162
  behind. `world.serverTick()` is the estimated server tick. Events: `frame`, `message`, `seat`
160
- (`joined | left | dropped | resumed`), `rejected` and `closed`.
163
+ (`joined | left | dropped | resumed`), `rejected` and `closed` (`{ reason, detail? }`). The `frame` event and
164
+ `world.state` always carry the whole state, also when the server sends patch frames.
161
165
 
162
166
  `send(command)` resolves `{ applied: true, tick }` or `{ applied: false, code, reason? }`. In a ticking world a
163
167
  newer `send` before the next tick resolves the waiting one with `SUPERSEDED`. It rejects with `DISCONNECTED` while
@@ -168,6 +172,78 @@ order.
168
172
  While seated in a ticking world the client sends a clock request every 5 s (`clockEveryMs`). It feeds
169
173
  `serverTick()` and, on Cloudflare, is a real message to the world's object. A world with no tick is never pinged.
170
174
 
175
+ ## Patch frames
176
+
177
+ By default every frame is the whole state, so a frame costs the state's size whether or not anything moved. When
178
+ most of the state stands still, such as a large layout beside a few moving players, send patches instead:
179
+
180
+ ```ts
181
+ const mp = multiplayer({ world: office, onlyWorld: null, authorize, frames: 'patch' })
182
+ ```
183
+
184
+ Each frame then carries only what changed since the previous frame of that world, still encoded once for the whole
185
+ room. A patch is plain JSON, the exported type `StatePatch`. It mirrors the shape of the state and holds only the
186
+ keys that changed, each as one of: a nested patch object (go into the key); `[value]` (set the key); `[changes,
187
+ length]` (the key holds an array: `length` is its new length, `changes` holds by index what changed in each element,
188
+ in these same forms); `0` (delete the key). For example,
189
+ `{ "units": { "u7": { "x": [12.5] }, "u3": 0 }, "phase": ["over"], "path": [{ "2": [9] }, 3] }` moves unit `u7`,
190
+ removes `u3`, sets `phase`, and makes `path` three long with `9` as its last element. An array whose elements shifted
191
+ (one inserted or removed before the end) is sent whole as `[value]`, so keep things that come and go in records
192
+ keyed by id.
193
+
194
+ Nothing changes on the client. A joining or re-joining player gets the whole state first. The client applies each
195
+ patch, and parts it did not touch keep their object identity (`next.layout === prev.layout` when nothing under
196
+ `layout` changed), so a renderer can skip them by reference. Each patch frame carries a counter `n`. A patch at or
197
+ below the latest `n` is dropped (a join's response and room broadcasts can arrive out of order through a broker
198
+ adapter such as Redis). A patch that skips ahead means a frame was lost, for example to a WebSocket server set to
199
+ drop frames under backpressure: the client asks once for the whole state by joining again on the same connection
200
+ (no new seat, no `onJoin`) and ignores patches until it arrives, as it does while any join is in flight. A new clock
201
+ epoch and a wake send a whole frame. A raw `client.on('mp.state')` listener receives `StateFrame | PatchFrame`; the
202
+ world handle's `frame` event stays a whole `StateFrame`, carrying `n` in patch mode. A 0.2.0 client reads both modes with no
203
+ option, and needs nothing beyond ECMAScript built-ins to apply a patch.
204
+
205
+ Turn it on when most of the state does not change between frames. When nearly everything moves every frame, a patch
206
+ is about as large as the state and the server diffs it each frame for nothing.
207
+
208
+ ## Server-side control
209
+
210
+ **Seed a new world.** `multiplayer({ initialState: (world) => state })` builds the state of a new world from the
211
+ world id, for example from a database. It runs only when a world is created (no saved row, not in memory), may be
212
+ async, and concurrent first joins share one call. Its result must be plain JSON and pass the state schema, or the join
213
+ fails with `STATE_INVALID`. A throw reaches the joiner unchanged (a `SuperLineError` keeps its code, anything else is
214
+ `INTERNAL`). Either way no world and no row are created, and the next join tries again. After
215
+ `worlds.delete(id)` the next join seeds again. `defineWorld`'s `initialState()` stays required: the client and
216
+ `defineWorld`'s JSON check use it.
217
+
218
+ ```ts
219
+ const mp = multiplayer({
220
+ world: office,
221
+ onlyWorld: null,
222
+ authorize,
223
+ initialState: async (world) => ({ layout: await loadLayout(world), players: {} }),
224
+ })
225
+ ```
226
+
227
+ **Change a world.** `worlds.run(id, fn)` runs `fn(state, ctx)` on a world with no player as the sender and the
228
+ guarantees of a command: it runs on a copy, so a throw (including `reject()`) leaves the state untouched and is
229
+ rethrown. Then the change goes out the way a command's result does: in a world whose clock runs, in the next frame
230
+ and the next periodic save; in a world with no clock running (no `tickRate`, or a ticking world with no seats), as
231
+ one frame and a save at once, which `run` awaits. Its messages go out after the frame. A world that is not live is
232
+ loaded from its row. It never creates a world: it resolves `false` when there is none.
233
+
234
+ ```ts
235
+ await mp.worlds.run('lobby', (s, ctx) => {
236
+ s.layout = newLayout
237
+ ctx.broadcast({ type: 'layout-changed' })
238
+ })
239
+ ```
240
+
241
+ **Remove a seat.** `worlds.removeSeat(id, player, { reason })` ends a seat now, held or away: `onLeave` runs, the
242
+ player leaves the state, and others get `seat` with `left`. The seat's connection gets `closed` with `removed` and
243
+ `detail` set to your `reason`. Its socket stays open, as with `replaced`, and its handle does not re-join. A world that
244
+ is not live is loaded from its row, so an away seat can be removed after a restart. It resolves `false` when the
245
+ world or the seat does not exist. The player can join again later through `authorize`.
246
+
171
247
  ## Stats
172
248
 
173
249
  Both halves measure what the plugin does, for a profiling overlay or a load run.
@@ -187,7 +263,7 @@ draws its own player pays nothing extra; a client that never predicts, such as a
187
263
  | `latenessMs`, `jitterMs` | ms | how late frames arrive against the clock, and how much that varies |
188
264
  | `predictionLeadTicks` | ticks | how far ahead of the latest frame the prediction runs |
189
265
  | `framesPerSecond` | per second | state frames received over about the last second |
190
- | `frameBytes` | bytes | the latest frame's size on the wire with the default JSON serializer |
266
+ | `frameBytes` | bytes | the latest frame's size on the wire with the default JSON serializer; with patch frames, the patch |
191
267
  | `msSinceFrame` | ms | time since the latest frame arrived |
192
268
  | `pendingCommands` | count | sent and not yet shown in a frame, rejected or failed |
193
269
  | `commandsSent`, `commandsApplied`, `commandsRejected`, `commandsSuperseded` | count | since the handle opened |
@@ -205,7 +281,7 @@ only `tick`, `ms` and `epoch`. The type is `WorldServerStats`.
205
281
  | `tickMsMean`, `tickMsMax` | ms | over the last completed one-second window |
206
282
  | `ticksPerSecond` | per second | ticks run in that window |
207
283
  | `ticksDropped` | ticks | catch-up ticks skipped because the loop fell more than 5 behind, since the world loaded |
208
- | `frameBytes` | bytes | the latest state frame, encoded once more with the server's serializer, as it goes on the wire |
284
+ | `frameBytes` | bytes | the latest state frame, encoded once more with the server's serializer, as it goes on the wire; with patch frames, the patch |
209
285
  | `framesSent` | count | state frames sent since the world loaded |
210
286
  | `seated`, `away` | count | seats held by a connection, and seats held for a dropped player |
211
287
  | `saveMs` | ms | the latest save |
@@ -234,6 +310,8 @@ connection id.
234
310
  build a new wrapper and join.
235
311
  - **Without `identify`**, every connection is its own principal, so a reconnect is a new player and the old
236
312
  seat expires after the grace.
313
+ - **The server can remove a seat** with `worlds.removeSeat`. The client gets `closed` with `removed`; its socket
314
+ stays open and its handle does not re-join.
237
315
 
238
316
  ## Saving
239
317
 
@@ -318,8 +396,9 @@ inside each world's Durable Object, accounts belong to that world.
318
396
 
319
397
  ## Limits and what is not in this version
320
398
 
321
- - Every player gets the whole state, the same for everyone, at the send rate. There are no deltas and no private
322
- per-player views. That suits tens of players, not hundreds.
399
+ - Every player gets the same frames at the send rate, whole or patched. There are no private per-player views.
400
+ Whole frames suit tens of players, not hundreds; patch frames help when most of the state stands still.
401
+ - A saved row whose state no longer fits the schema is not migrated: it fails joins with `STATE_INVALID`.
323
402
  - A world lives on one node. In a Node cluster, every player of a world must reach the same process.
324
403
  - Commands are not exactly-once across a reconnect: one sent while disconnected fails.
325
404
  - One row per world, capped by the backend, with no splitting.
@@ -331,5 +410,5 @@ See [`examples/game-arena`](../../examples/game-arena): a PlayCanvas arena on Cl
331
410
 
332
411
  ## Third-party code
333
412
 
334
- The client's clock, prediction and interpolation are ported from [Tickflare](https://github.com/Giamme/tickflare)
335
- (MIT). The files and the license are listed in [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
413
+ The client's clock, prediction and interpolation, and the patch format with the diff that produces it, are ported
414
+ from [Tickflare](https://github.com/Giamme/tickflare) (MIT). The files and the license are listed in [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
@@ -9,6 +9,7 @@ Parts of this package are ported from [Tickflare](https://github.com/Giamme/tick
9
9
  | `src/client/clock.ts` | `src/client/clock.ts` (`ServerClock`) |
10
10
  | `src/client/predict.ts` | `src/client/predict.ts` (`Predictor`) |
11
11
  | `src/client/buffered.ts` | `src/client/buffered.ts` (`BufferedInterpolator`) and `src/client/interpolate.ts` (`Interpolator`, as `Glide`) |
12
+ | `src/patch.ts` | `src/patch.ts` (`diff`, `applyPatch`, `diffArrays`; `Patch` as `StatePatch`) |
12
13
 
13
14
  ```
14
15
  MIT License
@@ -0,0 +1,127 @@
1
+ // src/bytes.ts
2
+ function encodedBytes(encoded) {
3
+ if (typeof encoded !== "string") return encoded.byteLength;
4
+ let bytes = 0;
5
+ for (let i = 0; i < encoded.length; i++) {
6
+ const c = encoded.charCodeAt(i);
7
+ if (c < 128) bytes += 1;
8
+ else if (c < 2048) bytes += 2;
9
+ else if (c >= 55296 && c < 56320 && i + 1 < encoded.length) {
10
+ bytes += 4;
11
+ i++;
12
+ } else bytes += 3;
13
+ }
14
+ return bytes;
15
+ }
16
+
17
+ // src/patch.ts
18
+ function diff(prev, next) {
19
+ if (isPlainObject(prev) && isPlainObject(next)) return diffObjects(prev, next);
20
+ return jsonEqual(prev, next) ? void 0 : null;
21
+ }
22
+ function applyPatch(base, patch) {
23
+ const out = isPlainObject(base) ? { ...base } : {};
24
+ for (const key of Object.keys(patch)) {
25
+ if (key === "__proto__") continue;
26
+ const change = patch[key];
27
+ if (change === 0) delete out[key];
28
+ else if (Array.isArray(change)) out[key] = change.length === 2 ? applyArrayPatch(own(out, key), change) : change[0];
29
+ else if (change) out[key] = applyPatch(own(out, key), change);
30
+ }
31
+ return out;
32
+ }
33
+ var INDEX = /^(0|[1-9][0-9]*)$/;
34
+ function applyArrayPatch(base, [changes, length]) {
35
+ const out = Array.isArray(base) ? base.slice(0, length) : [];
36
+ for (const key of Object.keys(changes)) {
37
+ const index = Number(key);
38
+ if (!INDEX.test(key) || index >= length) continue;
39
+ const change = changes[key];
40
+ if (Array.isArray(change)) out[index] = change.length === 2 ? applyArrayPatch(out[index], change) : change[0];
41
+ else out[index] = applyPatch(out[index], change);
42
+ }
43
+ for (let index = out.length; index < length; index++) out[index] = null;
44
+ for (let index = 0; index < length; index++) if (!(index in out)) out[index] = null;
45
+ return out;
46
+ }
47
+ function diffArrays(prev, next) {
48
+ const changes = {};
49
+ let changed = 0;
50
+ let replaced = 0;
51
+ const shared = Math.min(prev.length, next.length);
52
+ for (let index = 0; index < shared; index++) {
53
+ const from = prev[index];
54
+ const to = next[index] === void 0 ? null : next[index];
55
+ if (isPlainObject(from) && isPlainObject(to)) {
56
+ const inner = diffObjects(from, to);
57
+ if (!inner) continue;
58
+ changes[index] = inner;
59
+ if (Object.keys(inner).length * 2 > Object.keys(to).length) replaced += 1;
60
+ } else if (Array.isArray(from) && Array.isArray(to)) {
61
+ const inner = diffArrays(from, to);
62
+ if (inner === void 0) continue;
63
+ if (inner === null) replaced += 1;
64
+ changes[index] = inner ?? [to];
65
+ } else if (jsonEqual(from, to)) {
66
+ continue;
67
+ } else {
68
+ changes[index] = [to];
69
+ replaced += 1;
70
+ }
71
+ changed += 1;
72
+ if (replaced * 2 > next.length) return null;
73
+ }
74
+ replaced += next.length - shared;
75
+ if (replaced * 2 > next.length) return null;
76
+ for (let index = shared; index < next.length; index++) {
77
+ changes[index] = [next[index] === void 0 ? null : next[index]];
78
+ changed += 1;
79
+ }
80
+ if (changed === 0 && prev.length === next.length) return void 0;
81
+ return [changes, next.length];
82
+ }
83
+ function diffObjects(prev, next) {
84
+ let patch;
85
+ for (const key of Object.keys(next)) {
86
+ const to = next[key];
87
+ if (to === void 0) continue;
88
+ const from = own(prev, key);
89
+ if (isPlainObject(from) && isPlainObject(to)) {
90
+ const inner = diffObjects(from, to);
91
+ if (inner) (patch ??= {})[key] = inner;
92
+ } else if (Array.isArray(from) && Array.isArray(to)) {
93
+ const inner = diffArrays(from, to);
94
+ if (inner !== void 0) (patch ??= {})[key] = inner ?? [to];
95
+ } else if (from === void 0 || !jsonEqual(from, to)) {
96
+ (patch ??= {})[key] = [to];
97
+ }
98
+ }
99
+ for (const key of Object.keys(prev)) {
100
+ if (prev[key] !== void 0 && own(next, key) === void 0) (patch ??= {})[key] = 0;
101
+ }
102
+ return patch;
103
+ }
104
+ function own(object, key) {
105
+ return Object.prototype.hasOwnProperty.call(object, key) ? object[key] : void 0;
106
+ }
107
+ function jsonEqual(a, b) {
108
+ if (a === b) return true;
109
+ if (Array.isArray(a)) {
110
+ if (!Array.isArray(b) || a.length !== b.length) return false;
111
+ for (let i = 0; i < a.length; i++) {
112
+ if (!jsonEqual(a[i], b[i])) return false;
113
+ }
114
+ return true;
115
+ }
116
+ if (isPlainObject(a) && isPlainObject(b)) return diffObjects(a, b) === void 0;
117
+ return false;
118
+ }
119
+ function isPlainObject(value) {
120
+ return typeof value === "object" && value !== null && !Array.isArray(value);
121
+ }
122
+
123
+ export {
124
+ encodedBytes,
125
+ diff,
126
+ applyPatch
127
+ };
@@ -24,6 +24,15 @@ var hostSchema = (schema) => {
24
24
  return result.value;
25
25
  }).meta(shape);
26
26
  };
27
+ var isJson = (value) => {
28
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
29
+ if (typeof value === "number") return Number.isFinite(value);
30
+ if (Array.isArray(value)) return value.every(isJson);
31
+ if (typeof value !== "object") return false;
32
+ const proto = Object.getPrototypeOf(value);
33
+ if (proto !== Object.prototype && proto !== null) return false;
34
+ return Object.values(value).every(isJson);
35
+ };
27
36
 
28
37
  // src/index.ts
29
38
  var CommandRejected = class extends Error {
@@ -39,15 +48,6 @@ var CommandRejected = class extends Error {
39
48
  function reject(code, reason) {
40
49
  throw new CommandRejected(code, reason);
41
50
  }
42
- var isJson = (value) => {
43
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
44
- if (typeof value === "number") return Number.isFinite(value);
45
- if (Array.isArray(value)) return value.every(isJson);
46
- if (typeof value !== "object") return false;
47
- const proto = Object.getPrototypeOf(value);
48
- if (proto !== Object.prototype && proto !== null) return false;
49
- return Object.values(value).every(isJson);
50
- };
51
51
  function defineWorld(world) {
52
52
  const { maxPlayers, tickRate, sendRate } = world;
53
53
  if (!Number.isFinite(maxPlayers) || maxPlayers <= 0) throw new TypeError("maxPlayers must be a positive number");
@@ -69,15 +69,20 @@ var rowSchema = z2.strictObject({
69
69
  seats: z2.array(z2.strictObject({ player, profile: z2.unknown() })),
70
70
  updatedAt: z2.number()
71
71
  });
72
+ var element = z2.lazy(
73
+ () => z2.union([patchSchema, z2.tuple([z2.unknown()]), z2.tuple([z2.record(z2.string(), element), z2.number().int().min(0)])])
74
+ );
75
+ var patchSchema = z2.record(z2.string(), z2.union([element, z2.literal(0)]));
72
76
  var surfaceOf = (world) => {
73
- const frame = z2.strictObject({
77
+ const head = {
74
78
  world: worldId,
75
79
  tick,
76
80
  ms: z2.number().int().min(0).optional(),
77
81
  epoch: z2.string().max(64).optional(),
78
- acks: z2.record(player, z2.number().int().min(0)),
79
- state: hostSchema(world.state)
80
- });
82
+ acks: z2.record(player, z2.number().int().min(0))
83
+ };
84
+ const count = z2.number().int().min(0);
85
+ const frame = z2.strictObject({ ...head, n: count.optional(), state: hostSchema(world.state) });
81
86
  const rate = z2.number().min(0);
82
87
  const n = z2.number().min(0);
83
88
  const stats = z2.strictObject({
@@ -116,7 +121,7 @@ var surfaceOf = (world) => {
116
121
  }
117
122
  },
118
123
  serverToClient: {
119
- "mp.state": { payload: frame },
124
+ "mp.state": { payload: z2.union([frame, z2.strictObject({ ...head, n: count, patch: patchSchema })]) },
120
125
  "mp.message": {
121
126
  payload: z2.strictObject({ world: worldId, message: world.message ? hostSchema(world.message) : z2.never() })
122
127
  },
@@ -127,7 +132,13 @@ var surfaceOf = (world) => {
127
132
  change: z2.enum(["joined", "left", "dropped", "resumed"])
128
133
  })
129
134
  },
130
- "mp.closed": { payload: z2.strictObject({ world: worldId, reason: z2.enum(["deleted", "replaced", "lost"]) }) }
135
+ "mp.closed": {
136
+ payload: z2.strictObject({
137
+ world: worldId,
138
+ reason: z2.enum(["deleted", "replaced", "lost", "removed"]),
139
+ detail: z2.string().optional()
140
+ })
141
+ }
131
142
  }
132
143
  };
133
144
  };
@@ -140,6 +151,7 @@ function multiplayerContract(world) {
140
151
  }
141
152
 
142
153
  export {
154
+ isJson,
143
155
  CommandRejected,
144
156
  reject,
145
157
  defineWorld,
package/dist/client.cjs CHANGED
@@ -366,6 +366,39 @@ var Predictor = class {
366
366
  }
367
367
  };
368
368
 
369
+ // src/patch.ts
370
+ function applyPatch(base, patch) {
371
+ const out = isPlainObject(base) ? { ...base } : {};
372
+ for (const key of Object.keys(patch)) {
373
+ if (key === "__proto__") continue;
374
+ const change = patch[key];
375
+ if (change === 0) delete out[key];
376
+ else if (Array.isArray(change)) out[key] = change.length === 2 ? applyArrayPatch(own(out, key), change) : change[0];
377
+ else if (change) out[key] = applyPatch(own(out, key), change);
378
+ }
379
+ return out;
380
+ }
381
+ var INDEX = /^(0|[1-9][0-9]*)$/;
382
+ function applyArrayPatch(base, [changes, length]) {
383
+ const out = Array.isArray(base) ? base.slice(0, length) : [];
384
+ for (const key of Object.keys(changes)) {
385
+ const index = Number(key);
386
+ if (!INDEX.test(key) || index >= length) continue;
387
+ const change = changes[key];
388
+ if (Array.isArray(change)) out[index] = change.length === 2 ? applyArrayPatch(out[index], change) : change[0];
389
+ else out[index] = applyPatch(out[index], change);
390
+ }
391
+ for (let index = out.length; index < length; index++) out[index] = null;
392
+ for (let index = 0; index < length; index++) if (!(index in out)) out[index] = null;
393
+ return out;
394
+ }
395
+ function own(object, key) {
396
+ return Object.prototype.hasOwnProperty.call(object, key) ? object[key] : void 0;
397
+ }
398
+ function isPlainObject(value) {
399
+ return typeof value === "object" && value !== null && !Array.isArray(value);
400
+ }
401
+
369
402
  // src/client.ts
370
403
  var log = (0, import_logtape.getLogger)(["super-line", "plugin-multiplayer", "client"]);
371
404
  var distance = (a, b) => {
@@ -406,7 +439,9 @@ function multiplayerClient(client, fragment, opts = {}) {
406
439
  let correction;
407
440
  let correctFrom;
408
441
  let frameAt = localNow();
442
+ let wire = first.frame;
409
443
  let sized;
444
+ let syncing = 0;
410
445
  let frameBytes = 0;
411
446
  const rate = { since: frameAt, frames: 0, perSecond: 0 };
412
447
  const emit = (type, event) => {
@@ -421,7 +456,7 @@ function multiplayerClient(client, fragment, opts = {}) {
421
456
  const adopt = (j, sent) => {
422
457
  const now = localNow();
423
458
  joined = j;
424
- latest = j.frame;
459
+ latest = wire = j.frame;
425
460
  clock.roundTrip(now - sent);
426
461
  clock.reading(j.frame.tick, j.tickRate, j.frame.ms, j.frame.epoch, now);
427
462
  buffer.update(j.frame.state, j.frame.tick, now);
@@ -507,20 +542,20 @@ function multiplayerClient(client, fragment, opts = {}) {
507
542
  if (entityId !== joined.seat || !game.lerp || !(joined.tickRate > 0)) return buffer.at(entityId);
508
543
  const now = localNow();
509
544
  const state = predictor.predicted(now);
510
- const own = game.entity?.(state, entityId);
511
- if (own === void 0) return void 0;
545
+ const own2 = game.entity?.(state, entityId);
546
+ if (own2 === void 0) return void 0;
512
547
  if (state !== glidedFrom) {
513
548
  glidedFrom = state;
514
- glide.to(own, now);
549
+ glide.to(own2, now);
515
550
  }
516
551
  return glide.at(now);
517
552
  },
518
553
  serverTick: (now) => clock.tick(now),
519
554
  stats() {
520
555
  const now = localNow();
521
- if (sized !== latest) {
522
- sized = latest;
523
- frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d: latest }));
556
+ if (sized !== wire) {
557
+ sized = wire;
558
+ frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d: wire }));
524
559
  }
525
560
  if (correctFrom !== void 0) {
526
561
  const after = predictor.predicted(now);
@@ -577,11 +612,37 @@ function multiplayerClient(client, fragment, opts = {}) {
577
612
  });
578
613
  }
579
614
  };
615
+ const sync = () => {
616
+ syncing++;
617
+ const sent = localNow();
618
+ dyn.mpJoin({ world: id }).then(
619
+ (j) => {
620
+ syncing--;
621
+ if (closed) return;
622
+ adopt(j, sent);
623
+ emit("frame", latest);
624
+ },
625
+ (error) => {
626
+ syncing--;
627
+ if (failedWith(error, "DISCONNECTED")) return;
628
+ log.warn("re-joining world {world} failed: {error}", { world: id, error });
629
+ handle.close("disconnected");
630
+ }
631
+ );
632
+ };
580
633
  const handle = {
581
634
  world,
582
635
  emit,
583
- frame(f) {
636
+ frame(received) {
584
637
  if (closed) return;
638
+ let f;
639
+ if ("patch" in received) {
640
+ if (syncing || received.n <= (latest.n ?? -1)) return;
641
+ if (received.n !== latest.n + 1) return sync();
642
+ const { patch, ...rest } = received;
643
+ f = { ...rest, state: applyPatch(latest.state, patch) };
644
+ } else f = received;
645
+ wire = received;
585
646
  const now = localNow();
586
647
  const made = predictor.made;
587
648
  correctFrom = game.entity && joined.tickRate > 0 && made && made.base === latest.state ? made.state : void 0;
@@ -602,21 +663,9 @@ function multiplayerClient(client, fragment, opts = {}) {
602
663
  if (closed) return;
603
664
  clock.reset();
604
665
  predictor.reconnected();
605
- const sent = localNow();
606
- dyn.mpJoin({ world: id }).then(
607
- (j) => {
608
- if (closed) return;
609
- adopt(j, sent);
610
- emit("frame", latest);
611
- },
612
- (error) => {
613
- if (failedWith(error, "DISCONNECTED")) return;
614
- log.warn("re-joining world {world} failed: {error}", { world: id, error });
615
- handle.close("disconnected");
616
- }
617
- );
666
+ sync();
618
667
  },
619
- close(reason) {
668
+ close(reason, detail) {
620
669
  if (closed) return;
621
670
  closed = reason;
622
671
  handles.delete(id);
@@ -629,7 +678,7 @@ function multiplayerClient(client, fragment, opts = {}) {
629
678
  predictor.clear();
630
679
  buffer.clear();
631
680
  glide.clear();
632
- emit("closed", { reason });
681
+ emit("closed", detail === void 0 ? { reason } : { reason, detail });
633
682
  }
634
683
  };
635
684
  const predictor = new Predictor(game, world);
@@ -647,7 +696,10 @@ function multiplayerClient(client, fragment, opts = {}) {
647
696
  "mp.seat",
648
697
  (e) => handles.get(e.world)?.emit("seat", { player: e.player, change: e.change })
649
698
  ),
650
- dyn.on("mp.closed", (e) => handles.get(e.world)?.close(e.reason)),
699
+ dyn.on(
700
+ "mp.closed",
701
+ (e) => handles.get(e.world)?.close(e.reason, e.detail)
702
+ ),
651
703
  dyn.onReconnect(() => {
652
704
  for (const h of handles.values()) h.rejoin();
653
705
  })
package/dist/client.d.cts CHANGED
@@ -16,8 +16,10 @@ interface WorldEvents<W extends AnyWorld> {
16
16
  code: string;
17
17
  reason?: string;
18
18
  };
19
+ /** `detail` is the server's reason for a `removed` seat. */
19
20
  closed: {
20
21
  reason: WorldCloseReason;
22
+ detail?: string;
21
23
  };
22
24
  }
23
25
  /** What a world handle measures, read with `world.stats()`. Durations are local milliseconds. */
package/dist/client.d.ts CHANGED
@@ -16,8 +16,10 @@ interface WorldEvents<W extends AnyWorld> {
16
16
  code: string;
17
17
  reason?: string;
18
18
  };
19
+ /** `detail` is the server's reason for a `removed` seat. */
19
20
  closed: {
20
21
  reason: WorldCloseReason;
22
+ detail?: string;
21
23
  };
22
24
  }
23
25
  /** What a world handle measures, read with `world.stats()`. Durations are local milliseconds. */