tickflare 0.0.0-stage → 0.1.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 (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -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/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,423 @@
1
+ import type { TokenSource } from "./token.js";
2
+
3
+ /*
4
+ * The client side of `Accounts`: sign up, sign in, a guest identity before
5
+ * that, the player's own data, profiles and leaderboards.
6
+ */
7
+
8
+ /** Where the accounts API is and how the session travels. Every option has a default. */
9
+ export interface AccountClientOptions {
10
+ /** Where the Worker is, e.g. "https://game.example.com". Defaults to the page's own origin. */
11
+ baseUrl?: string;
12
+ /** Where the accounts API is served. Default "/api/accounts". */
13
+ prefix?: string;
14
+ /**
15
+ * How the session travels. "cookie" (the default in browsers): an HttpOnly
16
+ * cookie the page's scripts never see. "bearer" (the default elsewhere):
17
+ * the client keeps the session token and sends it with every request; pass
18
+ * `session` to restore one and `onSession` to keep it.
19
+ */
20
+ mode?: "cookie" | "bearer";
21
+ /** A session token to start with, in bearer mode. */
22
+ session?: string | null;
23
+ /** Called when the session token changes, in bearer mode: store it to stay signed in. */
24
+ onSession?(token: string | null): void;
25
+ /** Where to keep the guest identity between visits. Defaults to `localStorage` when there is one. */
26
+ storage?: KeyValueStore | null;
27
+ /** The fetch to use. Defaults to the global one. */
28
+ fetch?: typeof fetch;
29
+ }
30
+
31
+ /** The signed-in player's own account, as `GET /me` returns it. */
32
+ export interface Account {
33
+ /** The player id. A guest who registered keeps theirs. */
34
+ id: string;
35
+ /** The account name. */
36
+ name: string;
37
+ /** The email address, if one was given. */
38
+ email: string | null;
39
+ /** When the account was made, in epoch milliseconds. */
40
+ createdAt: number;
41
+ /** Whether the account has a recovery code. */
42
+ recoveryCode: boolean;
43
+ /** Every data key the player has, private ones included. */
44
+ data: Record<string, unknown>;
45
+ /** Every stat the player has. */
46
+ stats: Record<string, number>;
47
+ }
48
+
49
+ /** What anyone may see of a player. */
50
+ export interface Profile {
51
+ /** The player id. */
52
+ id: string;
53
+ /** The account name. */
54
+ name: string;
55
+ /** When the account was made, in epoch milliseconds. */
56
+ createdAt: number;
57
+ /** The data keys the game made public. */
58
+ data: Record<string, unknown>;
59
+ /** Every stat the player has. */
60
+ stats: Record<string, number>;
61
+ }
62
+
63
+ /** One line of a leaderboard. */
64
+ export interface LeaderboardLine {
65
+ /** 1 for the highest value. Players with the same value share a rank. */
66
+ rank: number;
67
+ /** The player id. */
68
+ id: string;
69
+ /** The account name. */
70
+ name: string;
71
+ /** The player's value of the stat. */
72
+ value: number;
73
+ }
74
+
75
+ /** A page of a leaderboard, highest value first. */
76
+ export interface Leaderboard {
77
+ /** The stat it ranks. */
78
+ stat: string;
79
+ /** This page's lines. */
80
+ entries: LeaderboardLine[];
81
+ /** Players with a value for this stat, in total. */
82
+ total: number;
83
+ }
84
+
85
+ /** A guest identity: a player id with a join token, before or instead of an account. */
86
+ export interface Guest {
87
+ /** The guest's player id. */
88
+ id: string;
89
+ /** A join token for `id`. */
90
+ token: string;
91
+ /** When the token stops working, in epoch milliseconds. */
92
+ expiresAt: number;
93
+ /** When the client renews it for the same id, in epoch milliseconds. */
94
+ renewAt: number;
95
+ }
96
+
97
+ /** A request the accounts API refused. `code` is machine-readable, e.g. "name_taken" or "invalid_credentials". */
98
+ export class AccountRequestError extends Error {
99
+ /** The HTTP status, e.g. 409. */
100
+ readonly status: number;
101
+ /** Machine-readable, e.g. `name_taken`. */
102
+ readonly code: string;
103
+
104
+ constructor(status: number, code: string, message: string) {
105
+ super(message);
106
+ this.name = "AccountRequestError";
107
+ this.status = status;
108
+ this.code = code;
109
+ }
110
+ }
111
+
112
+ /** The part of `localStorage` the client uses. */
113
+ export interface KeyValueStore {
114
+ /** The value under `key`, or null. */
115
+ getItem(key: string): string | null;
116
+ /** Stores `value` under `key`. */
117
+ setItem(key: string, value: string): void;
118
+ /** Removes `key`. */
119
+ removeItem(key: string): void;
120
+ }
121
+
122
+ const GUEST_KEY = "tickflare.guest";
123
+ /** What a browser has, seen from code that is not typed for one. */
124
+ const browser = globalThis as { document?: unknown; location?: { origin: string }; localStorage?: KeyValueStore };
125
+
126
+ /**
127
+ * The client side of `Accounts`: a guest identity until the player signs up,
128
+ * sign-up and sign-in, the player's own data, profiles and leaderboards.
129
+ *
130
+ * const accounts = new AccountClient();
131
+ * await accounts.restore();
132
+ * const room = new RoomClient(url, { token: accounts.tokenSource });
133
+ */
134
+ export class AccountClient {
135
+ #account: Account | null = null;
136
+
137
+ readonly #base: string;
138
+ readonly #mode: "cookie" | "bearer";
139
+ readonly #fetch: typeof fetch;
140
+ readonly #storage: AccountClientOptions["storage"];
141
+ readonly #onSession: AccountClientOptions["onSession"];
142
+ #session: string | null;
143
+ #guest: Guest | null = null;
144
+ #listeners = new Set<(account: Account | null) => void>();
145
+
146
+ constructor(options: AccountClientOptions = {}) {
147
+ const inBrowser = browser.document !== undefined;
148
+ const origin = options.baseUrl ?? browser.location?.origin ?? "";
149
+ this.#base = `${origin.replace(/\/+$/, "")}${(options.prefix ?? "/api/accounts").replace(/\/+$/, "")}`;
150
+ this.#mode = options.mode ?? (inBrowser ? "cookie" : "bearer");
151
+ this.#session = options.session ?? null;
152
+ this.#onSession = options.onSession;
153
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
154
+ this.#storage = options.storage !== undefined ? options.storage : (browser.localStorage ?? null);
155
+ }
156
+
157
+ /** The signed-in account, once `restore`, `login` or `register` has found one. */
158
+ get account(): Account | null {
159
+ return this.#account;
160
+ }
161
+
162
+ /** Whether someone is signed in. */
163
+ get signedIn(): boolean {
164
+ return this.#account !== null;
165
+ }
166
+
167
+ /** The player id to use: the account's, else the guest's, else undefined. */
168
+ get playerId(): string | undefined {
169
+ return this.#account?.id ?? this.#guest?.id ?? this.#storedGuest()?.id;
170
+ }
171
+
172
+ /** Calls `listener` whenever the signed-in account changes. Returns a function that stops it. */
173
+ onChange(listener: (account: Account | null) => void): () => void {
174
+ this.#listeners.add(listener);
175
+ return () => this.#listeners.delete(listener);
176
+ }
177
+
178
+ /** Finds out whether a session is still good. Call once at startup. */
179
+ async restore(): Promise<Account | null> {
180
+ if (this.#mode === "bearer" && !this.#session) return this.#setAccount(null);
181
+ try {
182
+ return this.#setAccount(await this.#request<Account>("GET", "/me"));
183
+ } catch (error) {
184
+ if (error instanceof AccountRequestError && error.status === 401) {
185
+ this.#setSession(null);
186
+ return this.#setAccount(null);
187
+ }
188
+ throw error;
189
+ }
190
+ }
191
+
192
+ /** Creates an account and signs in. A guest who registers keeps their player id. */
193
+ async register(input: { name: string; password: string; email?: string }): Promise<Account> {
194
+ const guest = this.#guest ?? this.#storedGuest();
195
+ const body = guest && guest.expiresAt > Date.now() ? { ...input, guestToken: guest.token } : input;
196
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/register", body);
197
+ this.#forgetGuest();
198
+ this.#setSession(result.token);
199
+ this.#setAccount(result.account);
200
+ return result.account;
201
+ }
202
+
203
+ /** Signs in. Rejects with `AccountRequestError` (`invalid_credentials`, `too_many_attempts`) if it cannot. */
204
+ async login(name: string, password: string): Promise<Account> {
205
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/login", { name, password });
206
+ this.#setSession(result.token);
207
+ this.#setAccount(result.account);
208
+ return result.account;
209
+ }
210
+
211
+ /** Ends the session, on the server and here. */
212
+ async logout(): Promise<void> {
213
+ try {
214
+ await this.#request("POST", "/logout");
215
+ } finally {
216
+ this.#setSession(null);
217
+ this.#setAccount(null);
218
+ }
219
+ }
220
+
221
+ /** Changes the password. Every other session of the account is signed out. */
222
+ async changePassword(current: string, next: string): Promise<void> {
223
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/password", { current, next });
224
+ this.#setSession(result.token);
225
+ this.#setAccount(result.account);
226
+ }
227
+
228
+ /**
229
+ * Makes a recovery code and returns it: show it to the player once, to
230
+ * keep somewhere safe. It sets a new password with `recover`, with no
231
+ * email involved, and replaces the code the account had. Needs the password.
232
+ */
233
+ async createRecoveryCode(password: string): Promise<string> {
234
+ const result = await this.#request<{ code: string }>("POST", "/recovery-code", { password });
235
+ if (this.#account) this.#setAccount({ ...this.#account, recoveryCode: true });
236
+ return result.code;
237
+ }
238
+
239
+ /**
240
+ * Sets a new password with a recovery code, and signs in. The code is used
241
+ * up. Rejects with `AccountRequestError` (`invalid_code`, `too_many_attempts`).
242
+ */
243
+ async recover(name: string, code: string, password: string): Promise<Account> {
244
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/recover", { name, code, password });
245
+ this.#setSession(result.token);
246
+ this.#setAccount(result.account);
247
+ return result.account;
248
+ }
249
+
250
+ /**
251
+ * Asks for a password reset link to be sent to the account with this name,
252
+ * or to every account with this email address. It resolves whether or not
253
+ * there is such an account, so as not to tell. Rejects with `not_enabled`
254
+ * if the game does not send email.
255
+ */
256
+ async forgotPassword(who: { name: string } | { email: string }): Promise<void> {
257
+ await this.#request("POST", "/forgot", who);
258
+ }
259
+
260
+ /** Sets a new password with the token from a reset link, and signs in. Rejects with `invalid_token`. */
261
+ async resetPassword(token: string, password: string): Promise<Account> {
262
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/reset", { token, password });
263
+ this.#setSession(result.token);
264
+ this.#setAccount(result.account);
265
+ return result.account;
266
+ }
267
+
268
+ /** Takes another name. */
269
+ async rename(name: string): Promise<Account> {
270
+ const account = await this.#request<Account>("POST", "/name", { name });
271
+ this.#account = account;
272
+ return account;
273
+ }
274
+
275
+ /** Sets the email address, or removes it with null. Needs the password. */
276
+ async setEmail(password: string, email: string | null): Promise<Account> {
277
+ const account = await this.#request<Account>("POST", "/email", { password, email });
278
+ this.#account = account;
279
+ return account;
280
+ }
281
+
282
+ /** Deletes the account and everything stored with it. */
283
+ async deleteAccount(password: string): Promise<void> {
284
+ await this.#request("DELETE", "/me", { password });
285
+ this.#setSession(null);
286
+ this.#setAccount(null);
287
+ }
288
+
289
+ /** Everything the server keeps about the signed-in player. */
290
+ async exportData(): Promise<Record<string, unknown>> {
291
+ return this.#request("GET", "/export");
292
+ }
293
+
294
+ /**
295
+ * A guest identity, made on first use and kept in `storage`. Its token is
296
+ * renewed, for the same player id, once it is half way to expiring; a
297
+ * guest who stays away until it has expired starts over as a new player.
298
+ */
299
+ async guest(): Promise<Guest> {
300
+ const known = this.#guest ?? this.#storedGuest();
301
+ if (known && known.renewAt > Date.now()) return (this.#guest = known);
302
+ const guest = await this.#request<Guest>("POST", "/guest", known ? { token: known.token } : undefined);
303
+ this.#guest = guest;
304
+ try {
305
+ this.#storage?.setItem(GUEST_KEY, JSON.stringify(guest));
306
+ } catch {
307
+ // Storage full or blocked: the guest lasts for this visit.
308
+ }
309
+ return guest;
310
+ }
311
+
312
+ /** A short-lived join token for a room or queue, for the signed-in player. */
313
+ async joinToken(scope?: string): Promise<string> {
314
+ const result = await this.#request<{ token: string }>("POST", "/token", scope === undefined ? {} : { scope });
315
+ return result.token;
316
+ }
317
+
318
+ /**
319
+ * For `RoomClient`'s `token` option: a join token for the signed-in player,
320
+ * or the guest's token for anyone else.
321
+ */
322
+ readonly tokenSource: TokenSource = async (room) => {
323
+ if (this.#account) return this.joinToken(room);
324
+ return (await this.guest()).token;
325
+ };
326
+
327
+ /** The signed-in player's value under `key`, or undefined. */
328
+ async getData<T = unknown>(key: string): Promise<T | undefined> {
329
+ try {
330
+ return (await this.#request<{ value: T }>("GET", `/data/${encodeURIComponent(key)}`)).value;
331
+ } catch (error) {
332
+ if (error instanceof AccountRequestError && error.status === 404) return undefined;
333
+ throw error;
334
+ }
335
+ }
336
+
337
+ /** Stores a value under a key the game lets players write. */
338
+ async setData(key: string, value: unknown): Promise<void> {
339
+ await this.#request("PUT", `/data/${encodeURIComponent(key)}`, { value });
340
+ if (this.#account) this.#account = { ...this.#account, data: { ...this.#account.data, [key]: value } };
341
+ }
342
+
343
+ /** Removes a value under a key the game lets players write. */
344
+ async deleteData(key: string): Promise<void> {
345
+ await this.#request("DELETE", `/data/${encodeURIComponent(key)}`);
346
+ if (this.#account) {
347
+ const { [key]: _removed, ...data } = this.#account.data;
348
+ this.#account = { ...this.#account, data };
349
+ }
350
+ }
351
+
352
+ /** A player's public profile, or null if there is no such account. */
353
+ async profile(playerId: string): Promise<Profile | null> {
354
+ try {
355
+ return await this.#request<Profile>("GET", `/players/${encodeURIComponent(playerId)}`);
356
+ } catch (error) {
357
+ if (error instanceof AccountRequestError && error.status === 404) return null;
358
+ throw error;
359
+ }
360
+ }
361
+
362
+ /** A page of the leaderboard for `stat`, highest first. */
363
+ async leaderboard(stat: string, page: { limit?: number; offset?: number } = {}): Promise<Leaderboard> {
364
+ const query = new URLSearchParams();
365
+ if (page.limit !== undefined) query.set("limit", String(page.limit));
366
+ if (page.offset !== undefined) query.set("offset", String(page.offset));
367
+ const suffix = query.size > 0 ? `?${query}` : "";
368
+ return this.#request("GET", `/leaderboards/${encodeURIComponent(stat)}${suffix}`);
369
+ }
370
+
371
+ async #request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {
372
+ const headers: Record<string, string> = {};
373
+ if (body !== undefined) headers["Content-Type"] = "application/json";
374
+ if (this.#mode === "bearer" && this.#session) headers.Authorization = `Bearer ${this.#session}`;
375
+ const init: RequestInit & { credentials?: "include" } = {
376
+ method,
377
+ headers,
378
+ body: body === undefined ? undefined : JSON.stringify(body),
379
+ };
380
+ // So the cookie also travels when the API is on another origin. Not set otherwise:
381
+ // runtimes other than browsers may not know the option.
382
+ if (this.#mode === "cookie") init.credentials = "include";
383
+ const response = await this.#fetch(`${this.#base}${path}`, init);
384
+ if (response.status === 204) return undefined as T;
385
+ const payload = (await response.json().catch(() => null)) as { error?: string; message?: string } | null;
386
+ if (!response.ok) {
387
+ throw new AccountRequestError(response.status, payload?.error ?? "request_failed", payload?.message ?? response.statusText);
388
+ }
389
+ return payload as T;
390
+ }
391
+
392
+ #setSession(token: string | null): void {
393
+ if (this.#mode !== "bearer" || this.#session === token) return;
394
+ this.#session = token;
395
+ this.#onSession?.(token);
396
+ }
397
+
398
+ #setAccount(account: Account | null): Account | null {
399
+ const changed = this.#account?.id !== account?.id;
400
+ this.#account = account;
401
+ if (changed) for (const listener of this.#listeners) listener(account);
402
+ return account;
403
+ }
404
+
405
+ #storedGuest(): Guest | null {
406
+ try {
407
+ const raw = this.#storage?.getItem(GUEST_KEY);
408
+ const guest = raw ? (JSON.parse(raw) as Guest) : null;
409
+ return guest && typeof guest.token === "string" && guest.expiresAt > Date.now() ? guest : null;
410
+ } catch {
411
+ return null;
412
+ }
413
+ }
414
+
415
+ #forgetGuest(): void {
416
+ this.#guest = null;
417
+ try {
418
+ this.#storage?.removeItem(GUEST_KEY);
419
+ } catch {
420
+ // Nothing to forget.
421
+ }
422
+ }
423
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Changing a copy of a state without copying the state.
3
+ *
4
+ * `produce(base, recipe)` hands `recipe` a draft of `base` to change in
5
+ * place, as a room's hooks change `this.state`, and returns the result.
6
+ * `base` is not touched. Only the objects on the way to something that
7
+ * changed are copied; everything else in the result is the same object as in
8
+ * `base`, so the result can be compared with it by reference, part by part.
9
+ *
10
+ * It follows plain objects and arrays, which is what a state made of JSON
11
+ * has. Anything else in it (a `Date`, a `Map`) is handed over as it is.
12
+ */
13
+
14
+ /** One object or array of the base, and its copy once something in it has changed. */
15
+ interface Node {
16
+ base: object;
17
+ copy: object | undefined;
18
+ parent: Node | undefined;
19
+ /** Where it is in its parent. */
20
+ key: string | undefined;
21
+ proxy: object;
22
+ /** Drafts handed out for what is inside, by key. */
23
+ children: Map<string, Node>;
24
+ }
25
+
26
+ const nodes = new WeakMap<object, Node>();
27
+
28
+ /**
29
+ * The state `recipe` makes of `base`, with `base` left as it was. If the
30
+ * recipe changes nothing, the result is `base` itself.
31
+ */
32
+ export function produce<T>(base: T, recipe: (draft: T) => void): T {
33
+ if (!isDraftable(base)) {
34
+ recipe(base);
35
+ return base;
36
+ }
37
+ const root = draftOf(base, undefined, undefined);
38
+ recipe(root.proxy as T);
39
+ return (root.copy ?? root.base) as T;
40
+ }
41
+
42
+ function isDraftable(value: unknown): value is object {
43
+ if (typeof value !== "object" || value === null) return false;
44
+ if (Array.isArray(value)) return true;
45
+ const prototype = Object.getPrototypeOf(value) as unknown;
46
+ return prototype === Object.prototype || prototype === null;
47
+ }
48
+
49
+ function draftOf(base: object, parent: Node | undefined, key: string | undefined): Node {
50
+ const node: Node = { base, copy: undefined, parent, key, proxy: undefined as unknown as object, children: new Map() };
51
+ // The proxy's own target is an empty stand-in: nothing is read from it or written to it, and a
52
+ // base that was frozen cannot get in the way.
53
+ node.proxy = new Proxy(Array.isArray(base) ? [] : {}, handlerFor(node));
54
+ nodes.set(node.proxy, node);
55
+ return node;
56
+ }
57
+
58
+ /** What the draft holds now: its copy if it has one. */
59
+ const current = (node: Node): Record<string, unknown> => (node.copy ?? node.base) as Record<string, unknown>;
60
+
61
+ /** Gives the node a copy to write to, and puts that copy in its parent's, all the way up. */
62
+ function writable(node: Node): Record<string, unknown> {
63
+ if (node.copy === undefined) {
64
+ node.copy = Array.isArray(node.base) ? node.base.slice() : { ...node.base };
65
+ if (node.parent && node.key !== undefined) writable(node.parent)[node.key] = node.copy;
66
+ }
67
+ return node.copy as Record<string, unknown>;
68
+ }
69
+
70
+ /** A value on its way into a draft, with any drafts in it replaced by what they hold. */
71
+ function settled(value: unknown): unknown {
72
+ if (typeof value !== "object" || value === null) return value;
73
+ const node = nodes.get(value);
74
+ if (node) return current(node);
75
+ if (!isDraftable(value)) return value;
76
+ // A new object or array: it is the recipe's own, so drafts inside it are replaced in place.
77
+ const holder = value as Record<string, unknown>;
78
+ for (const key of Object.keys(holder)) {
79
+ const inner = holder[key];
80
+ if (typeof inner === "object" && inner !== null) {
81
+ const plain = settled(inner);
82
+ if (plain !== inner) holder[key] = plain;
83
+ }
84
+ }
85
+ return value;
86
+ }
87
+
88
+ function handlerFor(node: Node): ProxyHandler<object> {
89
+ return {
90
+ get(_target, key, receiver) {
91
+ const source = current(node);
92
+ if (typeof key === "symbol") return Reflect.get(source, key, receiver);
93
+ const value = source[key];
94
+ if (!isDraftable(value)) {
95
+ // An array's own methods run on the draft, so that what they write is followed.
96
+ return typeof value === "function" ? Reflect.get(source, key, receiver) : value;
97
+ }
98
+ let child = node.children.get(key);
99
+ if (!child || current(child) !== value) {
100
+ child = draftOf(value, node, key);
101
+ node.children.set(key, child);
102
+ }
103
+ return child.proxy;
104
+ },
105
+ set(_target, key, value) {
106
+ if (typeof key === "symbol") return false;
107
+ const next = settled(value);
108
+ const source = current(node);
109
+ // Writing what is there already is not a change, and must not cost a copy.
110
+ if (Object.prototype.hasOwnProperty.call(source, key) && Object.is(source[key], next)) return true;
111
+ writable(node)[key] = next;
112
+ node.children.delete(key);
113
+ return true;
114
+ },
115
+ deleteProperty(_target, key) {
116
+ if (typeof key === "symbol") return false;
117
+ if (!Object.prototype.hasOwnProperty.call(current(node), key)) return true;
118
+ delete writable(node)[key];
119
+ node.children.delete(key);
120
+ return true;
121
+ },
122
+ defineProperty(_target, key, descriptor) {
123
+ if (typeof key === "symbol" || !("value" in descriptor)) return false;
124
+ writable(node)[key] = settled(descriptor.value);
125
+ node.children.delete(key);
126
+ return true;
127
+ },
128
+ has: (_target, key) => Reflect.has(current(node), key),
129
+ ownKeys: () => Reflect.ownKeys(current(node)),
130
+ getOwnPropertyDescriptor(_target, key) {
131
+ const descriptor = Reflect.getOwnPropertyDescriptor(current(node), key);
132
+ // What the draft holds is not the proxy's own target, so nothing in it may claim to be fixed
133
+ // there, except an array's length, which is.
134
+ if (descriptor && !(Array.isArray(node.base) && key === "length")) descriptor.configurable = true;
135
+ return descriptor;
136
+ },
137
+ };
138
+ }