jaelis-node 1.10.0 → 2.0.0

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