cbor-x 1.4.1 → 1.5.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.
@@ -0,0 +1,1137 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CBOR = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ let decoder;
8
+ try {
9
+ decoder = new TextDecoder();
10
+ } catch(error) {}
11
+ let src;
12
+ let srcEnd;
13
+ let position = 0;
14
+ const EMPTY_ARRAY = [];
15
+ const LEGACY_RECORD_INLINE_ID = 105;
16
+ const RECORD_DEFINITIONS_ID = 0xdffe;
17
+ const RECORD_INLINE_ID = 0xdfff; // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'
18
+ const BUNDLED_STRINGS_ID = 0xdff9;
19
+ const PACKED_REFERENCE_TAG_ID = 6;
20
+ const STOP_CODE = {};
21
+ let strings = EMPTY_ARRAY;
22
+ let stringPosition = 0;
23
+ let currentDecoder = {};
24
+ let currentStructures;
25
+ let srcString;
26
+ let srcStringStart = 0;
27
+ let srcStringEnd = 0;
28
+ let bundledStrings;
29
+ let referenceMap;
30
+ let currentExtensions = [];
31
+ let currentExtensionRanges = [];
32
+ let packedValues;
33
+ let dataView;
34
+ let restoreMapsAsObject;
35
+ let defaultOptions = {
36
+ useRecords: false,
37
+ mapsAsObjects: true
38
+ };
39
+ let sequentialMode = false;
40
+
41
+ class Decoder {
42
+ constructor(options) {
43
+ if (options) {
44
+ if ((options.keyMap || options._keyMap) && !options.useRecords) {
45
+ options.useRecords = false;
46
+ options.mapsAsObjects = true;
47
+ }
48
+ if (options.useRecords === false && options.mapsAsObjects === undefined)
49
+ options.mapsAsObjects = true;
50
+ if (options.getStructures)
51
+ options.getShared = options.getStructures;
52
+ if (options.getShared && !options.structures)
53
+ (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
54
+ if (options.keyMap) {
55
+ this.mapKey = new Map();
56
+ for (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k);
57
+ }
58
+ }
59
+ Object.assign(this, options);
60
+ }
61
+ /*
62
+ decodeKey(key) {
63
+ return this.keyMap
64
+ ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
65
+ : key
66
+ }
67
+ */
68
+ decodeKey(key) {
69
+ return this.keyMap ? this.mapKey.get(key) || key : key
70
+ }
71
+
72
+ encodeKey(key) {
73
+ return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key
74
+ }
75
+
76
+ encodeKeys(rec) {
77
+ if (!this._keyMap) return rec
78
+ let map = new Map();
79
+ for (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v);
80
+ return map
81
+ }
82
+
83
+ decodeKeys(map) {
84
+ if (!this._keyMap || map.constructor.name != 'Map') return map
85
+ if (!this._mapKey) {
86
+ this._mapKey = new Map();
87
+ for (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k);
88
+ }
89
+ let res = {};
90
+ //map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)
91
+ map.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
92
+ return res
93
+ }
94
+
95
+ mapDecode(source, end) {
96
+
97
+ let res = this.decode(source);
98
+ if (this._keyMap) {
99
+ //Experiemntal support for Optimised KeyMap decoding
100
+ switch (res.constructor.name) {
101
+ case 'Array': return res.map(r => this.decodeKeys(r))
102
+ //case 'Map': return this.decodeKeys(res)
103
+ }
104
+ }
105
+ return res
106
+ }
107
+
108
+ decode(source, end) {
109
+ if (src) {
110
+ // re-entrant execution, save the state and restore it after we do this decode
111
+ return saveState(() => {
112
+ clearSource();
113
+ return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)
114
+ })
115
+ }
116
+ srcEnd = end > -1 ? end : source.length;
117
+ position = 0;
118
+ stringPosition = 0;
119
+ srcStringEnd = 0;
120
+ srcString = null;
121
+ strings = EMPTY_ARRAY;
122
+ bundledStrings = null;
123
+ src = source;
124
+ // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
125
+ // technique for getting data from a database where it can be copied into an existing buffer instead of creating
126
+ // new ones
127
+ try {
128
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
129
+ } catch(error) {
130
+ // if it doesn't have a buffer, maybe it is the wrong type of object
131
+ src = null;
132
+ if (source instanceof Uint8Array)
133
+ throw error
134
+ throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
135
+ }
136
+ if (this instanceof Decoder) {
137
+ currentDecoder = this;
138
+ packedValues = this.sharedValues &&
139
+ (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :
140
+ this.sharedValues);
141
+ if (this.structures) {
142
+ currentStructures = this.structures;
143
+ return checkedRead()
144
+ } else if (!currentStructures || currentStructures.length > 0) {
145
+ currentStructures = [];
146
+ }
147
+ } else {
148
+ currentDecoder = defaultOptions;
149
+ if (!currentStructures || currentStructures.length > 0)
150
+ currentStructures = [];
151
+ packedValues = null;
152
+ }
153
+ return checkedRead()
154
+ }
155
+ decodeMultiple(source, forEach) {
156
+ let values, lastPosition = 0;
157
+ try {
158
+ let size = source.length;
159
+ sequentialMode = true;
160
+ let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
161
+ if (forEach) {
162
+ if (forEach(value) === false) {
163
+ return
164
+ }
165
+ while(position < size) {
166
+ lastPosition = position;
167
+ if (forEach(checkedRead()) === false) {
168
+ return
169
+ }
170
+ }
171
+ }
172
+ else {
173
+ values = [ value ];
174
+ while(position < size) {
175
+ lastPosition = position;
176
+ values.push(checkedRead());
177
+ }
178
+ return values
179
+ }
180
+ } catch(error) {
181
+ error.lastPosition = lastPosition;
182
+ error.values = values;
183
+ throw error
184
+ } finally {
185
+ sequentialMode = false;
186
+ clearSource();
187
+ }
188
+ }
189
+ }
190
+ function getPosition() {
191
+ return position
192
+ }
193
+ function checkedRead() {
194
+ try {
195
+ let result = read();
196
+ if (bundledStrings) {
197
+ if (position >= bundledStrings.postBundlePosition) {
198
+ let error = new Error('Unexpected bundle position');
199
+ error.incomplete = true;
200
+ throw error
201
+ }
202
+ // bundled strings to skip past
203
+ position = bundledStrings.postBundlePosition;
204
+ bundledStrings = null;
205
+ }
206
+
207
+ if (position == srcEnd) {
208
+ // finished reading this source, cleanup references
209
+ currentStructures = null;
210
+ src = null;
211
+ if (referenceMap)
212
+ referenceMap = null;
213
+ } else if (position > srcEnd) {
214
+ // over read
215
+ let error = new Error('Unexpected end of CBOR data');
216
+ error.incomplete = true;
217
+ throw error
218
+ } else if (!sequentialMode) {
219
+ throw new Error('Data read, but end of buffer not reached')
220
+ }
221
+ // else more to read, but we are reading sequentially, so don't clear source yet
222
+ return result
223
+ } catch(error) {
224
+ clearSource();
225
+ if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {
226
+ error.incomplete = true;
227
+ }
228
+ throw error
229
+ }
230
+ }
231
+
232
+ function read() {
233
+ let token = src[position++];
234
+ let majorType = token >> 5;
235
+ token = token & 0x1f;
236
+ if (token > 0x17) {
237
+ switch (token) {
238
+ case 0x18:
239
+ token = src[position++];
240
+ break
241
+ case 0x19:
242
+ if (majorType == 7) {
243
+ return getFloat16()
244
+ }
245
+ token = dataView.getUint16(position);
246
+ position += 2;
247
+ break
248
+ case 0x1a:
249
+ if (majorType == 7) {
250
+ let value = dataView.getFloat32(position);
251
+ if (currentDecoder.useFloat32 > 2) {
252
+ // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
253
+ let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
254
+ position += 4;
255
+ return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
256
+ }
257
+ position += 4;
258
+ return value
259
+ }
260
+ token = dataView.getUint32(position);
261
+ position += 4;
262
+ break
263
+ case 0x1b:
264
+ if (majorType == 7) {
265
+ let value = dataView.getFloat64(position);
266
+ position += 8;
267
+ return value
268
+ }
269
+ if (majorType > 1) {
270
+ if (dataView.getUint32(position) > 0)
271
+ throw new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')
272
+ token = dataView.getUint32(position + 4);
273
+ } else if (currentDecoder.int64AsNumber) {
274
+ token = dataView.getUint32(position) * 0x100000000;
275
+ token += dataView.getUint32(position + 4);
276
+ } else
277
+ token = dataView.getBigUint64(position);
278
+ position += 8;
279
+ break
280
+ case 0x1f:
281
+ // indefinite length
282
+ switch(majorType) {
283
+ case 2: // byte string
284
+ case 3: // text string
285
+ throw new Error('Indefinite length not supported for byte or text strings')
286
+ case 4: // array
287
+ let array = [];
288
+ let value, i = 0;
289
+ while ((value = read()) != STOP_CODE) {
290
+ array[i++] = value;
291
+ }
292
+ return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)
293
+ case 5: // map
294
+ let key;
295
+ if (currentDecoder.mapsAsObjects) {
296
+ let object = {};
297
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) object[safeKey(currentDecoder.decodeKey(key))] = read();
298
+ else while ((key = read()) != STOP_CODE) object[safeKey(key)] = read();
299
+ return object
300
+ } else {
301
+ if (restoreMapsAsObject) {
302
+ currentDecoder.mapsAsObjects = true;
303
+ restoreMapsAsObject = false;
304
+ }
305
+ let map = new Map();
306
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) map.set(currentDecoder.decodeKey(key), read());
307
+ else while ((key = read()) != STOP_CODE) map.set(key, read());
308
+ return map
309
+ }
310
+ case 7:
311
+ return STOP_CODE
312
+ default:
313
+ throw new Error('Invalid major type for indefinite length ' + majorType)
314
+ }
315
+ default:
316
+ throw new Error('Unknown token ' + token)
317
+ }
318
+ }
319
+ switch (majorType) {
320
+ case 0: // positive int
321
+ return token
322
+ case 1: // negative int
323
+ return ~token
324
+ case 2: // buffer
325
+ return readBin(token)
326
+ case 3: // string
327
+ if (srcStringEnd >= position) {
328
+ return srcString.slice(position - srcStringStart, (position += token) - srcStringStart)
329
+ }
330
+ if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
331
+ // for small blocks, avoiding the overhead of the extract call is helpful
332
+ let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
333
+ if (string != null)
334
+ return string
335
+ }
336
+ return readFixedString(token)
337
+ case 4: // array
338
+ let array = new Array(token);
339
+ //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())
340
+ //else
341
+ for (let i = 0; i < token; i++) array[i] = read();
342
+ return array
343
+ case 5: // map
344
+ if (currentDecoder.mapsAsObjects) {
345
+ let object = {};
346
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
347
+ else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
348
+ return object
349
+ } else {
350
+ if (restoreMapsAsObject) {
351
+ currentDecoder.mapsAsObjects = true;
352
+ restoreMapsAsObject = false;
353
+ }
354
+ let map = new Map();
355
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read());
356
+ else for (let i = 0; i < token; i++) map.set(read(), read());
357
+ return map
358
+ }
359
+ case 6: // extension
360
+ if (token >= BUNDLED_STRINGS_ID) {
361
+ let structure = currentStructures[token & 0x1fff]; // check record structures first
362
+ // At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000))
363
+ if (structure) {
364
+ if (!structure.read) structure.read = createStructureReader(structure);
365
+ return structure.read()
366
+ }
367
+ if (token < 0x10000) {
368
+ if (token == RECORD_INLINE_ID) // we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
369
+ return recordDefinition(read())
370
+ else if (token == RECORD_DEFINITIONS_ID) {
371
+ let length = readJustLength();
372
+ let id = read();
373
+ for (let i = 2; i < length; i++) {
374
+ recordDefinition([id++, read()]);
375
+ }
376
+ return read()
377
+ } else if (token == BUNDLED_STRINGS_ID) {
378
+ return readBundleExt()
379
+ }
380
+ if (currentDecoder.getShared) {
381
+ loadShared();
382
+ structure = currentStructures[token & 0x1fff];
383
+ if (structure) {
384
+ if (!structure.read)
385
+ structure.read = createStructureReader(structure);
386
+ return structure.read()
387
+ }
388
+ }
389
+ }
390
+ }
391
+ let extension = currentExtensions[token];
392
+ if (extension) {
393
+ if (extension.handlesRead)
394
+ return extension(read)
395
+ else
396
+ return extension(read())
397
+ } else {
398
+ let input = read();
399
+ for (let i = 0; i < currentExtensionRanges.length; i++) {
400
+ let value = currentExtensionRanges[i](token, input);
401
+ if (value !== undefined)
402
+ return value
403
+ }
404
+ return new Tag(input, token)
405
+ }
406
+ case 7: // fixed value
407
+ switch (token) {
408
+ case 0x14: return false
409
+ case 0x15: return true
410
+ case 0x16: return null
411
+ case 0x17: return; // undefined
412
+ case 0x1f:
413
+ default:
414
+ let packedValue = (packedValues || getPackedValues())[token];
415
+ if (packedValue !== undefined)
416
+ return packedValue
417
+ throw new Error('Unknown token ' + token)
418
+ }
419
+ default: // negative int
420
+ if (isNaN(token)) {
421
+ let error = new Error('Unexpected end of CBOR data');
422
+ error.incomplete = true;
423
+ throw error
424
+ }
425
+ throw new Error('Unknown CBOR token ' + token)
426
+ }
427
+ }
428
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
429
+ function createStructureReader(structure) {
430
+ function readObject() {
431
+ // get the array size from the header
432
+ let length = src[position++];
433
+ //let majorType = token >> 5
434
+ length = length & 0x1f;
435
+ if (length > 0x17) {
436
+ switch (length) {
437
+ case 0x18:
438
+ length = src[position++];
439
+ break
440
+ case 0x19:
441
+ length = dataView.getUint16(position);
442
+ position += 2;
443
+ break
444
+ case 0x1a:
445
+ length = dataView.getUint32(position);
446
+ position += 4;
447
+ break
448
+ default:
449
+ throw new Error('Expected array header, but got ' + src[position - 1])
450
+ }
451
+ }
452
+ // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
453
+ let compiledReader = this.compiledReader; // first look to see if we have the fast compiled function
454
+ while(compiledReader) {
455
+ // we have a fast compiled object literal reader
456
+ if (compiledReader.propertyCount === length)
457
+ return compiledReader(read) // with the right length, so we use it
458
+ compiledReader = compiledReader.next; // see if there is another reader with the right length
459
+ }
460
+ if (this.slowReads++ >= 3) { // create a fast compiled reader
461
+ let array = this.length == length ? this : this.slice(0, length);
462
+ compiledReader = currentDecoder.keyMap
463
+ ? new BlockedFunction ('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')
464
+ : new BlockedFunction ('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}');
465
+ if (this.compiledReader)
466
+ compiledReader.next = this.compiledReader; // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure
467
+ compiledReader.propertyCount = length;
468
+ this.compiledReader = compiledReader;
469
+ return compiledReader(read)
470
+ }
471
+ let object = {};
472
+ if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
473
+ else for (let i = 0; i < length; i++) {
474
+ object[safeKey(this[i])] = read();
475
+ }
476
+ return object
477
+ }
478
+ structure.slowReads = 0;
479
+ return readObject
480
+ }
481
+
482
+ function safeKey(key) {
483
+ return key === '__proto__' ? '__proto_' : key
484
+ }
485
+
486
+ let readFixedString = readStringJS;
487
+
488
+ exports.isNativeAccelerationEnabled = false;
489
+ function setExtractor(extractStrings) {
490
+ exports.isNativeAccelerationEnabled = true;
491
+ readFixedString = readString();
492
+ function readString(headerLength) {
493
+ return function readString(length) {
494
+ let string = strings[stringPosition++];
495
+ if (string == null) {
496
+ if (bundledStrings)
497
+ return readStringJS(length)
498
+ let extraction = extractStrings(position, srcEnd, length, src);
499
+ if (typeof extraction == 'string') {
500
+ string = extraction;
501
+ strings = EMPTY_ARRAY;
502
+ } else {
503
+ strings = extraction;
504
+ stringPosition = 1;
505
+ srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
506
+ string = strings[0];
507
+ if (string === undefined)
508
+ throw new Error('Unexpected end of buffer')
509
+ }
510
+ }
511
+ let srcStringLength = string.length;
512
+ if (srcStringLength <= length) {
513
+ position += length;
514
+ return string
515
+ }
516
+ srcString = string;
517
+ srcStringStart = position;
518
+ srcStringEnd = position + srcStringLength;
519
+ position += length;
520
+ return string.slice(0, length) // we know we just want the beginning
521
+ }
522
+ }
523
+ }
524
+ function readStringJS(length) {
525
+ let result;
526
+ if (length < 16) {
527
+ if (result = shortStringInJS(length))
528
+ return result
529
+ }
530
+ if (length > 64 && decoder)
531
+ return decoder.decode(src.subarray(position, position += length))
532
+ const end = position + length;
533
+ const units = [];
534
+ result = '';
535
+ while (position < end) {
536
+ const byte1 = src[position++];
537
+ if ((byte1 & 0x80) === 0) {
538
+ // 1 byte
539
+ units.push(byte1);
540
+ } else if ((byte1 & 0xe0) === 0xc0) {
541
+ // 2 bytes
542
+ const byte2 = src[position++] & 0x3f;
543
+ units.push(((byte1 & 0x1f) << 6) | byte2);
544
+ } else if ((byte1 & 0xf0) === 0xe0) {
545
+ // 3 bytes
546
+ const byte2 = src[position++] & 0x3f;
547
+ const byte3 = src[position++] & 0x3f;
548
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
549
+ } else if ((byte1 & 0xf8) === 0xf0) {
550
+ // 4 bytes
551
+ const byte2 = src[position++] & 0x3f;
552
+ const byte3 = src[position++] & 0x3f;
553
+ const byte4 = src[position++] & 0x3f;
554
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
555
+ if (unit > 0xffff) {
556
+ unit -= 0x10000;
557
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
558
+ unit = 0xdc00 | (unit & 0x3ff);
559
+ }
560
+ units.push(unit);
561
+ } else {
562
+ units.push(byte1);
563
+ }
564
+
565
+ if (units.length >= 0x1000) {
566
+ result += fromCharCode.apply(String, units);
567
+ units.length = 0;
568
+ }
569
+ }
570
+
571
+ if (units.length > 0) {
572
+ result += fromCharCode.apply(String, units);
573
+ }
574
+
575
+ return result
576
+ }
577
+ let fromCharCode = String.fromCharCode;
578
+ function longStringInJS(length) {
579
+ let start = position;
580
+ let bytes = new Array(length);
581
+ for (let i = 0; i < length; i++) {
582
+ const byte = src[position++];
583
+ if ((byte & 0x80) > 0) {
584
+ position = start;
585
+ return
586
+ }
587
+ bytes[i] = byte;
588
+ }
589
+ return fromCharCode.apply(String, bytes)
590
+ }
591
+ function shortStringInJS(length) {
592
+ if (length < 4) {
593
+ if (length < 2) {
594
+ if (length === 0)
595
+ return ''
596
+ else {
597
+ let a = src[position++];
598
+ if ((a & 0x80) > 1) {
599
+ position -= 1;
600
+ return
601
+ }
602
+ return fromCharCode(a)
603
+ }
604
+ } else {
605
+ let a = src[position++];
606
+ let b = src[position++];
607
+ if ((a & 0x80) > 0 || (b & 0x80) > 0) {
608
+ position -= 2;
609
+ return
610
+ }
611
+ if (length < 3)
612
+ return fromCharCode(a, b)
613
+ let c = src[position++];
614
+ if ((c & 0x80) > 0) {
615
+ position -= 3;
616
+ return
617
+ }
618
+ return fromCharCode(a, b, c)
619
+ }
620
+ } else {
621
+ let a = src[position++];
622
+ let b = src[position++];
623
+ let c = src[position++];
624
+ let d = src[position++];
625
+ if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
626
+ position -= 4;
627
+ return
628
+ }
629
+ if (length < 6) {
630
+ if (length === 4)
631
+ return fromCharCode(a, b, c, d)
632
+ else {
633
+ let e = src[position++];
634
+ if ((e & 0x80) > 0) {
635
+ position -= 5;
636
+ return
637
+ }
638
+ return fromCharCode(a, b, c, d, e)
639
+ }
640
+ } else if (length < 8) {
641
+ let e = src[position++];
642
+ let f = src[position++];
643
+ if ((e & 0x80) > 0 || (f & 0x80) > 0) {
644
+ position -= 6;
645
+ return
646
+ }
647
+ if (length < 7)
648
+ return fromCharCode(a, b, c, d, e, f)
649
+ let g = src[position++];
650
+ if ((g & 0x80) > 0) {
651
+ position -= 7;
652
+ return
653
+ }
654
+ return fromCharCode(a, b, c, d, e, f, g)
655
+ } else {
656
+ let e = src[position++];
657
+ let f = src[position++];
658
+ let g = src[position++];
659
+ let h = src[position++];
660
+ if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
661
+ position -= 8;
662
+ return
663
+ }
664
+ if (length < 10) {
665
+ if (length === 8)
666
+ return fromCharCode(a, b, c, d, e, f, g, h)
667
+ else {
668
+ let i = src[position++];
669
+ if ((i & 0x80) > 0) {
670
+ position -= 9;
671
+ return
672
+ }
673
+ return fromCharCode(a, b, c, d, e, f, g, h, i)
674
+ }
675
+ } else if (length < 12) {
676
+ let i = src[position++];
677
+ let j = src[position++];
678
+ if ((i & 0x80) > 0 || (j & 0x80) > 0) {
679
+ position -= 10;
680
+ return
681
+ }
682
+ if (length < 11)
683
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j)
684
+ let k = src[position++];
685
+ if ((k & 0x80) > 0) {
686
+ position -= 11;
687
+ return
688
+ }
689
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
690
+ } else {
691
+ let i = src[position++];
692
+ let j = src[position++];
693
+ let k = src[position++];
694
+ let l = src[position++];
695
+ if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
696
+ position -= 12;
697
+ return
698
+ }
699
+ if (length < 14) {
700
+ if (length === 12)
701
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
702
+ else {
703
+ let m = src[position++];
704
+ if ((m & 0x80) > 0) {
705
+ position -= 13;
706
+ return
707
+ }
708
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
709
+ }
710
+ } else {
711
+ let m = src[position++];
712
+ let n = src[position++];
713
+ if ((m & 0x80) > 0 || (n & 0x80) > 0) {
714
+ position -= 14;
715
+ return
716
+ }
717
+ if (length < 15)
718
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
719
+ let o = src[position++];
720
+ if ((o & 0x80) > 0) {
721
+ position -= 15;
722
+ return
723
+ }
724
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
725
+ }
726
+ }
727
+ }
728
+ }
729
+ }
730
+
731
+ function readBin(length) {
732
+ return currentDecoder.copyBuffers ?
733
+ // specifically use the copying slice (not the node one)
734
+ Uint8Array.prototype.slice.call(src, position, position += length) :
735
+ src.subarray(position, position += length)
736
+ }
737
+ let f32Array = new Float32Array(1);
738
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
739
+ function getFloat16() {
740
+ let byte0 = src[position++];
741
+ let byte1 = src[position++];
742
+ let exponent = (byte0 & 0x7f) >> 2;
743
+ if (exponent === 0x1f) { // specials
744
+ if (byte1 || (byte0 & 3))
745
+ return NaN;
746
+ return (byte0 & 0x80) ? -Infinity : Infinity;
747
+ }
748
+ if (exponent === 0) { // sub-normals
749
+ // significand with 10 fractional bits and divided by 2^14
750
+ let abs = (((byte0 & 3) << 8) | byte1) / (1 << 24);
751
+ return (byte0 & 0x80) ? -abs : abs
752
+ }
753
+
754
+ u8Array[3] = (byte0 & 0x80) | // sign bit
755
+ ((exponent >> 1) + 56); // 4 of 5 of the exponent bits, re-offset-ed
756
+ u8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits
757
+ (byte1 >> 3); // next 5 bits of mantissa
758
+ u8Array[1] = byte1 << 5; // last three bits of mantissa
759
+ u8Array[0] = 0;
760
+ return f32Array[0];
761
+ }
762
+
763
+ new Array(4096);
764
+
765
+ class Tag {
766
+ constructor(value, tag) {
767
+ this.value = value;
768
+ this.tag = tag;
769
+ }
770
+ }
771
+
772
+ currentExtensions[0] = (dateString) => {
773
+ // string date extension
774
+ return new Date(dateString)
775
+ };
776
+
777
+ currentExtensions[1] = (epochSec) => {
778
+ // numeric date extension
779
+ return new Date(Math.round(epochSec * 1000))
780
+ };
781
+
782
+ currentExtensions[2] = (buffer) => {
783
+ // bigint extension
784
+ let value = BigInt(0);
785
+ for (let i = 0, l = buffer.byteLength; i < l; i++) {
786
+ value = BigInt(buffer[i]) + value << BigInt(8);
787
+ }
788
+ return value
789
+ };
790
+
791
+ currentExtensions[3] = (buffer) => {
792
+ // negative bigint extension
793
+ return BigInt(-1) - currentExtensions[2](buffer)
794
+ };
795
+ currentExtensions[4] = (fraction) => {
796
+ // best to reparse to maintain accuracy
797
+ return +(fraction[1] + 'e' + fraction[0])
798
+ };
799
+
800
+ currentExtensions[5] = (fraction) => {
801
+ // probably not sufficiently accurate
802
+ return fraction[1] * Math.exp(fraction[0] * Math.log(2))
803
+ };
804
+
805
+ // the registration of the record definition extension
806
+ const recordDefinition = (definition) => {
807
+ let id = definition[0] - 0xe000;
808
+ let structure = definition[1];
809
+ let existingStructure = currentStructures[id];
810
+ if (existingStructure && existingStructure.isShared) {
811
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
812
+ }
813
+ currentStructures[id] = structure;
814
+
815
+ structure.read = createStructureReader(structure);
816
+ let object = {};
817
+ if (currentDecoder.keyMap) for (let i = 2,l = definition.length; i < l; i++) {
818
+ let key = currentDecoder.decodeKey(structure[i - 2]);
819
+ object[safeKey(key)] = definition[i];
820
+ }
821
+ else for (let i = 2,l = definition.length; i < l; i++) {
822
+ let key = structure[i - 2];
823
+ object[safeKey(key)] = definition[i];
824
+ }
825
+ return object
826
+ };
827
+ currentExtensions[LEGACY_RECORD_INLINE_ID] = recordDefinition;
828
+ currentExtensions[14] = (value) => {
829
+ if (bundledStrings)
830
+ return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 += value)
831
+ return new Tag(value, 14)
832
+ };
833
+ currentExtensions[15] = (value) => {
834
+ if (bundledStrings)
835
+ return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
836
+ return new Tag(value, 15)
837
+ };
838
+ let glbl = { Error, RegExp };
839
+ currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object
840
+ return (glbl[data[0]] || Error)(data[1], data[2])
841
+ };
842
+ const packedTable = (read) => {
843
+ if (src[position++] != 0x84)
844
+ throw new Error('Packed values structure must be followed by a 4 element array')
845
+ let newPackedValues = read(); // packed values
846
+ packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
847
+ packedValues.prefixes = read();
848
+ packedValues.suffixes = read();
849
+ return read() // read the rump
850
+ };
851
+ packedTable.handlesRead = true;
852
+ currentExtensions[51] = packedTable;
853
+
854
+ currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference
855
+ if (!packedValues) {
856
+ if (currentDecoder.getShared)
857
+ loadShared();
858
+ else
859
+ return new Tag(data, PACKED_REFERENCE_TAG_ID)
860
+ }
861
+ if (typeof data == 'number')
862
+ return packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]
863
+ throw new Error('No support for non-integer packed references yet')
864
+ };
865
+
866
+ // The following code is an incomplete implementation of http://cbor.schmorp.de/stringref
867
+ // the real thing would need to implemennt more logic to populate the stringRefs table and
868
+ // maintain a stack of stringRef "namespaces".
869
+ //
870
+ // currentExtensions[25] = (id) => {
871
+ // return stringRefs[id]
872
+ // }
873
+ // currentExtensions[256] = (read) => {
874
+ // stringRefs = []
875
+ // try {
876
+ // return read()
877
+ // } finally {
878
+ // stringRefs = null
879
+ // }
880
+ // }
881
+ // currentExtensions[256].handlesRead = true
882
+
883
+ currentExtensions[28] = (read) => {
884
+ // shareable http://cbor.schmorp.de/value-sharing (for structured clones)
885
+ if (!referenceMap) {
886
+ referenceMap = new Map();
887
+ referenceMap.id = 0;
888
+ }
889
+ let id = referenceMap.id++;
890
+ let token = src[position];
891
+ let target;
892
+ // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
893
+ // ahead past references to record structure definitions
894
+ if ((token >> 5) == 4)
895
+ target = [];
896
+ else
897
+ target = {};
898
+
899
+ let refEntry = { target }; // a placeholder object
900
+ referenceMap.set(id, refEntry);
901
+ let targetProperties = read(); // read the next value as the target object to id
902
+ if (refEntry.used) // there is a cycle, so we have to assign properties to original target
903
+ return Object.assign(target, targetProperties)
904
+ refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
905
+ return targetProperties // no cycle, can just use the returned read object
906
+ };
907
+ currentExtensions[28].handlesRead = true;
908
+
909
+ currentExtensions[29] = (id) => {
910
+ // sharedref http://cbor.schmorp.de/value-sharing (for structured clones)
911
+ let refEntry = referenceMap.get(id);
912
+ refEntry.used = true;
913
+ return refEntry.target
914
+ };
915
+
916
+ currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
917
+ (currentExtensions[259] = (read) => {
918
+ // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec
919
+ // for decoding as a standard Map
920
+ if (currentDecoder.mapsAsObjects) {
921
+ currentDecoder.mapsAsObjects = false;
922
+ restoreMapsAsObject = true;
923
+ }
924
+ return read()
925
+ }).handlesRead = true;
926
+ function combine(a, b) {
927
+ if (typeof a === 'string')
928
+ return a + b
929
+ if (a instanceof Array)
930
+ return a.concat(b)
931
+ return Object.assign({}, a, b)
932
+ }
933
+ function getPackedValues() {
934
+ if (!packedValues) {
935
+ if (currentDecoder.getShared)
936
+ loadShared();
937
+ else
938
+ throw new Error('No packed values available')
939
+ }
940
+ return packedValues
941
+ }
942
+ const SHARED_DATA_TAG_ID = 0x53687264; // ascii 'Shrd'
943
+ currentExtensionRanges.push((tag, input) => {
944
+ if (tag >= 225 && tag <= 255)
945
+ return combine(getPackedValues().prefixes[tag - 224], input)
946
+ if (tag >= 28704 && tag <= 32767)
947
+ return combine(getPackedValues().prefixes[tag - 28672], input)
948
+ if (tag >= 1879052288 && tag <= 2147483647)
949
+ return combine(getPackedValues().prefixes[tag - 1879048192], input)
950
+ if (tag >= 216 && tag <= 223)
951
+ return combine(input, getPackedValues().suffixes[tag - 216])
952
+ if (tag >= 27647 && tag <= 28671)
953
+ return combine(input, getPackedValues().suffixes[tag - 27639])
954
+ if (tag >= 1811940352 && tag <= 1879048191)
955
+ return combine(input, getPackedValues().suffixes[tag - 1811939328])
956
+ if (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)
957
+ return {
958
+ packedValues: packedValues,
959
+ structures: currentStructures.slice(0),
960
+ version: input,
961
+ }
962
+ }
963
+ if (tag == 55799) // self-descriptive CBOR tag, just return input value
964
+ return input
965
+ });
966
+
967
+ const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
968
+ const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
969
+ typeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,
970
+ typeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array];
971
+ const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
972
+ for (let i = 0; i < typedArrays.length; i++) {
973
+ registerTypedArray(typedArrays[i], typedArrayTags[i]);
974
+ }
975
+ function registerTypedArray(TypedArray, tag) {
976
+ let dvMethod = 'get' + TypedArray.name.slice(0, -5);
977
+ if (typeof TypedArray !== 'function')
978
+ TypedArray = null;
979
+ let bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
980
+ for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
981
+ if (!littleEndian && bytesPerElement == 1)
982
+ continue
983
+ let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : 3;
984
+ currentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine) ? (buffer) => {
985
+ if (!TypedArray)
986
+ throw new Error('Could not find typed array for code ' + tag)
987
+ // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
988
+ return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)
989
+ } : buffer => {
990
+ if (!TypedArray)
991
+ throw new Error('Could not find typed array for code ' + tag)
992
+ let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
993
+ let elements = buffer.length >> sizeShift;
994
+ let ta = new TypedArray(elements);
995
+ let method = dv[dvMethod];
996
+ for (let i = 0; i < elements; i++) {
997
+ ta[i] = method.call(dv, i << sizeShift, littleEndian);
998
+ }
999
+ return ta
1000
+ };
1001
+ }
1002
+ }
1003
+
1004
+ function readBundleExt() {
1005
+ let length = readJustLength();
1006
+ let bundlePosition = position + read();
1007
+ for (let i = 2; i < length; i++) {
1008
+ // skip past bundles that were already read
1009
+ let bundleLength = readJustLength(); // this will increment position, so must add to position afterwards
1010
+ position += bundleLength;
1011
+ }
1012
+ let dataPosition = position;
1013
+ position = bundlePosition;
1014
+ bundledStrings = [readStringJS(readJustLength()), readStringJS(readJustLength())];
1015
+ bundledStrings.position0 = 0;
1016
+ bundledStrings.position1 = 0;
1017
+ bundledStrings.postBundlePosition = position;
1018
+ position = dataPosition;
1019
+ return read()
1020
+ }
1021
+
1022
+ function readJustLength() {
1023
+ let token = src[position++] & 0x1f;
1024
+ if (token > 0x17) {
1025
+ switch (token) {
1026
+ case 0x18:
1027
+ token = src[position++];
1028
+ break
1029
+ case 0x19:
1030
+ token = dataView.getUint16(position);
1031
+ position += 2;
1032
+ break
1033
+ case 0x1a:
1034
+ token = dataView.getUint32(position);
1035
+ position += 4;
1036
+ break
1037
+ }
1038
+ }
1039
+ return token
1040
+ }
1041
+
1042
+ function loadShared() {
1043
+ if (currentDecoder.getShared) {
1044
+ let sharedData = saveState(() => {
1045
+ // save the state in case getShared modifies our buffer
1046
+ src = null;
1047
+ return currentDecoder.getShared()
1048
+ }) || {};
1049
+ let updatedStructures = sharedData.structures || [];
1050
+ currentDecoder.sharedVersion = sharedData.version;
1051
+ packedValues = currentDecoder.sharedValues = sharedData.packedValues;
1052
+ if (currentStructures === true)
1053
+ currentDecoder.structures = currentStructures = updatedStructures;
1054
+ else
1055
+ currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
1056
+ }
1057
+ }
1058
+
1059
+ function saveState(callback) {
1060
+ let savedSrcEnd = srcEnd;
1061
+ let savedPosition = position;
1062
+ let savedStringPosition = stringPosition;
1063
+ let savedSrcStringStart = srcStringStart;
1064
+ let savedSrcStringEnd = srcStringEnd;
1065
+ let savedSrcString = srcString;
1066
+ let savedStrings = strings;
1067
+ let savedReferenceMap = referenceMap;
1068
+ let savedBundledStrings = bundledStrings;
1069
+
1070
+ // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1071
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1072
+ let savedStructures = currentStructures;
1073
+ let savedDecoder = currentDecoder;
1074
+ let savedSequentialMode = sequentialMode;
1075
+ let value = callback();
1076
+ srcEnd = savedSrcEnd;
1077
+ position = savedPosition;
1078
+ stringPosition = savedStringPosition;
1079
+ srcStringStart = savedSrcStringStart;
1080
+ srcStringEnd = savedSrcStringEnd;
1081
+ srcString = savedSrcString;
1082
+ strings = savedStrings;
1083
+ referenceMap = savedReferenceMap;
1084
+ bundledStrings = savedBundledStrings;
1085
+ src = savedSrc;
1086
+ sequentialMode = savedSequentialMode;
1087
+ currentStructures = savedStructures;
1088
+ currentDecoder = savedDecoder;
1089
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1090
+ return value
1091
+ }
1092
+ function clearSource() {
1093
+ src = null;
1094
+ referenceMap = null;
1095
+ currentStructures = null;
1096
+ }
1097
+
1098
+ function addExtension(extension) {
1099
+ currentExtensions[extension.tag] = extension.decode;
1100
+ }
1101
+
1102
+ const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1103
+ for (let i = 0; i < 256; i++) {
1104
+ mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1105
+ }
1106
+ let defaultDecoder = new Decoder({ useRecords: false });
1107
+ const decode = defaultDecoder.decode;
1108
+ const decodeMultiple = defaultDecoder.decodeMultiple;
1109
+ const FLOAT32_OPTIONS = {
1110
+ NEVER: 0,
1111
+ ALWAYS: 1,
1112
+ DECIMAL_ROUND: 3,
1113
+ DECIMAL_FIT: 4
1114
+ };
1115
+ function roundFloat32(float32Number) {
1116
+ f32Array[0] = float32Number;
1117
+ let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1118
+ return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1119
+ }
1120
+
1121
+ exports.Decoder = Decoder;
1122
+ exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
1123
+ exports.Tag = Tag;
1124
+ exports.addExtension = addExtension;
1125
+ exports.checkedRead = checkedRead;
1126
+ exports.clearSource = clearSource;
1127
+ exports.decode = decode;
1128
+ exports.decodeMultiple = decodeMultiple;
1129
+ exports.getPosition = getPosition;
1130
+ exports.mult10 = mult10;
1131
+ exports.read = read;
1132
+ exports.roundFloat32 = roundFloat32;
1133
+ exports.setExtractor = setExtractor;
1134
+ exports.typedArrays = typedArrays;
1135
+
1136
+ }));
1137
+ //# sourceMappingURL=decode-no-eval.cjs.map