index-no-eval.cjs 81 KB

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