node.cjs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  1. 'use strict';
  2. var stream = require('stream');
  3. var module$1 = require('module');
  4. var decoder;
  5. try {
  6. decoder = new TextDecoder();
  7. } catch(error) {}
  8. var src;
  9. var srcEnd;
  10. var position$1 = 0;
  11. const EMPTY_ARRAY = [];
  12. var strings = EMPTY_ARRAY;
  13. var stringPosition = 0;
  14. var currentUnpackr = {};
  15. var currentStructures;
  16. var srcString;
  17. var srcStringStart = 0;
  18. var srcStringEnd = 0;
  19. var bundledStrings$1;
  20. var referenceMap;
  21. var currentExtensions = [];
  22. var dataView;
  23. var defaultOptions = {
  24. useRecords: false,
  25. mapsAsObjects: true
  26. };
  27. class C1Type {}
  28. const C1 = new C1Type();
  29. C1.name = 'MessagePack 0xC1';
  30. var sequentialMode = false;
  31. var inlineObjectReadThreshold = 2;
  32. var readStruct$1, onLoadedStructures$1, onSaveState;
  33. // no-eval build
  34. try {
  35. new Function('');
  36. } catch(error) {
  37. // if eval variants are not supported, do not create inline object readers ever
  38. inlineObjectReadThreshold = Infinity;
  39. }
  40. class Unpackr {
  41. constructor(options) {
  42. if (options) {
  43. if (options.useRecords === false && options.mapsAsObjects === undefined)
  44. options.mapsAsObjects = true;
  45. if (options.sequential && options.trusted !== false) {
  46. options.trusted = true;
  47. if (!options.structures && options.useRecords != false) {
  48. options.structures = [];
  49. if (!options.maxSharedStructures)
  50. options.maxSharedStructures = 0;
  51. }
  52. }
  53. if (options.structures)
  54. options.structures.sharedLength = options.structures.length;
  55. else if (options.getStructures) {
  56. (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
  57. options.structures.sharedLength = 0;
  58. }
  59. if (options.int64AsNumber) {
  60. options.int64AsType = 'number';
  61. }
  62. }
  63. Object.assign(this, options);
  64. }
  65. unpack(source, options) {
  66. if (src) {
  67. // re-entrant execution, save the state and restore it after we do this unpack
  68. return saveState$1(() => {
  69. clearSource();
  70. return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
  71. })
  72. }
  73. if (!source.buffer && source.constructor === ArrayBuffer)
  74. source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
  75. if (typeof options === 'object') {
  76. srcEnd = options.end || source.length;
  77. position$1 = options.start || 0;
  78. } else {
  79. position$1 = 0;
  80. srcEnd = options > -1 ? options : source.length;
  81. }
  82. stringPosition = 0;
  83. srcStringEnd = 0;
  84. srcString = null;
  85. strings = EMPTY_ARRAY;
  86. bundledStrings$1 = null;
  87. src = source;
  88. // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
  89. // technique for getting data from a database where it can be copied into an existing buffer instead of creating
  90. // new ones
  91. try {
  92. dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
  93. } catch(error) {
  94. // if it doesn't have a buffer, maybe it is the wrong type of object
  95. src = null;
  96. if (source instanceof Uint8Array)
  97. throw error
  98. throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
  99. }
  100. if (this instanceof Unpackr) {
  101. currentUnpackr = this;
  102. if (this.structures) {
  103. currentStructures = this.structures;
  104. return checkedRead(options)
  105. } else if (!currentStructures || currentStructures.length > 0) {
  106. currentStructures = [];
  107. }
  108. } else {
  109. currentUnpackr = defaultOptions;
  110. if (!currentStructures || currentStructures.length > 0)
  111. currentStructures = [];
  112. }
  113. return checkedRead(options)
  114. }
  115. unpackMultiple(source, forEach) {
  116. let values, lastPosition = 0;
  117. try {
  118. sequentialMode = true;
  119. let size = source.length;
  120. let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
  121. if (forEach) {
  122. if (forEach(value, lastPosition, position$1) === false) return;
  123. while(position$1 < size) {
  124. lastPosition = position$1;
  125. if (forEach(checkedRead(), lastPosition, position$1) === false) {
  126. return
  127. }
  128. }
  129. }
  130. else {
  131. values = [ value ];
  132. while(position$1 < size) {
  133. lastPosition = position$1;
  134. values.push(checkedRead());
  135. }
  136. return values
  137. }
  138. } catch(error) {
  139. error.lastPosition = lastPosition;
  140. error.values = values;
  141. throw error
  142. } finally {
  143. sequentialMode = false;
  144. clearSource();
  145. }
  146. }
  147. _mergeStructures(loadedStructures, existingStructures) {
  148. if (onLoadedStructures$1)
  149. loadedStructures = onLoadedStructures$1.call(this, loadedStructures);
  150. loadedStructures = loadedStructures || [];
  151. if (Object.isFrozen(loadedStructures))
  152. loadedStructures = loadedStructures.map(structure => structure.slice(0));
  153. for (let i = 0, l = loadedStructures.length; i < l; i++) {
  154. let structure = loadedStructures[i];
  155. if (structure) {
  156. structure.isShared = true;
  157. if (i >= 32)
  158. structure.highByte = (i - 32) >> 5;
  159. }
  160. }
  161. loadedStructures.sharedLength = loadedStructures.length;
  162. for (let id in existingStructures || []) {
  163. if (id >= 0) {
  164. let structure = loadedStructures[id];
  165. let existing = existingStructures[id];
  166. if (existing) {
  167. if (structure)
  168. (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
  169. loadedStructures[id] = existing;
  170. }
  171. }
  172. }
  173. return this.structures = loadedStructures
  174. }
  175. decode(source, options) {
  176. return this.unpack(source, options)
  177. }
  178. }
  179. function checkedRead(options) {
  180. try {
  181. if (!currentUnpackr.trusted && !sequentialMode) {
  182. let sharedLength = currentStructures.sharedLength || 0;
  183. if (sharedLength < currentStructures.length)
  184. currentStructures.length = sharedLength;
  185. }
  186. let result;
  187. if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct$1) {
  188. result = readStruct$1(src, position$1, srcEnd, currentUnpackr);
  189. src = null; // dispose of this so that recursive unpack calls don't save state
  190. if (!(options && options.lazy) && result)
  191. result = result.toJSON();
  192. position$1 = srcEnd;
  193. } else
  194. result = read();
  195. if (bundledStrings$1) { // bundled strings to skip past
  196. position$1 = bundledStrings$1.postBundlePosition;
  197. bundledStrings$1 = null;
  198. }
  199. if (sequentialMode)
  200. // we only need to restore the structures if there was an error, but if we completed a read,
  201. // we can clear this out and keep the structures we read
  202. currentStructures.restoreStructures = null;
  203. if (position$1 == srcEnd) {
  204. // finished reading this source, cleanup references
  205. if (currentStructures && currentStructures.restoreStructures)
  206. restoreStructures();
  207. currentStructures = null;
  208. src = null;
  209. if (referenceMap)
  210. referenceMap = null;
  211. } else if (position$1 > srcEnd) {
  212. // over read
  213. throw new Error('Unexpected end of MessagePack data')
  214. } else if (!sequentialMode) {
  215. let jsonView;
  216. try {
  217. jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
  218. } catch(error) {
  219. jsonView = '(JSON view not available ' + error + ')';
  220. }
  221. throw new Error('Data read, but end of buffer not reached ' + jsonView)
  222. }
  223. // else more to read, but we are reading sequentially, so don't clear source yet
  224. return result
  225. } catch(error) {
  226. if (currentStructures && currentStructures.restoreStructures)
  227. restoreStructures();
  228. clearSource();
  229. if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
  230. error.incomplete = true;
  231. }
  232. throw error
  233. }
  234. }
  235. function restoreStructures() {
  236. for (let id in currentStructures.restoreStructures) {
  237. currentStructures[id] = currentStructures.restoreStructures[id];
  238. }
  239. currentStructures.restoreStructures = null;
  240. }
  241. function read() {
  242. let token = src[position$1++];
  243. if (token < 0xa0) {
  244. if (token < 0x80) {
  245. if (token < 0x40)
  246. return token
  247. else {
  248. let structure = currentStructures[token & 0x3f] ||
  249. currentUnpackr.getStructures && loadStructures()[token & 0x3f];
  250. if (structure) {
  251. if (!structure.read) {
  252. structure.read = createStructureReader(structure, token & 0x3f);
  253. }
  254. return structure.read()
  255. } else
  256. return token
  257. }
  258. } else if (token < 0x90) {
  259. // map
  260. token -= 0x80;
  261. if (currentUnpackr.mapsAsObjects) {
  262. let object = {};
  263. for (let i = 0; i < token; i++) {
  264. let key = readKey();
  265. if (key === '__proto__')
  266. key = '__proto_';
  267. object[key] = read();
  268. }
  269. return object
  270. } else {
  271. let map = new Map();
  272. for (let i = 0; i < token; i++) {
  273. map.set(read(), read());
  274. }
  275. return map
  276. }
  277. } else {
  278. token -= 0x90;
  279. let array = new Array(token);
  280. for (let i = 0; i < token; i++) {
  281. array[i] = read();
  282. }
  283. if (currentUnpackr.freezeData)
  284. return Object.freeze(array)
  285. return array
  286. }
  287. } else if (token < 0xc0) {
  288. // fixstr
  289. let length = token - 0xa0;
  290. if (srcStringEnd >= position$1) {
  291. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  292. }
  293. if (srcStringEnd == 0 && srcEnd < 140) {
  294. // for small blocks, avoiding the overhead of the extract call is helpful
  295. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  296. if (string != null)
  297. return string
  298. }
  299. return readFixedString(length)
  300. } else {
  301. let value;
  302. switch (token) {
  303. case 0xc0: return null
  304. case 0xc1:
  305. if (bundledStrings$1) {
  306. value = read(); // followed by the length of the string in characters (not bytes!)
  307. if (value > 0)
  308. return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
  309. else
  310. return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
  311. }
  312. return C1; // "never-used", return special object to denote that
  313. case 0xc2: return false
  314. case 0xc3: return true
  315. case 0xc4:
  316. // bin 8
  317. value = src[position$1++];
  318. if (value === undefined)
  319. throw new Error('Unexpected end of buffer')
  320. return readBin(value)
  321. case 0xc5:
  322. // bin 16
  323. value = dataView.getUint16(position$1);
  324. position$1 += 2;
  325. return readBin(value)
  326. case 0xc6:
  327. // bin 32
  328. value = dataView.getUint32(position$1);
  329. position$1 += 4;
  330. return readBin(value)
  331. case 0xc7:
  332. // ext 8
  333. return readExt(src[position$1++])
  334. case 0xc8:
  335. // ext 16
  336. value = dataView.getUint16(position$1);
  337. position$1 += 2;
  338. return readExt(value)
  339. case 0xc9:
  340. // ext 32
  341. value = dataView.getUint32(position$1);
  342. position$1 += 4;
  343. return readExt(value)
  344. case 0xca:
  345. value = dataView.getFloat32(position$1);
  346. if (currentUnpackr.useFloat32 > 2) {
  347. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  348. let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
  349. position$1 += 4;
  350. return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  351. }
  352. position$1 += 4;
  353. return value
  354. case 0xcb:
  355. value = dataView.getFloat64(position$1);
  356. position$1 += 8;
  357. return value
  358. // uint handlers
  359. case 0xcc:
  360. return src[position$1++]
  361. case 0xcd:
  362. value = dataView.getUint16(position$1);
  363. position$1 += 2;
  364. return value
  365. case 0xce:
  366. value = dataView.getUint32(position$1);
  367. position$1 += 4;
  368. return value
  369. case 0xcf:
  370. if (currentUnpackr.int64AsType === 'number') {
  371. value = dataView.getUint32(position$1) * 0x100000000;
  372. value += dataView.getUint32(position$1 + 4);
  373. } else if (currentUnpackr.int64AsType === 'string') {
  374. value = dataView.getBigUint64(position$1).toString();
  375. } else if (currentUnpackr.int64AsType === 'auto') {
  376. value = dataView.getBigUint64(position$1);
  377. if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
  378. } else
  379. value = dataView.getBigUint64(position$1);
  380. position$1 += 8;
  381. return value
  382. // int handlers
  383. case 0xd0:
  384. return dataView.getInt8(position$1++)
  385. case 0xd1:
  386. value = dataView.getInt16(position$1);
  387. position$1 += 2;
  388. return value
  389. case 0xd2:
  390. value = dataView.getInt32(position$1);
  391. position$1 += 4;
  392. return value
  393. case 0xd3:
  394. if (currentUnpackr.int64AsType === 'number') {
  395. value = dataView.getInt32(position$1) * 0x100000000;
  396. value += dataView.getUint32(position$1 + 4);
  397. } else if (currentUnpackr.int64AsType === 'string') {
  398. value = dataView.getBigInt64(position$1).toString();
  399. } else if (currentUnpackr.int64AsType === 'auto') {
  400. value = dataView.getBigInt64(position$1);
  401. if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
  402. } else
  403. value = dataView.getBigInt64(position$1);
  404. position$1 += 8;
  405. return value
  406. case 0xd4:
  407. // fixext 1
  408. value = src[position$1++];
  409. if (value == 0x72) {
  410. return recordDefinition(src[position$1++] & 0x3f)
  411. } else {
  412. let extension = currentExtensions[value];
  413. if (extension) {
  414. if (extension.read) {
  415. position$1++; // skip filler byte
  416. return extension.read(read())
  417. } else if (extension.noBuffer) {
  418. position$1++; // skip filler byte
  419. return extension()
  420. } else
  421. return extension(src.subarray(position$1, ++position$1))
  422. } else
  423. throw new Error('Unknown extension ' + value)
  424. }
  425. case 0xd5:
  426. // fixext 2
  427. value = src[position$1];
  428. if (value == 0x72) {
  429. position$1++;
  430. return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
  431. } else
  432. return readExt(2)
  433. case 0xd6:
  434. // fixext 4
  435. return readExt(4)
  436. case 0xd7:
  437. // fixext 8
  438. return readExt(8)
  439. case 0xd8:
  440. // fixext 16
  441. return readExt(16)
  442. case 0xd9:
  443. // str 8
  444. value = src[position$1++];
  445. if (srcStringEnd >= position$1) {
  446. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  447. }
  448. return readString8(value)
  449. case 0xda:
  450. // str 16
  451. value = dataView.getUint16(position$1);
  452. position$1 += 2;
  453. if (srcStringEnd >= position$1) {
  454. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  455. }
  456. return readString16(value)
  457. case 0xdb:
  458. // str 32
  459. value = dataView.getUint32(position$1);
  460. position$1 += 4;
  461. if (srcStringEnd >= position$1) {
  462. return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
  463. }
  464. return readString32(value)
  465. case 0xdc:
  466. // array 16
  467. value = dataView.getUint16(position$1);
  468. position$1 += 2;
  469. return readArray(value)
  470. case 0xdd:
  471. // array 32
  472. value = dataView.getUint32(position$1);
  473. position$1 += 4;
  474. return readArray(value)
  475. case 0xde:
  476. // map 16
  477. value = dataView.getUint16(position$1);
  478. position$1 += 2;
  479. return readMap(value)
  480. case 0xdf:
  481. // map 32
  482. value = dataView.getUint32(position$1);
  483. position$1 += 4;
  484. return readMap(value)
  485. default: // negative int
  486. if (token >= 0xe0)
  487. return token - 0x100
  488. if (token === undefined) {
  489. let error = new Error('Unexpected end of MessagePack data');
  490. error.incomplete = true;
  491. throw error
  492. }
  493. throw new Error('Unknown MessagePack token ' + token)
  494. }
  495. }
  496. }
  497. const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
  498. function createStructureReader(structure, firstId) {
  499. function readObject() {
  500. // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
  501. if (readObject.count++ > inlineObjectReadThreshold) {
  502. let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
  503. '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
  504. if (structure.highByte === 0)
  505. structure.read = createSecondByteReader(firstId, structure.read);
  506. return readObject() // second byte is already read, if there is one so immediately read object
  507. }
  508. let object = {};
  509. for (let i = 0, l = structure.length; i < l; i++) {
  510. let key = structure[i];
  511. if (key === '__proto__')
  512. key = '__proto_';
  513. object[key] = read();
  514. }
  515. if (currentUnpackr.freezeData)
  516. return Object.freeze(object);
  517. return object
  518. }
  519. readObject.count = 0;
  520. if (structure.highByte === 0) {
  521. return createSecondByteReader(firstId, readObject)
  522. }
  523. return readObject
  524. }
  525. const createSecondByteReader = (firstId, read0) => {
  526. return function() {
  527. let highByte = src[position$1++];
  528. if (highByte === 0)
  529. return read0()
  530. let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
  531. let structure = currentStructures[id] || loadStructures()[id];
  532. if (!structure) {
  533. throw new Error('Record id is not defined for ' + id)
  534. }
  535. if (!structure.read)
  536. structure.read = createStructureReader(structure, firstId);
  537. return structure.read()
  538. }
  539. };
  540. function loadStructures() {
  541. let loadedStructures = saveState$1(() => {
  542. // save the state in case getStructures modifies our buffer
  543. src = null;
  544. return currentUnpackr.getStructures()
  545. });
  546. return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
  547. }
  548. var readFixedString = readStringJS;
  549. var readString8 = readStringJS;
  550. var readString16 = readStringJS;
  551. var readString32 = readStringJS;
  552. exports.isNativeAccelerationEnabled = false;
  553. function setExtractor(extractStrings) {
  554. exports.isNativeAccelerationEnabled = true;
  555. readFixedString = readString(1);
  556. readString8 = readString(2);
  557. readString16 = readString(3);
  558. readString32 = readString(5);
  559. function readString(headerLength) {
  560. return function readString(length) {
  561. let string = strings[stringPosition++];
  562. if (string == null) {
  563. if (bundledStrings$1)
  564. return readStringJS(length)
  565. let byteOffset = src.byteOffset;
  566. let extraction = extractStrings(position$1 - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);
  567. if (typeof extraction == 'string') {
  568. string = extraction;
  569. strings = EMPTY_ARRAY;
  570. } else {
  571. strings = extraction;
  572. stringPosition = 1;
  573. 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
  574. string = strings[0];
  575. if (string === undefined)
  576. throw new Error('Unexpected end of buffer')
  577. }
  578. }
  579. let srcStringLength = string.length;
  580. if (srcStringLength <= length) {
  581. position$1 += length;
  582. return string
  583. }
  584. srcString = string;
  585. srcStringStart = position$1;
  586. srcStringEnd = position$1 + srcStringLength;
  587. position$1 += length;
  588. return string.slice(0, length) // we know we just want the beginning
  589. }
  590. }
  591. }
  592. function readStringJS(length) {
  593. let result;
  594. if (length < 16) {
  595. if (result = shortStringInJS(length))
  596. return result
  597. }
  598. if (length > 64 && decoder)
  599. return decoder.decode(src.subarray(position$1, position$1 += length))
  600. const end = position$1 + length;
  601. const units = [];
  602. result = '';
  603. while (position$1 < end) {
  604. const byte1 = src[position$1++];
  605. if ((byte1 & 0x80) === 0) {
  606. // 1 byte
  607. units.push(byte1);
  608. } else if ((byte1 & 0xe0) === 0xc0) {
  609. // 2 bytes
  610. const byte2 = src[position$1++] & 0x3f;
  611. units.push(((byte1 & 0x1f) << 6) | byte2);
  612. } else if ((byte1 & 0xf0) === 0xe0) {
  613. // 3 bytes
  614. const byte2 = src[position$1++] & 0x3f;
  615. const byte3 = src[position$1++] & 0x3f;
  616. units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
  617. } else if ((byte1 & 0xf8) === 0xf0) {
  618. // 4 bytes
  619. const byte2 = src[position$1++] & 0x3f;
  620. const byte3 = src[position$1++] & 0x3f;
  621. const byte4 = src[position$1++] & 0x3f;
  622. let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
  623. if (unit > 0xffff) {
  624. unit -= 0x10000;
  625. units.push(((unit >>> 10) & 0x3ff) | 0xd800);
  626. unit = 0xdc00 | (unit & 0x3ff);
  627. }
  628. units.push(unit);
  629. } else {
  630. units.push(byte1);
  631. }
  632. if (units.length >= 0x1000) {
  633. result += fromCharCode.apply(String, units);
  634. units.length = 0;
  635. }
  636. }
  637. if (units.length > 0) {
  638. result += fromCharCode.apply(String, units);
  639. }
  640. return result
  641. }
  642. function readString(source, start, length) {
  643. let existingSrc = src;
  644. src = source;
  645. position$1 = start;
  646. try {
  647. return readStringJS(length);
  648. } finally {
  649. src = existingSrc;
  650. }
  651. }
  652. function readArray(length) {
  653. let array = new Array(length);
  654. for (let i = 0; i < length; i++) {
  655. array[i] = read();
  656. }
  657. if (currentUnpackr.freezeData)
  658. return Object.freeze(array)
  659. return array
  660. }
  661. function readMap(length) {
  662. if (currentUnpackr.mapsAsObjects) {
  663. let object = {};
  664. for (let i = 0; i < length; i++) {
  665. let key = readKey();
  666. if (key === '__proto__')
  667. key = '__proto_';
  668. object[key] = read();
  669. }
  670. return object
  671. } else {
  672. let map = new Map();
  673. for (let i = 0; i < length; i++) {
  674. map.set(read(), read());
  675. }
  676. return map
  677. }
  678. }
  679. var fromCharCode = String.fromCharCode;
  680. function longStringInJS(length) {
  681. let start = position$1;
  682. let bytes = new Array(length);
  683. for (let i = 0; i < length; i++) {
  684. const byte = src[position$1++];
  685. if ((byte & 0x80) > 0) {
  686. position$1 = start;
  687. return
  688. }
  689. bytes[i] = byte;
  690. }
  691. return fromCharCode.apply(String, bytes)
  692. }
  693. function shortStringInJS(length) {
  694. if (length < 4) {
  695. if (length < 2) {
  696. if (length === 0)
  697. return ''
  698. else {
  699. let a = src[position$1++];
  700. if ((a & 0x80) > 1) {
  701. position$1 -= 1;
  702. return
  703. }
  704. return fromCharCode(a)
  705. }
  706. } else {
  707. let a = src[position$1++];
  708. let b = src[position$1++];
  709. if ((a & 0x80) > 0 || (b & 0x80) > 0) {
  710. position$1 -= 2;
  711. return
  712. }
  713. if (length < 3)
  714. return fromCharCode(a, b)
  715. let c = src[position$1++];
  716. if ((c & 0x80) > 0) {
  717. position$1 -= 3;
  718. return
  719. }
  720. return fromCharCode(a, b, c)
  721. }
  722. } else {
  723. let a = src[position$1++];
  724. let b = src[position$1++];
  725. let c = src[position$1++];
  726. let d = src[position$1++];
  727. if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
  728. position$1 -= 4;
  729. return
  730. }
  731. if (length < 6) {
  732. if (length === 4)
  733. return fromCharCode(a, b, c, d)
  734. else {
  735. let e = src[position$1++];
  736. if ((e & 0x80) > 0) {
  737. position$1 -= 5;
  738. return
  739. }
  740. return fromCharCode(a, b, c, d, e)
  741. }
  742. } else if (length < 8) {
  743. let e = src[position$1++];
  744. let f = src[position$1++];
  745. if ((e & 0x80) > 0 || (f & 0x80) > 0) {
  746. position$1 -= 6;
  747. return
  748. }
  749. if (length < 7)
  750. return fromCharCode(a, b, c, d, e, f)
  751. let g = src[position$1++];
  752. if ((g & 0x80) > 0) {
  753. position$1 -= 7;
  754. return
  755. }
  756. return fromCharCode(a, b, c, d, e, f, g)
  757. } else {
  758. let e = src[position$1++];
  759. let f = src[position$1++];
  760. let g = src[position$1++];
  761. let h = src[position$1++];
  762. if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
  763. position$1 -= 8;
  764. return
  765. }
  766. if (length < 10) {
  767. if (length === 8)
  768. return fromCharCode(a, b, c, d, e, f, g, h)
  769. else {
  770. let i = src[position$1++];
  771. if ((i & 0x80) > 0) {
  772. position$1 -= 9;
  773. return
  774. }
  775. return fromCharCode(a, b, c, d, e, f, g, h, i)
  776. }
  777. } else if (length < 12) {
  778. let i = src[position$1++];
  779. let j = src[position$1++];
  780. if ((i & 0x80) > 0 || (j & 0x80) > 0) {
  781. position$1 -= 10;
  782. return
  783. }
  784. if (length < 11)
  785. return fromCharCode(a, b, c, d, e, f, g, h, i, j)
  786. let k = src[position$1++];
  787. if ((k & 0x80) > 0) {
  788. position$1 -= 11;
  789. return
  790. }
  791. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
  792. } else {
  793. let i = src[position$1++];
  794. let j = src[position$1++];
  795. let k = src[position$1++];
  796. let l = src[position$1++];
  797. if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
  798. position$1 -= 12;
  799. return
  800. }
  801. if (length < 14) {
  802. if (length === 12)
  803. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
  804. else {
  805. let m = src[position$1++];
  806. if ((m & 0x80) > 0) {
  807. position$1 -= 13;
  808. return
  809. }
  810. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
  811. }
  812. } else {
  813. let m = src[position$1++];
  814. let n = src[position$1++];
  815. if ((m & 0x80) > 0 || (n & 0x80) > 0) {
  816. position$1 -= 14;
  817. return
  818. }
  819. if (length < 15)
  820. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
  821. let o = src[position$1++];
  822. if ((o & 0x80) > 0) {
  823. position$1 -= 15;
  824. return
  825. }
  826. return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
  827. }
  828. }
  829. }
  830. }
  831. }
  832. function readOnlyJSString() {
  833. let token = src[position$1++];
  834. let length;
  835. if (token < 0xc0) {
  836. // fixstr
  837. length = token - 0xa0;
  838. } else {
  839. switch(token) {
  840. case 0xd9:
  841. // str 8
  842. length = src[position$1++];
  843. break
  844. case 0xda:
  845. // str 16
  846. length = dataView.getUint16(position$1);
  847. position$1 += 2;
  848. break
  849. case 0xdb:
  850. // str 32
  851. length = dataView.getUint32(position$1);
  852. position$1 += 4;
  853. break
  854. default:
  855. throw new Error('Expected string')
  856. }
  857. }
  858. return readStringJS(length)
  859. }
  860. function readBin(length) {
  861. return currentUnpackr.copyBuffers ?
  862. // specifically use the copying slice (not the node one)
  863. Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
  864. src.subarray(position$1, position$1 += length)
  865. }
  866. function readExt(length) {
  867. let type = src[position$1++];
  868. if (currentExtensions[type]) {
  869. let end;
  870. return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
  871. position$1 = readPosition;
  872. try {
  873. return read();
  874. } finally {
  875. position$1 = end;
  876. }
  877. })
  878. }
  879. else
  880. throw new Error('Unknown extension type ' + type)
  881. }
  882. var keyCache = new Array(4096);
  883. function readKey() {
  884. let length = src[position$1++];
  885. if (length >= 0xa0 && length < 0xc0) {
  886. // fixstr, potentially use key cache
  887. length = length - 0xa0;
  888. if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
  889. return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
  890. else if (!(srcStringEnd == 0 && srcEnd < 180))
  891. return readFixedString(length)
  892. } else { // not cacheable, go back and do a standard read
  893. position$1--;
  894. return asSafeString(read())
  895. }
  896. let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
  897. let entry = keyCache[key];
  898. let checkPosition = position$1;
  899. let end = position$1 + length - 3;
  900. let chunk;
  901. let i = 0;
  902. if (entry && entry.bytes == length) {
  903. while (checkPosition < end) {
  904. chunk = dataView.getUint32(checkPosition);
  905. if (chunk != entry[i++]) {
  906. checkPosition = 0x70000000;
  907. break
  908. }
  909. checkPosition += 4;
  910. }
  911. end += 3;
  912. while (checkPosition < end) {
  913. chunk = src[checkPosition++];
  914. if (chunk != entry[i++]) {
  915. checkPosition = 0x70000000;
  916. break
  917. }
  918. }
  919. if (checkPosition === end) {
  920. position$1 = checkPosition;
  921. return entry.string
  922. }
  923. end -= 3;
  924. checkPosition = position$1;
  925. }
  926. entry = [];
  927. keyCache[key] = entry;
  928. entry.bytes = length;
  929. while (checkPosition < end) {
  930. chunk = dataView.getUint32(checkPosition);
  931. entry.push(chunk);
  932. checkPosition += 4;
  933. }
  934. end += 3;
  935. while (checkPosition < end) {
  936. chunk = src[checkPosition++];
  937. entry.push(chunk);
  938. }
  939. // for small blocks, avoiding the overhead of the extract call is helpful
  940. let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
  941. if (string != null)
  942. return entry.string = string
  943. return entry.string = readFixedString(length)
  944. }
  945. function asSafeString(property) {
  946. // protect against expensive (DoS) string conversions
  947. if (typeof property === 'string') return property;
  948. if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
  949. if (property == null) return property + '';
  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. // decode bigint
  976. let length = data.length;
  977. let value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  978. for (let i = 1; i < length; i++) {
  979. value <<= BigInt(8);
  980. value += BigInt(data[i]);
  981. }
  982. return value;
  983. };
  984. let errors = { Error, TypeError, ReferenceError };
  985. currentExtensions[0x65] = () => {
  986. let data = read();
  987. return (errors[data[0]] || Error)(data[1], { cause: data[2] })
  988. };
  989. currentExtensions[0x69] = (data) => {
  990. // id extension (for structured clones)
  991. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  992. let id = dataView.getUint32(position$1 - 4);
  993. if (!referenceMap)
  994. referenceMap = new Map();
  995. let token = src[position$1];
  996. let target;
  997. // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
  998. // ahead past references to record structure definitions
  999. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  1000. target = [];
  1001. else
  1002. target = {};
  1003. let refEntry = { target }; // a placeholder object
  1004. referenceMap.set(id, refEntry);
  1005. let targetProperties = read(); // read the next value as the target object to id
  1006. if (refEntry.used) // there is a cycle, so we have to assign properties to original target
  1007. return Object.assign(target, targetProperties)
  1008. refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
  1009. return targetProperties // no cycle, can just use the returned read object
  1010. };
  1011. currentExtensions[0x70] = (data) => {
  1012. // pointer extension (for structured clones)
  1013. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1014. let id = dataView.getUint32(position$1 - 4);
  1015. let refEntry = referenceMap.get(id);
  1016. refEntry.used = true;
  1017. return refEntry.target
  1018. };
  1019. currentExtensions[0x73] = () => new Set(read());
  1020. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1021. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1022. currentExtensions[0x74] = (data) => {
  1023. let typeCode = data[0];
  1024. let typedArrayName = typedArrays[typeCode];
  1025. if (!typedArrayName) {
  1026. if (typeCode === 16) {
  1027. let ab = new ArrayBuffer(data.length - 1);
  1028. let u8 = new Uint8Array(ab);
  1029. u8.set(data.subarray(1));
  1030. return ab;
  1031. }
  1032. throw new Error('Could not find typed array for code ' + typeCode)
  1033. }
  1034. // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
  1035. return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
  1036. };
  1037. currentExtensions[0x78] = () => {
  1038. let data = read();
  1039. return new RegExp(data[0], data[1])
  1040. };
  1041. const TEMP_BUNDLE = [];
  1042. currentExtensions[0x62] = (data) => {
  1043. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1044. let dataPosition = position$1;
  1045. position$1 += dataSize - data.length;
  1046. bundledStrings$1 = TEMP_BUNDLE;
  1047. bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
  1048. bundledStrings$1.position0 = 0;
  1049. bundledStrings$1.position1 = 0;
  1050. bundledStrings$1.postBundlePosition = position$1;
  1051. position$1 = dataPosition;
  1052. return read()
  1053. };
  1054. currentExtensions[0xff] = (data) => {
  1055. // 32-bit date extension
  1056. if (data.length == 4)
  1057. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1058. else if (data.length == 8)
  1059. return new Date(
  1060. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1061. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1062. else if (data.length == 12)// TODO: Implement support for negative
  1063. return new Date(
  1064. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1065. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1066. else
  1067. return new Date('invalid')
  1068. }; // notepack defines extension 0 to mean undefined, so use that as the default here
  1069. // registration of bulk record definition?
  1070. // currentExtensions[0x52] = () =>
  1071. function saveState$1(callback) {
  1072. if (onSaveState)
  1073. onSaveState();
  1074. let savedSrcEnd = srcEnd;
  1075. let savedPosition = position$1;
  1076. let savedStringPosition = stringPosition;
  1077. let savedSrcStringStart = srcStringStart;
  1078. let savedSrcStringEnd = srcStringEnd;
  1079. let savedSrcString = srcString;
  1080. let savedStrings = strings;
  1081. let savedReferenceMap = referenceMap;
  1082. let savedBundledStrings = bundledStrings$1;
  1083. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1084. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1085. let savedStructures = currentStructures;
  1086. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1087. let savedPackr = currentUnpackr;
  1088. let savedSequentialMode = sequentialMode;
  1089. let value = callback();
  1090. srcEnd = savedSrcEnd;
  1091. position$1 = savedPosition;
  1092. stringPosition = savedStringPosition;
  1093. srcStringStart = savedSrcStringStart;
  1094. srcStringEnd = savedSrcStringEnd;
  1095. srcString = savedSrcString;
  1096. strings = savedStrings;
  1097. referenceMap = savedReferenceMap;
  1098. bundledStrings$1 = savedBundledStrings;
  1099. src = savedSrc;
  1100. sequentialMode = savedSequentialMode;
  1101. currentStructures = savedStructures;
  1102. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1103. currentUnpackr = savedPackr;
  1104. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1105. return value
  1106. }
  1107. function clearSource() {
  1108. src = null;
  1109. referenceMap = null;
  1110. currentStructures = null;
  1111. }
  1112. function addExtension$1(extension) {
  1113. if (extension.unpack)
  1114. currentExtensions[extension.type] = extension.unpack;
  1115. else
  1116. currentExtensions[extension.type] = extension;
  1117. }
  1118. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1119. for (let i = 0; i < 256; i++) {
  1120. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1121. }
  1122. const Decoder = Unpackr;
  1123. var defaultUnpackr = new Unpackr({ useRecords: false });
  1124. const unpack = defaultUnpackr.unpack;
  1125. const unpackMultiple = defaultUnpackr.unpackMultiple;
  1126. const decode = defaultUnpackr.unpack;
  1127. const FLOAT32_OPTIONS = {
  1128. NEVER: 0,
  1129. ALWAYS: 1,
  1130. DECIMAL_ROUND: 3,
  1131. DECIMAL_FIT: 4
  1132. };
  1133. let f32Array = new Float32Array(1);
  1134. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1135. function roundFloat32(float32Number) {
  1136. f32Array[0] = float32Number;
  1137. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1138. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1139. }
  1140. function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
  1141. readStruct$1 = updatedReadStruct;
  1142. onLoadedStructures$1 = loadedStructs;
  1143. onSaveState = saveState;
  1144. }
  1145. let textEncoder$1;
  1146. try {
  1147. textEncoder$1 = new TextEncoder();
  1148. } catch (error) {}
  1149. let extensions, extensionClasses;
  1150. const hasNodeBuffer$1 = typeof Buffer !== 'undefined';
  1151. const ByteArrayAllocate = hasNodeBuffer$1 ?
  1152. function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
  1153. const ByteArray = hasNodeBuffer$1 ? Buffer : Uint8Array;
  1154. const MAX_BUFFER_SIZE = hasNodeBuffer$1 ? 0x100000000 : 0x7fd00000;
  1155. let target, keysTarget;
  1156. let targetView;
  1157. let position = 0;
  1158. let safeEnd;
  1159. let bundledStrings = null;
  1160. let writeStructSlots;
  1161. const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
  1162. const hasNonLatin = /[\u0080-\uFFFF]/;
  1163. const RECORD_SYMBOL = Symbol('record-id');
  1164. class Packr extends Unpackr {
  1165. constructor(options) {
  1166. super(options);
  1167. this.offset = 0;
  1168. let start;
  1169. let hasSharedUpdate;
  1170. let structures;
  1171. let referenceMap;
  1172. let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
  1173. return target.utf8Write(string, position, target.byteLength - position)
  1174. } : (textEncoder$1 && textEncoder$1.encodeInto) ?
  1175. function(string, position) {
  1176. return textEncoder$1.encodeInto(string, target.subarray(position)).written
  1177. } : false;
  1178. let packr = this;
  1179. if (!options)
  1180. options = {};
  1181. let isSequential = options && options.sequential;
  1182. let hasSharedStructures = options.structures || options.saveStructures;
  1183. let maxSharedStructures = options.maxSharedStructures;
  1184. if (maxSharedStructures == null)
  1185. maxSharedStructures = hasSharedStructures ? 32 : 0;
  1186. if (maxSharedStructures > 8160)
  1187. throw new Error('Maximum maxSharedStructure is 8160')
  1188. if (options.structuredClone && options.moreTypes == undefined) {
  1189. this.moreTypes = true;
  1190. }
  1191. let maxOwnStructures = options.maxOwnStructures;
  1192. if (maxOwnStructures == null)
  1193. maxOwnStructures = hasSharedStructures ? 32 : 64;
  1194. if (!this.structures && options.useRecords != false)
  1195. this.structures = [];
  1196. // two byte record ids for shared structures
  1197. let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
  1198. let sharedLimitId = maxSharedStructures + 0x40;
  1199. let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
  1200. if (maxStructureId > 8256) {
  1201. throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
  1202. }
  1203. let recordIdsToRemove = [];
  1204. let transitionsCount = 0;
  1205. let serializationsSinceTransitionRebuild = 0;
  1206. this.pack = this.encode = function(value, encodeOptions) {
  1207. if (!target) {
  1208. target = new ByteArrayAllocate(8192);
  1209. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
  1210. position = 0;
  1211. }
  1212. safeEnd = target.length - 10;
  1213. if (safeEnd - position < 0x800) {
  1214. // don't start too close to the end,
  1215. target = new ByteArrayAllocate(target.length);
  1216. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
  1217. safeEnd = target.length - 10;
  1218. position = 0;
  1219. } else
  1220. position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
  1221. start = position;
  1222. if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
  1223. referenceMap = packr.structuredClone ? new Map() : null;
  1224. if (packr.bundleStrings && typeof value !== 'string') {
  1225. bundledStrings = [];
  1226. bundledStrings.size = Infinity; // force a new bundle start on first string
  1227. } else
  1228. bundledStrings = null;
  1229. structures = packr.structures;
  1230. if (structures) {
  1231. if (structures.uninitialized)
  1232. structures = packr._mergeStructures(packr.getStructures());
  1233. let sharedLength = structures.sharedLength || 0;
  1234. if (sharedLength > maxSharedStructures) {
  1235. //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
  1236. throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
  1237. }
  1238. if (!structures.transitions) {
  1239. // rebuild our structure transitions
  1240. structures.transitions = Object.create(null);
  1241. for (let i = 0; i < sharedLength; i++) {
  1242. let keys = structures[i];
  1243. if (!keys)
  1244. continue
  1245. let nextTransition, transition = structures.transitions;
  1246. for (let j = 0, l = keys.length; j < l; j++) {
  1247. let key = keys[j];
  1248. nextTransition = transition[key];
  1249. if (!nextTransition) {
  1250. nextTransition = transition[key] = Object.create(null);
  1251. }
  1252. transition = nextTransition;
  1253. }
  1254. transition[RECORD_SYMBOL] = i + 0x40;
  1255. }
  1256. this.lastNamedStructuresLength = sharedLength;
  1257. }
  1258. if (!isSequential) {
  1259. structures.nextId = sharedLength + 0x40;
  1260. }
  1261. }
  1262. if (hasSharedUpdate)
  1263. hasSharedUpdate = false;
  1264. let encodingError;
  1265. try {
  1266. if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
  1267. writeStruct(value);
  1268. else
  1269. pack(value);
  1270. let lastBundle = bundledStrings;
  1271. if (bundledStrings)
  1272. writeBundles(start, pack, 0);
  1273. if (referenceMap && referenceMap.idsToInsert) {
  1274. let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  1275. let i = idsToInsert.length;
  1276. let incrementPosition = -1;
  1277. while (lastBundle && i > 0) {
  1278. let insertionPoint = idsToInsert[--i].offset + start;
  1279. if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
  1280. incrementPosition = 0;
  1281. if (insertionPoint > (lastBundle.position + start)) {
  1282. if (incrementPosition >= 0)
  1283. incrementPosition += 6;
  1284. } else {
  1285. if (incrementPosition >= 0) {
  1286. // update the bundle reference now
  1287. targetView.setUint32(lastBundle.position + start,
  1288. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1289. incrementPosition = -1; // reset
  1290. }
  1291. lastBundle = lastBundle.previous;
  1292. i++;
  1293. }
  1294. }
  1295. if (incrementPosition >= 0 && lastBundle) {
  1296. // update the bundle reference now
  1297. targetView.setUint32(lastBundle.position + start,
  1298. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1299. }
  1300. position += idsToInsert.length * 6;
  1301. if (position > safeEnd)
  1302. makeRoom(position);
  1303. packr.offset = position;
  1304. let serialized = insertIds(target.subarray(start, position), idsToInsert);
  1305. referenceMap = null;
  1306. return serialized
  1307. }
  1308. packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
  1309. if (encodeOptions & REUSE_BUFFER_MODE) {
  1310. target.start = start;
  1311. target.end = position;
  1312. return target
  1313. }
  1314. return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
  1315. } catch(error) {
  1316. encodingError = error;
  1317. throw error;
  1318. } finally {
  1319. if (structures) {
  1320. resetStructures();
  1321. if (hasSharedUpdate && packr.saveStructures) {
  1322. let sharedLength = structures.sharedLength || 0;
  1323. // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
  1324. let returnBuffer = target.subarray(start, position);
  1325. let newSharedData = prepareStructures$1(structures, packr);
  1326. if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
  1327. if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
  1328. // get updated structures and try again if the update failed
  1329. return packr.pack(value, encodeOptions)
  1330. }
  1331. packr.lastNamedStructuresLength = sharedLength;
  1332. // don't keep large buffers around
  1333. if (target.length > 0x40000000) target = null;
  1334. return returnBuffer
  1335. }
  1336. }
  1337. }
  1338. // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
  1339. if (target.length > 0x40000000) target = null;
  1340. if (encodeOptions & RESET_BUFFER_MODE)
  1341. position = start;
  1342. }
  1343. };
  1344. const resetStructures = () => {
  1345. if (serializationsSinceTransitionRebuild < 10)
  1346. serializationsSinceTransitionRebuild++;
  1347. let sharedLength = structures.sharedLength || 0;
  1348. if (structures.length > sharedLength && !isSequential)
  1349. structures.length = sharedLength;
  1350. if (transitionsCount > 10000) {
  1351. // force a rebuild occasionally after a lot of transitions so it can get cleaned up
  1352. structures.transitions = null;
  1353. serializationsSinceTransitionRebuild = 0;
  1354. transitionsCount = 0;
  1355. if (recordIdsToRemove.length > 0)
  1356. recordIdsToRemove = [];
  1357. } else if (recordIdsToRemove.length > 0 && !isSequential) {
  1358. for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
  1359. recordIdsToRemove[i][RECORD_SYMBOL] = 0;
  1360. }
  1361. recordIdsToRemove = [];
  1362. }
  1363. };
  1364. const packArray = (value) => {
  1365. var length = value.length;
  1366. if (length < 0x10) {
  1367. target[position++] = 0x90 | length;
  1368. } else if (length < 0x10000) {
  1369. target[position++] = 0xdc;
  1370. target[position++] = length >> 8;
  1371. target[position++] = length & 0xff;
  1372. } else {
  1373. target[position++] = 0xdd;
  1374. targetView.setUint32(position, length);
  1375. position += 4;
  1376. }
  1377. for (let i = 0; i < length; i++) {
  1378. pack(value[i]);
  1379. }
  1380. };
  1381. const pack = (value) => {
  1382. if (position > safeEnd)
  1383. target = makeRoom(position);
  1384. var type = typeof value;
  1385. var length;
  1386. if (type === 'string') {
  1387. let strLength = value.length;
  1388. if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
  1389. if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
  1390. let extStart;
  1391. let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
  1392. if (position + maxBytes > safeEnd)
  1393. target = makeRoom(position + maxBytes);
  1394. let lastBundle;
  1395. 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
  1396. lastBundle = bundledStrings;
  1397. target[position] = 0xc8; // ext 16
  1398. position += 3; // reserve for the writing bundle size
  1399. target[position++] = 0x62; // 'b'
  1400. extStart = position - start;
  1401. position += 4; // reserve for writing bundle reference
  1402. writeBundles(start, pack, 0); // write the last bundles
  1403. targetView.setUint16(extStart + start - 3, position - start - extStart);
  1404. } 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)
  1405. target[position++] = 0xd6; // fixext 4
  1406. target[position++] = 0x62; // 'b'
  1407. extStart = position - start;
  1408. position += 4; // reserve for writing bundle reference
  1409. }
  1410. bundledStrings = ['', '']; // create new ones
  1411. bundledStrings.previous = lastBundle;
  1412. bundledStrings.size = 0;
  1413. bundledStrings.position = extStart;
  1414. }
  1415. let twoByte = hasNonLatin.test(value);
  1416. bundledStrings[twoByte ? 0 : 1] += value;
  1417. target[position++] = 0xc1;
  1418. pack(twoByte ? -strLength : strLength);
  1419. return
  1420. }
  1421. let headerSize;
  1422. // first we estimate the header size, so we can write to the correct location
  1423. if (strLength < 0x20) {
  1424. headerSize = 1;
  1425. } else if (strLength < 0x100) {
  1426. headerSize = 2;
  1427. } else if (strLength < 0x10000) {
  1428. headerSize = 3;
  1429. } else {
  1430. headerSize = 5;
  1431. }
  1432. let maxBytes = strLength * 3;
  1433. if (position + maxBytes > safeEnd)
  1434. target = makeRoom(position + maxBytes);
  1435. if (strLength < 0x40 || !encodeUtf8) {
  1436. let i, c1, c2, strPosition = position + headerSize;
  1437. for (i = 0; i < strLength; i++) {
  1438. c1 = value.charCodeAt(i);
  1439. if (c1 < 0x80) {
  1440. target[strPosition++] = c1;
  1441. } else if (c1 < 0x800) {
  1442. target[strPosition++] = c1 >> 6 | 0xc0;
  1443. target[strPosition++] = c1 & 0x3f | 0x80;
  1444. } else if (
  1445. (c1 & 0xfc00) === 0xd800 &&
  1446. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  1447. ) {
  1448. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  1449. i++;
  1450. target[strPosition++] = c1 >> 18 | 0xf0;
  1451. target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
  1452. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1453. target[strPosition++] = c1 & 0x3f | 0x80;
  1454. } else {
  1455. target[strPosition++] = c1 >> 12 | 0xe0;
  1456. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1457. target[strPosition++] = c1 & 0x3f | 0x80;
  1458. }
  1459. }
  1460. length = strPosition - position - headerSize;
  1461. } else {
  1462. length = encodeUtf8(value, position + headerSize);
  1463. }
  1464. if (length < 0x20) {
  1465. target[position++] = 0xa0 | length;
  1466. } else if (length < 0x100) {
  1467. if (headerSize < 2) {
  1468. target.copyWithin(position + 2, position + 1, position + 1 + length);
  1469. }
  1470. target[position++] = 0xd9;
  1471. target[position++] = length;
  1472. } else if (length < 0x10000) {
  1473. if (headerSize < 3) {
  1474. target.copyWithin(position + 3, position + 2, position + 2 + length);
  1475. }
  1476. target[position++] = 0xda;
  1477. target[position++] = length >> 8;
  1478. target[position++] = length & 0xff;
  1479. } else {
  1480. if (headerSize < 5) {
  1481. target.copyWithin(position + 5, position + 3, position + 3 + length);
  1482. }
  1483. target[position++] = 0xdb;
  1484. targetView.setUint32(position, length);
  1485. position += 4;
  1486. }
  1487. position += length;
  1488. } else if (type === 'number') {
  1489. if (value >>> 0 === value) {// positive integer, 32-bit or less
  1490. // positive uint
  1491. if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
  1492. target[position++] = value;
  1493. } else if (value < 0x100) {
  1494. target[position++] = 0xcc;
  1495. target[position++] = value;
  1496. } else if (value < 0x10000) {
  1497. target[position++] = 0xcd;
  1498. target[position++] = value >> 8;
  1499. target[position++] = value & 0xff;
  1500. } else {
  1501. target[position++] = 0xce;
  1502. targetView.setUint32(position, value);
  1503. position += 4;
  1504. }
  1505. } else if (value >> 0 === value) { // negative integer
  1506. if (value >= -0x20) {
  1507. target[position++] = 0x100 + value;
  1508. } else if (value >= -0x80) {
  1509. target[position++] = 0xd0;
  1510. target[position++] = value + 0x100;
  1511. } else if (value >= -0x8000) {
  1512. target[position++] = 0xd1;
  1513. targetView.setInt16(position, value);
  1514. position += 2;
  1515. } else {
  1516. target[position++] = 0xd2;
  1517. targetView.setInt32(position, value);
  1518. position += 4;
  1519. }
  1520. } else {
  1521. let useFloat32;
  1522. if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
  1523. target[position++] = 0xca;
  1524. targetView.setFloat32(position, value);
  1525. let xShifted;
  1526. if (useFloat32 < 4 ||
  1527. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  1528. ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
  1529. position += 4;
  1530. return
  1531. } else
  1532. position--; // move back into position for writing a double
  1533. }
  1534. target[position++] = 0xcb;
  1535. targetView.setFloat64(position, value);
  1536. position += 8;
  1537. }
  1538. } else if (type === 'object' || type === 'function') {
  1539. if (!value)
  1540. target[position++] = 0xc0;
  1541. else {
  1542. if (referenceMap) {
  1543. let referee = referenceMap.get(value);
  1544. if (referee) {
  1545. if (!referee.id) {
  1546. let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
  1547. referee.id = idsToInsert.push(referee);
  1548. }
  1549. target[position++] = 0xd6; // fixext 4
  1550. target[position++] = 0x70; // "p" for pointer
  1551. targetView.setUint32(position, referee.id);
  1552. position += 4;
  1553. return
  1554. } else
  1555. referenceMap.set(value, { offset: position - start });
  1556. }
  1557. let constructor = value.constructor;
  1558. if (constructor === Object) {
  1559. writeObject(value);
  1560. } else if (constructor === Array) {
  1561. packArray(value);
  1562. } else if (constructor === Map) {
  1563. if (this.mapAsEmptyObject) target[position++] = 0x80;
  1564. else {
  1565. length = value.size;
  1566. if (length < 0x10) {
  1567. target[position++] = 0x80 | length;
  1568. } else if (length < 0x10000) {
  1569. target[position++] = 0xde;
  1570. target[position++] = length >> 8;
  1571. target[position++] = length & 0xff;
  1572. } else {
  1573. target[position++] = 0xdf;
  1574. targetView.setUint32(position, length);
  1575. position += 4;
  1576. }
  1577. for (let [key, entryValue] of value) {
  1578. pack(key);
  1579. pack(entryValue);
  1580. }
  1581. }
  1582. } else {
  1583. for (let i = 0, l = extensions.length; i < l; i++) {
  1584. let extensionClass = extensionClasses[i];
  1585. if (value instanceof extensionClass) {
  1586. let extension = extensions[i];
  1587. if (extension.write) {
  1588. if (extension.type) {
  1589. target[position++] = 0xd4; // one byte "tag" extension
  1590. target[position++] = extension.type;
  1591. target[position++] = 0;
  1592. }
  1593. let writeResult = extension.write.call(this, value);
  1594. if (writeResult === value) { // avoid infinite recursion
  1595. if (Array.isArray(value)) {
  1596. packArray(value);
  1597. } else {
  1598. writeObject(value);
  1599. }
  1600. } else {
  1601. pack(writeResult);
  1602. }
  1603. return
  1604. }
  1605. let currentTarget = target;
  1606. let currentTargetView = targetView;
  1607. let currentPosition = position;
  1608. target = null;
  1609. let result;
  1610. try {
  1611. result = extension.pack.call(this, value, (size) => {
  1612. // restore target and use it
  1613. target = currentTarget;
  1614. currentTarget = null;
  1615. position += size;
  1616. if (position > safeEnd)
  1617. makeRoom(position);
  1618. return {
  1619. target, targetView, position: position - size
  1620. }
  1621. }, pack);
  1622. } finally {
  1623. // restore current target information (unless already restored)
  1624. if (currentTarget) {
  1625. target = currentTarget;
  1626. targetView = currentTargetView;
  1627. position = currentPosition;
  1628. safeEnd = target.length - 10;
  1629. }
  1630. }
  1631. if (result) {
  1632. if (result.length + position > safeEnd)
  1633. makeRoom(result.length + position);
  1634. position = writeExtensionData(result, target, position, extension.type);
  1635. }
  1636. return
  1637. }
  1638. }
  1639. // check isArray after extensions, because extensions can extend Array
  1640. if (Array.isArray(value)) {
  1641. packArray(value);
  1642. } else {
  1643. // use this as an alternate mechanism for expressing how to serialize
  1644. if (value.toJSON) {
  1645. const json = value.toJSON();
  1646. // if for some reason value.toJSON returns itself it'll loop forever
  1647. if (json !== value)
  1648. return pack(json)
  1649. }
  1650. // if there is a writeFunction, use it, otherwise just encode as undefined
  1651. if (type === 'function')
  1652. return pack(this.writeFunction && this.writeFunction(value));
  1653. // no extension found, write as plain object
  1654. writeObject(value);
  1655. }
  1656. }
  1657. }
  1658. } else if (type === 'boolean') {
  1659. target[position++] = value ? 0xc3 : 0xc2;
  1660. } else if (type === 'bigint') {
  1661. if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
  1662. // use a signed int as long as it fits
  1663. target[position++] = 0xd3;
  1664. targetView.setBigInt64(position, value);
  1665. } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
  1666. // if we can fit an unsigned int, use that
  1667. target[position++] = 0xcf;
  1668. targetView.setBigUint64(position, value);
  1669. } else {
  1670. // overflow
  1671. if (this.largeBigIntToFloat) {
  1672. target[position++] = 0xcb;
  1673. targetView.setFloat64(position, Number(value));
  1674. } else if (this.largeBigIntToString) {
  1675. return pack(value.toString());
  1676. } else if (this.useBigIntExtension && value < BigInt(2)**BigInt(1023) && value > -(BigInt(2)**BigInt(1023))) {
  1677. target[position++] = 0xc7;
  1678. position++;
  1679. target[position++] = 0x42; // "B" for BigInt
  1680. let bytes = [];
  1681. let alignedSign;
  1682. do {
  1683. let byte = value & BigInt(0xff);
  1684. alignedSign = (byte & BigInt(0x80)) === (value < BigInt(0) ? BigInt(0x80) : BigInt(0));
  1685. bytes.push(byte);
  1686. value >>= BigInt(8);
  1687. } while (!((value === BigInt(0) || value === BigInt(-1)) && alignedSign));
  1688. target[position-2] = bytes.length;
  1689. for (let i = bytes.length; i > 0;) {
  1690. target[position++] = Number(bytes[--i]);
  1691. }
  1692. return
  1693. } else {
  1694. throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
  1695. ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +
  1696. ' largeBigIntToString to convert to string')
  1697. }
  1698. }
  1699. position += 8;
  1700. } else if (type === 'undefined') {
  1701. if (this.encodeUndefinedAsNil)
  1702. target[position++] = 0xc0;
  1703. else {
  1704. target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
  1705. target[position++] = 0;
  1706. target[position++] = 0;
  1707. }
  1708. } else {
  1709. throw new Error('Unknown type: ' + type)
  1710. }
  1711. };
  1712. const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {
  1713. // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
  1714. let keys;
  1715. if (this.skipValues) {
  1716. keys = [];
  1717. for (let key in object) {
  1718. if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&
  1719. !this.skipValues.includes(object[key]))
  1720. keys.push(key);
  1721. }
  1722. } else {
  1723. keys = Object.keys(object);
  1724. }
  1725. let length = keys.length;
  1726. if (length < 0x10) {
  1727. target[position++] = 0x80 | length;
  1728. } else if (length < 0x10000) {
  1729. target[position++] = 0xde;
  1730. target[position++] = length >> 8;
  1731. target[position++] = length & 0xff;
  1732. } else {
  1733. target[position++] = 0xdf;
  1734. targetView.setUint32(position, length);
  1735. position += 4;
  1736. }
  1737. let key;
  1738. if (this.coercibleKeyAsNumber) {
  1739. for (let i = 0; i < length; i++) {
  1740. key = keys[i];
  1741. let num = Number(key);
  1742. pack(isNaN(num) ? key : num);
  1743. pack(object[key]);
  1744. }
  1745. } else {
  1746. for (let i = 0; i < length; i++) {
  1747. pack(key = keys[i]);
  1748. pack(object[key]);
  1749. }
  1750. }
  1751. } :
  1752. (object) => {
  1753. target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
  1754. let objectOffset = position - start;
  1755. position += 2;
  1756. let size = 0;
  1757. for (let key in object) {
  1758. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1759. pack(key);
  1760. pack(object[key]);
  1761. size++;
  1762. }
  1763. }
  1764. if (size > 0xffff) {
  1765. throw new Error('Object is too large to serialize with fast 16-bit map size,' +
  1766. ' use the "variableMapSize" option to serialize this object');
  1767. }
  1768. target[objectOffset++ + start] = size >> 8;
  1769. target[objectOffset + start] = size & 0xff;
  1770. };
  1771. const writeRecord = this.useRecords === false ? writePlainObject :
  1772. (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)
  1773. (object) => {
  1774. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1775. let objectOffset = position++ - start;
  1776. let wroteKeys;
  1777. for (let key in object) {
  1778. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1779. nextTransition = transition[key];
  1780. if (nextTransition)
  1781. transition = nextTransition;
  1782. else {
  1783. // record doesn't exist, create full new record and insert it
  1784. let keys = Object.keys(object);
  1785. let lastTransition = transition;
  1786. transition = structures.transitions;
  1787. let newTransitions = 0;
  1788. for (let i = 0, l = keys.length; i < l; i++) {
  1789. let key = keys[i];
  1790. nextTransition = transition[key];
  1791. if (!nextTransition) {
  1792. nextTransition = transition[key] = Object.create(null);
  1793. newTransitions++;
  1794. }
  1795. transition = nextTransition;
  1796. }
  1797. if (objectOffset + start + 1 == position) {
  1798. // first key, so we don't need to insert, we can just write record directly
  1799. position--;
  1800. newRecord(transition, keys, newTransitions);
  1801. } else // otherwise we need to insert the record, moving existing data after the record
  1802. insertNewRecord(transition, keys, objectOffset, newTransitions);
  1803. wroteKeys = true;
  1804. transition = lastTransition[key];
  1805. }
  1806. pack(object[key]);
  1807. }
  1808. }
  1809. if (!wroteKeys) {
  1810. let recordId = transition[RECORD_SYMBOL];
  1811. if (recordId)
  1812. target[objectOffset + start] = recordId;
  1813. else
  1814. insertNewRecord(transition, Object.keys(object), objectOffset, 0);
  1815. }
  1816. } :
  1817. (object) => {
  1818. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1819. let newTransitions = 0;
  1820. for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1821. nextTransition = transition[key];
  1822. if (!nextTransition) {
  1823. nextTransition = transition[key] = Object.create(null);
  1824. newTransitions++;
  1825. }
  1826. transition = nextTransition;
  1827. }
  1828. let recordId = transition[RECORD_SYMBOL];
  1829. if (recordId) {
  1830. if (recordId >= 0x60 && useTwoByteRecords) {
  1831. target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
  1832. target[position++] = recordId >> 5;
  1833. } else
  1834. target[position++] = recordId;
  1835. } else {
  1836. newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
  1837. }
  1838. // now write the values
  1839. for (let key in object)
  1840. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1841. pack(object[key]);
  1842. }
  1843. };
  1844. // create reference to useRecords if useRecords is a function
  1845. const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
  1846. const writeObject = checkUseRecords ? (object) => {
  1847. checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
  1848. } : writeRecord;
  1849. const makeRoom = (end) => {
  1850. let newSize;
  1851. if (end > 0x1000000) {
  1852. // special handling for really large buffers
  1853. if ((end - start) > MAX_BUFFER_SIZE)
  1854. throw new Error('Packed buffer would be larger than maximum buffer size')
  1855. newSize = Math.min(MAX_BUFFER_SIZE,
  1856. Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
  1857. } else // faster handling for smaller buffers
  1858. newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
  1859. let newBuffer = new ByteArrayAllocate(newSize);
  1860. targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
  1861. end = Math.min(end, target.length);
  1862. if (target.copy)
  1863. target.copy(newBuffer, 0, start, end);
  1864. else
  1865. newBuffer.set(target.slice(start, end));
  1866. position -= start;
  1867. start = 0;
  1868. safeEnd = newBuffer.length - 10;
  1869. return target = newBuffer
  1870. };
  1871. const newRecord = (transition, keys, newTransitions) => {
  1872. let recordId = structures.nextId;
  1873. if (!recordId)
  1874. recordId = 0x40;
  1875. if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
  1876. recordId = structures.nextOwnId;
  1877. if (!(recordId < maxStructureId))
  1878. recordId = sharedLimitId;
  1879. structures.nextOwnId = recordId + 1;
  1880. } else {
  1881. if (recordId >= maxStructureId)// cycle back around
  1882. recordId = sharedLimitId;
  1883. structures.nextId = recordId + 1;
  1884. }
  1885. let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
  1886. transition[RECORD_SYMBOL] = recordId;
  1887. transition.__keys__ = keys;
  1888. structures[recordId - 0x40] = keys;
  1889. if (recordId < sharedLimitId) {
  1890. keys.isShared = true;
  1891. structures.sharedLength = recordId - 0x3f;
  1892. hasSharedUpdate = true;
  1893. if (highByte >= 0) {
  1894. target[position++] = (recordId & 0x1f) + 0x60;
  1895. target[position++] = highByte;
  1896. } else {
  1897. target[position++] = recordId;
  1898. }
  1899. } else {
  1900. if (highByte >= 0) {
  1901. target[position++] = 0xd5; // fixext 2
  1902. target[position++] = 0x72; // "r" record defintion extension type
  1903. target[position++] = (recordId & 0x1f) + 0x60;
  1904. target[position++] = highByte;
  1905. } else {
  1906. target[position++] = 0xd4; // fixext 1
  1907. target[position++] = 0x72; // "r" record defintion extension type
  1908. target[position++] = recordId;
  1909. }
  1910. if (newTransitions)
  1911. transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
  1912. // record the removal of the id, we can maintain our shared structure
  1913. if (recordIdsToRemove.length >= maxOwnStructures)
  1914. recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
  1915. recordIdsToRemove.push(transition);
  1916. pack(keys);
  1917. }
  1918. };
  1919. const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
  1920. let mainTarget = target;
  1921. let mainPosition = position;
  1922. let mainSafeEnd = safeEnd;
  1923. let mainStart = start;
  1924. target = keysTarget;
  1925. position = 0;
  1926. start = 0;
  1927. if (!target)
  1928. keysTarget = target = new ByteArrayAllocate(8192);
  1929. safeEnd = target.length - 10;
  1930. newRecord(transition, keys, newTransitions);
  1931. keysTarget = target;
  1932. let keysPosition = position;
  1933. target = mainTarget;
  1934. position = mainPosition;
  1935. safeEnd = mainSafeEnd;
  1936. start = mainStart;
  1937. if (keysPosition > 1) {
  1938. let newEnd = position + keysPosition - 1;
  1939. if (newEnd > safeEnd)
  1940. makeRoom(newEnd);
  1941. let insertionPosition = insertionOffset + start;
  1942. target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
  1943. target.set(keysTarget.slice(0, keysPosition), insertionPosition);
  1944. position = newEnd;
  1945. } else {
  1946. target[insertionOffset + start] = keysTarget[0];
  1947. }
  1948. };
  1949. const writeStruct = (object) => {
  1950. let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
  1951. if (notifySharedUpdate)
  1952. return hasSharedUpdate = true;
  1953. position = newPosition;
  1954. let startTarget = target;
  1955. pack(value);
  1956. resetStructures();
  1957. if (startTarget !== target) {
  1958. return { position, targetView, target }; // indicate the buffer was re-allocated
  1959. }
  1960. return position;
  1961. }, this);
  1962. if (newPosition === 0) // bail and go to a msgpack object
  1963. return writeObject(object);
  1964. position = newPosition;
  1965. };
  1966. }
  1967. useBuffer(buffer) {
  1968. // this means we are finished using our own buffer and we can write over it safely
  1969. target = buffer;
  1970. target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));
  1971. position = 0;
  1972. }
  1973. set position (value) {
  1974. position = value;
  1975. }
  1976. get position() {
  1977. return position;
  1978. }
  1979. clearSharedData() {
  1980. if (this.structures)
  1981. this.structures = [];
  1982. if (this.typedStructs)
  1983. this.typedStructs = [];
  1984. }
  1985. }
  1986. extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
  1987. extensions = [{
  1988. pack(date, allocateForWrite, pack) {
  1989. let seconds = date.getTime() / 1000;
  1990. if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
  1991. // Timestamp 32
  1992. let { target, targetView, position} = allocateForWrite(6);
  1993. target[position++] = 0xd6;
  1994. target[position++] = 0xff;
  1995. targetView.setUint32(position, seconds);
  1996. } else if (seconds > 0 && seconds < 0x100000000) {
  1997. // Timestamp 64
  1998. let { target, targetView, position} = allocateForWrite(10);
  1999. target[position++] = 0xd7;
  2000. target[position++] = 0xff;
  2001. targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
  2002. targetView.setUint32(position + 4, seconds);
  2003. } else if (isNaN(seconds)) {
  2004. if (this.onInvalidDate) {
  2005. allocateForWrite(0);
  2006. return pack(this.onInvalidDate())
  2007. }
  2008. // Intentionally invalid timestamp
  2009. let { target, targetView, position} = allocateForWrite(3);
  2010. target[position++] = 0xd4;
  2011. target[position++] = 0xff;
  2012. target[position++] = 0xff;
  2013. } else {
  2014. // Timestamp 96
  2015. let { target, targetView, position} = allocateForWrite(15);
  2016. target[position++] = 0xc7;
  2017. target[position++] = 12;
  2018. target[position++] = 0xff;
  2019. targetView.setUint32(position, date.getMilliseconds() * 1000000);
  2020. targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
  2021. }
  2022. }
  2023. }, {
  2024. pack(set, allocateForWrite, pack) {
  2025. if (this.setAsEmptyObject) {
  2026. allocateForWrite(0);
  2027. return pack({})
  2028. }
  2029. let array = Array.from(set);
  2030. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2031. if (this.moreTypes) {
  2032. target[position++] = 0xd4;
  2033. target[position++] = 0x73; // 's' for Set
  2034. target[position++] = 0;
  2035. }
  2036. pack(array);
  2037. }
  2038. }, {
  2039. pack(error, allocateForWrite, pack) {
  2040. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2041. if (this.moreTypes) {
  2042. target[position++] = 0xd4;
  2043. target[position++] = 0x65; // 'e' for error
  2044. target[position++] = 0;
  2045. }
  2046. pack([ error.name, error.message, error.cause ]);
  2047. }
  2048. }, {
  2049. pack(regex, allocateForWrite, pack) {
  2050. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2051. if (this.moreTypes) {
  2052. target[position++] = 0xd4;
  2053. target[position++] = 0x78; // 'x' for regeXp
  2054. target[position++] = 0;
  2055. }
  2056. pack([ regex.source, regex.flags ]);
  2057. }
  2058. }, {
  2059. pack(arrayBuffer, allocateForWrite) {
  2060. if (this.moreTypes)
  2061. writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
  2062. else
  2063. writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2064. }
  2065. }, {
  2066. pack(typedArray, allocateForWrite) {
  2067. let constructor = typedArray.constructor;
  2068. if (constructor !== ByteArray && this.moreTypes)
  2069. writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
  2070. else
  2071. writeBuffer(typedArray, allocateForWrite);
  2072. }
  2073. }, {
  2074. pack(c1, allocateForWrite) { // specific 0xC1 object
  2075. let { target, position} = allocateForWrite(1);
  2076. target[position] = 0xc1;
  2077. }
  2078. }];
  2079. function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
  2080. let length = typedArray.byteLength;
  2081. if (length + 1 < 0x100) {
  2082. var { target, position } = allocateForWrite(4 + length);
  2083. target[position++] = 0xc7;
  2084. target[position++] = length + 1;
  2085. } else if (length + 1 < 0x10000) {
  2086. var { target, position } = allocateForWrite(5 + length);
  2087. target[position++] = 0xc8;
  2088. target[position++] = (length + 1) >> 8;
  2089. target[position++] = (length + 1) & 0xff;
  2090. } else {
  2091. var { target, position, targetView } = allocateForWrite(7 + length);
  2092. target[position++] = 0xc9;
  2093. targetView.setUint32(position, length + 1); // plus one for the type byte
  2094. position += 4;
  2095. }
  2096. target[position++] = 0x74; // "t" for typed array
  2097. target[position++] = type;
  2098. if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
  2099. target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
  2100. }
  2101. function writeBuffer(buffer, allocateForWrite) {
  2102. let length = buffer.byteLength;
  2103. var target, position;
  2104. if (length < 0x100) {
  2105. var { target, position } = allocateForWrite(length + 2);
  2106. target[position++] = 0xc4;
  2107. target[position++] = length;
  2108. } else if (length < 0x10000) {
  2109. var { target, position } = allocateForWrite(length + 3);
  2110. target[position++] = 0xc5;
  2111. target[position++] = length >> 8;
  2112. target[position++] = length & 0xff;
  2113. } else {
  2114. var { target, position, targetView } = allocateForWrite(length + 5);
  2115. target[position++] = 0xc6;
  2116. targetView.setUint32(position, length);
  2117. position += 4;
  2118. }
  2119. target.set(buffer, position);
  2120. }
  2121. function writeExtensionData(result, target, position, type) {
  2122. let length = result.length;
  2123. switch (length) {
  2124. case 1:
  2125. target[position++] = 0xd4;
  2126. break
  2127. case 2:
  2128. target[position++] = 0xd5;
  2129. break
  2130. case 4:
  2131. target[position++] = 0xd6;
  2132. break
  2133. case 8:
  2134. target[position++] = 0xd7;
  2135. break
  2136. case 16:
  2137. target[position++] = 0xd8;
  2138. break
  2139. default:
  2140. if (length < 0x100) {
  2141. target[position++] = 0xc7;
  2142. target[position++] = length;
  2143. } else if (length < 0x10000) {
  2144. target[position++] = 0xc8;
  2145. target[position++] = length >> 8;
  2146. target[position++] = length & 0xff;
  2147. } else {
  2148. target[position++] = 0xc9;
  2149. target[position++] = length >> 24;
  2150. target[position++] = (length >> 16) & 0xff;
  2151. target[position++] = (length >> 8) & 0xff;
  2152. target[position++] = length & 0xff;
  2153. }
  2154. }
  2155. target[position++] = type;
  2156. target.set(result, position);
  2157. position += length;
  2158. return position
  2159. }
  2160. function insertIds(serialized, idsToInsert) {
  2161. // insert the ids that need to be referenced for structured clones
  2162. let nextId;
  2163. let distanceToMove = idsToInsert.length * 6;
  2164. let lastEnd = serialized.length - distanceToMove;
  2165. while (nextId = idsToInsert.pop()) {
  2166. let offset = nextId.offset;
  2167. let id = nextId.id;
  2168. serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
  2169. distanceToMove -= 6;
  2170. let position = offset + distanceToMove;
  2171. serialized[position++] = 0xd6;
  2172. serialized[position++] = 0x69; // 'i'
  2173. serialized[position++] = id >> 24;
  2174. serialized[position++] = (id >> 16) & 0xff;
  2175. serialized[position++] = (id >> 8) & 0xff;
  2176. serialized[position++] = id & 0xff;
  2177. lastEnd = offset;
  2178. }
  2179. return serialized
  2180. }
  2181. function writeBundles(start, pack, incrementPosition) {
  2182. if (bundledStrings.length > 0) {
  2183. targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
  2184. bundledStrings.stringsPosition = position - start;
  2185. let writeStrings = bundledStrings;
  2186. bundledStrings = null;
  2187. pack(writeStrings[0]);
  2188. pack(writeStrings[1]);
  2189. }
  2190. }
  2191. function addExtension(extension) {
  2192. if (extension.Class) {
  2193. if (!extension.pack && !extension.write)
  2194. throw new Error('Extension has no pack or write function')
  2195. if (extension.pack && !extension.type)
  2196. throw new Error('Extension has no type (numeric code to identify the extension)')
  2197. extensionClasses.unshift(extension.Class);
  2198. extensions.unshift(extension);
  2199. }
  2200. addExtension$1(extension);
  2201. }
  2202. function prepareStructures$1(structures, packr) {
  2203. structures.isCompatible = (existingStructures) => {
  2204. let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
  2205. if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
  2206. packr._mergeStructures(existingStructures);
  2207. return compatible;
  2208. };
  2209. return structures
  2210. }
  2211. function setWriteStructSlots(writeSlots, makeStructures) {
  2212. writeStructSlots = writeSlots;
  2213. prepareStructures$1 = makeStructures;
  2214. }
  2215. let defaultPackr = new Packr({ useRecords: false });
  2216. const pack = defaultPackr.pack;
  2217. const encode = defaultPackr.pack;
  2218. const Encoder = Packr;
  2219. const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
  2220. const REUSE_BUFFER_MODE = 512;
  2221. const RESET_BUFFER_MODE = 1024;
  2222. const RESERVE_START_SPACE = 2048;
  2223. 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)
  2224. const NUMBER = 0;
  2225. const UTF8 = 2;
  2226. const OBJECT_DATA = 1;
  2227. const DATE = 16;
  2228. const TYPE_NAMES = ['num', 'object', 'string', 'ascii'];
  2229. TYPE_NAMES[DATE] = 'date';
  2230. const float32Headers = [false, true, true, false, false, true, true, false];
  2231. let evalSupported;
  2232. try {
  2233. new Function('');
  2234. evalSupported = true;
  2235. } catch(error) {
  2236. // if eval variants are not supported, do not create inline object readers ever
  2237. }
  2238. let updatedPosition;
  2239. const hasNodeBuffer = typeof Buffer !== 'undefined';
  2240. let textEncoder, currentSource;
  2241. try {
  2242. textEncoder = new TextEncoder();
  2243. } catch (error) {}
  2244. const encodeUtf8 = hasNodeBuffer ? function(target, string, position) {
  2245. return target.utf8Write(string, position, target.byteLength - position)
  2246. } : (textEncoder && textEncoder.encodeInto) ?
  2247. function(target, string, position) {
  2248. return textEncoder.encodeInto(string, target.subarray(position)).written
  2249. } : false;
  2250. setWriteStructSlots(writeStruct, prepareStructures);
  2251. function writeStruct(object, target, encodingStart, position, structures, makeRoom, pack, packr) {
  2252. let typedStructs = packr.typedStructs || (packr.typedStructs = []);
  2253. // note that we rely on pack.js to load stored structures before we get to this point
  2254. let targetView = target.dataView;
  2255. let refsStartPosition = (typedStructs.lastStringStart || 100) + position;
  2256. let safeEnd = target.length - 10;
  2257. let start = position;
  2258. if (position > safeEnd) {
  2259. target = makeRoom(position);
  2260. targetView = target.dataView;
  2261. position -= encodingStart;
  2262. start -= encodingStart;
  2263. refsStartPosition -= encodingStart;
  2264. encodingStart = 0;
  2265. safeEnd = target.length - 10;
  2266. }
  2267. let refOffset, refPosition = refsStartPosition;
  2268. let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
  2269. let nextId = typedStructs.nextId || typedStructs.length;
  2270. let headerSize =
  2271. nextId < 0xf ? 1 :
  2272. nextId < 0xf0 ? 2 :
  2273. nextId < 0xf000 ? 3 :
  2274. nextId < 0xf00000 ? 4 : 0;
  2275. if (headerSize === 0)
  2276. return 0;
  2277. position += headerSize;
  2278. let queuedReferences = [];
  2279. let usedAscii0;
  2280. let keyIndex = 0;
  2281. for (let key in object) {
  2282. let value = object[key];
  2283. let nextTransition = transition[key];
  2284. if (!nextTransition) {
  2285. transition[key] = nextTransition = {
  2286. key,
  2287. parent: transition,
  2288. enumerationOffset: 0,
  2289. ascii0: null,
  2290. ascii8: null,
  2291. num8: null,
  2292. string16: null,
  2293. object16: null,
  2294. num32: null,
  2295. float64: null,
  2296. date64: null
  2297. };
  2298. }
  2299. if (position > safeEnd) {
  2300. target = makeRoom(position);
  2301. targetView = target.dataView;
  2302. position -= encodingStart;
  2303. start -= encodingStart;
  2304. refsStartPosition -= encodingStart;
  2305. refPosition -= encodingStart;
  2306. encodingStart = 0;
  2307. safeEnd = target.length - 10;
  2308. }
  2309. switch (typeof value) {
  2310. case 'number':
  2311. let number = value;
  2312. // first check to see if we are using a lot of ids and should default to wide/common format
  2313. if (nextId < 200 || !nextTransition.num64) {
  2314. if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
  2315. if (number < 0xf6 && number >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number < 0x20 && !nextTransition.num32)) {
  2316. transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1);
  2317. target[position++] = number;
  2318. } else {
  2319. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2320. targetView.setUint32(position, number, true);
  2321. position += 4;
  2322. }
  2323. break;
  2324. } else if (number < 0x100000000 && number >= -0x80000000) {
  2325. targetView.setFloat32(position, number, true);
  2326. if (float32Headers[target[position + 3] >>> 5]) {
  2327. let xShifted;
  2328. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2329. if (((xShifted = number * mult10[((target[position + 3] & 0x7f) << 1) | (target[position + 2] >> 7)]) >> 0) === xShifted) {
  2330. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2331. position += 4;
  2332. break;
  2333. }
  2334. }
  2335. }
  2336. }
  2337. transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8);
  2338. targetView.setFloat64(position, number, true);
  2339. position += 8;
  2340. break;
  2341. case 'string':
  2342. let strLength = value.length;
  2343. refOffset = refPosition - refsStartPosition;
  2344. if ((strLength << 2) + refPosition > safeEnd) {
  2345. target = makeRoom((strLength << 2) + refPosition);
  2346. targetView = target.dataView;
  2347. position -= encodingStart;
  2348. start -= encodingStart;
  2349. refsStartPosition -= encodingStart;
  2350. refPosition -= encodingStart;
  2351. encodingStart = 0;
  2352. safeEnd = target.length - 10;
  2353. }
  2354. if (strLength > ((0xff00 + refOffset) >> 2)) {
  2355. queuedReferences.push(key, value, position - start);
  2356. break;
  2357. }
  2358. let isNotAscii;
  2359. let strStart = refPosition;
  2360. if (strLength < 0x40) {
  2361. let i, c1, c2;
  2362. for (i = 0; i < strLength; i++) {
  2363. c1 = value.charCodeAt(i);
  2364. if (c1 < 0x80) {
  2365. target[refPosition++] = c1;
  2366. } else if (c1 < 0x800) {
  2367. isNotAscii = true;
  2368. target[refPosition++] = c1 >> 6 | 0xc0;
  2369. target[refPosition++] = c1 & 0x3f | 0x80;
  2370. } else if (
  2371. (c1 & 0xfc00) === 0xd800 &&
  2372. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  2373. ) {
  2374. isNotAscii = true;
  2375. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  2376. i++;
  2377. target[refPosition++] = c1 >> 18 | 0xf0;
  2378. target[refPosition++] = c1 >> 12 & 0x3f | 0x80;
  2379. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2380. target[refPosition++] = c1 & 0x3f | 0x80;
  2381. } else {
  2382. isNotAscii = true;
  2383. target[refPosition++] = c1 >> 12 | 0xe0;
  2384. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2385. target[refPosition++] = c1 & 0x3f | 0x80;
  2386. }
  2387. }
  2388. } else {
  2389. refPosition += encodeUtf8(target, value, refPosition);
  2390. isNotAscii = refPosition - strStart > strLength;
  2391. }
  2392. if (refOffset < 0xa0 || (refOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
  2393. // short strings
  2394. if (isNotAscii) {
  2395. if (!(transition = nextTransition.string8)) {
  2396. if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
  2397. // we can safely change ascii to utf8 in place since they are compatible
  2398. transition.__type = UTF8;
  2399. nextTransition.ascii8 = null;
  2400. nextTransition.string8 = transition;
  2401. pack(null, 0, true); // special call to notify that structures have been updated
  2402. } else {
  2403. transition = createTypeTransition(nextTransition, UTF8, 1);
  2404. }
  2405. }
  2406. } else if (refOffset === 0 && !usedAscii0) {
  2407. usedAscii0 = true;
  2408. transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0);
  2409. break; // don't increment position
  2410. }// else ascii:
  2411. else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8)))
  2412. transition = createTypeTransition(nextTransition, ASCII, 1);
  2413. target[position++] = refOffset;
  2414. } else {
  2415. // TODO: Enable ascii16 at some point, but get the logic right
  2416. //if (isNotAscii)
  2417. transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2);
  2418. //else
  2419. //transition = nextTransition.ascii16 || createTypeTransition(nextTransition, ASCII, 2);
  2420. targetView.setUint16(position, refOffset, true);
  2421. position += 2;
  2422. }
  2423. break;
  2424. case 'object':
  2425. if (value) {
  2426. if (value.constructor === Date) {
  2427. transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8);
  2428. targetView.setFloat64(position, value.getTime(), true);
  2429. position += 8;
  2430. } else {
  2431. queuedReferences.push(key, value, keyIndex);
  2432. }
  2433. break;
  2434. } else { // null
  2435. nextTransition = anyType(nextTransition, position, targetView, -10); // match CBOR with this
  2436. if (nextTransition) {
  2437. transition = nextTransition;
  2438. position = updatedPosition;
  2439. } else queuedReferences.push(key, value, keyIndex);
  2440. }
  2441. break;
  2442. case 'boolean':
  2443. transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1);
  2444. target[position++] = value ? 0xf9 : 0xf8; // match CBOR with these
  2445. break;
  2446. case 'undefined':
  2447. nextTransition = anyType(nextTransition, position, targetView, -9); // match CBOR with this
  2448. if (nextTransition) {
  2449. transition = nextTransition;
  2450. position = updatedPosition;
  2451. } else queuedReferences.push(key, value, keyIndex);
  2452. break;
  2453. default:
  2454. queuedReferences.push(key, value, keyIndex);
  2455. }
  2456. keyIndex++;
  2457. }
  2458. for (let i = 0, l = queuedReferences.length; i < l;) {
  2459. let key = queuedReferences[i++];
  2460. let value = queuedReferences[i++];
  2461. let propertyIndex = queuedReferences[i++];
  2462. let nextTransition = transition[key];
  2463. if (!nextTransition) {
  2464. transition[key] = nextTransition = {
  2465. key,
  2466. parent: transition,
  2467. enumerationOffset: propertyIndex - keyIndex,
  2468. ascii0: null,
  2469. ascii8: null,
  2470. num8: null,
  2471. string16: null,
  2472. object16: null,
  2473. num32: null,
  2474. float64: null
  2475. };
  2476. }
  2477. let newPosition;
  2478. if (value) {
  2479. /*if (typeof value === 'string') { // TODO: we could re-enable long strings
  2480. if (position + value.length * 3 > safeEnd) {
  2481. target = makeRoom(position + value.length * 3);
  2482. position -= start;
  2483. targetView = target.dataView;
  2484. start = 0;
  2485. }
  2486. newPosition = position + target.utf8Write(value, position, 0xffffffff);
  2487. } else { */
  2488. let size;
  2489. refOffset = refPosition - refsStartPosition;
  2490. if (refOffset < 0xff00) {
  2491. transition = nextTransition.object16;
  2492. if (transition)
  2493. size = 2;
  2494. else if ((transition = nextTransition.object32))
  2495. size = 4;
  2496. else {
  2497. transition = createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2498. size = 2;
  2499. }
  2500. } else {
  2501. transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4);
  2502. size = 4;
  2503. }
  2504. newPosition = pack(value, refPosition);
  2505. //}
  2506. if (typeof newPosition === 'object') {
  2507. // re-allocated
  2508. refPosition = newPosition.position;
  2509. targetView = newPosition.targetView;
  2510. target = newPosition.target;
  2511. refsStartPosition -= encodingStart;
  2512. position -= encodingStart;
  2513. start -= encodingStart;
  2514. encodingStart = 0;
  2515. } else
  2516. refPosition = newPosition;
  2517. if (size === 2) {
  2518. targetView.setUint16(position, refOffset, true);
  2519. position += 2;
  2520. } else {
  2521. targetView.setUint32(position, refOffset, true);
  2522. position += 4;
  2523. }
  2524. } else { // null or undefined
  2525. transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2526. targetView.setInt16(position, value === null ? -10 : -9, true);
  2527. position += 2;
  2528. }
  2529. keyIndex++;
  2530. }
  2531. let recordId = transition[RECORD_SYMBOL];
  2532. if (recordId == null) {
  2533. recordId = packr.typedStructs.length;
  2534. let structure = [];
  2535. let nextTransition = transition;
  2536. let key, type;
  2537. while ((type = nextTransition.__type) !== undefined) {
  2538. let size = nextTransition.__size;
  2539. nextTransition = nextTransition.__parent;
  2540. key = nextTransition.key;
  2541. let property = [type, size, key];
  2542. if (nextTransition.enumerationOffset)
  2543. property.push(nextTransition.enumerationOffset);
  2544. structure.push(property);
  2545. nextTransition = nextTransition.parent;
  2546. }
  2547. structure.reverse();
  2548. transition[RECORD_SYMBOL] = recordId;
  2549. packr.typedStructs[recordId] = structure;
  2550. pack(null, 0, true); // special call to notify that structures have been updated
  2551. }
  2552. switch (headerSize) {
  2553. case 1:
  2554. if (recordId >= 0x10) return 0;
  2555. target[start] = recordId + 0x20;
  2556. break;
  2557. case 2:
  2558. if (recordId >= 0x100) return 0;
  2559. target[start] = 0x38;
  2560. target[start + 1] = recordId;
  2561. break;
  2562. case 3:
  2563. if (recordId >= 0x10000) return 0;
  2564. target[start] = 0x39;
  2565. targetView.setUint16(start + 1, recordId, true);
  2566. break;
  2567. case 4:
  2568. if (recordId >= 0x1000000) return 0;
  2569. targetView.setUint32(start, (recordId << 8) + 0x3a, true);
  2570. break;
  2571. }
  2572. if (position < refsStartPosition) {
  2573. if (refsStartPosition === refPosition)
  2574. return position; // no refs
  2575. // adjust positioning
  2576. target.copyWithin(position, refsStartPosition, refPosition);
  2577. refPosition += position - refsStartPosition;
  2578. typedStructs.lastStringStart = position - start;
  2579. } else if (position > refsStartPosition) {
  2580. if (refsStartPosition === refPosition)
  2581. return position; // no refs
  2582. typedStructs.lastStringStart = position - start;
  2583. return writeStruct(object, target, encodingStart, start, structures, makeRoom, pack, packr);
  2584. }
  2585. return refPosition;
  2586. }
  2587. function anyType(transition, position, targetView, value) {
  2588. let nextTransition;
  2589. if ((nextTransition = transition.ascii8 || transition.num8)) {
  2590. targetView.setInt8(position, value, true);
  2591. updatedPosition = position + 1;
  2592. return nextTransition;
  2593. }
  2594. if ((nextTransition = transition.string16 || transition.object16)) {
  2595. targetView.setInt16(position, value, true);
  2596. updatedPosition = position + 2;
  2597. return nextTransition;
  2598. }
  2599. if (nextTransition = transition.num32) {
  2600. targetView.setUint32(position, 0xe0000100 + value, true);
  2601. updatedPosition = position + 4;
  2602. return nextTransition;
  2603. }
  2604. // transition.float64
  2605. if (nextTransition = transition.num64) {
  2606. targetView.setFloat64(position, NaN, true);
  2607. targetView.setInt8(position, value);
  2608. updatedPosition = position + 8;
  2609. return nextTransition;
  2610. }
  2611. updatedPosition = position;
  2612. // TODO: can we do an "any" type where we defer the decision?
  2613. return;
  2614. }
  2615. function createTypeTransition(transition, type, size) {
  2616. let typeName = TYPE_NAMES[type] + (size << 3);
  2617. let newTransition = transition[typeName] || (transition[typeName] = Object.create(null));
  2618. newTransition.__type = type;
  2619. newTransition.__size = size;
  2620. newTransition.__parent = transition;
  2621. return newTransition;
  2622. }
  2623. function onLoadedStructures(sharedData) {
  2624. if (!(sharedData instanceof Map))
  2625. return sharedData;
  2626. let typed = sharedData.get('typed') || [];
  2627. if (Object.isFrozen(typed))
  2628. typed = typed.map(structure => structure.slice(0));
  2629. let named = sharedData.get('named');
  2630. let transitions = Object.create(null);
  2631. for (let i = 0, l = typed.length; i < l; i++) {
  2632. let structure = typed[i];
  2633. let transition = transitions;
  2634. for (let [type, size, key] of structure) {
  2635. let nextTransition = transition[key];
  2636. if (!nextTransition) {
  2637. transition[key] = nextTransition = {
  2638. key,
  2639. parent: transition,
  2640. enumerationOffset: 0,
  2641. ascii0: null,
  2642. ascii8: null,
  2643. num8: null,
  2644. string16: null,
  2645. object16: null,
  2646. num32: null,
  2647. float64: null,
  2648. date64: null,
  2649. };
  2650. }
  2651. transition = createTypeTransition(nextTransition, type, size);
  2652. }
  2653. transition[RECORD_SYMBOL] = i;
  2654. }
  2655. typed.transitions = transitions;
  2656. this.typedStructs = typed;
  2657. this.lastTypedStructuresLength = typed.length;
  2658. return named;
  2659. }
  2660. var sourceSymbol = Symbol.for('source');
  2661. function readStruct(src, position, srcEnd, unpackr) {
  2662. let recordId = src[position++] - 0x20;
  2663. if (recordId >= 24) {
  2664. switch(recordId) {
  2665. case 24: recordId = src[position++]; break;
  2666. // little endian:
  2667. case 25: recordId = src[position++] + (src[position++] << 8); break;
  2668. case 26: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16); break;
  2669. case 27: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16) + (src[position++] << 24); break;
  2670. }
  2671. }
  2672. let structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
  2673. if (!structure) {
  2674. // copy src buffer because getStructures will override it
  2675. src = Uint8Array.prototype.slice.call(src, position, srcEnd);
  2676. srcEnd -= position;
  2677. position = 0;
  2678. if (!unpackr.getStructures)
  2679. throw new Error(`Reference to shared structure ${recordId} without getStructures method`);
  2680. unpackr._mergeStructures(unpackr.getStructures());
  2681. if (!unpackr.typedStructs)
  2682. throw new Error('Could not find any shared typed structures');
  2683. unpackr.lastTypedStructuresLength = unpackr.typedStructs.length;
  2684. structure = unpackr.typedStructs[recordId];
  2685. if (!structure)
  2686. throw new Error('Could not find typed structure ' + recordId);
  2687. }
  2688. var construct = structure.construct;
  2689. if (!construct) {
  2690. construct = structure.construct = function LazyObject() {
  2691. };
  2692. var prototype = construct.prototype;
  2693. let properties = [];
  2694. let currentOffset = 0;
  2695. let lastRefProperty;
  2696. for (let i = 0, l = structure.length; i < l; i++) {
  2697. let definition = structure[i];
  2698. let [ type, size, key, enumerationOffset ] = definition;
  2699. if (key === '__proto__')
  2700. key = '__proto_';
  2701. let property = {
  2702. key,
  2703. offset: currentOffset,
  2704. };
  2705. if (enumerationOffset)
  2706. properties.splice(i + enumerationOffset, 0, property);
  2707. else
  2708. properties.push(property);
  2709. let getRef;
  2710. switch(size) { // TODO: Move into a separate function
  2711. case 0: getRef = () => 0; break;
  2712. case 1:
  2713. getRef = (source, position) => {
  2714. let ref = source.bytes[position + property.offset];
  2715. return ref >= 0xf6 ? toConstant(ref) : ref;
  2716. };
  2717. break;
  2718. case 2:
  2719. getRef = (source, position) => {
  2720. let src = source.bytes;
  2721. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2722. let ref = dataView.getUint16(position + property.offset, true);
  2723. return ref >= 0xff00 ? toConstant(ref & 0xff) : ref;
  2724. };
  2725. break;
  2726. case 4:
  2727. getRef = (source, position) => {
  2728. let src = source.bytes;
  2729. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2730. let ref = dataView.getUint32(position + property.offset, true);
  2731. return ref >= 0xffffff00 ? toConstant(ref & 0xff) : ref;
  2732. };
  2733. break;
  2734. }
  2735. property.getRef = getRef;
  2736. currentOffset += size;
  2737. let get;
  2738. switch(type) {
  2739. case ASCII:
  2740. if (lastRefProperty && !lastRefProperty.next)
  2741. lastRefProperty.next = property;
  2742. lastRefProperty = property;
  2743. property.multiGetCount = 0;
  2744. get = function(source) {
  2745. let src = source.bytes;
  2746. let position = source.position;
  2747. let refStart = currentOffset + position;
  2748. let ref = getRef(source, position);
  2749. if (typeof ref !== 'number') return ref;
  2750. let end, next = property.next;
  2751. while(next) {
  2752. end = next.getRef(source, position);
  2753. if (typeof end === 'number')
  2754. break;
  2755. else
  2756. end = null;
  2757. next = next.next;
  2758. }
  2759. if (end == null)
  2760. end = source.bytesEnd - refStart;
  2761. if (source.srcString) {
  2762. return source.srcString.slice(ref, end);
  2763. }
  2764. /*if (property.multiGetCount > 0) {
  2765. let asciiEnd;
  2766. next = firstRefProperty;
  2767. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2768. do {
  2769. asciiEnd = dataView.getUint16(source.position + next.offset, true);
  2770. if (asciiEnd < 0xff00)
  2771. break;
  2772. else
  2773. asciiEnd = null;
  2774. } while((next = next.next));
  2775. if (asciiEnd == null)
  2776. asciiEnd = source.bytesEnd - refStart
  2777. source.srcString = src.toString('latin1', refStart, refStart + asciiEnd);
  2778. return source.srcString.slice(ref, end);
  2779. }
  2780. if (source.prevStringGet) {
  2781. source.prevStringGet.multiGetCount += 2;
  2782. } else {
  2783. source.prevStringGet = property;
  2784. property.multiGetCount--;
  2785. }*/
  2786. return readString(src, ref + refStart, end - ref);
  2787. //return src.toString('latin1', ref + refStart, end + refStart);
  2788. };
  2789. break;
  2790. case UTF8: case OBJECT_DATA:
  2791. if (lastRefProperty && !lastRefProperty.next)
  2792. lastRefProperty.next = property;
  2793. lastRefProperty = property;
  2794. get = function(source) {
  2795. let position = source.position;
  2796. let refStart = currentOffset + position;
  2797. let ref = getRef(source, position);
  2798. if (typeof ref !== 'number') return ref;
  2799. let src = source.bytes;
  2800. let end, next = property.next;
  2801. while(next) {
  2802. end = next.getRef(source, position);
  2803. if (typeof end === 'number')
  2804. break;
  2805. else
  2806. end = null;
  2807. next = next.next;
  2808. }
  2809. if (end == null)
  2810. end = source.bytesEnd - refStart;
  2811. if (type === UTF8) {
  2812. return src.toString('utf8', ref + refStart, end + refStart);
  2813. } else {
  2814. currentSource = source;
  2815. try {
  2816. return unpackr.unpack(src, { start: ref + refStart, end: end + refStart });
  2817. } finally {
  2818. currentSource = null;
  2819. }
  2820. }
  2821. };
  2822. break;
  2823. case NUMBER:
  2824. switch(size) {
  2825. case 4:
  2826. get = function (source) {
  2827. let src = source.bytes;
  2828. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2829. let position = source.position + property.offset;
  2830. let value = dataView.getInt32(position, true);
  2831. if (value < 0x20000000) {
  2832. if (value > -0x1f000000)
  2833. return value;
  2834. if (value > -0x20000000)
  2835. return toConstant(value & 0xff);
  2836. }
  2837. let fValue = dataView.getFloat32(position, true);
  2838. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2839. let multiplier = mult10[((src[position + 3] & 0x7f) << 1) | (src[position + 2] >> 7)];
  2840. return ((multiplier * fValue + (fValue > 0 ? 0.5 : -0.5)) >> 0) / multiplier;
  2841. };
  2842. break;
  2843. case 8:
  2844. get = function (source) {
  2845. let src = source.bytes;
  2846. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2847. let value = dataView.getFloat64(source.position + property.offset, true);
  2848. if (isNaN(value)) {
  2849. let byte = src[source.position + property.offset];
  2850. if (byte >= 0xf6)
  2851. return toConstant(byte);
  2852. }
  2853. return value;
  2854. };
  2855. break;
  2856. case 1:
  2857. get = function (source) {
  2858. let src = source.bytes;
  2859. let value = src[source.position + property.offset];
  2860. return value < 0xf6 ? value : toConstant(value);
  2861. };
  2862. break;
  2863. }
  2864. break;
  2865. case DATE:
  2866. get = function (source) {
  2867. let src = source.bytes;
  2868. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2869. return new Date(dataView.getFloat64(source.position + property.offset, true));
  2870. };
  2871. break;
  2872. }
  2873. property.get = get;
  2874. }
  2875. // TODO: load the srcString for faster string decoding on toJSON
  2876. if (evalSupported) {
  2877. let objectLiteralProperties = [];
  2878. let args = [];
  2879. let i = 0;
  2880. let hasInheritedProperties;
  2881. for (let property of properties) { // assign in enumeration order
  2882. if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) {
  2883. // these properties are not eagerly evaluated and this can be used for creating properties
  2884. // that are not serialized as JSON
  2885. hasInheritedProperties = true;
  2886. continue;
  2887. }
  2888. Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true });
  2889. let valueFunction = 'v' + i++;
  2890. args.push(valueFunction);
  2891. objectLiteralProperties.push('[' + JSON.stringify(property.key) + ']:' + valueFunction + '(s)');
  2892. }
  2893. if (hasInheritedProperties) {
  2894. objectLiteralProperties.push('__proto__:this');
  2895. }
  2896. let toObject = (new Function(...args, 'return function(s){return{' + objectLiteralProperties.join(',') + '}}')).apply(null, properties.map(prop => prop.get));
  2897. Object.defineProperty(prototype, 'toJSON', {
  2898. value(omitUnderscoredProperties) {
  2899. return toObject.call(this, this[sourceSymbol]);
  2900. }
  2901. });
  2902. } else {
  2903. Object.defineProperty(prototype, 'toJSON', {
  2904. value(omitUnderscoredProperties) {
  2905. // return an enumerable object with own properties to JSON stringify
  2906. let resolved = {};
  2907. for (let i = 0, l = properties.length; i < l; i++) {
  2908. // TODO: check alwaysLazyProperty
  2909. let key = properties[i].key;
  2910. resolved[key] = this[key];
  2911. }
  2912. return resolved;
  2913. },
  2914. // not enumerable or anything
  2915. });
  2916. }
  2917. }
  2918. var instance = new construct();
  2919. instance[sourceSymbol] = {
  2920. bytes: src,
  2921. position,
  2922. srcString: '',
  2923. bytesEnd: srcEnd
  2924. };
  2925. return instance;
  2926. }
  2927. function toConstant(code) {
  2928. switch(code) {
  2929. case 0xf6: return null;
  2930. case 0xf7: return undefined;
  2931. case 0xf8: return false;
  2932. case 0xf9: return true;
  2933. }
  2934. throw new Error('Unknown constant');
  2935. }
  2936. function withSource(get) {
  2937. return function() {
  2938. return get(this[sourceSymbol]);
  2939. }
  2940. }
  2941. function saveState() {
  2942. if (currentSource) {
  2943. currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd);
  2944. currentSource.position = 0;
  2945. currentSource.bytesEnd = currentSource.bytes.length;
  2946. }
  2947. }
  2948. function prepareStructures(structures, packr) {
  2949. if (packr.typedStructs) {
  2950. let structMap = new Map();
  2951. structMap.set('named', structures);
  2952. structMap.set('typed', packr.typedStructs);
  2953. structures = structMap;
  2954. }
  2955. let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0;
  2956. structures.isCompatible = existing => {
  2957. let compatible = true;
  2958. if (existing instanceof Map) {
  2959. let named = existing.get('named') || [];
  2960. if (named.length !== (packr.lastNamedStructuresLength || 0))
  2961. compatible = false;
  2962. let typed = existing.get('typed') || [];
  2963. if (typed.length !== lastTypedStructuresLength)
  2964. compatible = false;
  2965. } else if (existing instanceof Array || Array.isArray(existing)) {
  2966. if (existing.length !== (packr.lastNamedStructuresLength || 0))
  2967. compatible = false;
  2968. }
  2969. if (!compatible)
  2970. packr._mergeStructures(existing);
  2971. return compatible;
  2972. };
  2973. packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length;
  2974. return structures;
  2975. }
  2976. setReadStruct(readStruct, onLoadedStructures, saveState);
  2977. class PackrStream extends stream.Transform {
  2978. constructor(options) {
  2979. if (!options)
  2980. options = {};
  2981. options.writableObjectMode = true;
  2982. super(options);
  2983. options.sequential = true;
  2984. this.packr = options.packr || new Packr(options);
  2985. }
  2986. _transform(value, encoding, callback) {
  2987. this.push(this.packr.pack(value));
  2988. callback();
  2989. }
  2990. }
  2991. class UnpackrStream extends stream.Transform {
  2992. constructor(options) {
  2993. if (!options)
  2994. options = {};
  2995. options.objectMode = true;
  2996. super(options);
  2997. options.structures = [];
  2998. this.unpackr = options.unpackr || new Unpackr(options);
  2999. }
  3000. _transform(chunk, encoding, callback) {
  3001. if (this.incompleteBuffer) {
  3002. chunk = Buffer.concat([this.incompleteBuffer, chunk]);
  3003. this.incompleteBuffer = null;
  3004. }
  3005. let values;
  3006. try {
  3007. values = this.unpackr.unpackMultiple(chunk);
  3008. } catch(error) {
  3009. if (error.incomplete) {
  3010. this.incompleteBuffer = chunk.slice(error.lastPosition);
  3011. values = error.values;
  3012. }
  3013. else
  3014. throw error
  3015. } finally {
  3016. for (let value of values || []) {
  3017. if (value === null)
  3018. value = this.getNullValue();
  3019. this.push(value);
  3020. }
  3021. }
  3022. if (callback) callback();
  3023. }
  3024. getNullValue() {
  3025. return Symbol.for(null)
  3026. }
  3027. }
  3028. /**
  3029. * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
  3030. * If the argument is only Async Iterable, the return value will be an Async Iterable.
  3031. * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
  3032. * @param {options} [options] - msgpackr pack options
  3033. * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
  3034. */
  3035. function packIter (objectIterator, options = {}) {
  3036. if (!objectIterator || typeof objectIterator !== 'object') {
  3037. throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
  3038. } else if (typeof objectIterator[Symbol.iterator] === 'function') {
  3039. return packIterSync(objectIterator, options)
  3040. } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
  3041. return packIterAsync(objectIterator, options)
  3042. } else {
  3043. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
  3044. }
  3045. }
  3046. function * packIterSync (objectIterator, options) {
  3047. const packr = new Packr(options);
  3048. for (const value of objectIterator) {
  3049. yield packr.pack(value);
  3050. }
  3051. }
  3052. async function * packIterAsync (objectIterator, options) {
  3053. const packr = new Packr(options);
  3054. for await (const value of objectIterator) {
  3055. yield packr.pack(value);
  3056. }
  3057. }
  3058. /**
  3059. * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
  3060. * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
  3061. * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
  3062. * @param {object} [options] - unpackr options
  3063. * @returns {IterableIterator|Promise.<AsyncIterableIterator}
  3064. */
  3065. function unpackIter (bufferIterator, options = {}) {
  3066. if (!bufferIterator || typeof bufferIterator !== 'object') {
  3067. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
  3068. }
  3069. const unpackr = new Unpackr(options);
  3070. let incomplete;
  3071. const parser = (chunk) => {
  3072. let yields;
  3073. // if there's incomplete data from previous chunk, concatinate and try again
  3074. if (incomplete) {
  3075. chunk = Buffer.concat([incomplete, chunk]);
  3076. incomplete = undefined;
  3077. }
  3078. try {
  3079. yields = unpackr.unpackMultiple(chunk);
  3080. } catch (err) {
  3081. if (err.incomplete) {
  3082. incomplete = chunk.slice(err.lastPosition);
  3083. yields = err.values;
  3084. } else {
  3085. throw err
  3086. }
  3087. }
  3088. return yields
  3089. };
  3090. if (typeof bufferIterator[Symbol.iterator] === 'function') {
  3091. return (function * iter () {
  3092. for (const value of bufferIterator) {
  3093. yield * parser(value);
  3094. }
  3095. })()
  3096. } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
  3097. return (async function * iter () {
  3098. for await (const value of bufferIterator) {
  3099. yield * parser(value);
  3100. }
  3101. })()
  3102. }
  3103. }
  3104. const decodeIter = unpackIter;
  3105. const encodeIter = packIter;
  3106. const useRecords = false;
  3107. const mapsAsObjects = true;
  3108. const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
  3109. if (!nativeAccelerationDisabled) {
  3110. let extractor;
  3111. try {
  3112. if (typeof require == 'function')
  3113. extractor = require('msgpackr-extract');
  3114. else
  3115. extractor = module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('node.cjs', document.baseURI).href)))('msgpackr-extract');
  3116. if (extractor)
  3117. setExtractor(extractor.extractStrings);
  3118. } catch (error) {
  3119. // native module is optional
  3120. }
  3121. }
  3122. exports.ALWAYS = ALWAYS;
  3123. exports.C1 = C1;
  3124. exports.DECIMAL_FIT = DECIMAL_FIT;
  3125. exports.DECIMAL_ROUND = DECIMAL_ROUND;
  3126. exports.Decoder = Decoder;
  3127. exports.DecoderStream = UnpackrStream;
  3128. exports.Encoder = Encoder;
  3129. exports.EncoderStream = PackrStream;
  3130. exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
  3131. exports.NEVER = NEVER;
  3132. exports.Packr = Packr;
  3133. exports.PackrStream = PackrStream;
  3134. exports.Unpackr = Unpackr;
  3135. exports.UnpackrStream = UnpackrStream;
  3136. exports.addExtension = addExtension;
  3137. exports.clearSource = clearSource;
  3138. exports.decode = decode;
  3139. exports.decodeIter = decodeIter;
  3140. exports.encode = encode;
  3141. exports.encodeIter = encodeIter;
  3142. exports.mapsAsObjects = mapsAsObjects;
  3143. exports.pack = pack;
  3144. exports.roundFloat32 = roundFloat32;
  3145. exports.unpack = unpack;
  3146. exports.unpackMultiple = unpackMultiple;
  3147. exports.useRecords = useRecords;
  3148. //# sourceMappingURL=node.cjs.map