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
package/src/binary.ts ADDED
@@ -0,0 +1,496 @@
1
+ /**
2
+ * Patches in binary, for clients that ask for them.
3
+ *
4
+ * A browser's WebSocket is compressed by Cloudflare, which makes JSON patches
5
+ * small on the wire. A client that does not offer compression, as many game
6
+ * engines' do not, is sent the JSON as it is: for those, this format is about
7
+ * a third of the size. It carries exactly what a `patch` frame carries, and
8
+ * nothing else is sent in binary.
9
+ *
10
+ * The layout is in the protocol reference. In short: a frame is a WebSocket
11
+ * binary message; whole numbers are varints; a name used as a key is sent
12
+ * once, and by its number after that.
13
+ */
14
+ import type { PatchFrame } from "./protocol.js";
15
+ import type { ArrayPatch, Patch } from "./patch.js";
16
+
17
+ /** The value of the `patches` query parameter that asks for this format, and its first byte. */
18
+ export const BINARY_PATCHES = "b1";
19
+ const MAGIC = 0xb1;
20
+
21
+ const FLAG_FROM = 1;
22
+ const FLAG_SHOWS = 2;
23
+ const FLAG_FORGET = 4;
24
+
25
+ const enum Tag {
26
+ Null = 0,
27
+ False = 1,
28
+ True = 2,
29
+ /** A whole number, zero or more: a varint. */
30
+ Int = 3,
31
+ /** A whole number below zero: a varint of its size. */
32
+ NegativeInt = 4,
33
+ /** A number with one decimal place: a varint of ten times it. */
34
+ Tenths = 5,
35
+ NegativeTenths = 6,
36
+ /** A number with two decimal places: a varint of a hundred times it. */
37
+ Hundredths = 7,
38
+ NegativeHundredths = 8,
39
+ /** Any other number: eight bytes, big-endian. */
40
+ Float = 9,
41
+ String = 10,
42
+ Array = 11,
43
+ Object = 12,
44
+ /** In a patch only: the key is deleted. */
45
+ Delete = 13,
46
+ /** In a patch only: a patch of what the key holds follows. */
47
+ Nested = 14,
48
+ /** In a patch only: the key holds an array, and what changed in it follows. */
49
+ Elements = 15,
50
+ }
51
+
52
+ /** Keys longer than this are sent in full every time: a name is short, and an id that long is rare. */
53
+ const LONGEST_KEY = 64;
54
+ /** The most keys a table holds before it is started again. */
55
+ export const MOST_KEYS = 8192;
56
+ /** Numbers up to this size are tried as tenths and hundredths. */
57
+ const DECIMAL_LIMIT = 1e12;
58
+
59
+ const utf8 = new TextEncoder();
60
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
61
+
62
+ /**
63
+ * The buffer every writer starts in. Writing is done one writer at a time, and `done()` copies
64
+ * what was written out, so they can share it: a room sending a thousand players a frame each
65
+ * makes a thousand small copies a tick, not a thousand buffers to grow and throw away.
66
+ */
67
+ let scratch = new Uint8Array(4096);
68
+ let scratchView = new DataView(scratch.buffer);
69
+ /** A buffer grown past this is not kept for the next writer. */
70
+ const LARGEST_SCRATCH = 64 * 1024;
71
+
72
+ /** Bytes, written one after another into a buffer that grows. */
73
+ class Writer {
74
+ #bytes = scratch;
75
+ #view = scratchView;
76
+ length = 0;
77
+
78
+ #room(more: number): void {
79
+ if (this.length + more <= this.#bytes.length) return;
80
+ const grown = new Uint8Array(Math.max(this.#bytes.length * 2, this.length + more));
81
+ grown.set(this.#bytes.subarray(0, this.length));
82
+ this.#bytes = grown;
83
+ this.#view = new DataView(grown.buffer);
84
+ if (grown.length <= LARGEST_SCRATCH) {
85
+ scratch = grown;
86
+ scratchView = this.#view;
87
+ }
88
+ }
89
+
90
+ byte(value: number): void {
91
+ this.#room(1);
92
+ this.#bytes[this.length++] = value;
93
+ }
94
+
95
+ /** A whole number from 0 to 2^53, seven bits to a byte, least first; every byte but the last has its top bit set. */
96
+ varint(value: number): void {
97
+ if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`not a whole number from 0 up: ${value}`);
98
+ this.#room(8);
99
+ while (value >= 0x80) {
100
+ this.#bytes[this.length++] = (value % 0x80) | 0x80;
101
+ value = Math.floor(value / 0x80);
102
+ }
103
+ this.#bytes[this.length++] = value;
104
+ }
105
+
106
+ float(value: number): void {
107
+ this.#room(8);
108
+ this.#view.setFloat64(this.length, value);
109
+ this.length += 8;
110
+ }
111
+
112
+ bytes(value: Uint8Array): void {
113
+ this.#room(value.length);
114
+ this.#bytes.set(value, this.length);
115
+ this.length += value.length;
116
+ }
117
+
118
+ /** A string: its length in bytes as a varint, then its UTF-8. */
119
+ string(value: string): void {
120
+ const encoded = utf8.encode(value);
121
+ this.varint(encoded.length);
122
+ this.bytes(encoded);
123
+ }
124
+
125
+ done(): Uint8Array {
126
+ return this.#bytes.slice(0, this.length);
127
+ }
128
+
129
+ /** A copy of what was written from `start` on. */
130
+ copy(start: number): Uint8Array {
131
+ return this.#bytes.slice(start, this.length);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * What `encodePatch` can share between patches: the bytes already written for each value of the
137
+ * state (an object or an array), and for each change (a nested patch or an array's elements), by
138
+ * the object itself. Players who see the same unit, or are sent the same change to a part of the
139
+ * state they share, get one encoding of it. Good for one generation of one key table.
140
+ */
141
+ export interface SharedEncodings {
142
+ values: Map<object, Uint8Array>;
143
+ changes: Map<object, Uint8Array>;
144
+ }
145
+
146
+ let sharing: SharedEncodings | undefined;
147
+
148
+ /**
149
+ * The names a room has sent as keys, each with a number: its place in the
150
+ * order they were first sent. One table serves every socket of the room; a
151
+ * socket is told the names it has not been told yet at the start of its
152
+ * next frame.
153
+ */
154
+ export class KeyTable {
155
+ #numbers = new Map<string, number>();
156
+ /** Every name, as it is written in a definition: length and UTF-8. */
157
+ #definitions: Uint8Array[] = [];
158
+ /** Goes up each time the table is started again: a socket that knows another has to forget its keys. */
159
+ generation = 0;
160
+
161
+ get size(): number {
162
+ return this.#definitions.length;
163
+ }
164
+
165
+ /** Starts the table again if it is full. Between frames only: a frame's numbers are of one table. */
166
+ renew(): void {
167
+ if (this.#definitions.length < MOST_KEYS) return;
168
+ this.#numbers.clear();
169
+ this.#definitions = [];
170
+ this.generation += 1;
171
+ }
172
+
173
+ /** Writes a key: its number, or the name itself if it is not in the table and cannot be put there. */
174
+ write(to: Writer, key: string): void {
175
+ let number = this.#numbers.get(key);
176
+ if (number === undefined && key.length <= LONGEST_KEY && this.#definitions.length < MOST_KEYS) {
177
+ number = this.#definitions.length;
178
+ this.#numbers.set(key, number);
179
+ // At most 64 characters, so at most 192 bytes: the length fits the two bytes kept for it.
180
+ const name = utf8.encode(key);
181
+ const definition = new Uint8Array(name.length + (name.length < 0x80 ? 1 : 2));
182
+ if (name.length < 0x80) definition[0] = name.length;
183
+ else definition.set([(name.length % 0x80) | 0x80, name.length >> 7]);
184
+ definition.set(name, definition.length - name.length);
185
+ this.#definitions.push(definition);
186
+ }
187
+ if (number === undefined) {
188
+ to.byte(0);
189
+ to.string(key);
190
+ } else {
191
+ to.varint(number + 1);
192
+ }
193
+ }
194
+
195
+ /** Writes the definitions of the keys numbered `from` and up: how many, then each. */
196
+ define(to: Writer, from: number): void {
197
+ to.varint(this.#definitions.length - from);
198
+ for (let number = from; number < this.#definitions.length; number++) to.bytes(this.#definitions[number]!);
199
+ }
200
+ }
201
+
202
+ function writeValue(to: Writer, keys: KeyTable, value: unknown): void {
203
+ switch (typeof value) {
204
+ case "boolean":
205
+ return to.byte(value ? Tag.True : Tag.False);
206
+ case "string":
207
+ to.byte(Tag.String);
208
+ return to.string(value);
209
+ case "number":
210
+ return writeNumber(to, value);
211
+ case "object": {
212
+ if (value === null) return to.byte(Tag.Null);
213
+ // As JSON.stringify does: a Date, say, is written as what its toJSON gives.
214
+ if (typeof (value as { toJSON?: unknown }).toJSON === "function") {
215
+ return writeValue(to, keys, (value as { toJSON(): unknown }).toJSON());
216
+ }
217
+ const known = sharing?.values.get(value);
218
+ if (known) return to.bytes(known);
219
+ const start = to.length;
220
+ if (Array.isArray(value)) {
221
+ to.byte(Tag.Array);
222
+ to.varint(value.length);
223
+ // As in JSON: what cannot be said is null in an array.
224
+ for (const item of value) writeValue(to, keys, item === undefined ? null : item);
225
+ } else {
226
+ const record = value as Record<string, unknown>;
227
+ const names = Object.keys(record).filter((name) => record[name] !== undefined);
228
+ to.byte(Tag.Object);
229
+ to.varint(names.length);
230
+ for (const name of names) {
231
+ keys.write(to, name);
232
+ writeValue(to, keys, record[name]);
233
+ }
234
+ }
235
+ sharing?.values.set(value, to.copy(start));
236
+ return;
237
+ }
238
+ default:
239
+ throw new TypeError(`cannot be sent: ${typeof value}`);
240
+ }
241
+ }
242
+
243
+ function writeNumber(to: Writer, value: number): void {
244
+ if (Number.isSafeInteger(value) && !Object.is(value, -0)) {
245
+ to.byte(value < 0 ? Tag.NegativeInt : Tag.Int);
246
+ return to.varint(Math.abs(value));
247
+ }
248
+ const size = Math.abs(value);
249
+ // Not minus zero: its sign would be lost.
250
+ if (size < DECIMAL_LIMIT && size !== 0) {
251
+ // Sent as a whole number of tenths or hundredths only if dividing gives the very same number back.
252
+ const tenths = Math.round(size * 10);
253
+ if (tenths / 10 === size) {
254
+ to.byte(value < 0 ? Tag.NegativeTenths : Tag.Tenths);
255
+ return to.varint(tenths);
256
+ }
257
+ const hundredths = Math.round(size * 100);
258
+ if (hundredths / 100 === size) {
259
+ to.byte(value < 0 ? Tag.NegativeHundredths : Tag.Hundredths);
260
+ return to.varint(hundredths);
261
+ }
262
+ }
263
+ if (!Number.isFinite(value)) throw new TypeError(`cannot be sent: ${value}`);
264
+ to.byte(Tag.Float);
265
+ to.float(value);
266
+ }
267
+
268
+ function writePatch(to: Writer, keys: KeyTable, patch: Patch): void {
269
+ const names = Object.keys(patch);
270
+ to.varint(names.length);
271
+ for (const name of names) {
272
+ keys.write(to, name);
273
+ writeChange(to, keys, patch[name]!);
274
+ }
275
+ }
276
+
277
+ /** What to do with one key of an object or one element of an array. */
278
+ function writeChange(to: Writer, keys: KeyTable, change: Patch[string]): void {
279
+ if (change === 0) return to.byte(Tag.Delete);
280
+ if (Array.isArray(change) && change.length !== 2) return writeValue(to, keys, change[0] === undefined ? null : change[0]);
281
+ const known = sharing?.changes.get(change);
282
+ if (known) return to.bytes(known);
283
+ const start = to.length;
284
+ if (!Array.isArray(change)) {
285
+ to.byte(Tag.Nested);
286
+ writePatch(to, keys, change);
287
+ } else {
288
+ // An array's elements: its new length, how many changed, and each by its index.
289
+ const [changes, length] = change;
290
+ const indexes = Object.keys(changes);
291
+ to.byte(Tag.Elements);
292
+ to.varint(length);
293
+ to.varint(indexes.length);
294
+ for (const index of indexes) {
295
+ to.varint(Number(index));
296
+ writeChange(to, keys, changes[index]!);
297
+ }
298
+ }
299
+ sharing?.changes.set(change, to.copy(start));
300
+ }
301
+
302
+ /**
303
+ * A patch as bytes, without the frame around it. Keys it has not seen go into `keys`. With
304
+ * `shared`, values and changes in it that were written before, for another patch with the same
305
+ * table, are copied from there instead of written again; it must not outlive the table's
306
+ * generation.
307
+ */
308
+ export function encodePatch(patch: Patch, keys: KeyTable, shared?: SharedEncodings): Uint8Array {
309
+ const to = new Writer();
310
+ sharing = shared;
311
+ try {
312
+ writePatch(to, keys, patch);
313
+ } finally {
314
+ sharing = undefined;
315
+ }
316
+ return to.done();
317
+ }
318
+
319
+ /**
320
+ * The frame around an encoded patch, for a socket that knows the first
321
+ * `known` keys of the table, or none of them when `forget` is set.
322
+ */
323
+ export function encodePatchFrame(
324
+ head: { seq: number; tick: number; from?: number | undefined; c?: number | undefined },
325
+ keys: KeyTable,
326
+ known: number,
327
+ forget: boolean,
328
+ patch: Uint8Array,
329
+ ): Uint8Array {
330
+ const to = new Writer();
331
+ to.byte(MAGIC);
332
+ to.byte((head.from === undefined ? 0 : FLAG_FROM) | (head.c === undefined ? 0 : FLAG_SHOWS) | (forget ? FLAG_FORGET : 0));
333
+ to.varint(head.seq);
334
+ to.varint(head.tick);
335
+ if (head.from !== undefined) to.varint(head.from);
336
+ if (head.c !== undefined) to.varint(head.c);
337
+ keys.define(to, forget ? 0 : known);
338
+ to.bytes(patch);
339
+ return to.done();
340
+ }
341
+
342
+ /** Bytes, read one after another. */
343
+ class Reader {
344
+ readonly #bytes: Uint8Array;
345
+ readonly #view: DataView;
346
+ at = 0;
347
+
348
+ constructor(bytes: Uint8Array) {
349
+ this.#bytes = bytes;
350
+ this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
351
+ }
352
+
353
+ byte(): number {
354
+ if (this.at >= this.#bytes.length) throw new RangeError("the frame ends too soon");
355
+ return this.#bytes[this.at++]!;
356
+ }
357
+
358
+ varint(): number {
359
+ let value = 0;
360
+ let scale = 1;
361
+ for (;;) {
362
+ const byte = this.byte();
363
+ value += (byte & 0x7f) * scale;
364
+ if (byte < 0x80) break;
365
+ scale *= 0x80;
366
+ if (scale > Number.MAX_SAFE_INTEGER) throw new RangeError("a number in the frame is too long");
367
+ }
368
+ if (!Number.isSafeInteger(value)) throw new RangeError("a number in the frame is too large");
369
+ return value;
370
+ }
371
+
372
+ float(): number {
373
+ if (this.at + 8 > this.#bytes.length) throw new RangeError("the frame ends too soon");
374
+ const value = this.#view.getFloat64(this.at);
375
+ this.at += 8;
376
+ return value;
377
+ }
378
+
379
+ string(): string {
380
+ const length = this.varint();
381
+ if (this.at + length > this.#bytes.length) throw new RangeError("the frame ends too soon");
382
+ const value = text.decode(this.#bytes.subarray(this.at, this.at + length));
383
+ this.at += length;
384
+ return value;
385
+ }
386
+
387
+ get done(): boolean {
388
+ return this.at === this.#bytes.length;
389
+ }
390
+ }
391
+
392
+ function readKey(from: Reader, keys: readonly string[]): string {
393
+ const number = from.varint();
394
+ if (number === 0) return from.string();
395
+ const key = keys[number - 1];
396
+ if (key === undefined) throw new RangeError(`the frame uses key ${number - 1}, which was never defined`);
397
+ return key;
398
+ }
399
+
400
+ function readValue(from: Reader, keys: readonly string[], tag = from.byte()): unknown {
401
+ switch (tag) {
402
+ case Tag.Null:
403
+ return null;
404
+ case Tag.False:
405
+ return false;
406
+ case Tag.True:
407
+ return true;
408
+ case Tag.Int:
409
+ return from.varint();
410
+ case Tag.NegativeInt:
411
+ return -from.varint();
412
+ case Tag.Tenths:
413
+ return from.varint() / 10;
414
+ case Tag.NegativeTenths:
415
+ return -(from.varint() / 10);
416
+ case Tag.Hundredths:
417
+ return from.varint() / 100;
418
+ case Tag.NegativeHundredths:
419
+ return -(from.varint() / 100);
420
+ case Tag.Float:
421
+ return from.float();
422
+ case Tag.String:
423
+ return from.string();
424
+ case Tag.Array: {
425
+ const items: unknown[] = [];
426
+ for (let left = from.varint(); left > 0; left--) items.push(readValue(from, keys));
427
+ return items;
428
+ }
429
+ case Tag.Object: {
430
+ const record: Record<string, unknown> = {};
431
+ for (let left = from.varint(); left > 0; left--) {
432
+ const key = readKey(from, keys);
433
+ define(record, key, readValue(from, keys));
434
+ }
435
+ return record;
436
+ }
437
+ default:
438
+ throw new RangeError(`the frame has a value of a kind this client does not know: ${tag}`);
439
+ }
440
+ }
441
+
442
+ /** Sets a key as JSON.parse does: as the object's own, whatever its name. */
443
+ function define(record: Record<string, unknown>, key: string, value: unknown): void {
444
+ if (key === "__proto__") Object.defineProperty(record, key, { value, enumerable: true, writable: true, configurable: true });
445
+ else record[key] = value;
446
+ }
447
+
448
+ function readPatch(from: Reader, keys: readonly string[]): Patch {
449
+ const patch: Patch = {};
450
+ for (let left = from.varint(); left > 0; left--) {
451
+ const key = readKey(from, keys);
452
+ define(patch as Record<string, unknown>, key, readChange(from, keys));
453
+ }
454
+ return patch;
455
+ }
456
+
457
+ function readChange(from: Reader, keys: readonly string[]): Patch[string] {
458
+ const tag = from.byte();
459
+ if (tag === Tag.Delete) return 0;
460
+ if (tag === Tag.Nested) return readPatch(from, keys);
461
+ if (tag !== Tag.Elements) return [readValue(from, keys, tag)];
462
+ const length = from.varint();
463
+ const changes: ArrayPatch[0] = {};
464
+ for (let left = from.varint(); left > 0; left--) {
465
+ const index = from.varint();
466
+ const change = readChange(from, keys);
467
+ if (change === 0) throw new RangeError("the frame deletes an element of an array, which nothing does");
468
+ changes[index] = change;
469
+ }
470
+ return [changes, length];
471
+ }
472
+
473
+ /**
474
+ * Reads a binary `patch` frame into the same object its JSON form would
475
+ * parse to. `keys` is the table of the connection the frame came on: start
476
+ * each connection with an empty array and hand in the same one every time.
477
+ * The frame's key definitions are added to it, after it has been emptied if
478
+ * the frame says to forget.
479
+ *
480
+ * Throws if the bytes are not a frame of this format. The connection's
481
+ * table can then no longer be trusted: reconnect.
482
+ */
483
+ export function decodePatchFrame(bytes: Uint8Array, keys: string[]): PatchFrame {
484
+ const from = new Reader(bytes);
485
+ if (from.byte() !== MAGIC) throw new RangeError("not a binary patch frame");
486
+ const flags = from.byte();
487
+ // The fields in the order the JSON frame has them.
488
+ const frame = { t: "patch", seq: from.varint(), tick: from.varint() } as PatchFrame;
489
+ if (flags & FLAG_FROM) frame.from = from.varint();
490
+ if (flags & FLAG_SHOWS) frame.c = from.varint();
491
+ if (flags & FLAG_FORGET) keys.length = 0;
492
+ for (let left = from.varint(); left > 0; left--) keys.push(from.string());
493
+ frame.p = readPatch(from, keys);
494
+ if (!from.done) throw new RangeError("the frame is longer than what it holds");
495
+ return frame;
496
+ }