@tinyshed/tinystore 0.1.0-rc.1

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 (100) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +262 -0
  3. package/bin/tinystore.js +50 -0
  4. package/dist/background.d.ts +30 -0
  5. package/dist/background.js +93 -0
  6. package/dist/blobs.d.ts +98 -0
  7. package/dist/blobs.js +299 -0
  8. package/dist/cancel.d.ts +14 -0
  9. package/dist/cancel.js +22 -0
  10. package/dist/clock.d.ts +21 -0
  11. package/dist/clock.js +35 -0
  12. package/dist/config.d.ts +60 -0
  13. package/dist/config.js +417 -0
  14. package/dist/connection.d.ts +78 -0
  15. package/dist/connection.js +405 -0
  16. package/dist/console.d.ts +48 -0
  17. package/dist/console.js +195 -0
  18. package/dist/errors.d.ts +103 -0
  19. package/dist/errors.js +158 -0
  20. package/dist/handles.d.ts +28 -0
  21. package/dist/handles.js +37 -0
  22. package/dist/index.d.ts +21 -0
  23. package/dist/index.js +7 -0
  24. package/dist/jobs.d.ts +304 -0
  25. package/dist/jobs.js +684 -0
  26. package/dist/kv.d.ts +283 -0
  27. package/dist/kv.js +815 -0
  28. package/dist/limiter.d.ts +45 -0
  29. package/dist/limiter.js +68 -0
  30. package/dist/logger.d.ts +96 -0
  31. package/dist/logger.js +243 -0
  32. package/dist/metrics.d.ts +249 -0
  33. package/dist/metrics.js +610 -0
  34. package/dist/once.d.ts +31 -0
  35. package/dist/once.js +116 -0
  36. package/dist/quota.d.ts +44 -0
  37. package/dist/quota.js +98 -0
  38. package/dist/records.d.ts +182 -0
  39. package/dist/records.js +346 -0
  40. package/dist/runtime/bun.d.ts +2 -0
  41. package/dist/runtime/bun.js +164 -0
  42. package/dist/runtime/node.d.ts +2 -0
  43. package/dist/runtime/node.js +157 -0
  44. package/dist/runtime/shared.d.ts +25 -0
  45. package/dist/runtime/shared.js +45 -0
  46. package/dist/runtime.d.ts +48 -0
  47. package/dist/runtime.js +4 -0
  48. package/dist/schema.d.ts +39 -0
  49. package/dist/schema.js +21 -0
  50. package/dist/session.d.ts +120 -0
  51. package/dist/session.js +546 -0
  52. package/dist/sql.d.ts +121 -0
  53. package/dist/sql.js +342 -0
  54. package/dist/store.d.ts +103 -0
  55. package/dist/store.js +153 -0
  56. package/dist/time.d.ts +35 -0
  57. package/dist/time.js +44 -0
  58. package/dist/trace.d.ts +18 -0
  59. package/dist/trace.js +22 -0
  60. package/dist/wire/codec.d.ts +90 -0
  61. package/dist/wire/codec.js +383 -0
  62. package/dist/wire/frame.d.ts +41 -0
  63. package/dist/wire/frame.js +102 -0
  64. package/dist/wire/messages.d.ts +1403 -0
  65. package/dist/wire/messages.js +472 -0
  66. package/dist/wire/msgpack.d.ts +93 -0
  67. package/dist/wire/msgpack.js +680 -0
  68. package/package.json +40 -0
  69. package/src/background.ts +108 -0
  70. package/src/blobs.ts +437 -0
  71. package/src/cancel.ts +26 -0
  72. package/src/clock.ts +45 -0
  73. package/src/config.ts +501 -0
  74. package/src/connection.ts +512 -0
  75. package/src/console.ts +228 -0
  76. package/src/errors.ts +211 -0
  77. package/src/handles.ts +68 -0
  78. package/src/index.ts +92 -0
  79. package/src/jobs.ts +963 -0
  80. package/src/kv.ts +1093 -0
  81. package/src/limiter.ts +99 -0
  82. package/src/logger.ts +326 -0
  83. package/src/metrics.ts +896 -0
  84. package/src/once.ts +142 -0
  85. package/src/quota.ts +137 -0
  86. package/src/records.ts +537 -0
  87. package/src/runtime/bun.ts +190 -0
  88. package/src/runtime/node.ts +177 -0
  89. package/src/runtime/shared.ts +61 -0
  90. package/src/runtime.ts +57 -0
  91. package/src/schema.ts +69 -0
  92. package/src/session.ts +665 -0
  93. package/src/sql.ts +478 -0
  94. package/src/store.ts +219 -0
  95. package/src/time.ts +87 -0
  96. package/src/trace.ts +32 -0
  97. package/src/wire/codec.ts +445 -0
  98. package/src/wire/frame.ts +139 -0
  99. package/src/wire/messages.ts +562 -0
  100. package/src/wire/msgpack.ts +712 -0
@@ -0,0 +1,712 @@
1
+ // The MessagePack profile of docs/wire.md, written for this SDK rather than
2
+ // taken from a library: a general one accepts a float 32, an extension, a key
3
+ // twice or a value nested nine deep, which the profile refuses, and rounds a
4
+ // 64-bit integer unless told. An encoder writes the shortest form of every
5
+ // integer, length and count and every float in eight bytes, so that a vector
6
+ // compares byte for byte; a decoder takes any valid form.
7
+
8
+ import { InvalidError, ProtocolError } from '../errors.ts'
9
+
10
+ const NIL = 0xc0
11
+ const FALSE = 0xc2
12
+ const TRUE = 0xc3
13
+ const BIN8 = 0xc4
14
+ const BIN16 = 0xc5
15
+ const BIN32 = 0xc6
16
+ const FLOAT64 = 0xcb
17
+ const UINT8 = 0xcc
18
+ const UINT16 = 0xcd
19
+ const UINT32 = 0xce
20
+ const UINT64 = 0xcf
21
+ const INT8 = 0xd0
22
+ const INT16 = 0xd1
23
+ const INT32 = 0xd2
24
+ const INT64 = 0xd3
25
+ const STR8 = 0xd9
26
+ const STR16 = 0xda
27
+ const STR32 = 0xdb
28
+ const ARRAY16 = 0xdc
29
+ const ARRAY32 = 0xdd
30
+ const MAP16 = 0xde
31
+ const MAP32 = 0xdf
32
+ const FIXMAP = 0x80
33
+ const FIXARRAY = 0x90
34
+ const FIXSTR = 0xa0
35
+ const NEGFIX = 0xe0
36
+
37
+ /** How deeply maps and arrays may nest in a message. */
38
+ export const maxDepth = 8
39
+
40
+ const encoder = new TextEncoder()
41
+
42
+ // fatal refuses bytes that are not UTF-8, and ignoreBOM keeps a U+FEFF that
43
+ // begins a str as the character it is, where the default drops it
44
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
45
+
46
+ const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER)
47
+ const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER)
48
+
49
+ /** Writes one message, its buffer growing as it must. */
50
+ export class Writer {
51
+ #bytes: Uint8Array
52
+ #view: DataView
53
+ #length = 0
54
+
55
+ constructor(capacity = 128) {
56
+ this.#bytes = new Uint8Array(capacity)
57
+ this.#view = new DataView(this.#bytes.buffer)
58
+ }
59
+
60
+ get length(): number {
61
+ return this.#length
62
+ }
63
+
64
+ /** A copy of what was written. */
65
+ bytes(): Uint8Array {
66
+ return this.#bytes.slice(0, this.#length)
67
+ }
68
+
69
+ /** Makes room for n bytes at the end and says where they begin. */
70
+ #room(n: number): number {
71
+ const at = this.#length
72
+ const need = at + n
73
+ if (need > this.#bytes.length) {
74
+ let size = this.#bytes.length * 2
75
+ while (size < need) {
76
+ size *= 2
77
+ }
78
+ const grown = new Uint8Array(size)
79
+ grown.set(this.#bytes.subarray(0, at))
80
+ this.#bytes = grown
81
+ this.#view = new DataView(grown.buffer)
82
+ }
83
+ this.#length = need
84
+ return at
85
+ }
86
+
87
+ // room first: in this.#bytes[this.#room(1)] the old buffer is read before
88
+ // #room grows it, and a byte at 128, 256, 512… went into the old one
89
+ #byte(b: number): void {
90
+ const at = this.#room(1)
91
+ this.#bytes[at] = b
92
+ }
93
+
94
+ nil(): void {
95
+ this.#byte(NIL)
96
+ }
97
+
98
+ bool(v: boolean): void {
99
+ this.#byte(v ? TRUE : FALSE)
100
+ }
101
+
102
+ /**
103
+ * Writes a value from 0 in the unsigned family's shortest form:
104
+ *
105
+ * 7 → 07 300 → cd 01 2c 70000 → ce 00 01 11 70
106
+ */
107
+ uint(v: number | bigint): void {
108
+ if (typeof v === 'bigint') {
109
+ if (v < 0n || v > 0xffff_ffff_ffff_ffffn) {
110
+ throw new InvalidError(`${v} is not an unsigned 64-bit integer`)
111
+ }
112
+ if (v > MAX_SAFE) {
113
+ const at = this.#room(9)
114
+ this.#bytes[at] = UINT64
115
+ this.#view.setBigUint64(at + 1, v)
116
+ return
117
+ }
118
+ v = Number(v)
119
+ }
120
+ if (!Number.isSafeInteger(v) || v < 0) {
121
+ throw new InvalidError(
122
+ `${v} is not an unsigned integer a number holds exactly; give a bigint`,
123
+ )
124
+ }
125
+ if (v <= 0x7f) {
126
+ this.#byte(v)
127
+ } else if (v <= 0xff) {
128
+ const at = this.#room(2)
129
+ this.#bytes[at] = UINT8
130
+ this.#bytes[at + 1] = v
131
+ } else if (v <= 0xffff) {
132
+ const at = this.#room(3)
133
+ this.#bytes[at] = UINT16
134
+ this.#view.setUint16(at + 1, v)
135
+ } else if (v <= 0xffff_ffff) {
136
+ const at = this.#room(5)
137
+ this.#bytes[at] = UINT32
138
+ this.#view.setUint32(at + 1, v)
139
+ } else {
140
+ const at = this.#room(9)
141
+ this.#bytes[at] = UINT64
142
+ this.#view.setBigUint64(at + 1, BigInt(v))
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Writes a value from 0 as uint does, and a negative one in the signed
148
+ * family's shortest form:
149
+ *
150
+ * -1 → ff -33 → d0 df -300 → d1 fe d4
151
+ */
152
+ int(v: number | bigint): void {
153
+ if (typeof v === 'bigint') {
154
+ if (v >= 0n) {
155
+ this.uint(v)
156
+ return
157
+ }
158
+ if (v < -0x8000_0000_0000_0000n) {
159
+ throw new InvalidError(`${v} is not a 64-bit integer`)
160
+ }
161
+ if (v < MIN_SAFE) {
162
+ const at = this.#room(9)
163
+ this.#bytes[at] = INT64
164
+ this.#view.setBigInt64(at + 1, v)
165
+ return
166
+ }
167
+ v = Number(v)
168
+ }
169
+ if (!Number.isSafeInteger(v)) {
170
+ throw new InvalidError(`${v} is not an integer a number holds exactly; give a bigint`)
171
+ }
172
+ if (v >= 0) {
173
+ this.uint(v)
174
+ } else if (v >= -32) {
175
+ this.#byte(v & 0xff)
176
+ } else if (v >= -0x80) {
177
+ const at = this.#room(2)
178
+ this.#bytes[at] = INT8
179
+ this.#view.setInt8(at + 1, v)
180
+ } else if (v >= -0x8000) {
181
+ const at = this.#room(3)
182
+ this.#bytes[at] = INT16
183
+ this.#view.setInt16(at + 1, v)
184
+ } else if (v >= -0x8000_0000) {
185
+ const at = this.#room(5)
186
+ this.#bytes[at] = INT32
187
+ this.#view.setInt32(at + 1, v)
188
+ } else {
189
+ const at = this.#room(9)
190
+ this.#bytes[at] = INT64
191
+ this.#view.setBigInt64(at + 1, BigInt(v))
192
+ }
193
+ }
194
+
195
+ /** Writes a float 64 with its bits: -0 → cb 80 00 00 00 00 00 00 00. */
196
+ float(v: number): void {
197
+ const at = this.#room(9)
198
+ this.#bytes[at] = FLOAT64
199
+ this.#view.setFloat64(at + 1, v)
200
+ }
201
+
202
+ /**
203
+ * Writes text as UTF-8. A string holding a lone surrogate has no UTF-8 to
204
+ * write and is refused, rather than changed into U+FFFD.
205
+ */
206
+ str(s: string): void {
207
+ if (!s.isWellFormed()) {
208
+ throw new InvalidError('a string with a lone surrogate, which UTF-8 cannot spell')
209
+ }
210
+ // room for the longest UTF-8 the string may take behind the longest
211
+ // header that length needs; the header shrinks to its shortest after
212
+ const most = s.length * 3
213
+ const header = headerOf(most)
214
+ const at = this.#room(header + most)
215
+ const { written } = encoder.encodeInto(s, this.#bytes.subarray(at + header))
216
+ const shortest = headerOf(written)
217
+ if (shortest !== header) {
218
+ this.#bytes.copyWithin(at + shortest, at + header, at + header + written)
219
+ }
220
+ this.#length = at + shortest + written
221
+ this.#strHeader(at, written)
222
+ }
223
+
224
+ #strHeader(at: number, n: number): void {
225
+ if (n <= 31) {
226
+ this.#bytes[at] = FIXSTR | n
227
+ } else if (n <= 0xff) {
228
+ this.#bytes[at] = STR8
229
+ this.#bytes[at + 1] = n
230
+ } else if (n <= 0xffff) {
231
+ this.#bytes[at] = STR16
232
+ this.#view.setUint16(at + 1, n)
233
+ } else {
234
+ this.#bytes[at] = STR32
235
+ this.#view.setUint32(at + 1, n)
236
+ }
237
+ }
238
+
239
+ bin(b: Uint8Array): void {
240
+ const n = b.length
241
+ let at: number
242
+ if (n <= 0xff) {
243
+ at = this.#room(2 + n)
244
+ this.#bytes[at] = BIN8
245
+ this.#bytes[at + 1] = n
246
+ at += 2
247
+ } else if (n <= 0xffff) {
248
+ at = this.#room(3 + n)
249
+ this.#bytes[at] = BIN16
250
+ this.#view.setUint16(at + 1, n)
251
+ at += 3
252
+ } else {
253
+ at = this.#room(5 + n)
254
+ this.#bytes[at] = BIN32
255
+ this.#view.setUint32(at + 1, n)
256
+ at += 5
257
+ }
258
+ this.#bytes.set(b, at)
259
+ }
260
+
261
+ array(n: number): void {
262
+ this.#count(n, FIXARRAY, ARRAY16, ARRAY32)
263
+ }
264
+
265
+ map(n: number): void {
266
+ this.#count(n, FIXMAP, MAP16, MAP32)
267
+ }
268
+
269
+ #count(n: number, fix: number, two: number, four: number): void {
270
+ if (n <= 15) {
271
+ this.#byte(fix | n)
272
+ } else if (n <= 0xffff) {
273
+ const at = this.#room(3)
274
+ this.#bytes[at] = two
275
+ this.#view.setUint16(at + 1, n)
276
+ } else {
277
+ const at = this.#room(5)
278
+ this.#bytes[at] = four
279
+ this.#view.setUint32(at + 1, n)
280
+ }
281
+ }
282
+ }
283
+
284
+ /** The bytes a str's header takes for a length. */
285
+ function headerOf(n: number): number {
286
+ if (n <= 31) {
287
+ return 1
288
+ }
289
+ if (n <= 0xff) {
290
+ return 2
291
+ }
292
+ return n <= 0xffff ? 3 : 5
293
+ }
294
+
295
+ /** The kind of the next value a Reader holds. */
296
+ export type Type = 'nil' | 'bool' | 'int' | 'float' | 'str' | 'bin' | 'array' | 'map' | 'invalid'
297
+
298
+ /** The type a value's first byte says. */
299
+ export function typeOf(b: number): Type {
300
+ if (b <= 0x7f || b >= NEGFIX || (b >= UINT8 && b <= INT64)) {
301
+ return 'int'
302
+ }
303
+ if ((b & 0xf0) === FIXMAP || b === MAP16 || b === MAP32) {
304
+ return 'map'
305
+ }
306
+ if ((b & 0xf0) === FIXARRAY || b === ARRAY16 || b === ARRAY32) {
307
+ return 'array'
308
+ }
309
+ if ((b & 0xe0) === FIXSTR || (b >= STR8 && b <= STR32)) {
310
+ return 'str'
311
+ }
312
+ if (b >= BIN8 && b <= BIN32) {
313
+ return 'bin'
314
+ }
315
+ if (b === NIL) {
316
+ return 'nil'
317
+ }
318
+ if (b === FALSE || b === TRUE) {
319
+ return 'bool'
320
+ }
321
+ // a float 32, an extension, or the byte never used
322
+ return b === FLOAT64 ? 'float' : 'invalid'
323
+ }
324
+
325
+ const typeNames: Record<Type, string> = {
326
+ nil: 'nil',
327
+ bool: 'a bool',
328
+ int: 'an integer',
329
+ float: 'a float',
330
+ str: 'a str',
331
+ bin: 'a bin',
332
+ array: 'an array',
333
+ map: 'a map',
334
+ invalid: 'an invalid type',
335
+ }
336
+
337
+ /**
338
+ * Reads one message and checks the profile as it goes: a value the profile
339
+ * refuses, one past the bytes left, or bytes after the message throw a
340
+ * ProtocolError. What it returns of the body, a bin, is a view of the body.
341
+ */
342
+ export class Reader {
343
+ readonly #bytes: Uint8Array
344
+ readonly #view: DataView
345
+ #at = 0
346
+ #depth = 0
347
+
348
+ constructor(bytes: Uint8Array) {
349
+ this.#bytes = bytes
350
+ this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
351
+ }
352
+
353
+ /** Refuses bytes left after the one value a message is. */
354
+ end(): void {
355
+ if (this.#at !== this.#bytes.length) {
356
+ throw fail(`${this.#bytes.length - this.#at} bytes after the message`)
357
+ }
358
+ }
359
+
360
+ /** The next value's type, without reading it. */
361
+ type(): Type {
362
+ const b = this.#bytes[this.#at]
363
+ return b === undefined ? 'invalid' : typeOf(b)
364
+ }
365
+
366
+ #next(): number {
367
+ const b = this.#bytes[this.#at]
368
+ if (b === undefined) {
369
+ throw fail('the body ends inside a value')
370
+ }
371
+ this.#at++
372
+ return b
373
+ }
374
+
375
+ #take(n: number): number {
376
+ const left = this.#bytes.length - this.#at
377
+ if (n > left) {
378
+ throw fail(`${n} bytes asked for where ${left} are left`)
379
+ }
380
+ const at = this.#at
381
+ this.#at += n
382
+ return at
383
+ }
384
+
385
+ /**
386
+ * Reads any encoding of an integer as a bigint; unsigned says it came in the
387
+ * unsigned family, so that a uint 64 past the int 64 range reads as its value
388
+ */
389
+ #integer(want: string): bigint {
390
+ const b = this.#next()
391
+ if (b <= 0x7f) {
392
+ return BigInt(b)
393
+ }
394
+ if (b >= NEGFIX) {
395
+ return BigInt(b - 0x100)
396
+ }
397
+ switch (b) {
398
+ case UINT8:
399
+ return BigInt(this.#bytes[this.#take(1)]!)
400
+ case UINT16:
401
+ return BigInt(this.#view.getUint16(this.#take(2)))
402
+ case UINT32:
403
+ return BigInt(this.#view.getUint32(this.#take(4)))
404
+ case UINT64:
405
+ return this.#view.getBigUint64(this.#take(8))
406
+ case INT8:
407
+ return BigInt(this.#view.getInt8(this.#take(1)))
408
+ case INT16:
409
+ return BigInt(this.#view.getInt16(this.#take(2)))
410
+ case INT32:
411
+ return BigInt(this.#view.getInt32(this.#take(4)))
412
+ case INT64:
413
+ return this.#view.getBigInt64(this.#take(8))
414
+ }
415
+ throw fail(`${typeNames[typeOf(b)]} where ${want} belongs`)
416
+ }
417
+
418
+ /** Reads an unsigned integer in any encoding of its value, a bigint. */
419
+ uint64(): bigint {
420
+ const v = this.#integer('an unsigned integer')
421
+ if (v < 0n) {
422
+ throw fail(`${v} where an unsigned integer belongs`)
423
+ }
424
+ return v
425
+ }
426
+
427
+ /** Reads a signed 64-bit integer in any encoding of its value, a bigint. */
428
+ int64(): bigint {
429
+ const v = this.#integer('an integer')
430
+ if (v > 0x7fff_ffff_ffff_ffffn) {
431
+ throw fail(`${v} where an int64 belongs`)
432
+ }
433
+ return v
434
+ }
435
+
436
+ /** Reads an unsigned integer a number holds exactly. */
437
+ uint(): number {
438
+ const v = this.uint64()
439
+ if (v > MAX_SAFE) {
440
+ throw fail(`${v}, past what a number holds exactly, where a number belongs`)
441
+ }
442
+ return Number(v)
443
+ }
444
+
445
+ /** Reads an integer a number holds exactly. */
446
+ int(): number {
447
+ const v = this.int64()
448
+ if (v > MAX_SAFE || v < MIN_SAFE) {
449
+ throw fail(`${v}, past what a number holds exactly, where a number belongs`)
450
+ }
451
+ return Number(v)
452
+ }
453
+
454
+ /**
455
+ * Reads a float 64, or an integer a float 64 holds exactly, since a
456
+ * JavaScript encoder may write 3.0 as 3.
457
+ */
458
+ float(): number {
459
+ const t = this.type()
460
+ if (t === 'float') {
461
+ this.#at++
462
+ return this.#view.getFloat64(this.#take(8))
463
+ }
464
+ if (t !== 'int') {
465
+ throw fail(`${typeNames[t]} where a float belongs`)
466
+ }
467
+ const v = this.#integer('a float')
468
+ const f = Number(v)
469
+ // a float at 2^64 does not convert back to a uint 64, though BigInt reads it
470
+ if (f >= 2 ** 64 || BigInt(f) !== v) {
471
+ throw fail(`${v}, which a float 64 does not hold exactly`)
472
+ }
473
+ return f
474
+ }
475
+
476
+ bool(): boolean {
477
+ const b = this.#next()
478
+ if (b === TRUE) {
479
+ return true
480
+ }
481
+ if (b !== FALSE) {
482
+ throw fail(`${typeNames[typeOf(b)]} where a bool belongs`)
483
+ }
484
+ return false
485
+ }
486
+
487
+ /** Reads a nil if one is next and says so, leaving any other value. */
488
+ nil(): boolean {
489
+ if (this.type() === 'nil') {
490
+ this.#at++
491
+ return true
492
+ }
493
+ return false
494
+ }
495
+
496
+ /** Reads a str, which must be valid UTF-8. */
497
+ str(): string {
498
+ const b = this.#next()
499
+ let n: number
500
+ if ((b & 0xe0) === FIXSTR) {
501
+ n = b & 0x1f
502
+ } else if (b === STR8) {
503
+ n = this.#bytes[this.#take(1)]!
504
+ } else if (b === STR16) {
505
+ n = this.#view.getUint16(this.#take(2))
506
+ } else if (b === STR32) {
507
+ n = this.#view.getUint32(this.#take(4))
508
+ } else {
509
+ throw fail(`${typeNames[typeOf(b)]} where a str belongs`)
510
+ }
511
+ const at = this.#take(n)
512
+ try {
513
+ return decoder.decode(this.#bytes.subarray(at, at + n))
514
+ } catch {
515
+ throw fail('a str that is not UTF-8')
516
+ }
517
+ }
518
+
519
+ /** Reads a bin as a view of the body; an empty one is an empty array. */
520
+ bin(): Uint8Array {
521
+ const b = this.#next()
522
+ let n: number
523
+ if (b === BIN8) {
524
+ n = this.#bytes[this.#take(1)]!
525
+ } else if (b === BIN16) {
526
+ n = this.#view.getUint16(this.#take(2))
527
+ } else if (b === BIN32) {
528
+ n = this.#view.getUint32(this.#take(4))
529
+ } else {
530
+ throw fail(`${typeNames[typeOf(b)]} where a bin belongs`)
531
+ }
532
+ const at = this.#take(n)
533
+ return this.#bytes.subarray(at, at + n)
534
+ }
535
+
536
+ /**
537
+ * Reads an array's count and enters it; leave once its elements are read.
538
+ * A count past the bytes left is refused before anything is made of it,
539
+ * since every element takes at least a byte.
540
+ */
541
+ array(): number {
542
+ return this.#enter('array', FIXARRAY, ARRAY16, ARRAY32, 1)
543
+ }
544
+
545
+ /** Reads a map's count and enters it, each entry taking two bytes at least. */
546
+ map(): number {
547
+ return this.#enter('map', FIXMAP, MAP16, MAP32, 2)
548
+ }
549
+
550
+ leave(): void {
551
+ this.#depth--
552
+ }
553
+
554
+ #enter(kind: Type, fix: number, two: number, four: number, each: number): number {
555
+ const b = this.#next()
556
+ let n: number
557
+ if ((b & 0xf0) === fix) {
558
+ n = b & 0x0f
559
+ } else if (b === two) {
560
+ n = this.#view.getUint16(this.#take(2))
561
+ } else if (b === four) {
562
+ n = this.#view.getUint32(this.#take(4))
563
+ } else {
564
+ throw fail(`${typeNames[typeOf(b)]} where ${typeNames[kind]} belongs`)
565
+ }
566
+ const left = this.#bytes.length - this.#at
567
+ if (n * each > left) {
568
+ throw fail(`${typeNames[kind]} of ${n} elements in ${left} bytes`)
569
+ }
570
+ if (this.#depth === maxDepth) {
571
+ throw fail(`${typeNames[kind]} nested deeper than ${maxDepth}`)
572
+ }
573
+ this.#depth++
574
+ return n
575
+ }
576
+
577
+ /**
578
+ * Reads a map with unsigned keys, a message or a field of one, calling each
579
+ * with its key and the value next: it reads the value, or returns false to
580
+ * have it skipped, well formed and within bounds. A key twice is refused.
581
+ */
582
+ fields(each: (key: number) => boolean): void {
583
+ const n = this.map()
584
+ const seen = new Keys()
585
+ for (let i = 0; i < n; i++) {
586
+ const key = this.uint()
587
+ if (!seen.add(key)) {
588
+ throw fail(`key ${key} twice`)
589
+ }
590
+ const at = this.#at
591
+ if (!each(key) || this.#at === at) {
592
+ this.#at = at
593
+ this.skip()
594
+ }
595
+ }
596
+ this.leave()
597
+ }
598
+
599
+ /** Reads a map of names, an error's what or a series' labels, as fields does. */
600
+ names(each: (name: string) => void): void {
601
+ const n = this.map()
602
+ const seen = new Set<string>()
603
+ for (let i = 0; i < n; i++) {
604
+ const name = this.str()
605
+ if (seen.has(name)) {
606
+ throw fail(`name ${JSON.stringify(name)} twice`)
607
+ }
608
+ seen.add(name)
609
+ const at = this.#at
610
+ each(name)
611
+ if (this.#at === at) {
612
+ this.skip()
613
+ }
614
+ }
615
+ this.leave()
616
+ }
617
+
618
+ /** Reads an array, calling each with an element's index and the element next. */
619
+ items(each: (index: number) => void): void {
620
+ const n = this.array()
621
+ for (let i = 0; i < n; i++) {
622
+ const at = this.#at
623
+ each(i)
624
+ if (this.#at === at) {
625
+ this.skip()
626
+ }
627
+ }
628
+ this.leave()
629
+ }
630
+
631
+ /** Reads past one value, checking it is well formed as if it were read. */
632
+ skip(): void {
633
+ switch (this.type()) {
634
+ case 'nil':
635
+ case 'bool':
636
+ this.#at++
637
+ return
638
+ case 'int':
639
+ this.#integer('an integer')
640
+ return
641
+ case 'float':
642
+ this.float()
643
+ return
644
+ case 'str':
645
+ this.str()
646
+ return
647
+ case 'bin':
648
+ this.bin()
649
+ return
650
+ case 'array':
651
+ this.items(() => this.skip())
652
+ return
653
+ case 'map':
654
+ this.#skipMap()
655
+ return
656
+ }
657
+ throw fail(this.#describe())
658
+ }
659
+
660
+ // a map's keys are unsigned integers or names, as a message's maps are
661
+ #skipMap(): void {
662
+ const at = this.#at
663
+ const n = this.map()
664
+ const named = n > 0 && this.type() === 'str'
665
+ this.#at = at
666
+ this.#depth--
667
+ if (named) {
668
+ this.names(() => this.skip())
669
+ } else {
670
+ this.fields(() => false)
671
+ }
672
+ }
673
+
674
+ #describe(): string {
675
+ const b = this.#bytes[this.#at]
676
+ if (b === undefined) {
677
+ return 'the body ends where a value belongs'
678
+ }
679
+ if (b === 0xca) {
680
+ return 'a float 32, which the profile does not allow'
681
+ }
682
+ if (b === 0xc1) {
683
+ return 'the type byte 0xc1, which MessagePack never uses'
684
+ }
685
+ return `the extension type 0x${b.toString(16)}, which the profile does not allow`
686
+ }
687
+ }
688
+
689
+ /** The keys a map has shown: those under 32 in bits, the rest in a set. */
690
+ class Keys {
691
+ #low = 0
692
+ #high: Set<number> | undefined
693
+
694
+ add(key: number): boolean {
695
+ if (key < 32) {
696
+ const bit = 1 << key
697
+ const fresh = (this.#low & bit) === 0
698
+ this.#low |= bit
699
+ return fresh
700
+ }
701
+ this.#high ??= new Set()
702
+ if (this.#high.has(key)) {
703
+ return false
704
+ }
705
+ this.#high.add(key)
706
+ return true
707
+ }
708
+ }
709
+
710
+ function fail(reason: string): ProtocolError {
711
+ return new ProtocolError(`invalid message: ${reason}`)
712
+ }