tickflare 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.
Files changed (125) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/buffered.d.ts +88 -0
  11. package/dist/client/buffered.js +229 -0
  12. package/dist/client/buffered.js.map +1 -0
  13. package/dist/client/clock.d.ts +36 -0
  14. package/dist/client/clock.js +83 -0
  15. package/dist/client/clock.js.map +1 -0
  16. package/dist/client/draft.d.ts +17 -0
  17. package/dist/client/draft.js +133 -0
  18. package/dist/client/draft.js.map +1 -0
  19. package/dist/client/index.d.ts +182 -0
  20. package/dist/client/index.js +496 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/interpolate.d.ts +31 -0
  23. package/dist/client/interpolate.js +59 -0
  24. package/dist/client/interpolate.js.map +1 -0
  25. package/dist/client/lockstep.d.ts +86 -0
  26. package/dist/client/lockstep.js +339 -0
  27. package/dist/client/lockstep.js.map +1 -0
  28. package/dist/client/matchmaking.d.ts +21 -0
  29. package/dist/client/matchmaking.js +55 -0
  30. package/dist/client/matchmaking.js.map +1 -0
  31. package/dist/client/pacer.d.ts +22 -0
  32. package/dist/client/pacer.js +65 -0
  33. package/dist/client/pacer.js.map +1 -0
  34. package/dist/client/predict.d.ts +75 -0
  35. package/dist/client/predict.js +203 -0
  36. package/dist/client/predict.js.map +1 -0
  37. package/dist/client/token.d.ts +10 -0
  38. package/dist/client/token.js +15 -0
  39. package/dist/client/token.js.map +1 -0
  40. package/dist/lockstep.d.ts +154 -0
  41. package/dist/lockstep.js +140 -0
  42. package/dist/lockstep.js.map +1 -0
  43. package/dist/patch.d.ts +54 -0
  44. package/dist/patch.js +186 -0
  45. package/dist/patch.js.map +1 -0
  46. package/dist/protocol.d.ts +268 -0
  47. package/dist/protocol.js +54 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/dist/server/accounts.d.ts +320 -0
  50. package/dist/server/accounts.js +1223 -0
  51. package/dist/server/accounts.js.map +1 -0
  52. package/dist/server/delta.d.ts +50 -0
  53. package/dist/server/delta.js +426 -0
  54. package/dist/server/delta.js.map +1 -0
  55. package/dist/server/frames.d.ts +15 -0
  56. package/dist/server/frames.js +23 -0
  57. package/dist/server/frames.js.map +1 -0
  58. package/dist/server/gateway.d.ts +80 -0
  59. package/dist/server/gateway.js +144 -0
  60. package/dist/server/gateway.js.map +1 -0
  61. package/dist/server/index.d.ts +21 -0
  62. package/dist/server/index.js +22 -0
  63. package/dist/server/index.js.map +1 -0
  64. package/dist/server/limiter.d.ts +12 -0
  65. package/dist/server/limiter.js +43 -0
  66. package/dist/server/limiter.js.map +1 -0
  67. package/dist/server/lockstep.d.ts +127 -0
  68. package/dist/server/lockstep.js +549 -0
  69. package/dist/server/lockstep.js.map +1 -0
  70. package/dist/server/matches.d.ts +31 -0
  71. package/dist/server/matches.js +69 -0
  72. package/dist/server/matches.js.map +1 -0
  73. package/dist/server/matchmaker.d.ts +121 -0
  74. package/dist/server/matchmaker.js +479 -0
  75. package/dist/server/matchmaker.js.map +1 -0
  76. package/dist/server/room.d.ts +402 -0
  77. package/dist/server/room.js +1896 -0
  78. package/dist/server/room.js.map +1 -0
  79. package/dist/server/signals.d.ts +18 -0
  80. package/dist/server/signals.js +37 -0
  81. package/dist/server/signals.js.map +1 -0
  82. package/dist/server/storage.d.ts +117 -0
  83. package/dist/server/storage.js +330 -0
  84. package/dist/server/storage.js.map +1 -0
  85. package/dist/server/tokens.d.ts +74 -0
  86. package/dist/server/tokens.js +117 -0
  87. package/dist/server/tokens.js.map +1 -0
  88. package/dist/server/tracked.d.ts +47 -0
  89. package/dist/server/tracked.js +270 -0
  90. package/dist/server/tracked.js.map +1 -0
  91. package/dist/world.d.ts +20 -0
  92. package/dist/world.js +21 -0
  93. package/dist/world.js.map +1 -0
  94. package/package.json +74 -4
  95. package/src/binary.ts +496 -0
  96. package/src/client/accounts.ts +423 -0
  97. package/src/client/buffered.ts +264 -0
  98. package/src/client/clock.ts +86 -0
  99. package/src/client/draft.ts +138 -0
  100. package/src/client/index.ts +631 -0
  101. package/src/client/interpolate.ts +60 -0
  102. package/src/client/lockstep.ts +398 -0
  103. package/src/client/matchmaking.ts +61 -0
  104. package/src/client/pacer.ts +67 -0
  105. package/src/client/predict.ts +239 -0
  106. package/src/client/token.ts +22 -0
  107. package/src/lockstep.ts +285 -0
  108. package/src/patch.ts +188 -0
  109. package/src/protocol.ts +300 -0
  110. package/src/server/accounts.ts +1474 -0
  111. package/src/server/delta.ts +467 -0
  112. package/src/server/frames.ts +23 -0
  113. package/src/server/gateway.ts +213 -0
  114. package/src/server/index.ts +86 -0
  115. package/src/server/limiter.ts +41 -0
  116. package/src/server/lockstep.ts +617 -0
  117. package/src/server/matches.ts +99 -0
  118. package/src/server/matchmaker.ts +537 -0
  119. package/src/server/room.ts +1999 -0
  120. package/src/server/signals.ts +46 -0
  121. package/src/server/storage.ts +392 -0
  122. package/src/server/tokens.ts +184 -0
  123. package/src/server/tracked.ts +260 -0
  124. package/src/world.ts +29 -0
  125. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,193 @@
1
+ import type { TokenSource } from "./token.js";
2
+ /** Where the accounts API is and how the session travels. Every option has a default. */
3
+ export interface AccountClientOptions {
4
+ /** Where the Worker is, e.g. "https://game.example.com". Defaults to the page's own origin. */
5
+ baseUrl?: string;
6
+ /** Where the accounts API is served. Default "/api/accounts". */
7
+ prefix?: string;
8
+ /**
9
+ * How the session travels. "cookie" (the default in browsers): an HttpOnly
10
+ * cookie the page's scripts never see. "bearer" (the default elsewhere):
11
+ * the client keeps the session token and sends it with every request; pass
12
+ * `session` to restore one and `onSession` to keep it.
13
+ */
14
+ mode?: "cookie" | "bearer";
15
+ /** A session token to start with, in bearer mode. */
16
+ session?: string | null;
17
+ /** Called when the session token changes, in bearer mode: store it to stay signed in. */
18
+ onSession?(token: string | null): void;
19
+ /** Where to keep the guest identity between visits. Defaults to `localStorage` when there is one. */
20
+ storage?: KeyValueStore | null;
21
+ /** The fetch to use. Defaults to the global one. */
22
+ fetch?: typeof fetch;
23
+ }
24
+ /** The signed-in player's own account, as `GET /me` returns it. */
25
+ export interface Account {
26
+ /** The player id. A guest who registered keeps theirs. */
27
+ id: string;
28
+ /** The account name. */
29
+ name: string;
30
+ /** The email address, if one was given. */
31
+ email: string | null;
32
+ /** When the account was made, in epoch milliseconds. */
33
+ createdAt: number;
34
+ /** Whether the account has a recovery code. */
35
+ recoveryCode: boolean;
36
+ /** Every data key the player has, private ones included. */
37
+ data: Record<string, unknown>;
38
+ /** Every stat the player has. */
39
+ stats: Record<string, number>;
40
+ }
41
+ /** What anyone may see of a player. */
42
+ export interface Profile {
43
+ /** The player id. */
44
+ id: string;
45
+ /** The account name. */
46
+ name: string;
47
+ /** When the account was made, in epoch milliseconds. */
48
+ createdAt: number;
49
+ /** The data keys the game made public. */
50
+ data: Record<string, unknown>;
51
+ /** Every stat the player has. */
52
+ stats: Record<string, number>;
53
+ }
54
+ /** One line of a leaderboard. */
55
+ export interface LeaderboardLine {
56
+ /** 1 for the highest value. Players with the same value share a rank. */
57
+ rank: number;
58
+ /** The player id. */
59
+ id: string;
60
+ /** The account name. */
61
+ name: string;
62
+ /** The player's value of the stat. */
63
+ value: number;
64
+ }
65
+ /** A page of a leaderboard, highest value first. */
66
+ export interface Leaderboard {
67
+ /** The stat it ranks. */
68
+ stat: string;
69
+ /** This page's lines. */
70
+ entries: LeaderboardLine[];
71
+ /** Players with a value for this stat, in total. */
72
+ total: number;
73
+ }
74
+ /** A guest identity: a player id with a join token, before or instead of an account. */
75
+ export interface Guest {
76
+ /** The guest's player id. */
77
+ id: string;
78
+ /** A join token for `id`. */
79
+ token: string;
80
+ /** When the token stops working, in epoch milliseconds. */
81
+ expiresAt: number;
82
+ /** When the client renews it for the same id, in epoch milliseconds. */
83
+ renewAt: number;
84
+ }
85
+ /** A request the accounts API refused. `code` is machine-readable, e.g. "name_taken" or "invalid_credentials". */
86
+ export declare class AccountRequestError extends Error {
87
+ /** The HTTP status, e.g. 409. */
88
+ readonly status: number;
89
+ /** Machine-readable, e.g. `name_taken`. */
90
+ readonly code: string;
91
+ constructor(status: number, code: string, message: string);
92
+ }
93
+ /** The part of `localStorage` the client uses. */
94
+ export interface KeyValueStore {
95
+ /** The value under `key`, or null. */
96
+ getItem(key: string): string | null;
97
+ /** Stores `value` under `key`. */
98
+ setItem(key: string, value: string): void;
99
+ /** Removes `key`. */
100
+ removeItem(key: string): void;
101
+ }
102
+ /**
103
+ * The client side of `Accounts`: a guest identity until the player signs up,
104
+ * sign-up and sign-in, the player's own data, profiles and leaderboards.
105
+ *
106
+ * const accounts = new AccountClient();
107
+ * await accounts.restore();
108
+ * const room = new RoomClient(url, { token: accounts.tokenSource });
109
+ */
110
+ export declare class AccountClient {
111
+ #private;
112
+ constructor(options?: AccountClientOptions);
113
+ /** The signed-in account, once `restore`, `login` or `register` has found one. */
114
+ get account(): Account | null;
115
+ /** Whether someone is signed in. */
116
+ get signedIn(): boolean;
117
+ /** The player id to use: the account's, else the guest's, else undefined. */
118
+ get playerId(): string | undefined;
119
+ /** Calls `listener` whenever the signed-in account changes. Returns a function that stops it. */
120
+ onChange(listener: (account: Account | null) => void): () => void;
121
+ /** Finds out whether a session is still good. Call once at startup. */
122
+ restore(): Promise<Account | null>;
123
+ /** Creates an account and signs in. A guest who registers keeps their player id. */
124
+ register(input: {
125
+ name: string;
126
+ password: string;
127
+ email?: string;
128
+ }): Promise<Account>;
129
+ /** Signs in. Rejects with `AccountRequestError` (`invalid_credentials`, `too_many_attempts`) if it cannot. */
130
+ login(name: string, password: string): Promise<Account>;
131
+ /** Ends the session, on the server and here. */
132
+ logout(): Promise<void>;
133
+ /** Changes the password. Every other session of the account is signed out. */
134
+ changePassword(current: string, next: string): Promise<void>;
135
+ /**
136
+ * Makes a recovery code and returns it: show it to the player once, to
137
+ * keep somewhere safe. It sets a new password with `recover`, with no
138
+ * email involved, and replaces the code the account had. Needs the password.
139
+ */
140
+ createRecoveryCode(password: string): Promise<string>;
141
+ /**
142
+ * Sets a new password with a recovery code, and signs in. The code is used
143
+ * up. Rejects with `AccountRequestError` (`invalid_code`, `too_many_attempts`).
144
+ */
145
+ recover(name: string, code: string, password: string): Promise<Account>;
146
+ /**
147
+ * Asks for a password reset link to be sent to the account with this name,
148
+ * or to every account with this email address. It resolves whether or not
149
+ * there is such an account, so as not to tell. Rejects with `not_enabled`
150
+ * if the game does not send email.
151
+ */
152
+ forgotPassword(who: {
153
+ name: string;
154
+ } | {
155
+ email: string;
156
+ }): Promise<void>;
157
+ /** Sets a new password with the token from a reset link, and signs in. Rejects with `invalid_token`. */
158
+ resetPassword(token: string, password: string): Promise<Account>;
159
+ /** Takes another name. */
160
+ rename(name: string): Promise<Account>;
161
+ /** Sets the email address, or removes it with null. Needs the password. */
162
+ setEmail(password: string, email: string | null): Promise<Account>;
163
+ /** Deletes the account and everything stored with it. */
164
+ deleteAccount(password: string): Promise<void>;
165
+ /** Everything the server keeps about the signed-in player. */
166
+ exportData(): Promise<Record<string, unknown>>;
167
+ /**
168
+ * A guest identity, made on first use and kept in `storage`. Its token is
169
+ * renewed, for the same player id, once it is half way to expiring; a
170
+ * guest who stays away until it has expired starts over as a new player.
171
+ */
172
+ guest(): Promise<Guest>;
173
+ /** A short-lived join token for a room or queue, for the signed-in player. */
174
+ joinToken(scope?: string): Promise<string>;
175
+ /**
176
+ * For `RoomClient`'s `token` option: a join token for the signed-in player,
177
+ * or the guest's token for anyone else.
178
+ */
179
+ readonly tokenSource: TokenSource;
180
+ /** The signed-in player's value under `key`, or undefined. */
181
+ getData<T = unknown>(key: string): Promise<T | undefined>;
182
+ /** Stores a value under a key the game lets players write. */
183
+ setData(key: string, value: unknown): Promise<void>;
184
+ /** Removes a value under a key the game lets players write. */
185
+ deleteData(key: string): Promise<void>;
186
+ /** A player's public profile, or null if there is no such account. */
187
+ profile(playerId: string): Promise<Profile | null>;
188
+ /** A page of the leaderboard for `stat`, highest first. */
189
+ leaderboard(stat: string, page?: {
190
+ limit?: number;
191
+ offset?: number;
192
+ }): Promise<Leaderboard>;
193
+ }
@@ -0,0 +1,306 @@
1
+ /** A request the accounts API refused. `code` is machine-readable, e.g. "name_taken" or "invalid_credentials". */
2
+ export class AccountRequestError extends Error {
3
+ /** The HTTP status, e.g. 409. */
4
+ status;
5
+ /** Machine-readable, e.g. `name_taken`. */
6
+ code;
7
+ constructor(status, code, message) {
8
+ super(message);
9
+ this.name = "AccountRequestError";
10
+ this.status = status;
11
+ this.code = code;
12
+ }
13
+ }
14
+ const GUEST_KEY = "tickflare.guest";
15
+ /** What a browser has, seen from code that is not typed for one. */
16
+ const browser = globalThis;
17
+ /**
18
+ * The client side of `Accounts`: a guest identity until the player signs up,
19
+ * sign-up and sign-in, the player's own data, profiles and leaderboards.
20
+ *
21
+ * const accounts = new AccountClient();
22
+ * await accounts.restore();
23
+ * const room = new RoomClient(url, { token: accounts.tokenSource });
24
+ */
25
+ export class AccountClient {
26
+ #account = null;
27
+ #base;
28
+ #mode;
29
+ #fetch;
30
+ #storage;
31
+ #onSession;
32
+ #session;
33
+ #guest = null;
34
+ #listeners = new Set();
35
+ constructor(options = {}) {
36
+ const inBrowser = browser.document !== undefined;
37
+ const origin = options.baseUrl ?? browser.location?.origin ?? "";
38
+ this.#base = `${origin.replace(/\/+$/, "")}${(options.prefix ?? "/api/accounts").replace(/\/+$/, "")}`;
39
+ this.#mode = options.mode ?? (inBrowser ? "cookie" : "bearer");
40
+ this.#session = options.session ?? null;
41
+ this.#onSession = options.onSession;
42
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
43
+ this.#storage = options.storage !== undefined ? options.storage : (browser.localStorage ?? null);
44
+ }
45
+ /** The signed-in account, once `restore`, `login` or `register` has found one. */
46
+ get account() {
47
+ return this.#account;
48
+ }
49
+ /** Whether someone is signed in. */
50
+ get signedIn() {
51
+ return this.#account !== null;
52
+ }
53
+ /** The player id to use: the account's, else the guest's, else undefined. */
54
+ get playerId() {
55
+ return this.#account?.id ?? this.#guest?.id ?? this.#storedGuest()?.id;
56
+ }
57
+ /** Calls `listener` whenever the signed-in account changes. Returns a function that stops it. */
58
+ onChange(listener) {
59
+ this.#listeners.add(listener);
60
+ return () => this.#listeners.delete(listener);
61
+ }
62
+ /** Finds out whether a session is still good. Call once at startup. */
63
+ async restore() {
64
+ if (this.#mode === "bearer" && !this.#session)
65
+ return this.#setAccount(null);
66
+ try {
67
+ return this.#setAccount(await this.#request("GET", "/me"));
68
+ }
69
+ catch (error) {
70
+ if (error instanceof AccountRequestError && error.status === 401) {
71
+ this.#setSession(null);
72
+ return this.#setAccount(null);
73
+ }
74
+ throw error;
75
+ }
76
+ }
77
+ /** Creates an account and signs in. A guest who registers keeps their player id. */
78
+ async register(input) {
79
+ const guest = this.#guest ?? this.#storedGuest();
80
+ const body = guest && guest.expiresAt > Date.now() ? { ...input, guestToken: guest.token } : input;
81
+ const result = await this.#request("POST", "/register", body);
82
+ this.#forgetGuest();
83
+ this.#setSession(result.token);
84
+ this.#setAccount(result.account);
85
+ return result.account;
86
+ }
87
+ /** Signs in. Rejects with `AccountRequestError` (`invalid_credentials`, `too_many_attempts`) if it cannot. */
88
+ async login(name, password) {
89
+ const result = await this.#request("POST", "/login", { name, password });
90
+ this.#setSession(result.token);
91
+ this.#setAccount(result.account);
92
+ return result.account;
93
+ }
94
+ /** Ends the session, on the server and here. */
95
+ async logout() {
96
+ try {
97
+ await this.#request("POST", "/logout");
98
+ }
99
+ finally {
100
+ this.#setSession(null);
101
+ this.#setAccount(null);
102
+ }
103
+ }
104
+ /** Changes the password. Every other session of the account is signed out. */
105
+ async changePassword(current, next) {
106
+ const result = await this.#request("POST", "/password", { current, next });
107
+ this.#setSession(result.token);
108
+ this.#setAccount(result.account);
109
+ }
110
+ /**
111
+ * Makes a recovery code and returns it: show it to the player once, to
112
+ * keep somewhere safe. It sets a new password with `recover`, with no
113
+ * email involved, and replaces the code the account had. Needs the password.
114
+ */
115
+ async createRecoveryCode(password) {
116
+ const result = await this.#request("POST", "/recovery-code", { password });
117
+ if (this.#account)
118
+ this.#setAccount({ ...this.#account, recoveryCode: true });
119
+ return result.code;
120
+ }
121
+ /**
122
+ * Sets a new password with a recovery code, and signs in. The code is used
123
+ * up. Rejects with `AccountRequestError` (`invalid_code`, `too_many_attempts`).
124
+ */
125
+ async recover(name, code, password) {
126
+ const result = await this.#request("POST", "/recover", { name, code, password });
127
+ this.#setSession(result.token);
128
+ this.#setAccount(result.account);
129
+ return result.account;
130
+ }
131
+ /**
132
+ * Asks for a password reset link to be sent to the account with this name,
133
+ * or to every account with this email address. It resolves whether or not
134
+ * there is such an account, so as not to tell. Rejects with `not_enabled`
135
+ * if the game does not send email.
136
+ */
137
+ async forgotPassword(who) {
138
+ await this.#request("POST", "/forgot", who);
139
+ }
140
+ /** Sets a new password with the token from a reset link, and signs in. Rejects with `invalid_token`. */
141
+ async resetPassword(token, password) {
142
+ const result = await this.#request("POST", "/reset", { token, password });
143
+ this.#setSession(result.token);
144
+ this.#setAccount(result.account);
145
+ return result.account;
146
+ }
147
+ /** Takes another name. */
148
+ async rename(name) {
149
+ const account = await this.#request("POST", "/name", { name });
150
+ this.#account = account;
151
+ return account;
152
+ }
153
+ /** Sets the email address, or removes it with null. Needs the password. */
154
+ async setEmail(password, email) {
155
+ const account = await this.#request("POST", "/email", { password, email });
156
+ this.#account = account;
157
+ return account;
158
+ }
159
+ /** Deletes the account and everything stored with it. */
160
+ async deleteAccount(password) {
161
+ await this.#request("DELETE", "/me", { password });
162
+ this.#setSession(null);
163
+ this.#setAccount(null);
164
+ }
165
+ /** Everything the server keeps about the signed-in player. */
166
+ async exportData() {
167
+ return this.#request("GET", "/export");
168
+ }
169
+ /**
170
+ * A guest identity, made on first use and kept in `storage`. Its token is
171
+ * renewed, for the same player id, once it is half way to expiring; a
172
+ * guest who stays away until it has expired starts over as a new player.
173
+ */
174
+ async guest() {
175
+ const known = this.#guest ?? this.#storedGuest();
176
+ if (known && known.renewAt > Date.now())
177
+ return (this.#guest = known);
178
+ const guest = await this.#request("POST", "/guest", known ? { token: known.token } : undefined);
179
+ this.#guest = guest;
180
+ try {
181
+ this.#storage?.setItem(GUEST_KEY, JSON.stringify(guest));
182
+ }
183
+ catch {
184
+ // Storage full or blocked: the guest lasts for this visit.
185
+ }
186
+ return guest;
187
+ }
188
+ /** A short-lived join token for a room or queue, for the signed-in player. */
189
+ async joinToken(scope) {
190
+ const result = await this.#request("POST", "/token", scope === undefined ? {} : { scope });
191
+ return result.token;
192
+ }
193
+ /**
194
+ * For `RoomClient`'s `token` option: a join token for the signed-in player,
195
+ * or the guest's token for anyone else.
196
+ */
197
+ tokenSource = async (room) => {
198
+ if (this.#account)
199
+ return this.joinToken(room);
200
+ return (await this.guest()).token;
201
+ };
202
+ /** The signed-in player's value under `key`, or undefined. */
203
+ async getData(key) {
204
+ try {
205
+ return (await this.#request("GET", `/data/${encodeURIComponent(key)}`)).value;
206
+ }
207
+ catch (error) {
208
+ if (error instanceof AccountRequestError && error.status === 404)
209
+ return undefined;
210
+ throw error;
211
+ }
212
+ }
213
+ /** Stores a value under a key the game lets players write. */
214
+ async setData(key, value) {
215
+ await this.#request("PUT", `/data/${encodeURIComponent(key)}`, { value });
216
+ if (this.#account)
217
+ this.#account = { ...this.#account, data: { ...this.#account.data, [key]: value } };
218
+ }
219
+ /** Removes a value under a key the game lets players write. */
220
+ async deleteData(key) {
221
+ await this.#request("DELETE", `/data/${encodeURIComponent(key)}`);
222
+ if (this.#account) {
223
+ const { [key]: _removed, ...data } = this.#account.data;
224
+ this.#account = { ...this.#account, data };
225
+ }
226
+ }
227
+ /** A player's public profile, or null if there is no such account. */
228
+ async profile(playerId) {
229
+ try {
230
+ return await this.#request("GET", `/players/${encodeURIComponent(playerId)}`);
231
+ }
232
+ catch (error) {
233
+ if (error instanceof AccountRequestError && error.status === 404)
234
+ return null;
235
+ throw error;
236
+ }
237
+ }
238
+ /** A page of the leaderboard for `stat`, highest first. */
239
+ async leaderboard(stat, page = {}) {
240
+ const query = new URLSearchParams();
241
+ if (page.limit !== undefined)
242
+ query.set("limit", String(page.limit));
243
+ if (page.offset !== undefined)
244
+ query.set("offset", String(page.offset));
245
+ const suffix = query.size > 0 ? `?${query}` : "";
246
+ return this.#request("GET", `/leaderboards/${encodeURIComponent(stat)}${suffix}`);
247
+ }
248
+ async #request(method, path, body) {
249
+ const headers = {};
250
+ if (body !== undefined)
251
+ headers["Content-Type"] = "application/json";
252
+ if (this.#mode === "bearer" && this.#session)
253
+ headers.Authorization = `Bearer ${this.#session}`;
254
+ const init = {
255
+ method,
256
+ headers,
257
+ body: body === undefined ? undefined : JSON.stringify(body),
258
+ };
259
+ // So the cookie also travels when the API is on another origin. Not set otherwise:
260
+ // runtimes other than browsers may not know the option.
261
+ if (this.#mode === "cookie")
262
+ init.credentials = "include";
263
+ const response = await this.#fetch(`${this.#base}${path}`, init);
264
+ if (response.status === 204)
265
+ return undefined;
266
+ const payload = (await response.json().catch(() => null));
267
+ if (!response.ok) {
268
+ throw new AccountRequestError(response.status, payload?.error ?? "request_failed", payload?.message ?? response.statusText);
269
+ }
270
+ return payload;
271
+ }
272
+ #setSession(token) {
273
+ if (this.#mode !== "bearer" || this.#session === token)
274
+ return;
275
+ this.#session = token;
276
+ this.#onSession?.(token);
277
+ }
278
+ #setAccount(account) {
279
+ const changed = this.#account?.id !== account?.id;
280
+ this.#account = account;
281
+ if (changed)
282
+ for (const listener of this.#listeners)
283
+ listener(account);
284
+ return account;
285
+ }
286
+ #storedGuest() {
287
+ try {
288
+ const raw = this.#storage?.getItem(GUEST_KEY);
289
+ const guest = raw ? JSON.parse(raw) : null;
290
+ return guest && typeof guest.token === "string" && guest.expiresAt > Date.now() ? guest : null;
291
+ }
292
+ catch {
293
+ return null;
294
+ }
295
+ }
296
+ #forgetGuest() {
297
+ this.#guest = null;
298
+ try {
299
+ this.#storage?.removeItem(GUEST_KEY);
300
+ }
301
+ catch {
302
+ // Nothing to forget.
303
+ }
304
+ }
305
+ }
306
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounts.js","sourceRoot":"","sources":["../../src/client/accounts.ts"],"names":[],"mappings":"AAgGA,kHAAkH;AAClH,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC5C,iCAAiC;IACxB,MAAM,CAAS;IACxB,2CAA2C;IAClC,IAAI,CAAS;IAEtB,YAAY,MAAc,EAAE,IAAY,EAAE,OAAe;QACvD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAYD,MAAM,SAAS,GAAG,iBAAiB,CAAC;AACpC,oEAAoE;AACpE,MAAM,OAAO,GAAG,UAAiG,CAAC;AAElH;;;;;;;GAOG;AACH,MAAM,OAAO,aAAa;IACxB,QAAQ,GAAmB,IAAI,CAAC;IAEvB,KAAK,CAAS;IACd,KAAK,CAAsB;IAC3B,MAAM,CAAe;IACrB,QAAQ,CAAkC;IAC1C,UAAU,CAAoC;IACvD,QAAQ,CAAgB;IACxB,MAAM,GAAiB,IAAI,CAAC;IAC5B,UAAU,GAAG,IAAI,GAAG,EAAqC,CAAC;IAE1D,YAAY,OAAO,GAAyB,EAAE;QAC5C,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,KAAK,SAAS,CAAC;QACjD,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,CAAC;QACjE,IAAI,CAAC,KAAK,G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AAC;IAED,YAAY;QACV,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC;YACH,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;QACvC,CAAC;QAAC,MAAM,CAAC;YACP,qBAAqB;QACvB,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,88 @@
1
+ /** What `BufferedInterpolator` reads the ticks from: a `RoomClient` will do. */
2
+ export interface TickSource {
3
+ /** The tick of the latest state: read when `update` is called. */
4
+ readonly tick: number;
5
+ /** Ticks a second; 0 in event mode. */
6
+ readonly tickRate: number;
7
+ /** The tick the room is on at `now`, by estimate, as `RoomClient.serverTick` gives it. */
8
+ serverTick?(now?: number): number | undefined;
9
+ }
10
+ /** Settings for `BufferedInterpolator`. */
11
+ export interface BufferedInterpolatorOptions<Field extends string> {
12
+ /**
13
+ * How far behind the newest state it expects to have, in ticks, before the
14
+ * margin for jitter is added. 2 by default: a patch can be a tick late, or
15
+ * cover two ticks, without anything having to be guessed.
16
+ */
17
+ delayTicks?: number;
18
+ /**
19
+ * For how many ticks a thing keeps moving at its last speed when no newer
20
+ * state has arrived for it, before it stops where it got to. 3 by default;
21
+ * 0 stops it at its last known place.
22
+ */
23
+ maxExtrapolationTicks?: number;
24
+ /**
25
+ * A change between two states in a row farther than this, measured over
26
+ * the fields that are not angles, is a jump: drawn as one, when the time
27
+ * comes, instead of a slide. Off by default. Set it above the farthest
28
+ * anything moves between two patches.
29
+ */
30
+ snapDistance?: number;
31
+ /** Fields that are angles in radians, which go the short way round through ±π. */
32
+ angles?: readonly Field[];
33
+ }
34
+ /**
35
+ * Smooths values that arrive once per tick by drawing them a little in the
36
+ * past, at an even pace, from the ticks they belong to.
37
+ *
38
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
39
+ * delay, but things speed up when two patches arrive together and stop when
40
+ * one is late. This one keeps the last few states of each id, keyed by the
41
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
42
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
43
+ * Motion then keeps the pace of the room, whatever the network does to the
44
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
45
+ * it measures, which it keeps adjusting.
46
+ *
47
+ * When the newest state is older than the moment it draws, it carries each
48
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
49
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
50
+ * set `snapDistance`.
51
+ *
52
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
53
+ * room.on("state", (state) => glide.update(state.units));
54
+ * // in the render loop:
55
+ * const { x, y } = glide.at(id) ?? state.units[id];
56
+ *
57
+ * Against a room older than 0.2, which does not say where its clock is, it
58
+ * times the patches as they arrive instead.
59
+ */
60
+ export declare class BufferedInterpolator<Field extends string> {
61
+ #private;
62
+ /**
63
+ * @param source where the ticks come from: the `RoomClient`
64
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
65
+ * @param options see `BufferedInterpolatorOptions`
66
+ */
67
+ constructor(source: TickSource, fields: readonly Field[], options?: BufferedInterpolatorOptions<Field>);
68
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
69
+ get delay(): number;
70
+ /**
71
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
72
+ * latest unless given. Ids missing from `targets` are forgotten.
73
+ *
74
+ * @param now when they arrived, from `performance.now()`
75
+ */
76
+ update(targets: Record<string, Record<Field, number>>, tick?: number, now?: number): void;
77
+ /**
78
+ * The latest values given for `id` were a jump, such as a respawn: draw
79
+ * them in one step when their tick comes, not as a slide. Call it after
80
+ * the `update` that brought them, for instance when a message says so:
81
+ * messages arrive after the patch of the same tick.
82
+ */
83
+ snap(id: string): void;
84
+ /** The values to draw for `id` right now, or undefined if it is not known. */
85
+ at(id: string, now?: number): Record<Field, number> | undefined;
86
+ /** Forget everything, e.g. after moving to another room. */
87
+ clear(): void;
88
+ }