test.js 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536
  1. (function (chai, stream, module, fs) {
  2. 'use strict';
  3. var decoder;
  4. try {
  5. decoder = new TextDecoder();
  6. } catch(error) {}
  7. var src;
  8. var srcEnd;
  9. var position$1 = 0;
  10. const EMPTY_ARRAY = [];
  11. var strings = EMPTY_ARRAY;
  12. var stringPosition = 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$1, onLoadedStructures$1, onSaveState;
  32. // no-eval build
  33. try {
  34. new Function('');
  35. } catch(error) {
  36. // if eval variants are not supported, do not create inline object readers ever
  37. inlineObjectReadThreshold = Infinity;
  38. }
  39. let Unpackr$1 = class Unpackr {
  40. constructor(options) {
  41. if (options) {
  42. if (options.useRecords === false && options.mapsAsObjects === undefined)
  43. options.mapsAsObjects = true;
  44. if (options.sequential && options.trusted !== false) {
  45. options.trusted = true;
  46. if (!options.structures && options.useRecords != false) {
  47. options.structures = [];
  48. if (!options.maxSharedStructures)
  49. options.maxSharedStructures = 0;
  50. }
  51. }
  52. if (options.structures)
  53. options.structures.sharedLength = options.structures.length;
  54. else if (options.getStructures) {
  55. (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
  56. options.structures.sharedLength = 0;
  57. }
  58. if (options.int64AsNumber) {
  59. options.int64AsType = 'number';
  60. }
  61. }
  62. Object.assign(this, options);
  63. }
  64. unpack(source, options) {
  65. if (src) {
  66. // re-entrant execution, save the state and restore it after we do this unpack
  67. return saveState$1(() => {
  68. clearSource();
  69. return this ? this.unpack(source, options) : Unpackr$1.prototype.unpack.call(defaultOptions, source, options)
  70. })
  71. }
  72. if (!source.buffer && source.constructor === ArrayBuffer)
  73. source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
  74. if (typeof options === 'object') {
  75. srcEnd = options.end || source.length;
  76. position$1 = options.start || 0;
  77. } else {
  78. position$1 = 0;
  79. srcEnd = options > -1 ? options : source.length;
  80. }
  81. stringPosition = 0;
  82. srcStringEnd = 0;
  83. srcString = null;
  84. strings = EMPTY_ARRAY;
  85. bundledStrings$1 = null;
  86. src = source;
  87. // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
  88. // technique for getting data from a database where it can be copied into an existing buffer instead of creating
  89. // new ones
  90. try {
  91. dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
  92. } catch(error) {
  93. // if it doesn't have a buffer, maybe it is the wrong type of object
  94. src = null;
  95. if (source instanceof Uint8Array)
  96. throw error
  97. throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
  98. }
  99. if (this instanceof Unpackr$1) {
  100. currentUnpackr = this;
  101. if (this.structures) {
  102. currentStructures = this.structures;
  103. return checkedRead(options)
  104. } else if (!currentStructures || currentStructures.length > 0) {
  105. currentStructures = [];
  106. }
  107. } else {
  108. currentUnpackr = defaultOptions;
  109. if (!currentStructures || currentStructures.length > 0)
  110. currentStructures = [];
  111. }
  112. return checkedRead(options)
  113. }
  114. unpackMultiple(source, forEach) {
  115. let values, lastPosition = 0;
  116. try {
  117. sequentialMode = true;
  118. let size = source.length;
  119. let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
  120. if (forEach) {
  121. if (forEach(value, lastPosition, position$1) === false) return;
  122. while(position$1 < size) {
  123. lastPosition = position$1;
  124. if (forEach(checkedRead(), lastPosition, position$1) === false) {
  125. return
  126. }
  127. }
  128. }
  129. else {
  130. values = [ value ];
  131. while(position$1 < size) {
  132. lastPosition = position$1;
  133. values.push(checkedRead());
  134. }
  135. return values
  136. }
  137. } catch(error) {
  138. error.lastPosition = lastPosition;
  139. error.values = values;
  140. throw error
  141. } finally {
  142. sequentialMode = false;
  143. clearSource();
  144. }
  145. }
  146. _mergeStructures(loadedStructures, existingStructures) {
  147. if (onLoadedStructures$1)
  148. loadedStructures = onLoadedStructures$1.call(this, loadedStructures);
  149. loadedStructures = loadedStructures || [];
  150. if (Object.isFrozen(loadedStructures))
  151. loadedStructures = loadedStructures.map(structure => structure.slice(0));
  152. for (let i = 0, l = loadedStructures.length; i < l; i++) {
  153. let structure = loadedStructures[i];
  154. if (structure) {
  155. structure.isShared = true;
  156. if (i >= 32)
  157. structure.highByte = (i - 32) >> 5;
  158. }
  159. }
  160. loadedStructures.sharedLength = loadedStructures.length;
  161. for (let id in existingStructures || []) {
  162. if (id >= 0) {
  163. let structure = loadedStructures[id];
  164. let existing = existingStructures[id];
  165. if (existing) {
  166. if (structure)
  167. (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
  168. loadedStructures[id] = existing;
  169. }
  170. }
  171. }
  172. return this.structures = loadedStructures
  173. }
  174. decode(source, options) {
  175. return this.unpack(source, options)
  176. }
  177. };
  178. function checkedRead(options) {
  179. try {
  180. if (!currentUnpackr.trusted && !sequentialMode) {
  181. let sharedLength = currentStructures.sharedLength || 0;
  182. if (sharedLength < currentStructures.length)
  183. currentStructures.length = sharedLength;
  184. }
  185. let result;
  186. if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct$1) {
  187. result = readStruct$1(src, position$1, srcEnd, currentUnpackr);
  188. src = null; // dispose of this so that recursive unpack calls don't save state
  189. if (!(options && options.lazy) && result)
  190. result = result.toJSON();
  191. position$1 = srcEnd;
  192. } else
  193. result = read();
  194. if (bundledStrings$1) { // bundled strings to skip past
  195. position$1 = bundledStrings$1.postBundlePosition;
  196. bundledStrings$1 = null;
  197. }
  198. if (sequentialMode)
  199. // we only need to restore the structures if there was an error, but if we completed a read,
  200. // we can clear this out and keep the structures we read
  201. currentStructures.restoreStructures = null;
  202. if (position$1 == srcEnd) {
  203. // finished reading this source, cleanup references
  204. if (currentStructures && currentStructures.restoreStructures)
  205. restoreStructures();
  206. currentStructures = null;
  207. src = null;
  208. if (referenceMap)
  209. referenceMap = null;
  210. } else if (position$1 > srcEnd) {
  211. // over read
  212. throw new Error('Unexpected end of MessagePack data')
  213. } else if (!sequentialMode) {
  214. let jsonView;
  215. try {
  216. jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
  217. } catch(error) {
  218. jsonView = '(JSON view not available ' + error + ')';
  219. }
  220. throw new Error('Data read, but end of buffer not reached ' + jsonView)
  221. }
  222. // else more to read, but we are reading sequentially, so don't clear source yet
  223. return result
  224. } catch(error) {
  225. if (currentStructures && currentStructures.restoreStructures)
  226. restoreStructures();
  227. clearSource();
  228. if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
  229. error.incomplete = true;
  230. }
  231. throw error
  232. }
  233. }
  234. function restoreStructures() {
  235. for (let id in currentStructures.restoreStructures) {
  236. currentStructures[id] = currentStructures.restoreStructures[id];
  237. }
  238. currentStructures.restoreStructures = null;
  239. }
  240. function read() {
  241. let token = src[position$1++];
  242. if (token < 0xa0) {
  243. if (token < 0x80) {
  244. if (token < 0x40)
  245. return token
  246. else {
  247. let structure = currentStructures[token & 0x3f] ||
  248. currentUnpackr.getStructures && loadStructures()[token & 0x3f];
  249. if (structure) {
  250. if (!structure.read) {
  251. structure.read = createStructureReader(structure, token & 0x3f);
  252. }
  253. return structure.read()
  254. } else
  255. return token
  256. }
  257. } else if (token < 0x90) {
  258. // map
  259. token -= 0x80;
  260. if (currentUnpackr.mapsAsObjects) {
  261. let object = {};
  262. for (let i = 0; i < token; i++) {
  263. let key = readKey();
  264. if (key === '__proto__')
  265. key = '__proto_';
  266. object[key] = read();
  267. }
  268. return object
  269. } else {
  270. let map = new Map();
  271. for (let i = 0; i < token; i++) {
  272. map.set(read(), read());
  273. }
  274. return map
  275. }
  276. } else {
  277. token -= 0x90;
  278. let array = new Array(token);
  279. for (let i = 0; i < token; i++) {
  280. array[i] = read();
  281. }
  282. if (currentUnpackr.freezeData)
  283. return Object.freeze(array)
  284. return array
  285. }
  286. } else if (token < 0xc0) {
  287. // fixstr
  288. let length = token - 0xa0;
  289. if (srcStringEnd >= position$1) {
  290. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  291. }
  292. if (srcStringEnd == 0 && srcEnd < 140) {
  293. // for small blocks, avoiding the overhead of the extract call is helpful
  294. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  295. if (string != null)
  296. return string
  297. }
  298. return readFixedString(length)
  299. } else {
  300. let value;
  301. switch (token) {
  302. case 0xc0: return null
  303. case 0xc1:
  304. if (bundledStrings$1) {
  305. value = read(); // followed by the length of the string in characters (not bytes!)
  306. if (value > 0)
  307. return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
  308. else
  309. return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
  310. }
  311. return C1; // "never-used", return special object to denote that
  312. case 0xc2: return false
  313. case 0xc3: return true
  314. case 0xc4:
  315. // bin 8
  316. value = src[position$1++];
  317. if (value === undefined)
  318. throw new Error('Unexpected end of buffer')
  319. return readBin(value)
  320. case 0xc5:
  321. // bin 16
  322. value = dataView.getUint16(position$1);
  323. position$1 += 2;
  324. return readBin(value)
  325. case 0xc6:
  326. // bin 32
  327. value = dataView.getUint32(position$1);
  328. position$1 += 4;
  329. return readBin(value)
  330. case 0xc7:
  331. // ext 8
  332. return readExt(src[position$1++])
  333. case 0xc8:
  334. // ext 16
  335. value = dataView.getUint16(position$1);
  336. position$1 += 2;
  337. return readExt(value)
  338. case 0xc9:
  339. // ext 32
  340. value = dataView.getUint32(position$1);
  341. position$1 += 4;
  342. return readExt(value)
  343. case 0xca:
  344. value = dataView.getFloat32(position$1);
  345. if (currentUnpackr.useFloat32 > 2) {
  346. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  347. let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
  348. position$1 += 4;
  349. return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  350. }
  351. position$1 += 4;
  352. return value
  353. case 0xcb:
  354. value = dataView.getFloat64(position$1);
  355. position$1 += 8;
  356. return value
  357. // uint handlers
  358. case 0xcc:
  359. return src[position$1++]
  360. case 0xcd:
  361. value = dataView.getUint16(position$1);
  362. position$1 += 2;
  363. return value
  364. case 0xce:
  365. value = dataView.getUint32(position$1);
  366. position$1 += 4;
  367. return value
  368. case 0xcf:
  369. if (currentUnpackr.int64AsType === 'number') {
  370. value = dataView.getUint32(position$1) * 0x100000000;
  371. value += dataView.getUint32(position$1 + 4);
  372. } else if (currentUnpackr.int64AsType === 'string') {
  373. value = dataView.getBigUint64(position$1).toString();
  374. } else if (currentUnpackr.int64AsType === 'auto') {
  375. value = dataView.getBigUint64(position$1);
  376. if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
  377. } else
  378. value = dataView.getBigUint64(position$1);
  379. position$1 += 8;
  380. return value
  381. // int handlers
  382. case 0xd0:
  383. return dataView.getInt8(position$1++)
  384. case 0xd1:
  385. value = dataView.getInt16(position$1);
  386. position$1 += 2;
  387. return value
  388. case 0xd2:
  389. value = dataView.getInt32(position$1);
  390. position$1 += 4;
  391. return value
  392. case 0xd3:
  393. if (currentUnpackr.int64AsType === 'number') {
  394. value = dataView.getInt32(position$1) * 0x100000000;
  395. value += dataView.getUint32(position$1 + 4);
  396. } else if (currentUnpackr.int64AsType === 'string') {
  397. value = dataView.getBigInt64(position$1).toString();
  398. } else if (currentUnpackr.int64AsType === 'auto') {
  399. value = dataView.getBigInt64(position$1);
  400. if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
  401. } else
  402. value = dataView.getBigInt64(position$1);
  403. position$1 += 8;
  404. return value
  405. case 0xd4:
  406. // fixext 1
  407. value = src[position$1++];
  408. if (value == 0x72) {
  409. return recordDefinition(src[position$1++] & 0x3f)
  410. } else {
  411. let extension = currentExtensions[value];
  412. if (extension) {
  413. if (extension.read) {
  414. position$1++; // skip filler byte
  415. return extension.read(read())
  416. } else if (extension.noBuffer) {
  417. position$1++; // skip filler byte
  418. return extension()
  419. } else
  420. return extension(src.subarray(position$1, ++position$1))
  421. } else
  422. throw new Error('Unknown extension ' + value)
  423. }
  424. case 0xd5:
  425. // fixext 2
  426. value = src[position$1];
  427. if (value == 0x72) {
  428. position$1++;
  429. return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
  430. } else
  431. return readExt(2)
  432. case 0xd6:
  433. // fixext 4
  434. return readExt(4)
  435. case 0xd7:
  436. // fixext 8
  437. return readExt(8)
  438. case 0xd8:
  439. // fixext 16
  440. return readExt(16)
  441. case 0xd9:
  442. // str 8
  443. value = src[position$1++];
  444. if (srcStringEnd >= position$1) {
  445. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  446. }
  447. return readString8(value)
  448. case 0xda:
  449. // str 16
  450. value = dataView.getUint16(position$1);
  451. position$1 += 2;
  452. if (srcStringEnd >= position$1) {
  453. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  454. }
  455. return readString16(value)
  456. case 0xdb:
  457. // str 32
  458. value = dataView.getUint32(position$1);
  459. position$1 += 4;
  460. if (srcStringEnd >= position$1) {
  461. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  462. }
  463. return readString32(value)
  464. case 0xdc:
  465. // array 16
  466. value = dataView.getUint16(position$1);
  467. position$1 += 2;
  468. return readArray(value)
  469. case 0xdd:
  470. // array 32
  471. value = dataView.getUint32(position$1);
  472. position$1 += 4;
  473. return readArray(value)
  474. case 0xde:
  475. // map 16
  476. value = dataView.getUint16(position$1);
  477. position$1 += 2;
  478. return readMap(value)
  479. case 0xdf:
  480. // map 32
  481. value = dataView.getUint32(position$1);
  482. position$1 += 4;
  483. return readMap(value)
  484. default: // negative int
  485. if (token >= 0xe0)
  486. return token - 0x100
  487. if (token === undefined) {
  488. let error = new Error('Unexpected end of MessagePack data');
  489. error.incomplete = true;
  490. throw error
  491. }
  492. throw new Error('Unknown MessagePack token ' + token)
  493. }
  494. }
  495. }
  496. const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
  497. function createStructureReader(structure, firstId) {
  498. function readObject() {
  499. // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
  500. if (readObject.count++ > inlineObjectReadThreshold) {
  501. let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
  502. '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
  503. if (structure.highByte === 0)
  504. structure.read = createSecondByteReader(firstId, structure.read);
  505. return readObject() // second byte is already read, if there is one so immediately read object
  506. }
  507. let object = {};
  508. for (let i = 0, l = structure.length; i < l; i++) {
  509. let key = structure[i];
  510. if (key === '__proto__')
  511. key = '__proto_';
  512. object[key] = read();
  513. }
  514. if (currentUnpackr.freezeData)
  515. return Object.freeze(object);
  516. return object
  517. }
  518. readObject.count = 0;
  519. if (structure.highByte === 0) {
  520. return createSecondByteReader(firstId, readObject)
  521. }
  522. return readObject
  523. }
  524. const createSecondByteReader = (firstId, read0) => {
  525. return function() {
  526. let highByte = src[position$1++];
  527. if (highByte === 0)
  528. return read0()
  529. let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
  530. let structure = currentStructures[id] || loadStructures()[id];
  531. if (!structure) {
  532. throw new Error('Record id is not defined for ' + id)
  533. }
  534. if (!structure.read)
  535. structure.read = createStructureReader(structure, firstId);
  536. return structure.read()
  537. }
  538. };
  539. function loadStructures() {
  540. let loadedStructures = saveState$1(() => {
  541. // save the state in case getStructures modifies our buffer
  542. src = null;
  543. return currentUnpackr.getStructures()
  544. });
  545. return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
  546. }
  547. var readFixedString = readStringJS;
  548. var readString8 = readStringJS;
  549. var readString16 = readStringJS;
  550. var readString32 = readStringJS;
  551. function setExtractor(extractStrings) {
  552. readFixedString = readString(1);
  553. readString8 = readString(2);
  554. readString16 = readString(3);
  555. readString32 = readString(5);
  556. function readString(headerLength) {
  557. return function readString(length) {
  558. let string = strings[stringPosition++];
  559. if (string == null) {
  560. if (bundledStrings$1)
  561. return readStringJS(length)
  562. let byteOffset = src.byteOffset;
  563. let extraction = extractStrings(position$1 - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);
  564. if (typeof extraction == 'string') {
  565. string = extraction;
  566. strings = EMPTY_ARRAY;
  567. } else {
  568. strings = extraction;
  569. stringPosition = 1;
  570. srcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings
  571. string = strings[0];
  572. if (string === undefined)
  573. throw new Error('Unexpected end of buffer')
  574. }
  575. }
  576. let srcStringLength = string.length;
  577. if (srcStringLength <= length) {
  578. position$1 += length;
  579. return string
  580. }
  581. srcString = string;
  582. srcStringStart = position$1;
  583. srcStringEnd = position$1 + srcStringLength;
  584. position$1 += length;
  585. return string.slice(0, length) // we know we just want the beginning
  586. }
  587. }
  588. }
  589. function readStringJS(length) {
  590. let result;
  591. if (length < 16) {
  592. if (result = shortStringInJS(length))
  593. return result
  594. }
  595. if (length > 64 && decoder)
  596. return decoder.decode(src.subarray(position$1, position$1 += length))
  597. const end = position$1 + length;
  598. const units = [];
  599. result = '';
  600. while (position$1 < end) {
  601. const byte1 = src[position$1++];
  602. if ((byte1 & 0x80) === 0) {
  603. // 1 byte
  604. units.push(byte1);
  605. } else if ((byte1 & 0xe0) === 0xc0) {
  606. // 2 bytes
  607. const byte2 = src[position$1++] & 0x3f;
  608. units.push(((byte1 & 0x1f) << 6) | byte2);
  609. } else if ((byte1 & 0xf0) === 0xe0) {
  610. // 3 bytes
  611. const byte2 = src[position$1++] & 0x3f;
  612. const byte3 = src[position$1++] & 0x3f;
  613. units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
  614. } else if ((byte1 & 0xf8) === 0xf0) {
  615. // 4 bytes
  616. const byte2 = src[position$1++] & 0x3f;
  617. const byte3 = src[position$1++] & 0x3f;
  618. const byte4 = src[position$1++] & 0x3f;
  619. let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
  620. if (unit > 0xffff) {
  621. unit -= 0x10000;
  622. units.push(((unit >>> 10) & 0x3ff) | 0xd800);
  623. unit = 0xdc00 | (unit & 0x3ff);
  624. }
  625. units.push(unit);
  626. } else {
  627. units.push(byte1);
  628. }
  629. if (units.length >= 0x1000) {
  630. result += fromCharCode.apply(String, units);
  631. units.length = 0;
  632. }
  633. }
  634. if (units.length > 0) {
  635. result += fromCharCode.apply(String, units);
  636. }
  637. return result
  638. }
  639. function readString(source, start, length) {
  640. let existingSrc = src;
  641. src = source;
  642. position$1 = start;
  643. try {
  644. return readStringJS(length);
  645. } finally {
  646. src = existingSrc;
  647. }
  648. }
  649. function readArray(length) {
  650. let array = new Array(length);
  651. for (let i = 0; i < length; i++) {
  652. array[i] = read();
  653. }
  654. if (currentUnpackr.freezeData)
  655. return Object.freeze(array)
  656. return array
  657. }
  658. function readMap(length) {
  659. if (currentUnpackr.mapsAsObjects) {
  660. let object = {};
  661. for (let i = 0; i < length; i++) {
  662. let key = readKey();
  663. if (key === '__proto__')
  664. key = '__proto_';
  665. object[key] = read();
  666. }
  667. return object
  668. } else {
  669. let map = new Map();
  670. for (let i = 0; i < length; i++) {
  671. map.set(read(), read());
  672. }
  673. return map
  674. }
  675. }
  676. var fromCharCode = String.fromCharCode;
  677. function longStringInJS(length) {
  678. let start = position$1;
  679. let bytes = new Array(length);
  680. for (let i = 0; i < length; i++) {
  681. const byte = src[position$1++];
  682. if ((byte & 0x80) > 0) {
  683. position$1 = start;
  684. return
  685. }
  686. bytes[i] = byte;
  687. }
  688. return fromCharCode.apply(String, bytes)
  689. }
  690. function shortStringInJS(length) {
  691. if (length < 4) {
  692. if (length < 2) {
  693. if (length === 0)
  694. return ''
  695. else {
  696. let a = src[position$1++];
  697. if ((a & 0x80) > 1) {
  698. position$1 -= 1;
  699. return
  700. }
  701. return fromCharCode(a)
  702. }
  703. } else {
  704. let a = src[position$1++];
  705. let b = src[position$1++];
  706. if ((a & 0x80) > 0 || (b & 0x80) > 0) {
  707. position$1 -= 2;
  708. return
  709. }
  710. if (length < 3)
  711. return fromCharCode(a, b)
  712. let c = src[position$1++];
  713. if ((c & 0x80) > 0) {
  714. position$1 -= 3;
  715. return
  716. }
  717. return fromCharCode(a, b, c)
  718. }
  719. } else {
  720. let a = src[position$1++];
  721. let b = src[position$1++];
  722. let c = src[position$1++];
  723. let d = src[position$1++];
  724. if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
  725. position$1 -= 4;
  726. return
  727. }
  728. if (length < 6) {
  729. if (length === 4)
  730. return fromCharCode(a, b, c, d)
  731. else {
  732. let e = src[position$1++];
  733. if ((e & 0x80) > 0) {
  734. position$1 -= 5;
  735. return
  736. }
  737. return fromCharCode(a, b, c, d, e)
  738. }
  739. } else if (length < 8) {
  740. let e = src[position$1++];
  741. let f = src[position$1++];
  742. if ((e & 0x80) > 0 || (f & 0x80) > 0) {
  743. position$1 -= 6;
  744. return
  745. }
  746. if (length < 7)
  747. return fromCharCode(a, b, c, d, e, f)
  748. let g = src[position$1++];
  749. if ((g & 0x80) > 0) {
  750. position$1 -= 7;
  751. return
  752. }
  753. return fromCharCode(a, b, c, d, e, f, g)
  754. } else {
  755. let e = src[position$1++];
  756. let f = src[position$1++];
  757. let g = src[position$1++];
  758. let h = src[position$1++];
  759. if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
  760. position$1 -= 8;
  761. return
  762. }
  763. if (length < 10) {
  764. if (length === 8)
  765. return fromCharCode(a, b, c, d, e, f, g, h)
  766. else {
  767. let i = src[position$1++];
  768. if ((i & 0x80) > 0) {
  769. position$1 -= 9;
  770. return
  771. }
  772. return fromCharCode(a, b, c, d, e, f, g, h, i)
  773. }
  774. } else if (length < 12) {
  775. let i = src[position$1++];
  776. let j = src[position$1++];
  777. if ((i & 0x80) > 0 || (j & 0x80) > 0) {
  778. position$1 -= 10;
  779. return
  780. }
  781. if (length < 11)
  782. return fromCharCode(a, b, c, d, e, f, g, h, i, j)
  783. let k = src[position$1++];
  784. if ((k & 0x80) > 0) {
  785. position$1 -= 11;
  786. return
  787. }
  788. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
  789. } else {
  790. let i = src[position$1++];
  791. let j = src[position$1++];
  792. let k = src[position$1++];
  793. let l = src[position$1++];
  794. if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
  795. position$1 -= 12;
  796. return
  797. }
  798. if (length < 14) {
  799. if (length === 12)
  800. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
  801. else {
  802. let m = src[position$1++];
  803. if ((m & 0x80) > 0) {
  804. position$1 -= 13;
  805. return
  806. }
  807. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
  808. }
  809. } else {
  810. let m = src[position$1++];
  811. let n = src[position$1++];
  812. if ((m & 0x80) > 0 || (n & 0x80) > 0) {
  813. position$1 -= 14;
  814. return
  815. }
  816. if (length < 15)
  817. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
  818. let o = src[position$1++];
  819. if ((o & 0x80) > 0) {
  820. position$1 -= 15;
  821. return
  822. }
  823. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
  824. }
  825. }
  826. }
  827. }
  828. }
  829. function readOnlyJSString() {
  830. let token = src[position$1++];
  831. let length;
  832. if (token < 0xc0) {
  833. // fixstr
  834. length = token - 0xa0;
  835. } else {
  836. switch(token) {
  837. case 0xd9:
  838. // str 8
  839. length = src[position$1++];
  840. break
  841. case 0xda:
  842. // str 16
  843. length = dataView.getUint16(position$1);
  844. position$1 += 2;
  845. break
  846. case 0xdb:
  847. // str 32
  848. length = dataView.getUint32(position$1);
  849. position$1 += 4;
  850. break
  851. default:
  852. throw new Error('Expected string')
  853. }
  854. }
  855. return readStringJS(length)
  856. }
  857. function readBin(length) {
  858. return currentUnpackr.copyBuffers ?
  859. // specifically use the copying slice (not the node one)
  860. Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
  861. src.subarray(position$1, position$1 += length)
  862. }
  863. function readExt(length) {
  864. let type = src[position$1++];
  865. if (currentExtensions[type]) {
  866. let end;
  867. return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
  868. position$1 = readPosition;
  869. try {
  870. return read();
  871. } finally {
  872. position$1 = end;
  873. }
  874. })
  875. }
  876. else
  877. throw new Error('Unknown extension type ' + type)
  878. }
  879. var keyCache = new Array(4096);
  880. function readKey() {
  881. let length = src[position$1++];
  882. if (length >= 0xa0 && length < 0xc0) {
  883. // fixstr, potentially use key cache
  884. length = length - 0xa0;
  885. if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
  886. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  887. else if (!(srcStringEnd == 0 && srcEnd < 180))
  888. return readFixedString(length)
  889. } else { // not cacheable, go back and do a standard read
  890. position$1--;
  891. return asSafeString(read())
  892. }
  893. let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
  894. let entry = keyCache[key];
  895. let checkPosition = position$1;
  896. let end = position$1 + length - 3;
  897. let chunk;
  898. let i = 0;
  899. if (entry && entry.bytes == length) {
  900. while (checkPosition < end) {
  901. chunk = dataView.getUint32(checkPosition);
  902. if (chunk != entry[i++]) {
  903. checkPosition = 0x70000000;
  904. break
  905. }
  906. checkPosition += 4;
  907. }
  908. end += 3;
  909. while (checkPosition < end) {
  910. chunk = src[checkPosition++];
  911. if (chunk != entry[i++]) {
  912. checkPosition = 0x70000000;
  913. break
  914. }
  915. }
  916. if (checkPosition === end) {
  917. position$1 = checkPosition;
  918. return entry.string
  919. }
  920. end -= 3;
  921. checkPosition = position$1;
  922. }
  923. entry = [];
  924. keyCache[key] = entry;
  925. entry.bytes = length;
  926. while (checkPosition < end) {
  927. chunk = dataView.getUint32(checkPosition);
  928. entry.push(chunk);
  929. checkPosition += 4;
  930. }
  931. end += 3;
  932. while (checkPosition < end) {
  933. chunk = src[checkPosition++];
  934. entry.push(chunk);
  935. }
  936. // for small blocks, avoiding the overhead of the extract call is helpful
  937. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  938. if (string != null)
  939. return entry.string = string
  940. return entry.string = readFixedString(length)
  941. }
  942. function asSafeString(property) {
  943. // protect against expensive (DoS) string conversions
  944. if (typeof property === 'string') return property;
  945. if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
  946. if (property == null) return property + '';
  947. if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {
  948. return property.flat().toString();
  949. }
  950. throw new Error(`Invalid property type for record: ${typeof property}`);
  951. }
  952. // the registration of the record definition extension (as "r")
  953. const recordDefinition = (id, highByte) => {
  954. let structure = read().map(asSafeString); // ensure that all keys are strings and
  955. // that the array is mutable
  956. let firstByte = id;
  957. if (highByte !== undefined) {
  958. id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  959. structure.highByte = highByte;
  960. }
  961. let existingStructure = currentStructures[id];
  962. // If it is a shared structure, we need to restore any changes after reading.
  963. // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
  964. // to the state prior to an incomplete read in order to properly resume.
  965. if (existingStructure && (existingStructure.isShared || sequentialMode)) {
  966. (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  967. }
  968. currentStructures[id] = structure;
  969. structure.read = createStructureReader(structure, firstByte);
  970. return structure.read()
  971. };
  972. currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  973. currentExtensions[0].noBuffer = true;
  974. currentExtensions[0x42] = data => {
  975. let headLength = (data.byteLength % 8) || 8;
  976. let head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  977. for (let i = 1; i < headLength; i++) {
  978. head <<= BigInt(8);
  979. head += BigInt(data[i]);
  980. }
  981. if (data.byteLength !== headLength) {
  982. let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  983. let decode = (start, end) => {
  984. let length = end - start;
  985. if (length <= 40) {
  986. let out = view.getBigUint64(start);
  987. for (let i = start + 8; i < end; i += 8) {
  988. out <<= BigInt(64n);
  989. out |= view.getBigUint64(i);
  990. }
  991. return out
  992. }
  993. // if (length === 8) return view.getBigUint64(start)
  994. let middle = start + (length >> 4 << 3);
  995. let left = decode(start, middle);
  996. let right = decode(middle, end);
  997. return (left << BigInt((end - middle) * 8)) | right
  998. };
  999. head = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);
  1000. }
  1001. return head
  1002. };
  1003. let errors = {
  1004. Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,
  1005. };
  1006. currentExtensions[0x65] = () => {
  1007. let data = read();
  1008. if (!errors[data[0]]) {
  1009. let error = Error(data[1], { cause: data[2] });
  1010. error.name = data[0];
  1011. return error
  1012. }
  1013. return errors[data[0]](data[1], { cause: data[2] })
  1014. };
  1015. currentExtensions[0x69] = (data) => {
  1016. // id extension (for structured clones)
  1017. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1018. let id = dataView.getUint32(position$1 - 4);
  1019. if (!referenceMap)
  1020. referenceMap = new Map();
  1021. let token = src[position$1];
  1022. let target;
  1023. // TODO: handle any other types that can cycle and make the code more robust if there are other extensions
  1024. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  1025. target = [];
  1026. else if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)
  1027. target = new Map();
  1028. else if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position$1 + 1] === 0x73)
  1029. target = new Set();
  1030. else
  1031. target = {};
  1032. let refEntry = { target }; // a placeholder object
  1033. referenceMap.set(id, refEntry);
  1034. let targetProperties = read(); // read the next value as the target object to id
  1035. if (!refEntry.used) {
  1036. // no cycle, can just use the returned read object
  1037. return refEntry.target = targetProperties // replace the placeholder with the real one
  1038. } else {
  1039. // there is a cycle, so we have to assign properties to original target
  1040. Object.assign(target, targetProperties);
  1041. }
  1042. // copy over map/set entries if we're able to
  1043. if (target instanceof Map)
  1044. for (let [k, v] of targetProperties.entries()) target.set(k, v);
  1045. if (target instanceof Set)
  1046. for (let i of Array.from(targetProperties)) target.add(i);
  1047. return target
  1048. };
  1049. currentExtensions[0x70] = (data) => {
  1050. // pointer extension (for structured clones)
  1051. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1052. let id = dataView.getUint32(position$1 - 4);
  1053. let refEntry = referenceMap.get(id);
  1054. refEntry.used = true;
  1055. return refEntry.target
  1056. };
  1057. currentExtensions[0x73] = () => new Set(read());
  1058. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1059. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1060. currentExtensions[0x74] = (data) => {
  1061. let typeCode = data[0];
  1062. // we always have to slice to get a new ArrayBuffer that is aligned
  1063. let buffer = Uint8Array.prototype.slice.call(data, 1).buffer;
  1064. let typedArrayName = typedArrays[typeCode];
  1065. if (!typedArrayName) {
  1066. if (typeCode === 16) return buffer
  1067. if (typeCode === 17) return new DataView(buffer)
  1068. throw new Error('Could not find typed array for code ' + typeCode)
  1069. }
  1070. return new glbl[typedArrayName](buffer)
  1071. };
  1072. currentExtensions[0x78] = () => {
  1073. let data = read();
  1074. return new RegExp(data[0], data[1])
  1075. };
  1076. const TEMP_BUNDLE = [];
  1077. currentExtensions[0x62] = (data) => {
  1078. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1079. let dataPosition = position$1;
  1080. position$1 += dataSize - data.length;
  1081. bundledStrings$1 = TEMP_BUNDLE;
  1082. bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
  1083. bundledStrings$1.position0 = 0;
  1084. bundledStrings$1.position1 = 0;
  1085. bundledStrings$1.postBundlePosition = position$1;
  1086. position$1 = dataPosition;
  1087. return read()
  1088. };
  1089. currentExtensions[0xff] = (data) => {
  1090. // 32-bit date extension
  1091. if (data.length == 4)
  1092. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1093. else if (data.length == 8)
  1094. return new Date(
  1095. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1096. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1097. else if (data.length == 12)
  1098. return new Date(
  1099. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1100. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1101. else
  1102. return new Date('invalid')
  1103. };
  1104. // registration of bulk record definition?
  1105. // currentExtensions[0x52] = () =>
  1106. function saveState$1(callback) {
  1107. if (onSaveState)
  1108. onSaveState();
  1109. let savedSrcEnd = srcEnd;
  1110. let savedPosition = position$1;
  1111. let savedStringPosition = stringPosition;
  1112. let savedSrcStringStart = srcStringStart;
  1113. let savedSrcStringEnd = srcStringEnd;
  1114. let savedSrcString = srcString;
  1115. let savedStrings = strings;
  1116. let savedReferenceMap = referenceMap;
  1117. let savedBundledStrings = bundledStrings$1;
  1118. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1119. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1120. let savedStructures = currentStructures;
  1121. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1122. let savedPackr = currentUnpackr;
  1123. let savedSequentialMode = sequentialMode;
  1124. let value = callback();
  1125. srcEnd = savedSrcEnd;
  1126. position$1 = savedPosition;
  1127. stringPosition = savedStringPosition;
  1128. srcStringStart = savedSrcStringStart;
  1129. srcStringEnd = savedSrcStringEnd;
  1130. srcString = savedSrcString;
  1131. strings = savedStrings;
  1132. referenceMap = savedReferenceMap;
  1133. bundledStrings$1 = savedBundledStrings;
  1134. src = savedSrc;
  1135. sequentialMode = savedSequentialMode;
  1136. currentStructures = savedStructures;
  1137. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1138. currentUnpackr = savedPackr;
  1139. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1140. return value
  1141. }
  1142. function clearSource() {
  1143. src = null;
  1144. referenceMap = null;
  1145. currentStructures = null;
  1146. }
  1147. function addExtension$2(extension) {
  1148. if (extension.unpack)
  1149. currentExtensions[extension.type] = extension.unpack;
  1150. else
  1151. currentExtensions[extension.type] = extension;
  1152. }
  1153. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1154. for (let i = 0; i < 256; i++) {
  1155. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1156. }
  1157. var defaultUnpackr = new Unpackr$1({ useRecords: false });
  1158. const unpack$1 = defaultUnpackr.unpack;
  1159. const unpackMultiple$1 = defaultUnpackr.unpackMultiple;
  1160. defaultUnpackr.unpack;
  1161. const FLOAT32_OPTIONS = {
  1162. NEVER: 0,
  1163. ALWAYS: 1,
  1164. DECIMAL_ROUND: 3,
  1165. DECIMAL_FIT: 4
  1166. };
  1167. let f32Array = new Float32Array(1);
  1168. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1169. function roundFloat32$1(float32Number) {
  1170. f32Array[0] = float32Number;
  1171. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1172. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1173. }
  1174. function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
  1175. readStruct$1 = updatedReadStruct;
  1176. onLoadedStructures$1 = loadedStructs;
  1177. onSaveState = saveState;
  1178. }
  1179. let textEncoder$1;
  1180. try {
  1181. textEncoder$1 = new TextEncoder();
  1182. } catch (error) {}
  1183. let extensions, extensionClasses;
  1184. const hasNodeBuffer$1 = typeof Buffer !== 'undefined';
  1185. const ByteArrayAllocate = hasNodeBuffer$1 ?
  1186. function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
  1187. const ByteArray = hasNodeBuffer$1 ? Buffer : Uint8Array;
  1188. const MAX_BUFFER_SIZE = hasNodeBuffer$1 ? 0x100000000 : 0x7fd00000;
  1189. let target, keysTarget;
  1190. let targetView;
  1191. let position = 0;
  1192. let safeEnd;
  1193. let bundledStrings = null;
  1194. let writeStructSlots;
  1195. const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
  1196. const hasNonLatin = /[\u0080-\uFFFF]/;
  1197. const RECORD_SYMBOL = Symbol('record-id');
  1198. let Packr$1 = class Packr extends Unpackr$1 {
  1199. constructor(options) {
  1200. super(options);
  1201. this.offset = 0;
  1202. let start;
  1203. let hasSharedUpdate;
  1204. let structures;
  1205. let referenceMap;
  1206. let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
  1207. return target.utf8Write(string, position, target.byteLength - position)
  1208. } : (textEncoder$1 && textEncoder$1.encodeInto) ?
  1209. function(string, position) {
  1210. return textEncoder$1.encodeInto(string, target.subarray(position)).written
  1211. } : false;
  1212. let packr = this;
  1213. if (!options)
  1214. options = {};
  1215. let isSequential = options && options.sequential;
  1216. let hasSharedStructures = options.structures || options.saveStructures;
  1217. let maxSharedStructures = options.maxSharedStructures;
  1218. if (maxSharedStructures == null)
  1219. maxSharedStructures = hasSharedStructures ? 32 : 0;
  1220. if (maxSharedStructures > 8160)
  1221. throw new Error('Maximum maxSharedStructure is 8160')
  1222. if (options.structuredClone && options.moreTypes == undefined) {
  1223. this.moreTypes = true;
  1224. }
  1225. let maxOwnStructures = options.maxOwnStructures;
  1226. if (maxOwnStructures == null)
  1227. maxOwnStructures = hasSharedStructures ? 32 : 64;
  1228. if (!this.structures && options.useRecords != false)
  1229. this.structures = [];
  1230. // two byte record ids for shared structures
  1231. let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
  1232. let sharedLimitId = maxSharedStructures + 0x40;
  1233. let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
  1234. if (maxStructureId > 8256) {
  1235. throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
  1236. }
  1237. let recordIdsToRemove = [];
  1238. let transitionsCount = 0;
  1239. let serializationsSinceTransitionRebuild = 0;
  1240. this.pack = this.encode = function(value, encodeOptions) {
  1241. if (!target) {
  1242. target = new ByteArrayAllocate(8192);
  1243. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
  1244. position = 0;
  1245. }
  1246. safeEnd = target.length - 10;
  1247. if (safeEnd - position < 0x800) {
  1248. // don't start too close to the end,
  1249. target = new ByteArrayAllocate(target.length);
  1250. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
  1251. safeEnd = target.length - 10;
  1252. position = 0;
  1253. } else
  1254. position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
  1255. start = position;
  1256. if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
  1257. referenceMap = packr.structuredClone ? new Map() : null;
  1258. if (packr.bundleStrings && typeof value !== 'string') {
  1259. bundledStrings = [];
  1260. bundledStrings.size = Infinity; // force a new bundle start on first string
  1261. } else
  1262. bundledStrings = null;
  1263. structures = packr.structures;
  1264. if (structures) {
  1265. if (structures.uninitialized)
  1266. structures = packr._mergeStructures(packr.getStructures());
  1267. let sharedLength = structures.sharedLength || 0;
  1268. if (sharedLength > maxSharedStructures) {
  1269. //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
  1270. throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
  1271. }
  1272. if (!structures.transitions) {
  1273. // rebuild our structure transitions
  1274. structures.transitions = Object.create(null);
  1275. for (let i = 0; i < sharedLength; i++) {
  1276. let keys = structures[i];
  1277. if (!keys)
  1278. continue
  1279. let nextTransition, transition = structures.transitions;
  1280. for (let j = 0, l = keys.length; j < l; j++) {
  1281. let key = keys[j];
  1282. nextTransition = transition[key];
  1283. if (!nextTransition) {
  1284. nextTransition = transition[key] = Object.create(null);
  1285. }
  1286. transition = nextTransition;
  1287. }
  1288. transition[RECORD_SYMBOL] = i + 0x40;
  1289. }
  1290. this.lastNamedStructuresLength = sharedLength;
  1291. }
  1292. if (!isSequential) {
  1293. structures.nextId = sharedLength + 0x40;
  1294. }
  1295. }
  1296. if (hasSharedUpdate)
  1297. hasSharedUpdate = false;
  1298. let encodingError;
  1299. try {
  1300. if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
  1301. writeStruct(value);
  1302. else
  1303. pack(value);
  1304. let lastBundle = bundledStrings;
  1305. if (bundledStrings)
  1306. writeBundles(start, pack, 0);
  1307. if (referenceMap && referenceMap.idsToInsert) {
  1308. let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  1309. let i = idsToInsert.length;
  1310. let incrementPosition = -1;
  1311. while (lastBundle && i > 0) {
  1312. let insertionPoint = idsToInsert[--i].offset + start;
  1313. if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
  1314. incrementPosition = 0;
  1315. if (insertionPoint > (lastBundle.position + start)) {
  1316. if (incrementPosition >= 0)
  1317. incrementPosition += 6;
  1318. } else {
  1319. if (incrementPosition >= 0) {
  1320. // update the bundle reference now
  1321. targetView.setUint32(lastBundle.position + start,
  1322. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1323. incrementPosition = -1; // reset
  1324. }
  1325. lastBundle = lastBundle.previous;
  1326. i++;
  1327. }
  1328. }
  1329. if (incrementPosition >= 0 && lastBundle) {
  1330. // update the bundle reference now
  1331. targetView.setUint32(lastBundle.position + start,
  1332. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1333. }
  1334. position += idsToInsert.length * 6;
  1335. if (position > safeEnd)
  1336. makeRoom(position);
  1337. packr.offset = position;
  1338. let serialized = insertIds(target.subarray(start, position), idsToInsert);
  1339. referenceMap = null;
  1340. return serialized
  1341. }
  1342. packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
  1343. if (encodeOptions & REUSE_BUFFER_MODE) {
  1344. target.start = start;
  1345. target.end = position;
  1346. return target
  1347. }
  1348. return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
  1349. } catch(error) {
  1350. encodingError = error;
  1351. throw error;
  1352. } finally {
  1353. if (structures) {
  1354. resetStructures();
  1355. if (hasSharedUpdate && packr.saveStructures) {
  1356. let sharedLength = structures.sharedLength || 0;
  1357. // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
  1358. let returnBuffer = target.subarray(start, position);
  1359. let newSharedData = prepareStructures$1(structures, packr);
  1360. if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
  1361. if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
  1362. // get updated structures and try again if the update failed
  1363. return packr.pack(value, encodeOptions)
  1364. }
  1365. packr.lastNamedStructuresLength = sharedLength;
  1366. // don't keep large buffers around
  1367. if (target.length > 0x40000000) target = null;
  1368. return returnBuffer
  1369. }
  1370. }
  1371. }
  1372. // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
  1373. if (target.length > 0x40000000) target = null;
  1374. if (encodeOptions & RESET_BUFFER_MODE)
  1375. position = start;
  1376. }
  1377. };
  1378. const resetStructures = () => {
  1379. if (serializationsSinceTransitionRebuild < 10)
  1380. serializationsSinceTransitionRebuild++;
  1381. let sharedLength = structures.sharedLength || 0;
  1382. if (structures.length > sharedLength && !isSequential)
  1383. structures.length = sharedLength;
  1384. if (transitionsCount > 10000) {
  1385. // force a rebuild occasionally after a lot of transitions so it can get cleaned up
  1386. structures.transitions = null;
  1387. serializationsSinceTransitionRebuild = 0;
  1388. transitionsCount = 0;
  1389. if (recordIdsToRemove.length > 0)
  1390. recordIdsToRemove = [];
  1391. } else if (recordIdsToRemove.length > 0 && !isSequential) {
  1392. for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
  1393. recordIdsToRemove[i][RECORD_SYMBOL] = 0;
  1394. }
  1395. recordIdsToRemove = [];
  1396. }
  1397. };
  1398. const packArray = (value) => {
  1399. var length = value.length;
  1400. if (length < 0x10) {
  1401. target[position++] = 0x90 | length;
  1402. } else if (length < 0x10000) {
  1403. target[position++] = 0xdc;
  1404. target[position++] = length >> 8;
  1405. target[position++] = length & 0xff;
  1406. } else {
  1407. target[position++] = 0xdd;
  1408. targetView.setUint32(position, length);
  1409. position += 4;
  1410. }
  1411. for (let i = 0; i < length; i++) {
  1412. pack(value[i]);
  1413. }
  1414. };
  1415. const pack = (value) => {
  1416. if (position > safeEnd)
  1417. target = makeRoom(position);
  1418. var type = typeof value;
  1419. var length;
  1420. if (type === 'string') {
  1421. let strLength = value.length;
  1422. if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
  1423. if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
  1424. let extStart;
  1425. let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
  1426. if (position + maxBytes > safeEnd)
  1427. target = makeRoom(position + maxBytes);
  1428. let lastBundle;
  1429. 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
  1430. lastBundle = bundledStrings;
  1431. target[position] = 0xc8; // ext 16
  1432. position += 3; // reserve for the writing bundle size
  1433. target[position++] = 0x62; // 'b'
  1434. extStart = position - start;
  1435. position += 4; // reserve for writing bundle reference
  1436. writeBundles(start, pack, 0); // write the last bundles
  1437. targetView.setUint16(extStart + start - 3, position - start - extStart);
  1438. } 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)
  1439. target[position++] = 0xd6; // fixext 4
  1440. target[position++] = 0x62; // 'b'
  1441. extStart = position - start;
  1442. position += 4; // reserve for writing bundle reference
  1443. }
  1444. bundledStrings = ['', '']; // create new ones
  1445. bundledStrings.previous = lastBundle;
  1446. bundledStrings.size = 0;
  1447. bundledStrings.position = extStart;
  1448. }
  1449. let twoByte = hasNonLatin.test(value);
  1450. bundledStrings[twoByte ? 0 : 1] += value;
  1451. target[position++] = 0xc1;
  1452. pack(twoByte ? -strLength : strLength);
  1453. return
  1454. }
  1455. let headerSize;
  1456. // first we estimate the header size, so we can write to the correct location
  1457. if (strLength < 0x20) {
  1458. headerSize = 1;
  1459. } else if (strLength < 0x100) {
  1460. headerSize = 2;
  1461. } else if (strLength < 0x10000) {
  1462. headerSize = 3;
  1463. } else {
  1464. headerSize = 5;
  1465. }
  1466. let maxBytes = strLength * 3;
  1467. if (position + maxBytes > safeEnd)
  1468. target = makeRoom(position + maxBytes);
  1469. if (strLength < 0x40 || !encodeUtf8) {
  1470. let i, c1, c2, strPosition = position + headerSize;
  1471. for (i = 0; i < strLength; i++) {
  1472. c1 = value.charCodeAt(i);
  1473. if (c1 < 0x80) {
  1474. target[strPosition++] = c1;
  1475. } else if (c1 < 0x800) {
  1476. target[strPosition++] = c1 >> 6 | 0xc0;
  1477. target[strPosition++] = c1 & 0x3f | 0x80;
  1478. } else if (
  1479. (c1 & 0xfc00) === 0xd800 &&
  1480. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  1481. ) {
  1482. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  1483. i++;
  1484. target[strPosition++] = c1 >> 18 | 0xf0;
  1485. target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
  1486. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1487. target[strPosition++] = c1 & 0x3f | 0x80;
  1488. } else {
  1489. target[strPosition++] = c1 >> 12 | 0xe0;
  1490. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1491. target[strPosition++] = c1 & 0x3f | 0x80;
  1492. }
  1493. }
  1494. length = strPosition - position - headerSize;
  1495. } else {
  1496. length = encodeUtf8(value, position + headerSize);
  1497. }
  1498. if (length < 0x20) {
  1499. target[position++] = 0xa0 | length;
  1500. } else if (length < 0x100) {
  1501. if (headerSize < 2) {
  1502. target.copyWithin(position + 2, position + 1, position + 1 + length);
  1503. }
  1504. target[position++] = 0xd9;
  1505. target[position++] = length;
  1506. } else if (length < 0x10000) {
  1507. if (headerSize < 3) {
  1508. target.copyWithin(position + 3, position + 2, position + 2 + length);
  1509. }
  1510. target[position++] = 0xda;
  1511. target[position++] = length >> 8;
  1512. target[position++] = length & 0xff;
  1513. } else {
  1514. if (headerSize < 5) {
  1515. target.copyWithin(position + 5, position + 3, position + 3 + length);
  1516. }
  1517. target[position++] = 0xdb;
  1518. targetView.setUint32(position, length);
  1519. position += 4;
  1520. }
  1521. position += length;
  1522. } else if (type === 'number') {
  1523. if (value >>> 0 === value) {// positive integer, 32-bit or less
  1524. // positive uint
  1525. if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
  1526. target[position++] = value;
  1527. } else if (value < 0x100) {
  1528. target[position++] = 0xcc;
  1529. target[position++] = value;
  1530. } else if (value < 0x10000) {
  1531. target[position++] = 0xcd;
  1532. target[position++] = value >> 8;
  1533. target[position++] = value & 0xff;
  1534. } else {
  1535. target[position++] = 0xce;
  1536. targetView.setUint32(position, value);
  1537. position += 4;
  1538. }
  1539. } else if (value >> 0 === value) { // negative integer
  1540. if (value >= -0x20) {
  1541. target[position++] = 0x100 + value;
  1542. } else if (value >= -0x80) {
  1543. target[position++] = 0xd0;
  1544. target[position++] = value + 0x100;
  1545. } else if (value >= -0x8000) {
  1546. target[position++] = 0xd1;
  1547. targetView.setInt16(position, value);
  1548. position += 2;
  1549. } else {
  1550. target[position++] = 0xd2;
  1551. targetView.setInt32(position, value);
  1552. position += 4;
  1553. }
  1554. } else {
  1555. let useFloat32;
  1556. if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
  1557. target[position++] = 0xca;
  1558. targetView.setFloat32(position, value);
  1559. let xShifted;
  1560. if (useFloat32 < 4 ||
  1561. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  1562. ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
  1563. position += 4;
  1564. return
  1565. } else
  1566. position--; // move back into position for writing a double
  1567. }
  1568. target[position++] = 0xcb;
  1569. targetView.setFloat64(position, value);
  1570. position += 8;
  1571. }
  1572. } else if (type === 'object' || type === 'function') {
  1573. if (!value)
  1574. target[position++] = 0xc0;
  1575. else {
  1576. if (referenceMap) {
  1577. let referee = referenceMap.get(value);
  1578. if (referee) {
  1579. if (!referee.id) {
  1580. let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
  1581. referee.id = idsToInsert.push(referee);
  1582. }
  1583. target[position++] = 0xd6; // fixext 4
  1584. target[position++] = 0x70; // "p" for pointer
  1585. targetView.setUint32(position, referee.id);
  1586. position += 4;
  1587. return
  1588. } else
  1589. referenceMap.set(value, { offset: position - start });
  1590. }
  1591. let constructor = value.constructor;
  1592. if (constructor === Object) {
  1593. writeObject(value);
  1594. } else if (constructor === Array) {
  1595. packArray(value);
  1596. } else if (constructor === Map) {
  1597. if (this.mapAsEmptyObject) target[position++] = 0x80;
  1598. else {
  1599. length = value.size;
  1600. if (length < 0x10) {
  1601. target[position++] = 0x80 | length;
  1602. } else if (length < 0x10000) {
  1603. target[position++] = 0xde;
  1604. target[position++] = length >> 8;
  1605. target[position++] = length & 0xff;
  1606. } else {
  1607. target[position++] = 0xdf;
  1608. targetView.setUint32(position, length);
  1609. position += 4;
  1610. }
  1611. for (let [key, entryValue] of value) {
  1612. pack(key);
  1613. pack(entryValue);
  1614. }
  1615. }
  1616. } else {
  1617. for (let i = 0, l = extensions.length; i < l; i++) {
  1618. let extensionClass = extensionClasses[i];
  1619. if (value instanceof extensionClass) {
  1620. let extension = extensions[i];
  1621. if (extension.write) {
  1622. if (extension.type) {
  1623. target[position++] = 0xd4; // one byte "tag" extension
  1624. target[position++] = extension.type;
  1625. target[position++] = 0;
  1626. }
  1627. let writeResult = extension.write.call(this, value);
  1628. if (writeResult === value) { // avoid infinite recursion
  1629. if (Array.isArray(value)) {
  1630. packArray(value);
  1631. } else {
  1632. writeObject(value);
  1633. }
  1634. } else {
  1635. pack(writeResult);
  1636. }
  1637. return
  1638. }
  1639. let currentTarget = target;
  1640. let currentTargetView = targetView;
  1641. let currentPosition = position;
  1642. target = null;
  1643. let result;
  1644. try {
  1645. result = extension.pack.call(this, value, (size) => {
  1646. // restore target and use it
  1647. target = currentTarget;
  1648. currentTarget = null;
  1649. position += size;
  1650. if (position > safeEnd)
  1651. makeRoom(position);
  1652. return {
  1653. target, targetView, position: position - size
  1654. }
  1655. }, pack);
  1656. } finally {
  1657. // restore current target information (unless already restored)
  1658. if (currentTarget) {
  1659. target = currentTarget;
  1660. targetView = currentTargetView;
  1661. position = currentPosition;
  1662. safeEnd = target.length - 10;
  1663. }
  1664. }
  1665. if (result) {
  1666. if (result.length + position > safeEnd)
  1667. makeRoom(result.length + position);
  1668. position = writeExtensionData(result, target, position, extension.type);
  1669. }
  1670. return
  1671. }
  1672. }
  1673. // check isArray after extensions, because extensions can extend Array
  1674. if (Array.isArray(value)) {
  1675. packArray(value);
  1676. } else {
  1677. // use this as an alternate mechanism for expressing how to serialize
  1678. if (value.toJSON) {
  1679. const json = value.toJSON();
  1680. // if for some reason value.toJSON returns itself it'll loop forever
  1681. if (json !== value)
  1682. return pack(json)
  1683. }
  1684. // if there is a writeFunction, use it, otherwise just encode as undefined
  1685. if (type === 'function')
  1686. return pack(this.writeFunction && this.writeFunction(value));
  1687. // no extension found, write as plain object
  1688. writeObject(value);
  1689. }
  1690. }
  1691. }
  1692. } else if (type === 'boolean') {
  1693. target[position++] = value ? 0xc3 : 0xc2;
  1694. } else if (type === 'bigint') {
  1695. if (value < 0x8000000000000000 && value >= -0x8000000000000000) {
  1696. // use a signed int as long as it fits
  1697. target[position++] = 0xd3;
  1698. targetView.setBigInt64(position, value);
  1699. } else if (value < 0x10000000000000000 && value > 0) {
  1700. // if we can fit an unsigned int, use that
  1701. target[position++] = 0xcf;
  1702. targetView.setBigUint64(position, value);
  1703. } else {
  1704. // overflow
  1705. if (this.largeBigIntToFloat) {
  1706. target[position++] = 0xcb;
  1707. targetView.setFloat64(position, Number(value));
  1708. } else if (this.largeBigIntToString) {
  1709. return pack(value.toString());
  1710. } else if (this.useBigIntExtension || this.moreTypes) {
  1711. let empty = value < 0 ? BigInt(-1) : BigInt(0);
  1712. let array;
  1713. if (value >> BigInt(0x10000) === empty) {
  1714. let mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow
  1715. let chunks = [];
  1716. while (true) {
  1717. chunks.push(value & mask);
  1718. if ((value >> BigInt(63)) === empty) break
  1719. value >>= BigInt(64);
  1720. }
  1721. array = new Uint8Array(new BigUint64Array(chunks).buffer);
  1722. array.reverse();
  1723. } else {
  1724. let invert = value < 0;
  1725. let string = (invert ? ~value : value).toString(16);
  1726. if (string.length % 2) {
  1727. string = '0' + string;
  1728. } else if (parseInt(string.charAt(0), 16) >= 8) {
  1729. string = '00' + string;
  1730. }
  1731. if (hasNodeBuffer$1) {
  1732. array = Buffer.from(string, 'hex');
  1733. } else {
  1734. array = new Uint8Array(string.length / 2);
  1735. for (let i = 0; i < array.length; i++) {
  1736. array[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);
  1737. }
  1738. }
  1739. if (invert) {
  1740. for (let i = 0; i < array.length; i++) array[i] = ~array[i];
  1741. }
  1742. }
  1743. if (array.length + position > safeEnd)
  1744. makeRoom(array.length + position);
  1745. position = writeExtensionData(array, target, position, 0x42);
  1746. return
  1747. } else {
  1748. throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
  1749. ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +
  1750. ' largeBigIntToString to convert to string')
  1751. }
  1752. }
  1753. position += 8;
  1754. } else if (type === 'undefined') {
  1755. if (this.encodeUndefinedAsNil)
  1756. target[position++] = 0xc0;
  1757. else {
  1758. target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
  1759. target[position++] = 0;
  1760. target[position++] = 0;
  1761. }
  1762. } else {
  1763. throw new Error('Unknown type: ' + type)
  1764. }
  1765. };
  1766. const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {
  1767. // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
  1768. let keys;
  1769. if (this.skipValues) {
  1770. keys = [];
  1771. for (let key in object) {
  1772. if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&
  1773. !this.skipValues.includes(object[key]))
  1774. keys.push(key);
  1775. }
  1776. } else {
  1777. keys = Object.keys(object);
  1778. }
  1779. let length = keys.length;
  1780. if (length < 0x10) {
  1781. target[position++] = 0x80 | length;
  1782. } else if (length < 0x10000) {
  1783. target[position++] = 0xde;
  1784. target[position++] = length >> 8;
  1785. target[position++] = length & 0xff;
  1786. } else {
  1787. target[position++] = 0xdf;
  1788. targetView.setUint32(position, length);
  1789. position += 4;
  1790. }
  1791. let key;
  1792. if (this.coercibleKeyAsNumber) {
  1793. for (let i = 0; i < length; i++) {
  1794. key = keys[i];
  1795. let num = Number(key);
  1796. pack(isNaN(num) ? key : num);
  1797. pack(object[key]);
  1798. }
  1799. } else {
  1800. for (let i = 0; i < length; i++) {
  1801. pack(key = keys[i]);
  1802. pack(object[key]);
  1803. }
  1804. }
  1805. } :
  1806. (object) => {
  1807. target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
  1808. let objectOffset = position - start;
  1809. position += 2;
  1810. let size = 0;
  1811. for (let key in object) {
  1812. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1813. pack(key);
  1814. pack(object[key]);
  1815. size++;
  1816. }
  1817. }
  1818. if (size > 0xffff) {
  1819. throw new Error('Object is too large to serialize with fast 16-bit map size,' +
  1820. ' use the "variableMapSize" option to serialize this object');
  1821. }
  1822. target[objectOffset++ + start] = size >> 8;
  1823. target[objectOffset + start] = size & 0xff;
  1824. };
  1825. const writeRecord = this.useRecords === false ? writePlainObject :
  1826. (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)
  1827. (object) => {
  1828. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1829. let objectOffset = position++ - start;
  1830. let wroteKeys;
  1831. for (let key in object) {
  1832. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1833. nextTransition = transition[key];
  1834. if (nextTransition)
  1835. transition = nextTransition;
  1836. else {
  1837. // record doesn't exist, create full new record and insert it
  1838. let keys = Object.keys(object);
  1839. let lastTransition = transition;
  1840. transition = structures.transitions;
  1841. let newTransitions = 0;
  1842. for (let i = 0, l = keys.length; i < l; i++) {
  1843. let key = keys[i];
  1844. nextTransition = transition[key];
  1845. if (!nextTransition) {
  1846. nextTransition = transition[key] = Object.create(null);
  1847. newTransitions++;
  1848. }
  1849. transition = nextTransition;
  1850. }
  1851. if (objectOffset + start + 1 == position) {
  1852. // first key, so we don't need to insert, we can just write record directly
  1853. position--;
  1854. newRecord(transition, keys, newTransitions);
  1855. } else // otherwise we need to insert the record, moving existing data after the record
  1856. insertNewRecord(transition, keys, objectOffset, newTransitions);
  1857. wroteKeys = true;
  1858. transition = lastTransition[key];
  1859. }
  1860. pack(object[key]);
  1861. }
  1862. }
  1863. if (!wroteKeys) {
  1864. let recordId = transition[RECORD_SYMBOL];
  1865. if (recordId)
  1866. target[objectOffset + start] = recordId;
  1867. else
  1868. insertNewRecord(transition, Object.keys(object), objectOffset, 0);
  1869. }
  1870. } :
  1871. (object) => {
  1872. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1873. let newTransitions = 0;
  1874. for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1875. nextTransition = transition[key];
  1876. if (!nextTransition) {
  1877. nextTransition = transition[key] = Object.create(null);
  1878. newTransitions++;
  1879. }
  1880. transition = nextTransition;
  1881. }
  1882. let recordId = transition[RECORD_SYMBOL];
  1883. if (recordId) {
  1884. if (recordId >= 0x60 && useTwoByteRecords) {
  1885. target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
  1886. target[position++] = recordId >> 5;
  1887. } else
  1888. target[position++] = recordId;
  1889. } else {
  1890. newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
  1891. }
  1892. // now write the values
  1893. for (let key in object)
  1894. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1895. pack(object[key]);
  1896. }
  1897. };
  1898. // create reference to useRecords if useRecords is a function
  1899. const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
  1900. const writeObject = checkUseRecords ? (object) => {
  1901. checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
  1902. } : writeRecord;
  1903. const makeRoom = (end) => {
  1904. let newSize;
  1905. if (end > 0x1000000) {
  1906. // special handling for really large buffers
  1907. if ((end - start) > MAX_BUFFER_SIZE)
  1908. throw new Error('Packed buffer would be larger than maximum buffer size')
  1909. newSize = Math.min(MAX_BUFFER_SIZE,
  1910. Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
  1911. } else // faster handling for smaller buffers
  1912. newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
  1913. let newBuffer = new ByteArrayAllocate(newSize);
  1914. targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
  1915. end = Math.min(end, target.length);
  1916. if (target.copy)
  1917. target.copy(newBuffer, 0, start, end);
  1918. else
  1919. newBuffer.set(target.slice(start, end));
  1920. position -= start;
  1921. start = 0;
  1922. safeEnd = newBuffer.length - 10;
  1923. return target = newBuffer
  1924. };
  1925. const newRecord = (transition, keys, newTransitions) => {
  1926. let recordId = structures.nextId;
  1927. if (!recordId)
  1928. recordId = 0x40;
  1929. if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
  1930. recordId = structures.nextOwnId;
  1931. if (!(recordId < maxStructureId))
  1932. recordId = sharedLimitId;
  1933. structures.nextOwnId = recordId + 1;
  1934. } else {
  1935. if (recordId >= maxStructureId)// cycle back around
  1936. recordId = sharedLimitId;
  1937. structures.nextId = recordId + 1;
  1938. }
  1939. let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
  1940. transition[RECORD_SYMBOL] = recordId;
  1941. transition.__keys__ = keys;
  1942. structures[recordId - 0x40] = keys;
  1943. if (recordId < sharedLimitId) {
  1944. keys.isShared = true;
  1945. structures.sharedLength = recordId - 0x3f;
  1946. hasSharedUpdate = true;
  1947. if (highByte >= 0) {
  1948. target[position++] = (recordId & 0x1f) + 0x60;
  1949. target[position++] = highByte;
  1950. } else {
  1951. target[position++] = recordId;
  1952. }
  1953. } else {
  1954. if (highByte >= 0) {
  1955. target[position++] = 0xd5; // fixext 2
  1956. target[position++] = 0x72; // "r" record defintion extension type
  1957. target[position++] = (recordId & 0x1f) + 0x60;
  1958. target[position++] = highByte;
  1959. } else {
  1960. target[position++] = 0xd4; // fixext 1
  1961. target[position++] = 0x72; // "r" record defintion extension type
  1962. target[position++] = recordId;
  1963. }
  1964. if (newTransitions)
  1965. transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
  1966. // record the removal of the id, we can maintain our shared structure
  1967. if (recordIdsToRemove.length >= maxOwnStructures)
  1968. recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
  1969. recordIdsToRemove.push(transition);
  1970. pack(keys);
  1971. }
  1972. };
  1973. const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
  1974. let mainTarget = target;
  1975. let mainPosition = position;
  1976. let mainSafeEnd = safeEnd;
  1977. let mainStart = start;
  1978. target = keysTarget;
  1979. position = 0;
  1980. start = 0;
  1981. if (!target)
  1982. keysTarget = target = new ByteArrayAllocate(8192);
  1983. safeEnd = target.length - 10;
  1984. newRecord(transition, keys, newTransitions);
  1985. keysTarget = target;
  1986. let keysPosition = position;
  1987. target = mainTarget;
  1988. position = mainPosition;
  1989. safeEnd = mainSafeEnd;
  1990. start = mainStart;
  1991. if (keysPosition > 1) {
  1992. let newEnd = position + keysPosition - 1;
  1993. if (newEnd > safeEnd)
  1994. makeRoom(newEnd);
  1995. let insertionPosition = insertionOffset + start;
  1996. target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
  1997. target.set(keysTarget.slice(0, keysPosition), insertionPosition);
  1998. position = newEnd;
  1999. } else {
  2000. target[insertionOffset + start] = keysTarget[0];
  2001. }
  2002. };
  2003. const writeStruct = (object) => {
  2004. let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
  2005. if (notifySharedUpdate)
  2006. return hasSharedUpdate = true;
  2007. position = newPosition;
  2008. let startTarget = target;
  2009. pack(value);
  2010. resetStructures();
  2011. if (startTarget !== target) {
  2012. return { position, targetView, target }; // indicate the buffer was re-allocated
  2013. }
  2014. return position;
  2015. }, this);
  2016. if (newPosition === 0) // bail and go to a msgpack object
  2017. return writeObject(object);
  2018. position = newPosition;
  2019. };
  2020. }
  2021. useBuffer(buffer) {
  2022. // this means we are finished using our own buffer and we can write over it safely
  2023. target = buffer;
  2024. target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));
  2025. targetView = target.dataView;
  2026. position = 0;
  2027. }
  2028. set position (value) {
  2029. position = value;
  2030. }
  2031. get position() {
  2032. return position;
  2033. }
  2034. clearSharedData() {
  2035. if (this.structures)
  2036. this.structures = [];
  2037. if (this.typedStructs)
  2038. this.typedStructs = [];
  2039. }
  2040. };
  2041. extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];
  2042. extensions = [{
  2043. pack(date, allocateForWrite, pack) {
  2044. let seconds = date.getTime() / 1000;
  2045. if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
  2046. // Timestamp 32
  2047. let { target, targetView, position} = allocateForWrite(6);
  2048. target[position++] = 0xd6;
  2049. target[position++] = 0xff;
  2050. targetView.setUint32(position, seconds);
  2051. } else if (seconds > 0 && seconds < 0x100000000) {
  2052. // Timestamp 64
  2053. let { target, targetView, position} = allocateForWrite(10);
  2054. target[position++] = 0xd7;
  2055. target[position++] = 0xff;
  2056. targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
  2057. targetView.setUint32(position + 4, seconds);
  2058. } else if (isNaN(seconds)) {
  2059. if (this.onInvalidDate) {
  2060. allocateForWrite(0);
  2061. return pack(this.onInvalidDate())
  2062. }
  2063. // Intentionally invalid timestamp
  2064. let { target, targetView, position} = allocateForWrite(3);
  2065. target[position++] = 0xd4;
  2066. target[position++] = 0xff;
  2067. target[position++] = 0xff;
  2068. } else {
  2069. // Timestamp 96
  2070. let { target, targetView, position} = allocateForWrite(15);
  2071. target[position++] = 0xc7;
  2072. target[position++] = 12;
  2073. target[position++] = 0xff;
  2074. targetView.setUint32(position, date.getMilliseconds() * 1000000);
  2075. targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
  2076. }
  2077. }
  2078. }, {
  2079. pack(set, allocateForWrite, pack) {
  2080. if (this.setAsEmptyObject) {
  2081. allocateForWrite(0);
  2082. return pack({})
  2083. }
  2084. let array = Array.from(set);
  2085. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2086. if (this.moreTypes) {
  2087. target[position++] = 0xd4;
  2088. target[position++] = 0x73; // 's' for Set
  2089. target[position++] = 0;
  2090. }
  2091. pack(array);
  2092. }
  2093. }, {
  2094. pack(error, allocateForWrite, pack) {
  2095. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2096. if (this.moreTypes) {
  2097. target[position++] = 0xd4;
  2098. target[position++] = 0x65; // 'e' for error
  2099. target[position++] = 0;
  2100. }
  2101. pack([ error.name, error.message, error.cause ]);
  2102. }
  2103. }, {
  2104. pack(regex, allocateForWrite, pack) {
  2105. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2106. if (this.moreTypes) {
  2107. target[position++] = 0xd4;
  2108. target[position++] = 0x78; // 'x' for regeXp
  2109. target[position++] = 0;
  2110. }
  2111. pack([ regex.source, regex.flags ]);
  2112. }
  2113. }, {
  2114. pack(arrayBuffer, allocateForWrite) {
  2115. if (this.moreTypes)
  2116. writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
  2117. else
  2118. writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2119. }
  2120. }, {
  2121. pack(typedArray, allocateForWrite) {
  2122. let constructor = typedArray.constructor;
  2123. if (constructor !== ByteArray && this.moreTypes)
  2124. writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
  2125. else
  2126. writeBuffer(typedArray, allocateForWrite);
  2127. }
  2128. }, {
  2129. pack(arrayBuffer, allocateForWrite) {
  2130. if (this.moreTypes)
  2131. writeExtBuffer(arrayBuffer, 0x11, allocateForWrite);
  2132. else
  2133. writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2134. }
  2135. }, {
  2136. pack(c1, allocateForWrite) { // specific 0xC1 object
  2137. let { target, position} = allocateForWrite(1);
  2138. target[position] = 0xc1;
  2139. }
  2140. }];
  2141. function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
  2142. let length = typedArray.byteLength;
  2143. if (length + 1 < 0x100) {
  2144. var { target, position } = allocateForWrite(4 + length);
  2145. target[position++] = 0xc7;
  2146. target[position++] = length + 1;
  2147. } else if (length + 1 < 0x10000) {
  2148. var { target, position } = allocateForWrite(5 + length);
  2149. target[position++] = 0xc8;
  2150. target[position++] = (length + 1) >> 8;
  2151. target[position++] = (length + 1) & 0xff;
  2152. } else {
  2153. var { target, position, targetView } = allocateForWrite(7 + length);
  2154. target[position++] = 0xc9;
  2155. targetView.setUint32(position, length + 1); // plus one for the type byte
  2156. position += 4;
  2157. }
  2158. target[position++] = 0x74; // "t" for typed array
  2159. target[position++] = type;
  2160. if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
  2161. target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
  2162. }
  2163. function writeBuffer(buffer, allocateForWrite) {
  2164. let length = buffer.byteLength;
  2165. var target, position;
  2166. if (length < 0x100) {
  2167. var { target, position } = allocateForWrite(length + 2);
  2168. target[position++] = 0xc4;
  2169. target[position++] = length;
  2170. } else if (length < 0x10000) {
  2171. var { target, position } = allocateForWrite(length + 3);
  2172. target[position++] = 0xc5;
  2173. target[position++] = length >> 8;
  2174. target[position++] = length & 0xff;
  2175. } else {
  2176. var { target, position, targetView } = allocateForWrite(length + 5);
  2177. target[position++] = 0xc6;
  2178. targetView.setUint32(position, length);
  2179. position += 4;
  2180. }
  2181. target.set(buffer, position);
  2182. }
  2183. function writeExtensionData(result, target, position, type) {
  2184. let length = result.length;
  2185. switch (length) {
  2186. case 1:
  2187. target[position++] = 0xd4;
  2188. break
  2189. case 2:
  2190. target[position++] = 0xd5;
  2191. break
  2192. case 4:
  2193. target[position++] = 0xd6;
  2194. break
  2195. case 8:
  2196. target[position++] = 0xd7;
  2197. break
  2198. case 16:
  2199. target[position++] = 0xd8;
  2200. break
  2201. default:
  2202. if (length < 0x100) {
  2203. target[position++] = 0xc7;
  2204. target[position++] = length;
  2205. } else if (length < 0x10000) {
  2206. target[position++] = 0xc8;
  2207. target[position++] = length >> 8;
  2208. target[position++] = length & 0xff;
  2209. } else {
  2210. target[position++] = 0xc9;
  2211. target[position++] = length >> 24;
  2212. target[position++] = (length >> 16) & 0xff;
  2213. target[position++] = (length >> 8) & 0xff;
  2214. target[position++] = length & 0xff;
  2215. }
  2216. }
  2217. target[position++] = type;
  2218. target.set(result, position);
  2219. position += length;
  2220. return position
  2221. }
  2222. function insertIds(serialized, idsToInsert) {
  2223. // insert the ids that need to be referenced for structured clones
  2224. let nextId;
  2225. let distanceToMove = idsToInsert.length * 6;
  2226. let lastEnd = serialized.length - distanceToMove;
  2227. while (nextId = idsToInsert.pop()) {
  2228. let offset = nextId.offset;
  2229. let id = nextId.id;
  2230. serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
  2231. distanceToMove -= 6;
  2232. let position = offset + distanceToMove;
  2233. serialized[position++] = 0xd6;
  2234. serialized[position++] = 0x69; // 'i'
  2235. serialized[position++] = id >> 24;
  2236. serialized[position++] = (id >> 16) & 0xff;
  2237. serialized[position++] = (id >> 8) & 0xff;
  2238. serialized[position++] = id & 0xff;
  2239. lastEnd = offset;
  2240. }
  2241. return serialized
  2242. }
  2243. function writeBundles(start, pack, incrementPosition) {
  2244. if (bundledStrings.length > 0) {
  2245. targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
  2246. bundledStrings.stringsPosition = position - start;
  2247. let writeStrings = bundledStrings;
  2248. bundledStrings = null;
  2249. pack(writeStrings[0]);
  2250. pack(writeStrings[1]);
  2251. }
  2252. }
  2253. function addExtension$1(extension) {
  2254. if (extension.Class) {
  2255. if (!extension.pack && !extension.write)
  2256. throw new Error('Extension has no pack or write function')
  2257. if (extension.pack && !extension.type)
  2258. throw new Error('Extension has no type (numeric code to identify the extension)')
  2259. extensionClasses.unshift(extension.Class);
  2260. extensions.unshift(extension);
  2261. }
  2262. addExtension$2(extension);
  2263. }
  2264. function prepareStructures$1(structures, packr) {
  2265. structures.isCompatible = (existingStructures) => {
  2266. let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
  2267. if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
  2268. packr._mergeStructures(existingStructures);
  2269. return compatible;
  2270. };
  2271. return structures
  2272. }
  2273. function setWriteStructSlots(writeSlots, makeStructures) {
  2274. writeStructSlots = writeSlots;
  2275. prepareStructures$1 = makeStructures;
  2276. }
  2277. let defaultPackr = new Packr$1({ useRecords: false });
  2278. const pack$1 = defaultPackr.pack;
  2279. defaultPackr.pack;
  2280. const REUSE_BUFFER_MODE = 512;
  2281. const RESET_BUFFER_MODE = 1024;
  2282. const RESERVE_START_SPACE = 2048;
  2283. const ASCII = 3; // the MIBenum from https://www.iana.org/assignments/character-sets/character-sets.xhtml (and other character encodings could be referenced by MIBenum)
  2284. const NUMBER = 0;
  2285. const UTF8 = 2;
  2286. const OBJECT_DATA = 1;
  2287. const DATE = 16;
  2288. const TYPE_NAMES = ['num', 'object', 'string', 'ascii'];
  2289. TYPE_NAMES[DATE] = 'date';
  2290. const float32Headers = [false, true, true, false, false, true, true, false];
  2291. let evalSupported;
  2292. try {
  2293. new Function('');
  2294. evalSupported = true;
  2295. } catch(error) {
  2296. // if eval variants are not supported, do not create inline object readers ever
  2297. }
  2298. let updatedPosition;
  2299. const hasNodeBuffer = typeof Buffer !== 'undefined';
  2300. let textEncoder, currentSource;
  2301. try {
  2302. textEncoder = new TextEncoder();
  2303. } catch (error) {}
  2304. const encodeUtf8 = hasNodeBuffer ? function(target, string, position) {
  2305. return target.utf8Write(string, position, target.byteLength - position)
  2306. } : (textEncoder && textEncoder.encodeInto) ?
  2307. function(target, string, position) {
  2308. return textEncoder.encodeInto(string, target.subarray(position)).written
  2309. } : false;
  2310. setWriteStructSlots(writeStruct, prepareStructures);
  2311. function writeStruct(object, target, encodingStart, position, structures, makeRoom, pack, packr) {
  2312. let typedStructs = packr.typedStructs || (packr.typedStructs = []);
  2313. // note that we rely on pack.js to load stored structures before we get to this point
  2314. let targetView = target.dataView;
  2315. let refsStartPosition = (typedStructs.lastStringStart || 100) + position;
  2316. let safeEnd = target.length - 10;
  2317. let start = position;
  2318. if (position > safeEnd) {
  2319. target = makeRoom(position);
  2320. targetView = target.dataView;
  2321. position -= encodingStart;
  2322. start -= encodingStart;
  2323. refsStartPosition -= encodingStart;
  2324. encodingStart = 0;
  2325. safeEnd = target.length - 10;
  2326. }
  2327. let refOffset, refPosition = refsStartPosition;
  2328. let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
  2329. let nextId = typedStructs.nextId || typedStructs.length;
  2330. let headerSize =
  2331. nextId < 0xf ? 1 :
  2332. nextId < 0xf0 ? 2 :
  2333. nextId < 0xf000 ? 3 :
  2334. nextId < 0xf00000 ? 4 : 0;
  2335. if (headerSize === 0)
  2336. return 0;
  2337. position += headerSize;
  2338. let queuedReferences = [];
  2339. let usedAscii0;
  2340. let keyIndex = 0;
  2341. for (let key in object) {
  2342. let value = object[key];
  2343. let nextTransition = transition[key];
  2344. if (!nextTransition) {
  2345. transition[key] = nextTransition = {
  2346. key,
  2347. parent: transition,
  2348. enumerationOffset: 0,
  2349. ascii0: null,
  2350. ascii8: null,
  2351. num8: null,
  2352. string16: null,
  2353. object16: null,
  2354. num32: null,
  2355. float64: null,
  2356. date64: null
  2357. };
  2358. }
  2359. if (position > safeEnd) {
  2360. target = makeRoom(position);
  2361. targetView = target.dataView;
  2362. position -= encodingStart;
  2363. start -= encodingStart;
  2364. refsStartPosition -= encodingStart;
  2365. refPosition -= encodingStart;
  2366. encodingStart = 0;
  2367. safeEnd = target.length - 10;
  2368. }
  2369. switch (typeof value) {
  2370. case 'number':
  2371. let number = value;
  2372. // first check to see if we are using a lot of ids and should default to wide/common format
  2373. if (nextId < 200 || !nextTransition.num64) {
  2374. if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
  2375. if (number < 0xf6 && number >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number < 0x20 && !nextTransition.num32)) {
  2376. transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1);
  2377. target[position++] = number;
  2378. } else {
  2379. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2380. targetView.setUint32(position, number, true);
  2381. position += 4;
  2382. }
  2383. break;
  2384. } else if (number < 0x100000000 && number >= -0x80000000) {
  2385. targetView.setFloat32(position, number, true);
  2386. if (float32Headers[target[position + 3] >>> 5]) {
  2387. let xShifted;
  2388. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2389. if (((xShifted = number * mult10[((target[position + 3] & 0x7f) << 1) | (target[position + 2] >> 7)]) >> 0) === xShifted) {
  2390. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2391. position += 4;
  2392. break;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8);
  2398. targetView.setFloat64(position, number, true);
  2399. position += 8;
  2400. break;
  2401. case 'string':
  2402. let strLength = value.length;
  2403. refOffset = refPosition - refsStartPosition;
  2404. if ((strLength << 2) + refPosition > safeEnd) {
  2405. target = makeRoom((strLength << 2) + refPosition);
  2406. targetView = target.dataView;
  2407. position -= encodingStart;
  2408. start -= encodingStart;
  2409. refsStartPosition -= encodingStart;
  2410. refPosition -= encodingStart;
  2411. encodingStart = 0;
  2412. safeEnd = target.length - 10;
  2413. }
  2414. if (strLength > ((0xff00 + refOffset) >> 2)) {
  2415. queuedReferences.push(key, value, position - start);
  2416. break;
  2417. }
  2418. let isNotAscii;
  2419. let strStart = refPosition;
  2420. if (strLength < 0x40) {
  2421. let i, c1, c2;
  2422. for (i = 0; i < strLength; i++) {
  2423. c1 = value.charCodeAt(i);
  2424. if (c1 < 0x80) {
  2425. target[refPosition++] = c1;
  2426. } else if (c1 < 0x800) {
  2427. isNotAscii = true;
  2428. target[refPosition++] = c1 >> 6 | 0xc0;
  2429. target[refPosition++] = c1 & 0x3f | 0x80;
  2430. } else if (
  2431. (c1 & 0xfc00) === 0xd800 &&
  2432. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  2433. ) {
  2434. isNotAscii = true;
  2435. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  2436. i++;
  2437. target[refPosition++] = c1 >> 18 | 0xf0;
  2438. target[refPosition++] = c1 >> 12 & 0x3f | 0x80;
  2439. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2440. target[refPosition++] = c1 & 0x3f | 0x80;
  2441. } else {
  2442. isNotAscii = true;
  2443. target[refPosition++] = c1 >> 12 | 0xe0;
  2444. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2445. target[refPosition++] = c1 & 0x3f | 0x80;
  2446. }
  2447. }
  2448. } else {
  2449. refPosition += encodeUtf8(target, value, refPosition);
  2450. isNotAscii = refPosition - strStart > strLength;
  2451. }
  2452. if (refOffset < 0xa0 || (refOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
  2453. // short strings
  2454. if (isNotAscii) {
  2455. if (!(transition = nextTransition.string8)) {
  2456. if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
  2457. // we can safely change ascii to utf8 in place since they are compatible
  2458. transition.__type = UTF8;
  2459. nextTransition.ascii8 = null;
  2460. nextTransition.string8 = transition;
  2461. pack(null, 0, true); // special call to notify that structures have been updated
  2462. } else {
  2463. transition = createTypeTransition(nextTransition, UTF8, 1);
  2464. }
  2465. }
  2466. } else if (refOffset === 0 && !usedAscii0) {
  2467. usedAscii0 = true;
  2468. transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0);
  2469. break; // don't increment position
  2470. }// else ascii:
  2471. else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8)))
  2472. transition = createTypeTransition(nextTransition, ASCII, 1);
  2473. target[position++] = refOffset;
  2474. } else {
  2475. // TODO: Enable ascii16 at some point, but get the logic right
  2476. //if (isNotAscii)
  2477. transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2);
  2478. //else
  2479. //transition = nextTransition.ascii16 || createTypeTransition(nextTransition, ASCII, 2);
  2480. targetView.setUint16(position, refOffset, true);
  2481. position += 2;
  2482. }
  2483. break;
  2484. case 'object':
  2485. if (value) {
  2486. if (value.constructor === Date) {
  2487. transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8);
  2488. targetView.setFloat64(position, value.getTime(), true);
  2489. position += 8;
  2490. } else {
  2491. queuedReferences.push(key, value, keyIndex);
  2492. }
  2493. break;
  2494. } else { // null
  2495. nextTransition = anyType(nextTransition, position, targetView, -10); // match CBOR with this
  2496. if (nextTransition) {
  2497. transition = nextTransition;
  2498. position = updatedPosition;
  2499. } else queuedReferences.push(key, value, keyIndex);
  2500. }
  2501. break;
  2502. case 'boolean':
  2503. transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1);
  2504. target[position++] = value ? 0xf9 : 0xf8; // match CBOR with these
  2505. break;
  2506. case 'undefined':
  2507. nextTransition = anyType(nextTransition, position, targetView, -9); // match CBOR with this
  2508. if (nextTransition) {
  2509. transition = nextTransition;
  2510. position = updatedPosition;
  2511. } else queuedReferences.push(key, value, keyIndex);
  2512. break;
  2513. default:
  2514. queuedReferences.push(key, value, keyIndex);
  2515. }
  2516. keyIndex++;
  2517. }
  2518. for (let i = 0, l = queuedReferences.length; i < l;) {
  2519. let key = queuedReferences[i++];
  2520. let value = queuedReferences[i++];
  2521. let propertyIndex = queuedReferences[i++];
  2522. let nextTransition = transition[key];
  2523. if (!nextTransition) {
  2524. transition[key] = nextTransition = {
  2525. key,
  2526. parent: transition,
  2527. enumerationOffset: propertyIndex - keyIndex,
  2528. ascii0: null,
  2529. ascii8: null,
  2530. num8: null,
  2531. string16: null,
  2532. object16: null,
  2533. num32: null,
  2534. float64: null
  2535. };
  2536. }
  2537. let newPosition;
  2538. if (value) {
  2539. /*if (typeof value === 'string') { // TODO: we could re-enable long strings
  2540. if (position + value.length * 3 > safeEnd) {
  2541. target = makeRoom(position + value.length * 3);
  2542. position -= start;
  2543. targetView = target.dataView;
  2544. start = 0;
  2545. }
  2546. newPosition = position + target.utf8Write(value, position, 0xffffffff);
  2547. } else { */
  2548. let size;
  2549. refOffset = refPosition - refsStartPosition;
  2550. if (refOffset < 0xff00) {
  2551. transition = nextTransition.object16;
  2552. if (transition)
  2553. size = 2;
  2554. else if ((transition = nextTransition.object32))
  2555. size = 4;
  2556. else {
  2557. transition = createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2558. size = 2;
  2559. }
  2560. } else {
  2561. transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4);
  2562. size = 4;
  2563. }
  2564. newPosition = pack(value, refPosition);
  2565. //}
  2566. if (typeof newPosition === 'object') {
  2567. // re-allocated
  2568. refPosition = newPosition.position;
  2569. targetView = newPosition.targetView;
  2570. target = newPosition.target;
  2571. refsStartPosition -= encodingStart;
  2572. position -= encodingStart;
  2573. start -= encodingStart;
  2574. encodingStart = 0;
  2575. } else
  2576. refPosition = newPosition;
  2577. if (size === 2) {
  2578. targetView.setUint16(position, refOffset, true);
  2579. position += 2;
  2580. } else {
  2581. targetView.setUint32(position, refOffset, true);
  2582. position += 4;
  2583. }
  2584. } else { // null or undefined
  2585. transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2586. targetView.setInt16(position, value === null ? -10 : -9, true);
  2587. position += 2;
  2588. }
  2589. keyIndex++;
  2590. }
  2591. let recordId = transition[RECORD_SYMBOL];
  2592. if (recordId == null) {
  2593. recordId = packr.typedStructs.length;
  2594. let structure = [];
  2595. let nextTransition = transition;
  2596. let key, type;
  2597. while ((type = nextTransition.__type) !== undefined) {
  2598. let size = nextTransition.__size;
  2599. nextTransition = nextTransition.__parent;
  2600. key = nextTransition.key;
  2601. let property = [type, size, key];
  2602. if (nextTransition.enumerationOffset)
  2603. property.push(nextTransition.enumerationOffset);
  2604. structure.push(property);
  2605. nextTransition = nextTransition.parent;
  2606. }
  2607. structure.reverse();
  2608. transition[RECORD_SYMBOL] = recordId;
  2609. packr.typedStructs[recordId] = structure;
  2610. pack(null, 0, true); // special call to notify that structures have been updated
  2611. }
  2612. switch (headerSize) {
  2613. case 1:
  2614. if (recordId >= 0x10) return 0;
  2615. target[start] = recordId + 0x20;
  2616. break;
  2617. case 2:
  2618. if (recordId >= 0x100) return 0;
  2619. target[start] = 0x38;
  2620. target[start + 1] = recordId;
  2621. break;
  2622. case 3:
  2623. if (recordId >= 0x10000) return 0;
  2624. target[start] = 0x39;
  2625. targetView.setUint16(start + 1, recordId, true);
  2626. break;
  2627. case 4:
  2628. if (recordId >= 0x1000000) return 0;
  2629. targetView.setUint32(start, (recordId << 8) + 0x3a, true);
  2630. break;
  2631. }
  2632. if (position < refsStartPosition) {
  2633. if (refsStartPosition === refPosition)
  2634. return position; // no refs
  2635. // adjust positioning
  2636. target.copyWithin(position, refsStartPosition, refPosition);
  2637. refPosition += position - refsStartPosition;
  2638. typedStructs.lastStringStart = position - start;
  2639. } else if (position > refsStartPosition) {
  2640. if (refsStartPosition === refPosition)
  2641. return position; // no refs
  2642. typedStructs.lastStringStart = position - start;
  2643. return writeStruct(object, target, encodingStart, start, structures, makeRoom, pack, packr);
  2644. }
  2645. return refPosition;
  2646. }
  2647. function anyType(transition, position, targetView, value) {
  2648. let nextTransition;
  2649. if ((nextTransition = transition.ascii8 || transition.num8)) {
  2650. targetView.setInt8(position, value, true);
  2651. updatedPosition = position + 1;
  2652. return nextTransition;
  2653. }
  2654. if ((nextTransition = transition.string16 || transition.object16)) {
  2655. targetView.setInt16(position, value, true);
  2656. updatedPosition = position + 2;
  2657. return nextTransition;
  2658. }
  2659. if (nextTransition = transition.num32) {
  2660. targetView.setUint32(position, 0xe0000100 + value, true);
  2661. updatedPosition = position + 4;
  2662. return nextTransition;
  2663. }
  2664. // transition.float64
  2665. if (nextTransition = transition.num64) {
  2666. targetView.setFloat64(position, NaN, true);
  2667. targetView.setInt8(position, value);
  2668. updatedPosition = position + 8;
  2669. return nextTransition;
  2670. }
  2671. updatedPosition = position;
  2672. // TODO: can we do an "any" type where we defer the decision?
  2673. return;
  2674. }
  2675. function createTypeTransition(transition, type, size) {
  2676. let typeName = TYPE_NAMES[type] + (size << 3);
  2677. let newTransition = transition[typeName] || (transition[typeName] = Object.create(null));
  2678. newTransition.__type = type;
  2679. newTransition.__size = size;
  2680. newTransition.__parent = transition;
  2681. return newTransition;
  2682. }
  2683. function onLoadedStructures(sharedData) {
  2684. if (!(sharedData instanceof Map))
  2685. return sharedData;
  2686. let typed = sharedData.get('typed') || [];
  2687. if (Object.isFrozen(typed))
  2688. typed = typed.map(structure => structure.slice(0));
  2689. let named = sharedData.get('named');
  2690. let transitions = Object.create(null);
  2691. for (let i = 0, l = typed.length; i < l; i++) {
  2692. let structure = typed[i];
  2693. let transition = transitions;
  2694. for (let [type, size, key] of structure) {
  2695. let nextTransition = transition[key];
  2696. if (!nextTransition) {
  2697. transition[key] = nextTransition = {
  2698. key,
  2699. parent: transition,
  2700. enumerationOffset: 0,
  2701. ascii0: null,
  2702. ascii8: null,
  2703. num8: null,
  2704. string16: null,
  2705. object16: null,
  2706. num32: null,
  2707. float64: null,
  2708. date64: null,
  2709. };
  2710. }
  2711. transition = createTypeTransition(nextTransition, type, size);
  2712. }
  2713. transition[RECORD_SYMBOL] = i;
  2714. }
  2715. typed.transitions = transitions;
  2716. this.typedStructs = typed;
  2717. this.lastTypedStructuresLength = typed.length;
  2718. return named;
  2719. }
  2720. var sourceSymbol = Symbol.for('source');
  2721. function readStruct(src, position, srcEnd, unpackr) {
  2722. let recordId = src[position++] - 0x20;
  2723. if (recordId >= 24) {
  2724. switch(recordId) {
  2725. case 24: recordId = src[position++]; break;
  2726. // little endian:
  2727. case 25: recordId = src[position++] + (src[position++] << 8); break;
  2728. case 26: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16); break;
  2729. case 27: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16) + (src[position++] << 24); break;
  2730. }
  2731. }
  2732. let structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
  2733. if (!structure) {
  2734. // copy src buffer because getStructures will override it
  2735. src = Uint8Array.prototype.slice.call(src, position, srcEnd);
  2736. srcEnd -= position;
  2737. position = 0;
  2738. if (!unpackr.getStructures)
  2739. throw new Error(`Reference to shared structure ${recordId} without getStructures method`);
  2740. unpackr._mergeStructures(unpackr.getStructures());
  2741. if (!unpackr.typedStructs)
  2742. throw new Error('Could not find any shared typed structures');
  2743. unpackr.lastTypedStructuresLength = unpackr.typedStructs.length;
  2744. structure = unpackr.typedStructs[recordId];
  2745. if (!structure)
  2746. throw new Error('Could not find typed structure ' + recordId);
  2747. }
  2748. var construct = structure.construct;
  2749. var fullConstruct = structure.fullConstruct;
  2750. if (!construct) {
  2751. construct = structure.construct = function LazyObject() {
  2752. };
  2753. fullConstruct = structure.fullConstruct = function LoadedObject() {
  2754. };
  2755. fullConstruct.prototype = unpackr.structPrototype || {};
  2756. var prototype = construct.prototype = unpackr.structPrototype ? Object.create(unpackr.structPrototype) : {};
  2757. let properties = [];
  2758. let currentOffset = 0;
  2759. let lastRefProperty;
  2760. for (let i = 0, l = structure.length; i < l; i++) {
  2761. let definition = structure[i];
  2762. let [ type, size, key, enumerationOffset ] = definition;
  2763. if (key === '__proto__')
  2764. key = '__proto_';
  2765. let property = {
  2766. key,
  2767. offset: currentOffset,
  2768. };
  2769. if (enumerationOffset)
  2770. properties.splice(i + enumerationOffset, 0, property);
  2771. else
  2772. properties.push(property);
  2773. let getRef;
  2774. switch(size) { // TODO: Move into a separate function
  2775. case 0: getRef = () => 0; break;
  2776. case 1:
  2777. getRef = (source, position) => {
  2778. let ref = source.bytes[position + property.offset];
  2779. return ref >= 0xf6 ? toConstant(ref) : ref;
  2780. };
  2781. break;
  2782. case 2:
  2783. getRef = (source, position) => {
  2784. let src = source.bytes;
  2785. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2786. let ref = dataView.getUint16(position + property.offset, true);
  2787. return ref >= 0xff00 ? toConstant(ref & 0xff) : ref;
  2788. };
  2789. break;
  2790. case 4:
  2791. getRef = (source, position) => {
  2792. let src = source.bytes;
  2793. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2794. let ref = dataView.getUint32(position + property.offset, true);
  2795. return ref >= 0xffffff00 ? toConstant(ref & 0xff) : ref;
  2796. };
  2797. break;
  2798. }
  2799. property.getRef = getRef;
  2800. currentOffset += size;
  2801. let get;
  2802. switch(type) {
  2803. case ASCII:
  2804. if (lastRefProperty && !lastRefProperty.next)
  2805. lastRefProperty.next = property;
  2806. lastRefProperty = property;
  2807. property.multiGetCount = 0;
  2808. get = function(source) {
  2809. let src = source.bytes;
  2810. let position = source.position;
  2811. let refStart = currentOffset + position;
  2812. let ref = getRef(source, position);
  2813. if (typeof ref !== 'number') return ref;
  2814. let end, next = property.next;
  2815. while(next) {
  2816. end = next.getRef(source, position);
  2817. if (typeof end === 'number')
  2818. break;
  2819. else
  2820. end = null;
  2821. next = next.next;
  2822. }
  2823. if (end == null)
  2824. end = source.bytesEnd - refStart;
  2825. if (source.srcString) {
  2826. return source.srcString.slice(ref, end);
  2827. }
  2828. /*if (property.multiGetCount > 0) {
  2829. let asciiEnd;
  2830. next = firstRefProperty;
  2831. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2832. do {
  2833. asciiEnd = dataView.getUint16(source.position + next.offset, true);
  2834. if (asciiEnd < 0xff00)
  2835. break;
  2836. else
  2837. asciiEnd = null;
  2838. } while((next = next.next));
  2839. if (asciiEnd == null)
  2840. asciiEnd = source.bytesEnd - refStart
  2841. source.srcString = src.toString('latin1', refStart, refStart + asciiEnd);
  2842. return source.srcString.slice(ref, end);
  2843. }
  2844. if (source.prevStringGet) {
  2845. source.prevStringGet.multiGetCount += 2;
  2846. } else {
  2847. source.prevStringGet = property;
  2848. property.multiGetCount--;
  2849. }*/
  2850. return readString(src, ref + refStart, end - ref);
  2851. //return src.toString('latin1', ref + refStart, end + refStart);
  2852. };
  2853. break;
  2854. case UTF8: case OBJECT_DATA:
  2855. if (lastRefProperty && !lastRefProperty.next)
  2856. lastRefProperty.next = property;
  2857. lastRefProperty = property;
  2858. get = function(source) {
  2859. let position = source.position;
  2860. let refStart = currentOffset + position;
  2861. let ref = getRef(source, position);
  2862. if (typeof ref !== 'number') return ref;
  2863. let src = source.bytes;
  2864. let end, next = property.next;
  2865. while(next) {
  2866. end = next.getRef(source, position);
  2867. if (typeof end === 'number')
  2868. break;
  2869. else
  2870. end = null;
  2871. next = next.next;
  2872. }
  2873. if (end == null)
  2874. end = source.bytesEnd - refStart;
  2875. if (type === UTF8) {
  2876. return src.toString('utf8', ref + refStart, end + refStart);
  2877. } else {
  2878. currentSource = source;
  2879. try {
  2880. return unpackr.unpack(src, { start: ref + refStart, end: end + refStart });
  2881. } finally {
  2882. currentSource = null;
  2883. }
  2884. }
  2885. };
  2886. break;
  2887. case NUMBER:
  2888. switch(size) {
  2889. case 4:
  2890. get = function (source) {
  2891. let src = source.bytes;
  2892. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2893. let position = source.position + property.offset;
  2894. let value = dataView.getInt32(position, true);
  2895. if (value < 0x20000000) {
  2896. if (value > -0x1f000000)
  2897. return value;
  2898. if (value > -0x20000000)
  2899. return toConstant(value & 0xff);
  2900. }
  2901. let fValue = dataView.getFloat32(position, true);
  2902. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2903. let multiplier = mult10[((src[position + 3] & 0x7f) << 1) | (src[position + 2] >> 7)];
  2904. return ((multiplier * fValue + (fValue > 0 ? 0.5 : -0.5)) >> 0) / multiplier;
  2905. };
  2906. break;
  2907. case 8:
  2908. get = function (source) {
  2909. let src = source.bytes;
  2910. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2911. let value = dataView.getFloat64(source.position + property.offset, true);
  2912. if (isNaN(value)) {
  2913. let byte = src[source.position + property.offset];
  2914. if (byte >= 0xf6)
  2915. return toConstant(byte);
  2916. }
  2917. return value;
  2918. };
  2919. break;
  2920. case 1:
  2921. get = function (source) {
  2922. let src = source.bytes;
  2923. let value = src[source.position + property.offset];
  2924. return value < 0xf6 ? value : toConstant(value);
  2925. };
  2926. break;
  2927. }
  2928. break;
  2929. case DATE:
  2930. get = function (source) {
  2931. let src = source.bytes;
  2932. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2933. return new Date(dataView.getFloat64(source.position + property.offset, true));
  2934. };
  2935. break;
  2936. }
  2937. property.get = get;
  2938. }
  2939. // TODO: load the srcString for faster string decoding on toJSON
  2940. if (evalSupported) {
  2941. let objectLiteralProperties = [];
  2942. let args = [];
  2943. let i = 0;
  2944. let hasInheritedProperties;
  2945. for (let property of properties) { // assign in enumeration order
  2946. if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) {
  2947. // these properties are not eagerly evaluated and this can be used for creating properties
  2948. // that are not serialized as JSON
  2949. hasInheritedProperties = true;
  2950. continue;
  2951. }
  2952. Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true });
  2953. let valueFunction = 'v' + i++;
  2954. args.push(valueFunction);
  2955. objectLiteralProperties.push('o[' + JSON.stringify(property.key) + ']=' + valueFunction + '(s)');
  2956. }
  2957. if (hasInheritedProperties) {
  2958. objectLiteralProperties.push('__proto__:this');
  2959. }
  2960. let toObject = (new Function(...args, 'var c=this;return function(s){var o=new c();' + objectLiteralProperties.join(';') + ';return o;}')).apply(fullConstruct, properties.map(prop => prop.get));
  2961. Object.defineProperty(prototype, 'toJSON', {
  2962. value(omitUnderscoredProperties) {
  2963. return toObject.call(this, this[sourceSymbol]);
  2964. }
  2965. });
  2966. } else {
  2967. Object.defineProperty(prototype, 'toJSON', {
  2968. value(omitUnderscoredProperties) {
  2969. // return an enumerable object with own properties to JSON stringify
  2970. let resolved = {};
  2971. for (let i = 0, l = properties.length; i < l; i++) {
  2972. // TODO: check alwaysLazyProperty
  2973. let key = properties[i].key;
  2974. resolved[key] = this[key];
  2975. }
  2976. return resolved;
  2977. },
  2978. // not enumerable or anything
  2979. });
  2980. }
  2981. }
  2982. var instance = new construct();
  2983. instance[sourceSymbol] = {
  2984. bytes: src,
  2985. position,
  2986. srcString: '',
  2987. bytesEnd: srcEnd
  2988. };
  2989. return instance;
  2990. }
  2991. function toConstant(code) {
  2992. switch(code) {
  2993. case 0xf6: return null;
  2994. case 0xf7: return undefined;
  2995. case 0xf8: return false;
  2996. case 0xf9: return true;
  2997. }
  2998. throw new Error('Unknown constant');
  2999. }
  3000. function withSource(get) {
  3001. return function() {
  3002. return get(this[sourceSymbol]);
  3003. }
  3004. }
  3005. function saveState() {
  3006. if (currentSource) {
  3007. currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd);
  3008. currentSource.position = 0;
  3009. currentSource.bytesEnd = currentSource.bytes.length;
  3010. }
  3011. }
  3012. function prepareStructures(structures, packr) {
  3013. if (packr.typedStructs) {
  3014. let structMap = new Map();
  3015. structMap.set('named', structures);
  3016. structMap.set('typed', packr.typedStructs);
  3017. structures = structMap;
  3018. }
  3019. let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0;
  3020. structures.isCompatible = existing => {
  3021. let compatible = true;
  3022. if (existing instanceof Map) {
  3023. let named = existing.get('named') || [];
  3024. if (named.length !== (packr.lastNamedStructuresLength || 0))
  3025. compatible = false;
  3026. let typed = existing.get('typed') || [];
  3027. if (typed.length !== lastTypedStructuresLength)
  3028. compatible = false;
  3029. } else if (existing instanceof Array || Array.isArray(existing)) {
  3030. if (existing.length !== (packr.lastNamedStructuresLength || 0))
  3031. compatible = false;
  3032. }
  3033. if (!compatible)
  3034. packr._mergeStructures(existing);
  3035. return compatible;
  3036. };
  3037. packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length;
  3038. return structures;
  3039. }
  3040. setReadStruct(readStruct, onLoadedStructures, saveState);
  3041. const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
  3042. if (!nativeAccelerationDisabled) {
  3043. let extractor;
  3044. try {
  3045. if (typeof require == 'function')
  3046. extractor = require('msgpackr-extract');
  3047. else
  3048. extractor = module.createRequire((document.currentScript && document.currentScript.src || new URL('test.js', document.baseURI).href))('msgpackr-extract');
  3049. if (extractor)
  3050. setExtractor(extractor.extractStrings);
  3051. } catch (error) {
  3052. // native module is optional
  3053. }
  3054. }
  3055. let allSampleData = [];
  3056. for (let i = 1; i < 6; i++) {
  3057. allSampleData.push(JSON.parse(fs.readFileSync(new URL(`./example${i > 1 ? i : ''}.json`, (document.currentScript && document.currentScript.src || new URL('test.js', document.baseURI).href)))));
  3058. }
  3059. allSampleData.push({
  3060. name: 'some other types',
  3061. date: new Date(),
  3062. empty: '',
  3063. });
  3064. const sampleData = allSampleData[3];
  3065. function tryRequire(module) {
  3066. try {
  3067. return require(module)
  3068. } catch(error) {
  3069. return {}
  3070. }
  3071. }
  3072. let seed = 0;
  3073. function random() {
  3074. seed++;
  3075. let a = seed * 15485863;
  3076. return (a * a * a % 2038074743) / 2038074743;
  3077. }
  3078. //if (typeof chai === 'undefined') { chai = require('chai') }
  3079. var assert = chai.assert;
  3080. //if (typeof msgpackr === 'undefined') { msgpackr = require('..') }
  3081. var Packr = Packr$1;
  3082. var Unpackr = Unpackr$1;
  3083. var unpack = unpack$1;
  3084. var unpackMultiple = unpackMultiple$1;
  3085. var roundFloat32 = roundFloat32$1;
  3086. var pack = pack$1;
  3087. var DECIMAL_FIT = FLOAT32_OPTIONS.DECIMAL_FIT;
  3088. var addExtension = addExtension$1;
  3089. var zlib = tryRequire('zlib');
  3090. zlib.deflateSync;
  3091. zlib.inflateSync;
  3092. zlib.brotliCompressSync;
  3093. zlib.brotliDecompressSync;
  3094. zlib.constants;
  3095. var ITERATIONS = 4000;
  3096. class ExtendArray extends Array {
  3097. }
  3098. class ExtendArray2 extends Array {
  3099. }
  3100. class ExtendArray3 extends Array {
  3101. }
  3102. class ExtendObject {
  3103. }
  3104. suite('msgpackr basic tests', function() {
  3105. test('pack/unpack data', function () {
  3106. var data = {
  3107. data: [
  3108. {a: 1, name: 'one', type: 'odd', isOdd: true},
  3109. {a: 2, name: 'two', type: 'even'},
  3110. {a: 3, name: 'three', type: 'odd', isOdd: true},
  3111. {a: 4, name: 'four', type: 'even'},
  3112. {a: 5, name: 'five', type: 'odd', isOdd: true},
  3113. {a: 6, name: 'six', type: 'even', isOdd: null}
  3114. ],
  3115. description: 'some names',
  3116. types: ['odd', 'even'],
  3117. convertEnumToNum: [
  3118. {prop: 'test'},
  3119. {prop: 'test'},
  3120. {prop: 'test'},
  3121. {prop: 1},
  3122. {prop: 2},
  3123. {prop: [undefined]},
  3124. {prop: null}
  3125. ]
  3126. };
  3127. let structures = [];
  3128. let packr = new Packr({structures});
  3129. var serialized = packr.pack(data);
  3130. serialized = packr.pack(data);
  3131. serialized = packr.pack(data);
  3132. var deserialized = packr.unpack(serialized);
  3133. assert.deepEqual(deserialized, data);
  3134. });
  3135. test('mixed structures', function () {
  3136. let data1 = {a: 1, b: 2, c: 3};
  3137. let data2 = {a: 1, b: 2, d: 4};
  3138. let data3 = {a: 1, b: 2, e: 5};
  3139. let structures = [];
  3140. let packr = new Packr({structures});
  3141. var serialized = packr.pack(data1);
  3142. var deserialized = packr.unpack(serialized);
  3143. assert.deepEqual(deserialized, data1);
  3144. var serialized = packr.pack(data2);
  3145. var deserialized = packr.unpack(serialized);
  3146. assert.deepEqual(deserialized, data2);
  3147. var serialized = packr.pack(data3);
  3148. var deserialized = packr.unpack(serialized);
  3149. assert.deepEqual(deserialized, data3);
  3150. });
  3151. test('mixed array', function () {
  3152. var data = [
  3153. 'one',
  3154. 'two',
  3155. 'one',
  3156. 10,
  3157. 11,
  3158. null,
  3159. true,
  3160. 'three',
  3161. 'three',
  3162. 'one', [
  3163. 3, -5, -50, -400, 1.3, -5.3, true
  3164. ]
  3165. ];
  3166. let structures = [];
  3167. let packr = new Packr({structures});
  3168. var serialized = packr.pack(data);
  3169. var deserialized = packr.unpack(serialized);
  3170. assert.deepEqual(deserialized, data);
  3171. });
  3172. test('255 chars', function () {
  3173. const data = 'RRZG9A6I7xupPeOZhxcOcioFsuhszGOdyDUcbRf4Zef2kdPIfC9RaLO4jTM5JhuZvTsF09fbRHMGtqk7YAgu3vespeTe9l61ziZ6VrMnYu2CamK96wCkmz0VUXyqaiUoTPgzk414LS9yYrd5uh7w18ksJF5SlC2e91rukWvNqAZJjYN3jpkqHNOFchCwFrhbxq2Lrv1kSJPYCx9blRg2hGmYqTbElLTZHv20iNqwZeQbRMgSBPT6vnbCBPnOh1W';
  3174. var serialized = pack(data);
  3175. var deserialized = unpack(serialized);
  3176. assert.equal(deserialized, data);
  3177. });
  3178. test('use ArrayBuffer', function () {
  3179. const data = {prop: 'a test'};
  3180. var serialized = pack(data);
  3181. let ab = new ArrayBuffer(serialized.length);
  3182. let u8 = new Uint8Array(ab);
  3183. u8.set(serialized);
  3184. var deserialized = unpack(ab);
  3185. assert.deepEqual(deserialized, data);
  3186. });
  3187. test('pack/unpack varying data with random access structures', function () {
  3188. let structures = [];
  3189. let packr = new Packr({
  3190. structures, useRecords: true, randomAccessStructure: true, freezeData: true, saveStructures(structures) {
  3191. }, getStructures() {
  3192. console.log('getStructures');
  3193. }
  3194. });
  3195. for (let i = 0; i < 2000; i++) {
  3196. let data = {};
  3197. let props = ['foo', 'bar', 'a', 'b', 'c', 'name', 'age', 'd'];
  3198. function makeString() {
  3199. let str = '';
  3200. while (random() < 0.9) {
  3201. str += random() < 0.8 ? 'hello world' : String.fromCharCode(300);
  3202. }
  3203. return str;
  3204. }
  3205. for (let i = 0; i < random() * 20; i++) {
  3206. data[props[Math.floor(random() * 8)]] =
  3207. random() < 0.3 ? Math.floor(random() * 400) / 2 :
  3208. random() < 0.3 ? makeString() : random() < 0.3 ? true : random() < 0.3 ? sampleData : null;
  3209. }
  3210. var serialized = packr.pack(data);
  3211. var deserialized = packr.unpack(serialized);
  3212. for (let key in deserialized) {
  3213. deserialized[key];
  3214. }
  3215. assert.deepEqual(deserialized, data);
  3216. }
  3217. });
  3218. for (let sampleData of allSampleData) {
  3219. let snippet = JSON.stringify(sampleData).slice(0, 20) + '...';
  3220. test('pack/unpack sample data ' + snippet, function () {
  3221. var data = sampleData;
  3222. var serialized = pack(data);
  3223. var deserialized = unpack(serialized);
  3224. assert.deepEqual(deserialized, data);
  3225. var serialized = pack(data);
  3226. var deserialized = unpack(serialized);
  3227. assert.deepEqual(deserialized, data);
  3228. });
  3229. test('pack/unpack sample data with Uint8Array encoding' + snippet, function () {
  3230. var data = sampleData;
  3231. var serialized = pack(data);
  3232. serialized = new Uint8Array(serialized);
  3233. var deserialized = unpack(serialized);
  3234. assert.deepEqual(deserialized, data);
  3235. var serialized = pack(data);
  3236. var deserialized = unpack(serialized);
  3237. assert.deepEqual(deserialized, data);
  3238. });
  3239. test('pack/unpack sample data with random access structures ' + snippet, function () {
  3240. var data = sampleData;
  3241. let structures = [];
  3242. let packr = new Packr({
  3243. structures, useRecords: true, randomAccessStructure: true, freezeData: true, saveStructures(structures) {
  3244. }, getStructures() {
  3245. console.log('getStructures');
  3246. }
  3247. });
  3248. for (let i = 0; i < 20; i++) {
  3249. var serialized = packr.pack(data);
  3250. var deserialized = packr.unpack(serialized, {lazy: true});
  3251. var copied = {};
  3252. for (let key in deserialized) {
  3253. copied[key] = deserialized[key];
  3254. }
  3255. assert.deepEqual(copied, data);
  3256. }
  3257. });
  3258. test('pack/unpack sample data with bundled strings ' + snippet, function () {
  3259. var data = sampleData;
  3260. let packr = new Packr({ /*structures,*/ useRecords: false, bundleStrings: true});
  3261. var serialized = packr.pack(data);
  3262. var deserialized = packr.unpack(serialized);
  3263. assert.deepEqual(deserialized, data);
  3264. });
  3265. }
  3266. test('pack/unpack sample data with useRecords function', function () {
  3267. var data = [
  3268. {id: 1, type: 1, labels: {a: 1, b: 2}},
  3269. {id: 2, type: 1, labels: {b: 1, c: 2}},
  3270. {id: 3, type: 1, labels: {d: 1, e: 2}}
  3271. ];
  3272. var alternatives = [
  3273. {useRecords: false}, // 88 bytes
  3274. {useRecords: true}, // 58 bytes
  3275. {mapsAsObjects: true, useRecords: (v)=>!!v.id}, // 55 bytes
  3276. {mapsAsObjects: true, variableMapSize: true, useRecords: (v)=>!!v.id} // 49 bytes
  3277. ];
  3278. for(let o of alternatives) {
  3279. let packr = new Packr(o);
  3280. var serialized = packr.pack(data);
  3281. var deserialized = packr.unpack(serialized);
  3282. assert.deepEqual(deserialized, data);
  3283. }
  3284. });
  3285. test('mapAsEmptyObject combination', function () {
  3286. const msgpackr = new Packr({ useRecords: false, encodeUndefinedAsNil: true, variableMapSize: true, mapAsEmptyObject: true, setAsEmptyObject: true });
  3287. const map = new Map();
  3288. map.set('a', 1);
  3289. map.set('b', 2);
  3290. const set = new Set();
  3291. set.add('a');
  3292. set.add('b');
  3293. const input = { map, set };
  3294. const packed = msgpackr.pack(input);
  3295. const unpacked = msgpackr.unpack(packed);
  3296. assert.deepEqual(unpacked.map, {});
  3297. assert.deepEqual(unpacked.set, {});
  3298. });
  3299. test('pack/unpack numeric coercible keys', function () {
  3300. var data = { a: 1, 2: 'test', '-3.45': 'test2'};
  3301. let packr = new Packr({variableMapSize: true, coercibleKeyAsNumber: true, useRecords: false});
  3302. var serialized = packr.pack(data);
  3303. var deserialized = packr.unpack(serialized);
  3304. assert.deepEqual(deserialized, data);
  3305. });
  3306. test('pack/unpack empty data with bundled strings', function () {
  3307. var data = {};
  3308. let packr = new Packr({bundleStrings: true});
  3309. var serialized = packr.pack(data);
  3310. var deserialized = packr.unpack(serialized);
  3311. assert.deepEqual(deserialized, data);
  3312. });
  3313. test('pack/unpack large amount of chinese characters', function() {
  3314. const MSGPACK_OPTIONS = {bundleStrings: true};
  3315. const item = {
  3316. message: '你好你好你好你好你好你好你好你好你好', // some Chinese characters
  3317. };
  3318. testSize(100);
  3319. testSize(1000);
  3320. testSize(10000);
  3321. function testSize(size) {
  3322. const list = [];
  3323. for (let i = 0; i < size; i++) {
  3324. list.push({...item});
  3325. }
  3326. const packer = new Packr(MSGPACK_OPTIONS);
  3327. const unpacker = new Unpackr(MSGPACK_OPTIONS);
  3328. const encoded = packer.pack(list);
  3329. const decoded = unpacker.unpack(encoded);
  3330. assert.deepEqual(list, decoded);
  3331. }
  3332. });
  3333. test('pack/unpack sequential data', function () {
  3334. var data = {foo: 1, bar: 2};
  3335. let packr = new Packr({sequential: true});
  3336. let unpackr = new Unpackr({sequential: true});
  3337. var serialized = packr.pack(data);
  3338. var deserialized = unpackr.unpack(serialized);
  3339. assert.deepEqual(deserialized, data);
  3340. var serialized = packr.pack(data);
  3341. var deserialized = unpackr.unpack(serialized);
  3342. assert.deepEqual(deserialized, data);
  3343. });
  3344. test('pack/unpack with bundled strings and sequential', function () {
  3345. const options = {
  3346. bundleStrings: true,
  3347. sequential: true,
  3348. };
  3349. const packer = new Packr(options);
  3350. const unpacker = new Packr(options);
  3351. const data = {data: 42}; // key length >= 4
  3352. unpacker.unpackMultiple(Buffer.concat([
  3353. packer.pack(data),
  3354. packer.pack(data)
  3355. ]));
  3356. });
  3357. if (typeof Buffer != 'undefined')
  3358. test('replace data', function(){
  3359. var data1 = {
  3360. data: [
  3361. { a: 1, name: 'one', type: 'odd', isOdd: true, a: '13 characters' },
  3362. { a: 2, name: 'two', type: 'even', a: '11 characte' },
  3363. { a: 3, name: 'three', type: 'odd', isOdd: true, a: '12 character' },
  3364. { a: 4, name: 'four', type: 'even', a: '9 charact'},
  3365. { a: 5, name: 'five', type: 'odd', isOdd: true, a: '14 characters!' },
  3366. { a: 6, name: 'six', type: 'even', isOdd: null }
  3367. ],
  3368. };
  3369. var data2 = {
  3370. data: [
  3371. { foo: 7, name: 'one', type: 'odd', isOdd: true },
  3372. { foo: 8, name: 'two', type: 'even'},
  3373. { foo: 9, name: 'three', type: 'odd', isOdd: true },
  3374. { foo: 10, name: 'four', type: 'even'},
  3375. { foo: 11, name: 'five', type: 'odd', isOdd: true },
  3376. { foo: 12, name: 'six', type: 'even', isOdd: null }
  3377. ],
  3378. };
  3379. var serialized1 = pack(data1);
  3380. var serialized2 = pack(data2);
  3381. var b = Buffer.alloc(8000);
  3382. serialized1.copy(b);
  3383. var deserialized1 = unpack(b, serialized1.length);
  3384. serialized2.copy(b);
  3385. var deserialized2 = unpack(b, serialized2.length);
  3386. assert.deepEqual(deserialized1, data1);
  3387. assert.deepEqual(deserialized2, data2);
  3388. });
  3389. test('compact 123', function() {
  3390. assert.equal(pack(123).length, 1);
  3391. });
  3392. test('BigInt', function() {
  3393. let packr = new Packr({ useBigIntExtension: true });
  3394. let data = {
  3395. a: 3333333333333333333333333333n,
  3396. b: 1234567890123456789012345678901234567890n,
  3397. c: -3333333333333333333333333333n,
  3398. d: -352523523642364364364264264264264264262642642n,
  3399. e: 0xffffffffffffffffffffffffffn,
  3400. f: -0xffffffffffffffffffffffffffn,
  3401. g: (1234n << 123n) ^ (5678n << 56n) ^ 890n,
  3402. h: (-1234n << 123n) ^ (5678n << 56n) ^ 890n,
  3403. i: (1234n << 1234n) ^ (5678n << 567n) ^ 890n,
  3404. j: (-1234n << 1234n) ^ (5678n << 567n) ^ 890n,
  3405. k: 0xdeadn << 0xbeefn,
  3406. l: -0xdeadn << 0xbeefn,
  3407. m: 11n << 0x11111n ^ 111n,
  3408. n: -11n << 0x11111n ^ 111n,
  3409. o: 12345678901234567890n,
  3410. p: -12345678901234567890n,
  3411. exp: [],
  3412. expexp: [],
  3413. };
  3414. for (let n = 1n; n.toString(16).length * 4 < 1500; n <<= 1n, n |= BigInt(Math.floor(Math.random() * 2))) {
  3415. data.exp.push(n, -n);
  3416. }
  3417. for (let n = 7n; n.toString(16).length * 4 < 150000; n *= n) {
  3418. data.expexp.push(n, -n);
  3419. }
  3420. let serialized = packr.pack(data);
  3421. let deserialized = packr.unpack(serialized);
  3422. assert.deepEqual(data, deserialized);
  3423. });
  3424. test('extended class pack/unpack', function(){
  3425. function Extended() {
  3426. }
  3427. Extended.prototype.getDouble = function() {
  3428. return this.value * 2
  3429. };
  3430. var instance = new Extended();
  3431. instance.value = 4;
  3432. instance.string = 'decode this: ᾜ';
  3433. var data = {
  3434. prop1: 'has multi-byte: ᾜ',
  3435. extendedInstance: instance,
  3436. prop2: 'more string',
  3437. num: 3,
  3438. };
  3439. let packr = new Packr();
  3440. addExtension({
  3441. Class: Extended,
  3442. type: 11,
  3443. unpack: function(buffer) {
  3444. let e = new Extended();
  3445. let data = packr.unpack(buffer);
  3446. e.value = data[0];
  3447. e.string = data[1];
  3448. return e
  3449. },
  3450. pack: function(instance) {
  3451. return packr.pack([instance.value, instance.string])
  3452. }
  3453. });
  3454. var serialized = pack(data);
  3455. var deserialized = unpack(serialized);
  3456. assert.deepEqual(data, deserialized);
  3457. assert.equal(deserialized.extendedInstance.getDouble(), 8);
  3458. });
  3459. test('extended Array class read/write', function(){
  3460. var instance = new ExtendArray();
  3461. instance.push(0);
  3462. instance.push(1);
  3463. instance.push(2);
  3464. var data = {
  3465. prop1: 'has multi-byte: ᾜ',
  3466. extendedInstance: instance,
  3467. prop2: 'more string',
  3468. num: 3,
  3469. };
  3470. new Packr();
  3471. addExtension({
  3472. Class: ExtendArray,
  3473. type: 12,
  3474. read: function(data) {
  3475. Object.setPrototypeOf(data, ExtendArray.prototype);
  3476. return data
  3477. },
  3478. write: function(instance) {
  3479. return [...instance]
  3480. }
  3481. });
  3482. var serialized = pack(data);
  3483. var deserialized = unpack(serialized);
  3484. assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), ExtendArray.prototype);
  3485. assert.deepEqual(data, deserialized);
  3486. });
  3487. test('unregistered extended Array class read/write', function(){
  3488. var instance = new ExtendArray2();
  3489. instance.push(0);
  3490. instance.push(1);
  3491. instance.push(2);
  3492. var data = {
  3493. prop1: 'has multi-byte: ᾜ',
  3494. extendedInstance: instance,
  3495. prop2: 'more string',
  3496. num: 3,
  3497. };
  3498. new Packr();
  3499. var serialized = pack(data);
  3500. var deserialized = unpack(serialized);
  3501. assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Array.prototype);
  3502. assert.deepEqual(data, deserialized);
  3503. });
  3504. test('unregistered extended Object class read/write', function(){
  3505. var instance = new ExtendObject();
  3506. instance.test1 = "string";
  3507. instance.test2 = 3421321;
  3508. var data = {
  3509. prop1: 'has multi-byte: ᾜ',
  3510. extendedInstance: instance,
  3511. prop2: 'more string',
  3512. num: 3,
  3513. };
  3514. new Packr();
  3515. var serialized = pack(data);
  3516. var deserialized = unpack(serialized);
  3517. assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Object.prototype);
  3518. assert.deepEqual(data, deserialized);
  3519. });
  3520. test('extended class pack/unpack custom size', function(){
  3521. function TestClass() {
  3522. }
  3523. addExtension({
  3524. Class: TestClass,
  3525. type: 0x01,
  3526. pack() {
  3527. return typeof Buffer != 'undefined' ? Buffer.alloc(256) : new Uint8Array(256)
  3528. },
  3529. unpack(data) {
  3530. return data.length
  3531. }
  3532. });
  3533. let result = unpack(pack(new TestClass()));
  3534. assert.equal(result, 256);
  3535. });
  3536. test('extended class read/write', function(){
  3537. function Extended() {
  3538. }
  3539. Extended.prototype.getDouble = function() {
  3540. return this.value * 2
  3541. };
  3542. var instance = new Extended();
  3543. instance.value = 4;
  3544. instance.string = 'decode this: ᾜ';
  3545. var data = {
  3546. prop1: 'has multi-byte: ᾜ',
  3547. extendedInstance: instance,
  3548. prop2: 'more string',
  3549. num: 3,
  3550. };
  3551. new Packr();
  3552. addExtension({
  3553. Class: Extended,
  3554. type: 12,
  3555. read: function(data) {
  3556. let e = new Extended();
  3557. e.value = data[0];
  3558. e.string = data[1];
  3559. return e
  3560. },
  3561. write: function(instance) {
  3562. return [instance.value, instance.string]
  3563. }
  3564. });
  3565. var serialized = pack(data);
  3566. var deserialized = unpack(serialized);
  3567. assert.deepEqual(data, deserialized);
  3568. assert.equal(deserialized.extendedInstance.getDouble(), 8);
  3569. });
  3570. test('extended class return self', function(){
  3571. function Extended() {
  3572. }
  3573. Extended.prototype.getDouble = function() {
  3574. return this.value * 2
  3575. };
  3576. var instance = new Extended();
  3577. instance.value = 4;
  3578. instance.string = 'decode this: ᾜ';
  3579. var data = {
  3580. prop1: 'has multi-byte: ᾜ',
  3581. extendedInstance: instance,
  3582. prop2: 'more string',
  3583. num: 3,
  3584. };
  3585. new Packr();
  3586. addExtension({
  3587. Class: Extended,
  3588. type: 13,
  3589. read: function(data) {
  3590. Object.setPrototypeOf(data, Extended.prototype);
  3591. return data
  3592. },
  3593. write: function(data) {
  3594. return data
  3595. }
  3596. });
  3597. var serialized = pack(data);
  3598. var deserialized = unpack(serialized);
  3599. assert.deepEqual(data, deserialized);
  3600. assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), Extended.prototype);
  3601. assert.equal(deserialized.extendedInstance.getDouble(), 8);
  3602. });
  3603. test('extended Array class return self', function(){
  3604. var instance = new ExtendArray3();
  3605. instance.push(0);
  3606. instance.push('has multi-byte: ᾜ');
  3607. var data = {
  3608. prop1: 'has multi-byte: ᾜ',
  3609. extendedInstance: instance,
  3610. prop2: 'more string',
  3611. num: 3,
  3612. };
  3613. new Packr();
  3614. addExtension({
  3615. Class: ExtendArray3,
  3616. type: 14,
  3617. read: function(data) {
  3618. Object.setPrototypeOf(data, ExtendArray3.prototype);
  3619. return data
  3620. },
  3621. write: function(data) {
  3622. return data
  3623. }
  3624. });
  3625. var serialized = pack(data);
  3626. var deserialized = unpack(serialized);
  3627. assert.deepEqual(data, deserialized);
  3628. assert.strictEqual(Object.getPrototypeOf(deserialized.extendedInstance), ExtendArray3.prototype);
  3629. assert.equal(deserialized.extendedInstance[0], 0);
  3630. });
  3631. test('extended class pack/unpack proxied', function(){
  3632. function Extended() {
  3633. }
  3634. Extended.prototype.__call__ = function(){
  3635. return this.value * 4
  3636. };
  3637. Extended.prototype.getDouble = function() {
  3638. return this.value * 2
  3639. };
  3640. var instance = function() { instance.__call__();/* callable stuff */ };
  3641. Object.setPrototypeOf(instance,Extended.prototype);
  3642. instance.value = 4;
  3643. var data = instance;
  3644. let packr = new Packr();
  3645. addExtension({
  3646. Class: Extended,
  3647. type: 15,
  3648. unpack: function(buffer) {
  3649. var e = function() { e.__call__(); };
  3650. Object.setPrototypeOf(e,Extended.prototype);
  3651. e.value = packr.unpack(buffer);
  3652. return e
  3653. },
  3654. pack: function(instance) {
  3655. return packr.pack(instance.value)
  3656. }
  3657. });
  3658. var serialized = pack(data);
  3659. var deserialized = unpack(serialized);
  3660. assert.equal(deserialized.getDouble(), 8);
  3661. });
  3662. test.skip('convert Date to string', function(){
  3663. var data = {
  3664. aDate: new Date(),
  3665. };
  3666. new Packr();
  3667. addExtension({
  3668. Class: Date,
  3669. write(date) {
  3670. return date.toString()
  3671. }
  3672. });
  3673. var serialized = pack(data);
  3674. var deserialized = unpack(serialized);
  3675. assert.equal(deserialized.aDate, data.aDate.toString());
  3676. });
  3677. test('standard pack fails on circular reference with shared structures', function () {
  3678. var data = {};
  3679. data.self = data;
  3680. let structures = [];
  3681. let packr = new Packr({
  3682. structures,
  3683. saveStructures(structures) {
  3684. }
  3685. });
  3686. assert.throws(function () {
  3687. packr.pack(data);
  3688. });
  3689. });
  3690. test('proto handling', function() {
  3691. var objectWithProto = JSON.parse('{"__proto__":{"foo":3}}');
  3692. var decoded = unpack(pack(objectWithProto));
  3693. assert(!decoded.foo);
  3694. var objectsWithProto = [objectWithProto, objectWithProto, objectWithProto, objectWithProto, objectWithProto, objectWithProto];
  3695. let packr = new Packr();
  3696. var decoded = packr.unpack(packr.pack(objectsWithProto));
  3697. for (let object of decoded) {
  3698. assert(!decoded.foo);
  3699. }
  3700. });
  3701. test.skip('text decoder', function() {
  3702. let td = new TextDecoder('ISO-8859-15');
  3703. let b = Buffer.alloc(3);
  3704. for (var i = 0; i < 256; i++) {
  3705. b[0] = i;
  3706. b[1] = 0;
  3707. b[2] = 0;
  3708. let s = td.decode(b);
  3709. if (!require('msgpackr-extract').isOneByte(s)) {
  3710. console.log(i.toString(16), s.length);
  3711. }
  3712. }
  3713. });
  3714. test('moreTypes: Error with causes', function() {
  3715. const object = {
  3716. error: new Error('test'),
  3717. errorWithCause: new Error('test-1', { cause: new Error('test-2') }),
  3718. type: new TypeError(),
  3719. range: new RangeError('test', { cause: [1, 2] }),
  3720. };
  3721. const packr = new Packr({
  3722. moreTypes: true,
  3723. });
  3724. const serialized = packr.pack(object);
  3725. const deserialized = packr.unpack(serialized);
  3726. assert.equal(deserialized.error.message, object.error.message);
  3727. assert.equal(deserialized.error.cause, object.error.cause);
  3728. assert.equal(deserialized.errorWithCause.message, object.errorWithCause.message);
  3729. assert.equal(deserialized.errorWithCause.cause.message, object.errorWithCause.cause.message);
  3730. assert.equal(deserialized.errorWithCause.cause.cause, object.errorWithCause.cause.cause);
  3731. assert.equal(deserialized.type.message, object.type.message);
  3732. assert.equal(deserialized.range.message, object.range.message);
  3733. assert.deepEqual(deserialized.range.cause, object.range.cause);
  3734. assert(deserialized.error instanceof Error);
  3735. assert(deserialized.type instanceof TypeError);
  3736. assert(deserialized.range instanceof RangeError);
  3737. });
  3738. test('structured cloning: self reference', function() {
  3739. let object = {
  3740. test: 'string',
  3741. children: [
  3742. { name: 'child' }
  3743. ],
  3744. value: new ArrayBuffer(10)
  3745. };
  3746. let u8 = new Uint8Array(object.value);
  3747. u8[0] = 1;
  3748. u8[1] = 2;
  3749. object.self = object;
  3750. object.children[1] = object;
  3751. object.children[2] = object.children[0];
  3752. object.childrenAgain = object.children;
  3753. let packr = new Packr({
  3754. moreTypes: true,
  3755. structuredClone: true,
  3756. });
  3757. var serialized = packr.pack(object);
  3758. var deserialized = packr.unpack(serialized);
  3759. assert.equal(deserialized.self, deserialized);
  3760. assert.equal(deserialized.children[0].name, 'child');
  3761. assert.equal(deserialized.children[1], deserialized);
  3762. assert.equal(deserialized.children[0], deserialized.children[2]);
  3763. assert.equal(deserialized.children, deserialized.childrenAgain);
  3764. assert.equal(deserialized.value.constructor.name, 'ArrayBuffer');
  3765. u8 = new Uint8Array(deserialized.value);
  3766. assert.equal(u8[0], 1);
  3767. assert.equal(u8[1], 2);
  3768. });
  3769. test('structured cloning: self reference with more types', function() {
  3770. let set = new Set();
  3771. set.add(['hello', 1, 2, { map: new Map([[set, set], ['a', 'b']]) }]);
  3772. let packr = new Packr({
  3773. moreTypes: true,
  3774. structuredClone: true,
  3775. });
  3776. let serialized = packr.pack(set);
  3777. let deserialized = packr.unpack(serialized);
  3778. assert.equal(deserialized.constructor.name, 'Set');
  3779. let map = Array.from(deserialized)[0][3].map;
  3780. assert.equal(map.get(deserialized), deserialized);
  3781. let sizeTestMap = new Map();
  3782. for (let i = 0; i < 50; i++) {
  3783. sizeTestMap.set(i || sizeTestMap, sizeTestMap);
  3784. let deserialized = packr.unpack(packr.pack(sizeTestMap));
  3785. assert.equal(deserialized.size, i + 1);
  3786. assert(deserialized.has(deserialized));
  3787. assert(deserialized.has(i || deserialized));
  3788. }
  3789. let sizeTestSet = new Set();
  3790. for (let i = 0; i < 50; i++) {
  3791. sizeTestSet.add(i || sizeTestSet);
  3792. let deserialized = packr.unpack(packr.pack(sizeTestSet));
  3793. assert.equal(deserialized.size, i + 1);
  3794. assert(deserialized.has(deserialized));
  3795. assert(deserialized.has(i || deserialized));
  3796. }
  3797. });
  3798. test('structured cloning: types', function() {
  3799. let b = typeof Buffer != 'undefined' ? Buffer.alloc(20) : new Uint8Array(20);
  3800. let fa = new Float32Array(b.buffer, 8, 2);
  3801. fa[0] = 2.25;
  3802. fa[1] = 6;
  3803. let object = {
  3804. error: new Error('test'),
  3805. set: new Set(['a', 'b']),
  3806. regexp: /test/gi,
  3807. float32Array: fa,
  3808. uint16Array: new Uint16Array([3, 4]),
  3809. arrayBuffer: new Uint8Array([0xde, 0xad]).buffer,
  3810. dataView: new DataView(new Uint8Array([0xbe, 0xef]).buffer),
  3811. };
  3812. let packr = new Packr({
  3813. moreTypes: true,
  3814. structuredClone: true,
  3815. });
  3816. var serialized = packr.pack(object);
  3817. var deserialized = packr.unpack(serialized);
  3818. assert.deepEqual(Array.from(deserialized.set), Array.from(object.set));
  3819. assert.equal(deserialized.error.message, object.error.message);
  3820. assert.equal(deserialized.regexp.test('TEST'), true);
  3821. assert.equal(deserialized.float32Array.constructor.name, 'Float32Array');
  3822. assert.equal(deserialized.float32Array[0], 2.25);
  3823. assert.equal(deserialized.float32Array[1], 6);
  3824. assert.equal(deserialized.uint16Array.constructor.name, 'Uint16Array');
  3825. assert.equal(deserialized.uint16Array[0], 3);
  3826. assert.equal(deserialized.uint16Array[1], 4);
  3827. assert.equal(deserialized.arrayBuffer.constructor.name, 'ArrayBuffer');
  3828. assert.equal(new DataView(deserialized.arrayBuffer).getUint16(), 0xdead);
  3829. assert.equal(deserialized.dataView.constructor.name, 'DataView');
  3830. assert.equal(deserialized.dataView.getUint16(), 0xbeef);
  3831. });
  3832. test('big bundledStrings', function() {
  3833. const MSGPACK_OPTIONS = {bundleStrings: true};
  3834. const packer = new Packr(MSGPACK_OPTIONS);
  3835. const unpacker = new Unpackr(MSGPACK_OPTIONS);
  3836. const payload = {
  3837. output: [
  3838. {
  3839. url: 'https://www.example.com/',
  3840. },
  3841. ],
  3842. };
  3843. for (let i = 0; i < 10000; i++) {
  3844. payload.output.push(payload.output[0]);
  3845. }
  3846. let deserialized = unpacker.unpack(packer.pack(payload));
  3847. assert.equal(deserialized.output[0].url, payload.output[0].url);
  3848. });
  3849. test('structured clone with bundled strings', function() {
  3850. const packer = new Packr({
  3851. structuredClone: true, // both options must be enabled
  3852. bundleStrings: true,
  3853. });
  3854. const v = {};
  3855. let shared = {
  3856. name1: v,
  3857. name2: v,
  3858. };
  3859. let deserialized = packer.unpack(packer.pack(shared));
  3860. assert.equal(deserialized.name1, deserialized.name2);
  3861. shared = {};
  3862. shared.aaaa = shared; // key length >= 4
  3863. deserialized = packer.unpack(packer.pack(shared));
  3864. assert.equal(deserialized.aaaa, deserialized);
  3865. });
  3866. test('object without prototype', function(){
  3867. var data = Object.create(null);
  3868. data.test = 3;
  3869. var serialized = pack(data);
  3870. var deserialized = unpack(serialized);
  3871. assert.deepEqual(deserialized, data);
  3872. });
  3873. test('object with __proto__', function(){
  3874. const data = { foo: 'bar', __proto__: { isAdmin: true } };
  3875. var serialized = pack(data);
  3876. var deserialized = unpack(serialized);
  3877. assert.deepEqual(deserialized, { foo: 'bar' });
  3878. });
  3879. test('separate instances', function() {
  3880. const packr = new Packr({
  3881. structures: [['m', 'e'], ['action', 'share']]
  3882. });
  3883. const packr2 = new Packr({
  3884. structures: [['m', 'e'], ['action', 'share']]
  3885. });
  3886. let packed = packr.pack([{m: 1, e: 2}, {action: 3, share: 4}]);
  3887. // also tried directly decoding this without the first Packr instance packed = new Uint8Array([0x92, 0x40, 0x01, 0x02, 0x41, 0x03, 0x04]);
  3888. console.log(packr2.unpack(packed));
  3889. });
  3890. test('many shared structures', function() {
  3891. let data = [];
  3892. for (let i = 0; i < 200; i++) {
  3893. data.push({['a' + i]: i});
  3894. }
  3895. let structures = [];
  3896. let savedStructures;
  3897. let packr = new Packr({
  3898. structures,
  3899. saveStructures(structures) {
  3900. savedStructures = structures;
  3901. }
  3902. });
  3903. var serializedWith32 = packr.pack(data);
  3904. assert.equal(savedStructures.length, 32);
  3905. var deserialized = packr.unpack(serializedWith32);
  3906. assert.deepEqual(deserialized, data);
  3907. structures = structures.slice(0, 32);
  3908. packr = new Packr({
  3909. structures,
  3910. maxSharedStructures: 100,
  3911. saveStructures(structures) {
  3912. savedStructures = structures;
  3913. }
  3914. });
  3915. deserialized = packr.unpack(serializedWith32);
  3916. assert.deepEqual(deserialized, data);
  3917. structures = structures.slice(0, 32);
  3918. packr = new Packr({
  3919. structures,
  3920. maxSharedStructures: 100,
  3921. saveStructures(structures) {
  3922. savedStructures = structures;
  3923. }
  3924. });
  3925. let serialized = packr.pack(data);
  3926. assert.equal(savedStructures.length, 100);
  3927. deserialized = packr.unpack(serialized);
  3928. assert.deepEqual(deserialized, data);
  3929. deserialized = packr.unpack(serializedWith32);
  3930. assert.deepEqual(deserialized, data);
  3931. assert.equal(savedStructures.length, 100);
  3932. deserialized = packr.unpack(serialized);
  3933. assert.deepEqual(deserialized, data);
  3934. assert.equal(packr.structures.sharedLength, 100);
  3935. });
  3936. test('more shared structures', function() {
  3937. const structures = [];
  3938. for (let i = 0; i < 40; i++) {
  3939. structures.push(['a' + i]);
  3940. }
  3941. const structures2 = [...structures];
  3942. const packr = new Packr({
  3943. getStructures() {
  3944. return structures
  3945. },
  3946. saveStructures(structures) {
  3947. },
  3948. maxSharedStructures: 100
  3949. });
  3950. const packr2 = new Packr({
  3951. getStructures() {
  3952. return structures2
  3953. },
  3954. saveStructures(structures) {
  3955. },
  3956. maxSharedStructures: 100
  3957. });
  3958. const inputData = {a35: 35};
  3959. const buffer = packr.pack(inputData);
  3960. const outputData = packr2.decode(buffer);
  3961. assert.deepEqual(inputData, outputData);
  3962. });
  3963. test('big buffer', function() {
  3964. var size = 100000000;
  3965. var data = new Uint8Array(size).fill(1);
  3966. var packed = pack(data);
  3967. var unpacked = unpack(packed);
  3968. assert.equal(unpacked.length, size);
  3969. });
  3970. test('random strings', function(){
  3971. var data = [];
  3972. for (var i = 0; i < 2000; i++) {
  3973. var str = 'test';
  3974. while (Math.random() < 0.7 && str.length < 0x100000) {
  3975. str = str + String.fromCharCode(90/(Math.random() + 0.01)) + str;
  3976. }
  3977. data.push(str);
  3978. }
  3979. var serialized = pack(data);
  3980. var deserialized = unpack(serialized);
  3981. assert.deepEqual(deserialized, data);
  3982. });
  3983. test('map/date', function(){
  3984. var map = new Map();
  3985. map.set(4, 'four');
  3986. map.set('three', 3);
  3987. var data = {
  3988. map: map,
  3989. date: new Date(1532219539733),
  3990. farFutureDate: new Date(3532219539133),
  3991. fartherFutureDate: new Date('2106-08-05T18:48:20.323Z'),
  3992. ancient: new Date(-3532219539133),
  3993. invalidDate: new Date('invalid')
  3994. };
  3995. let packr = new Packr();
  3996. var serialized = packr.pack(data);
  3997. var deserialized = packr.unpack(serialized);
  3998. assert.equal(deserialized.map.get(4), 'four');
  3999. assert.equal(deserialized.map.get('three'), 3);
  4000. assert.equal(deserialized.date.getTime(), 1532219539733);
  4001. assert.equal(deserialized.farFutureDate.getTime(), 3532219539133);
  4002. assert.equal(deserialized.fartherFutureDate.toISOString(), '2106-08-05T18:48:20.323Z');
  4003. assert.equal(deserialized.ancient.getTime(), -3532219539133);
  4004. assert.equal(deserialized.invalidDate.toString(), 'Invalid Date');
  4005. });
  4006. test('map/date with options', function(){
  4007. var map = new Map();
  4008. map.set(4, 'four');
  4009. map.set('three', 3);
  4010. var data = {
  4011. map: map,
  4012. date: new Date(1532219539011),
  4013. invalidDate: new Date('invalid')
  4014. };
  4015. let packr = new Packr({
  4016. mapsAsObjects: true,
  4017. useTimestamp32: true,
  4018. onInvalidDate: () => 'Custom invalid date'
  4019. });
  4020. var serialized = packr.pack(data);
  4021. var deserialized = packr.unpack(serialized);
  4022. assert.equal(deserialized.map[4], 'four');
  4023. assert.equal(deserialized.map.three, 3);
  4024. assert.equal(deserialized.date.getTime(), 1532219539000);
  4025. assert.equal(deserialized.invalidDate, 'Custom invalid date');
  4026. });
  4027. test('key caching', function() {
  4028. var data = {
  4029. foo: 2,
  4030. bar: 'test',
  4031. four: 4,
  4032. seven: 7,
  4033. foz: 3,
  4034. };
  4035. var serialized = pack(data);
  4036. var deserialized = unpack(serialized);
  4037. assert.deepEqual(deserialized, data);
  4038. // do multiple times to test caching
  4039. var serialized = pack(data);
  4040. var deserialized = unpack(serialized);
  4041. assert.deepEqual(deserialized, data);
  4042. var serialized = pack(data);
  4043. var deserialized = unpack(serialized);
  4044. assert.deepEqual(deserialized, data);
  4045. });
  4046. test('strings', function() {
  4047. var data = [''];
  4048. var serialized = pack(data);
  4049. var deserialized = unpack(serialized);
  4050. assert.deepEqual(deserialized, data);
  4051. // do multiple times
  4052. var serialized = pack(data);
  4053. var deserialized = unpack(serialized);
  4054. assert.deepEqual(deserialized, data);
  4055. data = 'decode this: ᾜ';
  4056. var serialized = pack(data);
  4057. var deserialized = unpack(serialized);
  4058. assert.deepEqual(deserialized, data);
  4059. data = 'decode this that is longer but without any non-latin characters';
  4060. var serialized = pack(data);
  4061. var deserialized = unpack(serialized);
  4062. assert.deepEqual(deserialized, data);
  4063. });
  4064. test('decimal float32', function() {
  4065. var data = {
  4066. a: 2.526,
  4067. b: 0.0035235,
  4068. c: 0.00000000000352501,
  4069. d: 3252.77,
  4070. };
  4071. let packr = new Packr({
  4072. useFloat32: DECIMAL_FIT
  4073. });
  4074. var serialized = packr.pack(data);
  4075. assert.equal(serialized.length, 32);
  4076. var deserialized = packr.unpack(serialized);
  4077. assert.deepEqual(deserialized, data);
  4078. });
  4079. test('int64/uint64 should be bigints by default', function() {
  4080. var data = {
  4081. a: 325283295382932843n
  4082. };
  4083. let packr = new Packr();
  4084. var serialized = packr.pack(data);
  4085. var deserialized = packr.unpack(serialized);
  4086. assert.deepEqual(deserialized.a, 325283295382932843n);
  4087. });
  4088. test('bigint to float', function() {
  4089. var data = {
  4090. a: 325283295382932843n
  4091. };
  4092. let packr = new Packr({
  4093. int64AsType: 'number'
  4094. });
  4095. var serialized = packr.pack(data);
  4096. var deserialized = packr.unpack(serialized);
  4097. assert.deepEqual(deserialized.a, 325283295382932843);
  4098. });
  4099. test('int64AsNumber compatibility', function() {
  4100. // https://github.com/kriszyp/msgpackr/pull/85
  4101. var data = {
  4102. a: 325283295382932843n
  4103. };
  4104. let packr = new Packr({
  4105. int64AsNumber: true
  4106. });
  4107. var serialized = packr.pack(data);
  4108. var deserialized = packr.unpack(serialized);
  4109. assert.deepEqual(deserialized.a, 325283295382932843);
  4110. });
  4111. test('bigint to auto (float or bigint)', function() {
  4112. var data = {
  4113. a: -9007199254740993n,
  4114. b: -9007199254740992n,
  4115. c: 0n,
  4116. d: 9007199254740992n,
  4117. e: 9007199254740993n,
  4118. };
  4119. let packr = new Packr({
  4120. int64AsType: 'auto'
  4121. });
  4122. var serialized = packr.pack(data);
  4123. var deserialized = packr.unpack(serialized);
  4124. assert.deepEqual(deserialized.a, -9007199254740993n);
  4125. assert.deepEqual(deserialized.b, -9007199254740992);
  4126. assert.deepEqual(deserialized.c, 0);
  4127. assert.deepEqual(deserialized.d, 9007199254740992);
  4128. assert.deepEqual(deserialized.e, 9007199254740993n);
  4129. });
  4130. test('bigint to string', function() {
  4131. var data = {
  4132. a: 325283295382932843n,
  4133. };
  4134. let packr = new Packr({
  4135. int64AsType: 'string'
  4136. });
  4137. var serialized = packr.pack(data);
  4138. var deserialized = packr.unpack(serialized);
  4139. assert.deepEqual(deserialized.a, '325283295382932843');
  4140. });
  4141. test('fixint should be one byte', function(){
  4142. let encoded = pack(123);
  4143. assert.equal(encoded.length, 1);
  4144. });
  4145. test('numbers', function(){
  4146. var data = {
  4147. bigEncodable: 48978578104322,
  4148. dateEpoch: 1530886513200,
  4149. realBig: 3432235352353255323,
  4150. decimal: 32.55234,
  4151. negative: -34.11,
  4152. exponential: 0.234e123,
  4153. tiny: 3.233e-120,
  4154. zero: 0,
  4155. //negativeZero: -0,
  4156. Infinity: Infinity
  4157. };
  4158. var serialized = pack(data);
  4159. var deserialized = unpack(serialized);
  4160. assert.deepEqual(deserialized, data);
  4161. });
  4162. test('bigint', function(){
  4163. var data = {
  4164. bigintSmall: 352n,
  4165. bigintSmallNegative: -333335252n,
  4166. bigintBig: 2n**64n - 1n, // biggest possible
  4167. bigintBigNegative: -(2n**63n), // largest negative
  4168. mixedWithNormal: 44,
  4169. };
  4170. var serialized = pack(data);
  4171. var deserialized = unpack(serialized);
  4172. assert.deepEqual(deserialized, data);
  4173. var tooBigInt = {
  4174. tooBig: 2n**66n
  4175. };
  4176. assert.throws(function(){ serialized = pack(tooBigInt); });
  4177. let packr = new Packr({
  4178. largeBigIntToFloat: true
  4179. });
  4180. serialized = packr.pack(tooBigInt);
  4181. deserialized = unpack(serialized);
  4182. assert.isTrue(deserialized.tooBig > 2n**65n);
  4183. packr = new Packr({
  4184. largeBigIntToString: true
  4185. });
  4186. serialized = packr.pack(tooBigInt);
  4187. deserialized = unpack(serialized);
  4188. assert.equal(deserialized.tooBig, (2n**66n).toString());
  4189. });
  4190. test('roundFloat32', function() {
  4191. assert.equal(roundFloat32(0.00333000003), 0.00333);
  4192. assert.equal(roundFloat32(43.29999999993), 43.3);
  4193. });
  4194. test('buffers', function(){
  4195. var data = {
  4196. buffer1: new Uint8Array([2,3,4]),
  4197. buffer2: new Uint8Array(pack(sampleData))
  4198. };
  4199. var serialized = pack(data);
  4200. var deserialized = unpack(serialized);
  4201. assert.deepEqual(deserialized, data);
  4202. });
  4203. test('notepack test', function() {
  4204. const data = {
  4205. foo: 1,
  4206. bar: [1, 2, 3, 4, 'abc', 'def'],
  4207. foobar: {
  4208. foo: true,
  4209. bar: -2147483649,
  4210. foobar: {
  4211. foo: new Uint8Array([1, 2, 3, 4, 5]),
  4212. bar: 1.5,
  4213. foobar: [true, false, 'abcdefghijkmonpqrstuvwxyz']
  4214. }
  4215. }
  4216. };
  4217. var serialized = pack(data);
  4218. var deserialized = unpack(serialized);
  4219. var deserialized = unpack(serialized);
  4220. var deserialized = unpack(serialized);
  4221. assert.deepEqual(deserialized, data);
  4222. });
  4223. test('arrays in map keys', function() {
  4224. const msgpackr = new Packr({ mapsAsObjects: true, allowArraysInMapKeys: true });
  4225. const map = new Map();
  4226. map.set([1, 2, 3], 1);
  4227. map.set([1, 2, ['foo', 3.14]], 2);
  4228. const packed = msgpackr.pack(map);
  4229. const unpacked = msgpackr.unpack(packed);
  4230. assert.deepEqual(unpacked, { '1,2,3': 1, '1,2,foo,3.14': 2 });
  4231. });
  4232. test('utf16 causing expansion', function() {
  4233. this.timeout(10000);
  4234. let data = {fixstr: 'ᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝ', str8:'ᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝᾐᾑᾒᾓᾔᾕᾖᾗᾘᾙᾚᾛᾜᾝ'};
  4235. var serialized = pack(data);
  4236. var deserialized = unpack(serialized);
  4237. assert.deepEqual(deserialized, data);
  4238. });
  4239. test('unpackMultiple', () => {
  4240. let values = unpackMultiple(new Uint8Array([1, 2, 3, 4]));
  4241. assert.deepEqual(values, [1, 2, 3, 4]);
  4242. values = [];
  4243. unpackMultiple(new Uint8Array([1, 2, 3, 4]), value => values.push(value));
  4244. assert.deepEqual(values, [1, 2, 3, 4]);
  4245. });
  4246. test('unpackMultiple with positions', () => {
  4247. let values = unpackMultiple(new Uint8Array([1, 2, 3, 4]));
  4248. assert.deepEqual(values, [1, 2, 3, 4]);
  4249. values = [];
  4250. unpackMultiple(new Uint8Array([1, 2, 3, 4]), (value,start,end) => values.push([value,start,end]));
  4251. assert.deepEqual(values, [[1,0,1], [2,1,2], [3,2,3], [4,3,4]]);
  4252. });
  4253. test('pack toJSON returning this', () => {
  4254. class Serializable {
  4255. someData = [1, 2, 3, 4]
  4256. toJSON() {
  4257. return this
  4258. }
  4259. }
  4260. const serialized = pack(new Serializable);
  4261. const deserialized = unpack(serialized);
  4262. assert.deepStrictEqual(deserialized, { someData: [1, 2, 3, 4] });
  4263. });
  4264. test('skip values', function () {
  4265. var data = {
  4266. data: [
  4267. { a: 1, name: 'one', type: 'odd', isOdd: true },
  4268. { a: 2, name: 'two', type: 'even', isOdd: undefined },
  4269. { a: 3, name: 'three', type: 'odd', isOdd: true },
  4270. { a: 4, name: 'four', type: 'even', isOdd: null},
  4271. { a: 5, name: 'five', type: 'odd', isOdd: true },
  4272. { a: 6, name: 'six', type: 'even', isOdd: null }
  4273. ],
  4274. description: 'some names',
  4275. types: ['odd', 'even'],
  4276. convertEnumToNum: [
  4277. { prop: 'test' },
  4278. { prop: 'test' },
  4279. { prop: 'test' },
  4280. { prop: 1 },
  4281. { prop: 2 },
  4282. { prop: [undefined, null] },
  4283. { prop: null }
  4284. ]
  4285. };
  4286. var expected = {
  4287. data: [
  4288. { a: 1, name: 'one', type: 'odd', isOdd: true },
  4289. { a: 2, name: 'two', type: 'even' },
  4290. { a: 3, name: 'three', type: 'odd', isOdd: true },
  4291. { a: 4, name: 'four', type: 'even', },
  4292. { a: 5, name: 'five', type: 'odd', isOdd: true },
  4293. { a: 6, name: 'six', type: 'even' }
  4294. ],
  4295. description: 'some names',
  4296. types: ['odd', 'even'],
  4297. convertEnumToNum: [
  4298. { prop: 'test' },
  4299. { prop: 'test' },
  4300. { prop: 'test' },
  4301. { prop: 1 },
  4302. { prop: 2 },
  4303. { prop: [undefined, null] },
  4304. {}
  4305. ]
  4306. };
  4307. let packr = new Packr({ useRecords: false, skipValues: [undefined, null] });
  4308. var serialized = packr.pack(data);
  4309. var deserialized = packr.unpack(serialized);
  4310. assert.deepEqual(deserialized, expected);
  4311. });
  4312. });
  4313. suite('msgpackr performance tests', function(){
  4314. test('performance JSON.parse', function() {
  4315. var data = sampleData;
  4316. this.timeout(10000);
  4317. var serialized = JSON.stringify(data);
  4318. console.log('JSON size', serialized.length);
  4319. for (var i = 0; i < ITERATIONS; i++) {
  4320. JSON.parse(serialized);
  4321. }
  4322. });
  4323. test('performance JSON.stringify', function() {
  4324. var data = sampleData;
  4325. this.timeout(10000);
  4326. for (var i = 0; i < ITERATIONS; i++) {
  4327. JSON.stringify(data);
  4328. }
  4329. });
  4330. test('performance unpack', function() {
  4331. var data = sampleData;
  4332. this.timeout(10000);
  4333. let structures = [];
  4334. var serialized = pack(data);
  4335. console.log('MessagePack size', serialized.length);
  4336. let packr = new Packr({ structures, bundleStrings: false });
  4337. var serialized = packr.pack(data);
  4338. console.log('msgpackr w/ record ext size', serialized.length);
  4339. for (var i = 0; i < ITERATIONS; i++) {
  4340. packr.unpack(serialized);
  4341. }
  4342. });
  4343. test('performance pack', function() {
  4344. var data = sampleData;
  4345. this.timeout(10000);
  4346. let structures = [];
  4347. let packr = new Packr({ structures, bundleStrings: false });
  4348. let buffer = typeof Buffer != 'undefined' ? Buffer.alloc(0x10000) : new Uint8Array(0x10000);
  4349. for (var i = 0; i < ITERATIONS; i++) {
  4350. //serialized = pack(data, { shared: sharedStructure })
  4351. packr.useBuffer(buffer);
  4352. packr.pack(data);
  4353. //var serializedGzip = deflateSync(serialized)
  4354. }
  4355. //console.log('serialized', serialized.length, global.propertyComparisons)
  4356. });
  4357. });
  4358. })(chai, null, module, fs);
  4359. //# sourceMappingURL=test.js.map