@super-line/plugin-multiplayer 0.0.0-stage → 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 ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ Generated from conventional commits by [git-cliff](https://git-cliff.org) —
4
+ run `pnpm changelog` rather than editing by hand.
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
+
12
+ ## [plugin-multiplayer-v0.1.0] — 2026-11-29
13
+
14
+ ### Features
15
+
16
+ - **plugin-multiplayer:** Publishable manifest, license, README corrections ([3091b97])
17
+ - **plugin-multiplayer:** Client and server stats, lazy correction ([60e4384])
18
+ - **plugin-multiplayer:** Server-run game worlds ([739d7da])
19
+
20
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,414 @@
1
- # Temporary Holding Version
1
+ # @super-line/plugin-multiplayer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 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
+ code runs in one Node process, which hosts many worlds, and on Cloudflare, with one Durable Object per world.
7
+
8
+ ```bash
9
+ pnpm add @super-line/plugin-multiplayer
10
+ ```
11
+
12
+ Guides: [run a game world](https://super-line.dogar.biz/how-to/plugin-multiplayer) ·
13
+ [game worlds on Cloudflare](https://super-line.dogar.biz/how-to/multiplayer-on-cloudflare) ·
14
+ [measure and tune](https://super-line.dogar.biz/how-to/multiplayer-measure-and-tune) ·
15
+ [tutorial](https://super-line.dogar.biz/tutorials/build-a-multiplayer-game) ·
16
+ [how it works](https://super-line.dogar.biz/concepts/server-ticked-worlds).
17
+
18
+ > **0.x.** The API may change between minor versions.
19
+
20
+ ## The game
21
+
22
+ A game is a plain object of functions over its state. The schemas are any Standard Schema with a synchronous
23
+ validator; zod is used below.
24
+
25
+ ```ts
26
+ // world.ts: imported by the server and the browser
27
+ import * as z from 'zod'
28
+ import { defineWorld } from '@super-line/plugin-multiplayer'
29
+
30
+ const player = z.object({ name: z.string(), x: z.number(), y: z.number(), ix: z.number(), iy: z.number() })
31
+
32
+ export const arena = defineWorld({
33
+ state: z.object({ players: z.record(z.string(), player) }),
34
+ command: z.object({ x: z.number().min(-1).max(1), y: z.number().min(-1).max(1) }),
35
+ profile: z.object({ name: z.string().max(64) }),
36
+ tickRate: 30, // ticks a second; leave it out and the world only reacts to commands
37
+ sendRate: 10, // frames a second, at most tickRate; default min(10, tickRate)
38
+ maxPlayers: 10,
39
+
40
+ initialState: () => ({ players: {} }),
41
+ onJoin(s, { player: id, profile }) {
42
+ s.players[id] = { name: profile.name, x: 3, y: 3, ix: 0, iy: 0 }
43
+ },
44
+ onLeave(s, { player: id }) {
45
+ delete s.players[id]
46
+ },
47
+ onCommand(s, input, { player: id }) {
48
+ const me = s.players[id]
49
+ if (me) Object.assign(me, { ix: input.x, iy: input.y })
50
+ },
51
+ onTick(s, { dt }) {
52
+ for (const p of Object.values(s.players)) {
53
+ p.x += p.ix * 7 * dt
54
+ p.y += p.iy * 7 * dt
55
+ }
56
+ },
57
+
58
+ // What the client draws: an entity per id, and how to blend two of them.
59
+ entity: (s, id): { x: number; y: number } | undefined => {
60
+ const p = s.players[id]
61
+ return p && { x: p.x, y: p.y }
62
+ },
63
+ lerp: (a, b, t) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
64
+ })
65
+ ```
66
+
67
+ - Functions change the state **in place**. Call `reject(code, reason?)` inside `onCommand` to refuse a command:
68
+ the state goes back to what it was before the command, and the sender gets
69
+ `{ applied: false, code, reason }`. If `onCommand` throws anything else, the result is `{ applied: false, code: 'INTERNAL' }`
70
+ and the error is logged. A throw in `onTick` is logged and the loop goes on.
71
+ - Every function gets one context: `tick`, `now`, `players`, `predicting`, and `send(player, message)` /
72
+ `broadcast(message)` for the optional `message` schema. Join, leave and command add `player` and `profile`;
73
+ tick adds `dt` (always `1 / tickRate` seconds). Messages are sent only after the function returns, and are
74
+ dropped if the command is rejected.
75
+ - The browser runs `onCommand` and `predict ?? onTick` to predict its own moves. Keep them free of anything only
76
+ the server knows: while predicting, `ctx.players` is just your own seat, `ctx.profile` is `undefined`, and
77
+ `send`/`broadcast` do nothing. Pass a separate `predict` when the tick does work the client cannot repeat.
78
+ - `defineWorld` throws a `TypeError` for a `maxPlayers` that is not positive, a `tickRate` outside `(0, 60]`, a
79
+ `sendRate` above `tickRate`, and an `initialState()` that is not plain JSON.
80
+ - A player id is the seat's principal (below). It is a key in the state, so every player sees it. Entity ids
81
+ share the space with player ids: name a non-player entity something no principal can be (`'ball'` next to
82
+ UUIDs).
83
+
84
+ ## Wiring
85
+
86
+ ```ts
87
+ // contract.ts
88
+ import { defineContract } from '@super-line/core'
89
+ import { multiplayerContract } from '@super-line/plugin-multiplayer'
90
+ import { arena } from './world.js'
91
+
92
+ export const arenaContract = multiplayerContract(arena)
93
+ export const contract = defineContract({ roles: { user: {} }, plugins: [arenaContract] })
94
+ ```
95
+
96
+ ```ts
97
+ // server.ts: one Node process, any number of worlds
98
+ import { createServer } from 'node:http'
99
+ import { createSuperLineServer } from '@super-line/server'
100
+ import { webSocketServerTransport } from '@super-line/transport-websocket'
101
+ import { memoryCollections } from '@super-line/collections-memory'
102
+ import { multiplayer } from '@super-line/plugin-multiplayer/server'
103
+
104
+ const mp = multiplayer({
105
+ world: arena,
106
+ onlyWorld: null, // host any world id
107
+ authorize: ({ player }) => ({ profile: { name: player } }), // who may take a seat; return false to refuse
108
+ })
109
+
110
+ const server = createServer()
111
+ createSuperLineServer(contract, {
112
+ transports: [webSocketServerTransport({ server })],
113
+ collections: memoryCollections(), // required: each world is saved as a row
114
+ authenticate: () => ({ role: 'user', ctx: {} }),
115
+ plugins: [mp.plugin],
116
+ })
117
+ server.listen(8080)
118
+ ```
119
+
120
+ ```ts
121
+ // browser
122
+ import { multiplayerClient } from '@super-line/plugin-multiplayer/client'
123
+
124
+ const mp = multiplayerClient(client, arenaContract) // one wrapper per connected super-line client
125
+ const world = await mp.join('lobby')
126
+
127
+ function onRenderFrame(input: { x: number; y: number }) {
128
+ void world.send(input) // at most one command goes out per tick
129
+ const me = world.at(world.seat) // your own character, predicted
130
+ for (const id of Object.keys(world.state.players)) {
131
+ if (id !== world.seat) draw(id, world.at(id)) // everyone else, interpolated
132
+ }
133
+ draw(world.seat, me)
134
+ }
135
+
136
+ world.on('closed', ({ reason }) => showNotice(reason))
137
+ ```
138
+
139
+ The server kit's options:
140
+
141
+ | Option | Meaning |
142
+ | --- | --- |
143
+ | `world` | the game from `defineWorld` |
144
+ | `onlyWorld` | `string \| null`, required. A string is the one world id this server hosts; any other id gets `WRONG_WORLD` before `authorize` runs. `null` hosts any id. |
145
+ | `authorize` | required. `({ joiner, player, world, exists, ctx }) => false \| true \| { profile }`, may be async. Deny-by-default: `false` or a missing hook refuses the join with `FORBIDDEN`; a throw fails the join with that error if it is a `SuperLineError`, otherwise with `INTERNAL`. When the world has a `profile` schema, return `{ profile }`; it is validated and reaches the game as `ctx.profile`. `exists` is whether the world has been created. |
146
+ | `seatGraceMs` | how long a dropped player's seat is held, default 30 000; `0` leaves at once |
147
+ | `saveEveryMs` | how often a ticking world saves, default 5 000 |
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). |
151
+
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).
155
+
156
+ ### The world handle
157
+
158
+ `world.state` and `world.tick` are the latest server state. `world.predicted` is that state with your unconfirmed
159
+ commands re-applied and the tick run forward. `world.at(id)` is the entity to draw now: your own from the
160
+ prediction, glided over one tick so a correction bends instead of jumping, and everyone else's from a buffer of
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
162
+ behind. `world.serverTick()` is the estimated server tick. Events: `frame`, `message`, `seat`
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.
165
+
166
+ `send(command)` resolves `{ applied: true, tick }` or `{ applied: false, code, reason? }`. In a ticking world a
167
+ newer `send` before the next tick resolves the waiting one with `SUPERSEDED`. It rejects with `DISCONNECTED` while
168
+ the connection is down: a command is never queued across a reconnect. A command counts as confirmed when a
169
+ state frame shows the server handled it, not when its response arrives, because the two can arrive in either
170
+ order.
171
+
172
+ While seated in a ticking world the client sends a clock request every 5 s (`clockEveryMs`). It feeds
173
+ `serverTick()` and, on Cloudflare, is a real message to the world's object. A world with no tick is never pinged.
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
+
247
+ ## Stats
248
+
249
+ Both halves measure what the plugin does, for a profiling overlay or a load run.
250
+
251
+ **Client.** `world.stats()` returns plain numbers and is cheap enough to call every render frame: the counters
252
+ and rolling values are kept where frames, commands and clock replies already arrive, and a frame arriving computes
253
+ nothing for stats. Two numbers are worked out on the first `stats()` read after a frame, and only then: the frame
254
+ size, which re-encodes the latest frame as JSON, and `correction`, which needs the prediction from the new frame.
255
+ That is the prediction the next render reads anyway (`world.at(world.seat)` or `world.predicted`), so a page that
256
+ draws its own player pays nothing extra; a client that never predicts, such as a headless bot, never pays for it.
257
+
258
+ | Field | Unit | Meaning |
259
+ | --- | --- | --- |
260
+ | `rttMs` | ms | smoothed round trip of the join and clock requests; undefined until one returns |
261
+ | `clockErrorMs` | ms | how far clock readings land from the client's estimate of the server clock, smoothed |
262
+ | `renderDelayTicks`, `renderDelayMs` | ticks, ms | how far behind the server clock other entities are drawn |
263
+ | `latenessMs`, `jitterMs` | ms | how late frames arrive against the clock, and how much that varies |
264
+ | `predictionLeadTicks` | ticks | how far ahead of the latest frame the prediction runs |
265
+ | `framesPerSecond` | per second | state frames received over about the last second |
266
+ | `frameBytes` | bytes | the latest frame's size on the wire with the default JSON serializer; with patch frames, the patch |
267
+ | `msSinceFrame` | ms | time since the latest frame arrived |
268
+ | `pendingCommands` | count | sent and not yet shown in a frame, rejected or failed |
269
+ | `commandsSent`, `commandsApplied`, `commandsRejected`, `commandsSuperseded` | count | since the handle opened |
270
+ | `correction` | state units | how far the latest frame moved your predicted entity: the straight-line distance over the numeric fields `entity` returns, between the last prediction made from the previous frame and the first made from the new one. It keeps its last value when nothing predicted between two frames, and is undefined without `entity` or before a comparison |
271
+ | `server` | | the server's numbers from the latest clock reply, or undefined |
272
+
273
+ **Server.** With `multiplayer({ ..., stats: true })` each world records the numbers below. They ride in every
274
+ clock reply, so a client sees them as `world.stats().server`, and the kit returns them as `stats` from
275
+ `worlds.get` and `worlds.list` for a live world. With `stats` off nothing is measured and the clock reply carries
276
+ only `tick`, `ms` and `epoch`. The type is `WorldServerStats`.
277
+
278
+ | Field | Unit | Meaning |
279
+ | --- | --- | --- |
280
+ | `tickMsLast` | ms | the latest tick: `onTick` and sending the messages it queued, not the frame |
281
+ | `tickMsMean`, `tickMsMax` | ms | over the last completed one-second window |
282
+ | `ticksPerSecond` | per second | ticks run in that window |
283
+ | `ticksDropped` | ticks | catch-up ticks skipped because the loop fell more than 5 behind, since the world loaded |
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 |
285
+ | `framesSent` | count | state frames sent since the world loaded |
286
+ | `seated`, `away` | count | seats held by a connection, and seats held for a dropped player |
287
+ | `saveMs` | ms | the latest save |
288
+
289
+ Measuring a frame costs one extra encode per send, which is why `stats` is off by default. Durations use
290
+ `performance.now()`. On deployed Cloudflare Workers, `performance.now()` and `Date.now()` only advance after I/O,
291
+ so a tick that does no I/O reads `0` there; `wrangler dev` advances them normally. Use Cloudflare's CPU profiling
292
+ for production tick cost. A save writes to the object's SQLite, and may read `0` for the same reason.
293
+
294
+ To refresh the server's numbers about once a second, ping faster:
295
+ `multiplayerClient(client, arenaContract, { clockEveryMs: 1000 })`. `WorldStats` and `WorldServerStats` are both
296
+ exported from `/client`.
297
+
298
+ ## Seats
299
+
300
+ A seat belongs to the connection's principal, which is the server's `identify(conn)` and falls back to the
301
+ connection id.
302
+
303
+ - **A drop** puts the seat away for `seatGraceMs`. The character stays in the world, others get `seat` with
304
+ `dropped`, and the game hears `onLeave` only when the grace runs out. An away seat still counts toward
305
+ `maxPlayers` and keeps the world ticking.
306
+ - **A reconnect** within the grace resumes the seat without `authorize` or `onJoin`. The wrapper re-joins on its
307
+ own after a reconnect.
308
+ - **The newest connection wins.** The same principal joining from a second connection takes the seat. The first
309
+ gets `closed` with `replaced`, and its socket stays open. Its handle is closed for good: to play there again,
310
+ build a new wrapper and join.
311
+ - **Without `identify`**, every connection is its own principal, so a reconnect is a new player and the old
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.
315
+
316
+ ## Saving
317
+
318
+ Each world is one row in the server-only collection `mpWorlds`, which the contract fragment declares: the state,
319
+ the tick and the seats with their profiles. Clients get `FORBIDDEN` on it. The row is written on join, on leave
320
+ and grace expiry, every `saveEveryMs` while ticking, and after every applied command in a world with no tick. A crash or restart can lose up to one save interval of a ticking world.
321
+
322
+ On the first join after a restart the world loads from its row with every seat away. A row whose state no longer
323
+ fits the state schema fails the join with `STATE_INVALID` until the host fixes or deletes it.
324
+
325
+ A server with no `collections` backend refuses to start. A row is capped at 2 MB on Durable Object SQLite. A save
326
+ over a backend's limit is logged on every attempt, and the world keeps running from memory.
327
+
328
+ ## On Cloudflare
329
+
330
+ Run one Durable Object per world, reached by the world's name, and set `onlyWorld` to that name so one socket can
331
+ only ever reach its own world. Route only the socket path to the object, because every request wakes it:
332
+
333
+ ```ts
334
+ // worker.ts
335
+ import { cloudflareCollections } from '@super-line/collections-cloudflare'
336
+ import { createDurableNode, routeToNode } from '@super-line/transport-cloudflare'
337
+
338
+ export class WorldNode extends createDurableNode((ctx, _env: Env, base) => {
339
+ const name = ctx.id.name
340
+ if (name === undefined) throw new Error('WorldNode must be reached by name')
341
+ const collections = cloudflareCollections(ctx.storage, contract.collections)
342
+ const mp = multiplayer({ world: arena, onlyWorld: name, authorize: () => ({ profile: { name: 'guest' } }) })
343
+ return createSuperLineServer(contract, {
344
+ ...base,
345
+ collections,
346
+ authenticate: () => ({ role: 'user', ctx: {} }),
347
+ plugins: [mp.plugin],
348
+ })
349
+ }) {}
350
+
351
+ export default {
352
+ fetch: (request, env) => {
353
+ const url = new URL(request.url)
354
+ const world = url.searchParams.get('world')
355
+ if (url.pathname !== '/ws' || !world) return new Response('Not found', { status: 404 })
356
+ return routeToNode(request, env.WORLDS, { name: () => world })
357
+ },
358
+ } satisfies ExportedHandler<Env>
359
+ ```
360
+
361
+ A world with no tick can hibernate between commands, once no dropped player's seat is still inside its grace
362
+ period (that timer keeps the object awake). When an object wakes, the plugin reloads each world from its
363
+ row and gives the surviving connections their seats back without `onJoin`. The clock restarts from the saved
364
+ tick, so a ticking world loses what happened since its last save, and everyone gets one fresh frame. A connection with nothing saved to go back to gets `closed` with `lost`.
365
+ `ctx.id.name` is set on a wake caused by a WebSocket message, so the host does not need to store the name.
366
+
367
+ ## With plugin-auth
368
+
369
+ The plugin works with any `identify`. With plugin-auth the principal is the user id, so a seat follows the account
370
+ across reloads and tabs. A common `authorize` admits only signed-in users and hands the game their name:
371
+
372
+ ```ts
373
+ const authKit = auth({ contract, collections, defaultRoles: ['user'] })
374
+ const mp = multiplayer({
375
+ world: arena,
376
+ onlyWorld: name,
377
+ authorize: async ({ joiner }) => {
378
+ if (!joiner.userId) return false
379
+ const user = await authKit.users.get(joiner.userId)
380
+ return user && !user.deletedAt ? { profile: { name: user.displayName } } : false
381
+ },
382
+ })
383
+ createSuperLineServer(contract, {
384
+ ...base,
385
+ collections,
386
+ authenticate: authKit.authenticate,
387
+ identify: authKit.identify,
388
+ plugins: [authKit.plugin, mp.plugin],
389
+ })
390
+ ```
391
+
392
+ Put `authContract()` beside the game's fragment in `defineContract({ plugins })`. A plugin-auth sign-in or
393
+ sign-out replaces the super-line client, so build a new `multiplayerClient` on each new client. Leave the world
394
+ before signing out if the character should disappear at once instead of after the grace. If plugin-auth runs
395
+ inside each world's Durable Object, accounts belong to that world.
396
+
397
+ ## Limits and what is not in this version
398
+
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`.
402
+ - A world lives on one node. In a Node cluster, every player of a world must reach the same process.
403
+ - Commands are not exactly-once across a reconnect: one sent while disconnected fails.
404
+ - One row per world, capped by the backend, with no splitting.
405
+ - No physics engine (collision is the game's code), and no matchmaking, lockstep, spectators or lag compensation.
406
+ - TypeScript client only. There is no written wire protocol yet.
407
+ - The client imports no rendering engine: the game decides what an entity is and how to blend one.
408
+
409
+ See [`examples/game-arena`](../../examples/game-arena): a PlayCanvas arena on Cloudflare with plugin-auth.
410
+
411
+ ## Third-party code
412
+
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).
@@ -0,0 +1,36 @@
1
+ # Third-party notices
2
+
3
+ ## Tickflare
4
+
5
+ Parts of this package are ported from [Tickflare](https://github.com/Giamme/tickflare) (commit `2dc0fa0`):
6
+
7
+ | File in this package | Ported from |
8
+ | --- | --- |
9
+ | `src/client/clock.ts` | `src/client/clock.ts` (`ServerClock`) |
10
+ | `src/client/predict.ts` | `src/client/predict.ts` (`Predictor`) |
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`) |
13
+
14
+ ```
15
+ MIT License
16
+
17
+ Copyright (c) 2026 Giamme
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ of this software and associated documentation files (the "Software"), to deal
21
+ in the Software without restriction, including without limitation the rights
22
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ copies of the Software, and to permit persons to whom the Software is
24
+ furnished to do so, subject to the following conditions:
25
+
26
+ The above copyright notice and this permission notice shall be included in all
27
+ copies or substantial portions of the Software.
28
+
29
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ SOFTWARE.
36
+ ```
@@ -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
+ };