msgpackr 1.6.1 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,2015 +4,2034 @@
4
4
  (global = global || self, factory(global.msgpackr = {}));
5
5
  }(this, (function (exports) { 'use strict';
6
6
 
7
- var decoder;
8
- try {
9
- decoder = new TextDecoder();
10
- } catch(error) {}
11
- var src;
12
- var srcEnd;
13
- var position = 0;
14
- var currentUnpackr = {};
15
- var currentStructures;
16
- var srcString;
17
- var srcStringStart = 0;
18
- var srcStringEnd = 0;
19
- var bundledStrings;
20
- var referenceMap;
21
- var currentExtensions = [];
22
- var dataView;
23
- var defaultOptions = {
24
- useRecords: false,
25
- mapsAsObjects: true
26
- };
27
- class C1Type {}
28
- const C1 = new C1Type();
29
- C1.name = 'MessagePack 0xC1';
30
- var sequentialMode = false;
31
- var inlineObjectReadThreshold = 2;
32
- try {
33
- new Function('');
34
- } catch(error) {
35
- // if eval variants are not supported, do not create inline object readers ever
36
- inlineObjectReadThreshold = Infinity;
37
- }
38
-
39
- class Unpackr {
40
- constructor(options) {
41
- if (options) {
42
- if (options.useRecords === false && options.mapsAsObjects === undefined)
43
- options.mapsAsObjects = true;
44
- if (options.structures)
45
- options.structures.sharedLength = options.structures.length;
46
- else if (options.getStructures) {
47
- (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
48
- options.structures.sharedLength = 0;
49
- }
50
- }
51
- Object.assign(this, options);
52
- }
53
- unpack(source, end) {
54
- if (src) {
55
- // re-entrant execution, save the state and restore it after we do this unpack
56
- return saveState(() => {
57
- clearSource();
58
- return this ? this.unpack(source, end) : Unpackr.prototype.unpack.call(defaultOptions, source, end)
59
- })
60
- }
61
- srcEnd = end > -1 ? end : source.length;
62
- position = 0;
63
- srcStringEnd = 0;
64
- srcString = null;
65
- bundledStrings = null;
66
- src = source;
67
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
68
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
69
- // new ones
70
- try {
71
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
72
- } catch(error) {
73
- // if it doesn't have a buffer, maybe it is the wrong type of object
74
- src = null;
75
- if (source instanceof Uint8Array)
76
- throw error
77
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
78
- }
79
- if (this instanceof Unpackr) {
80
- currentUnpackr = this;
81
- if (this.structures) {
82
- currentStructures = this.structures;
83
- return checkedRead()
84
- } else if (!currentStructures || currentStructures.length > 0) {
85
- currentStructures = [];
86
- }
87
- } else {
88
- currentUnpackr = defaultOptions;
89
- if (!currentStructures || currentStructures.length > 0)
90
- currentStructures = [];
91
- }
92
- return checkedRead()
93
- }
94
- unpackMultiple(source, forEach) {
95
- let values, lastPosition = 0;
96
- try {
97
- sequentialMode = true;
98
- let size = source.length;
99
- let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
100
- if (forEach) {
101
- forEach(value);
102
- while(position < size) {
103
- lastPosition = position;
104
- if (forEach(checkedRead()) === false) {
105
- return
106
- }
107
- }
108
- }
109
- else {
110
- values = [ value ];
111
- while(position < size) {
112
- lastPosition = position;
113
- values.push(checkedRead());
114
- }
115
- return values
116
- }
117
- } catch(error) {
118
- error.lastPosition = lastPosition;
119
- error.values = values;
120
- throw error
121
- } finally {
122
- sequentialMode = false;
123
- clearSource();
124
- }
125
- }
126
- _mergeStructures(loadedStructures, existingStructures) {
127
- loadedStructures = loadedStructures || [];
128
- for (let i = 0, l = loadedStructures.length; i < l; i++) {
129
- let structure = loadedStructures[i];
130
- if (structure) {
131
- structure.isShared = true;
132
- if (i >= 32)
133
- structure.highByte = (i - 32) >> 5;
134
- }
135
- }
136
- loadedStructures.sharedLength = loadedStructures.length;
137
- for (let id in existingStructures || []) {
138
- if (id >= 0) {
139
- let structure = loadedStructures[id];
140
- let existing = existingStructures[id];
141
- if (existing) {
142
- if (structure)
143
- (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
144
- loadedStructures[id] = existing;
145
- }
146
- }
147
- }
148
- return this.structures = loadedStructures
149
- }
150
- decode(source, end) {
151
- return this.unpack(source, end)
152
- }
153
- }
154
- function checkedRead() {
155
- try {
156
- if (!currentUnpackr.trusted && !sequentialMode) {
157
- let sharedLength = currentStructures.sharedLength || 0;
158
- if (sharedLength < currentStructures.length)
159
- currentStructures.length = sharedLength;
160
- }
161
- let result = read();
162
- if (bundledStrings) // bundled strings to skip past
163
- position = bundledStrings.postBundlePosition;
164
-
165
- if (position == srcEnd) {
166
- // finished reading this source, cleanup references
167
- if (currentStructures.restoreStructures)
168
- restoreStructures();
169
- currentStructures = null;
170
- src = null;
171
- if (referenceMap)
172
- referenceMap = null;
173
- } else if (position > srcEnd) {
174
- // over read
175
- throw new Error('Unexpected end of MessagePack data')
176
- } else if (!sequentialMode) {
177
- throw new Error('Data read, but end of buffer not reached ' + JSON.stringify(result).slice(0, 100))
178
- }
179
- // else more to read, but we are reading sequentially, so don't clear source yet
180
- return result
181
- } catch(error) {
182
- if (currentStructures.restoreStructures)
183
- restoreStructures();
184
- clearSource();
185
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {
186
- error.incomplete = true;
187
- }
188
- throw error
189
- }
190
- }
191
-
192
- function restoreStructures() {
193
- for (let id in currentStructures.restoreStructures) {
194
- currentStructures[id] = currentStructures.restoreStructures[id];
195
- }
196
- currentStructures.restoreStructures = null;
197
- }
198
-
199
- function read() {
200
- let token = src[position++];
201
- if (token < 0xa0) {
202
- if (token < 0x80) {
203
- if (token < 0x40)
204
- return token
205
- else {
206
- let structure = currentStructures[token & 0x3f] ||
207
- currentUnpackr.getStructures && loadStructures()[token & 0x3f];
208
- if (structure) {
209
- if (!structure.read) {
210
- structure.read = createStructureReader(structure, token & 0x3f);
211
- }
212
- return structure.read()
213
- } else
214
- return token
215
- }
216
- } else if (token < 0x90) {
217
- // map
218
- token -= 0x80;
219
- if (currentUnpackr.mapsAsObjects) {
220
- let object = {};
221
- for (let i = 0; i < token; i++) {
222
- object[readKey()] = read();
223
- }
224
- return object
225
- } else {
226
- let map = new Map();
227
- for (let i = 0; i < token; i++) {
228
- map.set(read(), read());
229
- }
230
- return map
231
- }
232
- } else {
233
- token -= 0x90;
234
- let array = new Array(token);
235
- for (let i = 0; i < token; i++) {
236
- array[i] = read();
237
- }
238
- return array
239
- }
240
- } else if (token < 0xc0) {
241
- // fixstr
242
- let length = token - 0xa0;
243
- if (srcStringEnd >= position) {
244
- return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
245
- }
246
- if (srcStringEnd == 0 && srcEnd < 140) {
247
- // for small blocks, avoiding the overhead of the extract call is helpful
248
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
249
- if (string != null)
250
- return string
251
- }
252
- return readFixedString(length)
253
- } else {
254
- let value;
255
- switch (token) {
256
- case 0xc0: return null
257
- case 0xc1:
258
- if (bundledStrings) {
259
- value = read(); // followed by the length of the string in characters (not bytes!)
260
- if (value > 0)
261
- return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
262
- else
263
- return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)
264
- }
265
- return C1; // "never-used", return special object to denote that
266
- case 0xc2: return false
267
- case 0xc3: return true
268
- case 0xc4:
269
- // bin 8
270
- value = src[position++];
271
- if (value === undefined)
272
- throw new Error('Unexpected end of buffer')
273
- return readBin(value)
274
- case 0xc5:
275
- // bin 16
276
- value = dataView.getUint16(position);
277
- position += 2;
278
- return readBin(value)
279
- case 0xc6:
280
- // bin 32
281
- value = dataView.getUint32(position);
282
- position += 4;
283
- return readBin(value)
284
- case 0xc7:
285
- // ext 8
286
- return readExt(src[position++])
287
- case 0xc8:
288
- // ext 16
289
- value = dataView.getUint16(position);
290
- position += 2;
291
- return readExt(value)
292
- case 0xc9:
293
- // ext 32
294
- value = dataView.getUint32(position);
295
- position += 4;
296
- return readExt(value)
297
- case 0xca:
298
- value = dataView.getFloat32(position);
299
- if (currentUnpackr.useFloat32 > 2) {
300
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
301
- let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
302
- position += 4;
303
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
304
- }
305
- position += 4;
306
- return value
307
- case 0xcb:
308
- value = dataView.getFloat64(position);
309
- position += 8;
310
- return value
311
- // uint handlers
312
- case 0xcc:
313
- return src[position++]
314
- case 0xcd:
315
- value = dataView.getUint16(position);
316
- position += 2;
317
- return value
318
- case 0xce:
319
- value = dataView.getUint32(position);
320
- position += 4;
321
- return value
322
- case 0xcf:
323
- if (currentUnpackr.int64AsNumber) {
324
- value = dataView.getUint32(position) * 0x100000000;
325
- value += dataView.getUint32(position + 4);
326
- } else
327
- value = dataView.getBigUint64(position);
328
- position += 8;
329
- return value
330
-
331
- // int handlers
332
- case 0xd0:
333
- return dataView.getInt8(position++)
334
- case 0xd1:
335
- value = dataView.getInt16(position);
336
- position += 2;
337
- return value
338
- case 0xd2:
339
- value = dataView.getInt32(position);
340
- position += 4;
341
- return value
342
- case 0xd3:
343
- if (currentUnpackr.int64AsNumber) {
344
- value = dataView.getInt32(position) * 0x100000000;
345
- value += dataView.getUint32(position + 4);
346
- } else
347
- value = dataView.getBigInt64(position);
348
- position += 8;
349
- return value
350
-
351
- case 0xd4:
352
- // fixext 1
353
- value = src[position++];
354
- if (value == 0x72) {
355
- return recordDefinition(src[position++] & 0x3f)
356
- } else {
357
- let extension = currentExtensions[value];
358
- if (extension) {
359
- if (extension.read) {
360
- position++; // skip filler byte
361
- return extension.read(read())
362
- } else if (extension.noBuffer) {
363
- position++; // skip filler byte
364
- return extension()
365
- } else
366
- return extension(src.subarray(position, ++position))
367
- } else
368
- throw new Error('Unknown extension ' + value)
369
- }
370
- case 0xd5:
371
- // fixext 2
372
- value = src[position];
373
- if (value == 0x72) {
374
- position++;
375
- return recordDefinition(src[position++] & 0x3f, src[position++])
376
- } else
377
- return readExt(2)
378
- case 0xd6:
379
- // fixext 4
380
- return readExt(4)
381
- case 0xd7:
382
- // fixext 8
383
- return readExt(8)
384
- case 0xd8:
385
- // fixext 16
386
- return readExt(16)
387
- case 0xd9:
388
- // str 8
389
- value = src[position++];
390
- if (srcStringEnd >= position) {
391
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
392
- }
393
- return readString8(value)
394
- case 0xda:
395
- // str 16
396
- value = dataView.getUint16(position);
397
- position += 2;
398
- if (srcStringEnd >= position) {
399
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
400
- }
401
- return readString16(value)
402
- case 0xdb:
403
- // str 32
404
- value = dataView.getUint32(position);
405
- position += 4;
406
- if (srcStringEnd >= position) {
407
- return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
408
- }
409
- return readString32(value)
410
- case 0xdc:
411
- // array 16
412
- value = dataView.getUint16(position);
413
- position += 2;
414
- return readArray(value)
415
- case 0xdd:
416
- // array 32
417
- value = dataView.getUint32(position);
418
- position += 4;
419
- return readArray(value)
420
- case 0xde:
421
- // map 16
422
- value = dataView.getUint16(position);
423
- position += 2;
424
- return readMap(value)
425
- case 0xdf:
426
- // map 32
427
- value = dataView.getUint32(position);
428
- position += 4;
429
- return readMap(value)
430
- default: // negative int
431
- if (token >= 0xe0)
432
- return token - 0x100
433
- if (token === undefined) {
434
- let error = new Error('Unexpected end of MessagePack data');
435
- error.incomplete = true;
436
- throw error
437
- }
438
- throw new Error('Unknown MessagePack token ' + token)
439
-
440
- }
441
- }
442
- }
443
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
444
- function createStructureReader(structure, firstId) {
445
- function readObject() {
446
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
447
- if (readObject.count++ > inlineObjectReadThreshold) {
448
- let readObject = structure.read = (new Function('r', 'return function(){return {' + structure.map(key => validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}}'))(read);
449
- if (structure.highByte === 0)
450
- structure.read = createSecondByteReader(firstId, structure.read);
451
- return readObject() // second byte is already read, if there is one so immediately read object
452
- }
453
- let object = {};
454
- for (let i = 0, l = structure.length; i < l; i++) {
455
- let key = structure[i];
456
- object[key] = read();
457
- }
458
- return object
459
- }
460
- readObject.count = 0;
461
- if (structure.highByte === 0) {
462
- return createSecondByteReader(firstId, readObject)
463
- }
464
- return readObject
465
- }
466
-
467
- const createSecondByteReader = (firstId, read0) => {
468
- return function() {
469
- let highByte = src[position++];
470
- if (highByte === 0)
471
- return read0()
472
- let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
473
- let structure = currentStructures[id] || loadStructures()[id];
474
- if (!structure) {
475
- throw new Error('Record id is not defined for ' + id)
476
- }
477
- if (!structure.read)
478
- structure.read = createStructureReader(structure, firstId);
479
- return structure.read()
480
- }
481
- };
482
-
483
- function loadStructures() {
484
- let loadedStructures = saveState(() => {
485
- // save the state in case getStructures modifies our buffer
486
- src = null;
487
- return currentUnpackr.getStructures()
488
- });
489
- return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
490
- }
491
-
492
- var readFixedString = readStringJS;
493
- var readString8 = readStringJS;
494
- var readString16 = readStringJS;
495
- var readString32 = readStringJS;
496
- let isNativeAccelerationEnabled = false;
497
- function readStringJS(length) {
498
- let result;
499
- if (length < 16) {
500
- if (result = shortStringInJS(length))
501
- return result
502
- }
503
- if (length > 64 && decoder)
504
- return decoder.decode(src.subarray(position, position += length))
505
- const end = position + length;
506
- const units = [];
507
- result = '';
508
- while (position < end) {
509
- const byte1 = src[position++];
510
- if ((byte1 & 0x80) === 0) {
511
- // 1 byte
512
- units.push(byte1);
513
- } else if ((byte1 & 0xe0) === 0xc0) {
514
- // 2 bytes
515
- const byte2 = src[position++] & 0x3f;
516
- units.push(((byte1 & 0x1f) << 6) | byte2);
517
- } else if ((byte1 & 0xf0) === 0xe0) {
518
- // 3 bytes
519
- const byte2 = src[position++] & 0x3f;
520
- const byte3 = src[position++] & 0x3f;
521
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
522
- } else if ((byte1 & 0xf8) === 0xf0) {
523
- // 4 bytes
524
- const byte2 = src[position++] & 0x3f;
525
- const byte3 = src[position++] & 0x3f;
526
- const byte4 = src[position++] & 0x3f;
527
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
528
- if (unit > 0xffff) {
529
- unit -= 0x10000;
530
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
531
- unit = 0xdc00 | (unit & 0x3ff);
532
- }
533
- units.push(unit);
534
- } else {
535
- units.push(byte1);
536
- }
537
-
538
- if (units.length >= 0x1000) {
539
- result += fromCharCode.apply(String, units);
540
- units.length = 0;
541
- }
542
- }
543
-
544
- if (units.length > 0) {
545
- result += fromCharCode.apply(String, units);
546
- }
547
-
548
- return result
549
- }
550
-
551
- function readArray(length) {
552
- let array = new Array(length);
553
- for (let i = 0; i < length; i++) {
554
- array[i] = read();
555
- }
556
- return array
557
- }
558
-
559
- function readMap(length) {
560
- if (currentUnpackr.mapsAsObjects) {
561
- let object = {};
562
- for (let i = 0; i < length; i++) {
563
- object[readKey()] = read();
564
- }
565
- return object
566
- } else {
567
- let map = new Map();
568
- for (let i = 0; i < length; i++) {
569
- map.set(read(), read());
570
- }
571
- return map
572
- }
573
- }
574
-
575
- var fromCharCode = String.fromCharCode;
576
- function longStringInJS(length) {
577
- let start = position;
578
- let bytes = new Array(length);
579
- for (let i = 0; i < length; i++) {
580
- const byte = src[position++];
581
- if ((byte & 0x80) > 0) {
582
- position = start;
583
- return
584
- }
585
- bytes[i] = byte;
586
- }
587
- return fromCharCode.apply(String, bytes)
588
- }
589
- function shortStringInJS(length) {
590
- if (length < 4) {
591
- if (length < 2) {
592
- if (length === 0)
593
- return ''
594
- else {
595
- let a = src[position++];
596
- if ((a & 0x80) > 1) {
597
- position -= 1;
598
- return
599
- }
600
- return fromCharCode(a)
601
- }
602
- } else {
603
- let a = src[position++];
604
- let b = src[position++];
605
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
606
- position -= 2;
607
- return
608
- }
609
- if (length < 3)
610
- return fromCharCode(a, b)
611
- let c = src[position++];
612
- if ((c & 0x80) > 0) {
613
- position -= 3;
614
- return
615
- }
616
- return fromCharCode(a, b, c)
617
- }
618
- } else {
619
- let a = src[position++];
620
- let b = src[position++];
621
- let c = src[position++];
622
- let d = src[position++];
623
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
624
- position -= 4;
625
- return
626
- }
627
- if (length < 6) {
628
- if (length === 4)
629
- return fromCharCode(a, b, c, d)
630
- else {
631
- let e = src[position++];
632
- if ((e & 0x80) > 0) {
633
- position -= 5;
634
- return
635
- }
636
- return fromCharCode(a, b, c, d, e)
637
- }
638
- } else if (length < 8) {
639
- let e = src[position++];
640
- let f = src[position++];
641
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
642
- position -= 6;
643
- return
644
- }
645
- if (length < 7)
646
- return fromCharCode(a, b, c, d, e, f)
647
- let g = src[position++];
648
- if ((g & 0x80) > 0) {
649
- position -= 7;
650
- return
651
- }
652
- return fromCharCode(a, b, c, d, e, f, g)
653
- } else {
654
- let e = src[position++];
655
- let f = src[position++];
656
- let g = src[position++];
657
- let h = src[position++];
658
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
659
- position -= 8;
660
- return
661
- }
662
- if (length < 10) {
663
- if (length === 8)
664
- return fromCharCode(a, b, c, d, e, f, g, h)
665
- else {
666
- let i = src[position++];
667
- if ((i & 0x80) > 0) {
668
- position -= 9;
669
- return
670
- }
671
- return fromCharCode(a, b, c, d, e, f, g, h, i)
672
- }
673
- } else if (length < 12) {
674
- let i = src[position++];
675
- let j = src[position++];
676
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
677
- position -= 10;
678
- return
679
- }
680
- if (length < 11)
681
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
682
- let k = src[position++];
683
- if ((k & 0x80) > 0) {
684
- position -= 11;
685
- return
686
- }
687
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
688
- } else {
689
- let i = src[position++];
690
- let j = src[position++];
691
- let k = src[position++];
692
- let l = src[position++];
693
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
694
- position -= 12;
695
- return
696
- }
697
- if (length < 14) {
698
- if (length === 12)
699
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
700
- else {
701
- let m = src[position++];
702
- if ((m & 0x80) > 0) {
703
- position -= 13;
704
- return
705
- }
706
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
707
- }
708
- } else {
709
- let m = src[position++];
710
- let n = src[position++];
711
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
712
- position -= 14;
713
- return
714
- }
715
- if (length < 15)
716
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
717
- let o = src[position++];
718
- if ((o & 0x80) > 0) {
719
- position -= 15;
720
- return
721
- }
722
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
723
- }
724
- }
725
- }
726
- }
727
- }
728
-
729
- function readOnlyJSString() {
730
- let token = src[position++];
731
- let length;
732
- if (token < 0xc0) {
733
- // fixstr
734
- length = token - 0xa0;
735
- } else {
736
- switch(token) {
737
- case 0xd9:
738
- // str 8
739
- length = src[position++];
740
- break
741
- case 0xda:
742
- // str 16
743
- length = dataView.getUint16(position);
744
- position += 2;
745
- break
746
- case 0xdb:
747
- // str 32
748
- length = dataView.getUint32(position);
749
- position += 4;
750
- break
751
- default:
752
- throw new Error('Expected string')
753
- }
754
- }
755
- return readStringJS(length)
756
- }
757
-
758
-
759
- function readBin(length) {
760
- return currentUnpackr.copyBuffers ?
761
- // specifically use the copying slice (not the node one)
762
- Uint8Array.prototype.slice.call(src, position, position += length) :
763
- src.subarray(position, position += length)
764
- }
765
- function readExt(length) {
766
- let type = src[position++];
767
- if (currentExtensions[type]) {
768
- return currentExtensions[type](src.subarray(position, position += length))
769
- }
770
- else
771
- throw new Error('Unknown extension type ' + type)
772
- }
773
-
774
- var keyCache = new Array(4096);
775
- function readKey() {
776
- let length = src[position++];
777
- if (length >= 0xa0 && length < 0xc0) {
778
- // fixstr, potentially use key cache
779
- length = length - 0xa0;
780
- if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
781
- return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
782
- else if (!(srcStringEnd == 0 && srcEnd < 180))
783
- return readFixedString(length)
784
- } else { // not cacheable, go back and do a standard read
785
- position--;
786
- return read()
787
- }
788
- let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;
789
- let entry = keyCache[key];
790
- let checkPosition = position;
791
- let end = position + length - 3;
792
- let chunk;
793
- let i = 0;
794
- if (entry && entry.bytes == length) {
795
- while (checkPosition < end) {
796
- chunk = dataView.getUint32(checkPosition);
797
- if (chunk != entry[i++]) {
798
- checkPosition = 0x70000000;
799
- break
800
- }
801
- checkPosition += 4;
802
- }
803
- end += 3;
804
- while (checkPosition < end) {
805
- chunk = src[checkPosition++];
806
- if (chunk != entry[i++]) {
807
- checkPosition = 0x70000000;
808
- break
809
- }
810
- }
811
- if (checkPosition === end) {
812
- position = checkPosition;
813
- return entry.string
814
- }
815
- end -= 3;
816
- checkPosition = position;
817
- }
818
- entry = [];
819
- keyCache[key] = entry;
820
- entry.bytes = length;
821
- while (checkPosition < end) {
822
- chunk = dataView.getUint32(checkPosition);
823
- entry.push(chunk);
824
- checkPosition += 4;
825
- }
826
- end += 3;
827
- while (checkPosition < end) {
828
- chunk = src[checkPosition++];
829
- entry.push(chunk);
830
- }
831
- // for small blocks, avoiding the overhead of the extract call is helpful
832
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
833
- if (string != null)
834
- return entry.string = string
835
- return entry.string = readFixedString(length)
836
- }
837
-
838
- // the registration of the record definition extension (as "r")
839
- const recordDefinition = (id, highByte) => {
840
- var structure = read();
841
- let firstByte = id;
842
- if (highByte !== undefined) {
843
- id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
844
- structure.highByte = highByte;
845
- }
846
- let existingStructure = currentStructures[id];
847
- if (existingStructure && existingStructure.isShared) {
848
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
849
- }
850
- currentStructures[id] = structure;
851
- structure.read = createStructureReader(structure, firstByte);
852
- return structure.read()
853
- };
854
- currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
855
- currentExtensions[0].noBuffer = true;
856
-
857
- currentExtensions[0x65] = () => {
858
- let data = read();
859
- return (globalThis[data[0]] || Error)(data[1])
860
- };
861
-
862
- currentExtensions[0x69] = (data) => {
863
- // id extension (for structured clones)
864
- let id = dataView.getUint32(position - 4);
865
- if (!referenceMap)
866
- referenceMap = new Map();
867
- let token = src[position];
868
- let target;
869
- // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
870
- // ahead past references to record structure definitions
871
- if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
872
- target = [];
873
- else
874
- target = {};
875
-
876
- let refEntry = { target }; // a placeholder object
877
- referenceMap.set(id, refEntry);
878
- let targetProperties = read(); // read the next value as the target object to id
879
- if (refEntry.used) // there is a cycle, so we have to assign properties to original target
880
- return Object.assign(target, targetProperties)
881
- refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
882
- return targetProperties // no cycle, can just use the returned read object
883
- };
884
-
885
- currentExtensions[0x70] = (data) => {
886
- // pointer extension (for structured clones)
887
- let id = dataView.getUint32(position - 4);
888
- let refEntry = referenceMap.get(id);
889
- refEntry.used = true;
890
- return refEntry.target
891
- };
892
-
893
- currentExtensions[0x73] = () => new Set(read());
894
-
895
- const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
896
-
897
- currentExtensions[0x74] = (data) => {
898
- let typeCode = data[0];
899
- let typedArrayName = typedArrays[typeCode];
900
- if (!typedArrayName)
901
- throw new Error('Could not find typed array for code ' + typeCode)
902
- // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
903
- return new globalThis[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
904
- };
905
- currentExtensions[0x78] = () => {
906
- let data = read();
907
- return new RegExp(data[0], data[1])
908
- };
909
- const TEMP_BUNDLE = [];
910
- currentExtensions[0x62] = (data) => {
911
- let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
912
- let dataPosition = position;
913
- position += dataSize - data.length;
914
- bundledStrings = TEMP_BUNDLE;
915
- bundledStrings = [readOnlyJSString(), readOnlyJSString()];
916
- bundledStrings.position0 = 0;
917
- bundledStrings.position1 = 0;
918
- bundledStrings.postBundlePosition = position;
919
- position = dataPosition;
920
- return read()
921
- };
922
-
923
- currentExtensions[0xff] = (data) => {
924
- // 32-bit date extension
925
- if (data.length == 4)
926
- return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
927
- else if (data.length == 8)
928
- return new Date(
929
- ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
930
- ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
931
- else if (data.length == 12)// TODO: Implement support for negative
932
- return new Date(
933
- ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
934
- (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
935
- else
936
- return new Date('invalid')
937
- }; // notepack defines extension 0 to mean undefined, so use that as the default here
938
- // registration of bulk record definition?
939
- // currentExtensions[0x52] = () =>
940
-
941
- function saveState(callback) {
942
- let savedSrcEnd = srcEnd;
943
- let savedPosition = position;
944
- let savedSrcStringStart = srcStringStart;
945
- let savedSrcStringEnd = srcStringEnd;
946
- let savedSrcString = srcString;
947
- let savedReferenceMap = referenceMap;
948
- let savedBundledStrings = bundledStrings;
949
-
950
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
951
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
952
- let savedStructures = currentStructures;
953
- let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
954
- let savedPackr = currentUnpackr;
955
- let savedSequentialMode = sequentialMode;
956
- let value = callback();
957
- srcEnd = savedSrcEnd;
958
- position = savedPosition;
959
- srcStringStart = savedSrcStringStart;
960
- srcStringEnd = savedSrcStringEnd;
961
- srcString = savedSrcString;
962
- referenceMap = savedReferenceMap;
963
- bundledStrings = savedBundledStrings;
964
- src = savedSrc;
965
- sequentialMode = savedSequentialMode;
966
- currentStructures = savedStructures;
967
- currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
968
- currentUnpackr = savedPackr;
969
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
970
- return value
971
- }
972
- function clearSource() {
973
- src = null;
974
- referenceMap = null;
975
- currentStructures = null;
976
- }
977
-
978
- function addExtension(extension) {
979
- if (extension.unpack)
980
- currentExtensions[extension.type] = extension.unpack;
981
- else
982
- currentExtensions[extension.type] = extension;
983
- }
984
-
985
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
986
- for (let i = 0; i < 256; i++) {
987
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
988
- }
989
- const Decoder = Unpackr;
990
- var defaultUnpackr = new Unpackr({ useRecords: false });
991
- const unpack = defaultUnpackr.unpack;
992
- const unpackMultiple = defaultUnpackr.unpackMultiple;
993
- const decode = defaultUnpackr.unpack;
994
- const FLOAT32_OPTIONS = {
995
- NEVER: 0,
996
- ALWAYS: 1,
997
- DECIMAL_ROUND: 3,
998
- DECIMAL_FIT: 4
999
- };
1000
- let f32Array = new Float32Array(1);
1001
- let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
1002
- function roundFloat32(float32Number) {
1003
- f32Array[0] = float32Number;
1004
- let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1005
- return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
7
+ var decoder;
8
+ try {
9
+ decoder = new TextDecoder();
10
+ } catch(error) {}
11
+ var src;
12
+ var srcEnd;
13
+ var position = 0;
14
+ var currentUnpackr = {};
15
+ var currentStructures;
16
+ var srcString;
17
+ var srcStringStart = 0;
18
+ var srcStringEnd = 0;
19
+ var bundledStrings;
20
+ var referenceMap;
21
+ var currentExtensions = [];
22
+ var dataView;
23
+ var defaultOptions = {
24
+ useRecords: false,
25
+ mapsAsObjects: true
26
+ };
27
+ class C1Type {}
28
+ const C1 = new C1Type();
29
+ C1.name = 'MessagePack 0xC1';
30
+ var sequentialMode = false;
31
+ var inlineObjectReadThreshold = 2;
32
+ try {
33
+ new Function('');
34
+ } catch(error) {
35
+ // if eval variants are not supported, do not create inline object readers ever
36
+ inlineObjectReadThreshold = Infinity;
1006
37
  }
1007
38
 
1008
- let textEncoder;
1009
- try {
1010
- textEncoder = new TextEncoder();
1011
- } catch (error) {}
1012
- let extensions, extensionClasses;
1013
- const hasNodeBuffer = typeof Buffer !== 'undefined';
1014
- const ByteArrayAllocate = hasNodeBuffer ?
1015
- function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1016
- const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1017
- const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1018
- let target, keysTarget;
1019
- let targetView;
1020
- let position$1 = 0;
1021
- let safeEnd;
1022
- let bundledStrings$1 = null;
1023
- const MAX_BUNDLE_SIZE = 0xf000;
1024
- const hasNonLatin = /[\u0080-\uFFFF]/;
1025
- const RECORD_SYMBOL = Symbol('record-id');
1026
- class Packr extends Unpackr {
1027
- constructor(options) {
1028
- super(options);
1029
- this.offset = 0;
1030
- let start;
1031
- let hasSharedUpdate;
1032
- let structures;
1033
- let referenceMap;
1034
- let lastSharedStructuresLength = 0;
1035
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1036
- return target.utf8Write(string, position, 0xffffffff)
1037
- } : (textEncoder && textEncoder.encodeInto) ?
1038
- function(string, position) {
1039
- return textEncoder.encodeInto(string, target.subarray(position)).written
1040
- } : false;
1041
-
1042
- let packr = this;
1043
- if (!options)
1044
- options = {};
1045
- let isSequential = options && options.sequential;
1046
- let hasSharedStructures = options.structures || options.saveStructures;
1047
- let maxSharedStructures = options.maxSharedStructures;
1048
- if (maxSharedStructures == null)
1049
- maxSharedStructures = hasSharedStructures ? 32 : 0;
1050
- if (maxSharedStructures > 8160)
1051
- throw new Error('Maximum maxSharedStructure is 8160')
1052
- if (options.structuredClone && options.moreTypes == undefined) {
1053
- options.moreTypes = true;
1054
- }
1055
- let maxOwnStructures = options.maxOwnStructures;
1056
- if (maxOwnStructures == null)
1057
- maxOwnStructures = hasSharedStructures ? 32 : 64;
1058
- if (!this.structures && options.useRecords != false)
1059
- this.structures = [];
1060
- // two byte record ids for shared structures
1061
- let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1062
- let sharedLimitId = maxSharedStructures + 0x40;
1063
- let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1064
- if (maxStructureId > 8256) {
1065
- throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1066
- }
1067
- let recordIdsToRemove = [];
1068
- let transitionsCount = 0;
1069
- let serializationsSinceTransitionRebuild = 0;
1070
-
1071
- this.pack = this.encode = function(value, encodeOptions) {
1072
- if (!target) {
1073
- target = new ByteArrayAllocate(8192);
1074
- targetView = new DataView(target.buffer, 0, 8192);
1075
- position$1 = 0;
1076
- }
1077
- safeEnd = target.length - 10;
1078
- if (safeEnd - position$1 < 0x800) {
1079
- // don't start too close to the end,
1080
- target = new ByteArrayAllocate(target.length);
1081
- targetView = new DataView(target.buffer, 0, target.length);
1082
- safeEnd = target.length - 10;
1083
- position$1 = 0;
1084
- } else
1085
- position$1 = (position$1 + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1086
- start = position$1;
1087
- referenceMap = packr.structuredClone ? new Map() : null;
1088
- if (packr.bundleStrings && typeof value !== 'string') {
1089
- bundledStrings$1 = [];
1090
- bundledStrings$1.size = Infinity; // force a new bundle start on first string
1091
- } else
1092
- bundledStrings$1 = null;
1093
- structures = packr.structures;
1094
- if (structures) {
1095
- if (structures.uninitialized)
1096
- structures = packr._mergeStructures(packr.getStructures());
1097
- let sharedLength = structures.sharedLength || 0;
1098
- if (sharedLength > maxSharedStructures) {
1099
- //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1100
- throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1101
- }
1102
- if (!structures.transitions) {
1103
- // rebuild our structure transitions
1104
- structures.transitions = Object.create(null);
1105
- for (let i = 0; i < sharedLength; i++) {
1106
- let keys = structures[i];
1107
- if (!keys)
1108
- continue
1109
- let nextTransition, transition = structures.transitions;
1110
- for (let j = 0, l = keys.length; j < l; j++) {
1111
- let key = keys[j];
1112
- nextTransition = transition[key];
1113
- if (!nextTransition) {
1114
- nextTransition = transition[key] = Object.create(null);
1115
- }
1116
- transition = nextTransition;
1117
- }
1118
- transition[RECORD_SYMBOL] = i + 0x40;
1119
- }
1120
- lastSharedStructuresLength = sharedLength;
1121
- }
1122
- if (!isSequential) {
1123
- structures.nextId = sharedLength + 0x40;
1124
- }
1125
- }
1126
- if (hasSharedUpdate)
1127
- hasSharedUpdate = false;
1128
- try {
1129
- pack(value);
1130
- if (bundledStrings$1) {
1131
- writeBundles(start, pack);
1132
- }
1133
- packr.offset = position$1; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1134
- if (referenceMap && referenceMap.idsToInsert) {
1135
- position$1 += referenceMap.idsToInsert.length * 6;
1136
- if (position$1 > safeEnd)
1137
- makeRoom(position$1);
1138
- packr.offset = position$1;
1139
- let serialized = insertIds(target.subarray(start, position$1), referenceMap.idsToInsert);
1140
- referenceMap = null;
1141
- return serialized
1142
- }
1143
- if (encodeOptions & REUSE_BUFFER_MODE) {
1144
- target.start = start;
1145
- target.end = position$1;
1146
- return target
1147
- }
1148
- return target.subarray(start, position$1) // position can change if we call pack again in saveStructures, so we get the buffer now
1149
- } finally {
1150
- if (structures) {
1151
- if (serializationsSinceTransitionRebuild < 10)
1152
- serializationsSinceTransitionRebuild++;
1153
- let sharedLength = structures.sharedLength || maxSharedStructures;
1154
- if (structures.length > sharedLength)
1155
- structures.length = sharedLength;
1156
- if (transitionsCount > 10000) {
1157
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1158
- structures.transitions = null;
1159
- serializationsSinceTransitionRebuild = 0;
1160
- transitionsCount = 0;
1161
- if (recordIdsToRemove.length > 0)
1162
- recordIdsToRemove = [];
1163
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
1164
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1165
- recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1166
- }
1167
- recordIdsToRemove = [];
1168
- }
1169
- if (hasSharedUpdate && packr.saveStructures) {
1170
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1171
- let returnBuffer = target.subarray(start, position$1);
1172
- if (packr.saveStructures(structures, lastSharedStructuresLength) === false) {
1173
- // get updated structures and try again if the update failed
1174
- packr._mergeStructures(packr.getStructures());
1175
- return packr.pack(value)
1176
- }
1177
- lastSharedStructuresLength = sharedLength;
1178
- return returnBuffer
1179
- }
1180
- }
1181
- if (encodeOptions & RESET_BUFFER_MODE)
1182
- position$1 = start;
1183
- }
1184
- };
1185
- const pack = (value) => {
1186
- if (position$1 > safeEnd)
1187
- target = makeRoom(position$1);
1188
-
1189
- var type = typeof value;
1190
- var length;
1191
- if (type === 'string') {
1192
- let strLength = value.length;
1193
- if (bundledStrings$1 && strLength >= 4 && strLength < 0x1000) {
1194
- if ((bundledStrings$1.size += strLength) > MAX_BUNDLE_SIZE) {
1195
- let extStart;
1196
- let maxBytes = (bundledStrings$1[0] ? bundledStrings$1[0].length * 3 + bundledStrings$1[1].length : 0) + 10;
1197
- if (position$1 + maxBytes > safeEnd)
1198
- target = makeRoom(position$1 + maxBytes);
1199
- if (bundledStrings$1.position) { // here we use the 0x62 extension to write the last bundle and reserve sapce for the reference pointer to the next/current bundle
1200
- target[position$1] = 0xc8; // ext 16
1201
- position$1 += 3; // reserve for the writing bundle size
1202
- target[position$1++] = 0x62; // 'b'
1203
- extStart = position$1 - start;
1204
- position$1 += 4; // reserve for writing bundle reference
1205
- writeBundles(start, pack); // write the last bundles
1206
- targetView.setUint16(extStart + start - 3, position$1 - start - extStart);
1207
- } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
1208
- target[position$1++] = 0xd6; // fixext 4
1209
- target[position$1++] = 0x62; // 'b'
1210
- extStart = position$1 - start;
1211
- position$1 += 4; // reserve for writing bundle reference
1212
- }
1213
- bundledStrings$1 = ['', '']; // create new ones
1214
- bundledStrings$1.size = 0;
1215
- bundledStrings$1.position = extStart;
1216
- }
1217
- let twoByte = hasNonLatin.test(value);
1218
- bundledStrings$1[twoByte ? 0 : 1] += value;
1219
- target[position$1++] = 0xc1;
1220
- pack(twoByte ? -strLength : strLength);
1221
- return
1222
- }
1223
- let headerSize;
1224
- // first we estimate the header size, so we can write to the correct location
1225
- if (strLength < 0x20) {
1226
- headerSize = 1;
1227
- } else if (strLength < 0x100) {
1228
- headerSize = 2;
1229
- } else if (strLength < 0x10000) {
1230
- headerSize = 3;
1231
- } else {
1232
- headerSize = 5;
1233
- }
1234
- let maxBytes = strLength * 3;
1235
- if (position$1 + maxBytes > safeEnd)
1236
- target = makeRoom(position$1 + maxBytes);
1237
-
1238
- if (strLength < 0x40 || !encodeUtf8) {
1239
- let i, c1, c2, strPosition = position$1 + headerSize;
1240
- for (i = 0; i < strLength; i++) {
1241
- c1 = value.charCodeAt(i);
1242
- if (c1 < 0x80) {
1243
- target[strPosition++] = c1;
1244
- } else if (c1 < 0x800) {
1245
- target[strPosition++] = c1 >> 6 | 0xc0;
1246
- target[strPosition++] = c1 & 0x3f | 0x80;
1247
- } else if (
1248
- (c1 & 0xfc00) === 0xd800 &&
1249
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1250
- ) {
1251
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1252
- i++;
1253
- target[strPosition++] = c1 >> 18 | 0xf0;
1254
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1255
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1256
- target[strPosition++] = c1 & 0x3f | 0x80;
1257
- } else {
1258
- target[strPosition++] = c1 >> 12 | 0xe0;
1259
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1260
- target[strPosition++] = c1 & 0x3f | 0x80;
1261
- }
1262
- }
1263
- length = strPosition - position$1 - headerSize;
1264
- } else {
1265
- length = encodeUtf8(value, position$1 + headerSize);
1266
- }
1267
-
1268
- if (length < 0x20) {
1269
- target[position$1++] = 0xa0 | length;
1270
- } else if (length < 0x100) {
1271
- if (headerSize < 2) {
1272
- target.copyWithin(position$1 + 2, position$1 + 1, position$1 + 1 + length);
1273
- }
1274
- target[position$1++] = 0xd9;
1275
- target[position$1++] = length;
1276
- } else if (length < 0x10000) {
1277
- if (headerSize < 3) {
1278
- target.copyWithin(position$1 + 3, position$1 + 2, position$1 + 2 + length);
1279
- }
1280
- target[position$1++] = 0xda;
1281
- target[position$1++] = length >> 8;
1282
- target[position$1++] = length & 0xff;
1283
- } else {
1284
- if (headerSize < 5) {
1285
- target.copyWithin(position$1 + 5, position$1 + 3, position$1 + 3 + length);
1286
- }
1287
- target[position$1++] = 0xdb;
1288
- targetView.setUint32(position$1, length);
1289
- position$1 += 4;
1290
- }
1291
- position$1 += length;
1292
- } else if (type === 'number') {
1293
- if (value >>> 0 === value) {// positive integer, 32-bit or less
1294
- // positive uint
1295
- if (value < 0x40) {
1296
- target[position$1++] = value;
1297
- } else if (value < 0x100) {
1298
- target[position$1++] = 0xcc;
1299
- target[position$1++] = value;
1300
- } else if (value < 0x10000) {
1301
- target[position$1++] = 0xcd;
1302
- target[position$1++] = value >> 8;
1303
- target[position$1++] = value & 0xff;
1304
- } else {
1305
- target[position$1++] = 0xce;
1306
- targetView.setUint32(position$1, value);
1307
- position$1 += 4;
1308
- }
1309
- } else if (value >> 0 === value) { // negative integer
1310
- if (value >= -0x20) {
1311
- target[position$1++] = 0x100 + value;
1312
- } else if (value >= -0x80) {
1313
- target[position$1++] = 0xd0;
1314
- target[position$1++] = value + 0x100;
1315
- } else if (value >= -0x8000) {
1316
- target[position$1++] = 0xd1;
1317
- targetView.setInt16(position$1, value);
1318
- position$1 += 2;
1319
- } else {
1320
- target[position$1++] = 0xd2;
1321
- targetView.setInt32(position$1, value);
1322
- position$1 += 4;
1323
- }
1324
- } else {
1325
- let useFloat32;
1326
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1327
- target[position$1++] = 0xca;
1328
- targetView.setFloat32(position$1, value);
1329
- let xShifted;
1330
- if (useFloat32 < 4 ||
1331
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1332
- ((xShifted = value * mult10[((target[position$1] & 0x7f) << 1) | (target[position$1 + 1] >> 7)]) >> 0) === xShifted) {
1333
- position$1 += 4;
1334
- return
1335
- } else
1336
- position$1--; // move back into position for writing a double
1337
- }
1338
- target[position$1++] = 0xcb;
1339
- targetView.setFloat64(position$1, value);
1340
- position$1 += 8;
1341
- }
1342
- } else if (type === 'object') {
1343
- if (!value)
1344
- target[position$1++] = 0xc0;
1345
- else {
1346
- if (referenceMap) {
1347
- let referee = referenceMap.get(value);
1348
- if (referee) {
1349
- if (!referee.id) {
1350
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1351
- referee.id = idsToInsert.push(referee);
1352
- }
1353
- target[position$1++] = 0xd6; // fixext 4
1354
- target[position$1++] = 0x70; // "p" for pointer
1355
- targetView.setUint32(position$1, referee.id);
1356
- position$1 += 4;
1357
- return
1358
- } else
1359
- referenceMap.set(value, { offset: position$1 - start });
1360
- }
1361
- let constructor = value.constructor;
1362
- if (constructor === Object) {
1363
- writeObject(value, true);
1364
- } else if (constructor === Array) {
1365
- length = value.length;
1366
- if (length < 0x10) {
1367
- target[position$1++] = 0x90 | length;
1368
- } else if (length < 0x10000) {
1369
- target[position$1++] = 0xdc;
1370
- target[position$1++] = length >> 8;
1371
- target[position$1++] = length & 0xff;
1372
- } else {
1373
- target[position$1++] = 0xdd;
1374
- targetView.setUint32(position$1, length);
1375
- position$1 += 4;
1376
- }
1377
- for (let i = 0; i < length; i++) {
1378
- pack(value[i]);
1379
- }
1380
- } else if (constructor === Map) {
1381
- length = value.size;
1382
- if (length < 0x10) {
1383
- target[position$1++] = 0x80 | length;
1384
- } else if (length < 0x10000) {
1385
- target[position$1++] = 0xde;
1386
- target[position$1++] = length >> 8;
1387
- target[position$1++] = length & 0xff;
1388
- } else {
1389
- target[position$1++] = 0xdf;
1390
- targetView.setUint32(position$1, length);
1391
- position$1 += 4;
1392
- }
1393
- for (let [ key, entryValue ] of value) {
1394
- pack(key);
1395
- pack(entryValue);
1396
- }
1397
- } else {
1398
- for (let i = 0, l = extensions.length; i < l; i++) {
1399
- let extensionClass = extensionClasses[i];
1400
- if (value instanceof extensionClass) {
1401
- let extension = extensions[i];
1402
- if (extension.write) {
1403
- if (extension.type) {
1404
- target[position$1++] = 0xd4; // one byte "tag" extension
1405
- target[position$1++] = extension.type;
1406
- target[position$1++] = 0;
1407
- }
1408
- pack(extension.write.call(this, value));
1409
- return
1410
- }
1411
- let currentTarget = target;
1412
- let currentTargetView = targetView;
1413
- let currentPosition = position$1;
1414
- target = null;
1415
- let result;
1416
- try {
1417
- result = extension.pack.call(this, value, (size) => {
1418
- // restore target and use it
1419
- target = currentTarget;
1420
- currentTarget = null;
1421
- position$1 += size;
1422
- if (position$1 > safeEnd)
1423
- makeRoom(position$1);
1424
- return {
1425
- target, targetView, position: position$1 - size
1426
- }
1427
- }, pack);
1428
- } finally {
1429
- // restore current target information (unless already restored)
1430
- if (currentTarget) {
1431
- target = currentTarget;
1432
- targetView = currentTargetView;
1433
- position$1 = currentPosition;
1434
- safeEnd = target.length - 10;
1435
- }
1436
- }
1437
- if (result) {
1438
- if (result.length + position$1 > safeEnd)
1439
- makeRoom(result.length + position$1);
1440
- position$1 = writeExtensionData(result, target, position$1, extension.type);
1441
- }
1442
- return
1443
- }
1444
- }
1445
- // no extension found, write as object
1446
- writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1447
- }
1448
- }
1449
- } else if (type === 'boolean') {
1450
- target[position$1++] = value ? 0xc3 : 0xc2;
1451
- } else if (type === 'bigint') {
1452
- if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
1453
- // use a signed int as long as it fits
1454
- target[position$1++] = 0xd3;
1455
- targetView.setBigInt64(position$1, value);
1456
- } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
1457
- // if we can fit an unsigned int, use that
1458
- target[position$1++] = 0xcf;
1459
- targetView.setBigUint64(position$1, value);
1460
- } else {
1461
- // overflow
1462
- if (this.largeBigIntToFloat) {
1463
- target[position$1++] = 0xcb;
1464
- targetView.setFloat64(position$1, Number(value));
1465
- } else {
1466
- throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1467
- }
1468
- }
1469
- position$1 += 8;
1470
- } else if (type === 'undefined') {
1471
- if (this.encodeUndefinedAsNil)
1472
- target[position$1++] = 0xc0;
1473
- else {
1474
- target[position$1++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1475
- target[position$1++] = 0;
1476
- target[position$1++] = 0;
1477
- }
1478
- } else if (type === 'function') {
1479
- pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
1480
- } else {
1481
- throw new Error('Unknown type: ' + type)
1482
- }
1483
- };
1484
-
1485
- const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1486
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1487
- let keys = Object.keys(object);
1488
- let length = keys.length;
1489
- if (length < 0x10) {
1490
- target[position$1++] = 0x80 | length;
1491
- } else if (length < 0x10000) {
1492
- target[position$1++] = 0xde;
1493
- target[position$1++] = length >> 8;
1494
- target[position$1++] = length & 0xff;
1495
- } else {
1496
- target[position$1++] = 0xdf;
1497
- targetView.setUint32(position$1, length);
1498
- position$1 += 4;
1499
- }
1500
- let key;
1501
- for (let i = 0; i < length; i++) {
1502
- pack(key = keys[i]);
1503
- pack(object[key]);
1504
- }
1505
- } :
1506
- (object, safePrototype) => {
1507
- target[position$1++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1508
- let objectOffset = position$1 - start;
1509
- position$1 += 2;
1510
- let size = 0;
1511
- for (let key in object) {
1512
- if (safePrototype || object.hasOwnProperty(key)) {
1513
- pack(key);
1514
- pack(object[key]);
1515
- size++;
1516
- }
1517
- }
1518
- target[objectOffset++ + start] = size >> 8;
1519
- target[objectOffset + start] = size & 0xff;
1520
- } :
1521
- (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
1522
- (object, safePrototype) => {
1523
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1524
- let objectOffset = position$1++ - start;
1525
- let wroteKeys;
1526
- for (let key in object) {
1527
- if (safePrototype || object.hasOwnProperty(key)) {
1528
- nextTransition = transition[key];
1529
- if (nextTransition)
1530
- transition = nextTransition;
1531
- else {
1532
- // record doesn't exist, create full new record and insert it
1533
- let keys = Object.keys(object);
1534
- let lastTransition = transition;
1535
- transition = structures.transitions;
1536
- let newTransitions = 0;
1537
- for (let i = 0, l = keys.length; i < l; i++) {
1538
- let key = keys[i];
1539
- nextTransition = transition[key];
1540
- if (!nextTransition) {
1541
- nextTransition = transition[key] = Object.create(null);
1542
- newTransitions++;
1543
- }
1544
- transition = nextTransition;
1545
- }
1546
- if (objectOffset + start + 1 == position$1) {
1547
- // first key, so we don't need to insert, we can just write record directly
1548
- position$1--;
1549
- newRecord(transition, keys, newTransitions);
1550
- } else // otherwise we need to insert the record, moving existing data after the record
1551
- insertNewRecord(transition, keys, objectOffset, newTransitions);
1552
- wroteKeys = true;
1553
- transition = lastTransition[key];
1554
- }
1555
- pack(object[key]);
1556
- }
1557
- }
1558
- if (!wroteKeys) {
1559
- let recordId = transition[RECORD_SYMBOL];
1560
- if (recordId)
1561
- target[objectOffset + start] = recordId;
1562
- else
1563
- insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1564
- }
1565
- } :
1566
- (object, safePrototype) => {
1567
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1568
- let newTransitions = 0;
1569
- for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1570
- nextTransition = transition[key];
1571
- if (!nextTransition) {
1572
- nextTransition = transition[key] = Object.create(null);
1573
- newTransitions++;
1574
- }
1575
- transition = nextTransition;
1576
- }
1577
- let recordId = transition[RECORD_SYMBOL];
1578
- if (recordId) {
1579
- if (recordId >= 0x60 && useTwoByteRecords) {
1580
- target[position$1++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1581
- target[position$1++] = recordId >> 5;
1582
- } else
1583
- target[position$1++] = recordId;
1584
- } else {
1585
- newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1586
- }
1587
- // now write the values
1588
- for (let key in object)
1589
- if (safePrototype || object.hasOwnProperty(key))
1590
- pack(object[key]);
1591
- };
1592
- const makeRoom = (end) => {
1593
- let newSize;
1594
- if (end > 0x1000000) {
1595
- // special handling for really large buffers
1596
- if ((end - start) > MAX_BUFFER_SIZE)
1597
- throw new Error('Packed buffer would be larger than maximum buffer size')
1598
- newSize = Math.min(MAX_BUFFER_SIZE,
1599
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1600
- } else // faster handling for smaller buffers
1601
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1602
- let newBuffer = new ByteArrayAllocate(newSize);
1603
- targetView = new DataView(newBuffer.buffer, 0, newSize);
1604
- end = Math.min(end, target.length);
1605
- if (target.copy)
1606
- target.copy(newBuffer, 0, start, end);
1607
- else
1608
- newBuffer.set(target.slice(start, end));
1609
- position$1 -= start;
1610
- start = 0;
1611
- safeEnd = newBuffer.length - 10;
1612
- return target = newBuffer
1613
- };
1614
- const newRecord = (transition, keys, newTransitions) => {
1615
- let recordId = structures.nextId;
1616
- if (!recordId)
1617
- recordId = 0x40;
1618
- if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1619
- recordId = structures.nextOwnId;
1620
- if (!(recordId < maxStructureId))
1621
- recordId = sharedLimitId;
1622
- structures.nextOwnId = recordId + 1;
1623
- } else {
1624
- if (recordId >= maxStructureId)// cycle back around
1625
- recordId = sharedLimitId;
1626
- structures.nextId = recordId + 1;
1627
- }
1628
- let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
1629
- transition[RECORD_SYMBOL] = recordId;
1630
- transition.__keys__ = keys;
1631
- structures[recordId - 0x40] = keys;
1632
-
1633
- if (recordId < sharedLimitId) {
1634
- keys.isShared = true;
1635
- structures.sharedLength = recordId - 0x3f;
1636
- hasSharedUpdate = true;
1637
- if (highByte >= 0) {
1638
- target[position$1++] = (recordId & 0x1f) + 0x60;
1639
- target[position$1++] = highByte;
1640
- } else {
1641
- target[position$1++] = recordId;
1642
- }
1643
- } else {
1644
- if (highByte >= 0) {
1645
- target[position$1++] = 0xd5; // fixext 2
1646
- target[position$1++] = 0x72; // "r" record defintion extension type
1647
- target[position$1++] = (recordId & 0x1f) + 0x60;
1648
- target[position$1++] = highByte;
1649
- } else {
1650
- target[position$1++] = 0xd4; // fixext 1
1651
- target[position$1++] = 0x72; // "r" record defintion extension type
1652
- target[position$1++] = recordId;
1653
- }
1654
-
1655
- if (newTransitions)
1656
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1657
- // record the removal of the id, we can maintain our shared structure
1658
- if (recordIdsToRemove.length >= maxOwnStructures)
1659
- recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
1660
- recordIdsToRemove.push(transition);
1661
- pack(keys);
1662
- }
1663
- };
1664
- const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
1665
- let mainTarget = target;
1666
- let mainPosition = position$1;
1667
- let mainSafeEnd = safeEnd;
1668
- let mainStart = start;
1669
- target = keysTarget;
1670
- position$1 = 0;
1671
- start = 0;
1672
- if (!target)
1673
- keysTarget = target = new ByteArrayAllocate(8192);
1674
- safeEnd = target.length - 10;
1675
- newRecord(transition, keys, newTransitions);
1676
- keysTarget = target;
1677
- let keysPosition = position$1;
1678
- target = mainTarget;
1679
- position$1 = mainPosition;
1680
- safeEnd = mainSafeEnd;
1681
- start = mainStart;
1682
- if (keysPosition > 1) {
1683
- let newEnd = position$1 + keysPosition - 1;
1684
- if (newEnd > safeEnd)
1685
- makeRoom(newEnd);
1686
- let insertionPosition = insertionOffset + start;
1687
- target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position$1);
1688
- target.set(keysTarget.slice(0, keysPosition), insertionPosition);
1689
- position$1 = newEnd;
1690
- } else {
1691
- target[insertionOffset + start] = keysTarget[0];
1692
- }
1693
- };
1694
- }
1695
- useBuffer(buffer) {
1696
- // this means we are finished using our own buffer and we can write over it safely
1697
- target = buffer;
1698
- targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1699
- position$1 = 0;
1700
- }
1701
- clearSharedData() {
1702
- if (this.structures)
1703
- this.structures = [];
1704
- }
1705
- }
1706
-
1707
- extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
1708
- extensions = [{
1709
- pack(date, allocateForWrite, pack) {
1710
- let seconds = date.getTime() / 1000;
1711
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
1712
- // Timestamp 32
1713
- let { target, targetView, position} = allocateForWrite(6);
1714
- target[position++] = 0xd6;
1715
- target[position++] = 0xff;
1716
- targetView.setUint32(position, seconds);
1717
- } else if (seconds > 0 && seconds < 0x100000000) {
1718
- // Timestamp 64
1719
- let { target, targetView, position} = allocateForWrite(10);
1720
- target[position++] = 0xd7;
1721
- target[position++] = 0xff;
1722
- targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
1723
- targetView.setUint32(position + 4, seconds);
1724
- } else if (isNaN(seconds)) {
1725
- if (this.onInvalidDate) {
1726
- allocateForWrite(0);
1727
- return pack(this.onInvalidDate())
1728
- }
1729
- // Intentionally invalid timestamp
1730
- let { target, targetView, position} = allocateForWrite(3);
1731
- target[position++] = 0xd4;
1732
- target[position++] = 0xff;
1733
- target[position++] = 0xff;
1734
- } else {
1735
- // Timestamp 96
1736
- let { target, targetView, position} = allocateForWrite(15);
1737
- target[position++] = 0xc7;
1738
- target[position++] = 12;
1739
- target[position++] = 0xff;
1740
- targetView.setUint32(position, date.getMilliseconds() * 1000000);
1741
- targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
1742
- }
1743
- }
1744
- }, {
1745
- pack(set, allocateForWrite, pack) {
1746
- let array = Array.from(set);
1747
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1748
- if (this.moreTypes) {
1749
- target[position++] = 0xd4;
1750
- target[position++] = 0x73; // 's' for Set
1751
- target[position++] = 0;
1752
- }
1753
- pack(array);
1754
- }
1755
- }, {
1756
- pack(error, allocateForWrite, pack) {
1757
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1758
- if (this.moreTypes) {
1759
- target[position++] = 0xd4;
1760
- target[position++] = 0x65; // 'e' for error
1761
- target[position++] = 0;
1762
- }
1763
- pack([ error.name, error.message ]);
1764
- }
1765
- }, {
1766
- pack(regex, allocateForWrite, pack) {
1767
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1768
- if (this.moreTypes) {
1769
- target[position++] = 0xd4;
1770
- target[position++] = 0x78; // 'x' for regeXp
1771
- target[position++] = 0;
1772
- }
1773
- pack([ regex.source, regex.flags ]);
1774
- }
1775
- }, {
1776
- pack(arrayBuffer, allocateForWrite) {
1777
- if (this.moreTypes)
1778
- writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
1779
- else
1780
- writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
1781
- }
1782
- }, {
1783
- pack(typedArray, allocateForWrite) {
1784
- let constructor = typedArray.constructor;
1785
- if (constructor !== ByteArray && this.moreTypes)
1786
- writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
1787
- else
1788
- writeBuffer(typedArray, allocateForWrite);
1789
- }
1790
- }, {
1791
- pack(c1, allocateForWrite) { // specific 0xC1 object
1792
- let { target, position} = allocateForWrite(1);
1793
- target[position] = 0xc1;
1794
- }
1795
- }];
1796
-
1797
- function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
1798
- let length = typedArray.byteLength;
1799
- if (length + 1 < 0x100) {
1800
- var { target, position } = allocateForWrite(4 + length);
1801
- target[position++] = 0xc7;
1802
- target[position++] = length + 1;
1803
- } else if (length + 1 < 0x10000) {
1804
- var { target, position } = allocateForWrite(5 + length);
1805
- target[position++] = 0xc8;
1806
- target[position++] = (length + 1) >> 8;
1807
- target[position++] = (length + 1) & 0xff;
1808
- } else {
1809
- var { target, position, targetView } = allocateForWrite(7 + length);
1810
- target[position++] = 0xc9;
1811
- targetView.setUint32(position, length + 1); // plus one for the type byte
1812
- position += 4;
1813
- }
1814
- target[position++] = 0x74; // "t" for typed array
1815
- target[position++] = type;
1816
- target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
1817
- }
1818
- function writeBuffer(buffer, allocateForWrite) {
1819
- let length = buffer.byteLength;
1820
- var target, position;
1821
- if (length < 0x100) {
1822
- var { target, position } = allocateForWrite(length + 2);
1823
- target[position++] = 0xc4;
1824
- target[position++] = length;
1825
- } else if (length < 0x10000) {
1826
- var { target, position } = allocateForWrite(length + 3);
1827
- target[position++] = 0xc5;
1828
- target[position++] = length >> 8;
1829
- target[position++] = length & 0xff;
1830
- } else {
1831
- var { target, position, targetView } = allocateForWrite(length + 5);
1832
- target[position++] = 0xc6;
1833
- targetView.setUint32(position, length);
1834
- position += 4;
1835
- }
1836
- target.set(buffer, position);
1837
- }
1838
-
1839
- function writeExtensionData(result, target, position, type) {
1840
- let length = result.length;
1841
- switch (length) {
1842
- case 1:
1843
- target[position++] = 0xd4;
1844
- break
1845
- case 2:
1846
- target[position++] = 0xd5;
1847
- break
1848
- case 4:
1849
- target[position++] = 0xd6;
1850
- break
1851
- case 8:
1852
- target[position++] = 0xd7;
1853
- break
1854
- case 16:
1855
- target[position++] = 0xd8;
1856
- break
1857
- default:
1858
- if (length < 0x100) {
1859
- target[position++] = 0xc7;
1860
- target[position++] = length;
1861
- } else if (length < 0x10000) {
1862
- target[position++] = 0xc8;
1863
- target[position++] = length >> 8;
1864
- target[position++] = length & 0xff;
1865
- } else {
1866
- target[position++] = 0xc9;
1867
- target[position++] = length >> 24;
1868
- target[position++] = (length >> 16) & 0xff;
1869
- target[position++] = (length >> 8) & 0xff;
1870
- target[position++] = length & 0xff;
1871
- }
1872
- }
1873
- target[position++] = type;
1874
- target.set(result, position);
1875
- position += length;
1876
- return position
1877
- }
1878
-
1879
- function insertIds(serialized, idsToInsert) {
1880
- // insert the ids that need to be referenced for structured clones
1881
- let nextId;
1882
- let distanceToMove = idsToInsert.length * 6;
1883
- let lastEnd = serialized.length - distanceToMove;
1884
- idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1885
- while (nextId = idsToInsert.pop()) {
1886
- let offset = nextId.offset;
1887
- let id = nextId.id;
1888
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
1889
- distanceToMove -= 6;
1890
- let position = offset + distanceToMove;
1891
- serialized[position++] = 0xd6;
1892
- serialized[position++] = 0x69; // 'i'
1893
- serialized[position++] = id >> 24;
1894
- serialized[position++] = (id >> 16) & 0xff;
1895
- serialized[position++] = (id >> 8) & 0xff;
1896
- serialized[position++] = id & 0xff;
1897
- lastEnd = offset;
1898
- }
1899
- return serialized
1900
- }
1901
-
1902
- function writeBundles(start, pack) {
1903
- targetView.setUint32(bundledStrings$1.position + start, position$1 - bundledStrings$1.position - start);
1904
- let writeStrings = bundledStrings$1;
1905
- bundledStrings$1 = null;
1906
- pack(writeStrings[0]);
1907
- pack(writeStrings[1]);
1908
- }
1909
-
1910
- function addExtension$1(extension) {
1911
- if (extension.Class) {
1912
- if (!extension.pack && !extension.write)
1913
- throw new Error('Extension has no pack or write function')
1914
- if (extension.pack && !extension.type)
1915
- throw new Error('Extension has no type (numeric code to identify the extension)')
1916
- extensionClasses.unshift(extension.Class);
1917
- extensions.unshift(extension);
1918
- }
1919
- addExtension(extension);
1920
- }
1921
-
1922
- let defaultPackr = new Packr({ useRecords: false });
1923
- const pack = defaultPackr.pack;
1924
- const encode = defaultPackr.pack;
1925
- const Encoder = Packr;
1926
- const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
1927
- const REUSE_BUFFER_MODE = 512;
39
+ class Unpackr {
40
+ constructor(options) {
41
+ if (options) {
42
+ if (options.useRecords === false && options.mapsAsObjects === undefined)
43
+ options.mapsAsObjects = true;
44
+ if (options.sequential && options.trusted !== false) {
45
+ options.trusted = true;
46
+ if (!options.structures && options.useRecords != false) {
47
+ options.structures = [];
48
+ if (!options.maxSharedStructures)
49
+ options.maxSharedStructures = 0;
50
+ }
51
+ }
52
+ if (options.structures)
53
+ options.structures.sharedLength = options.structures.length;
54
+ else if (options.getStructures) {
55
+ (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
56
+ options.structures.sharedLength = 0;
57
+ }
58
+ }
59
+ Object.assign(this, options);
60
+ }
61
+ unpack(source, end) {
62
+ if (src) {
63
+ // re-entrant execution, save the state and restore it after we do this unpack
64
+ return saveState(() => {
65
+ clearSource();
66
+ return this ? this.unpack(source, end) : Unpackr.prototype.unpack.call(defaultOptions, source, end)
67
+ })
68
+ }
69
+ srcEnd = end > -1 ? end : source.length;
70
+ position = 0;
71
+ srcStringEnd = 0;
72
+ srcString = null;
73
+ bundledStrings = null;
74
+ src = source;
75
+ // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
76
+ // technique for getting data from a database where it can be copied into an existing buffer instead of creating
77
+ // new ones
78
+ try {
79
+ dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
80
+ } catch(error) {
81
+ // if it doesn't have a buffer, maybe it is the wrong type of object
82
+ src = null;
83
+ if (source instanceof Uint8Array)
84
+ throw error
85
+ throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
86
+ }
87
+ if (this instanceof Unpackr) {
88
+ currentUnpackr = this;
89
+ if (this.structures) {
90
+ currentStructures = this.structures;
91
+ return checkedRead()
92
+ } else if (!currentStructures || currentStructures.length > 0) {
93
+ currentStructures = [];
94
+ }
95
+ } else {
96
+ currentUnpackr = defaultOptions;
97
+ if (!currentStructures || currentStructures.length > 0)
98
+ currentStructures = [];
99
+ }
100
+ return checkedRead()
101
+ }
102
+ unpackMultiple(source, forEach) {
103
+ let values, lastPosition = 0;
104
+ try {
105
+ sequentialMode = true;
106
+ let size = source.length;
107
+ let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
108
+ if (forEach) {
109
+ forEach(value);
110
+ while(position < size) {
111
+ lastPosition = position;
112
+ if (forEach(checkedRead()) === false) {
113
+ return
114
+ }
115
+ }
116
+ }
117
+ else {
118
+ values = [ value ];
119
+ while(position < size) {
120
+ lastPosition = position;
121
+ values.push(checkedRead());
122
+ }
123
+ return values
124
+ }
125
+ } catch(error) {
126
+ error.lastPosition = lastPosition;
127
+ error.values = values;
128
+ throw error
129
+ } finally {
130
+ sequentialMode = false;
131
+ clearSource();
132
+ }
133
+ }
134
+ _mergeStructures(loadedStructures, existingStructures) {
135
+ loadedStructures = loadedStructures || [];
136
+ for (let i = 0, l = loadedStructures.length; i < l; i++) {
137
+ let structure = loadedStructures[i];
138
+ if (structure) {
139
+ structure.isShared = true;
140
+ if (i >= 32)
141
+ structure.highByte = (i - 32) >> 5;
142
+ }
143
+ }
144
+ loadedStructures.sharedLength = loadedStructures.length;
145
+ for (let id in existingStructures || []) {
146
+ if (id >= 0) {
147
+ let structure = loadedStructures[id];
148
+ let existing = existingStructures[id];
149
+ if (existing) {
150
+ if (structure)
151
+ (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
152
+ loadedStructures[id] = existing;
153
+ }
154
+ }
155
+ }
156
+ return this.structures = loadedStructures
157
+ }
158
+ decode(source, end) {
159
+ return this.unpack(source, end)
160
+ }
161
+ }
162
+ function checkedRead() {
163
+ try {
164
+ if (!currentUnpackr.trusted && !sequentialMode) {
165
+ let sharedLength = currentStructures.sharedLength || 0;
166
+ if (sharedLength < currentStructures.length)
167
+ currentStructures.length = sharedLength;
168
+ }
169
+ let result = read();
170
+ if (bundledStrings) // bundled strings to skip past
171
+ position = bundledStrings.postBundlePosition;
172
+
173
+ if (position == srcEnd) {
174
+ // finished reading this source, cleanup references
175
+ if (currentStructures.restoreStructures)
176
+ restoreStructures();
177
+ currentStructures = null;
178
+ src = null;
179
+ if (referenceMap)
180
+ referenceMap = null;
181
+ } else if (position > srcEnd) {
182
+ // over read
183
+ throw new Error('Unexpected end of MessagePack data')
184
+ } else if (!sequentialMode) {
185
+ throw new Error('Data read, but end of buffer not reached ' + JSON.stringify(result).slice(0, 100))
186
+ }
187
+ // else more to read, but we are reading sequentially, so don't clear source yet
188
+ return result
189
+ } catch(error) {
190
+ if (currentStructures.restoreStructures)
191
+ restoreStructures();
192
+ clearSource();
193
+ if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {
194
+ error.incomplete = true;
195
+ }
196
+ throw error
197
+ }
198
+ }
199
+
200
+ function restoreStructures() {
201
+ for (let id in currentStructures.restoreStructures) {
202
+ currentStructures[id] = currentStructures.restoreStructures[id];
203
+ }
204
+ currentStructures.restoreStructures = null;
205
+ }
206
+
207
+ function read() {
208
+ let token = src[position++];
209
+ if (token < 0xa0) {
210
+ if (token < 0x80) {
211
+ if (token < 0x40)
212
+ return token
213
+ else {
214
+ let structure = currentStructures[token & 0x3f] ||
215
+ currentUnpackr.getStructures && loadStructures()[token & 0x3f];
216
+ if (structure) {
217
+ if (!structure.read) {
218
+ structure.read = createStructureReader(structure, token & 0x3f);
219
+ }
220
+ return structure.read()
221
+ } else
222
+ return token
223
+ }
224
+ } else if (token < 0x90) {
225
+ // map
226
+ token -= 0x80;
227
+ if (currentUnpackr.mapsAsObjects) {
228
+ let object = {};
229
+ for (let i = 0; i < token; i++) {
230
+ let key = readKey();
231
+ if (key === '__proto__')
232
+ key = '__proto_';
233
+ object[key] = read();
234
+ }
235
+ return object
236
+ } else {
237
+ let map = new Map();
238
+ for (let i = 0; i < token; i++) {
239
+ map.set(read(), read());
240
+ }
241
+ return map
242
+ }
243
+ } else {
244
+ token -= 0x90;
245
+ let array = new Array(token);
246
+ for (let i = 0; i < token; i++) {
247
+ array[i] = read();
248
+ }
249
+ return array
250
+ }
251
+ } else if (token < 0xc0) {
252
+ // fixstr
253
+ let length = token - 0xa0;
254
+ if (srcStringEnd >= position) {
255
+ return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
256
+ }
257
+ if (srcStringEnd == 0 && srcEnd < 140) {
258
+ // for small blocks, avoiding the overhead of the extract call is helpful
259
+ let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
260
+ if (string != null)
261
+ return string
262
+ }
263
+ return readFixedString(length)
264
+ } else {
265
+ let value;
266
+ switch (token) {
267
+ case 0xc0: return null
268
+ case 0xc1:
269
+ if (bundledStrings) {
270
+ value = read(); // followed by the length of the string in characters (not bytes!)
271
+ if (value > 0)
272
+ return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)
273
+ else
274
+ return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)
275
+ }
276
+ return C1; // "never-used", return special object to denote that
277
+ case 0xc2: return false
278
+ case 0xc3: return true
279
+ case 0xc4:
280
+ // bin 8
281
+ value = src[position++];
282
+ if (value === undefined)
283
+ throw new Error('Unexpected end of buffer')
284
+ return readBin(value)
285
+ case 0xc5:
286
+ // bin 16
287
+ value = dataView.getUint16(position);
288
+ position += 2;
289
+ return readBin(value)
290
+ case 0xc6:
291
+ // bin 32
292
+ value = dataView.getUint32(position);
293
+ position += 4;
294
+ return readBin(value)
295
+ case 0xc7:
296
+ // ext 8
297
+ return readExt(src[position++])
298
+ case 0xc8:
299
+ // ext 16
300
+ value = dataView.getUint16(position);
301
+ position += 2;
302
+ return readExt(value)
303
+ case 0xc9:
304
+ // ext 32
305
+ value = dataView.getUint32(position);
306
+ position += 4;
307
+ return readExt(value)
308
+ case 0xca:
309
+ value = dataView.getFloat32(position);
310
+ if (currentUnpackr.useFloat32 > 2) {
311
+ // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
312
+ let multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];
313
+ position += 4;
314
+ return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
315
+ }
316
+ position += 4;
317
+ return value
318
+ case 0xcb:
319
+ value = dataView.getFloat64(position);
320
+ position += 8;
321
+ return value
322
+ // uint handlers
323
+ case 0xcc:
324
+ return src[position++]
325
+ case 0xcd:
326
+ value = dataView.getUint16(position);
327
+ position += 2;
328
+ return value
329
+ case 0xce:
330
+ value = dataView.getUint32(position);
331
+ position += 4;
332
+ return value
333
+ case 0xcf:
334
+ if (currentUnpackr.int64AsNumber) {
335
+ value = dataView.getUint32(position) * 0x100000000;
336
+ value += dataView.getUint32(position + 4);
337
+ } else
338
+ value = dataView.getBigUint64(position);
339
+ position += 8;
340
+ return value
341
+
342
+ // int handlers
343
+ case 0xd0:
344
+ return dataView.getInt8(position++)
345
+ case 0xd1:
346
+ value = dataView.getInt16(position);
347
+ position += 2;
348
+ return value
349
+ case 0xd2:
350
+ value = dataView.getInt32(position);
351
+ position += 4;
352
+ return value
353
+ case 0xd3:
354
+ if (currentUnpackr.int64AsNumber) {
355
+ value = dataView.getInt32(position) * 0x100000000;
356
+ value += dataView.getUint32(position + 4);
357
+ } else
358
+ value = dataView.getBigInt64(position);
359
+ position += 8;
360
+ return value
361
+
362
+ case 0xd4:
363
+ // fixext 1
364
+ value = src[position++];
365
+ if (value == 0x72) {
366
+ return recordDefinition(src[position++] & 0x3f)
367
+ } else {
368
+ let extension = currentExtensions[value];
369
+ if (extension) {
370
+ if (extension.read) {
371
+ position++; // skip filler byte
372
+ return extension.read(read())
373
+ } else if (extension.noBuffer) {
374
+ position++; // skip filler byte
375
+ return extension()
376
+ } else
377
+ return extension(src.subarray(position, ++position))
378
+ } else
379
+ throw new Error('Unknown extension ' + value)
380
+ }
381
+ case 0xd5:
382
+ // fixext 2
383
+ value = src[position];
384
+ if (value == 0x72) {
385
+ position++;
386
+ return recordDefinition(src[position++] & 0x3f, src[position++])
387
+ } else
388
+ return readExt(2)
389
+ case 0xd6:
390
+ // fixext 4
391
+ return readExt(4)
392
+ case 0xd7:
393
+ // fixext 8
394
+ return readExt(8)
395
+ case 0xd8:
396
+ // fixext 16
397
+ return readExt(16)
398
+ case 0xd9:
399
+ // str 8
400
+ value = src[position++];
401
+ if (srcStringEnd >= position) {
402
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
403
+ }
404
+ return readString8(value)
405
+ case 0xda:
406
+ // str 16
407
+ value = dataView.getUint16(position);
408
+ position += 2;
409
+ if (srcStringEnd >= position) {
410
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
411
+ }
412
+ return readString16(value)
413
+ case 0xdb:
414
+ // str 32
415
+ value = dataView.getUint32(position);
416
+ position += 4;
417
+ if (srcStringEnd >= position) {
418
+ return srcString.slice(position - srcStringStart, (position += value) - srcStringStart)
419
+ }
420
+ return readString32(value)
421
+ case 0xdc:
422
+ // array 16
423
+ value = dataView.getUint16(position);
424
+ position += 2;
425
+ return readArray(value)
426
+ case 0xdd:
427
+ // array 32
428
+ value = dataView.getUint32(position);
429
+ position += 4;
430
+ return readArray(value)
431
+ case 0xde:
432
+ // map 16
433
+ value = dataView.getUint16(position);
434
+ position += 2;
435
+ return readMap(value)
436
+ case 0xdf:
437
+ // map 32
438
+ value = dataView.getUint32(position);
439
+ position += 4;
440
+ return readMap(value)
441
+ default: // negative int
442
+ if (token >= 0xe0)
443
+ return token - 0x100
444
+ if (token === undefined) {
445
+ let error = new Error('Unexpected end of MessagePack data');
446
+ error.incomplete = true;
447
+ throw error
448
+ }
449
+ throw new Error('Unknown MessagePack token ' + token)
450
+
451
+ }
452
+ }
453
+ }
454
+ const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
455
+ function createStructureReader(structure, firstId) {
456
+ function readObject() {
457
+ // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
458
+ if (readObject.count++ > inlineObjectReadThreshold) {
459
+ let readObject = structure.read = (new Function('r', 'return function(){return {' + structure.map(key => key === '__proto__' ? '__proto_:r()' :
460
+ validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}}'))(read);
461
+ if (structure.highByte === 0)
462
+ structure.read = createSecondByteReader(firstId, structure.read);
463
+ return readObject() // second byte is already read, if there is one so immediately read object
464
+ }
465
+ let object = {};
466
+ for (let i = 0, l = structure.length; i < l; i++) {
467
+ let key = structure[i];
468
+ if (key === '__proto__')
469
+ key = '__proto_';
470
+ object[key] = read();
471
+ }
472
+ return object
473
+ }
474
+ readObject.count = 0;
475
+ if (structure.highByte === 0) {
476
+ return createSecondByteReader(firstId, readObject)
477
+ }
478
+ return readObject
479
+ }
480
+
481
+ const createSecondByteReader = (firstId, read0) => {
482
+ return function() {
483
+ let highByte = src[position++];
484
+ if (highByte === 0)
485
+ return read0()
486
+ let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
487
+ let structure = currentStructures[id] || loadStructures()[id];
488
+ if (!structure) {
489
+ throw new Error('Record id is not defined for ' + id)
490
+ }
491
+ if (!structure.read)
492
+ structure.read = createStructureReader(structure, firstId);
493
+ return structure.read()
494
+ }
495
+ };
496
+
497
+ function loadStructures() {
498
+ let loadedStructures = saveState(() => {
499
+ // save the state in case getStructures modifies our buffer
500
+ src = null;
501
+ return currentUnpackr.getStructures()
502
+ });
503
+ return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
504
+ }
505
+
506
+ var readFixedString = readStringJS;
507
+ var readString8 = readStringJS;
508
+ var readString16 = readStringJS;
509
+ var readString32 = readStringJS;
510
+ let isNativeAccelerationEnabled = false;
511
+ function readStringJS(length) {
512
+ let result;
513
+ if (length < 16) {
514
+ if (result = shortStringInJS(length))
515
+ return result
516
+ }
517
+ if (length > 64 && decoder)
518
+ return decoder.decode(src.subarray(position, position += length))
519
+ const end = position + length;
520
+ const units = [];
521
+ result = '';
522
+ while (position < end) {
523
+ const byte1 = src[position++];
524
+ if ((byte1 & 0x80) === 0) {
525
+ // 1 byte
526
+ units.push(byte1);
527
+ } else if ((byte1 & 0xe0) === 0xc0) {
528
+ // 2 bytes
529
+ const byte2 = src[position++] & 0x3f;
530
+ units.push(((byte1 & 0x1f) << 6) | byte2);
531
+ } else if ((byte1 & 0xf0) === 0xe0) {
532
+ // 3 bytes
533
+ const byte2 = src[position++] & 0x3f;
534
+ const byte3 = src[position++] & 0x3f;
535
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
536
+ } else if ((byte1 & 0xf8) === 0xf0) {
537
+ // 4 bytes
538
+ const byte2 = src[position++] & 0x3f;
539
+ const byte3 = src[position++] & 0x3f;
540
+ const byte4 = src[position++] & 0x3f;
541
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
542
+ if (unit > 0xffff) {
543
+ unit -= 0x10000;
544
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
545
+ unit = 0xdc00 | (unit & 0x3ff);
546
+ }
547
+ units.push(unit);
548
+ } else {
549
+ units.push(byte1);
550
+ }
551
+
552
+ if (units.length >= 0x1000) {
553
+ result += fromCharCode.apply(String, units);
554
+ units.length = 0;
555
+ }
556
+ }
557
+
558
+ if (units.length > 0) {
559
+ result += fromCharCode.apply(String, units);
560
+ }
561
+
562
+ return result
563
+ }
564
+
565
+ function readArray(length) {
566
+ let array = new Array(length);
567
+ for (let i = 0; i < length; i++) {
568
+ array[i] = read();
569
+ }
570
+ return array
571
+ }
572
+
573
+ function readMap(length) {
574
+ if (currentUnpackr.mapsAsObjects) {
575
+ let object = {};
576
+ for (let i = 0; i < length; i++) {
577
+ let key = readKey();
578
+ if (key === '__proto__')
579
+ key = '__proto_';
580
+ object[key] = read();
581
+ }
582
+ return object
583
+ } else {
584
+ let map = new Map();
585
+ for (let i = 0; i < length; i++) {
586
+ map.set(read(), read());
587
+ }
588
+ return map
589
+ }
590
+ }
591
+
592
+ var fromCharCode = String.fromCharCode;
593
+ function longStringInJS(length) {
594
+ let start = position;
595
+ let bytes = new Array(length);
596
+ for (let i = 0; i < length; i++) {
597
+ const byte = src[position++];
598
+ if ((byte & 0x80) > 0) {
599
+ position = start;
600
+ return
601
+ }
602
+ bytes[i] = byte;
603
+ }
604
+ return fromCharCode.apply(String, bytes)
605
+ }
606
+ function shortStringInJS(length) {
607
+ if (length < 4) {
608
+ if (length < 2) {
609
+ if (length === 0)
610
+ return ''
611
+ else {
612
+ let a = src[position++];
613
+ if ((a & 0x80) > 1) {
614
+ position -= 1;
615
+ return
616
+ }
617
+ return fromCharCode(a)
618
+ }
619
+ } else {
620
+ let a = src[position++];
621
+ let b = src[position++];
622
+ if ((a & 0x80) > 0 || (b & 0x80) > 0) {
623
+ position -= 2;
624
+ return
625
+ }
626
+ if (length < 3)
627
+ return fromCharCode(a, b)
628
+ let c = src[position++];
629
+ if ((c & 0x80) > 0) {
630
+ position -= 3;
631
+ return
632
+ }
633
+ return fromCharCode(a, b, c)
634
+ }
635
+ } else {
636
+ let a = src[position++];
637
+ let b = src[position++];
638
+ let c = src[position++];
639
+ let d = src[position++];
640
+ if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
641
+ position -= 4;
642
+ return
643
+ }
644
+ if (length < 6) {
645
+ if (length === 4)
646
+ return fromCharCode(a, b, c, d)
647
+ else {
648
+ let e = src[position++];
649
+ if ((e & 0x80) > 0) {
650
+ position -= 5;
651
+ return
652
+ }
653
+ return fromCharCode(a, b, c, d, e)
654
+ }
655
+ } else if (length < 8) {
656
+ let e = src[position++];
657
+ let f = src[position++];
658
+ if ((e & 0x80) > 0 || (f & 0x80) > 0) {
659
+ position -= 6;
660
+ return
661
+ }
662
+ if (length < 7)
663
+ return fromCharCode(a, b, c, d, e, f)
664
+ let g = src[position++];
665
+ if ((g & 0x80) > 0) {
666
+ position -= 7;
667
+ return
668
+ }
669
+ return fromCharCode(a, b, c, d, e, f, g)
670
+ } else {
671
+ let e = src[position++];
672
+ let f = src[position++];
673
+ let g = src[position++];
674
+ let h = src[position++];
675
+ if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
676
+ position -= 8;
677
+ return
678
+ }
679
+ if (length < 10) {
680
+ if (length === 8)
681
+ return fromCharCode(a, b, c, d, e, f, g, h)
682
+ else {
683
+ let i = src[position++];
684
+ if ((i & 0x80) > 0) {
685
+ position -= 9;
686
+ return
687
+ }
688
+ return fromCharCode(a, b, c, d, e, f, g, h, i)
689
+ }
690
+ } else if (length < 12) {
691
+ let i = src[position++];
692
+ let j = src[position++];
693
+ if ((i & 0x80) > 0 || (j & 0x80) > 0) {
694
+ position -= 10;
695
+ return
696
+ }
697
+ if (length < 11)
698
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j)
699
+ let k = src[position++];
700
+ if ((k & 0x80) > 0) {
701
+ position -= 11;
702
+ return
703
+ }
704
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
705
+ } else {
706
+ let i = src[position++];
707
+ let j = src[position++];
708
+ let k = src[position++];
709
+ let l = src[position++];
710
+ if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
711
+ position -= 12;
712
+ return
713
+ }
714
+ if (length < 14) {
715
+ if (length === 12)
716
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
717
+ else {
718
+ let m = src[position++];
719
+ if ((m & 0x80) > 0) {
720
+ position -= 13;
721
+ return
722
+ }
723
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
724
+ }
725
+ } else {
726
+ let m = src[position++];
727
+ let n = src[position++];
728
+ if ((m & 0x80) > 0 || (n & 0x80) > 0) {
729
+ position -= 14;
730
+ return
731
+ }
732
+ if (length < 15)
733
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
734
+ let o = src[position++];
735
+ if ((o & 0x80) > 0) {
736
+ position -= 15;
737
+ return
738
+ }
739
+ return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
740
+ }
741
+ }
742
+ }
743
+ }
744
+ }
745
+
746
+ function readOnlyJSString() {
747
+ let token = src[position++];
748
+ let length;
749
+ if (token < 0xc0) {
750
+ // fixstr
751
+ length = token - 0xa0;
752
+ } else {
753
+ switch(token) {
754
+ case 0xd9:
755
+ // str 8
756
+ length = src[position++];
757
+ break
758
+ case 0xda:
759
+ // str 16
760
+ length = dataView.getUint16(position);
761
+ position += 2;
762
+ break
763
+ case 0xdb:
764
+ // str 32
765
+ length = dataView.getUint32(position);
766
+ position += 4;
767
+ break
768
+ default:
769
+ throw new Error('Expected string')
770
+ }
771
+ }
772
+ return readStringJS(length)
773
+ }
774
+
775
+
776
+ function readBin(length) {
777
+ return currentUnpackr.copyBuffers ?
778
+ // specifically use the copying slice (not the node one)
779
+ Uint8Array.prototype.slice.call(src, position, position += length) :
780
+ src.subarray(position, position += length)
781
+ }
782
+ function readExt(length) {
783
+ let type = src[position++];
784
+ if (currentExtensions[type]) {
785
+ return currentExtensions[type](src.subarray(position, position += length))
786
+ }
787
+ else
788
+ throw new Error('Unknown extension type ' + type)
789
+ }
790
+
791
+ var keyCache = new Array(4096);
792
+ function readKey() {
793
+ let length = src[position++];
794
+ if (length >= 0xa0 && length < 0xc0) {
795
+ // fixstr, potentially use key cache
796
+ length = length - 0xa0;
797
+ if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
798
+ return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
799
+ else if (!(srcStringEnd == 0 && srcEnd < 180))
800
+ return readFixedString(length)
801
+ } else { // not cacheable, go back and do a standard read
802
+ position--;
803
+ return read()
804
+ }
805
+ let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;
806
+ let entry = keyCache[key];
807
+ let checkPosition = position;
808
+ let end = position + length - 3;
809
+ let chunk;
810
+ let i = 0;
811
+ if (entry && entry.bytes == length) {
812
+ while (checkPosition < end) {
813
+ chunk = dataView.getUint32(checkPosition);
814
+ if (chunk != entry[i++]) {
815
+ checkPosition = 0x70000000;
816
+ break
817
+ }
818
+ checkPosition += 4;
819
+ }
820
+ end += 3;
821
+ while (checkPosition < end) {
822
+ chunk = src[checkPosition++];
823
+ if (chunk != entry[i++]) {
824
+ checkPosition = 0x70000000;
825
+ break
826
+ }
827
+ }
828
+ if (checkPosition === end) {
829
+ position = checkPosition;
830
+ return entry.string
831
+ }
832
+ end -= 3;
833
+ checkPosition = position;
834
+ }
835
+ entry = [];
836
+ keyCache[key] = entry;
837
+ entry.bytes = length;
838
+ while (checkPosition < end) {
839
+ chunk = dataView.getUint32(checkPosition);
840
+ entry.push(chunk);
841
+ checkPosition += 4;
842
+ }
843
+ end += 3;
844
+ while (checkPosition < end) {
845
+ chunk = src[checkPosition++];
846
+ entry.push(chunk);
847
+ }
848
+ // for small blocks, avoiding the overhead of the extract call is helpful
849
+ let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
850
+ if (string != null)
851
+ return entry.string = string
852
+ return entry.string = readFixedString(length)
853
+ }
854
+
855
+ // the registration of the record definition extension (as "r")
856
+ const recordDefinition = (id, highByte) => {
857
+ var structure = read();
858
+ let firstByte = id;
859
+ if (highByte !== undefined) {
860
+ id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
861
+ structure.highByte = highByte;
862
+ }
863
+ let existingStructure = currentStructures[id];
864
+ if (existingStructure && existingStructure.isShared) {
865
+ (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
866
+ }
867
+ currentStructures[id] = structure;
868
+ structure.read = createStructureReader(structure, firstByte);
869
+ return structure.read()
870
+ };
871
+ currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
872
+ currentExtensions[0].noBuffer = true;
873
+
874
+ currentExtensions[0x65] = () => {
875
+ let data = read();
876
+ return (globalThis[data[0]] || Error)(data[1])
877
+ };
878
+
879
+ currentExtensions[0x69] = (data) => {
880
+ // id extension (for structured clones)
881
+ let id = dataView.getUint32(position - 4);
882
+ if (!referenceMap)
883
+ referenceMap = new Map();
884
+ let token = src[position];
885
+ let target;
886
+ // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
887
+ // ahead past references to record structure definitions
888
+ if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
889
+ target = [];
890
+ else
891
+ target = {};
892
+
893
+ let refEntry = { target }; // a placeholder object
894
+ referenceMap.set(id, refEntry);
895
+ let targetProperties = read(); // read the next value as the target object to id
896
+ if (refEntry.used) // there is a cycle, so we have to assign properties to original target
897
+ return Object.assign(target, targetProperties)
898
+ refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
899
+ return targetProperties // no cycle, can just use the returned read object
900
+ };
901
+
902
+ currentExtensions[0x70] = (data) => {
903
+ // pointer extension (for structured clones)
904
+ let id = dataView.getUint32(position - 4);
905
+ let refEntry = referenceMap.get(id);
906
+ refEntry.used = true;
907
+ return refEntry.target
908
+ };
909
+
910
+ currentExtensions[0x73] = () => new Set(read());
911
+
912
+ const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
913
+
914
+ currentExtensions[0x74] = (data) => {
915
+ let typeCode = data[0];
916
+ let typedArrayName = typedArrays[typeCode];
917
+ if (!typedArrayName)
918
+ throw new Error('Could not find typed array for code ' + typeCode)
919
+ // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
920
+ return new globalThis[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
921
+ };
922
+ currentExtensions[0x78] = () => {
923
+ let data = read();
924
+ return new RegExp(data[0], data[1])
925
+ };
926
+ const TEMP_BUNDLE = [];
927
+ currentExtensions[0x62] = (data) => {
928
+ let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
929
+ let dataPosition = position;
930
+ position += dataSize - data.length;
931
+ bundledStrings = TEMP_BUNDLE;
932
+ bundledStrings = [readOnlyJSString(), readOnlyJSString()];
933
+ bundledStrings.position0 = 0;
934
+ bundledStrings.position1 = 0;
935
+ bundledStrings.postBundlePosition = position;
936
+ position = dataPosition;
937
+ return read()
938
+ };
939
+
940
+ currentExtensions[0xff] = (data) => {
941
+ // 32-bit date extension
942
+ if (data.length == 4)
943
+ return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
944
+ else if (data.length == 8)
945
+ return new Date(
946
+ ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
947
+ ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
948
+ else if (data.length == 12)// TODO: Implement support for negative
949
+ return new Date(
950
+ ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
951
+ (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
952
+ else
953
+ return new Date('invalid')
954
+ }; // notepack defines extension 0 to mean undefined, so use that as the default here
955
+ // registration of bulk record definition?
956
+ // currentExtensions[0x52] = () =>
957
+
958
+ function saveState(callback) {
959
+ let savedSrcEnd = srcEnd;
960
+ let savedPosition = position;
961
+ let savedSrcStringStart = srcStringStart;
962
+ let savedSrcStringEnd = srcStringEnd;
963
+ let savedSrcString = srcString;
964
+ let savedReferenceMap = referenceMap;
965
+ let savedBundledStrings = bundledStrings;
966
+
967
+ // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
968
+ let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
969
+ let savedStructures = currentStructures;
970
+ let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
971
+ let savedPackr = currentUnpackr;
972
+ let savedSequentialMode = sequentialMode;
973
+ let value = callback();
974
+ srcEnd = savedSrcEnd;
975
+ position = savedPosition;
976
+ srcStringStart = savedSrcStringStart;
977
+ srcStringEnd = savedSrcStringEnd;
978
+ srcString = savedSrcString;
979
+ referenceMap = savedReferenceMap;
980
+ bundledStrings = savedBundledStrings;
981
+ src = savedSrc;
982
+ sequentialMode = savedSequentialMode;
983
+ currentStructures = savedStructures;
984
+ currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
985
+ currentUnpackr = savedPackr;
986
+ dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
987
+ return value
988
+ }
989
+ function clearSource() {
990
+ src = null;
991
+ referenceMap = null;
992
+ currentStructures = null;
993
+ }
994
+
995
+ function addExtension(extension) {
996
+ if (extension.unpack)
997
+ currentExtensions[extension.type] = extension.unpack;
998
+ else
999
+ currentExtensions[extension.type] = extension;
1000
+ }
1001
+
1002
+ const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1003
+ for (let i = 0; i < 256; i++) {
1004
+ mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1005
+ }
1006
+ const Decoder = Unpackr;
1007
+ var defaultUnpackr = new Unpackr({ useRecords: false });
1008
+ const unpack = defaultUnpackr.unpack;
1009
+ const unpackMultiple = defaultUnpackr.unpackMultiple;
1010
+ const decode = defaultUnpackr.unpack;
1011
+ const FLOAT32_OPTIONS = {
1012
+ NEVER: 0,
1013
+ ALWAYS: 1,
1014
+ DECIMAL_ROUND: 3,
1015
+ DECIMAL_FIT: 4
1016
+ };
1017
+ let f32Array = new Float32Array(1);
1018
+ let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
1019
+ function roundFloat32(float32Number) {
1020
+ f32Array[0] = float32Number;
1021
+ let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
1022
+ return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
1023
+ }
1024
+
1025
+ let textEncoder;
1026
+ try {
1027
+ textEncoder = new TextEncoder();
1028
+ } catch (error) {}
1029
+ let extensions, extensionClasses;
1030
+ const hasNodeBuffer = typeof Buffer !== 'undefined';
1031
+ const ByteArrayAllocate = hasNodeBuffer ?
1032
+ function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1033
+ const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1034
+ const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1035
+ let target, keysTarget;
1036
+ let targetView;
1037
+ let position$1 = 0;
1038
+ let safeEnd;
1039
+ let bundledStrings$1 = null;
1040
+ const MAX_BUNDLE_SIZE = 0xf000;
1041
+ const hasNonLatin = /[\u0080-\uFFFF]/;
1042
+ const RECORD_SYMBOL = Symbol('record-id');
1043
+ class Packr extends Unpackr {
1044
+ constructor(options) {
1045
+ super(options);
1046
+ this.offset = 0;
1047
+ let start;
1048
+ let hasSharedUpdate;
1049
+ let structures;
1050
+ let referenceMap;
1051
+ let lastSharedStructuresLength = 0;
1052
+ let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1053
+ return target.utf8Write(string, position, 0xffffffff)
1054
+ } : (textEncoder && textEncoder.encodeInto) ?
1055
+ function(string, position) {
1056
+ return textEncoder.encodeInto(string, target.subarray(position)).written
1057
+ } : false;
1058
+
1059
+ let packr = this;
1060
+ if (!options)
1061
+ options = {};
1062
+ let isSequential = options && options.sequential;
1063
+ let hasSharedStructures = options.structures || options.saveStructures;
1064
+ let maxSharedStructures = options.maxSharedStructures;
1065
+ if (maxSharedStructures == null)
1066
+ maxSharedStructures = hasSharedStructures ? 32 : 0;
1067
+ if (maxSharedStructures > 8160)
1068
+ throw new Error('Maximum maxSharedStructure is 8160')
1069
+ if (options.structuredClone && options.moreTypes == undefined) {
1070
+ options.moreTypes = true;
1071
+ }
1072
+ let maxOwnStructures = options.maxOwnStructures;
1073
+ if (maxOwnStructures == null)
1074
+ maxOwnStructures = hasSharedStructures ? 32 : 64;
1075
+ if (!this.structures && options.useRecords != false)
1076
+ this.structures = [];
1077
+ // two byte record ids for shared structures
1078
+ let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1079
+ let sharedLimitId = maxSharedStructures + 0x40;
1080
+ let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1081
+ if (maxStructureId > 8256) {
1082
+ throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1083
+ }
1084
+ let recordIdsToRemove = [];
1085
+ let transitionsCount = 0;
1086
+ let serializationsSinceTransitionRebuild = 0;
1087
+
1088
+ this.pack = this.encode = function(value, encodeOptions) {
1089
+ if (!target) {
1090
+ target = new ByteArrayAllocate(8192);
1091
+ targetView = new DataView(target.buffer, 0, 8192);
1092
+ position$1 = 0;
1093
+ }
1094
+ safeEnd = target.length - 10;
1095
+ if (safeEnd - position$1 < 0x800) {
1096
+ // don't start too close to the end,
1097
+ target = new ByteArrayAllocate(target.length);
1098
+ targetView = new DataView(target.buffer, 0, target.length);
1099
+ safeEnd = target.length - 10;
1100
+ position$1 = 0;
1101
+ } else
1102
+ position$1 = (position$1 + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1103
+ start = position$1;
1104
+ referenceMap = packr.structuredClone ? new Map() : null;
1105
+ if (packr.bundleStrings && typeof value !== 'string') {
1106
+ bundledStrings$1 = [];
1107
+ bundledStrings$1.size = Infinity; // force a new bundle start on first string
1108
+ } else
1109
+ bundledStrings$1 = null;
1110
+ structures = packr.structures;
1111
+ if (structures) {
1112
+ if (structures.uninitialized)
1113
+ structures = packr._mergeStructures(packr.getStructures());
1114
+ let sharedLength = structures.sharedLength || 0;
1115
+ if (sharedLength > maxSharedStructures) {
1116
+ //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1117
+ throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1118
+ }
1119
+ if (!structures.transitions) {
1120
+ // rebuild our structure transitions
1121
+ structures.transitions = Object.create(null);
1122
+ for (let i = 0; i < sharedLength; i++) {
1123
+ let keys = structures[i];
1124
+ if (!keys)
1125
+ continue
1126
+ let nextTransition, transition = structures.transitions;
1127
+ for (let j = 0, l = keys.length; j < l; j++) {
1128
+ let key = keys[j];
1129
+ nextTransition = transition[key];
1130
+ if (!nextTransition) {
1131
+ nextTransition = transition[key] = Object.create(null);
1132
+ }
1133
+ transition = nextTransition;
1134
+ }
1135
+ transition[RECORD_SYMBOL] = i + 0x40;
1136
+ }
1137
+ lastSharedStructuresLength = sharedLength;
1138
+ }
1139
+ if (!isSequential) {
1140
+ structures.nextId = sharedLength + 0x40;
1141
+ }
1142
+ }
1143
+ if (hasSharedUpdate)
1144
+ hasSharedUpdate = false;
1145
+ try {
1146
+ pack(value);
1147
+ if (bundledStrings$1) {
1148
+ writeBundles(start, pack);
1149
+ }
1150
+ packr.offset = position$1; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1151
+ if (referenceMap && referenceMap.idsToInsert) {
1152
+ position$1 += referenceMap.idsToInsert.length * 6;
1153
+ if (position$1 > safeEnd)
1154
+ makeRoom(position$1);
1155
+ packr.offset = position$1;
1156
+ let serialized = insertIds(target.subarray(start, position$1), referenceMap.idsToInsert);
1157
+ referenceMap = null;
1158
+ return serialized
1159
+ }
1160
+ if (encodeOptions & REUSE_BUFFER_MODE) {
1161
+ target.start = start;
1162
+ target.end = position$1;
1163
+ return target
1164
+ }
1165
+ return target.subarray(start, position$1) // position can change if we call pack again in saveStructures, so we get the buffer now
1166
+ } finally {
1167
+ if (structures) {
1168
+ if (serializationsSinceTransitionRebuild < 10)
1169
+ serializationsSinceTransitionRebuild++;
1170
+ let sharedLength = structures.sharedLength || maxSharedStructures;
1171
+ if (structures.length > sharedLength)
1172
+ structures.length = sharedLength;
1173
+ if (transitionsCount > 10000) {
1174
+ // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1175
+ structures.transitions = null;
1176
+ serializationsSinceTransitionRebuild = 0;
1177
+ transitionsCount = 0;
1178
+ if (recordIdsToRemove.length > 0)
1179
+ recordIdsToRemove = [];
1180
+ } else if (recordIdsToRemove.length > 0 && !isSequential) {
1181
+ for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1182
+ recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1183
+ }
1184
+ recordIdsToRemove = [];
1185
+ }
1186
+ if (hasSharedUpdate && packr.saveStructures) {
1187
+ // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1188
+ let returnBuffer = target.subarray(start, position$1);
1189
+ if (packr.saveStructures(structures, lastSharedStructuresLength) === false) {
1190
+ // get updated structures and try again if the update failed
1191
+ packr._mergeStructures(packr.getStructures());
1192
+ return packr.pack(value)
1193
+ }
1194
+ lastSharedStructuresLength = sharedLength;
1195
+ return returnBuffer
1196
+ }
1197
+ }
1198
+ if (encodeOptions & RESET_BUFFER_MODE)
1199
+ position$1 = start;
1200
+ }
1201
+ };
1202
+ const pack = (value) => {
1203
+ if (position$1 > safeEnd)
1204
+ target = makeRoom(position$1);
1205
+
1206
+ var type = typeof value;
1207
+ var length;
1208
+ if (type === 'string') {
1209
+ let strLength = value.length;
1210
+ if (bundledStrings$1 && strLength >= 4 && strLength < 0x1000) {
1211
+ if ((bundledStrings$1.size += strLength) > MAX_BUNDLE_SIZE) {
1212
+ let extStart;
1213
+ let maxBytes = (bundledStrings$1[0] ? bundledStrings$1[0].length * 3 + bundledStrings$1[1].length : 0) + 10;
1214
+ if (position$1 + maxBytes > safeEnd)
1215
+ target = makeRoom(position$1 + maxBytes);
1216
+ if (bundledStrings$1.position) { // here we use the 0x62 extension to write the last bundle and reserve sapce for the reference pointer to the next/current bundle
1217
+ target[position$1] = 0xc8; // ext 16
1218
+ position$1 += 3; // reserve for the writing bundle size
1219
+ target[position$1++] = 0x62; // 'b'
1220
+ extStart = position$1 - start;
1221
+ position$1 += 4; // reserve for writing bundle reference
1222
+ writeBundles(start, pack); // write the last bundles
1223
+ targetView.setUint16(extStart + start - 3, position$1 - start - extStart);
1224
+ } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
1225
+ target[position$1++] = 0xd6; // fixext 4
1226
+ target[position$1++] = 0x62; // 'b'
1227
+ extStart = position$1 - start;
1228
+ position$1 += 4; // reserve for writing bundle reference
1229
+ }
1230
+ bundledStrings$1 = ['', '']; // create new ones
1231
+ bundledStrings$1.size = 0;
1232
+ bundledStrings$1.position = extStart;
1233
+ }
1234
+ let twoByte = hasNonLatin.test(value);
1235
+ bundledStrings$1[twoByte ? 0 : 1] += value;
1236
+ target[position$1++] = 0xc1;
1237
+ pack(twoByte ? -strLength : strLength);
1238
+ return
1239
+ }
1240
+ let headerSize;
1241
+ // first we estimate the header size, so we can write to the correct location
1242
+ if (strLength < 0x20) {
1243
+ headerSize = 1;
1244
+ } else if (strLength < 0x100) {
1245
+ headerSize = 2;
1246
+ } else if (strLength < 0x10000) {
1247
+ headerSize = 3;
1248
+ } else {
1249
+ headerSize = 5;
1250
+ }
1251
+ let maxBytes = strLength * 3;
1252
+ if (position$1 + maxBytes > safeEnd)
1253
+ target = makeRoom(position$1 + maxBytes);
1254
+
1255
+ if (strLength < 0x40 || !encodeUtf8) {
1256
+ let i, c1, c2, strPosition = position$1 + headerSize;
1257
+ for (i = 0; i < strLength; i++) {
1258
+ c1 = value.charCodeAt(i);
1259
+ if (c1 < 0x80) {
1260
+ target[strPosition++] = c1;
1261
+ } else if (c1 < 0x800) {
1262
+ target[strPosition++] = c1 >> 6 | 0xc0;
1263
+ target[strPosition++] = c1 & 0x3f | 0x80;
1264
+ } else if (
1265
+ (c1 & 0xfc00) === 0xd800 &&
1266
+ ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1267
+ ) {
1268
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1269
+ i++;
1270
+ target[strPosition++] = c1 >> 18 | 0xf0;
1271
+ target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1272
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1273
+ target[strPosition++] = c1 & 0x3f | 0x80;
1274
+ } else {
1275
+ target[strPosition++] = c1 >> 12 | 0xe0;
1276
+ target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1277
+ target[strPosition++] = c1 & 0x3f | 0x80;
1278
+ }
1279
+ }
1280
+ length = strPosition - position$1 - headerSize;
1281
+ } else {
1282
+ length = encodeUtf8(value, position$1 + headerSize);
1283
+ }
1284
+
1285
+ if (length < 0x20) {
1286
+ target[position$1++] = 0xa0 | length;
1287
+ } else if (length < 0x100) {
1288
+ if (headerSize < 2) {
1289
+ target.copyWithin(position$1 + 2, position$1 + 1, position$1 + 1 + length);
1290
+ }
1291
+ target[position$1++] = 0xd9;
1292
+ target[position$1++] = length;
1293
+ } else if (length < 0x10000) {
1294
+ if (headerSize < 3) {
1295
+ target.copyWithin(position$1 + 3, position$1 + 2, position$1 + 2 + length);
1296
+ }
1297
+ target[position$1++] = 0xda;
1298
+ target[position$1++] = length >> 8;
1299
+ target[position$1++] = length & 0xff;
1300
+ } else {
1301
+ if (headerSize < 5) {
1302
+ target.copyWithin(position$1 + 5, position$1 + 3, position$1 + 3 + length);
1303
+ }
1304
+ target[position$1++] = 0xdb;
1305
+ targetView.setUint32(position$1, length);
1306
+ position$1 += 4;
1307
+ }
1308
+ position$1 += length;
1309
+ } else if (type === 'number') {
1310
+ if (value >>> 0 === value) {// positive integer, 32-bit or less
1311
+ // positive uint
1312
+ if (value < 0x40 || (value < 0x80 && this.useRecords === false)) {
1313
+ target[position$1++] = value;
1314
+ } else if (value < 0x100) {
1315
+ target[position$1++] = 0xcc;
1316
+ target[position$1++] = value;
1317
+ } else if (value < 0x10000) {
1318
+ target[position$1++] = 0xcd;
1319
+ target[position$1++] = value >> 8;
1320
+ target[position$1++] = value & 0xff;
1321
+ } else {
1322
+ target[position$1++] = 0xce;
1323
+ targetView.setUint32(position$1, value);
1324
+ position$1 += 4;
1325
+ }
1326
+ } else if (value >> 0 === value) { // negative integer
1327
+ if (value >= -0x20) {
1328
+ target[position$1++] = 0x100 + value;
1329
+ } else if (value >= -0x80) {
1330
+ target[position$1++] = 0xd0;
1331
+ target[position$1++] = value + 0x100;
1332
+ } else if (value >= -0x8000) {
1333
+ target[position$1++] = 0xd1;
1334
+ targetView.setInt16(position$1, value);
1335
+ position$1 += 2;
1336
+ } else {
1337
+ target[position$1++] = 0xd2;
1338
+ targetView.setInt32(position$1, value);
1339
+ position$1 += 4;
1340
+ }
1341
+ } else {
1342
+ let useFloat32;
1343
+ if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1344
+ target[position$1++] = 0xca;
1345
+ targetView.setFloat32(position$1, value);
1346
+ let xShifted;
1347
+ if (useFloat32 < 4 ||
1348
+ // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1349
+ ((xShifted = value * mult10[((target[position$1] & 0x7f) << 1) | (target[position$1 + 1] >> 7)]) >> 0) === xShifted) {
1350
+ position$1 += 4;
1351
+ return
1352
+ } else
1353
+ position$1--; // move back into position for writing a double
1354
+ }
1355
+ target[position$1++] = 0xcb;
1356
+ targetView.setFloat64(position$1, value);
1357
+ position$1 += 8;
1358
+ }
1359
+ } else if (type === 'object') {
1360
+ if (!value)
1361
+ target[position$1++] = 0xc0;
1362
+ else {
1363
+ if (referenceMap) {
1364
+ let referee = referenceMap.get(value);
1365
+ if (referee) {
1366
+ if (!referee.id) {
1367
+ let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1368
+ referee.id = idsToInsert.push(referee);
1369
+ }
1370
+ target[position$1++] = 0xd6; // fixext 4
1371
+ target[position$1++] = 0x70; // "p" for pointer
1372
+ targetView.setUint32(position$1, referee.id);
1373
+ position$1 += 4;
1374
+ return
1375
+ } else
1376
+ referenceMap.set(value, { offset: position$1 - start });
1377
+ }
1378
+ let constructor = value.constructor;
1379
+ if (constructor === Object) {
1380
+ writeObject(value, true);
1381
+ } else if (constructor === Array) {
1382
+ length = value.length;
1383
+ if (length < 0x10) {
1384
+ target[position$1++] = 0x90 | length;
1385
+ } else if (length < 0x10000) {
1386
+ target[position$1++] = 0xdc;
1387
+ target[position$1++] = length >> 8;
1388
+ target[position$1++] = length & 0xff;
1389
+ } else {
1390
+ target[position$1++] = 0xdd;
1391
+ targetView.setUint32(position$1, length);
1392
+ position$1 += 4;
1393
+ }
1394
+ for (let i = 0; i < length; i++) {
1395
+ pack(value[i]);
1396
+ }
1397
+ } else if (constructor === Map) {
1398
+ length = value.size;
1399
+ if (length < 0x10) {
1400
+ target[position$1++] = 0x80 | length;
1401
+ } else if (length < 0x10000) {
1402
+ target[position$1++] = 0xde;
1403
+ target[position$1++] = length >> 8;
1404
+ target[position$1++] = length & 0xff;
1405
+ } else {
1406
+ target[position$1++] = 0xdf;
1407
+ targetView.setUint32(position$1, length);
1408
+ position$1 += 4;
1409
+ }
1410
+ for (let [ key, entryValue ] of value) {
1411
+ pack(key);
1412
+ pack(entryValue);
1413
+ }
1414
+ } else {
1415
+ for (let i = 0, l = extensions.length; i < l; i++) {
1416
+ let extensionClass = extensionClasses[i];
1417
+ if (value instanceof extensionClass) {
1418
+ let extension = extensions[i];
1419
+ if (extension.write) {
1420
+ if (extension.type) {
1421
+ target[position$1++] = 0xd4; // one byte "tag" extension
1422
+ target[position$1++] = extension.type;
1423
+ target[position$1++] = 0;
1424
+ }
1425
+ pack(extension.write.call(this, value));
1426
+ return
1427
+ }
1428
+ let currentTarget = target;
1429
+ let currentTargetView = targetView;
1430
+ let currentPosition = position$1;
1431
+ target = null;
1432
+ let result;
1433
+ try {
1434
+ result = extension.pack.call(this, value, (size) => {
1435
+ // restore target and use it
1436
+ target = currentTarget;
1437
+ currentTarget = null;
1438
+ position$1 += size;
1439
+ if (position$1 > safeEnd)
1440
+ makeRoom(position$1);
1441
+ return {
1442
+ target, targetView, position: position$1 - size
1443
+ }
1444
+ }, pack);
1445
+ } finally {
1446
+ // restore current target information (unless already restored)
1447
+ if (currentTarget) {
1448
+ target = currentTarget;
1449
+ targetView = currentTargetView;
1450
+ position$1 = currentPosition;
1451
+ safeEnd = target.length - 10;
1452
+ }
1453
+ }
1454
+ if (result) {
1455
+ if (result.length + position$1 > safeEnd)
1456
+ makeRoom(result.length + position$1);
1457
+ position$1 = writeExtensionData(result, target, position$1, extension.type);
1458
+ }
1459
+ return
1460
+ }
1461
+ }
1462
+ // no extension found, write as object
1463
+ writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks
1464
+ }
1465
+ }
1466
+ } else if (type === 'boolean') {
1467
+ target[position$1++] = value ? 0xc3 : 0xc2;
1468
+ } else if (type === 'bigint') {
1469
+ if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
1470
+ // use a signed int as long as it fits
1471
+ target[position$1++] = 0xd3;
1472
+ targetView.setBigInt64(position$1, value);
1473
+ } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
1474
+ // if we can fit an unsigned int, use that
1475
+ target[position$1++] = 0xcf;
1476
+ targetView.setBigUint64(position$1, value);
1477
+ } else {
1478
+ // overflow
1479
+ if (this.largeBigIntToFloat) {
1480
+ target[position$1++] = 0xcb;
1481
+ targetView.setFloat64(position$1, Number(value));
1482
+ } else {
1483
+ throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, set largeBigIntToFloat to convert to float-64')
1484
+ }
1485
+ }
1486
+ position$1 += 8;
1487
+ } else if (type === 'undefined') {
1488
+ if (this.encodeUndefinedAsNil)
1489
+ target[position$1++] = 0xc0;
1490
+ else {
1491
+ target[position$1++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
1492
+ target[position$1++] = 0;
1493
+ target[position$1++] = 0;
1494
+ }
1495
+ } else if (type === 'function') {
1496
+ pack(this.writeFunction && this.writeFunction()); // if there is a writeFunction, use it, otherwise just encode as undefined
1497
+ } else {
1498
+ throw new Error('Unknown type: ' + type)
1499
+ }
1500
+ };
1501
+
1502
+ const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {
1503
+ // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
1504
+ let keys = Object.keys(object);
1505
+ let length = keys.length;
1506
+ if (length < 0x10) {
1507
+ target[position$1++] = 0x80 | length;
1508
+ } else if (length < 0x10000) {
1509
+ target[position$1++] = 0xde;
1510
+ target[position$1++] = length >> 8;
1511
+ target[position$1++] = length & 0xff;
1512
+ } else {
1513
+ target[position$1++] = 0xdf;
1514
+ targetView.setUint32(position$1, length);
1515
+ position$1 += 4;
1516
+ }
1517
+ let key;
1518
+ for (let i = 0; i < length; i++) {
1519
+ pack(key = keys[i]);
1520
+ pack(object[key]);
1521
+ }
1522
+ } :
1523
+ (object, safePrototype) => {
1524
+ target[position$1++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
1525
+ let objectOffset = position$1 - start;
1526
+ position$1 += 2;
1527
+ let size = 0;
1528
+ for (let key in object) {
1529
+ if (safePrototype || object.hasOwnProperty(key)) {
1530
+ pack(key);
1531
+ pack(object[key]);
1532
+ size++;
1533
+ }
1534
+ }
1535
+ target[objectOffset++ + start] = size >> 8;
1536
+ target[objectOffset + start] = size & 0xff;
1537
+ } :
1538
+ (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
1539
+ (object, safePrototype) => {
1540
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1541
+ let objectOffset = position$1++ - start;
1542
+ let wroteKeys;
1543
+ for (let key in object) {
1544
+ if (safePrototype || object.hasOwnProperty(key)) {
1545
+ nextTransition = transition[key];
1546
+ if (nextTransition)
1547
+ transition = nextTransition;
1548
+ else {
1549
+ // record doesn't exist, create full new record and insert it
1550
+ let keys = Object.keys(object);
1551
+ let lastTransition = transition;
1552
+ transition = structures.transitions;
1553
+ let newTransitions = 0;
1554
+ for (let i = 0, l = keys.length; i < l; i++) {
1555
+ let key = keys[i];
1556
+ nextTransition = transition[key];
1557
+ if (!nextTransition) {
1558
+ nextTransition = transition[key] = Object.create(null);
1559
+ newTransitions++;
1560
+ }
1561
+ transition = nextTransition;
1562
+ }
1563
+ if (objectOffset + start + 1 == position$1) {
1564
+ // first key, so we don't need to insert, we can just write record directly
1565
+ position$1--;
1566
+ newRecord(transition, keys, newTransitions);
1567
+ } else // otherwise we need to insert the record, moving existing data after the record
1568
+ insertNewRecord(transition, keys, objectOffset, newTransitions);
1569
+ wroteKeys = true;
1570
+ transition = lastTransition[key];
1571
+ }
1572
+ pack(object[key]);
1573
+ }
1574
+ }
1575
+ if (!wroteKeys) {
1576
+ let recordId = transition[RECORD_SYMBOL];
1577
+ if (recordId)
1578
+ target[objectOffset + start] = recordId;
1579
+ else
1580
+ insertNewRecord(transition, Object.keys(object), objectOffset, 0);
1581
+ }
1582
+ } :
1583
+ (object, safePrototype) => {
1584
+ let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
1585
+ let newTransitions = 0;
1586
+ for (let key in object) if (safePrototype || object.hasOwnProperty(key)) {
1587
+ nextTransition = transition[key];
1588
+ if (!nextTransition) {
1589
+ nextTransition = transition[key] = Object.create(null);
1590
+ newTransitions++;
1591
+ }
1592
+ transition = nextTransition;
1593
+ }
1594
+ let recordId = transition[RECORD_SYMBOL];
1595
+ if (recordId) {
1596
+ if (recordId >= 0x60 && useTwoByteRecords) {
1597
+ target[position$1++] = ((recordId -= 0x60) & 0x1f) + 0x60;
1598
+ target[position$1++] = recordId >> 5;
1599
+ } else
1600
+ target[position$1++] = recordId;
1601
+ } else {
1602
+ newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
1603
+ }
1604
+ // now write the values
1605
+ for (let key in object)
1606
+ if (safePrototype || object.hasOwnProperty(key))
1607
+ pack(object[key]);
1608
+ };
1609
+ const makeRoom = (end) => {
1610
+ let newSize;
1611
+ if (end > 0x1000000) {
1612
+ // special handling for really large buffers
1613
+ if ((end - start) > MAX_BUFFER_SIZE)
1614
+ throw new Error('Packed buffer would be larger than maximum buffer size')
1615
+ newSize = Math.min(MAX_BUFFER_SIZE,
1616
+ Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
1617
+ } else // faster handling for smaller buffers
1618
+ newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
1619
+ let newBuffer = new ByteArrayAllocate(newSize);
1620
+ targetView = new DataView(newBuffer.buffer, 0, newSize);
1621
+ end = Math.min(end, target.length);
1622
+ if (target.copy)
1623
+ target.copy(newBuffer, 0, start, end);
1624
+ else
1625
+ newBuffer.set(target.slice(start, end));
1626
+ position$1 -= start;
1627
+ start = 0;
1628
+ safeEnd = newBuffer.length - 10;
1629
+ return target = newBuffer
1630
+ };
1631
+ const newRecord = (transition, keys, newTransitions) => {
1632
+ let recordId = structures.nextId;
1633
+ if (!recordId)
1634
+ recordId = 0x40;
1635
+ if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
1636
+ recordId = structures.nextOwnId;
1637
+ if (!(recordId < maxStructureId))
1638
+ recordId = sharedLimitId;
1639
+ structures.nextOwnId = recordId + 1;
1640
+ } else {
1641
+ if (recordId >= maxStructureId)// cycle back around
1642
+ recordId = sharedLimitId;
1643
+ structures.nextId = recordId + 1;
1644
+ }
1645
+ let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
1646
+ transition[RECORD_SYMBOL] = recordId;
1647
+ transition.__keys__ = keys;
1648
+ structures[recordId - 0x40] = keys;
1649
+
1650
+ if (recordId < sharedLimitId) {
1651
+ keys.isShared = true;
1652
+ structures.sharedLength = recordId - 0x3f;
1653
+ hasSharedUpdate = true;
1654
+ if (highByte >= 0) {
1655
+ target[position$1++] = (recordId & 0x1f) + 0x60;
1656
+ target[position$1++] = highByte;
1657
+ } else {
1658
+ target[position$1++] = recordId;
1659
+ }
1660
+ } else {
1661
+ if (highByte >= 0) {
1662
+ target[position$1++] = 0xd5; // fixext 2
1663
+ target[position$1++] = 0x72; // "r" record defintion extension type
1664
+ target[position$1++] = (recordId & 0x1f) + 0x60;
1665
+ target[position$1++] = highByte;
1666
+ } else {
1667
+ target[position$1++] = 0xd4; // fixext 1
1668
+ target[position$1++] = 0x72; // "r" record defintion extension type
1669
+ target[position$1++] = recordId;
1670
+ }
1671
+
1672
+ if (newTransitions)
1673
+ transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
1674
+ // record the removal of the id, we can maintain our shared structure
1675
+ if (recordIdsToRemove.length >= maxOwnStructures)
1676
+ recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
1677
+ recordIdsToRemove.push(transition);
1678
+ pack(keys);
1679
+ }
1680
+ };
1681
+ const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
1682
+ let mainTarget = target;
1683
+ let mainPosition = position$1;
1684
+ let mainSafeEnd = safeEnd;
1685
+ let mainStart = start;
1686
+ target = keysTarget;
1687
+ position$1 = 0;
1688
+ start = 0;
1689
+ if (!target)
1690
+ keysTarget = target = new ByteArrayAllocate(8192);
1691
+ safeEnd = target.length - 10;
1692
+ newRecord(transition, keys, newTransitions);
1693
+ keysTarget = target;
1694
+ let keysPosition = position$1;
1695
+ target = mainTarget;
1696
+ position$1 = mainPosition;
1697
+ safeEnd = mainSafeEnd;
1698
+ start = mainStart;
1699
+ if (keysPosition > 1) {
1700
+ let newEnd = position$1 + keysPosition - 1;
1701
+ if (newEnd > safeEnd)
1702
+ makeRoom(newEnd);
1703
+ let insertionPosition = insertionOffset + start;
1704
+ target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position$1);
1705
+ target.set(keysTarget.slice(0, keysPosition), insertionPosition);
1706
+ position$1 = newEnd;
1707
+ } else {
1708
+ target[insertionOffset + start] = keysTarget[0];
1709
+ }
1710
+ };
1711
+ }
1712
+ useBuffer(buffer) {
1713
+ // this means we are finished using our own buffer and we can write over it safely
1714
+ target = buffer;
1715
+ targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
1716
+ position$1 = 0;
1717
+ }
1718
+ clearSharedData() {
1719
+ if (this.structures)
1720
+ this.structures = [];
1721
+ }
1722
+ }
1723
+
1724
+ extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
1725
+ extensions = [{
1726
+ pack(date, allocateForWrite, pack) {
1727
+ let seconds = date.getTime() / 1000;
1728
+ if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
1729
+ // Timestamp 32
1730
+ let { target, targetView, position} = allocateForWrite(6);
1731
+ target[position++] = 0xd6;
1732
+ target[position++] = 0xff;
1733
+ targetView.setUint32(position, seconds);
1734
+ } else if (seconds > 0 && seconds < 0x100000000) {
1735
+ // Timestamp 64
1736
+ let { target, targetView, position} = allocateForWrite(10);
1737
+ target[position++] = 0xd7;
1738
+ target[position++] = 0xff;
1739
+ targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
1740
+ targetView.setUint32(position + 4, seconds);
1741
+ } else if (isNaN(seconds)) {
1742
+ if (this.onInvalidDate) {
1743
+ allocateForWrite(0);
1744
+ return pack(this.onInvalidDate())
1745
+ }
1746
+ // Intentionally invalid timestamp
1747
+ let { target, targetView, position} = allocateForWrite(3);
1748
+ target[position++] = 0xd4;
1749
+ target[position++] = 0xff;
1750
+ target[position++] = 0xff;
1751
+ } else {
1752
+ // Timestamp 96
1753
+ let { target, targetView, position} = allocateForWrite(15);
1754
+ target[position++] = 0xc7;
1755
+ target[position++] = 12;
1756
+ target[position++] = 0xff;
1757
+ targetView.setUint32(position, date.getMilliseconds() * 1000000);
1758
+ targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
1759
+ }
1760
+ }
1761
+ }, {
1762
+ pack(set, allocateForWrite, pack) {
1763
+ let array = Array.from(set);
1764
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1765
+ if (this.moreTypes) {
1766
+ target[position++] = 0xd4;
1767
+ target[position++] = 0x73; // 's' for Set
1768
+ target[position++] = 0;
1769
+ }
1770
+ pack(array);
1771
+ }
1772
+ }, {
1773
+ pack(error, allocateForWrite, pack) {
1774
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1775
+ if (this.moreTypes) {
1776
+ target[position++] = 0xd4;
1777
+ target[position++] = 0x65; // 'e' for error
1778
+ target[position++] = 0;
1779
+ }
1780
+ pack([ error.name, error.message ]);
1781
+ }
1782
+ }, {
1783
+ pack(regex, allocateForWrite, pack) {
1784
+ let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
1785
+ if (this.moreTypes) {
1786
+ target[position++] = 0xd4;
1787
+ target[position++] = 0x78; // 'x' for regeXp
1788
+ target[position++] = 0;
1789
+ }
1790
+ pack([ regex.source, regex.flags ]);
1791
+ }
1792
+ }, {
1793
+ pack(arrayBuffer, allocateForWrite) {
1794
+ if (this.moreTypes)
1795
+ writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
1796
+ else
1797
+ writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
1798
+ }
1799
+ }, {
1800
+ pack(typedArray, allocateForWrite) {
1801
+ let constructor = typedArray.constructor;
1802
+ if (constructor !== ByteArray && this.moreTypes)
1803
+ writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
1804
+ else
1805
+ writeBuffer(typedArray, allocateForWrite);
1806
+ }
1807
+ }, {
1808
+ pack(c1, allocateForWrite) { // specific 0xC1 object
1809
+ let { target, position} = allocateForWrite(1);
1810
+ target[position] = 0xc1;
1811
+ }
1812
+ }];
1813
+
1814
+ function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
1815
+ let length = typedArray.byteLength;
1816
+ if (length + 1 < 0x100) {
1817
+ var { target, position } = allocateForWrite(4 + length);
1818
+ target[position++] = 0xc7;
1819
+ target[position++] = length + 1;
1820
+ } else if (length + 1 < 0x10000) {
1821
+ var { target, position } = allocateForWrite(5 + length);
1822
+ target[position++] = 0xc8;
1823
+ target[position++] = (length + 1) >> 8;
1824
+ target[position++] = (length + 1) & 0xff;
1825
+ } else {
1826
+ var { target, position, targetView } = allocateForWrite(7 + length);
1827
+ target[position++] = 0xc9;
1828
+ targetView.setUint32(position, length + 1); // plus one for the type byte
1829
+ position += 4;
1830
+ }
1831
+ target[position++] = 0x74; // "t" for typed array
1832
+ target[position++] = type;
1833
+ target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
1834
+ }
1835
+ function writeBuffer(buffer, allocateForWrite) {
1836
+ let length = buffer.byteLength;
1837
+ var target, position;
1838
+ if (length < 0x100) {
1839
+ var { target, position } = allocateForWrite(length + 2);
1840
+ target[position++] = 0xc4;
1841
+ target[position++] = length;
1842
+ } else if (length < 0x10000) {
1843
+ var { target, position } = allocateForWrite(length + 3);
1844
+ target[position++] = 0xc5;
1845
+ target[position++] = length >> 8;
1846
+ target[position++] = length & 0xff;
1847
+ } else {
1848
+ var { target, position, targetView } = allocateForWrite(length + 5);
1849
+ target[position++] = 0xc6;
1850
+ targetView.setUint32(position, length);
1851
+ position += 4;
1852
+ }
1853
+ target.set(buffer, position);
1854
+ }
1855
+
1856
+ function writeExtensionData(result, target, position, type) {
1857
+ let length = result.length;
1858
+ switch (length) {
1859
+ case 1:
1860
+ target[position++] = 0xd4;
1861
+ break
1862
+ case 2:
1863
+ target[position++] = 0xd5;
1864
+ break
1865
+ case 4:
1866
+ target[position++] = 0xd6;
1867
+ break
1868
+ case 8:
1869
+ target[position++] = 0xd7;
1870
+ break
1871
+ case 16:
1872
+ target[position++] = 0xd8;
1873
+ break
1874
+ default:
1875
+ if (length < 0x100) {
1876
+ target[position++] = 0xc7;
1877
+ target[position++] = length;
1878
+ } else if (length < 0x10000) {
1879
+ target[position++] = 0xc8;
1880
+ target[position++] = length >> 8;
1881
+ target[position++] = length & 0xff;
1882
+ } else {
1883
+ target[position++] = 0xc9;
1884
+ target[position++] = length >> 24;
1885
+ target[position++] = (length >> 16) & 0xff;
1886
+ target[position++] = (length >> 8) & 0xff;
1887
+ target[position++] = length & 0xff;
1888
+ }
1889
+ }
1890
+ target[position++] = type;
1891
+ target.set(result, position);
1892
+ position += length;
1893
+ return position
1894
+ }
1895
+
1896
+ function insertIds(serialized, idsToInsert) {
1897
+ // insert the ids that need to be referenced for structured clones
1898
+ let nextId;
1899
+ let distanceToMove = idsToInsert.length * 6;
1900
+ let lastEnd = serialized.length - distanceToMove;
1901
+ idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1902
+ while (nextId = idsToInsert.pop()) {
1903
+ let offset = nextId.offset;
1904
+ let id = nextId.id;
1905
+ serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
1906
+ distanceToMove -= 6;
1907
+ let position = offset + distanceToMove;
1908
+ serialized[position++] = 0xd6;
1909
+ serialized[position++] = 0x69; // 'i'
1910
+ serialized[position++] = id >> 24;
1911
+ serialized[position++] = (id >> 16) & 0xff;
1912
+ serialized[position++] = (id >> 8) & 0xff;
1913
+ serialized[position++] = id & 0xff;
1914
+ lastEnd = offset;
1915
+ }
1916
+ return serialized
1917
+ }
1918
+
1919
+ function writeBundles(start, pack) {
1920
+ if (bundledStrings$1.length > 0) {
1921
+ targetView.setUint32(bundledStrings$1.position + start, position$1 - bundledStrings$1.position - start);
1922
+ let writeStrings = bundledStrings$1;
1923
+ bundledStrings$1 = null;
1924
+ pack(writeStrings[0]);
1925
+ pack(writeStrings[1]);
1926
+ }
1927
+ }
1928
+
1929
+ function addExtension$1(extension) {
1930
+ if (extension.Class) {
1931
+ if (!extension.pack && !extension.write)
1932
+ throw new Error('Extension has no pack or write function')
1933
+ if (extension.pack && !extension.type)
1934
+ throw new Error('Extension has no type (numeric code to identify the extension)')
1935
+ extensionClasses.unshift(extension.Class);
1936
+ extensions.unshift(extension);
1937
+ }
1938
+ addExtension(extension);
1939
+ }
1940
+
1941
+ let defaultPackr = new Packr({ useRecords: false });
1942
+ const pack = defaultPackr.pack;
1943
+ const encode = defaultPackr.pack;
1944
+ const Encoder = Packr;
1945
+ const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
1946
+ const REUSE_BUFFER_MODE = 512;
1928
1947
  const RESET_BUFFER_MODE = 1024;
1929
1948
 
1930
- /**
1931
- * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
1932
- * If the argument is only Async Iterable, the return value will be an Async Iterable.
1933
- * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
1934
- * @param {options} [options] - msgpackr pack options
1935
- * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
1936
- */
1937
- function packIter (objectIterator, options = {}) {
1938
- if (!objectIterator || typeof objectIterator !== 'object') {
1939
- throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
1940
- } else if (typeof objectIterator[Symbol.iterator] === 'function') {
1941
- return packIterSync(objectIterator, options)
1942
- } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
1943
- return packIterAsync(objectIterator, options)
1944
- } else {
1945
- throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
1946
- }
1947
- }
1948
-
1949
- function * packIterSync (objectIterator, options) {
1950
- const packr = new Packr(options);
1951
- for (const value of objectIterator) {
1952
- yield packr.pack(value);
1953
- }
1954
- }
1955
-
1956
- async function * packIterAsync (objectIterator, options) {
1957
- const packr = new Packr(options);
1958
- for await (const value of objectIterator) {
1959
- yield packr.pack(value);
1960
- }
1961
- }
1962
-
1963
- /**
1964
- * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
1965
- * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
1966
- * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
1967
- * @param {object} [options] - unpackr options
1968
- * @returns {IterableIterator|Promise.<AsyncIterableIterator}
1969
- */
1970
- function unpackIter (bufferIterator, options = {}) {
1971
- if (!bufferIterator || typeof bufferIterator !== 'object') {
1972
- throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
1973
- }
1974
-
1975
- const unpackr = new Unpackr(options);
1976
- let incomplete;
1977
- const parser = (chunk) => {
1978
- let yields;
1979
- // if there's incomplete data from previous chunk, concatinate and try again
1980
- if (incomplete) {
1981
- chunk = Buffer.concat([incomplete, chunk]);
1982
- incomplete = undefined;
1983
- }
1984
-
1985
- try {
1986
- yields = unpackr.unpackMultiple(chunk);
1987
- } catch (err) {
1988
- if (err.incomplete) {
1989
- incomplete = chunk.slice(err.lastPosition);
1990
- yields = err.values;
1991
- } else {
1992
- throw err
1993
- }
1994
- }
1995
- return yields
1996
- };
1997
-
1998
- if (typeof bufferIterator[Symbol.iterator] === 'function') {
1999
- return (function * iter () {
2000
- for (const value of bufferIterator) {
2001
- yield * parser(value);
2002
- }
2003
- })()
2004
- } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2005
- return (async function * iter () {
2006
- for await (const value of bufferIterator) {
2007
- yield * parser(value);
2008
- }
2009
- })()
2010
- }
2011
- }
2012
- const decodeIter = unpackIter;
1949
+ /**
1950
+ * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
1951
+ * If the argument is only Async Iterable, the return value will be an Async Iterable.
1952
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
1953
+ * @param {options} [options] - msgpackr pack options
1954
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
1955
+ */
1956
+ function packIter (objectIterator, options = {}) {
1957
+ if (!objectIterator || typeof objectIterator !== 'object') {
1958
+ throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
1959
+ } else if (typeof objectIterator[Symbol.iterator] === 'function') {
1960
+ return packIterSync(objectIterator, options)
1961
+ } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
1962
+ return packIterAsync(objectIterator, options)
1963
+ } else {
1964
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
1965
+ }
1966
+ }
1967
+
1968
+ function * packIterSync (objectIterator, options) {
1969
+ const packr = new Packr(options);
1970
+ for (const value of objectIterator) {
1971
+ yield packr.pack(value);
1972
+ }
1973
+ }
1974
+
1975
+ async function * packIterAsync (objectIterator, options) {
1976
+ const packr = new Packr(options);
1977
+ for await (const value of objectIterator) {
1978
+ yield packr.pack(value);
1979
+ }
1980
+ }
1981
+
1982
+ /**
1983
+ * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
1984
+ * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
1985
+ * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
1986
+ * @param {object} [options] - unpackr options
1987
+ * @returns {IterableIterator|Promise.<AsyncIterableIterator}
1988
+ */
1989
+ function unpackIter (bufferIterator, options = {}) {
1990
+ if (!bufferIterator || typeof bufferIterator !== 'object') {
1991
+ throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
1992
+ }
1993
+
1994
+ const unpackr = new Unpackr(options);
1995
+ let incomplete;
1996
+ const parser = (chunk) => {
1997
+ let yields;
1998
+ // if there's incomplete data from previous chunk, concatinate and try again
1999
+ if (incomplete) {
2000
+ chunk = Buffer.concat([incomplete, chunk]);
2001
+ incomplete = undefined;
2002
+ }
2003
+
2004
+ try {
2005
+ yields = unpackr.unpackMultiple(chunk);
2006
+ } catch (err) {
2007
+ if (err.incomplete) {
2008
+ incomplete = chunk.slice(err.lastPosition);
2009
+ yields = err.values;
2010
+ } else {
2011
+ throw err
2012
+ }
2013
+ }
2014
+ return yields
2015
+ };
2016
+
2017
+ if (typeof bufferIterator[Symbol.iterator] === 'function') {
2018
+ return (function * iter () {
2019
+ for (const value of bufferIterator) {
2020
+ yield * parser(value);
2021
+ }
2022
+ })()
2023
+ } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
2024
+ return (async function * iter () {
2025
+ for await (const value of bufferIterator) {
2026
+ yield * parser(value);
2027
+ }
2028
+ })()
2029
+ }
2030
+ }
2031
+ const decodeIter = unpackIter;
2013
2032
  const encodeIter = packIter;
2014
2033
 
2015
- const useRecords = false;
2034
+ const useRecords = false;
2016
2035
  const mapsAsObjects = true;
2017
2036
 
2018
2037
  exports.ALWAYS = ALWAYS;