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,2376 @@
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$1 = 0;
14
+ const LEGACY_RECORD_INLINE_ID = 105;
15
+ const RECORD_DEFINITIONS_ID = 0xdffe;
16
+ const RECORD_INLINE_ID = 0xdfff; // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'
17
+ const BUNDLED_STRINGS_ID = 0xdff9;
18
+ const PACKED_REFERENCE_TAG_ID = 6;
19
+ const STOP_CODE = {};
20
+ let currentDecoder = {};
21
+ let currentStructures;
22
+ let srcString;
23
+ let srcStringStart = 0;
24
+ let srcStringEnd = 0;
25
+ let bundledStrings$1;
26
+ let referenceMap;
27
+ let currentExtensions = [];
28
+ let currentExtensionRanges = [];
29
+ let packedValues;
30
+ let dataView;
31
+ let restoreMapsAsObject;
32
+ let defaultOptions = {
33
+ useRecords: false,
34
+ mapsAsObjects: true
35
+ };
36
+ let sequentialMode = false;
37
+
38
+ class Decoder {
39
+ constructor(options) {
40
+ if (options) {
41
+ if ((options.keyMap || options._keyMap) && !options.useRecords) {
42
+ options.useRecords = false;
43
+ options.mapsAsObjects = true;
44
+ }
45
+ if (options.useRecords === false && options.mapsAsObjects === undefined)
46
+ options.mapsAsObjects = true;
47
+ if (options.getStructures)
48
+ options.getShared = options.getStructures;
49
+ if (options.getShared && !options.structures)
50
+ (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
51
+ if (options.keyMap) {
52
+ this.mapKey = new Map();
53
+ for (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k);
54
+ }
55
+ }
56
+ Object.assign(this, options);
57
+ }
58
+ /*
59
+ decodeKey(key) {
60
+ return this.keyMap
61
+ ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key
62
+ : key
63
+ }
64
+ */
65
+ decodeKey(key) {
66
+ return this.keyMap ? this.mapKey.get(key) || key : key
67
+ }
68
+
69
+ encodeKey(key) {
70
+ return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key
71
+ }
72
+
73
+ encodeKeys(rec) {
74
+ if (!this._keyMap) return rec
75
+ let map = new Map();
76
+ for (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v);
77
+ return map
78
+ }
79
+
80
+ decodeKeys(map) {
81
+ if (!this._keyMap || map.constructor.name != 'Map') return map
82
+ if (!this._mapKey) {
83
+ this._mapKey = new Map();
84
+ for (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k);
85
+ }
86
+ let res = {};
87
+ //map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)
88
+ map.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v);
89
+ return res
90
+ }
91
+
92
+ mapDecode(source, end) {
93
+
94
+ let res = this.decode(source);
95
+ if (this._keyMap) {
96
+ //Experiemntal support for Optimised KeyMap decoding
97
+ switch (res.constructor.name) {
98
+ case 'Array': return res.map(r => this.decodeKeys(r))
99
+ //case 'Map': return this.decodeKeys(res)
100
+ }
101
+ }
102
+ return res
103
+ }
104
+
105
+ decode(source, end) {
106
+ if (src) {
107
+ // re-entrant execution, save the state and restore it after we do this decode
108
+ return saveState(() => {
109
+ clearSource();
110
+ return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)
111
+ })
112
+ }
113
+ srcEnd = end > -1 ? end : source.length;
114
+ position$1 = 0;
115
+ srcStringEnd = 0;
116
+ srcString = null;
117
+ bundledStrings$1 = null;
118
+ src = source;
119
+ // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
120
+ // technique for getting data from a database where it can be copied into an existing buffer instead of creating
121
+ // new ones
122
+ try {
123
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
124
+ } catch(error) {
125
+ // if it doesn't have a buffer, maybe it is the wrong type of object
126
+ src = null;
127
+ if (source instanceof Uint8Array)
128
+ throw error
129
+ throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
130
+ }
131
+ if (this instanceof Decoder) {
132
+ currentDecoder = this;
133
+ packedValues = this.sharedValues &&
134
+ (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :
135
+ this.sharedValues);
136
+ if (this.structures) {
137
+ currentStructures = this.structures;
138
+ return checkedRead()
139
+ } else if (!currentStructures || currentStructures.length > 0) {
140
+ currentStructures = [];
141
+ }
142
+ } else {
143
+ currentDecoder = defaultOptions;
144
+ if (!currentStructures || currentStructures.length > 0)
145
+ currentStructures = [];
146
+ packedValues = null;
147
+ }
148
+ return checkedRead()
149
+ }
150
+ decodeMultiple(source, forEach) {
151
+ let values, lastPosition = 0;
152
+ try {
153
+ let size = source.length;
154
+ sequentialMode = true;
155
+ let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size);
156
+ if (forEach) {
157
+ if (forEach(value) === false) {
158
+ return
159
+ }
160
+ while(position$1 < size) {
161
+ lastPosition = position$1;
162
+ if (forEach(checkedRead()) === false) {
163
+ return
164
+ }
165
+ }
166
+ }
167
+ else {
168
+ values = [ value ];
169
+ while(position$1 < size) {
170
+ lastPosition = position$1;
171
+ values.push(checkedRead());
172
+ }
173
+ return values
174
+ }
175
+ } catch(error) {
176
+ error.lastPosition = lastPosition;
177
+ error.values = values;
178
+ throw error
179
+ } finally {
180
+ sequentialMode = false;
181
+ clearSource();
182
+ }
183
+ }
184
+ }
185
+ function checkedRead() {
186
+ try {
187
+ let result = read();
188
+ if (bundledStrings$1) {
189
+ if (position$1 >= bundledStrings$1.postBundlePosition) {
190
+ let error = new Error('Unexpected bundle position');
191
+ error.incomplete = true;
192
+ throw error
193
+ }
194
+ // bundled strings to skip past
195
+ position$1 = bundledStrings$1.postBundlePosition;
196
+ bundledStrings$1 = null;
197
+ }
198
+
199
+ if (position$1 == srcEnd) {
200
+ // finished reading this source, cleanup references
201
+ currentStructures = null;
202
+ src = null;
203
+ if (referenceMap)
204
+ referenceMap = null;
205
+ } else if (position$1 > srcEnd) {
206
+ // over read
207
+ let error = new Error('Unexpected end of CBOR data');
208
+ error.incomplete = true;
209
+ throw error
210
+ } else if (!sequentialMode) {
211
+ throw new Error('Data read, but end of buffer not reached')
212
+ }
213
+ // else more to read, but we are reading sequentially, so don't clear source yet
214
+ return result
215
+ } catch(error) {
216
+ clearSource();
217
+ if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {
218
+ error.incomplete = true;
219
+ }
220
+ throw error
221
+ }
222
+ }
223
+
224
+ function read() {
225
+ let token = src[position$1++];
226
+ let majorType = token >> 5;
227
+ token = token & 0x1f;
228
+ if (token > 0x17) {
229
+ switch (token) {
230
+ case 0x18:
231
+ token = src[position$1++];
232
+ break
233
+ case 0x19:
234
+ if (majorType == 7) {
235
+ return getFloat16()
236
+ }
237
+ token = dataView.getUint16(position$1);
238
+ position$1 += 2;
239
+ break
240
+ case 0x1a:
241
+ if (majorType == 7) {
242
+ let value = dataView.getFloat32(position$1);
243
+ if (currentDecoder.useFloat32 > 2) {
244
+ // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
245
+ let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
246
+ position$1 += 4;
247
+ return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
248
+ }
249
+ position$1 += 4;
250
+ return value
251
+ }
252
+ token = dataView.getUint32(position$1);
253
+ position$1 += 4;
254
+ break
255
+ case 0x1b:
256
+ if (majorType == 7) {
257
+ let value = dataView.getFloat64(position$1);
258
+ position$1 += 8;
259
+ return value
260
+ }
261
+ if (majorType > 1) {
262
+ if (dataView.getUint32(position$1) > 0)
263
+ throw new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')
264
+ token = dataView.getUint32(position$1 + 4);
265
+ } else if (currentDecoder.int64AsNumber) {
266
+ token = dataView.getUint32(position$1) * 0x100000000;
267
+ token += dataView.getUint32(position$1 + 4);
268
+ } else
269
+ token = dataView.getBigUint64(position$1);
270
+ position$1 += 8;
271
+ break
272
+ case 0x1f:
273
+ // indefinite length
274
+ switch(majorType) {
275
+ case 2: // byte string
276
+ case 3: // text string
277
+ throw new Error('Indefinite length not supported for byte or text strings')
278
+ case 4: // array
279
+ let array = [];
280
+ let value, i = 0;
281
+ while ((value = read()) != STOP_CODE) {
282
+ array[i++] = value;
283
+ }
284
+ return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)
285
+ case 5: // map
286
+ let key;
287
+ if (currentDecoder.mapsAsObjects) {
288
+ let object = {};
289
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) object[safeKey(currentDecoder.decodeKey(key))] = read();
290
+ else while ((key = read()) != STOP_CODE) object[safeKey(key)] = read();
291
+ return object
292
+ } else {
293
+ if (restoreMapsAsObject) {
294
+ currentDecoder.mapsAsObjects = true;
295
+ restoreMapsAsObject = false;
296
+ }
297
+ let map = new Map();
298
+ if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) map.set(currentDecoder.decodeKey(key), read());
299
+ else while ((key = read()) != STOP_CODE) map.set(key, read());
300
+ return map
301
+ }
302
+ case 7:
303
+ return STOP_CODE
304
+ default:
305
+ throw new Error('Invalid major type for indefinite length ' + majorType)
306
+ }
307
+ default:
308
+ throw new Error('Unknown token ' + token)
309
+ }
310
+ }
311
+ switch (majorType) {
312
+ case 0: // positive int
313
+ return token
314
+ case 1: // negative int
315
+ return ~token
316
+ case 2: // buffer
317
+ return readBin(token)
318
+ case 3: // string
319
+ if (srcStringEnd >= position$1) {
320
+ return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart)
321
+ }
322
+ if (srcStringEnd == 0 && srcEnd < 140 && token < 32) {
323
+ // for small blocks, avoiding the overhead of the extract call is helpful
324
+ let string = token < 16 ? shortStringInJS(token) : longStringInJS(token);
325
+ if (string != null)
326
+ return string
327
+ }
328
+ return readFixedString(token)
329
+ case 4: // array
330
+ let array = new Array(token);
331
+ //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())
332
+ //else
333
+ for (let i = 0; i < token; i++) array[i] = read();
334
+ return array
335
+ case 5: // map
336
+ if (currentDecoder.mapsAsObjects) {
337
+ let object = {};
338
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read();
339
+ else for (let i = 0; i < token; i++) object[safeKey(read())] = read();
340
+ return object
341
+ } else {
342
+ if (restoreMapsAsObject) {
343
+ currentDecoder.mapsAsObjects = true;
344
+ restoreMapsAsObject = false;
345
+ }
346
+ let map = new Map();
347
+ if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read());
348
+ else for (let i = 0; i < token; i++) map.set(read(), read());
349
+ return map
350
+ }
351
+ case 6: // extension
352
+ if (token >= BUNDLED_STRINGS_ID) {
353
+ let structure = currentStructures[token & 0x1fff]; // check record structures first
354
+ // 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))
355
+ if (structure) {
356
+ if (!structure.read) structure.read = createStructureReader(structure);
357
+ return structure.read()
358
+ }
359
+ if (token < 0x10000) {
360
+ 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)
361
+ return recordDefinition(read())
362
+ else if (token == RECORD_DEFINITIONS_ID) {
363
+ let length = readJustLength();
364
+ let id = read();
365
+ for (let i = 2; i < length; i++) {
366
+ recordDefinition([id++, read()]);
367
+ }
368
+ return read()
369
+ } else if (token == BUNDLED_STRINGS_ID) {
370
+ return readBundleExt()
371
+ }
372
+ if (currentDecoder.getShared) {
373
+ loadShared();
374
+ structure = currentStructures[token & 0x1fff];
375
+ if (structure) {
376
+ if (!structure.read)
377
+ structure.read = createStructureReader(structure);
378
+ return structure.read()
379
+ }
380
+ }
381
+ }
382
+ }
383
+ let extension = currentExtensions[token];
384
+ if (extension) {
385
+ if (extension.handlesRead)
386
+ return extension(read)
387
+ else
388
+ return extension(read())
389
+ } else {
390
+ let input = read();
391
+ for (let i = 0; i < currentExtensionRanges.length; i++) {
392
+ let value = currentExtensionRanges[i](token, input);
393
+ if (value !== undefined)
394
+ return value
395
+ }
396
+ return new Tag(input, token)
397
+ }
398
+ case 7: // fixed value
399
+ switch (token) {
400
+ case 0x14: return false
401
+ case 0x15: return true
402
+ case 0x16: return null
403
+ case 0x17: return; // undefined
404
+ case 0x1f:
405
+ default:
406
+ let packedValue = (packedValues || getPackedValues())[token];
407
+ if (packedValue !== undefined)
408
+ return packedValue
409
+ throw new Error('Unknown token ' + token)
410
+ }
411
+ default: // negative int
412
+ if (isNaN(token)) {
413
+ let error = new Error('Unexpected end of CBOR data');
414
+ error.incomplete = true;
415
+ throw error
416
+ }
417
+ throw new Error('Unknown CBOR token ' + token)
418
+ }
419
+ }
420
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
421
+ function createStructureReader(structure) {
422
+ function readObject() {
423
+ // get the array size from the header
424
+ let length = src[position$1++];
425
+ //let majorType = token >> 5
426
+ length = length & 0x1f;
427
+ if (length > 0x17) {
428
+ switch (length) {
429
+ case 0x18:
430
+ length = src[position$1++];
431
+ break
432
+ case 0x19:
433
+ length = dataView.getUint16(position$1);
434
+ position$1 += 2;
435
+ break
436
+ case 0x1a:
437
+ length = dataView.getUint32(position$1);
438
+ position$1 += 4;
439
+ break
440
+ default:
441
+ throw new Error('Expected array header, but got ' + src[position$1 - 1])
442
+ }
443
+ }
444
+ // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
445
+ let compiledReader = this.compiledReader; // first look to see if we have the fast compiled function
446
+ while(compiledReader) {
447
+ // we have a fast compiled object literal reader
448
+ if (compiledReader.propertyCount === length)
449
+ return compiledReader(read) // with the right length, so we use it
450
+ compiledReader = compiledReader.next; // see if there is another reader with the right length
451
+ }
452
+ if (this.slowReads++ >= 3) { // create a fast compiled reader
453
+ let array = this.length == length ? this : this.slice(0, length);
454
+ compiledReader = currentDecoder.keyMap
455
+ ? new BlockedFunction ('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')
456
+ : new BlockedFunction ('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}');
457
+ if (this.compiledReader)
458
+ 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
459
+ compiledReader.propertyCount = length;
460
+ this.compiledReader = compiledReader;
461
+ return compiledReader(read)
462
+ }
463
+ let object = {};
464
+ if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read();
465
+ else for (let i = 0; i < length; i++) {
466
+ object[safeKey(this[i])] = read();
467
+ }
468
+ return object
469
+ }
470
+ structure.slowReads = 0;
471
+ return readObject
472
+ }
473
+
474
+ function safeKey(key) {
475
+ return key === '__proto__' ? '__proto_' : key
476
+ }
477
+
478
+ let readFixedString = readStringJS;
479
+
480
+ let isNativeAccelerationEnabled = false;
481
+ function readStringJS(length) {
482
+ let result;
483
+ if (length < 16) {
484
+ if (result = shortStringInJS(length))
485
+ return result
486
+ }
487
+ if (length > 64 && decoder)
488
+ return decoder.decode(src.subarray(position$1, position$1 += length))
489
+ const end = position$1 + length;
490
+ const units = [];
491
+ result = '';
492
+ while (position$1 < end) {
493
+ const byte1 = src[position$1++];
494
+ if ((byte1 & 0x80) === 0) {
495
+ // 1 byte
496
+ units.push(byte1);
497
+ } else if ((byte1 & 0xe0) === 0xc0) {
498
+ // 2 bytes
499
+ const byte2 = src[position$1++] & 0x3f;
500
+ units.push(((byte1 & 0x1f) << 6) | byte2);
501
+ } else if ((byte1 & 0xf0) === 0xe0) {
502
+ // 3 bytes
503
+ const byte2 = src[position$1++] & 0x3f;
504
+ const byte3 = src[position$1++] & 0x3f;
505
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
506
+ } else if ((byte1 & 0xf8) === 0xf0) {
507
+ // 4 bytes
508
+ const byte2 = src[position$1++] & 0x3f;
509
+ const byte3 = src[position$1++] & 0x3f;
510
+ const byte4 = src[position$1++] & 0x3f;
511
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
512
+ if (unit > 0xffff) {
513
+ unit -= 0x10000;
514
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
515
+ unit = 0xdc00 | (unit & 0x3ff);
516
+ }
517
+ units.push(unit);
518
+ } else {
519
+ units.push(byte1);
520
+ }
521
+
522
+ if (units.length >= 0x1000) {
523
+ result += fromCharCode.apply(String, units);
524
+ units.length = 0;
525
+ }
526
+ }
527
+
528
+ if (units.length > 0) {
529
+ result += fromCharCode.apply(String, units);
530
+ }
531
+
532
+ return result
533
+ }
534
+ let fromCharCode = String.fromCharCode;
535
+ function longStringInJS(length) {
536
+ let start = position$1;
537
+ let bytes = new Array(length);
538
+ for (let i = 0; i < length; i++) {
539
+ const byte = src[position$1++];
540
+ if ((byte & 0x80) > 0) {
541
+ position$1 = start;
542
+ return
543
+ }
544
+ bytes[i] = byte;
545
+ }
546
+ return fromCharCode.apply(String, bytes)
547
+ }
548
+ function shortStringInJS(length) {
549
+ if (length < 4) {
550
+ if (length < 2) {
551
+ if (length === 0)
552
+ return ''
553
+ else {
554
+ let a = src[position$1++];
555
+ if ((a & 0x80) > 1) {
556
+ position$1 -= 1;
557
+ return
558
+ }
559
+ return fromCharCode(a)
560
+ }
561
+ } else {
562
+ let a = src[position$1++];
563
+ let b = src[position$1++];
564
+ if ((a & 0x80) > 0 || (b & 0x80) > 0) {
565
+ position$1 -= 2;
566
+ return
567
+ }
568
+ if (length < 3)
569
+ return fromCharCode(a, b)
570
+ let c = src[position$1++];
571
+ if ((c & 0x80) > 0) {
572
+ position$1 -= 3;
573
+ return
574
+ }
575
+ return fromCharCode(a, b, c)
576
+ }
577
+ } else {
578
+ let a = src[position$1++];
579
+ let b = src[position$1++];
580
+ let c = src[position$1++];
581
+ let d = src[position$1++];
582
+ if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
583
+ position$1 -= 4;
584
+ return
585
+ }
586
+ if (length < 6) {
587
+ if (length === 4)
588
+ return fromCharCode(a, b, c, d)
589
+ else {
590
+ let e = src[position$1++];
591
+ if ((e & 0x80) > 0) {
592
+ position$1 -= 5;
593
+ return
594
+ }
595
+ return fromCharCode(a, b, c, d, e)
596
+ }
597
+ } else if (length < 8) {
598
+ let e = src[position$1++];
599
+ let f = src[position$1++];
600
+ if ((e & 0x80) > 0 || (f & 0x80) > 0) {
601
+ position$1 -= 6;
602
+ return
603
+ }
604
+ if (length < 7)
605
+ return fromCharCode(a, b, c, d, e, f)
606
+ let g = src[position$1++];
607
+ if ((g & 0x80) > 0) {
608
+ position$1 -= 7;
609
+ return
610
+ }
611
+ return fromCharCode(a, b, c, d, e, f, g)
612
+ } else {
613
+ let e = src[position$1++];
614
+ let f = src[position$1++];
615
+ let g = src[position$1++];
616
+ let h = src[position$1++];
617
+ if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
618
+ position$1 -= 8;
619
+ return
620
+ }
621
+ if (length < 10) {
622
+ if (length === 8)
623
+ return fromCharCode(a, b, c, d, e, f, g, h)
624
+ else {
625
+ let i = src[position$1++];
626
+ if ((i & 0x80) > 0) {
627
+ position$1 -= 9;
628
+ return
629
+ }
630
+ return fromCharCode(a, b, c, d, e, f, g, h, i)
631
+ }
632
+ } else if (length < 12) {
633
+ let i = src[position$1++];
634
+ let j = src[position$1++];
635
+ if ((i & 0x80) > 0 || (j & 0x80) > 0) {
636
+ position$1 -= 10;
637
+ return
638
+ }
639
+ if (length < 11)
640
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j)
641
+ let k = src[position$1++];
642
+ if ((k & 0x80) > 0) {
643
+ position$1 -= 11;
644
+ return
645
+ }
646
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
647
+ } else {
648
+ let i = src[position$1++];
649
+ let j = src[position$1++];
650
+ let k = src[position$1++];
651
+ let l = src[position$1++];
652
+ if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
653
+ position$1 -= 12;
654
+ return
655
+ }
656
+ if (length < 14) {
657
+ if (length === 12)
658
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
659
+ else {
660
+ let m = src[position$1++];
661
+ if ((m & 0x80) > 0) {
662
+ position$1 -= 13;
663
+ return
664
+ }
665
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
666
+ }
667
+ } else {
668
+ let m = src[position$1++];
669
+ let n = src[position$1++];
670
+ if ((m & 0x80) > 0 || (n & 0x80) > 0) {
671
+ position$1 -= 14;
672
+ return
673
+ }
674
+ if (length < 15)
675
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
676
+ let o = src[position$1++];
677
+ if ((o & 0x80) > 0) {
678
+ position$1 -= 15;
679
+ return
680
+ }
681
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
682
+ }
683
+ }
684
+ }
685
+ }
686
+ }
687
+
688
+ function readBin(length) {
689
+ return currentDecoder.copyBuffers ?
690
+ // specifically use the copying slice (not the node one)
691
+ Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
692
+ src.subarray(position$1, position$1 += length)
693
+ }
694
+ let f32Array = new Float32Array(1);
695
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
696
+ function getFloat16() {
697
+ let byte0 = src[position$1++];
698
+ let byte1 = src[position$1++];
699
+ let exponent = (byte0 & 0x7f) >> 2;
700
+ if (exponent === 0x1f) { // specials
701
+ if (byte1 || (byte0 & 3))
702
+ return NaN;
703
+ return (byte0 & 0x80) ? -Infinity : Infinity;
704
+ }
705
+ if (exponent === 0) { // sub-normals
706
+ // significand with 10 fractional bits and divided by 2^14
707
+ let abs = (((byte0 & 3) << 8) | byte1) / (1 << 24);
708
+ return (byte0 & 0x80) ? -abs : abs
709
+ }
710
+
711
+ u8Array[3] = (byte0 & 0x80) | // sign bit
712
+ ((exponent >> 1) + 56); // 4 of 5 of the exponent bits, re-offset-ed
713
+ u8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits
714
+ (byte1 >> 3); // next 5 bits of mantissa
715
+ u8Array[1] = byte1 << 5; // last three bits of mantissa
716
+ u8Array[0] = 0;
717
+ return f32Array[0];
718
+ }
719
+
720
+ new Array(4096);
721
+
722
+ class Tag {
723
+ constructor(value, tag) {
724
+ this.value = value;
725
+ this.tag = tag;
726
+ }
727
+ }
728
+
729
+ currentExtensions[0] = (dateString) => {
730
+ // string date extension
731
+ return new Date(dateString)
732
+ };
733
+
734
+ currentExtensions[1] = (epochSec) => {
735
+ // numeric date extension
736
+ return new Date(Math.round(epochSec * 1000))
737
+ };
738
+
739
+ currentExtensions[2] = (buffer) => {
740
+ // bigint extension
741
+ let value = BigInt(0);
742
+ for (let i = 0, l = buffer.byteLength; i < l; i++) {
743
+ value = BigInt(buffer[i]) + value << BigInt(8);
744
+ }
745
+ return value
746
+ };
747
+
748
+ currentExtensions[3] = (buffer) => {
749
+ // negative bigint extension
750
+ return BigInt(-1) - currentExtensions[2](buffer)
751
+ };
752
+ currentExtensions[4] = (fraction) => {
753
+ // best to reparse to maintain accuracy
754
+ return +(fraction[1] + 'e' + fraction[0])
755
+ };
756
+
757
+ currentExtensions[5] = (fraction) => {
758
+ // probably not sufficiently accurate
759
+ return fraction[1] * Math.exp(fraction[0] * Math.log(2))
760
+ };
761
+
762
+ // the registration of the record definition extension
763
+ const recordDefinition = (definition) => {
764
+ let id = definition[0] - 0xe000;
765
+ let structure = definition[1];
766
+ let existingStructure = currentStructures[id];
767
+ if (existingStructure && existingStructure.isShared) {
768
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
769
+ }
770
+ currentStructures[id] = structure;
771
+
772
+ structure.read = createStructureReader(structure);
773
+ let object = {};
774
+ if (currentDecoder.keyMap) for (let i = 2,l = definition.length; i < l; i++) {
775
+ let key = currentDecoder.decodeKey(structure[i - 2]);
776
+ object[safeKey(key)] = definition[i];
777
+ }
778
+ else for (let i = 2,l = definition.length; i < l; i++) {
779
+ let key = structure[i - 2];
780
+ object[safeKey(key)] = definition[i];
781
+ }
782
+ return object
783
+ };
784
+ currentExtensions[LEGACY_RECORD_INLINE_ID] = recordDefinition;
785
+ currentExtensions[14] = (value) => {
786
+ if (bundledStrings$1)
787
+ return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value)
788
+ return new Tag(value, 14)
789
+ };
790
+ currentExtensions[15] = (value) => {
791
+ if (bundledStrings$1)
792
+ return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
793
+ return new Tag(value, 15)
794
+ };
795
+ let glbl = { Error, RegExp };
796
+ currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object
797
+ return (glbl[data[0]] || Error)(data[1], data[2])
798
+ };
799
+ const packedTable = (read) => {
800
+ if (src[position$1++] != 0x84)
801
+ throw new Error('Packed values structure must be followed by a 4 element array')
802
+ let newPackedValues = read(); // packed values
803
+ packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues;
804
+ packedValues.prefixes = read();
805
+ packedValues.suffixes = read();
806
+ return read() // read the rump
807
+ };
808
+ packedTable.handlesRead = true;
809
+ currentExtensions[51] = packedTable;
810
+
811
+ currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference
812
+ if (!packedValues) {
813
+ if (currentDecoder.getShared)
814
+ loadShared();
815
+ else
816
+ return new Tag(data, PACKED_REFERENCE_TAG_ID)
817
+ }
818
+ if (typeof data == 'number')
819
+ return packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]
820
+ throw new Error('No support for non-integer packed references yet')
821
+ };
822
+
823
+ // The following code is an incomplete implementation of http://cbor.schmorp.de/stringref
824
+ // the real thing would need to implemennt more logic to populate the stringRefs table and
825
+ // maintain a stack of stringRef "namespaces".
826
+ //
827
+ // currentExtensions[25] = (id) => {
828
+ // return stringRefs[id]
829
+ // }
830
+ // currentExtensions[256] = (read) => {
831
+ // stringRefs = []
832
+ // try {
833
+ // return read()
834
+ // } finally {
835
+ // stringRefs = null
836
+ // }
837
+ // }
838
+ // currentExtensions[256].handlesRead = true
839
+
840
+ currentExtensions[28] = (read) => {
841
+ // shareable http://cbor.schmorp.de/value-sharing (for structured clones)
842
+ if (!referenceMap) {
843
+ referenceMap = new Map();
844
+ referenceMap.id = 0;
845
+ }
846
+ let id = referenceMap.id++;
847
+ let token = src[position$1];
848
+ let target;
849
+ // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
850
+ // ahead past references to record structure definitions
851
+ if ((token >> 5) == 4)
852
+ target = [];
853
+ else
854
+ target = {};
855
+
856
+ let refEntry = { target }; // a placeholder object
857
+ referenceMap.set(id, refEntry);
858
+ let targetProperties = read(); // read the next value as the target object to id
859
+ if (refEntry.used) // there is a cycle, so we have to assign properties to original target
860
+ return Object.assign(target, targetProperties)
861
+ refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
862
+ return targetProperties // no cycle, can just use the returned read object
863
+ };
864
+ currentExtensions[28].handlesRead = true;
865
+
866
+ currentExtensions[29] = (id) => {
867
+ // sharedref http://cbor.schmorp.de/value-sharing (for structured clones)
868
+ let refEntry = referenceMap.get(id);
869
+ refEntry.used = true;
870
+ return refEntry.target
871
+ };
872
+
873
+ currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
874
+ (currentExtensions[259] = (read) => {
875
+ // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec
876
+ // for decoding as a standard Map
877
+ if (currentDecoder.mapsAsObjects) {
878
+ currentDecoder.mapsAsObjects = false;
879
+ restoreMapsAsObject = true;
880
+ }
881
+ return read()
882
+ }).handlesRead = true;
883
+ function combine(a, b) {
884
+ if (typeof a === 'string')
885
+ return a + b
886
+ if (a instanceof Array)
887
+ return a.concat(b)
888
+ return Object.assign({}, a, b)
889
+ }
890
+ function getPackedValues() {
891
+ if (!packedValues) {
892
+ if (currentDecoder.getShared)
893
+ loadShared();
894
+ else
895
+ throw new Error('No packed values available')
896
+ }
897
+ return packedValues
898
+ }
899
+ const SHARED_DATA_TAG_ID = 0x53687264; // ascii 'Shrd'
900
+ currentExtensionRanges.push((tag, input) => {
901
+ if (tag >= 225 && tag <= 255)
902
+ return combine(getPackedValues().prefixes[tag - 224], input)
903
+ if (tag >= 28704 && tag <= 32767)
904
+ return combine(getPackedValues().prefixes[tag - 28672], input)
905
+ if (tag >= 1879052288 && tag <= 2147483647)
906
+ return combine(getPackedValues().prefixes[tag - 1879048192], input)
907
+ if (tag >= 216 && tag <= 223)
908
+ return combine(input, getPackedValues().suffixes[tag - 216])
909
+ if (tag >= 27647 && tag <= 28671)
910
+ return combine(input, getPackedValues().suffixes[tag - 27639])
911
+ if (tag >= 1811940352 && tag <= 1879048191)
912
+ return combine(input, getPackedValues().suffixes[tag - 1811939328])
913
+ 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)
914
+ return {
915
+ packedValues: packedValues,
916
+ structures: currentStructures.slice(0),
917
+ version: input,
918
+ }
919
+ }
920
+ if (tag == 55799) // self-descriptive CBOR tag, just return input value
921
+ return input
922
+ });
923
+
924
+ const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
925
+ const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
926
+ typeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,
927
+ typeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array];
928
+ const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86];
929
+ for (let i = 0; i < typedArrays.length; i++) {
930
+ registerTypedArray(typedArrays[i], typedArrayTags[i]);
931
+ }
932
+ function registerTypedArray(TypedArray, tag) {
933
+ let dvMethod = 'get' + TypedArray.name.slice(0, -5);
934
+ if (typeof TypedArray !== 'function')
935
+ TypedArray = null;
936
+ let bytesPerElement = TypedArray.BYTES_PER_ELEMENT;
937
+ for (let littleEndian = 0; littleEndian < 2; littleEndian++) {
938
+ if (!littleEndian && bytesPerElement == 1)
939
+ continue
940
+ let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : 3;
941
+ currentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1) ? (buffer) => {
942
+ if (!TypedArray)
943
+ throw new Error('Could not find typed array for code ' + tag)
944
+ // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
945
+ return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)
946
+ } : buffer => {
947
+ if (!TypedArray)
948
+ throw new Error('Could not find typed array for code ' + tag)
949
+ let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
950
+ let elements = buffer.length >> sizeShift;
951
+ let ta = new TypedArray(elements);
952
+ let method = dv[dvMethod];
953
+ for (let i = 0; i < elements; i++) {
954
+ ta[i] = method.call(dv, i << sizeShift, littleEndian);
955
+ }
956
+ return ta
957
+ };
958
+ }
959
+ }
960
+
961
+ function readBundleExt() {
962
+ let length = readJustLength();
963
+ let bundlePosition = position$1 + read();
964
+ for (let i = 2; i < length; i++) {
965
+ // skip past bundles that were already read
966
+ let bundleLength = readJustLength(); // this will increment position, so must add to position afterwards
967
+ position$1 += bundleLength;
968
+ }
969
+ let dataPosition = position$1;
970
+ position$1 = bundlePosition;
971
+ bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())];
972
+ bundledStrings$1.position0 = 0;
973
+ bundledStrings$1.position1 = 0;
974
+ bundledStrings$1.postBundlePosition = position$1;
975
+ position$1 = dataPosition;
976
+ return read()
977
+ }
978
+
979
+ function readJustLength() {
980
+ let token = src[position$1++] & 0x1f;
981
+ if (token > 0x17) {
982
+ switch (token) {
983
+ case 0x18:
984
+ token = src[position$1++];
985
+ break
986
+ case 0x19:
987
+ token = dataView.getUint16(position$1);
988
+ position$1 += 2;
989
+ break
990
+ case 0x1a:
991
+ token = dataView.getUint32(position$1);
992
+ position$1 += 4;
993
+ break
994
+ }
995
+ }
996
+ return token
997
+ }
998
+
999
+ function loadShared() {
1000
+ if (currentDecoder.getShared) {
1001
+ let sharedData = saveState(() => {
1002
+ // save the state in case getShared modifies our buffer
1003
+ src = null;
1004
+ return currentDecoder.getShared()
1005
+ }) || {};
1006
+ let updatedStructures = sharedData.structures || [];
1007
+ currentDecoder.sharedVersion = sharedData.version;
1008
+ packedValues = currentDecoder.sharedValues = sharedData.packedValues;
1009
+ if (currentStructures === true)
1010
+ currentDecoder.structures = currentStructures = updatedStructures;
1011
+ else
1012
+ currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures));
1013
+ }
1014
+ }
1015
+
1016
+ function saveState(callback) {
1017
+ let savedSrcEnd = srcEnd;
1018
+ let savedPosition = position$1;
1019
+ let savedSrcStringStart = srcStringStart;
1020
+ let savedSrcStringEnd = srcStringEnd;
1021
+ let savedSrcString = srcString;
1022
+ let savedReferenceMap = referenceMap;
1023
+ let savedBundledStrings = bundledStrings$1;
1024
+
1025
+ // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1026
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1027
+ let savedStructures = currentStructures;
1028
+ let savedDecoder = currentDecoder;
1029
+ let savedSequentialMode = sequentialMode;
1030
+ let value = callback();
1031
+ srcEnd = savedSrcEnd;
1032
+ position$1 = savedPosition;
1033
+ srcStringStart = savedSrcStringStart;
1034
+ srcStringEnd = savedSrcStringEnd;
1035
+ srcString = savedSrcString;
1036
+ referenceMap = savedReferenceMap;
1037
+ bundledStrings$1 = savedBundledStrings;
1038
+ src = savedSrc;
1039
+ sequentialMode = savedSequentialMode;
1040
+ currentStructures = savedStructures;
1041
+ currentDecoder = savedDecoder;
1042
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1043
+ return value
1044
+ }
1045
+ function clearSource() {
1046
+ src = null;
1047
+ referenceMap = null;
1048
+ currentStructures = null;
1049
+ }
1050
+
1051
+ function addExtension$1(extension) {
1052
+ currentExtensions[extension.tag] = extension.decode;
1053
+ }
1054
+
1055
+ const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1056
+ for (let i = 0; i < 256; i++) {
1057
+ mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1058
+ }
1059
+ let defaultDecoder = new Decoder({ useRecords: false });
1060
+ const decode = defaultDecoder.decode;
1061
+ const decodeMultiple = defaultDecoder.decodeMultiple;
1062
+ const FLOAT32_OPTIONS = {
1063
+ NEVER: 0,
1064
+ ALWAYS: 1,
1065
+ DECIMAL_ROUND: 3,
1066
+ DECIMAL_FIT: 4
1067
+ };
1068
+ function roundFloat32(float32Number) {
1069
+ f32Array[0] = float32Number;
1070
+ let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1071
+ return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1072
+ }
1073
+
1074
+ let textEncoder;
1075
+ try {
1076
+ textEncoder = new TextEncoder();
1077
+ } catch (error) {}
1078
+ let extensions, extensionClasses;
1079
+ const hasNodeBuffer = typeof Buffer !== 'undefined';
1080
+ const ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array;
1081
+ const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1082
+ const BlobConstructor = typeof Blob === 'undefined' ? {} : Blob;
1083
+ const MAX_STRUCTURES = 0x100;
1084
+ const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1085
+ let throwOnIterable;
1086
+ let target;
1087
+ let targetView;
1088
+ let position = 0;
1089
+ let safeEnd;
1090
+ let bundledStrings = null;
1091
+ const MAX_BUNDLE_SIZE = 0xf000;
1092
+ const hasNonLatin = /[\u0080-\uFFFF]/;
1093
+ const RECORD_SYMBOL = Symbol('record-id');
1094
+ class Encoder extends Decoder {
1095
+ constructor(options) {
1096
+ super(options);
1097
+ this.offset = 0;
1098
+ let start;
1099
+ let sharedStructures;
1100
+ let hasSharedUpdate;
1101
+ let structures;
1102
+ let referenceMap;
1103
+ options = options || {};
1104
+ let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) {
1105
+ return target.utf8Write(string, position, maxBytes)
1106
+ } : (textEncoder && textEncoder.encodeInto) ?
1107
+ function(string, position) {
1108
+ return textEncoder.encodeInto(string, target.subarray(position)).written
1109
+ } : false;
1110
+
1111
+ let encoder = this;
1112
+ let hasSharedStructures = options.structures || options.saveStructures;
1113
+ let maxSharedStructures = options.maxSharedStructures;
1114
+ if (maxSharedStructures == null)
1115
+ maxSharedStructures = hasSharedStructures ? 128 : 0;
1116
+ if (maxSharedStructures > 8190)
1117
+ throw new Error('Maximum maxSharedStructure is 8190')
1118
+ let isSequential = options.sequential;
1119
+ if (isSequential) {
1120
+ maxSharedStructures = 0;
1121
+ }
1122
+ if (!this.structures)
1123
+ this.structures = [];
1124
+ if (this.saveStructures)
1125
+ this.saveShared = this.saveStructures;
1126
+ let samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues;
1127
+ let sharedPackedObjectMap;
1128
+ if (sharedValues) {
1129
+ sharedPackedObjectMap = Object.create(null);
1130
+ for (let i = 0, l = sharedValues.length; i < l; i++) {
1131
+ sharedPackedObjectMap[sharedValues[i]] = i;
1132
+ }
1133
+ }
1134
+ let recordIdsToRemove = [];
1135
+ let transitionsCount = 0;
1136
+ let serializationsSinceTransitionRebuild = 0;
1137
+
1138
+ this.mapEncode = function(value, encodeOptions) {
1139
+ // Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet)
1140
+ if (this._keyMap && !this._mapped) {
1141
+ //console.log('encoding ', value)
1142
+ switch (value.constructor.name) {
1143
+ case 'Array':
1144
+ value = value.map(r => this.encodeKeys(r));
1145
+ break
1146
+ //case 'Map':
1147
+ // value = this.encodeKeys(value)
1148
+ // break
1149
+ }
1150
+ //this._mapped = true
1151
+ }
1152
+ return this.encode(value, encodeOptions)
1153
+ };
1154
+
1155
+ this.encode = function(value, encodeOptions) {
1156
+ if (!target) {
1157
+ target = new ByteArrayAllocate(8192);
1158
+ targetView = new DataView(target.buffer, 0, 8192);
1159
+ position = 0;
1160
+ }
1161
+ safeEnd = target.length - 10;
1162
+ if (safeEnd - position < 0x800) {
1163
+ // don't start too close to the end,
1164
+ target = new ByteArrayAllocate(target.length);
1165
+ targetView = new DataView(target.buffer, 0, target.length);
1166
+ safeEnd = target.length - 10;
1167
+ position = 0;
1168
+ } else if (encodeOptions === REUSE_BUFFER_MODE)
1169
+ position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1170
+ start = position;
1171
+ if (encoder.useSelfDescribedHeader) {
1172
+ targetView.setUint32(position, 0xd9d9f700); // tag two byte, then self-descriptive tag
1173
+ position += 3;
1174
+ }
1175
+ referenceMap = encoder.structuredClone ? new Map() : null;
1176
+ if (encoder.bundleStrings && typeof value !== 'string') {
1177
+ bundledStrings = [];
1178
+ bundledStrings.size = Infinity; // force a new bundle start on first string
1179
+ } else
1180
+ bundledStrings = null;
1181
+
1182
+ sharedStructures = encoder.structures;
1183
+ if (sharedStructures) {
1184
+ if (sharedStructures.uninitialized) {
1185
+ let sharedData = encoder.getShared() || {};
1186
+ encoder.structures = sharedStructures = sharedData.structures || [];
1187
+ encoder.sharedVersion = sharedData.version;
1188
+ let sharedValues = encoder.sharedValues = sharedData.packedValues;
1189
+ if (sharedValues) {
1190
+ sharedPackedObjectMap = {};
1191
+ for (let i = 0, l = sharedValues.length; i < l; i++)
1192
+ sharedPackedObjectMap[sharedValues[i]] = i;
1193
+ }
1194
+ }
1195
+ let sharedStructuresLength = sharedStructures.length;
1196
+ if (sharedStructuresLength > maxSharedStructures && !isSequential)
1197
+ sharedStructuresLength = maxSharedStructures;
1198
+ if (!sharedStructures.transitions) {
1199
+ // rebuild our structure transitions
1200
+ sharedStructures.transitions = Object.create(null);
1201
+ for (let i = 0; i < sharedStructuresLength; i++) {
1202
+ let keys = sharedStructures[i];
1203
+ //console.log('shared struct keys:', keys)
1204
+ if (!keys)
1205
+ continue
1206
+ let nextTransition, transition = sharedStructures.transitions;
1207
+ for (let j = 0, l = keys.length; j < l; j++) {
1208
+ if (transition[RECORD_SYMBOL] === undefined)
1209
+ transition[RECORD_SYMBOL] = i;
1210
+ let key = keys[j];
1211
+ nextTransition = transition[key];
1212
+ if (!nextTransition) {
1213
+ nextTransition = transition[key] = Object.create(null);
1214
+ }
1215
+ transition = nextTransition;
1216
+ }
1217
+ transition[RECORD_SYMBOL] = i | 0x100000;
1218
+ }
1219
+ }
1220
+ if (!isSequential)
1221
+ sharedStructures.nextId = sharedStructuresLength;
1222
+ }
1223
+ if (hasSharedUpdate)
1224
+ hasSharedUpdate = false;
1225
+ structures = sharedStructures || [];
1226
+ packedObjectMap = sharedPackedObjectMap;
1227
+ if (options.pack) {
1228
+ let packedValues = new Map();
1229
+ packedValues.values = [];
1230
+ packedValues.encoder = encoder;
1231
+ packedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity);
1232
+ packedValues.objectMap = sharedPackedObjectMap || false;
1233
+ packedValues.samplingPackedValues = samplingPackedValues;
1234
+ findRepetitiveStrings(value, packedValues);
1235
+ if (packedValues.values.length > 0) {
1236
+ target[position++] = 0xd8; // one-byte tag
1237
+ target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1238
+ writeArrayHeader(4);
1239
+ let valuesArray = packedValues.values;
1240
+ encode(valuesArray);
1241
+ writeArrayHeader(0); // prefixes
1242
+ writeArrayHeader(0); // suffixes
1243
+ packedObjectMap = Object.create(sharedPackedObjectMap || null);
1244
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
1245
+ packedObjectMap[valuesArray[i]] = i;
1246
+ }
1247
+ }
1248
+ }
1249
+ throwOnIterable = encodeOptions & THROW_ON_ITERABLE;
1250
+ try {
1251
+ if (throwOnIterable)
1252
+ return;
1253
+ encode(value);
1254
+ if (bundledStrings) {
1255
+ writeBundles(start, encode);
1256
+ }
1257
+ encoder.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1258
+ if (referenceMap && referenceMap.idsToInsert) {
1259
+ position += referenceMap.idsToInsert.length * 2;
1260
+ if (position > safeEnd)
1261
+ makeRoom(position);
1262
+ encoder.offset = position;
1263
+ let serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert);
1264
+ referenceMap = null;
1265
+ return serialized
1266
+ }
1267
+ if (encodeOptions & REUSE_BUFFER_MODE) {
1268
+ target.start = start;
1269
+ target.end = position;
1270
+ return target
1271
+ }
1272
+ return target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now
1273
+ } finally {
1274
+ if (sharedStructures) {
1275
+ if (serializationsSinceTransitionRebuild < 10)
1276
+ serializationsSinceTransitionRebuild++;
1277
+ if (sharedStructures.length > maxSharedStructures)
1278
+ sharedStructures.length = maxSharedStructures;
1279
+ if (transitionsCount > 10000) {
1280
+ // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1281
+ sharedStructures.transitions = null;
1282
+ serializationsSinceTransitionRebuild = 0;
1283
+ transitionsCount = 0;
1284
+ if (recordIdsToRemove.length > 0)
1285
+ recordIdsToRemove = [];
1286
+ } else if (recordIdsToRemove.length > 0 && !isSequential) {
1287
+ for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1288
+ recordIdsToRemove[i][RECORD_SYMBOL] = undefined;
1289
+ }
1290
+ recordIdsToRemove = [];
1291
+ //sharedStructures.nextId = maxSharedStructures
1292
+ }
1293
+ }
1294
+ if (hasSharedUpdate && encoder.saveShared) {
1295
+ if (encoder.structures.length > maxSharedStructures) {
1296
+ encoder.structures = encoder.structures.slice(0, maxSharedStructures);
1297
+ }
1298
+ // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1299
+ let returnBuffer = target.subarray(start, position);
1300
+ if (encoder.updateSharedData() === false)
1301
+ return encoder.encode(value) // re-encode if it fails
1302
+ return returnBuffer
1303
+ }
1304
+ if (encodeOptions & RESET_BUFFER_MODE)
1305
+ position = start;
1306
+ }
1307
+ };
1308
+ this.findCommonStringsToPack = () => {
1309
+ samplingPackedValues = new Map();
1310
+ if (!sharedPackedObjectMap)
1311
+ sharedPackedObjectMap = Object.create(null);
1312
+ return (options) => {
1313
+ let threshold = options && options.threshold || 4;
1314
+ let position = this.pack ? options.maxPrivatePackedValues || 16 : 0;
1315
+ if (!sharedValues)
1316
+ sharedValues = this.sharedValues = [];
1317
+ for (let [ key, status ] of samplingPackedValues) {
1318
+ if (status.count > threshold) {
1319
+ sharedPackedObjectMap[key] = position++;
1320
+ sharedValues.push(key);
1321
+ hasSharedUpdate = true;
1322
+ }
1323
+ }
1324
+ while (this.saveShared && this.updateSharedData() === false) {}
1325
+ samplingPackedValues = null;
1326
+ }
1327
+ };
1328
+ const encode = (value) => {
1329
+ if (position > safeEnd)
1330
+ target = makeRoom(position);
1331
+
1332
+ var type = typeof value;
1333
+ var length;
1334
+ if (type === 'string') {
1335
+ if (packedObjectMap) {
1336
+ let packedPosition = packedObjectMap[value];
1337
+ if (packedPosition >= 0) {
1338
+ if (packedPosition < 16)
1339
+ target[position++] = packedPosition + 0xe0; // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1340
+ else {
1341
+ target[position++] = 0xc6; // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
1342
+ if (packedPosition & 1)
1343
+ encode((15 - packedPosition) >> 1);
1344
+ else
1345
+ encode((packedPosition - 16) >> 1);
1346
+ }
1347
+ return
1348
+ /* } else if (packedStatus.serializationId != serializationId) {
1349
+ packedStatus.serializationId = serializationId
1350
+ packedStatus.count = 1
1351
+ if (options.sharedPack) {
1352
+ let sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1
1353
+ if (shareCount > (options.sharedPack.threshold || 5)) {
1354
+ let sharedPosition = packedStatus.position = packedStatus.nextSharedPosition
1355
+ hasSharedUpdate = true
1356
+ if (sharedPosition < 16)
1357
+ target[position++] = sharedPosition + 0xc0
1358
+
1359
+ }
1360
+ }
1361
+ } // else any in-doc incrementation?*/
1362
+ } else if (samplingPackedValues && !options.pack) {
1363
+ let status = samplingPackedValues.get(value);
1364
+ if (status)
1365
+ status.count++;
1366
+ else
1367
+ samplingPackedValues.set(value, {
1368
+ count: 1,
1369
+ });
1370
+ }
1371
+ }
1372
+ let strLength = value.length;
1373
+ if (bundledStrings && strLength >= 4 && strLength < 0x400) {
1374
+ if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1375
+ let extStart;
1376
+ let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1377
+ if (position + maxBytes > safeEnd)
1378
+ target = makeRoom(position + maxBytes);
1379
+ target[position++] = 0xd9; // tag 16-bit
1380
+ target[position++] = 0xdf; // tag 0xdff9
1381
+ target[position++] = 0xf9;
1382
+ // TODO: If we only have one bundle with any string data, only write one string bundle
1383
+ target[position++] = bundledStrings.position ? 0x84 : 0x82; // array of 4 or 2 elements depending on if we write bundles
1384
+ target[position++] = 0x1a; // 32-bit unsigned int
1385
+ extStart = position - start;
1386
+ position += 4; // reserve for writing bundle reference
1387
+ if (bundledStrings.position) {
1388
+ writeBundles(start, encode); // write the last bundles
1389
+ }
1390
+ bundledStrings = ['', '']; // create new ones
1391
+ bundledStrings.size = 0;
1392
+ bundledStrings.position = extStart;
1393
+ }
1394
+ let twoByte = hasNonLatin.test(value);
1395
+ bundledStrings[twoByte ? 0 : 1] += value;
1396
+ target[position++] = twoByte ? 0xce : 0xcf;
1397
+ encode(strLength);
1398
+ return
1399
+ }
1400
+ let headerSize;
1401
+ // first we estimate the header size, so we can write to the correct location
1402
+ if (strLength < 0x20) {
1403
+ headerSize = 1;
1404
+ } else if (strLength < 0x100) {
1405
+ headerSize = 2;
1406
+ } else if (strLength < 0x10000) {
1407
+ headerSize = 3;
1408
+ } else {
1409
+ headerSize = 5;
1410
+ }
1411
+ let maxBytes = strLength * 3;
1412
+ if (position + maxBytes > safeEnd)
1413
+ target = makeRoom(position + maxBytes);
1414
+
1415
+ if (strLength < 0x40 || !encodeUtf8) {
1416
+ let i, c1, c2, strPosition = position + headerSize;
1417
+ for (i = 0; i < strLength; i++) {
1418
+ c1 = value.charCodeAt(i);
1419
+ if (c1 < 0x80) {
1420
+ target[strPosition++] = c1;
1421
+ } else if (c1 < 0x800) {
1422
+ target[strPosition++] = c1 >> 6 | 0xc0;
1423
+ target[strPosition++] = c1 & 0x3f | 0x80;
1424
+ } else if (
1425
+ (c1 & 0xfc00) === 0xd800 &&
1426
+ ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1427
+ ) {
1428
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1429
+ i++;
1430
+ target[strPosition++] = c1 >> 18 | 0xf0;
1431
+ target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1432
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1433
+ target[strPosition++] = c1 & 0x3f | 0x80;
1434
+ } else {
1435
+ target[strPosition++] = c1 >> 12 | 0xe0;
1436
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1437
+ target[strPosition++] = c1 & 0x3f | 0x80;
1438
+ }
1439
+ }
1440
+ length = strPosition - position - headerSize;
1441
+ } else {
1442
+ length = encodeUtf8(value, position + headerSize, maxBytes);
1443
+ }
1444
+
1445
+ if (length < 0x18) {
1446
+ target[position++] = 0x60 | length;
1447
+ } else if (length < 0x100) {
1448
+ if (headerSize < 2) {
1449
+ target.copyWithin(position + 2, position + 1, position + 1 + length);
1450
+ }
1451
+ target[position++] = 0x78;
1452
+ target[position++] = length;
1453
+ } else if (length < 0x10000) {
1454
+ if (headerSize < 3) {
1455
+ target.copyWithin(position + 3, position + 2, position + 2 + length);
1456
+ }
1457
+ target[position++] = 0x79;
1458
+ target[position++] = length >> 8;
1459
+ target[position++] = length & 0xff;
1460
+ } else {
1461
+ if (headerSize < 5) {
1462
+ target.copyWithin(position + 5, position + 3, position + 3 + length);
1463
+ }
1464
+ target[position++] = 0x7a;
1465
+ targetView.setUint32(position, length);
1466
+ position += 4;
1467
+ }
1468
+ position += length;
1469
+ } else if (type === 'number') {
1470
+ if (value >>> 0 === value) {// positive integer, 32-bit or less
1471
+ // positive uint
1472
+ if (value < 0x18) {
1473
+ target[position++] = value;
1474
+ } else if (value < 0x100) {
1475
+ target[position++] = 0x18;
1476
+ target[position++] = value;
1477
+ } else if (value < 0x10000) {
1478
+ target[position++] = 0x19;
1479
+ target[position++] = value >> 8;
1480
+ target[position++] = value & 0xff;
1481
+ } else {
1482
+ target[position++] = 0x1a;
1483
+ targetView.setUint32(position, value);
1484
+ position += 4;
1485
+ }
1486
+ } else if (value >> 0 === value) { // negative integer
1487
+ if (value >= -0x18) {
1488
+ target[position++] = 0x1f - value;
1489
+ } else if (value >= -0x100) {
1490
+ target[position++] = 0x38;
1491
+ target[position++] = ~value;
1492
+ } else if (value >= -0x10000) {
1493
+ target[position++] = 0x39;
1494
+ targetView.setUint16(position, ~value);
1495
+ position += 2;
1496
+ } else {
1497
+ target[position++] = 0x3a;
1498
+ targetView.setUint32(position, ~value);
1499
+ position += 4;
1500
+ }
1501
+ } else {
1502
+ let useFloat32;
1503
+ if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1504
+ target[position++] = 0xfa;
1505
+ targetView.setFloat32(position, value);
1506
+ let xShifted;
1507
+ if (useFloat32 < 4 ||
1508
+ // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1509
+ ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1510
+ position += 4;
1511
+ return
1512
+ } else
1513
+ position--; // move back into position for writing a double
1514
+ }
1515
+ target[position++] = 0xfb;
1516
+ targetView.setFloat64(position, value);
1517
+ position += 8;
1518
+ }
1519
+ } else if (type === 'object') {
1520
+ if (!value)
1521
+ target[position++] = 0xf6;
1522
+ else {
1523
+ if (referenceMap) {
1524
+ let referee = referenceMap.get(value);
1525
+ if (referee) {
1526
+ target[position++] = 0xd8;
1527
+ target[position++] = 29; // http://cbor.schmorp.de/value-sharing
1528
+ target[position++] = 0x19; // 16-bit uint
1529
+ if (!referee.references) {
1530
+ let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1531
+ referee.references = [];
1532
+ idsToInsert.push(referee);
1533
+ }
1534
+ referee.references.push(position - start);
1535
+ position += 2; // TODO: also support 32-bit
1536
+ return
1537
+ } else
1538
+ referenceMap.set(value, { offset: position - start });
1539
+ }
1540
+ let constructor = value.constructor;
1541
+ if (constructor === Object) {
1542
+ writeObject(value, true);
1543
+ } else if (constructor === Array) {
1544
+ length = value.length;
1545
+ if (length < 0x18) {
1546
+ target[position++] = 0x80 | length;
1547
+ } else {
1548
+ writeArrayHeader(length);
1549
+ }
1550
+ for (let i = 0; i < length; i++) {
1551
+ encode(value[i]);
1552
+ }
1553
+ } else if (constructor === Map) {
1554
+ if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {
1555
+ // use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way
1556
+ target[position++] = 0xd9;
1557
+ target[position++] = 1;
1558
+ target[position++] = 3;
1559
+ }
1560
+ length = value.size;
1561
+ if (length < 0x18) {
1562
+ target[position++] = 0xa0 | length;
1563
+ } else if (length < 0x100) {
1564
+ target[position++] = 0xb8;
1565
+ target[position++] = length;
1566
+ } else if (length < 0x10000) {
1567
+ target[position++] = 0xb9;
1568
+ target[position++] = length >> 8;
1569
+ target[position++] = length & 0xff;
1570
+ } else {
1571
+ target[position++] = 0xba;
1572
+ targetView.setUint32(position, length);
1573
+ position += 4;
1574
+ }
1575
+ if (encoder.keyMap) {
1576
+ for (let [ key, entryValue ] of value) {
1577
+ encode(encoder.encodeKey(key));
1578
+ encode(entryValue);
1579
+ }
1580
+ } else {
1581
+ for (let [ key, entryValue ] of value) {
1582
+ encode(key);
1583
+ encode(entryValue);
1584
+ }
1585
+ }
1586
+ } else {
1587
+ for (let i = 0, l = extensions.length; i < l; i++) {
1588
+ let extensionClass = extensionClasses[i];
1589
+ if (value instanceof extensionClass) {
1590
+ let extension = extensions[i];
1591
+ let tag = extension.tag;
1592
+ if (tag == undefined)
1593
+ tag = extension.getTag && extension.getTag.call(this, value);
1594
+ if (tag < 0x18) {
1595
+ target[position++] = 0xc0 | tag;
1596
+ } else if (tag < 0x100) {
1597
+ target[position++] = 0xd8;
1598
+ target[position++] = tag;
1599
+ } else if (tag < 0x10000) {
1600
+ target[position++] = 0xd9;
1601
+ target[position++] = tag >> 8;
1602
+ target[position++] = tag & 0xff;
1603
+ } else if (tag > -1) {
1604
+ target[position++] = 0xda;
1605
+ targetView.setUint32(position, tag);
1606
+ position += 4;
1607
+ } // else undefined, don't write tag
1608
+ extension.encode.call(this, value, encode, makeRoom);
1609
+ return
1610
+ }
1611
+ }
1612
+ if (value[Symbol.iterator]) {
1613
+ if (throwOnIterable) {
1614
+ let error = new Error('Iterable should be serialized as iterator');
1615
+ error.iteratorNotHandled = true;
1616
+ throw error;
1617
+ }
1618
+ target[position++] = 0x9f; // indefinite length array
1619
+ for (let entry of value) {
1620
+ encode(entry);
1621
+ }
1622
+ target[position++] = 0xff; // stop-code
1623
+ return
1624
+ }
1625
+ if (value[Symbol.asyncIterator] || constructor === BlobConstructor) {
1626
+ let error = new Error('Iterable/blob should be serialized as iterator');
1627
+ error.iteratorNotHandled = true;
1628
+ throw error;
1629
+ }
1630
+ // no extension found, write as object
1631
+ writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1632
+ }
1633
+ }
1634
+ } else if (type === 'boolean') {
1635
+ target[position++] = value ? 0xf5 : 0xf4;
1636
+ } else if (type === 'bigint') {
1637
+ if (value < (BigInt(1)<<BigInt(64)) && value >= 0) {
1638
+ // use an unsigned int as long as it fits
1639
+ target[position++] = 0x1b;
1640
+ targetView.setBigUint64(position, value);
1641
+ } else if (value > -(BigInt(1)<<BigInt(64)) && value < 0) {
1642
+ // if we can fit an unsigned int, use that
1643
+ target[position++] = 0x3b;
1644
+ targetView.setBigUint64(position, -value - BigInt(1));
1645
+ } else {
1646
+ // overflow
1647
+ if (this.largeBigIntToFloat) {
1648
+ target[position++] = 0xfb;
1649
+ targetView.setFloat64(position, Number(value));
1650
+ } else {
1651
+ throw new RangeError(value + ' was too large to fit in CBOR 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1652
+ }
1653
+ }
1654
+ position += 8;
1655
+ } else if (type === 'undefined') {
1656
+ target[position++] = 0xf7;
1657
+ } else {
1658
+ throw new Error('Unknown type: ' + type)
1659
+ }
1660
+ };
1661
+
1662
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1663
+ // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1664
+ let keys = Object.keys(object);
1665
+ let vals = Object.values(object);
1666
+ let length = keys.length;
1667
+ if (length < 0x18) {
1668
+ target[position++] = 0xa0 | length;
1669
+ } else if (length < 0x100) {
1670
+ target[position++] = 0xb8;
1671
+ target[position++] = length;
1672
+ } else if (length < 0x10000) {
1673
+ target[position++] = 0xb9;
1674
+ target[position++] = length >> 8;
1675
+ target[position++] = length & 0xff;
1676
+ } else {
1677
+ target[position++] = 0xba;
1678
+ targetView.setUint32(position, length);
1679
+ position += 4;
1680
+ }
1681
+ if (encoder.keyMap) {
1682
+ for (let i = 0; i < length; i++) {
1683
+ encode(encodeKey(keys[i]));
1684
+ encode(vals[i]);
1685
+ }
1686
+ } else {
1687
+ for (let i = 0; i < length; i++) {
1688
+ encode(keys[i]);
1689
+ encode(vals[i]);
1690
+ }
1691
+ }
1692
+ } :
1693
+ (object, safePrototype) => {
1694
+ target[position++] = 0xb9; // always use map 16, so we can preallocate and set the length afterwards
1695
+ let objectOffset = position - start;
1696
+ position += 2;
1697
+ let size = 0;
1698
+ if (encoder.keyMap) {
1699
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1700
+ encode(encoder.encodeKey(key));
1701
+ encode(object[key]);
1702
+ size++;
1703
+ }
1704
+ } else {
1705
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1706
+ encode(key);
1707
+ encode(object[key]);
1708
+ size++;
1709
+ }
1710
+ }
1711
+ target[objectOffset++ + start] = size >> 8;
1712
+ target[objectOffset + start] = size & 0xff;
1713
+ } :
1714
+ (object, safePrototype) => {
1715
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1716
+ let newTransitions = 0;
1717
+ let length = 0;
1718
+ let parentRecordId;
1719
+ let keys;
1720
+ if (this.keyMap) {
1721
+ keys = Object.keys(object).map(k => this.encodeKey(k));
1722
+ length = keys.length;
1723
+ for (let i = 0; i < length; i++) {
1724
+ let key = keys[i];
1725
+ nextTransition = transition[key];
1726
+ if (!nextTransition) {
1727
+ nextTransition = transition[key] = Object.create(null);
1728
+ newTransitions++;
1729
+ }
1730
+ transition = nextTransition;
1731
+ }
1732
+ } else {
1733
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1734
+ nextTransition = transition[key];
1735
+ if (!nextTransition) {
1736
+ if (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it
1737
+ parentRecordId = transition[RECORD_SYMBOL] & 0xffff;
1738
+ }
1739
+ nextTransition = transition[key] = Object.create(null);
1740
+ newTransitions++;
1741
+ }
1742
+ transition = nextTransition;
1743
+ length++;
1744
+ }
1745
+ }
1746
+ let recordId = transition[RECORD_SYMBOL];
1747
+ if (recordId !== undefined) {
1748
+ recordId &= 0xffff;
1749
+ target[position++] = 0xd9;
1750
+ target[position++] = (recordId >> 8) | 0xe0;
1751
+ target[position++] = recordId & 0xff;
1752
+ } else {
1753
+ if (!keys)
1754
+ keys = transition.__keys__ || (transition.__keys__ = Object.keys(object));
1755
+ if (parentRecordId === undefined) {
1756
+ recordId = structures.nextId++;
1757
+ if (!recordId) {
1758
+ recordId = 0;
1759
+ structures.nextId = 1;
1760
+ }
1761
+ if (recordId >= MAX_STRUCTURES) {// cycle back around
1762
+ structures.nextId = (recordId = maxSharedStructures) + 1;
1763
+ }
1764
+ } else {
1765
+ recordId = parentRecordId;
1766
+ }
1767
+ structures[recordId] = keys;
1768
+ if (recordId < maxSharedStructures) {
1769
+ target[position++] = 0xd9;
1770
+ target[position++] = (recordId >> 8) | 0xe0;
1771
+ target[position++] = recordId & 0xff;
1772
+ transition = structures.transitions;
1773
+ for (let i = 0; i < length; i++) {
1774
+ if (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000))
1775
+ transition[RECORD_SYMBOL] = recordId;
1776
+ transition = transition[keys[i]];
1777
+ }
1778
+ transition[RECORD_SYMBOL] = recordId | 0x100000; // indicates it is a extendable terminal
1779
+ hasSharedUpdate = true;
1780
+ } else {
1781
+ transition[RECORD_SYMBOL] = recordId;
1782
+ targetView.setUint32(position, 0xd9dfff00); // tag two byte, then record definition id
1783
+ position += 3;
1784
+ if (newTransitions)
1785
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1786
+ // record the removal of the id, we can maintain our shared structure
1787
+ if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)
1788
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = undefined; // we are cycling back through, and have to remove old ones
1789
+ recordIdsToRemove.push(transition);
1790
+ writeArrayHeader(length + 2);
1791
+ encode(0xe000 + recordId);
1792
+ encode(keys);
1793
+ if (safePrototype === null) return; // special exit for iterator
1794
+ for (let key in object)
1795
+ if (safePrototype || object.hasOwnProperty(key))
1796
+ encode(object[key]);
1797
+ return
1798
+ }
1799
+ }
1800
+ if (length < 0x18) { // write the array header
1801
+ target[position++] = 0x80 | length;
1802
+ } else {
1803
+ writeArrayHeader(length);
1804
+ }
1805
+ if (safePrototype === null) return; // special exit for iterator
1806
+ for (let key in object)
1807
+ if (safePrototype || object.hasOwnProperty(key))
1808
+ encode(object[key]);
1809
+ };
1810
+ const makeRoom = (end) => {
1811
+ let newSize;
1812
+ if (end > 0x1000000) {
1813
+ // special handling for really large buffers
1814
+ if ((end - start) > MAX_BUFFER_SIZE)
1815
+ throw new Error('Encoded buffer would be larger than maximum buffer size')
1816
+ newSize = Math.min(MAX_BUFFER_SIZE,
1817
+ Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1818
+ } else // faster handling for smaller buffers
1819
+ newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1820
+ let newBuffer = new ByteArrayAllocate(newSize);
1821
+ targetView = new DataView(newBuffer.buffer, 0, newSize);
1822
+ if (target.copy)
1823
+ target.copy(newBuffer, 0, start, end);
1824
+ else
1825
+ newBuffer.set(target.slice(start, end));
1826
+ position -= start;
1827
+ start = 0;
1828
+ safeEnd = newBuffer.length - 10;
1829
+ return target = newBuffer
1830
+ };
1831
+ let chunkThreshold = 100;
1832
+ let continuedChunkThreshold = 1000;
1833
+ this.encodeAsIterable = function(value, options) {
1834
+ return startEncoding(value, options, encodeObjectAsIterable);
1835
+ };
1836
+ this.encodeAsAsyncIterable = function(value, options) {
1837
+ return startEncoding(value, options, encodeObjectAsAsyncIterable);
1838
+ };
1839
+
1840
+ function* encodeObjectAsIterable(object, iterateProperties, finalIterable) {
1841
+ let constructor = object.constructor;
1842
+ if (constructor === Object) {
1843
+ let useRecords = encoder.useRecords !== false;
1844
+ if (useRecords)
1845
+ writeObject(object, null); // write the record identifier
1846
+ else
1847
+ writeEntityLength(Object.keys(object).length, 0xa0);
1848
+ for (let key in object) {
1849
+ let value = object[key];
1850
+ if (!useRecords) encode(key);
1851
+ if (value && typeof value === 'object') {
1852
+ if (iterateProperties[key])
1853
+ yield* encodeObjectAsIterable(value, iterateProperties[key]);
1854
+ else
1855
+ yield* tryEncode(value, iterateProperties, key);
1856
+ } else encode(value);
1857
+ }
1858
+ } else if (constructor === Array) {
1859
+ writeArrayHeader(object.length);
1860
+ for (let i = 0; i < length; i++) {
1861
+ let value = object[i];
1862
+ if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
1863
+ if (iterateProperties.element)
1864
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1865
+ else
1866
+ yield* tryEncode(value, iterateProperties, 'element');
1867
+ } else encode(value);
1868
+ }
1869
+ } else if (object[Symbol.iterator]) {
1870
+ target[position++] = 0x9f; // start indefinite array
1871
+ for (let value of object) {
1872
+ if (value && (typeof value === 'object' || position - start > chunkThreshold)) {
1873
+ if (iterateProperties.element)
1874
+ yield* encodeObjectAsIterable(value, iterateProperties.element);
1875
+ else
1876
+ yield* tryEncode(value, iterateProperties, 'element');
1877
+ } else encode(value);
1878
+ }
1879
+ target[position++] = 0xff; // stop byte
1880
+ } else if (constructor === BlobConstructor){
1881
+ writeEntityLength(object.size, 0x40); // encode as binary data
1882
+ yield target.subarray(start, position);
1883
+ yield object; // directly return blobs, they have to be encoded asynchronously
1884
+ restartEncoding();
1885
+ } else if (object[Symbol.asyncIterator]) {
1886
+ target[position++] = 0x9f; // start indefinite array
1887
+ yield target.subarray(start, position);
1888
+ yield object; // directly return async iterators, they have to be encoded asynchronously
1889
+ restartEncoding();
1890
+ target[position++] = 0xff; // stop byte
1891
+ } else {
1892
+ encode(object);
1893
+ }
1894
+ if (finalIterable && position > start) yield target.subarray(start, position);
1895
+ else if (position - start > chunkThreshold) {
1896
+ yield target.subarray(start, position);
1897
+ restartEncoding();
1898
+ }
1899
+ }
1900
+ function* tryEncode(value, iterateProperties, key) {
1901
+ let restart = position - start;
1902
+ try {
1903
+ encode(value);
1904
+ if (position - start > chunkThreshold) {
1905
+ yield target.subarray(start, position);
1906
+ restartEncoding();
1907
+ }
1908
+ } catch (error) {
1909
+ if (error.iteratorNotHandled) {
1910
+ iterateProperties[key] = {};
1911
+ position = start + restart; // restart our position so we don't have partial data from last encode
1912
+ yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);
1913
+ } else throw error;
1914
+ }
1915
+ }
1916
+ function restartEncoding() {
1917
+ chunkThreshold = continuedChunkThreshold;
1918
+ encoder.encode(null, THROW_ON_ITERABLE); // restart encoding
1919
+ }
1920
+ function startEncoding(value, options, encodeIterable) {
1921
+ if (options && options.chunkThreshold) // explicitly specified chunk sizes
1922
+ chunkThreshold = continuedChunkThreshold = options.chunkThreshold;
1923
+ else // we start with a smaller threshold to get initial bytes sent quickly
1924
+ chunkThreshold = 100;
1925
+ if (value && typeof value === 'object') {
1926
+ encoder.encode(null, THROW_ON_ITERABLE); // start encoding
1927
+ return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);
1928
+ }
1929
+ return [encoder.encode(value)];
1930
+ }
1931
+
1932
+ async function* encodeObjectAsAsyncIterable(value, iterateProperties) {
1933
+ for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {
1934
+ let constructor = encodedValue.constructor;
1935
+ if (constructor === ByteArray || constructor === Uint8Array)
1936
+ yield encodedValue;
1937
+ else if (constructor === BlobConstructor) {
1938
+ let reader = encodedValue.stream().getReader();
1939
+ let next;
1940
+ while (!(next = await reader.read()).done) {
1941
+ yield next.value;
1942
+ }
1943
+ } else if (encodedValue[Symbol.asyncIterator]) {
1944
+ for await (let asyncValue of encodedValue) {
1945
+ restartEncoding();
1946
+ if (asyncValue)
1947
+ yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));
1948
+ else yield encoder.encode(asyncValue);
1949
+ }
1950
+ } else {
1951
+ yield encodedValue;
1952
+ }
1953
+ }
1954
+ }
1955
+ }
1956
+ useBuffer(buffer) {
1957
+ // this means we are finished using our own buffer and we can write over it safely
1958
+ target = buffer;
1959
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1960
+ position = 0;
1961
+ }
1962
+ clearSharedData() {
1963
+ if (this.structures)
1964
+ this.structures = [];
1965
+ if (this.sharedValues)
1966
+ this.sharedValues = undefined;
1967
+ }
1968
+ updateSharedData() {
1969
+ let lastVersion = this.sharedVersion || 0;
1970
+ this.sharedVersion = lastVersion + 1;
1971
+ let structuresCopy = this.structures.slice(0);
1972
+ let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion);
1973
+ let saveResults = this.saveShared(sharedData,
1974
+ existingShared => (existingShared && existingShared.version || 0) == lastVersion);
1975
+ if (saveResults === false) {
1976
+ // get updated structures and try again if the update failed
1977
+ sharedData = this.getShared() || {};
1978
+ this.structures = sharedData.structures || [];
1979
+ this.sharedValues = sharedData.packedValues;
1980
+ this.sharedVersion = sharedData.version;
1981
+ this.structures.nextId = this.structures.length;
1982
+ } else {
1983
+ // restore structures
1984
+ structuresCopy.forEach((structure, i) => this.structures[i] = structure);
1985
+ }
1986
+ // saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data
1987
+ return saveResults
1988
+ }
1989
+ }
1990
+ function writeEntityLength(length, majorValue) {
1991
+ if (length < 0x18)
1992
+ target[position++] = majorValue | length;
1993
+ else if (length < 0x100) {
1994
+ target[position++] = majorValue | 0x18;
1995
+ target[position++] = length;
1996
+ } else if (length < 0x10000) {
1997
+ target[position++] = majorValue | 0x19;
1998
+ target[position++] = length >> 8;
1999
+ target[position++] = length & 0xff;
2000
+ } else {
2001
+ target[position++] = majorValue | 0x1a;
2002
+ targetView.setUint32(position, length);
2003
+ position += 4;
2004
+ }
2005
+
2006
+ }
2007
+ class SharedData {
2008
+ constructor(structures, values, version) {
2009
+ this.structures = structures;
2010
+ this.packedValues = values;
2011
+ this.version = version;
2012
+ }
2013
+ }
2014
+
2015
+ function writeArrayHeader(length) {
2016
+ if (length < 0x18)
2017
+ target[position++] = 0x80 | length;
2018
+ else if (length < 0x100) {
2019
+ target[position++] = 0x98;
2020
+ target[position++] = length;
2021
+ } else if (length < 0x10000) {
2022
+ target[position++] = 0x99;
2023
+ target[position++] = length >> 8;
2024
+ target[position++] = length & 0xff;
2025
+ } else {
2026
+ target[position++] = 0x9a;
2027
+ targetView.setUint32(position, length);
2028
+ position += 4;
2029
+ }
2030
+ }
2031
+
2032
+ function findRepetitiveStrings(value, packedValues) {
2033
+ switch(typeof value) {
2034
+ case 'string':
2035
+ if (value.length > 3) {
2036
+ if (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues)
2037
+ return
2038
+ let packedStatus = packedValues.get(value);
2039
+ if (packedStatus) {
2040
+ if (++packedStatus.count == 2) {
2041
+ packedValues.values.push(value);
2042
+ }
2043
+ } else {
2044
+ packedValues.set(value, {
2045
+ count: 1,
2046
+ });
2047
+ if (packedValues.samplingPackedValues) {
2048
+ let status = packedValues.samplingPackedValues.get(value);
2049
+ if (status)
2050
+ status.count++;
2051
+ else
2052
+ packedValues.samplingPackedValues.set(value, {
2053
+ count: 1,
2054
+ });
2055
+ }
2056
+ }
2057
+ }
2058
+ break
2059
+ case 'object':
2060
+ if (value) {
2061
+ if (value instanceof Array) {
2062
+ for (let i = 0, l = value.length; i < l; i++) {
2063
+ findRepetitiveStrings(value[i], packedValues);
2064
+ }
2065
+
2066
+ } else {
2067
+ let includeKeys = !packedValues.encoder.useRecords;
2068
+ for (var key in value) {
2069
+ if (value.hasOwnProperty(key)) {
2070
+ if (includeKeys)
2071
+ findRepetitiveStrings(key, packedValues);
2072
+ findRepetitiveStrings(value[key], packedValues);
2073
+ }
2074
+ }
2075
+ }
2076
+ }
2077
+ break
2078
+ case 'function': console.log(value);
2079
+ }
2080
+ }
2081
+ const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
2082
+ extensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer,
2083
+ Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
2084
+ typeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array,
2085
+ typeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array,
2086
+ Float32Array, Float64Array, SharedData ];
2087
+
2088
+ //Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/
2089
+ extensions = [{ // Date
2090
+ tag: 1,
2091
+ encode(date, encode) {
2092
+ let seconds = date.getTime() / 1000;
2093
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
2094
+ // Timestamp 32
2095
+ target[position++] = 0x1a;
2096
+ targetView.setUint32(position, seconds);
2097
+ position += 4;
2098
+ } else {
2099
+ // Timestamp float64
2100
+ target[position++] = 0xfb;
2101
+ targetView.setFloat64(position, seconds);
2102
+ position += 8;
2103
+ }
2104
+ }
2105
+ }, { // Set
2106
+ tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md
2107
+ encode(set, encode) {
2108
+ let array = Array.from(set);
2109
+ encode(array);
2110
+ }
2111
+ }, { // Error
2112
+ tag: 27, // http://cbor.schmorp.de/generic-object
2113
+ encode(error, encode) {
2114
+ encode([ error.name, error.message ]);
2115
+ }
2116
+ }, { // RegExp
2117
+ tag: 27, // http://cbor.schmorp.de/generic-object
2118
+ encode(regex, encode) {
2119
+ encode([ 'RegExp', regex.source, regex.flags ]);
2120
+ }
2121
+ }, { // Tag
2122
+ getTag(tag) {
2123
+ return tag.tag
2124
+ },
2125
+ encode(tag, encode) {
2126
+ encode(tag.value);
2127
+ }
2128
+ }, { // ArrayBuffer
2129
+ encode(arrayBuffer, encode, makeRoom) {
2130
+ writeBuffer(arrayBuffer, makeRoom);
2131
+ }
2132
+ }, { // Uint8Array
2133
+ getTag(typedArray) {
2134
+ if (typedArray.constructor === Uint8Array) {
2135
+ if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)
2136
+ return 64;
2137
+ } // else no tag
2138
+ },
2139
+ encode(typedArray, encode, makeRoom) {
2140
+ writeBuffer(typedArray, makeRoom);
2141
+ }
2142
+ },
2143
+ typedArrayEncoder(68, 1),
2144
+ typedArrayEncoder(69, 2),
2145
+ typedArrayEncoder(70, 4),
2146
+ typedArrayEncoder(71, 8),
2147
+ typedArrayEncoder(72, 1),
2148
+ typedArrayEncoder(77, 2),
2149
+ typedArrayEncoder(78, 4),
2150
+ typedArrayEncoder(79, 8),
2151
+ typedArrayEncoder(85, 4),
2152
+ typedArrayEncoder(86, 8),
2153
+ {
2154
+ encode(sharedData, encode) { // write SharedData
2155
+ let packedValues = sharedData.packedValues || [];
2156
+ let sharedStructures = sharedData.structures || [];
2157
+ if (packedValues.values.length > 0) {
2158
+ target[position++] = 0xd8; // one-byte tag
2159
+ target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt
2160
+ writeArrayHeader(4);
2161
+ let valuesArray = packedValues.values;
2162
+ encode(valuesArray);
2163
+ writeArrayHeader(0); // prefixes
2164
+ writeArrayHeader(0); // suffixes
2165
+ packedObjectMap = Object.create(sharedPackedObjectMap || null);
2166
+ for (let i = 0, l = valuesArray.length; i < l; i++) {
2167
+ packedObjectMap[valuesArray[i]] = i;
2168
+ }
2169
+ }
2170
+ if (sharedStructures) {
2171
+ targetView.setUint32(position, 0xd9dffe00);
2172
+ position += 3;
2173
+ let definitions = sharedStructures.slice(0);
2174
+ definitions.unshift(0xe000);
2175
+ definitions.push(new Tag(sharedData.version, 0x53687264));
2176
+ encode(definitions);
2177
+ } else
2178
+ encode(new Tag(sharedData.version, 0x53687264));
2179
+ }
2180
+ }];
2181
+ function typedArrayEncoder(tag, size) {
2182
+ if (!isLittleEndianMachine && size > 1)
2183
+ tag -= 4; // the big endian equivalents are 4 less
2184
+ return {
2185
+ tag: tag,
2186
+ encode: function writeExtBuffer(typedArray, encode) {
2187
+ let length = typedArray.byteLength;
2188
+ let offset = typedArray.byteOffset || 0;
2189
+ let buffer = typedArray.buffer || typedArray;
2190
+ encode(hasNodeBuffer ? Buffer.from(buffer, offset, length) :
2191
+ new Uint8Array(buffer, offset, length));
2192
+ }
2193
+ }
2194
+ }
2195
+ function writeBuffer(buffer, makeRoom) {
2196
+ let length = buffer.byteLength;
2197
+ if (length < 0x18) {
2198
+ target[position++] = 0x40 + length;
2199
+ } else if (length < 0x100) {
2200
+ target[position++] = 0x58;
2201
+ target[position++] = length;
2202
+ } else if (length < 0x10000) {
2203
+ target[position++] = 0x59;
2204
+ target[position++] = length >> 8;
2205
+ target[position++] = length & 0xff;
2206
+ } else {
2207
+ target[position++] = 0x5a;
2208
+ targetView.setUint32(position, length);
2209
+ position += 4;
2210
+ }
2211
+ if (position + length >= target.length) {
2212
+ makeRoom(position + length);
2213
+ }
2214
+ // if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself,
2215
+ // must wrap it to set it.
2216
+ target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position);
2217
+ position += length;
2218
+ }
2219
+
2220
+ function insertIds(serialized, idsToInsert) {
2221
+ // insert the ids that need to be referenced for structured clones
2222
+ let nextId;
2223
+ let distanceToMove = idsToInsert.length * 2;
2224
+ let lastEnd = serialized.length - distanceToMove;
2225
+ idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
2226
+ for (let id = 0; id < idsToInsert.length; id++) {
2227
+ let referee = idsToInsert[id];
2228
+ referee.id = id;
2229
+ for (let position of referee.references) {
2230
+ serialized[position++] = id >> 8;
2231
+ serialized[position] = id & 0xff;
2232
+ }
2233
+ }
2234
+ while (nextId = idsToInsert.pop()) {
2235
+ let offset = nextId.offset;
2236
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2237
+ distanceToMove -= 2;
2238
+ let position = offset + distanceToMove;
2239
+ serialized[position++] = 0xd8;
2240
+ serialized[position++] = 28; // http://cbor.schmorp.de/value-sharing
2241
+ lastEnd = offset;
2242
+ }
2243
+ return serialized
2244
+ }
2245
+ function writeBundles(start, encode) {
2246
+ targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1); // the offset to bundle
2247
+ let writeStrings = bundledStrings;
2248
+ bundledStrings = null;
2249
+ encode(writeStrings[0]);
2250
+ encode(writeStrings[1]);
2251
+ }
2252
+
2253
+ function addExtension(extension) {
2254
+ if (extension.Class) {
2255
+ if (!extension.encode)
2256
+ throw new Error('Extension has no encode function')
2257
+ extensionClasses.unshift(extension.Class);
2258
+ extensions.unshift(extension);
2259
+ }
2260
+ addExtension$1(extension);
2261
+ }
2262
+ let defaultEncoder = new Encoder({ useRecords: false });
2263
+ const encode = defaultEncoder.encode;
2264
+ const encodeAsIterable = defaultEncoder.encodeAsIterable;
2265
+ const encodeAsAsyncIterable = defaultEncoder.encodeAsAsyncIterable;
2266
+ const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
2267
+ const REUSE_BUFFER_MODE = 512;
2268
+ const RESET_BUFFER_MODE = 1024;
2269
+ const THROW_ON_ITERABLE = 2048;
2270
+
2271
+ /**
2272
+ * Given an Iterable first argument, returns an Iterable where each value is encoded as a Buffer
2273
+ * If the argument is only Async Iterable, the return value will be an Async Iterable.
2274
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
2275
+ * @param {options} [options] - cbor-x Encoder options
2276
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
2277
+ */
2278
+ function encodeIter (objectIterator, options = {}) {
2279
+ if (!objectIterator || typeof objectIterator !== 'object') {
2280
+ throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
2281
+ } else if (typeof objectIterator[Symbol.iterator] === 'function') {
2282
+ return encodeIterSync(objectIterator, options)
2283
+ } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
2284
+ return encodeIterAsync(objectIterator, options)
2285
+ } else {
2286
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
2287
+ }
2288
+ }
2289
+
2290
+ function * encodeIterSync (objectIterator, options) {
2291
+ const encoder = new Encoder(options);
2292
+ for (const value of objectIterator) {
2293
+ yield encoder.encode(value);
2294
+ }
2295
+ }
2296
+
2297
+ async function * encodeIterAsync (objectIterator, options) {
2298
+ const encoder = new Encoder(options);
2299
+ for await (const value of objectIterator) {
2300
+ yield encoder.encode(value);
2301
+ }
2302
+ }
2303
+
2304
+ /**
2305
+ * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
2306
+ * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
2307
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
2308
+ * @param {object} [options] - Decoder options
2309
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator}
2310
+ */
2311
+ function decodeIter (bufferIterator, options = {}) {
2312
+ if (!bufferIterator || typeof bufferIterator !== 'object') {
2313
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
2314
+ }
2315
+
2316
+ const decoder = new Decoder(options);
2317
+ let incomplete;
2318
+ const parser = (chunk) => {
2319
+ let yields;
2320
+ // if there's incomplete data from previous chunk, concatinate and try again
2321
+ if (incomplete) {
2322
+ chunk = Buffer.concat([incomplete, chunk]);
2323
+ incomplete = undefined;
2324
+ }
2325
+
2326
+ try {
2327
+ yields = decoder.decodeMultiple(chunk);
2328
+ } catch (err) {
2329
+ if (err.incomplete) {
2330
+ incomplete = chunk.slice(err.lastPosition);
2331
+ yields = err.values;
2332
+ } else {
2333
+ throw err
2334
+ }
2335
+ }
2336
+ return yields
2337
+ };
2338
+
2339
+ if (typeof bufferIterator[Symbol.iterator] === 'function') {
2340
+ return (function * iter () {
2341
+ for (const value of bufferIterator) {
2342
+ yield * parser(value);
2343
+ }
2344
+ })()
2345
+ } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2346
+ return (async function * iter () {
2347
+ for await (const value of bufferIterator) {
2348
+ yield * parser(value);
2349
+ }
2350
+ })()
2351
+ }
2352
+ }
2353
+
2354
+ exports.ALWAYS = ALWAYS;
2355
+ exports.DECIMAL_FIT = DECIMAL_FIT;
2356
+ exports.DECIMAL_ROUND = DECIMAL_ROUND;
2357
+ exports.Decoder = Decoder;
2358
+ exports.Encoder = Encoder;
2359
+ exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
2360
+ exports.NEVER = NEVER;
2361
+ exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE;
2362
+ exports.Tag = Tag;
2363
+ exports.addExtension = addExtension;
2364
+ exports.clearSource = clearSource;
2365
+ exports.decode = decode;
2366
+ exports.decodeIter = decodeIter;
2367
+ exports.decodeMultiple = decodeMultiple;
2368
+ exports.encode = encode;
2369
+ exports.encodeAsAsyncIterable = encodeAsAsyncIterable;
2370
+ exports.encodeAsIterable = encodeAsIterable;
2371
+ exports.encodeIter = encodeIter;
2372
+ exports.isNativeAccelerationEnabled = isNativeAccelerationEnabled;
2373
+ exports.roundFloat32 = roundFloat32;
2374
+
2375
+ }));
2376
+ //# sourceMappingURL=index-no-eval.cjs.map