playertwo-sdk 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Player Two
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,65 @@
1
- # Temporary Holding Version
1
+ # playertwo-sdk
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
+ Player Two's game SDK for bundled code, with TypeScript types: trophies, stats, leaderboards, cloud saves, presence,
4
+ invites, add-ons, the player's avatar, travel between games with their party, and multiplayer rooms (voice chat,
5
+ worlds, replays and your own server code in room.js included), for games hosted on [Player Two](https://playertwo.lol).
6
+ Everything it offers, each with its part of the docs: https://playertwo.lol/llms.txt
7
+
8
+ The SDK itself is one script, `https://playertwo.lol/sdk/v1.js`. On Player Two it is already in your game's page;
9
+ `init()` uses that copy, and loads the script only when the page doesn't have it (on localhost, say, where its
10
+ stand-in answers every call and two tabs are two players).
11
+
12
+ ```
13
+ npm install playertwo-sdk
14
+ ```
15
+
16
+ ```ts
17
+ import { init } from "playertwo-sdk";
18
+
19
+ const p2 = await init();
20
+ await p2.trophies.unlock("first-win");
21
+
22
+ const room = await p2.rooms.join({ mode: "arena", size: 16 });
23
+ room.on("message:emoted", ({ id, kind }) => showEmote(id, kind));
24
+ room.send("emote", "wave");
25
+
26
+ const sync = room.sync(myMesh, { fields: ["position.x", "position.y", "position.z", "rotation.y"], rate: 20, delay: 100, angles: ["rotation.y"] });
27
+ sync.on("join", (id) => sync.bind(id, makeMesh(id)));
28
+ // every frame: sync.step();
29
+ ```
30
+
31
+ Only want the types for the script tag's global `PlayerTwo`? Add `"types": ["playertwo-sdk"]` to your `tsconfig.json`,
32
+ or put `/// <reference types="playertwo-sdk" />` at the top of a file.
33
+
34
+ ## A room's server: playertwo-sdk/room
35
+
36
+ `room.js` at the root of your build runs on Player Two's servers, one copy per room. It is pushed as it is, so plain
37
+ JavaScript with JSDoc types is the simplest:
38
+
39
+ ```js
40
+ // @ts-check
41
+ /** @typedef {import("playertwo-sdk/room").Room} Room */
42
+ /** @typedef {import("playertwo-sdk/room").Player} Player */
43
+
44
+ export const tickRate = 20;
45
+
46
+ /** @param {Room} room @param {Player} player */
47
+ export function onJoin(room, player) {
48
+ room.state.set("hello", player.handle);
49
+ }
50
+ ```
51
+
52
+ If you bundle it into one file yourself (from TypeScript, say), `defineRoom` types every hook at once:
53
+
54
+ ```ts
55
+ import { defineRoom } from "playertwo-sdk/room";
56
+
57
+ export const { tickRate, onCreate, onJoin, onLeave, onMessage, onSync, onTick } = defineRoom<{ coins: number }>({
58
+ tickRate: 20,
59
+ onCreate(room) { room.data.coins = 8; },
60
+ onSync(room, player, values) { return Math.abs(values["position.x"]) < 18 ? values : false; },
61
+ });
62
+ ```
63
+
64
+ Docs: [the SDK](https://playertwo.lol/docs/sdk) and [rooms](https://playertwo.lol/docs/sdk#rooms). A whole game to start
65
+ from: `npm create playertwo-game@latest my-game`.
package/index.d.ts ADDED
@@ -0,0 +1,692 @@
1
+ /**
2
+ * Types for Player Two's game SDK, https://playertwo.lol/sdk/v1.js (its source: public/sdk/v1.js in Player Two's code;
3
+ * keep these in step with its part 4, "the helpers the game uses", and part 4b, "rooms"). Docs: https://playertwo.lol/docs/sdk
4
+ *
5
+ * import { init } from "playertwo-sdk"; // or the global PlayerTwo, from the script tag
6
+ * const p2 = await init();
7
+ * const room = await p2.rooms.join({ mode: "arena", size: 16 });
8
+ *
9
+ * The types of a room's own server script (room.js) are in "playertwo-sdk/room".
10
+ */
11
+
12
+ /** Anything that goes through JSON: what messages, the room's state and saves carry. */
13
+ export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
14
+
15
+ /** Where the game is: on Player Two or in its app, on localhost (the stand-in), or anywhere else. */
16
+ export type Env = "p2" | "local" | "disabled";
17
+
18
+ /** Every refusal rejects with one of these. */
19
+ export interface P2Error extends Error {
20
+ /** "not-on-player-two", "offline", "timeout", "unknown-trophy", "too-soon", "demo", "read-first", "version",
21
+ "cooldown", "full", "empty", "too-big", "old-build", "not-yours", "signed-out", "session-ended", ... */
22
+ code: string;
23
+ /** The HTTP status behind it, or 0. */
24
+ status: number;
25
+ /** A save refused for its version: the version there now. */
26
+ version?: number;
27
+ [extra: string]: unknown;
28
+ }
29
+
30
+ /** The player, as your game knows them: `id` is theirs for your game only. */
31
+ export interface Player {
32
+ id: string;
33
+ handle: string;
34
+ name: string;
35
+ picture: string | null;
36
+ creature: string;
37
+ level: number;
38
+ }
39
+
40
+ export interface Game {
41
+ slug: string;
42
+ title: string;
43
+ }
44
+
45
+ /** The stand-in's own trophies, add-ons and params, on localhost (or wherever, with `force`). */
46
+ export interface LocalOptions {
47
+ trophies?: { key: string; name?: string; how?: string; tier?: number; hidden?: boolean }[];
48
+ addons?: { key: string; name?: string; about?: string; price?: number; owned?: boolean }[];
49
+ params?: Record<string, string>;
50
+ /** Use the stand-in wherever the game runs. */
51
+ force?: boolean;
52
+ }
53
+
54
+ export interface InitOptions {
55
+ /** Outside Player Two, fill the page with "Play this on Player Two" and stop. */
56
+ required?: boolean;
57
+ /** The Player Two app's local address (the app sets P2_BRIDGE itself). */
58
+ bridge?: string;
59
+ /** The stand-in's trophies, add-ons and params; true (or { force: true }) uses the stand-in wherever the game runs. */
60
+ local?: true | LocalOptions;
61
+ /** How long to wait for the player's page to answer, in ms (1500). */
62
+ timeout?: number;
63
+ }
64
+
65
+ export interface Me {
66
+ player: Player;
67
+ game: Game;
68
+ session: string;
69
+ test: boolean;
70
+ demo: boolean;
71
+ /** "web": Player Two's player; "desktop": the app. */
72
+ from: "web" | "desktop";
73
+ params: Record<string, string> | null;
74
+ }
75
+
76
+ export interface Progress {
77
+ into: number;
78
+ need: number;
79
+ }
80
+
81
+ export interface Trophy {
82
+ key: string;
83
+ name: string;
84
+ how: string;
85
+ tier: number;
86
+ xp: number;
87
+ hidden: boolean;
88
+ art: string;
89
+ share: number;
90
+ rarity: string;
91
+ /** When the player earned it (ms), and which player to earn it they were (No. 1 is the first). */
92
+ earned: { at: number; n: number | null; test?: boolean } | null;
93
+ }
94
+
95
+ export interface TrophyList {
96
+ trophies: Trophy[];
97
+ xp: number;
98
+ level: number;
99
+ progress?: Progress;
100
+ }
101
+
102
+ export interface Unlocked {
103
+ trophy: Trophy;
104
+ /** false if they had it already. */
105
+ new: boolean;
106
+ n: number | null;
107
+ /** pending: XP that waits until your game counts toward levels. */
108
+ xp: { gained: number; total: number; pending?: number };
109
+ level: number;
110
+ progress?: Progress;
111
+ /** The completion trophy, earned with this one. */
112
+ complete?: Trophy;
113
+ test?: boolean;
114
+ }
115
+
116
+ export interface Addon {
117
+ key: string;
118
+ name: string;
119
+ about: string;
120
+ price: number;
121
+ owned: boolean;
122
+ }
123
+
124
+ export interface StatsChange {
125
+ stats: Record<string, number>;
126
+ /** Trophies waiting on a stat, earned by this change. */
127
+ unlocked: Unlocked[];
128
+ }
129
+
130
+ export interface Board {
131
+ key: string;
132
+ name: string;
133
+ order: "high" | "low";
134
+ format: string;
135
+ [more: string]: unknown;
136
+ }
137
+
138
+ export interface Submitted {
139
+ board: Board;
140
+ value: number;
141
+ /** Only a player's best is kept. */
142
+ best: number;
143
+ new: boolean;
144
+ previous: number | null;
145
+ rank: number | null;
146
+ total: number | null;
147
+ }
148
+
149
+ export interface BoardRow {
150
+ rank: number;
151
+ value: number;
152
+ at: number;
153
+ player: { id: string; handle: string; name: string; picture: string | null };
154
+ me?: boolean;
155
+ }
156
+
157
+ export interface BoardList {
158
+ board: Board;
159
+ rows: BoardRow[];
160
+ total: number;
161
+ me: { rank: number; value: number } | null;
162
+ }
163
+
164
+ export interface SaveSlot {
165
+ slot: string;
166
+ size: number;
167
+ version: number;
168
+ at: number;
169
+ }
170
+
171
+ export interface SaveList {
172
+ slots: SaveSlot[];
173
+ max: number;
174
+ maxBytes: number;
175
+ }
176
+
177
+ /** A save read back, as bytes, text or JSON. */
178
+ export interface Save extends SaveSlot {
179
+ /** base64 */
180
+ data: string;
181
+ bytes(): Uint8Array;
182
+ text(): string;
183
+ json<T = any>(): T;
184
+ }
185
+
186
+ export interface Trophies {
187
+ list(): Promise<TrophyList>;
188
+ /** The player sees the toast; your game doesn't have to. */
189
+ unlock(key: string): Promise<Unlocked>;
190
+ }
191
+
192
+ export interface Addons {
193
+ /** Each add-on on sale. */
194
+ list(): Promise<Addon[]>;
195
+ /** Whether the player has it (one taken off sale stays theirs). */
196
+ has(key: string): Promise<boolean>;
197
+ }
198
+
199
+ export interface Stats {
200
+ /** Every stat. */
201
+ get(): Promise<{ stats: Record<string, number> }>;
202
+ /** One stat's value (0 if it was never set). */
203
+ get(key: string): Promise<number>;
204
+ set(key: string, value: number): Promise<StatsChange>;
205
+ /** By 1, or any whole number. */
206
+ add(key: string, amount?: number): Promise<StatsChange>;
207
+ }
208
+
209
+ export interface Scores {
210
+ submit(board: string, value: number): Promise<Submitted>;
211
+ /** The top 10, or around the player, or their friends. */
212
+ list(board: string, options?: { around?: "top" | "me"; friends?: boolean; limit?: number }): Promise<BoardList>;
213
+ }
214
+
215
+ export interface Saves {
216
+ list(): Promise<SaveList>;
217
+ get(slot: string): Promise<Save>;
218
+ /** Text, an object (kept as JSON) or bytes, up to 1 MB; { version } to have it refused if another device saved since. */
219
+ put(slot: string, data: string | Json | ArrayBuffer | ArrayBufferView, options?: { version?: number }): Promise<SaveSlot>;
220
+ delete(slot: string): Promise<{ deleted: true; slot: string }>;
221
+ }
222
+
223
+ /* ---------- rooms ---------- */
224
+
225
+ /** Someone in a room. */
226
+ export interface RoomPlayer {
227
+ /** The same as their p2.player.id. */
228
+ id: string;
229
+ handle: string;
230
+ name: string;
231
+ picture: string | null;
232
+ face: string;
233
+ level: number;
234
+ kind: string;
235
+ /** Their connection dropped; their seat is held for them (20 s). */
236
+ away: boolean;
237
+ /** Their rating in this game (room.result in room.js), once they have one. */
238
+ rating?: number;
239
+ }
240
+
241
+ export interface MatchOptions {
242
+ /** A name you choose ("duel", "coop-hard"). */
243
+ mode?: string;
244
+ /** 1 to 64 players. */
245
+ size?: number;
246
+ }
247
+
248
+ export interface JoinOptions extends MatchOptions {
249
+ /** A private room's six-letter code. */
250
+ code?: string;
251
+ /** The room you were in (room.id), to come back to it. */
252
+ room?: string;
253
+ resume?: string;
254
+ /** A match by skill: rooms of players rated near you first (the game's own ratings: room.result in room.js). */
255
+ skill?: boolean;
256
+ /** Keep the room as a replay, from its first player (a scripted room's code says so itself: room.record). */
257
+ record?: boolean;
258
+ }
259
+
260
+ /** One of the game's public rooms open now (p2.rooms.live), to watch. */
261
+ export interface LiveRoom { id: string; mode: string; size: number; players: number; watchers: number; skill: number | null; closed: boolean }
262
+ /** One of the game's replays (p2.rooms.replays). */
263
+ export interface ReplayInfo { id: string; room: string; mode: string; size: number; players: { id: string; handle: string; name: string }[]; from: number; ms: number }
264
+ /** A replay's controls (room.replay, on a room from p2.rooms.replay). */
265
+ export interface ReplayControls {
266
+ /** How long it is (ms), and when it began. */
267
+ readonly duration: number;
268
+ readonly from: number;
269
+ /** How far into it now (ms). */
270
+ time(): number;
271
+ play(): void;
272
+ pause(): void;
273
+ /** How fast it plays, 0.1 to 8 (1 when none is said); says what it is. */
274
+ speed(x?: number): number;
275
+ /** To a moment of it (ms): the room as it was then (read room.players again). */
276
+ seek(ms: number): void;
277
+ on(type: "end", fn: () => void): () => void;
278
+ on(type: "seek", fn: (ms: number) => void): () => void;
279
+ }
280
+
281
+ export interface Rooms {
282
+ /** A match ({ mode, size }: the fullest open room of that mode and size, one near the player first, or a new one), a
283
+ room by its code ({ code }), or the room you were in ({ room, resume }). Resolves once you are in. */
284
+ join(options?: JoinOptions): Promise<Room>;
285
+ /** A new private room; friends join it by room.code. */
286
+ create(options?: MatchOptions): Promise<Room>;
287
+ /** Your party's own room, with only its members. */
288
+ party(options?: MatchOptions): Promise<Room>;
289
+ /** A world the game keeps for good ("main" when unnamed), or an area of it: one room each, never closed, its shared
290
+ state (and a scripted world's room.data and room.store) kept while no one is in it. It plays the live build: a page
291
+ on an older one hears "close" with "update" (reload it). */
292
+ world(name?: string, options?: { area?: string }): Promise<Room>;
293
+ /** Watch a room (its id, from live() or a friend): you hear and draw everything its players do, with no seat, and can
294
+ say nothing (room.watching). */
295
+ watch(options: { room: string }): Promise<Room>;
296
+ /** The game's public rooms open now, fullest first. */
297
+ live(options?: { mode?: string }): Promise<LiveRoom[]>;
298
+ /** The game's replays, newest first (kept 200 a game). */
299
+ replays(options?: { limit?: number }): Promise<ReplayInfo[]>;
300
+ /** A replay, as a room that plays itself (room.replay): draw it with room.sync, room.objects and room.on. */
301
+ replay(id: string): Promise<Room>;
302
+ /** A bad connection, on purpose, to try your game on: this page's rooms from now on (on localhost too), until
303
+ simulate(null). The page's address can ask for one too: ?p2-net=150,30,0.02 (lag, jitter, loss). Says what it is
304
+ now. */
305
+ simulate(options: NetSimulation | null): NetSimulation | null;
306
+ }
307
+
308
+ export interface NetSimulation {
309
+ /** ms more there and back (half each way). */
310
+ lag?: number;
311
+ /** ms of give or take, each way. */
312
+ jitter?: number;
313
+ /** 0 to 1 of what is sent lost: held up on a socket as TCP holds it (a retransmit's wait, with everything after it),
314
+ gone on the fast lane. */
315
+ loss?: number;
316
+ }
317
+
318
+ /** Voice chat in a room: each player's microphone to everyone else in voice, through Player Two's servers. */
319
+ export interface Voice {
320
+ /** Who is in voice: their ids. */
321
+ readonly who: readonly string[];
322
+ /** Your microphone to everyone else in voice, and theirs to you (the browser asks for the microphone first):
323
+ resolves once you're in. Fails with "no-mic" (not allowed), "voice-full" (24 in voice already) or "no-voice". */
324
+ join(options?: { muted?: boolean }): Promise<void>;
325
+ /** Out of voice: your microphone let go, and no one heard. */
326
+ leave(): void;
327
+ /** Your microphone off (true) or on (false), or the other way: says whether it is off. */
328
+ mute(off?: boolean): boolean;
329
+ isMuted(): boolean;
330
+ /** How loud a player is to you, 0 (not at all) to 1; this page only. */
331
+ volume(id: string, volume: number): void;
332
+ /** Whether a player (or you) is speaking now. */
333
+ speaking(id: string): boolean;
334
+ }
335
+
336
+ export interface SendOptions {
337
+ /** One player's id, or a list; everyone else in the room when left out. */
338
+ to?: string | string[];
339
+ /** The fast lane: lossy, for updates that the next one replaces (where a thing is, not what happened). */
340
+ fast?: boolean;
341
+ }
342
+
343
+ /** A sync's values: each field's number, by its path ("position.x"). */
344
+ export type SyncValues = Record<string, number>;
345
+
346
+ export interface SyncOptions {
347
+ /** The numbers to send, as paths on the object ("position.x", "rotation.y"); for a THREE.Object3D, position x, y, z
348
+ and rotation.y when left out, otherwise ["x", "y"]. */
349
+ fields?: string[];
350
+ /** Sends a second (30; 15 in a match of more than 16 players). */
351
+ rate?: number;
352
+ /** How far behind (ms) bound objects are drawn, so there are updates to move between: "auto" (the default) is each
353
+ player's own, as late as their updates come and the time between two; a number fixes it for everyone. */
354
+ delay?: number | "auto";
355
+ /** How far this page sees, in the units of the fields named x and z (or y): in a big room (an area of a world)
356
+ players within it move every tick and those further once a second. 0: no limit. */
357
+ near?: number;
358
+ /** Fields that are angles in radians, which turn the short way round. */
359
+ angles?: string[];
360
+ /** A jump longer than this between two updates is a teleport, not a glide (0: never). */
361
+ snap?: number;
362
+ /** When a scripted room's code corrects you: "replay" (the default) puts you right as of the move it corrected and
363
+ plays your moves since on top, as Unreal does, so only how far off you were shows; "snap" puts you where the room
364
+ says (losing your movement since). */
365
+ fix?: "replay" | "snap";
366
+ }
367
+
368
+ export interface ObjectsOptions {
369
+ /** A value's name to a path on a bound object ({ x: "position.x", ry: "rotation.y" }). On a three.js object (one
370
+ with a position) x, y, z, qx to qw (a physics body's quaternion) and rx to rz go to its position, quaternion and
371
+ rotation by themselves; on anything else the name itself. */
372
+ map?: Record<string, string>;
373
+ /** Names that are angles in radians (by default ry, rx, rz, yaw, pitch, roll, angle, heading and rotation.*). */
374
+ angles?: string[];
375
+ /** How far behind (ms) objects are drawn: "auto" (each its own, as late as its updates come), or a number. */
376
+ delay?: number | "auto";
377
+ /** A jump longer than this between two updates is a teleport, not a glide (0: never). */
378
+ snap?: number;
379
+ }
380
+
381
+ /** What a scripted room's code moves (room.objects), drawn smoothly as players are. */
382
+ export interface RoomObjects {
383
+ /** The code made one (its values by name): make yours and bind() it. */
384
+ on(type: "add", fn: (key: string, values: Record<string, number>) => void): () => void;
385
+ /** The code ended one. */
386
+ on(type: "remove", fn: (key: string) => void): () => void;
387
+ /** Move `target` to where the object `key` is, on every step() (each value to its path: options.map). */
388
+ bind(key: string, target: object): void;
389
+ /** Once a frame: moves every bound object. */
390
+ step(): void;
391
+ keys(): string[];
392
+ /** An object's smoothed values now, by name, or null. */
393
+ values(key: string): Record<string, number> | null;
394
+ /** How long ago (ms) an object is drawn now. */
395
+ delay(key: string): number | null;
396
+ /** The room's time an object is drawn at now (room.past(key, at) in room.js). */
397
+ seen(key: string): number;
398
+ stop(): void;
399
+ }
400
+
401
+ export interface InputsOptions<S, I> {
402
+ /** Your player's state to start from. */
403
+ state: S;
404
+ /** This tick's input (what the player pressed, where they aim): anything JSON carries, small. */
405
+ input(): I;
406
+ /** Your game's own step, the one your room.js runs on the same input: change `state` (or return a new one). */
407
+ step(state: S, input: I | null, dt: number): S | void;
408
+ /** Ticks a second: your room.js's tickRate (60 when left out). */
409
+ rate?: number;
410
+ /** ms to ease a correction off over in what view() draws (0: none). */
411
+ smooth?: number;
412
+ }
413
+ /** Your player in an input-run room (room.inputs). */
414
+ export interface Inputs<S> {
415
+ /** Each frame: runs the ticks owed since the last (input read, sent, stepped). */
416
+ update(): void;
417
+ /** Your player's state as this page has run it, the newest tick. */
418
+ readonly state: S;
419
+ /** What to draw this frame: between the last two ticks, a correction eased off. */
420
+ view(): S;
421
+ /** { seq, acked, pending, waiting (the room's queue for you, lately at least), rewinds, pace }. */
422
+ stats(): { seq: number; acked: number; pending: number; waiting: number | null; rewinds: number; pace: number };
423
+ /** The room's code had your player elsewhere after input `at`: run again from there with the `replayed` since. */
424
+ on(type: "fix", fn: (state: S, info: { at: number; replayed: number }) => void): () => void;
425
+ stop(): void;
426
+ }
427
+
428
+ /** One object of yours sent to the room, and everyone else's moved smoothly (room.sync). */
429
+ export interface Sync {
430
+ /** A player's first values arrived (in the order of `fields`): bind something to them. */
431
+ on(type: "join", fn: (id: string, values: number[]) => void): () => void;
432
+ /** They left, or stopped syncing. */
433
+ on(type: "leave", fn: (id: string) => void): () => void;
434
+ /** A scripted room's code refused or corrected your move (onSync), or moved you (room.correct): your object was put
435
+ right, as of your move at `at`, by `by` (each field's change, your moves since on top; null when it was put
436
+ where the room says). `values`: where it is now. */
437
+ on(type: "fix", fn: (values: number[], info: { at: number | null; by: number[] | null }) => void): () => void;
438
+ /** Move `target`'s fields to where player `id` was `delay` ms ago, on every step(). */
439
+ bind(id: string, target: object): void;
440
+ /** Once a frame: sends yours at `rate`, and moves every bound object. */
441
+ step(): void;
442
+ /** A player's smoothed values now (in the order of `fields`), or null before their first update. */
443
+ values(id: string): number[] | null;
444
+ /** How long ago (ms) a player is drawn now, or null before their first update. */
445
+ delay(id: string): number | null;
446
+ /** The room's time a player is drawn at now: send it with a shot, and room.js can look back to then with
447
+ room.past(id, at) to judge the hit as this player saw it. */
448
+ seen(id: string): number;
449
+ /** Stop sending and moving. */
450
+ stop(): void;
451
+ }
452
+
453
+ export interface RoomStats {
454
+ /** There and back to the room (ms), measured every 2 s; null before the first. */
455
+ ping: number | null;
456
+ /** How much the ping varies (ms). */
457
+ jitter: number;
458
+ /** How fast messages go: by the fast lane, the room's socket, or other tabs on localhost. */
459
+ lane: "fast" | "socket" | "local";
460
+ /** Bytes a second, sent and heard. */
461
+ up: number;
462
+ down: number;
463
+ }
464
+
465
+ export interface Room {
466
+ /** The room's name (to come back to it with). */
467
+ readonly id: string;
468
+ /** A private room's code, or null. */
469
+ readonly code: string | null;
470
+ readonly mode: string;
471
+ readonly size: number;
472
+ /** Your id in the room (the same as p2.player.id). */
473
+ readonly me: string;
474
+ /** The host's id: whoever has been here longest. */
475
+ readonly host: string;
476
+ /** Who is here, you too. */
477
+ readonly players: RoomPlayer[];
478
+ /** The shared state, key to value. */
479
+ readonly state: Record<string, any>;
480
+ /** Whose each key is (the first writer's; a leaver's become the host's). */
481
+ readonly owners: Record<string, string | null>;
482
+ /** The build has a room.js, running on Player Two's servers: only it writes the shared state. */
483
+ readonly scripted: boolean;
484
+ /** Whether it is a world, kept for good (p2.rooms.world). */
485
+ readonly world: boolean;
486
+ /** Whether you're watching it (p2.rooms.watch, or a replay): you hear everything and can say nothing. */
487
+ readonly watching: boolean;
488
+ /** A replay's controls (a room from p2.rooms.replay). */
489
+ readonly replay?: ReplayControls;
490
+ /** Voice chat. */
491
+ readonly voice: Voice;
492
+
493
+ /** Send `data` as a message of `type` to everyone else, or to `to`. In a scripted room, room.js hears it (onMessage). */
494
+ send(type: string, data?: Json, options?: SendOptions): void;
495
+ /** A key of the shared state (null takes it away): set here at once, refused ("error", not-yours) if it isn't yours. */
496
+ set(key: string, value: Json | undefined): void;
497
+ get<T = any>(key: string): T | undefined;
498
+ /** Whether you are the host. */
499
+ isHost(): boolean;
500
+ /** There and back, in ms (it also sets room.now()). Rejected ("lost") when the line drops before the answer, or after
501
+ 10 s with none ("timeout"): a game pinging in a loop goes on after a reconnect. */
502
+ ping(): Promise<number>;
503
+ /** How the connection is now. */
504
+ stats(): RoomStats;
505
+ /** The room's clock, the same for every player in it (ms). */
506
+ now(): number;
507
+ /** An input-run room (its room.js runs everyone's inputs in onTick): your inputs sent a tick each and your own player
508
+ run on them at once by the same step as the code's, put right ("fix") when the code's state says otherwise. */
509
+ inputs<S = any, I = any>(options: InputsOptions<S, I>): Inputs<S>;
510
+ /** Leave for good (your seat goes to someone else). */
511
+ leave(): void;
512
+ /** Send `target`'s fields `rate` times a second on the fast lane, and move bound objects to where their players were. */
513
+ sync(target: object, options: SyncOptions): Sync;
514
+ /** A scripted room's objects (room.objects in room.js: what its code moves), drawn smoothly. */
515
+ objects(options?: ObjectsOptions): RoomObjects;
516
+ /** Whether the room's sockets are held by gates (a world's area, a match of over 16 seats). */
517
+ readonly gated: boolean;
518
+
519
+ on(type: "join" | "away" | "back", fn: (player: RoomPlayer) => void): () => void;
520
+ /** why: "left", "dropped", "kicked", ... */
521
+ on(type: "leave", fn: (player: RoomPlayer | { id: string }, why: string) => void): () => void;
522
+ on(type: "host", fn: (id: string) => void): () => void;
523
+ /** A key changed (value null: taken away); by: who wrote it. */
524
+ on(type: "state", fn: (key: string, value: any, by: string | null) => void): () => void;
525
+ /** `from` is the sending player's id, or null for the room's own code (a scripted room's room.js). */
526
+ on(type: "message", fn: (type: string, data: any, from: string | null) => void): () => void;
527
+ on(type: `message:${string}`, fn: (data: any, from: string | null) => void): () => void;
528
+ on(type: "reconnecting" | "reconnected", fn: () => void): () => void;
529
+ /** A scripted room opened again between far-apart players (room.between() in room.js), after "reconnected": its new id. */
530
+ on(type: "moved", fn: (id: string) => void): () => void;
531
+ /** Someone came into voice (true) or left it. */
532
+ on(type: "voice", fn: (id: string, inVoice: boolean) => void): () => void;
533
+ /** Someone in voice (or you) started speaking (true) or stopped. */
534
+ on(type: "speaking", fn: (id: string, speaking: boolean) => void): () => void;
535
+ /** You're out: "left", "closed", "lost", "replaced", "stopped", "time", "empty", ... */
536
+ on(type: "close", fn: (why: string) => void): () => void;
537
+ on(type: "error", fn: (error: P2Error) => void): () => void;
538
+ }
539
+
540
+ /* ---------- travel and avatars (docs: /docs/sdk/travel) ---------- */
541
+
542
+ /** A pixel of a critter: x and y from the top left of its 18 by 18 box, the colour as CSS (#rrggbb or hsl()). */
543
+ export type Pixel = [x: number, y: number, colour: string];
544
+
545
+ /** Who the player is, to dress your game's character with. */
546
+ export interface Avatar {
547
+ /** The same as p2.player.id. */
548
+ id: string;
549
+ handle: string;
550
+ name: string;
551
+ level: number;
552
+ picture: string | null;
553
+ critter: {
554
+ /** The name it is drawn from: the same name, the same critter, everywhere on Player Two. */
555
+ face: string;
556
+ /** Its box: 18 pixels a side. */
557
+ size: number;
558
+ /** The colour of the tile it stands on in Player Two's own pages. */
559
+ tile: string;
560
+ /** Every pixel of it, eyes open. */
561
+ pixels: Pixel[];
562
+ /** The same critter as a 3D model (.glb), standing on the origin and facing +Z: anyone may load it. */
563
+ model: string;
564
+ };
565
+ /** What they have on from the Plaza shop (a hat, a trail, a skin): each with its picture, and a 3D model when it has one
566
+ (none yet). */
567
+ worn: { key: string; name: string; slot: string; model: string | null; picture: string | null }[];
568
+ }
569
+
570
+ /** One of the player's things from Player Two's shop in the Plaza (p2.items.list). */
571
+ export interface Item {
572
+ key: string;
573
+ name: string;
574
+ kind: "skin" | "avatar" | "wear" | "emote" | "effect";
575
+ tier: "common" | "rare" | "epic" | "legendary" | "mythic" | "divine";
576
+ /** Where it goes: head, face, neck or back for a wearable; skin, avatar or effect; none for an emote. */
577
+ slot: string | null;
578
+ /** Whether the player has it on. */
579
+ worn: boolean;
580
+ /** A Divine item's number, of the 77 made. */
581
+ number: number | null;
582
+ /** An SVG of it; none for an emote or an effect. */
583
+ picture: string | null;
584
+ }
585
+
586
+ /** A door for your own menu (p2.travel.links). */
587
+ export interface Door {
588
+ slug: string;
589
+ title: string;
590
+ tagline: string;
591
+ /** Its key art (square), or its vertical poster. */
592
+ art: string;
593
+ /** Players in it now. */
594
+ players: number;
595
+ /** Up to five of the player's friends in it now. */
596
+ friends: { handle: string; name: string }[];
597
+ /** Why it is here: the party's leader brought the party to it, friends are in it, the player played it lately, or
598
+ it is busy. */
599
+ why: "party" | "friends" | "recent" | "popular";
600
+ free: boolean;
601
+ /** In the player's library: a paid game they don't own opens with its demo, or Buy. */
602
+ owned: boolean;
603
+ }
604
+
605
+ /** Travel to other games on Player Two, with the player's party. In Player Two's player on the web; elsewhere each
606
+ rejects with code "no-travel". */
607
+ export interface Travel {
608
+ /** To another game, by its address (playertwo.lol/game/<slug>): it is given p2.params (yours, then `from`, this
609
+ game's address, and `place`). Resolves as the player goes; this page is closed after. */
610
+ to(slug: string, options?: { params?: Record<string, string>; place?: string }): Promise<{ to: { slug: string; title: string }; params: Record<string, string> }>;
611
+ /** Back to the Plaza, where every game on Player Two has its screen. */
612
+ home(): Promise<{ to: { slug: null; title: string; url: string } }>;
613
+ /** The doors to show in your own menu: where the party is, the games friends are in, the player's recent ones, the
614
+ busiest (up to 12). */
615
+ links(): Promise<{ home: { title: string; url: string }; links: Door[] }>;
616
+ }
617
+
618
+ /* ---------- the SDK ---------- */
619
+
620
+ /** What PlayerTwo.init() answers: who is playing, and every call. */
621
+ export interface P2 {
622
+ env: Env;
623
+ player: Player | null;
624
+ game: Game | null;
625
+ /** True while its developer (or an admin) plays. */
626
+ test: boolean;
627
+ /** True in a demo: demos earn no trophies. */
628
+ demo: boolean;
629
+ /** The invite params the player came with (a join link, or a friend's Join), or null. */
630
+ params: Record<string, string> | null;
631
+ /** Any call by its name (the helpers are these). */
632
+ call<T = unknown>(method: string, args?: unknown[]): Promise<T>;
633
+ me(): Promise<Me>;
634
+ /** Who is playing, for your own servers: a JWT signed by Player Two (RS256, typed "p2-id"), ten minutes. */
635
+ identity(): Promise<string>;
636
+ /** A link to your game on Player Two that opens it with these params (up to 16 strings, 512 bytes). */
637
+ invite(params?: Record<string, string>): Promise<string>;
638
+ trophies: Trophies;
639
+ addons: Addons;
640
+ stats: Stats;
641
+ scores: Scores;
642
+ saves: Saves;
643
+ /** The line friends see, and with { join } what they join the player with. */
644
+ presence: { set(status: string | null, options?: { join?: Record<string, string> }): Promise<unknown> };
645
+ loading: { done(): Promise<unknown> };
646
+ gameplay: { start(): Promise<unknown>; stop(): Promise<unknown> };
647
+ /** Multiplayer with no server of your own. */
648
+ rooms: Rooms;
649
+ /** Who the player is, to dress your game's character with: their critter as pixels and as a 3D model, and what they
650
+ wear. */
651
+ avatar(): Promise<Avatar>;
652
+ /** What the player has from Player Two's shop in the Plaza (avatars, skins, wearables, emotes, effects), and what
653
+ they have on: a game can dress its own character in them. */
654
+ items: { list(): Promise<Item[]> };
655
+ /** Travel to other games on Player Two, with the player's party. */
656
+ travel: Travel;
657
+ /** Whether a small live picture of the game goes to the Plaza's screens while it is played here (Player Two does
658
+ it; the player can stop it). */
659
+ onAir: boolean;
660
+ /** Player Two's own layer over the game opened (true) or closed (false). */
661
+ on(type: "overlay", fn: (open: boolean) => void): () => void;
662
+ /** The player is about to close the game: what you keep should go now (a promise is waited for). */
663
+ on(type: "flush", fn: (closing: true) => void | Promise<unknown>): () => void;
664
+ }
665
+
666
+ /** window.PlayerTwo. */
667
+ export interface PlayerTwoGlobal {
668
+ readonly v: 1;
669
+ /** Certain once init has settled. */
670
+ env: Env;
671
+ /** Finds Player Two once: every call answers the same promise, and the first call's options are the ones used. */
672
+ init(options?: InitOptions): Promise<P2>;
673
+ /** Settles once init has been called and Player Two found, or not. */
674
+ readonly ready: Promise<P2>;
675
+ }
676
+
677
+ declare global {
678
+ /** Player Two's SDK, from https://playertwo.lol/sdk/v1.js (on Player Two, already in the page). */
679
+ var PlayerTwo: PlayerTwoGlobal;
680
+ }
681
+
682
+ /** Where the SDK is loaded from when the page doesn't have it. */
683
+ export const SDK_URL: string;
684
+
685
+ /** window.PlayerTwo, loading the script from `src` (SDK_URL) first if the page doesn't have it. */
686
+ export function load(src?: string): Promise<PlayerTwoGlobal>;
687
+
688
+ /** PlayerTwo.init(options), loading the SDK first if the page doesn't have it. */
689
+ export function init(options?: InitOptions): Promise<P2>;
690
+
691
+ declare const sdk: { init: typeof init; load: typeof load; SDK_URL: string };
692
+ export default sdk;
package/index.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // playertwo-sdk: Player Two's game SDK for code that is bundled (Vite, webpack, esbuild). The SDK itself is one
2
+ // script, https://playertwo.lol/sdk/v1.js, which Player Two's games host puts in a hosted game's page; this uses that
3
+ // copy when the page has it, and otherwise loads the script and waits for it. Types: index.d.ts. Docs:
4
+ // https://playertwo.lol/docs/sdk
5
+ //
6
+ // import { init } from "playertwo-sdk";
7
+ // const p2 = await init(); // the same as PlayerTwo.init(), with the same options
8
+
9
+ export const SDK_URL = "https://playertwo.lol/sdk/v1.js";
10
+
11
+ let loading = null;
12
+
13
+ function refused(code, message) {
14
+ const e = new Error(message);
15
+ e.code = code;
16
+ e.status = 0;
17
+ return e;
18
+ }
19
+
20
+ /** window.PlayerTwo, loading the script first if the page doesn't have it. */
21
+ export function load(src = SDK_URL) {
22
+ if (typeof window === "undefined" || typeof document === "undefined") return Promise.reject(refused("no-window", "Player Two's SDK runs in a browser."));
23
+ if (window.PlayerTwo && window.PlayerTwo.v === 1) return Promise.resolve(window.PlayerTwo);
24
+ if (loading) return loading;
25
+ loading = new Promise((resolve, reject) => {
26
+ const s = document.createElement("script");
27
+ s.src = src;
28
+ s.async = true;
29
+ s.onload = () => {
30
+ if (window.PlayerTwo && window.PlayerTwo.v === 1) resolve(window.PlayerTwo);
31
+ else { loading = null; reject(refused("offline", "Player Two's SDK loaded, but didn't start.")); }
32
+ };
33
+ s.onerror = () => {
34
+ loading = null;
35
+ s.remove();
36
+ reject(refused("offline", `Player Two's SDK couldn't be loaded from ${src}.`));
37
+ };
38
+ (document.head || document.documentElement).appendChild(s);
39
+ });
40
+ return loading;
41
+ }
42
+
43
+ /** PlayerTwo.init(options): who is playing, and every call. */
44
+ export function init(options) {
45
+ return load().then((PlayerTwo) => PlayerTwo.init(options));
46
+ }
47
+
48
+ export default { init, load, SDK_URL };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "playertwo-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "description": "Player Two's game SDK: trophies, leaderboards, saves and multiplayer rooms for games hosted on Player Two, with TypeScript types",
6
+ "type": "module",
7
+ "main": "./index.mjs",
8
+ "module": "./index.mjs",
9
+ "types": "./index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "default": "./index.mjs"
14
+ },
15
+ "./room": {
16
+ "types": "./room.d.ts",
17
+ "default": "./room.mjs"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "index.mjs",
23
+ "index.d.ts",
24
+ "room.mjs",
25
+ "room.d.ts",
26
+ "README.md"
27
+ ],
28
+ "sideEffects": false,
29
+ "keywords": [
30
+ "playertwo",
31
+ "game",
32
+ "multiplayer",
33
+ "rooms",
34
+ "threejs",
35
+ "sdk"
36
+ ],
37
+ "homepage": "https://playertwo.lol/docs/sdk"
38
+ }
package/room.d.ts ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Types for a room's own server script: room.js at the root of a build pushed to Player Two, run on Player Two's
3
+ * servers, one copy for each room (on localhost, the SDK's stand-in runs it in the first tab). It is an ES module that
4
+ * exports the hooks it needs; in a room with a room.js only the script writes the shared state.
5
+ *
6
+ * Plain JavaScript, no build step (room.js is pushed as it is):
7
+ *
8
+ * // @ts-check
9
+ * /** @param {import("playertwo-sdk/room").Room} room @param {import("playertwo-sdk/room").Player} player *\/
10
+ * export function onJoin(room, player) { room.state.set("hello", player.handle); }
11
+ *
12
+ * Or bundled into one file (TypeScript, say), with every hook typed at once:
13
+ *
14
+ * import { defineRoom } from "playertwo-sdk/room";
15
+ * export const { tickRate, onCreate, onJoin, onLeave, onMessage, onSync, onTick } = defineRoom<{ coins: number }>({
16
+ * tickRate: 20,
17
+ * onCreate(room) { room.data.coins = 8; },
18
+ * onSync(room, player, values) { return Math.abs(values["position.x"]) < 18 ? values : false; },
19
+ * });
20
+ */
21
+ /* (the same as index.d.ts's, kept here so a server script doesn't take in the browser's global PlayerTwo) */
22
+ /** Anything that goes through JSON: what messages and the room's state carry. */
23
+ export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
24
+ /** A sync's values: each field's number, by its path ("position.x"). */
25
+ export type SyncValues = Record<string, number>;
26
+
27
+ /** Someone in the room, as room.js sees them. */
28
+ export interface Player {
29
+ id: string;
30
+ handle: string;
31
+ name: string;
32
+ level: number;
33
+ /** What the game kept of them with room.save (in any of its rooms, any time before), or null. */
34
+ saved: Json | null;
35
+ /** Their rating in this game (room.result moves it; 1500 before their first match). */
36
+ rating?: number;
37
+ }
38
+
39
+ /** What room.js is handed: the room it runs for. `D` is what you keep in room.data. */
40
+ /** A physics body room.objects.set takes as it is: Rapier's (translation() and rotation()), or one with a position and
41
+ a quaternion. */
42
+ export type PhysicsBody =
43
+ | { translation(): { x: number; y: number; z?: number }; rotation(): { x: number; y: number; z: number; w: number } | number }
44
+ | { position: { x: number; y: number; z?: number }; quaternion: { x: number; y: number; z: number; w: number } };
45
+
46
+ export interface Room<D extends object = Record<string, any>> {
47
+ /** Who is here. */
48
+ readonly players: readonly Player[];
49
+ /** One of them, or null. */
50
+ player(id: string): Player | null;
51
+ /** A message to every page in the room, or to `to` (an id, or a list). Pages hear it with room.on("message:<type>"). */
52
+ send(type: string, data?: Json, options?: { to?: string | string[] }): void;
53
+ /** The shared state every page reads (room.get, "state"); only room.js writes it. null takes a key away. */
54
+ readonly state: {
55
+ get<T = any>(key: string): T | undefined;
56
+ set(key: string, value: Json | undefined): void;
57
+ };
58
+ /** Take a player out of the room. */
59
+ kick(id: string, why?: string): void;
60
+ /** Where a player (or an object, by its key) was at the room's time `at` (from the last second), by field name: with
61
+ the time a shot was seen at (the page's sync.seen(id) or objects.seen(key)), judge the hit as the shooter saw it.
62
+ null: nothing of it. */
63
+ past(id: string, at?: number): SyncValues | number[] | null;
64
+ /** Put a player somewhere yourself (knocked back, pulled, teleported), by field name (or a list): as of their last
65
+ move the room took, so their page plays its moves since on top (they feel the push, not a jump back) and everyone
66
+ else sees them there at once. False before their first move. */
67
+ correct(id: string, values: SyncValues | number[]): boolean;
68
+ /** In an input-run room: the player's state after this step (onTick), sent to their page about 30 times a second
69
+ with the number of their last input it ran; their page runs its inputs again from it when it had them elsewhere. */
70
+ confirm(id: string, state: Json): void;
71
+ /** A match's outcome, best first (each place an id, or a list of those level), or ids by score: every player's rating
72
+ moves by it (Elo, every two compared), as player.rating, and players are matched by it ({ skill: true }). */
73
+ result(places: (string | string[])[] | Record<string, number>): void;
74
+ /** Closed to matching while a match is under way (false), and open again so its empty places are filled (true). */
75
+ open(on?: boolean): void;
76
+ /** Keep the room as a replay from now (true), until record(false) or the room closes (up to 30 minutes). */
77
+ record(on?: boolean): void;
78
+ /** What your code moves (enemies, projectiles, a platform), drawn smoothly on every page (room.objects() there):
79
+ up to 1000 a room, their values numbers by name (up to 32 names). In a big room each page gets those near it
80
+ every tick and the rest once a second. They live with your code: set them again in onStart after a restart. */
81
+ readonly objects: {
82
+ /** Make it, or move it: the values given change, the others stay. A physics body as it is (Rapier's, or anything
83
+ with a position and a quaternion: cannon-es, three.js) sets x, y, z and qx, qy, qz, qw (Rapier 2D: x, y and
84
+ angle). Set again unchanged (a body asleep), it is sent once more, then not until it moves. */
85
+ set(key: string, values: Record<string, number> | PhysicsBody): void;
86
+ get(key: string): Record<string, number> | undefined;
87
+ delete(key: string): void;
88
+ keys(): string[];
89
+ };
90
+ /** Close the room: every page hears "close" with `why`. */
91
+ close(why?: string): void;
92
+ /** Open the room again between its players when they are far apart (where your code decides hits, the one nearest
93
+ the room has the edge): in the region nearest the furthest of them, every page moved there by itself
94
+ ("reconnecting", "reconnected", "moved"). Your code starts again there as after a restart, with room.data and the
95
+ shared state (onCreate doesn't run again; what lives only in your module's own variables doesn't come along).
96
+ Players near each other stay where they are; once a minute at most. Call it as a match starts, say. */
97
+ between(): void;
98
+ /** Yours to keep things in, for as long as the room is open (a world's: for good). */
99
+ data: D;
100
+ /** The room's own key-value store, read and written at once, for what doesn't fit in data (a world's map, its
101
+ chests); a world's is kept for good, through every new build. Values are anything JSON. */
102
+ readonly store: {
103
+ get<T = any>(key: string): T | undefined;
104
+ set(key: string, value: Json | undefined): void;
105
+ delete(key: string): void;
106
+ /** Its keys starting with `prefix`, in order (up to `limit`, 1000). */
107
+ keys(prefix?: string, limit?: number): string[];
108
+ };
109
+ /** Keep what the game knows of a player on Player Two's servers, for good (up to 64 KB): their player.saved in any
110
+ of the game's rooms and worlds from then on. null forgets it. */
111
+ save(id: string, data: Json | null): void;
112
+ /** The room's clock (ms), the same as the pages' room.now(). */
113
+ now(): number;
114
+ /** To the room's log, in your studio. */
115
+ log(...args: unknown[]): void;
116
+ }
117
+
118
+ /** Every hook room.js may export. */
119
+ export interface RoomScript<D extends object = Record<string, any>> {
120
+ /** onTick calls a second, 1 to 60. */
121
+ tickRate?: number;
122
+ /** How far every player sees others move every tick (further: once a second), in the units of the fields room.sync
123
+ names x and z (or y): for big rooms, an area of a world. Over any page's own `near`. */
124
+ near?: number;
125
+ /** The room opened. */
126
+ onCreate?(room: Room<D>): void;
127
+ /** The code started: after onCreate the first time, and again after a new version, a restart or room.between()
128
+ (what lives only in your module's variables, and room.objects, start empty: set them again from room.data). */
129
+ onStart?(room: Room<D>): void;
130
+ onJoin?(room: Room<D>, player: Player): void;
131
+ /** why: "left", "dropped", "kicked", ... */
132
+ onLeave?(room: Room<D>, player: Player, why: string): void;
133
+ /** What a page sent with room.send(type, data). */
134
+ onMessage?(room: Room<D>, player: Player, type: string, data: Json): void;
135
+ /** A player's movement (room.sync), before anyone else gets it: the values to pass on (changed or not), or false to
136
+ drop them. A dropped or changed move is put right on the player's own page by itself (room.sync's "fix"). */
137
+ onSync?(room: Room<D>, player: Player, values: SyncValues): SyncValues | false;
138
+ /** tickRate times a second; dt in seconds. */
139
+ /** `inputs`: in an input-run room (its pages send room.inputs), each player's input for this step, by id (none when
140
+ theirs didn't come in time); dt is then always 1 / tickRate, the steps kept to real time. */
141
+ onTick?(room: Room<D>, dt: number, inputs: Record<string, any>): void;
142
+ }
143
+
144
+ /** Types every hook at once: answers `script` as it is. */
145
+ export function defineRoom<D extends object = Record<string, any>>(script: RoomScript<D>): RoomScript<D>;
package/room.mjs ADDED
@@ -0,0 +1,6 @@
1
+ // playertwo-sdk/room: for a room's server script (room.js). Types: room.d.ts.
2
+
3
+ /** Types every hook at once (in an editor that reads room.d.ts): answers `script` as it is. */
4
+ export function defineRoom(script) {
5
+ return script;
6
+ }