@atproto/lex-cbor 0.0.16 → 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.
package/dist/index.mjs DELETED
@@ -1,1723 +0,0 @@
1
- import { decodeCid, ifCid, cidForCbor } from "@atproto/lex-data";
2
- const objectTypeNames = [
3
- "Object",
4
- // for Object.create(null) and other non-plain objects
5
- "RegExp",
6
- "Date",
7
- "Error",
8
- "Map",
9
- "Set",
10
- "WeakMap",
11
- "WeakSet",
12
- "ArrayBuffer",
13
- "SharedArrayBuffer",
14
- "DataView",
15
- "Promise",
16
- "URL",
17
- "HTMLElement",
18
- "Int8Array",
19
- "Uint8ClampedArray",
20
- "Int16Array",
21
- "Uint16Array",
22
- "Int32Array",
23
- "Uint32Array",
24
- "Float32Array",
25
- "Float64Array",
26
- "BigInt64Array",
27
- "BigUint64Array"
28
- ];
29
- function is(value) {
30
- if (value === null) {
31
- return "null";
32
- }
33
- if (value === void 0) {
34
- return "undefined";
35
- }
36
- if (value === true || value === false) {
37
- return "boolean";
38
- }
39
- const typeOf = typeof value;
40
- if (typeOf === "string" || typeOf === "number" || typeOf === "bigint" || typeOf === "symbol") {
41
- return typeOf;
42
- }
43
- if (typeOf === "function") {
44
- return "Function";
45
- }
46
- if (Array.isArray(value)) {
47
- return "Array";
48
- }
49
- if (value instanceof Uint8Array) {
50
- return "Uint8Array";
51
- }
52
- if (value.constructor === Object) {
53
- return "Object";
54
- }
55
- const objectType = getObjectType(value);
56
- if (objectType) {
57
- return objectType;
58
- }
59
- return "Object";
60
- }
61
- function getObjectType(value) {
62
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
63
- if (objectTypeNames.includes(objectTypeName)) {
64
- return objectTypeName;
65
- }
66
- return void 0;
67
- }
68
- class Type {
69
- /**
70
- * @param {number} major
71
- * @param {string} name
72
- * @param {boolean} terminal
73
- */
74
- constructor(major, name, terminal) {
75
- this.major = major;
76
- this.majorEncoded = major << 5;
77
- this.name = name;
78
- this.terminal = terminal;
79
- }
80
- /* c8 ignore next 3 */
81
- toString() {
82
- return `Type[${this.major}].${this.name}`;
83
- }
84
- /**
85
- * @param {Type} typ
86
- * @returns {number}
87
- */
88
- compare(typ) {
89
- return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
90
- }
91
- /**
92
- * Check equality between two Type instances. Safe to use across different
93
- * copies of the Type class (e.g., when bundlers duplicate the module).
94
- * (major, name) uniquely identifies a Type; terminal is implied by these.
95
- * @param {Type} a
96
- * @param {Type} b
97
- * @returns {boolean}
98
- */
99
- static equals(a, b) {
100
- return a === b || a.major === b.major && a.name === b.name;
101
- }
102
- }
103
- Type.uint = new Type(0, "uint", true);
104
- Type.negint = new Type(1, "negint", true);
105
- Type.bytes = new Type(2, "bytes", true);
106
- Type.string = new Type(3, "string", true);
107
- Type.array = new Type(4, "array", false);
108
- Type.map = new Type(5, "map", false);
109
- Type.tag = new Type(6, "tag", false);
110
- Type.float = new Type(7, "float", true);
111
- Type.false = new Type(7, "false", true);
112
- Type.true = new Type(7, "true", true);
113
- Type.null = new Type(7, "null", true);
114
- Type.undefined = new Type(7, "undefined", true);
115
- Type.break = new Type(7, "break", true);
116
- class Token {
117
- /**
118
- * @param {Type} type
119
- * @param {any} [value]
120
- * @param {number} [encodedLength]
121
- */
122
- constructor(type, value, encodedLength) {
123
- this.type = type;
124
- this.value = value;
125
- this.encodedLength = encodedLength;
126
- this.encodedBytes = void 0;
127
- this.byteValue = void 0;
128
- }
129
- /* c8 ignore next 3 */
130
- toString() {
131
- return `Token[${this.type}].${this.value}`;
132
- }
133
- }
134
- const useBuffer = globalThis.process && // @ts-ignore
135
- !globalThis.process.browser && // @ts-ignore
136
- globalThis.Buffer && // @ts-ignore
137
- typeof globalThis.Buffer.isBuffer === "function";
138
- const textEncoder = new TextEncoder();
139
- function isBuffer(buf) {
140
- return useBuffer && globalThis.Buffer.isBuffer(buf);
141
- }
142
- function asU8A(buf) {
143
- if (!(buf instanceof Uint8Array)) {
144
- return Uint8Array.from(buf);
145
- }
146
- return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf;
147
- }
148
- const FROM_STRING_THRESHOLD_BUFFER = 24;
149
- const FROM_STRING_THRESHOLD_TEXTENCODER = 200;
150
- const fromString = useBuffer ? (
151
- // eslint-disable-line operator-linebreak
152
- /**
153
- * @param {string} string
154
- */
155
- (string) => {
156
- return string.length >= FROM_STRING_THRESHOLD_BUFFER ? (
157
- // eslint-disable-line operator-linebreak
158
- // @ts-ignore
159
- globalThis.Buffer.from(string)
160
- ) : utf8ToBytes(string);
161
- }
162
- ) : (
163
- // eslint-disable-line operator-linebreak
164
- /**
165
- * @param {string} string
166
- */
167
- (string) => {
168
- return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string);
169
- }
170
- );
171
- const fromArray = (arr) => {
172
- return Uint8Array.from(arr);
173
- };
174
- const slice = useBuffer ? (
175
- // eslint-disable-line operator-linebreak
176
- /**
177
- * @param {Uint8Array} bytes
178
- * @param {number} start
179
- * @param {number} end
180
- */
181
- // Buffer.slice() returns a view, not a copy, so we need special handling
182
- (bytes, start, end) => {
183
- if (isBuffer(bytes)) {
184
- return new Uint8Array(bytes.subarray(start, end));
185
- }
186
- return bytes.slice(start, end);
187
- }
188
- ) : (
189
- // eslint-disable-line operator-linebreak
190
- /**
191
- * @param {Uint8Array} bytes
192
- * @param {number} start
193
- * @param {number} end
194
- */
195
- (bytes, start, end) => {
196
- return bytes.slice(start, end);
197
- }
198
- );
199
- const concat = useBuffer ? (
200
- // eslint-disable-line operator-linebreak
201
- /**
202
- * @param {Uint8Array[]} chunks
203
- * @param {number} length
204
- * @returns {Uint8Array}
205
- */
206
- (chunks, length) => {
207
- chunks = chunks.map((c) => c instanceof Uint8Array ? c : (
208
- // eslint-disable-line operator-linebreak
209
- // @ts-ignore
210
- globalThis.Buffer.from(c)
211
- ));
212
- return asU8A(globalThis.Buffer.concat(chunks, length));
213
- }
214
- ) : (
215
- // eslint-disable-line operator-linebreak
216
- /**
217
- * @param {Uint8Array[]} chunks
218
- * @param {number} length
219
- * @returns {Uint8Array}
220
- */
221
- (chunks, length) => {
222
- const out = new Uint8Array(length);
223
- let off = 0;
224
- for (let b of chunks) {
225
- if (off + b.length > out.length) {
226
- b = b.subarray(0, out.length - off);
227
- }
228
- out.set(b, off);
229
- off += b.length;
230
- }
231
- return out;
232
- }
233
- );
234
- const alloc = useBuffer ? (
235
- // eslint-disable-line operator-linebreak
236
- /**
237
- * @param {number} size
238
- * @returns {Uint8Array}
239
- */
240
- (size) => {
241
- return globalThis.Buffer.allocUnsafe(size);
242
- }
243
- ) : (
244
- // eslint-disable-line operator-linebreak
245
- /**
246
- * @param {number} size
247
- * @returns {Uint8Array}
248
- */
249
- (size) => {
250
- return new Uint8Array(size);
251
- }
252
- );
253
- function compare(b1, b2) {
254
- if (isBuffer(b1) && isBuffer(b2)) {
255
- return b1.compare(b2);
256
- }
257
- for (let i = 0; i < b1.length; i++) {
258
- if (b1[i] === b2[i]) {
259
- continue;
260
- }
261
- return b1[i] < b2[i] ? -1 : 1;
262
- }
263
- return 0;
264
- }
265
- function utf8ToBytes(str) {
266
- const out = [];
267
- let p = 0;
268
- for (let i = 0; i < str.length; i++) {
269
- let c = str.charCodeAt(i);
270
- if (c < 128) {
271
- out[p++] = c;
272
- } else if (c < 2048) {
273
- out[p++] = c >> 6 | 192;
274
- out[p++] = c & 63 | 128;
275
- } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
276
- c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
277
- out[p++] = c >> 18 | 240;
278
- out[p++] = c >> 12 & 63 | 128;
279
- out[p++] = c >> 6 & 63 | 128;
280
- out[p++] = c & 63 | 128;
281
- } else {
282
- if (c >= 55296 && c <= 57343) {
283
- c = 65533;
284
- }
285
- out[p++] = c >> 12 | 224;
286
- out[p++] = c >> 6 & 63 | 128;
287
- out[p++] = c & 63 | 128;
288
- }
289
- }
290
- return out;
291
- }
292
- const defaultChunkSize = 256;
293
- class Bl {
294
- /**
295
- * @param {number} [chunkSize]
296
- */
297
- constructor(chunkSize = defaultChunkSize) {
298
- this.chunkSize = chunkSize;
299
- this.cursor = 0;
300
- this.maxCursor = -1;
301
- this.chunks = [];
302
- this._initReuseChunk = null;
303
- }
304
- reset() {
305
- this.cursor = 0;
306
- this.maxCursor = -1;
307
- if (this.chunks.length) {
308
- this.chunks = [];
309
- }
310
- if (this._initReuseChunk !== null) {
311
- this.chunks.push(this._initReuseChunk);
312
- this.maxCursor = this._initReuseChunk.length - 1;
313
- }
314
- }
315
- /**
316
- * @param {Uint8Array|number[]} bytes
317
- */
318
- push(bytes) {
319
- let topChunk = this.chunks[this.chunks.length - 1];
320
- const newMax = this.cursor + bytes.length;
321
- if (newMax <= this.maxCursor + 1) {
322
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
323
- topChunk.set(bytes, chunkPos);
324
- } else {
325
- if (topChunk) {
326
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
327
- if (chunkPos < topChunk.length) {
328
- this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
329
- this.maxCursor = this.cursor - 1;
330
- }
331
- }
332
- if (bytes.length < 64 && bytes.length < this.chunkSize) {
333
- topChunk = alloc(this.chunkSize);
334
- this.chunks.push(topChunk);
335
- this.maxCursor += topChunk.length;
336
- if (this._initReuseChunk === null) {
337
- this._initReuseChunk = topChunk;
338
- }
339
- topChunk.set(bytes, 0);
340
- } else {
341
- this.chunks.push(bytes);
342
- this.maxCursor += bytes.length;
343
- }
344
- }
345
- this.cursor += bytes.length;
346
- }
347
- /**
348
- * @param {boolean} [reset]
349
- * @returns {Uint8Array}
350
- */
351
- toBytes(reset = false) {
352
- let byts;
353
- if (this.chunks.length === 1) {
354
- const chunk = this.chunks[0];
355
- if (reset && this.cursor > chunk.length / 2) {
356
- byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
357
- this._initReuseChunk = null;
358
- this.chunks = [];
359
- } else {
360
- byts = slice(chunk, 0, this.cursor);
361
- }
362
- } else {
363
- byts = concat(this.chunks, this.cursor);
364
- }
365
- if (reset) {
366
- this.reset();
367
- }
368
- return byts;
369
- }
370
- }
371
- class U8Bl {
372
- /**
373
- * @param {Uint8Array} dest
374
- */
375
- constructor(dest) {
376
- this.dest = dest;
377
- this.cursor = 0;
378
- this.chunks = [dest];
379
- }
380
- reset() {
381
- this.cursor = 0;
382
- }
383
- /**
384
- * @param {Uint8Array|number[]} bytes
385
- */
386
- push(bytes) {
387
- if (this.cursor + bytes.length > this.dest.length) {
388
- throw new Error("write out of bounds, destination buffer is too small");
389
- }
390
- this.dest.set(bytes, this.cursor);
391
- this.cursor += bytes.length;
392
- }
393
- /**
394
- * @param {boolean} [reset]
395
- * @returns {Uint8Array}
396
- */
397
- toBytes(reset = false) {
398
- const byts = this.dest.subarray(0, this.cursor);
399
- if (reset) {
400
- this.reset();
401
- }
402
- return byts;
403
- }
404
- }
405
- const decodeErrPrefix = "CBOR decode error:";
406
- const encodeErrPrefix = "CBOR encode error:";
407
- function assertEnoughData(data, pos, need) {
408
- if (data.length - pos < need) {
409
- throw new Error(`${decodeErrPrefix} not enough data for type`);
410
- }
411
- }
412
- const uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
413
- function readUint8(data, offset, options) {
414
- assertEnoughData(data, offset, 1);
415
- const value = data[offset];
416
- if (options.strict === true && value < uintBoundaries[0]) {
417
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
418
- }
419
- return value;
420
- }
421
- function readUint16(data, offset, options) {
422
- assertEnoughData(data, offset, 2);
423
- const value = data[offset] << 8 | data[offset + 1];
424
- if (options.strict === true && value < uintBoundaries[1]) {
425
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
426
- }
427
- return value;
428
- }
429
- function readUint32(data, offset, options) {
430
- assertEnoughData(data, offset, 4);
431
- const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
432
- if (options.strict === true && value < uintBoundaries[2]) {
433
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
434
- }
435
- return value;
436
- }
437
- function readUint64(data, offset, options) {
438
- assertEnoughData(data, offset, 8);
439
- const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
440
- const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
441
- const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
442
- if (options.strict === true && value < uintBoundaries[3]) {
443
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
444
- }
445
- if (value <= Number.MAX_SAFE_INTEGER) {
446
- return Number(value);
447
- }
448
- if (options.allowBigInt === true) {
449
- return value;
450
- }
451
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
452
- }
453
- function decodeUint8(data, pos, _minor, options) {
454
- return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
455
- }
456
- function decodeUint16(data, pos, _minor, options) {
457
- return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
458
- }
459
- function decodeUint32(data, pos, _minor, options) {
460
- return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
461
- }
462
- function decodeUint64(data, pos, _minor, options) {
463
- return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
464
- }
465
- function encodeUint(writer, token) {
466
- return encodeUintValue(writer, 0, token.value);
467
- }
468
- function encodeUintValue(writer, major, uint) {
469
- if (uint < uintBoundaries[0]) {
470
- const nuint = Number(uint);
471
- writer.push([major | nuint]);
472
- } else if (uint < uintBoundaries[1]) {
473
- const nuint = Number(uint);
474
- writer.push([major | 24, nuint]);
475
- } else if (uint < uintBoundaries[2]) {
476
- const nuint = Number(uint);
477
- writer.push([major | 25, nuint >>> 8, nuint & 255]);
478
- } else if (uint < uintBoundaries[3]) {
479
- const nuint = Number(uint);
480
- writer.push([major | 26, nuint >>> 24 & 255, nuint >>> 16 & 255, nuint >>> 8 & 255, nuint & 255]);
481
- } else {
482
- const buint = BigInt(uint);
483
- if (buint < uintBoundaries[4]) {
484
- const set = [major | 27, 0, 0, 0, 0, 0, 0, 0];
485
- let lo = Number(buint & BigInt(4294967295));
486
- let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
487
- set[8] = lo & 255;
488
- lo = lo >> 8;
489
- set[7] = lo & 255;
490
- lo = lo >> 8;
491
- set[6] = lo & 255;
492
- lo = lo >> 8;
493
- set[5] = lo & 255;
494
- set[4] = hi & 255;
495
- hi = hi >> 8;
496
- set[3] = hi & 255;
497
- hi = hi >> 8;
498
- set[2] = hi & 255;
499
- hi = hi >> 8;
500
- set[1] = hi & 255;
501
- writer.push(set);
502
- } else {
503
- throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
504
- }
505
- }
506
- }
507
- encodeUint.encodedSize = function encodedSize(token) {
508
- return encodeUintValue.encodedSize(token.value);
509
- };
510
- encodeUintValue.encodedSize = function encodedSize2(uint) {
511
- if (uint < uintBoundaries[0]) {
512
- return 1;
513
- }
514
- if (uint < uintBoundaries[1]) {
515
- return 2;
516
- }
517
- if (uint < uintBoundaries[2]) {
518
- return 3;
519
- }
520
- if (uint < uintBoundaries[3]) {
521
- return 5;
522
- }
523
- return 9;
524
- };
525
- encodeUint.compareTokens = function compareTokens(tok1, tok2) {
526
- return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : (
527
- /* c8 ignore next */
528
- 0
529
- );
530
- };
531
- function decodeNegint8(data, pos, _minor, options) {
532
- return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
533
- }
534
- function decodeNegint16(data, pos, _minor, options) {
535
- return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
536
- }
537
- function decodeNegint32(data, pos, _minor, options) {
538
- return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
539
- }
540
- const neg1b$1 = BigInt(-1);
541
- const pos1b$1 = BigInt(1);
542
- function decodeNegint64(data, pos, _minor, options) {
543
- const int = readUint64(data, pos + 1, options);
544
- if (typeof int !== "bigint") {
545
- const value = -1 - int;
546
- if (value >= Number.MIN_SAFE_INTEGER) {
547
- return new Token(Type.negint, value, 9);
548
- }
549
- }
550
- if (options.allowBigInt !== true) {
551
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
552
- }
553
- return new Token(Type.negint, neg1b$1 - BigInt(int), 9);
554
- }
555
- function encodeNegint(writer, token) {
556
- const negint = token.value;
557
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
558
- encodeUintValue(writer, token.type.majorEncoded, unsigned);
559
- }
560
- encodeNegint.encodedSize = function encodedSize3(token) {
561
- const negint = token.value;
562
- const unsigned = typeof negint === "bigint" ? negint * neg1b$1 - pos1b$1 : negint * -1 - 1;
563
- if (unsigned < uintBoundaries[0]) {
564
- return 1;
565
- }
566
- if (unsigned < uintBoundaries[1]) {
567
- return 2;
568
- }
569
- if (unsigned < uintBoundaries[2]) {
570
- return 3;
571
- }
572
- if (unsigned < uintBoundaries[3]) {
573
- return 5;
574
- }
575
- return 9;
576
- };
577
- encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
578
- return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : (
579
- /* c8 ignore next */
580
- 0
581
- );
582
- };
583
- function toToken$3(data, pos, prefix, length) {
584
- assertEnoughData(data, pos, prefix + length);
585
- const buf = data.slice(pos + prefix, pos + prefix + length);
586
- return new Token(Type.bytes, buf, prefix + length);
587
- }
588
- function decodeBytesCompact(data, pos, minor, _options) {
589
- return toToken$3(data, pos, 1, minor);
590
- }
591
- function decodeBytes8(data, pos, _minor, options) {
592
- return toToken$3(data, pos, 2, readUint8(data, pos + 1, options));
593
- }
594
- function decodeBytes16(data, pos, _minor, options) {
595
- return toToken$3(data, pos, 3, readUint16(data, pos + 1, options));
596
- }
597
- function decodeBytes32(data, pos, _minor, options) {
598
- return toToken$3(data, pos, 5, readUint32(data, pos + 1, options));
599
- }
600
- function decodeBytes64(data, pos, _minor, options) {
601
- const l = readUint64(data, pos + 1, options);
602
- if (typeof l === "bigint") {
603
- throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
604
- }
605
- return toToken$3(data, pos, 9, l);
606
- }
607
- function tokenBytes(token) {
608
- if (token.encodedBytes === void 0) {
609
- token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value;
610
- }
611
- return token.encodedBytes;
612
- }
613
- function encodeBytes(writer, token) {
614
- const bytes = tokenBytes(token);
615
- encodeUintValue(writer, token.type.majorEncoded, bytes.length);
616
- writer.push(bytes);
617
- }
618
- encodeBytes.encodedSize = function encodedSize4(token) {
619
- const bytes = tokenBytes(token);
620
- return encodeUintValue.encodedSize(bytes.length) + bytes.length;
621
- };
622
- encodeBytes.compareTokens = function compareTokens3(tok1, tok2) {
623
- return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
624
- };
625
- function compareBytes(b1, b2) {
626
- return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
627
- }
628
- const textDecoder = new TextDecoder();
629
- const ASCII_THRESHOLD = 32;
630
- function toStr(bytes, start, end) {
631
- const len = end - start;
632
- if (len < ASCII_THRESHOLD) {
633
- let str = "";
634
- for (let i = start; i < end; i++) {
635
- const c = bytes[i];
636
- if (c & 128) {
637
- return textDecoder.decode(bytes.subarray(start, end));
638
- }
639
- str += String.fromCharCode(c);
640
- }
641
- return str;
642
- }
643
- return textDecoder.decode(bytes.subarray(start, end));
644
- }
645
- function toToken$2(data, pos, prefix, length, options) {
646
- const totLength = prefix + length;
647
- assertEnoughData(data, pos, totLength);
648
- const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength);
649
- if (options.retainStringBytes === true) {
650
- tok.byteValue = data.slice(pos + prefix, pos + totLength);
651
- }
652
- return tok;
653
- }
654
- function decodeStringCompact(data, pos, minor, options) {
655
- return toToken$2(data, pos, 1, minor, options);
656
- }
657
- function decodeString8(data, pos, _minor, options) {
658
- return toToken$2(data, pos, 2, readUint8(data, pos + 1, options), options);
659
- }
660
- function decodeString16(data, pos, _minor, options) {
661
- return toToken$2(data, pos, 3, readUint16(data, pos + 1, options), options);
662
- }
663
- function decodeString32(data, pos, _minor, options) {
664
- return toToken$2(data, pos, 5, readUint32(data, pos + 1, options), options);
665
- }
666
- function decodeString64(data, pos, _minor, options) {
667
- const l = readUint64(data, pos + 1, options);
668
- if (typeof l === "bigint") {
669
- throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
670
- }
671
- return toToken$2(data, pos, 9, l, options);
672
- }
673
- const encodeString = encodeBytes;
674
- function toToken$1(_data, _pos, prefix, length) {
675
- return new Token(Type.array, length, prefix);
676
- }
677
- function decodeArrayCompact(data, pos, minor, _options) {
678
- return toToken$1(data, pos, 1, minor);
679
- }
680
- function decodeArray8(data, pos, _minor, options) {
681
- return toToken$1(data, pos, 2, readUint8(data, pos + 1, options));
682
- }
683
- function decodeArray16(data, pos, _minor, options) {
684
- return toToken$1(data, pos, 3, readUint16(data, pos + 1, options));
685
- }
686
- function decodeArray32(data, pos, _minor, options) {
687
- return toToken$1(data, pos, 5, readUint32(data, pos + 1, options));
688
- }
689
- function decodeArray64(data, pos, _minor, options) {
690
- const l = readUint64(data, pos + 1, options);
691
- if (typeof l === "bigint") {
692
- throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
693
- }
694
- return toToken$1(data, pos, 9, l);
695
- }
696
- function decodeArrayIndefinite(data, pos, _minor, options) {
697
- if (options.allowIndefinite === false) {
698
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
699
- }
700
- return toToken$1(data, pos, 1, Infinity);
701
- }
702
- function encodeArray(writer, token) {
703
- encodeUintValue(writer, Type.array.majorEncoded, token.value);
704
- }
705
- encodeArray.compareTokens = encodeUint.compareTokens;
706
- encodeArray.encodedSize = function encodedSize5(token) {
707
- return encodeUintValue.encodedSize(token.value);
708
- };
709
- function toToken(_data, _pos, prefix, length) {
710
- return new Token(Type.map, length, prefix);
711
- }
712
- function decodeMapCompact(data, pos, minor, _options) {
713
- return toToken(data, pos, 1, minor);
714
- }
715
- function decodeMap8(data, pos, _minor, options) {
716
- return toToken(data, pos, 2, readUint8(data, pos + 1, options));
717
- }
718
- function decodeMap16(data, pos, _minor, options) {
719
- return toToken(data, pos, 3, readUint16(data, pos + 1, options));
720
- }
721
- function decodeMap32(data, pos, _minor, options) {
722
- return toToken(data, pos, 5, readUint32(data, pos + 1, options));
723
- }
724
- function decodeMap64(data, pos, _minor, options) {
725
- const l = readUint64(data, pos + 1, options);
726
- if (typeof l === "bigint") {
727
- throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
728
- }
729
- return toToken(data, pos, 9, l);
730
- }
731
- function decodeMapIndefinite(data, pos, _minor, options) {
732
- if (options.allowIndefinite === false) {
733
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
734
- }
735
- return toToken(data, pos, 1, Infinity);
736
- }
737
- function encodeMap(writer, token) {
738
- encodeUintValue(writer, Type.map.majorEncoded, token.value);
739
- }
740
- encodeMap.compareTokens = encodeUint.compareTokens;
741
- encodeMap.encodedSize = function encodedSize6(token) {
742
- return encodeUintValue.encodedSize(token.value);
743
- };
744
- function decodeTagCompact(_data, _pos, minor, _options) {
745
- return new Token(Type.tag, minor, 1);
746
- }
747
- function decodeTag8(data, pos, _minor, options) {
748
- return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
749
- }
750
- function decodeTag16(data, pos, _minor, options) {
751
- return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
752
- }
753
- function decodeTag32(data, pos, _minor, options) {
754
- return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
755
- }
756
- function decodeTag64(data, pos, _minor, options) {
757
- return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
758
- }
759
- function encodeTag(writer, token) {
760
- encodeUintValue(writer, Type.tag.majorEncoded, token.value);
761
- }
762
- encodeTag.compareTokens = encodeUint.compareTokens;
763
- encodeTag.encodedSize = function encodedSize7(token) {
764
- return encodeUintValue.encodedSize(token.value);
765
- };
766
- const MINOR_FALSE = 20;
767
- const MINOR_TRUE = 21;
768
- const MINOR_NULL = 22;
769
- const MINOR_UNDEFINED = 23;
770
- function decodeUndefined(_data, _pos, _minor, options) {
771
- if (options.allowUndefined === false) {
772
- throw new Error(`${decodeErrPrefix} undefined values are not supported`);
773
- } else if (options.coerceUndefinedToNull === true) {
774
- return new Token(Type.null, null, 1);
775
- }
776
- return new Token(Type.undefined, void 0, 1);
777
- }
778
- function decodeBreak(_data, _pos, _minor, options) {
779
- if (options.allowIndefinite === false) {
780
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
781
- }
782
- return new Token(Type.break, void 0, 1);
783
- }
784
- function createToken(value, bytes, options) {
785
- if (options) {
786
- if (options.allowNaN === false && Number.isNaN(value)) {
787
- throw new Error(`${decodeErrPrefix} NaN values are not supported`);
788
- }
789
- if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
790
- throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
791
- }
792
- }
793
- return new Token(Type.float, value, bytes);
794
- }
795
- function decodeFloat16(data, pos, _minor, options) {
796
- return createToken(readFloat16(data, pos + 1), 3, options);
797
- }
798
- function decodeFloat32(data, pos, _minor, options) {
799
- return createToken(readFloat32(data, pos + 1), 5, options);
800
- }
801
- function decodeFloat64(data, pos, _minor, options) {
802
- return createToken(readFloat64(data, pos + 1), 9, options);
803
- }
804
- function encodeFloat(writer, token, options) {
805
- const float = token.value;
806
- if (float === false) {
807
- writer.push([Type.float.majorEncoded | MINOR_FALSE]);
808
- } else if (float === true) {
809
- writer.push([Type.float.majorEncoded | MINOR_TRUE]);
810
- } else if (float === null) {
811
- writer.push([Type.float.majorEncoded | MINOR_NULL]);
812
- } else if (float === void 0) {
813
- writer.push([Type.float.majorEncoded | MINOR_UNDEFINED]);
814
- } else {
815
- let decoded;
816
- let success = false;
817
- if (!options || options.float64 !== true) {
818
- encodeFloat16(float);
819
- decoded = readFloat16(ui8a, 1);
820
- if (float === decoded || Number.isNaN(float)) {
821
- ui8a[0] = 249;
822
- writer.push(ui8a.slice(0, 3));
823
- success = true;
824
- } else {
825
- encodeFloat32(float);
826
- decoded = readFloat32(ui8a, 1);
827
- if (float === decoded) {
828
- ui8a[0] = 250;
829
- writer.push(ui8a.slice(0, 5));
830
- success = true;
831
- }
832
- }
833
- }
834
- if (!success) {
835
- encodeFloat64(float);
836
- decoded = readFloat64(ui8a, 1);
837
- ui8a[0] = 251;
838
- writer.push(ui8a.slice(0, 9));
839
- }
840
- }
841
- }
842
- encodeFloat.encodedSize = function encodedSize8(token, options) {
843
- const float = token.value;
844
- if (float === false || float === true || float === null || float === void 0) {
845
- return 1;
846
- }
847
- if (!options || options.float64 !== true) {
848
- encodeFloat16(float);
849
- let decoded = readFloat16(ui8a, 1);
850
- if (float === decoded || Number.isNaN(float)) {
851
- return 3;
852
- }
853
- encodeFloat32(float);
854
- decoded = readFloat32(ui8a, 1);
855
- if (float === decoded) {
856
- return 5;
857
- }
858
- }
859
- return 9;
860
- };
861
- const buffer = new ArrayBuffer(9);
862
- const dataView = new DataView(buffer, 1);
863
- const ui8a = new Uint8Array(buffer, 0);
864
- function encodeFloat16(inp) {
865
- if (inp === Infinity) {
866
- dataView.setUint16(0, 31744, false);
867
- } else if (inp === -Infinity) {
868
- dataView.setUint16(0, 64512, false);
869
- } else if (Number.isNaN(inp)) {
870
- dataView.setUint16(0, 32256, false);
871
- } else {
872
- dataView.setFloat32(0, inp);
873
- const valu32 = dataView.getUint32(0);
874
- const exponent = (valu32 & 2139095040) >> 23;
875
- const mantissa = valu32 & 8388607;
876
- if (exponent === 255) {
877
- dataView.setUint16(0, 31744, false);
878
- } else if (exponent === 0) {
879
- dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);
880
- } else {
881
- const logicalExponent = exponent - 127;
882
- if (logicalExponent < -24) {
883
- dataView.setUint16(0, 0);
884
- } else if (logicalExponent < -14) {
885
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | /* sign bit */
886
- 1 << 24 + logicalExponent, false);
887
- } else {
888
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
889
- }
890
- }
891
- }
892
- }
893
- function readFloat16(ui8a2, pos) {
894
- if (ui8a2.length - pos < 2) {
895
- throw new Error(`${decodeErrPrefix} not enough data for float16`);
896
- }
897
- const half = (ui8a2[pos] << 8) + ui8a2[pos + 1];
898
- if (half === 31744) {
899
- return Infinity;
900
- }
901
- if (half === 64512) {
902
- return -Infinity;
903
- }
904
- if (half === 32256) {
905
- return NaN;
906
- }
907
- const exp = half >> 10 & 31;
908
- const mant = half & 1023;
909
- let val;
910
- if (exp === 0) {
911
- val = mant * 2 ** -24;
912
- } else if (exp !== 31) {
913
- val = (mant + 1024) * 2 ** (exp - 25);
914
- } else {
915
- val = mant === 0 ? Infinity : NaN;
916
- }
917
- return half & 32768 ? -val : val;
918
- }
919
- function encodeFloat32(inp) {
920
- dataView.setFloat32(0, inp, false);
921
- }
922
- function readFloat32(ui8a2, pos) {
923
- if (ui8a2.length - pos < 4) {
924
- throw new Error(`${decodeErrPrefix} not enough data for float32`);
925
- }
926
- const offset = (ui8a2.byteOffset || 0) + pos;
927
- return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false);
928
- }
929
- function encodeFloat64(inp) {
930
- dataView.setFloat64(0, inp, false);
931
- }
932
- function readFloat64(ui8a2, pos) {
933
- if (ui8a2.length - pos < 8) {
934
- throw new Error(`${decodeErrPrefix} not enough data for float64`);
935
- }
936
- const offset = (ui8a2.byteOffset || 0) + pos;
937
- return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false);
938
- }
939
- encodeFloat.compareTokens = encodeUint.compareTokens;
940
- function invalidMinor(data, pos, minor) {
941
- throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
942
- }
943
- function errorer(msg) {
944
- return () => {
945
- throw new Error(`${decodeErrPrefix} ${msg}`);
946
- };
947
- }
948
- const jump = [];
949
- for (let i = 0; i <= 23; i++) {
950
- jump[i] = invalidMinor;
951
- }
952
- jump[24] = decodeUint8;
953
- jump[25] = decodeUint16;
954
- jump[26] = decodeUint32;
955
- jump[27] = decodeUint64;
956
- jump[28] = invalidMinor;
957
- jump[29] = invalidMinor;
958
- jump[30] = invalidMinor;
959
- jump[31] = invalidMinor;
960
- for (let i = 32; i <= 55; i++) {
961
- jump[i] = invalidMinor;
962
- }
963
- jump[56] = decodeNegint8;
964
- jump[57] = decodeNegint16;
965
- jump[58] = decodeNegint32;
966
- jump[59] = decodeNegint64;
967
- jump[60] = invalidMinor;
968
- jump[61] = invalidMinor;
969
- jump[62] = invalidMinor;
970
- jump[63] = invalidMinor;
971
- for (let i = 64; i <= 87; i++) {
972
- jump[i] = decodeBytesCompact;
973
- }
974
- jump[88] = decodeBytes8;
975
- jump[89] = decodeBytes16;
976
- jump[90] = decodeBytes32;
977
- jump[91] = decodeBytes64;
978
- jump[92] = invalidMinor;
979
- jump[93] = invalidMinor;
980
- jump[94] = invalidMinor;
981
- jump[95] = errorer("indefinite length bytes/strings are not supported");
982
- for (let i = 96; i <= 119; i++) {
983
- jump[i] = decodeStringCompact;
984
- }
985
- jump[120] = decodeString8;
986
- jump[121] = decodeString16;
987
- jump[122] = decodeString32;
988
- jump[123] = decodeString64;
989
- jump[124] = invalidMinor;
990
- jump[125] = invalidMinor;
991
- jump[126] = invalidMinor;
992
- jump[127] = errorer("indefinite length bytes/strings are not supported");
993
- for (let i = 128; i <= 151; i++) {
994
- jump[i] = decodeArrayCompact;
995
- }
996
- jump[152] = decodeArray8;
997
- jump[153] = decodeArray16;
998
- jump[154] = decodeArray32;
999
- jump[155] = decodeArray64;
1000
- jump[156] = invalidMinor;
1001
- jump[157] = invalidMinor;
1002
- jump[158] = invalidMinor;
1003
- jump[159] = decodeArrayIndefinite;
1004
- for (let i = 160; i <= 183; i++) {
1005
- jump[i] = decodeMapCompact;
1006
- }
1007
- jump[184] = decodeMap8;
1008
- jump[185] = decodeMap16;
1009
- jump[186] = decodeMap32;
1010
- jump[187] = decodeMap64;
1011
- jump[188] = invalidMinor;
1012
- jump[189] = invalidMinor;
1013
- jump[190] = invalidMinor;
1014
- jump[191] = decodeMapIndefinite;
1015
- for (let i = 192; i <= 215; i++) {
1016
- jump[i] = decodeTagCompact;
1017
- }
1018
- jump[216] = decodeTag8;
1019
- jump[217] = decodeTag16;
1020
- jump[218] = decodeTag32;
1021
- jump[219] = decodeTag64;
1022
- jump[220] = invalidMinor;
1023
- jump[221] = invalidMinor;
1024
- jump[222] = invalidMinor;
1025
- jump[223] = invalidMinor;
1026
- for (let i = 224; i <= 243; i++) {
1027
- jump[i] = errorer("simple values are not supported");
1028
- }
1029
- jump[244] = invalidMinor;
1030
- jump[245] = invalidMinor;
1031
- jump[246] = invalidMinor;
1032
- jump[247] = decodeUndefined;
1033
- jump[248] = errorer("simple values are not supported");
1034
- jump[249] = decodeFloat16;
1035
- jump[250] = decodeFloat32;
1036
- jump[251] = decodeFloat64;
1037
- jump[252] = invalidMinor;
1038
- jump[253] = invalidMinor;
1039
- jump[254] = invalidMinor;
1040
- jump[255] = decodeBreak;
1041
- const quick = [];
1042
- for (let i = 0; i < 24; i++) {
1043
- quick[i] = new Token(Type.uint, i, 1);
1044
- }
1045
- for (let i = -1; i >= -24; i--) {
1046
- quick[31 - i] = new Token(Type.negint, i, 1);
1047
- }
1048
- quick[64] = new Token(Type.bytes, new Uint8Array(0), 1);
1049
- quick[96] = new Token(Type.string, "", 1);
1050
- quick[128] = new Token(Type.array, 0, 1);
1051
- quick[160] = new Token(Type.map, 0, 1);
1052
- quick[244] = new Token(Type.false, false, 1);
1053
- quick[245] = new Token(Type.true, true, 1);
1054
- quick[246] = new Token(Type.null, null, 1);
1055
- function quickEncodeToken(token) {
1056
- switch (token.type) {
1057
- case Type.false:
1058
- return fromArray([244]);
1059
- case Type.true:
1060
- return fromArray([245]);
1061
- case Type.null:
1062
- return fromArray([246]);
1063
- case Type.bytes:
1064
- if (!token.value.length) {
1065
- return fromArray([64]);
1066
- }
1067
- return;
1068
- case Type.string:
1069
- if (token.value === "") {
1070
- return fromArray([96]);
1071
- }
1072
- return;
1073
- case Type.array:
1074
- if (token.value === 0) {
1075
- return fromArray([128]);
1076
- }
1077
- return;
1078
- case Type.map:
1079
- if (token.value === 0) {
1080
- return fromArray([160]);
1081
- }
1082
- return;
1083
- case Type.uint:
1084
- if (token.value < 24) {
1085
- return fromArray([Number(token.value)]);
1086
- }
1087
- return;
1088
- case Type.negint:
1089
- if (token.value >= -24) {
1090
- return fromArray([31 - Number(token.value)]);
1091
- }
1092
- }
1093
- }
1094
- const defaultEncodeOptions = {
1095
- float64: false,
1096
- mapSorter,
1097
- quickEncodeToken
1098
- };
1099
- function makeCborEncoders() {
1100
- const encoders = [];
1101
- encoders[Type.uint.major] = encodeUint;
1102
- encoders[Type.negint.major] = encodeNegint;
1103
- encoders[Type.bytes.major] = encodeBytes;
1104
- encoders[Type.string.major] = encodeString;
1105
- encoders[Type.array.major] = encodeArray;
1106
- encoders[Type.map.major] = encodeMap;
1107
- encoders[Type.tag.major] = encodeTag;
1108
- encoders[Type.float.major] = encodeFloat;
1109
- return encoders;
1110
- }
1111
- const cborEncoders = makeCborEncoders();
1112
- const defaultWriter = new Bl();
1113
- class Ref {
1114
- /**
1115
- * @param {object|any[]} obj
1116
- * @param {Reference|undefined} parent
1117
- */
1118
- constructor(obj, parent) {
1119
- this.obj = obj;
1120
- this.parent = parent;
1121
- }
1122
- /**
1123
- * @param {object|any[]} obj
1124
- * @returns {boolean}
1125
- */
1126
- includes(obj) {
1127
- let p = this;
1128
- do {
1129
- if (p.obj === obj) {
1130
- return true;
1131
- }
1132
- } while (p = p.parent);
1133
- return false;
1134
- }
1135
- /**
1136
- * @param {Reference|undefined} stack
1137
- * @param {object|any[]} obj
1138
- * @returns {Reference}
1139
- */
1140
- static createCheck(stack, obj) {
1141
- if (stack && stack.includes(obj)) {
1142
- throw new Error(`${encodeErrPrefix} object contains circular references`);
1143
- }
1144
- return new Ref(obj, stack);
1145
- }
1146
- }
1147
- const simpleTokens = {
1148
- null: new Token(Type.null, null),
1149
- undefined: new Token(Type.undefined, void 0),
1150
- true: new Token(Type.true, true),
1151
- false: new Token(Type.false, false),
1152
- emptyArray: new Token(Type.array, 0),
1153
- emptyMap: new Token(Type.map, 0)
1154
- };
1155
- const typeEncoders = {
1156
- /**
1157
- * @param {any} obj
1158
- * @param {string} _typ
1159
- * @param {EncodeOptions} _options
1160
- * @param {Reference} [_refStack]
1161
- * @returns {TokenOrNestedTokens}
1162
- */
1163
- number(obj, _typ, _options, _refStack) {
1164
- if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
1165
- return new Token(Type.float, obj);
1166
- } else if (obj >= 0) {
1167
- return new Token(Type.uint, obj);
1168
- } else {
1169
- return new Token(Type.negint, obj);
1170
- }
1171
- },
1172
- /**
1173
- * @param {any} obj
1174
- * @param {string} _typ
1175
- * @param {EncodeOptions} _options
1176
- * @param {Reference} [_refStack]
1177
- * @returns {TokenOrNestedTokens}
1178
- */
1179
- bigint(obj, _typ, _options, _refStack) {
1180
- if (obj >= BigInt(0)) {
1181
- return new Token(Type.uint, obj);
1182
- } else {
1183
- return new Token(Type.negint, obj);
1184
- }
1185
- },
1186
- /**
1187
- * @param {any} obj
1188
- * @param {string} _typ
1189
- * @param {EncodeOptions} _options
1190
- * @param {Reference} [_refStack]
1191
- * @returns {TokenOrNestedTokens}
1192
- */
1193
- Uint8Array(obj, _typ, _options, _refStack) {
1194
- return new Token(Type.bytes, obj);
1195
- },
1196
- /**
1197
- * @param {any} obj
1198
- * @param {string} _typ
1199
- * @param {EncodeOptions} _options
1200
- * @param {Reference} [_refStack]
1201
- * @returns {TokenOrNestedTokens}
1202
- */
1203
- string(obj, _typ, _options, _refStack) {
1204
- return new Token(Type.string, obj);
1205
- },
1206
- /**
1207
- * @param {any} obj
1208
- * @param {string} _typ
1209
- * @param {EncodeOptions} _options
1210
- * @param {Reference} [_refStack]
1211
- * @returns {TokenOrNestedTokens}
1212
- */
1213
- boolean(obj, _typ, _options, _refStack) {
1214
- return obj ? simpleTokens.true : simpleTokens.false;
1215
- },
1216
- /**
1217
- * @param {any} _obj
1218
- * @param {string} _typ
1219
- * @param {EncodeOptions} _options
1220
- * @param {Reference} [_refStack]
1221
- * @returns {TokenOrNestedTokens}
1222
- */
1223
- null(_obj, _typ, _options, _refStack) {
1224
- return simpleTokens.null;
1225
- },
1226
- /**
1227
- * @param {any} _obj
1228
- * @param {string} _typ
1229
- * @param {EncodeOptions} _options
1230
- * @param {Reference} [_refStack]
1231
- * @returns {TokenOrNestedTokens}
1232
- */
1233
- undefined(_obj, _typ, _options, _refStack) {
1234
- return simpleTokens.undefined;
1235
- },
1236
- /**
1237
- * @param {any} obj
1238
- * @param {string} _typ
1239
- * @param {EncodeOptions} _options
1240
- * @param {Reference} [_refStack]
1241
- * @returns {TokenOrNestedTokens}
1242
- */
1243
- ArrayBuffer(obj, _typ, _options, _refStack) {
1244
- return new Token(Type.bytes, new Uint8Array(obj));
1245
- },
1246
- /**
1247
- * @param {any} obj
1248
- * @param {string} _typ
1249
- * @param {EncodeOptions} _options
1250
- * @param {Reference} [_refStack]
1251
- * @returns {TokenOrNestedTokens}
1252
- */
1253
- DataView(obj, _typ, _options, _refStack) {
1254
- return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
1255
- },
1256
- /**
1257
- * @param {any} obj
1258
- * @param {string} _typ
1259
- * @param {EncodeOptions} options
1260
- * @param {Reference} [refStack]
1261
- * @returns {TokenOrNestedTokens}
1262
- */
1263
- Array(obj, _typ, options, refStack) {
1264
- if (!obj.length) {
1265
- if (options.addBreakTokens === true) {
1266
- return [simpleTokens.emptyArray, new Token(Type.break)];
1267
- }
1268
- return simpleTokens.emptyArray;
1269
- }
1270
- refStack = Ref.createCheck(refStack, obj);
1271
- const entries = [];
1272
- let i = 0;
1273
- for (const e of obj) {
1274
- entries[i++] = objectToTokens(e, options, refStack);
1275
- }
1276
- if (options.addBreakTokens) {
1277
- return [new Token(Type.array, obj.length), entries, new Token(Type.break)];
1278
- }
1279
- return [new Token(Type.array, obj.length), entries];
1280
- },
1281
- /**
1282
- * @param {any} obj
1283
- * @param {string} typ
1284
- * @param {EncodeOptions} options
1285
- * @param {Reference} [refStack]
1286
- * @returns {TokenOrNestedTokens}
1287
- */
1288
- Object(obj, typ, options, refStack) {
1289
- const isMap = typ !== "Object";
1290
- const keys = isMap ? obj.keys() : Object.keys(obj);
1291
- const maxLength = isMap ? obj.size : keys.length;
1292
- let entries;
1293
- if (maxLength) {
1294
- entries = new Array(maxLength);
1295
- refStack = Ref.createCheck(refStack, obj);
1296
- const skipUndefined = !isMap && options.ignoreUndefinedProperties;
1297
- let i = 0;
1298
- for (const key of keys) {
1299
- const value = isMap ? obj.get(key) : obj[key];
1300
- if (skipUndefined && value === void 0) {
1301
- continue;
1302
- }
1303
- entries[i++] = [
1304
- objectToTokens(key, options, refStack),
1305
- objectToTokens(value, options, refStack)
1306
- ];
1307
- }
1308
- if (i < maxLength) {
1309
- entries.length = i;
1310
- }
1311
- }
1312
- if (!(entries == null ? void 0 : entries.length)) {
1313
- if (options.addBreakTokens === true) {
1314
- return [simpleTokens.emptyMap, new Token(Type.break)];
1315
- }
1316
- return simpleTokens.emptyMap;
1317
- }
1318
- sortMapEntries(entries, options);
1319
- if (options.addBreakTokens) {
1320
- return [new Token(Type.map, entries.length), entries, new Token(Type.break)];
1321
- }
1322
- return [new Token(Type.map, entries.length), entries];
1323
- }
1324
- };
1325
- typeEncoders.Map = typeEncoders.Object;
1326
- typeEncoders.Buffer = typeEncoders.Uint8Array;
1327
- for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) {
1328
- typeEncoders[`${typ}Array`] = typeEncoders.DataView;
1329
- }
1330
- function objectToTokens(obj, options = {}, refStack) {
1331
- const typ = is(obj);
1332
- const customTypeEncoder = options && options.typeEncoders && /** @type {OptionalTypeEncoder} */
1333
- options.typeEncoders[typ] || typeEncoders[typ];
1334
- if (typeof customTypeEncoder === "function") {
1335
- const tokens = customTypeEncoder(obj, typ, options, refStack);
1336
- if (tokens != null) {
1337
- return tokens;
1338
- }
1339
- }
1340
- const typeEncoder = typeEncoders[typ];
1341
- if (!typeEncoder) {
1342
- throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1343
- }
1344
- return typeEncoder(obj, typ, options, refStack);
1345
- }
1346
- function sortMapEntries(entries, options) {
1347
- if (options.mapSorter) {
1348
- entries.sort(options.mapSorter);
1349
- }
1350
- }
1351
- function mapSorter(e1, e2) {
1352
- const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
1353
- const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
1354
- if (keyToken1.type !== keyToken2.type) {
1355
- return keyToken1.type.compare(keyToken2.type);
1356
- }
1357
- const major = keyToken1.type.major;
1358
- const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);
1359
- if (tcmp === 0) {
1360
- console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
1361
- }
1362
- return tcmp;
1363
- }
1364
- function tokensToEncoded(writer, tokens, encoders, options) {
1365
- if (Array.isArray(tokens)) {
1366
- for (const token of tokens) {
1367
- tokensToEncoded(writer, token, encoders, options);
1368
- }
1369
- } else {
1370
- encoders[tokens.type.major](writer, tokens, options);
1371
- }
1372
- }
1373
- const MAJOR_UINT = Type.uint.majorEncoded;
1374
- const MAJOR_NEGINT = Type.negint.majorEncoded;
1375
- const MAJOR_BYTES = Type.bytes.majorEncoded;
1376
- const MAJOR_STRING = Type.string.majorEncoded;
1377
- const MAJOR_ARRAY = Type.array.majorEncoded;
1378
- const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE;
1379
- const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE;
1380
- const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL;
1381
- const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED;
1382
- const neg1b = BigInt(-1);
1383
- const pos1b = BigInt(1);
1384
- function canDirectEncode(options) {
1385
- return options.addBreakTokens !== true;
1386
- }
1387
- function directEncode(writer, data, options, refStack) {
1388
- const typ = is(data);
1389
- const customEncoder = options.typeEncoders && options.typeEncoders[typ];
1390
- if (customEncoder) {
1391
- const tokens = customEncoder(data, typ, options, refStack);
1392
- if (tokens != null) {
1393
- tokensToEncoded(writer, tokens, cborEncoders, options);
1394
- return;
1395
- }
1396
- }
1397
- switch (typ) {
1398
- case "null":
1399
- writer.push([SIMPLE_NULL]);
1400
- return;
1401
- case "undefined":
1402
- writer.push([SIMPLE_UNDEFINED]);
1403
- return;
1404
- case "boolean":
1405
- writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE]);
1406
- return;
1407
- case "number":
1408
- if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
1409
- encodeFloat(writer, new Token(Type.float, data), options);
1410
- } else if (data >= 0) {
1411
- encodeUintValue(writer, MAJOR_UINT, data);
1412
- } else {
1413
- encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1);
1414
- }
1415
- return;
1416
- case "bigint":
1417
- if (data >= BigInt(0)) {
1418
- encodeUintValue(writer, MAJOR_UINT, data);
1419
- } else {
1420
- encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b);
1421
- }
1422
- return;
1423
- case "string": {
1424
- const bytes = fromString(data);
1425
- encodeUintValue(writer, MAJOR_STRING, bytes.length);
1426
- writer.push(bytes);
1427
- return;
1428
- }
1429
- case "Uint8Array":
1430
- encodeUintValue(writer, MAJOR_BYTES, data.length);
1431
- writer.push(data);
1432
- return;
1433
- case "Array":
1434
- if (!data.length) {
1435
- writer.push([MAJOR_ARRAY]);
1436
- return;
1437
- }
1438
- refStack = Ref.createCheck(refStack, data);
1439
- encodeUintValue(writer, MAJOR_ARRAY, data.length);
1440
- for (const elem of data) {
1441
- directEncode(writer, elem, options, refStack);
1442
- }
1443
- return;
1444
- case "Object":
1445
- case "Map":
1446
- {
1447
- const tokens = typeEncoders.Object(data, typ, options, refStack);
1448
- tokensToEncoded(writer, tokens, cborEncoders, options);
1449
- }
1450
- return;
1451
- default: {
1452
- const typeEncoder = typeEncoders[typ];
1453
- if (!typeEncoder) {
1454
- throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
1455
- }
1456
- const tokens = typeEncoder(data, typ, options, refStack);
1457
- tokensToEncoded(writer, tokens, cborEncoders, options);
1458
- }
1459
- }
1460
- }
1461
- function encodeCustom(data, encoders, options, destination) {
1462
- const hasDest = destination instanceof Uint8Array;
1463
- let writeTo = hasDest ? new U8Bl(destination) : defaultWriter;
1464
- const tokens = objectToTokens(data, options);
1465
- if (!Array.isArray(tokens) && options.quickEncodeToken) {
1466
- const quickBytes = options.quickEncodeToken(tokens);
1467
- if (quickBytes) {
1468
- if (hasDest) {
1469
- writeTo.push(quickBytes);
1470
- return writeTo.toBytes();
1471
- }
1472
- return quickBytes;
1473
- }
1474
- const encoder = encoders[tokens.type.major];
1475
- if (encoder.encodedSize) {
1476
- const size = encoder.encodedSize(tokens, options);
1477
- if (!hasDest) {
1478
- writeTo = new Bl(size);
1479
- }
1480
- encoder(writeTo, tokens, options);
1481
- if (writeTo.chunks.length !== 1) {
1482
- throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
1483
- }
1484
- return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0]);
1485
- }
1486
- }
1487
- writeTo.reset();
1488
- tokensToEncoded(writeTo, tokens, encoders, options);
1489
- return writeTo.toBytes(true);
1490
- }
1491
- function encode$1(data, options) {
1492
- options = Object.assign({}, defaultEncodeOptions, options);
1493
- if (canDirectEncode(options)) {
1494
- defaultWriter.reset();
1495
- directEncode(defaultWriter, data, options, void 0);
1496
- return defaultWriter.toBytes(true);
1497
- }
1498
- return encodeCustom(data, cborEncoders, options);
1499
- }
1500
- const defaultDecodeOptions = {
1501
- strict: false,
1502
- allowIndefinite: true,
1503
- allowUndefined: true,
1504
- allowBigInt: true
1505
- };
1506
- class Tokeniser {
1507
- /**
1508
- * @param {Uint8Array} data
1509
- * @param {DecodeOptions} options
1510
- */
1511
- constructor(data, options = {}) {
1512
- this._pos = 0;
1513
- this.data = data;
1514
- this.options = options;
1515
- }
1516
- pos() {
1517
- return this._pos;
1518
- }
1519
- done() {
1520
- return this._pos >= this.data.length;
1521
- }
1522
- next() {
1523
- const byt = this.data[this._pos];
1524
- let token = quick[byt];
1525
- if (token === void 0) {
1526
- const decoder = jump[byt];
1527
- if (!decoder) {
1528
- throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
1529
- }
1530
- const minor = byt & 31;
1531
- token = decoder(this.data, this._pos, minor, this.options);
1532
- }
1533
- this._pos += token.encodedLength;
1534
- return token;
1535
- }
1536
- }
1537
- const DONE = Symbol.for("DONE");
1538
- const BREAK = Symbol.for("BREAK");
1539
- function tokenToArray(token, tokeniser, options) {
1540
- const arr = [];
1541
- for (let i = 0; i < token.value; i++) {
1542
- const value = tokensToObject(tokeniser, options);
1543
- if (value === BREAK) {
1544
- if (token.value === Infinity) {
1545
- break;
1546
- }
1547
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
1548
- }
1549
- if (value === DONE) {
1550
- throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
1551
- }
1552
- arr[i] = value;
1553
- }
1554
- return arr;
1555
- }
1556
- function tokenToMap(token, tokeniser, options) {
1557
- const useMaps = options.useMaps === true;
1558
- const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true;
1559
- const obj = useMaps ? void 0 : {};
1560
- const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
1561
- for (let i = 0; i < token.value; i++) {
1562
- const key = tokensToObject(tokeniser, options);
1563
- if (key === BREAK) {
1564
- if (token.value === Infinity) {
1565
- break;
1566
- }
1567
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
1568
- }
1569
- if (key === DONE) {
1570
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
1571
- }
1572
- if (!useMaps && typeof key !== "string") {
1573
- throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
1574
- }
1575
- if (rejectDuplicateMapKeys) {
1576
- if (useMaps && m.has(key) || !useMaps && Object.hasOwn(obj, key)) {
1577
- throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
1578
- }
1579
- }
1580
- const value = tokensToObject(tokeniser, options);
1581
- if (value === DONE) {
1582
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
1583
- }
1584
- if (useMaps) {
1585
- m.set(key, value);
1586
- } else {
1587
- obj[key] = value;
1588
- }
1589
- }
1590
- return useMaps ? m : obj;
1591
- }
1592
- function tokensToObject(tokeniser, options) {
1593
- if (tokeniser.done()) {
1594
- return DONE;
1595
- }
1596
- const token = tokeniser.next();
1597
- if (Type.equals(token.type, Type.break)) {
1598
- return BREAK;
1599
- }
1600
- if (token.type.terminal) {
1601
- return token.value;
1602
- }
1603
- if (Type.equals(token.type, Type.array)) {
1604
- return tokenToArray(token, tokeniser, options);
1605
- }
1606
- if (Type.equals(token.type, Type.map)) {
1607
- return tokenToMap(token, tokeniser, options);
1608
- }
1609
- if (Type.equals(token.type, Type.tag)) {
1610
- if (options.tags && typeof options.tags[token.value] === "function") {
1611
- const tagged = tokensToObject(tokeniser, options);
1612
- return options.tags[token.value](tagged);
1613
- }
1614
- throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
1615
- }
1616
- throw new Error("unsupported");
1617
- }
1618
- function decodeFirst(data, options) {
1619
- if (!(data instanceof Uint8Array)) {
1620
- throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
1621
- }
1622
- options = Object.assign({}, defaultDecodeOptions, options);
1623
- const u8aData = asU8A(data);
1624
- const tokeniser = options.tokenizer || new Tokeniser(u8aData, options);
1625
- const decoded = tokensToObject(tokeniser, options);
1626
- if (decoded === DONE) {
1627
- throw new Error(`${decodeErrPrefix} did not find any content to decode`);
1628
- }
1629
- if (decoded === BREAK) {
1630
- throw new Error(`${decodeErrPrefix} got unexpected break`);
1631
- }
1632
- return [decoded, data.subarray(tokeniser.pos())];
1633
- }
1634
- function decode$1(data, options) {
1635
- const [decoded, remainder] = decodeFirst(data, options);
1636
- if (remainder.length > 0) {
1637
- throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
1638
- }
1639
- return decoded;
1640
- }
1641
- const CID_CBOR_TAG = 42;
1642
- const encodeOptions = Object.freeze({
1643
- float64: true,
1644
- ignoreUndefinedProperties: true,
1645
- typeEncoders: Object.freeze({
1646
- Map: (map) => {
1647
- for (const key of map.keys()) {
1648
- if (typeof key !== "string") {
1649
- throw new Error(
1650
- 'Only string keys are allowed in CBOR "map" by the AT Data Model'
1651
- );
1652
- }
1653
- }
1654
- return null;
1655
- },
1656
- Object: (obj) => {
1657
- const cid = ifCid(obj);
1658
- if (cid) {
1659
- const bytes = new Uint8Array(cid.bytes.byteLength + 1);
1660
- bytes.set(cid.bytes, 1);
1661
- return [new Token(Type.tag, CID_CBOR_TAG), new Token(Type.bytes, bytes)];
1662
- }
1663
- return null;
1664
- },
1665
- undefined: () => {
1666
- throw new Error("`undefined` is not supported by the AT Data Model");
1667
- },
1668
- number: (num) => {
1669
- if (Number.isSafeInteger(num)) return null;
1670
- throw new Error(
1671
- `Non-integer numbers (${num}) are not supported by the AT Data Model`
1672
- );
1673
- }
1674
- })
1675
- });
1676
- const decodeOptions = /* @__PURE__ */ Object.freeze({
1677
- allowIndefinite: false,
1678
- coerceUndefinedToNull: true,
1679
- allowNaN: false,
1680
- allowInfinity: false,
1681
- allowBigInt: true,
1682
- strict: true,
1683
- useMaps: false,
1684
- rejectDuplicateMapKeys: true,
1685
- tags: /* @__PURE__ */ Object.freeze(
1686
- /* @__PURE__ */ Object.assign([], {
1687
- [CID_CBOR_TAG]: (bytes) => {
1688
- if (bytes[0] !== 0) {
1689
- throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
1690
- }
1691
- const cibBytes = bytes.subarray(1);
1692
- return decodeCid(cibBytes);
1693
- }
1694
- })
1695
- )
1696
- });
1697
- function encode(data) {
1698
- return encode$1(data, encodeOptions);
1699
- }
1700
- function decode(bytes) {
1701
- return decode$1(bytes, decodeOptions);
1702
- }
1703
- function* decodeAll(data) {
1704
- do {
1705
- const [result, remainingBytes] = decodeFirst(data, decodeOptions);
1706
- yield result;
1707
- data = remainingBytes;
1708
- } while (data.byteLength > 0);
1709
- }
1710
- async function cidForLex(value) {
1711
- return cidForCbor(encode(value));
1712
- }
1713
- export {
1714
- decode as cborDecode,
1715
- decodeAll as cborDecodeAll,
1716
- encode as cborEncode,
1717
- cidForLex,
1718
- decode,
1719
- decodeAll,
1720
- decodeOptions,
1721
- encode,
1722
- encodeOptions
1723
- };