node.cjs 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313
  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. if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {
  951. return property.flat().toString();
  952. }
  953. throw new Error(`Invalid property type for record: ${typeof property}`);
  954. }
  955. // the registration of the record definition extension (as "r")
  956. const recordDefinition = (id, highByte) => {
  957. let structure = read().map(asSafeString); // ensure that all keys are strings and
  958. // that the array is mutable
  959. let firstByte = id;
  960. if (highByte !== undefined) {
  961. id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
  962. structure.highByte = highByte;
  963. }
  964. let existingStructure = currentStructures[id];
  965. // If it is a shared structure, we need to restore any changes after reading.
  966. // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
  967. // to the state prior to an incomplete read in order to properly resume.
  968. if (existingStructure && (existingStructure.isShared || sequentialMode)) {
  969. (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
  970. }
  971. currentStructures[id] = structure;
  972. structure.read = createStructureReader(structure, firstByte);
  973. return structure.read()
  974. };
  975. currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
  976. currentExtensions[0].noBuffer = true;
  977. currentExtensions[0x42] = data => {
  978. let headLength = (data.byteLength % 8) || 8;
  979. let head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
  980. for (let i = 1; i < headLength; i++) {
  981. head <<= BigInt(8);
  982. head += BigInt(data[i]);
  983. }
  984. if (data.byteLength !== headLength) {
  985. let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  986. let decode = (start, end) => {
  987. let length = end - start;
  988. if (length <= 40) {
  989. let out = view.getBigUint64(start);
  990. for (let i = start + 8; i < end; i += 8) {
  991. out <<= BigInt(64n);
  992. out |= view.getBigUint64(i);
  993. }
  994. return out
  995. }
  996. // if (length === 8) return view.getBigUint64(start)
  997. let middle = start + (length >> 4 << 3);
  998. let left = decode(start, middle);
  999. let right = decode(middle, end);
  1000. return (left << BigInt((end - middle) * 8)) | right
  1001. };
  1002. head = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);
  1003. }
  1004. return head
  1005. };
  1006. let errors = {
  1007. Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,
  1008. };
  1009. currentExtensions[0x65] = () => {
  1010. let data = read();
  1011. if (!errors[data[0]]) {
  1012. let error = Error(data[1], { cause: data[2] });
  1013. error.name = data[0];
  1014. return error
  1015. }
  1016. return errors[data[0]](data[1], { cause: data[2] })
  1017. };
  1018. currentExtensions[0x69] = (data) => {
  1019. // id extension (for structured clones)
  1020. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1021. let id = dataView.getUint32(position$1 - 4);
  1022. if (!referenceMap)
  1023. referenceMap = new Map();
  1024. let token = src[position$1];
  1025. let target;
  1026. // TODO: handle any other types that can cycle and make the code more robust if there are other extensions
  1027. if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
  1028. target = [];
  1029. else if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)
  1030. target = new Map();
  1031. else if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position$1 + 1] === 0x73)
  1032. target = new Set();
  1033. else
  1034. target = {};
  1035. let refEntry = { target }; // a placeholder object
  1036. referenceMap.set(id, refEntry);
  1037. let targetProperties = read(); // read the next value as the target object to id
  1038. if (!refEntry.used) {
  1039. // no cycle, can just use the returned read object
  1040. return refEntry.target = targetProperties // replace the placeholder with the real one
  1041. } else {
  1042. // there is a cycle, so we have to assign properties to original target
  1043. Object.assign(target, targetProperties);
  1044. }
  1045. // copy over map/set entries if we're able to
  1046. if (target instanceof Map)
  1047. for (let [k, v] of targetProperties.entries()) target.set(k, v);
  1048. if (target instanceof Set)
  1049. for (let i of Array.from(targetProperties)) target.add(i);
  1050. return target
  1051. };
  1052. currentExtensions[0x70] = (data) => {
  1053. // pointer extension (for structured clones)
  1054. if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
  1055. let id = dataView.getUint32(position$1 - 4);
  1056. let refEntry = referenceMap.get(id);
  1057. refEntry.used = true;
  1058. return refEntry.target
  1059. };
  1060. currentExtensions[0x73] = () => new Set(read());
  1061. const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
  1062. let glbl = typeof globalThis === 'object' ? globalThis : window;
  1063. currentExtensions[0x74] = (data) => {
  1064. let typeCode = data[0];
  1065. // we always have to slice to get a new ArrayBuffer that is aligned
  1066. let buffer = Uint8Array.prototype.slice.call(data, 1).buffer;
  1067. let typedArrayName = typedArrays[typeCode];
  1068. if (!typedArrayName) {
  1069. if (typeCode === 16) return buffer
  1070. if (typeCode === 17) return new DataView(buffer)
  1071. throw new Error('Could not find typed array for code ' + typeCode)
  1072. }
  1073. return new glbl[typedArrayName](buffer)
  1074. };
  1075. currentExtensions[0x78] = () => {
  1076. let data = read();
  1077. return new RegExp(data[0], data[1])
  1078. };
  1079. const TEMP_BUNDLE = [];
  1080. currentExtensions[0x62] = (data) => {
  1081. let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
  1082. let dataPosition = position$1;
  1083. position$1 += dataSize - data.length;
  1084. bundledStrings$1 = TEMP_BUNDLE;
  1085. bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
  1086. bundledStrings$1.position0 = 0;
  1087. bundledStrings$1.position1 = 0;
  1088. bundledStrings$1.postBundlePosition = position$1;
  1089. position$1 = dataPosition;
  1090. return read()
  1091. };
  1092. currentExtensions[0xff] = (data) => {
  1093. // 32-bit date extension
  1094. if (data.length == 4)
  1095. return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
  1096. else if (data.length == 8)
  1097. return new Date(
  1098. ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
  1099. ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
  1100. else if (data.length == 12)
  1101. return new Date(
  1102. ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
  1103. (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
  1104. else
  1105. return new Date('invalid')
  1106. };
  1107. // registration of bulk record definition?
  1108. // currentExtensions[0x52] = () =>
  1109. function saveState$1(callback) {
  1110. if (onSaveState)
  1111. onSaveState();
  1112. let savedSrcEnd = srcEnd;
  1113. let savedPosition = position$1;
  1114. let savedStringPosition = stringPosition;
  1115. let savedSrcStringStart = srcStringStart;
  1116. let savedSrcStringEnd = srcStringEnd;
  1117. let savedSrcString = srcString;
  1118. let savedStrings = strings;
  1119. let savedReferenceMap = referenceMap;
  1120. let savedBundledStrings = bundledStrings$1;
  1121. // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
  1122. let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
  1123. let savedStructures = currentStructures;
  1124. let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
  1125. let savedPackr = currentUnpackr;
  1126. let savedSequentialMode = sequentialMode;
  1127. let value = callback();
  1128. srcEnd = savedSrcEnd;
  1129. position$1 = savedPosition;
  1130. stringPosition = savedStringPosition;
  1131. srcStringStart = savedSrcStringStart;
  1132. srcStringEnd = savedSrcStringEnd;
  1133. srcString = savedSrcString;
  1134. strings = savedStrings;
  1135. referenceMap = savedReferenceMap;
  1136. bundledStrings$1 = savedBundledStrings;
  1137. src = savedSrc;
  1138. sequentialMode = savedSequentialMode;
  1139. currentStructures = savedStructures;
  1140. currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
  1141. currentUnpackr = savedPackr;
  1142. dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
  1143. return value
  1144. }
  1145. function clearSource() {
  1146. src = null;
  1147. referenceMap = null;
  1148. currentStructures = null;
  1149. }
  1150. function addExtension$1(extension) {
  1151. if (extension.unpack)
  1152. currentExtensions[extension.type] = extension.unpack;
  1153. else
  1154. currentExtensions[extension.type] = extension;
  1155. }
  1156. const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
  1157. for (let i = 0; i < 256; i++) {
  1158. mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
  1159. }
  1160. const Decoder = Unpackr;
  1161. var defaultUnpackr = new Unpackr({ useRecords: false });
  1162. const unpack = defaultUnpackr.unpack;
  1163. const unpackMultiple = defaultUnpackr.unpackMultiple;
  1164. const decode = defaultUnpackr.unpack;
  1165. const FLOAT32_OPTIONS = {
  1166. NEVER: 0,
  1167. ALWAYS: 1,
  1168. DECIMAL_ROUND: 3,
  1169. DECIMAL_FIT: 4
  1170. };
  1171. let f32Array = new Float32Array(1);
  1172. let u8Array = new Uint8Array(f32Array.buffer, 0, 4);
  1173. function roundFloat32(float32Number) {
  1174. f32Array[0] = float32Number;
  1175. let multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];
  1176. return ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier
  1177. }
  1178. function setReadStruct(updatedReadStruct, loadedStructs, saveState) {
  1179. readStruct$1 = updatedReadStruct;
  1180. onLoadedStructures$1 = loadedStructs;
  1181. onSaveState = saveState;
  1182. }
  1183. let textEncoder$1;
  1184. try {
  1185. textEncoder$1 = new TextEncoder();
  1186. } catch (error) {}
  1187. let extensions, extensionClasses;
  1188. const hasNodeBuffer$1 = typeof Buffer !== 'undefined';
  1189. const ByteArrayAllocate = hasNodeBuffer$1 ?
  1190. function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
  1191. const ByteArray = hasNodeBuffer$1 ? Buffer : Uint8Array;
  1192. const MAX_BUFFER_SIZE = hasNodeBuffer$1 ? 0x100000000 : 0x7fd00000;
  1193. let target, keysTarget;
  1194. let targetView;
  1195. let position = 0;
  1196. let safeEnd;
  1197. let bundledStrings = null;
  1198. let writeStructSlots;
  1199. const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
  1200. const hasNonLatin = /[\u0080-\uFFFF]/;
  1201. const RECORD_SYMBOL = Symbol('record-id');
  1202. class Packr extends Unpackr {
  1203. constructor(options) {
  1204. super(options);
  1205. this.offset = 0;
  1206. let start;
  1207. let hasSharedUpdate;
  1208. let structures;
  1209. let referenceMap;
  1210. let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
  1211. return target.utf8Write(string, position, target.byteLength - position)
  1212. } : (textEncoder$1 && textEncoder$1.encodeInto) ?
  1213. function(string, position) {
  1214. return textEncoder$1.encodeInto(string, target.subarray(position)).written
  1215. } : false;
  1216. let packr = this;
  1217. if (!options)
  1218. options = {};
  1219. let isSequential = options && options.sequential;
  1220. let hasSharedStructures = options.structures || options.saveStructures;
  1221. let maxSharedStructures = options.maxSharedStructures;
  1222. if (maxSharedStructures == null)
  1223. maxSharedStructures = hasSharedStructures ? 32 : 0;
  1224. if (maxSharedStructures > 8160)
  1225. throw new Error('Maximum maxSharedStructure is 8160')
  1226. if (options.structuredClone && options.moreTypes == undefined) {
  1227. this.moreTypes = true;
  1228. }
  1229. let maxOwnStructures = options.maxOwnStructures;
  1230. if (maxOwnStructures == null)
  1231. maxOwnStructures = hasSharedStructures ? 32 : 64;
  1232. if (!this.structures && options.useRecords != false)
  1233. this.structures = [];
  1234. // two byte record ids for shared structures
  1235. let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
  1236. let sharedLimitId = maxSharedStructures + 0x40;
  1237. let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
  1238. if (maxStructureId > 8256) {
  1239. throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
  1240. }
  1241. let recordIdsToRemove = [];
  1242. let transitionsCount = 0;
  1243. let serializationsSinceTransitionRebuild = 0;
  1244. this.pack = this.encode = function(value, encodeOptions) {
  1245. if (!target) {
  1246. target = new ByteArrayAllocate(8192);
  1247. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
  1248. position = 0;
  1249. }
  1250. safeEnd = target.length - 10;
  1251. if (safeEnd - position < 0x800) {
  1252. // don't start too close to the end,
  1253. target = new ByteArrayAllocate(target.length);
  1254. targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
  1255. safeEnd = target.length - 10;
  1256. position = 0;
  1257. } else
  1258. position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
  1259. start = position;
  1260. if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
  1261. referenceMap = packr.structuredClone ? new Map() : null;
  1262. if (packr.bundleStrings && typeof value !== 'string') {
  1263. bundledStrings = [];
  1264. bundledStrings.size = Infinity; // force a new bundle start on first string
  1265. } else
  1266. bundledStrings = null;
  1267. structures = packr.structures;
  1268. if (structures) {
  1269. if (structures.uninitialized)
  1270. structures = packr._mergeStructures(packr.getStructures());
  1271. let sharedLength = structures.sharedLength || 0;
  1272. if (sharedLength > maxSharedStructures) {
  1273. //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
  1274. throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
  1275. }
  1276. if (!structures.transitions) {
  1277. // rebuild our structure transitions
  1278. structures.transitions = Object.create(null);
  1279. for (let i = 0; i < sharedLength; i++) {
  1280. let keys = structures[i];
  1281. if (!keys)
  1282. continue
  1283. let nextTransition, transition = structures.transitions;
  1284. for (let j = 0, l = keys.length; j < l; j++) {
  1285. let key = keys[j];
  1286. nextTransition = transition[key];
  1287. if (!nextTransition) {
  1288. nextTransition = transition[key] = Object.create(null);
  1289. }
  1290. transition = nextTransition;
  1291. }
  1292. transition[RECORD_SYMBOL] = i + 0x40;
  1293. }
  1294. this.lastNamedStructuresLength = sharedLength;
  1295. }
  1296. if (!isSequential) {
  1297. structures.nextId = sharedLength + 0x40;
  1298. }
  1299. }
  1300. if (hasSharedUpdate)
  1301. hasSharedUpdate = false;
  1302. let encodingError;
  1303. try {
  1304. if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
  1305. writeStruct(value);
  1306. else
  1307. pack(value);
  1308. let lastBundle = bundledStrings;
  1309. if (bundledStrings)
  1310. writeBundles(start, pack, 0);
  1311. if (referenceMap && referenceMap.idsToInsert) {
  1312. let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
  1313. let i = idsToInsert.length;
  1314. let incrementPosition = -1;
  1315. while (lastBundle && i > 0) {
  1316. let insertionPoint = idsToInsert[--i].offset + start;
  1317. if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
  1318. incrementPosition = 0;
  1319. if (insertionPoint > (lastBundle.position + start)) {
  1320. if (incrementPosition >= 0)
  1321. incrementPosition += 6;
  1322. } else {
  1323. if (incrementPosition >= 0) {
  1324. // update the bundle reference now
  1325. targetView.setUint32(lastBundle.position + start,
  1326. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1327. incrementPosition = -1; // reset
  1328. }
  1329. lastBundle = lastBundle.previous;
  1330. i++;
  1331. }
  1332. }
  1333. if (incrementPosition >= 0 && lastBundle) {
  1334. // update the bundle reference now
  1335. targetView.setUint32(lastBundle.position + start,
  1336. targetView.getUint32(lastBundle.position + start) + incrementPosition);
  1337. }
  1338. position += idsToInsert.length * 6;
  1339. if (position > safeEnd)
  1340. makeRoom(position);
  1341. packr.offset = position;
  1342. let serialized = insertIds(target.subarray(start, position), idsToInsert);
  1343. referenceMap = null;
  1344. return serialized
  1345. }
  1346. packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
  1347. if (encodeOptions & REUSE_BUFFER_MODE) {
  1348. target.start = start;
  1349. target.end = position;
  1350. return target
  1351. }
  1352. return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
  1353. } catch(error) {
  1354. encodingError = error;
  1355. throw error;
  1356. } finally {
  1357. if (structures) {
  1358. resetStructures();
  1359. if (hasSharedUpdate && packr.saveStructures) {
  1360. let sharedLength = structures.sharedLength || 0;
  1361. // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
  1362. let returnBuffer = target.subarray(start, position);
  1363. let newSharedData = prepareStructures$1(structures, packr);
  1364. if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
  1365. if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
  1366. // get updated structures and try again if the update failed
  1367. return packr.pack(value, encodeOptions)
  1368. }
  1369. packr.lastNamedStructuresLength = sharedLength;
  1370. // don't keep large buffers around
  1371. if (target.length > 0x40000000) target = null;
  1372. return returnBuffer
  1373. }
  1374. }
  1375. }
  1376. // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
  1377. if (target.length > 0x40000000) target = null;
  1378. if (encodeOptions & RESET_BUFFER_MODE)
  1379. position = start;
  1380. }
  1381. };
  1382. const resetStructures = () => {
  1383. if (serializationsSinceTransitionRebuild < 10)
  1384. serializationsSinceTransitionRebuild++;
  1385. let sharedLength = structures.sharedLength || 0;
  1386. if (structures.length > sharedLength && !isSequential)
  1387. structures.length = sharedLength;
  1388. if (transitionsCount > 10000) {
  1389. // force a rebuild occasionally after a lot of transitions so it can get cleaned up
  1390. structures.transitions = null;
  1391. serializationsSinceTransitionRebuild = 0;
  1392. transitionsCount = 0;
  1393. if (recordIdsToRemove.length > 0)
  1394. recordIdsToRemove = [];
  1395. } else if (recordIdsToRemove.length > 0 && !isSequential) {
  1396. for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
  1397. recordIdsToRemove[i][RECORD_SYMBOL] = 0;
  1398. }
  1399. recordIdsToRemove = [];
  1400. }
  1401. };
  1402. const packArray = (value) => {
  1403. var length = value.length;
  1404. if (length < 0x10) {
  1405. target[position++] = 0x90 | length;
  1406. } else if (length < 0x10000) {
  1407. target[position++] = 0xdc;
  1408. target[position++] = length >> 8;
  1409. target[position++] = length & 0xff;
  1410. } else {
  1411. target[position++] = 0xdd;
  1412. targetView.setUint32(position, length);
  1413. position += 4;
  1414. }
  1415. for (let i = 0; i < length; i++) {
  1416. pack(value[i]);
  1417. }
  1418. };
  1419. const pack = (value) => {
  1420. if (position > safeEnd)
  1421. target = makeRoom(position);
  1422. var type = typeof value;
  1423. var length;
  1424. if (type === 'string') {
  1425. let strLength = value.length;
  1426. if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
  1427. if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
  1428. let extStart;
  1429. let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
  1430. if (position + maxBytes > safeEnd)
  1431. target = makeRoom(position + maxBytes);
  1432. let lastBundle;
  1433. 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
  1434. lastBundle = bundledStrings;
  1435. target[position] = 0xc8; // ext 16
  1436. position += 3; // reserve for the writing bundle size
  1437. target[position++] = 0x62; // 'b'
  1438. extStart = position - start;
  1439. position += 4; // reserve for writing bundle reference
  1440. writeBundles(start, pack, 0); // write the last bundles
  1441. targetView.setUint16(extStart + start - 3, position - start - extStart);
  1442. } 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)
  1443. target[position++] = 0xd6; // fixext 4
  1444. target[position++] = 0x62; // 'b'
  1445. extStart = position - start;
  1446. position += 4; // reserve for writing bundle reference
  1447. }
  1448. bundledStrings = ['', '']; // create new ones
  1449. bundledStrings.previous = lastBundle;
  1450. bundledStrings.size = 0;
  1451. bundledStrings.position = extStart;
  1452. }
  1453. let twoByte = hasNonLatin.test(value);
  1454. bundledStrings[twoByte ? 0 : 1] += value;
  1455. target[position++] = 0xc1;
  1456. pack(twoByte ? -strLength : strLength);
  1457. return
  1458. }
  1459. let headerSize;
  1460. // first we estimate the header size, so we can write to the correct location
  1461. if (strLength < 0x20) {
  1462. headerSize = 1;
  1463. } else if (strLength < 0x100) {
  1464. headerSize = 2;
  1465. } else if (strLength < 0x10000) {
  1466. headerSize = 3;
  1467. } else {
  1468. headerSize = 5;
  1469. }
  1470. let maxBytes = strLength * 3;
  1471. if (position + maxBytes > safeEnd)
  1472. target = makeRoom(position + maxBytes);
  1473. if (strLength < 0x40 || !encodeUtf8) {
  1474. let i, c1, c2, strPosition = position + headerSize;
  1475. for (i = 0; i < strLength; i++) {
  1476. c1 = value.charCodeAt(i);
  1477. if (c1 < 0x80) {
  1478. target[strPosition++] = c1;
  1479. } else if (c1 < 0x800) {
  1480. target[strPosition++] = c1 >> 6 | 0xc0;
  1481. target[strPosition++] = c1 & 0x3f | 0x80;
  1482. } else if (
  1483. (c1 & 0xfc00) === 0xd800 &&
  1484. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  1485. ) {
  1486. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  1487. i++;
  1488. target[strPosition++] = c1 >> 18 | 0xf0;
  1489. target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
  1490. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1491. target[strPosition++] = c1 & 0x3f | 0x80;
  1492. } else {
  1493. target[strPosition++] = c1 >> 12 | 0xe0;
  1494. target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
  1495. target[strPosition++] = c1 & 0x3f | 0x80;
  1496. }
  1497. }
  1498. length = strPosition - position - headerSize;
  1499. } else {
  1500. length = encodeUtf8(value, position + headerSize);
  1501. }
  1502. if (length < 0x20) {
  1503. target[position++] = 0xa0 | length;
  1504. } else if (length < 0x100) {
  1505. if (headerSize < 2) {
  1506. target.copyWithin(position + 2, position + 1, position + 1 + length);
  1507. }
  1508. target[position++] = 0xd9;
  1509. target[position++] = length;
  1510. } else if (length < 0x10000) {
  1511. if (headerSize < 3) {
  1512. target.copyWithin(position + 3, position + 2, position + 2 + length);
  1513. }
  1514. target[position++] = 0xda;
  1515. target[position++] = length >> 8;
  1516. target[position++] = length & 0xff;
  1517. } else {
  1518. if (headerSize < 5) {
  1519. target.copyWithin(position + 5, position + 3, position + 3 + length);
  1520. }
  1521. target[position++] = 0xdb;
  1522. targetView.setUint32(position, length);
  1523. position += 4;
  1524. }
  1525. position += length;
  1526. } else if (type === 'number') {
  1527. if (value >>> 0 === value) {// positive integer, 32-bit or less
  1528. // positive uint
  1529. if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
  1530. target[position++] = value;
  1531. } else if (value < 0x100) {
  1532. target[position++] = 0xcc;
  1533. target[position++] = value;
  1534. } else if (value < 0x10000) {
  1535. target[position++] = 0xcd;
  1536. target[position++] = value >> 8;
  1537. target[position++] = value & 0xff;
  1538. } else {
  1539. target[position++] = 0xce;
  1540. targetView.setUint32(position, value);
  1541. position += 4;
  1542. }
  1543. } else if (value >> 0 === value) { // negative integer
  1544. if (value >= -0x20) {
  1545. target[position++] = 0x100 + value;
  1546. } else if (value >= -0x80) {
  1547. target[position++] = 0xd0;
  1548. target[position++] = value + 0x100;
  1549. } else if (value >= -0x8000) {
  1550. target[position++] = 0xd1;
  1551. targetView.setInt16(position, value);
  1552. position += 2;
  1553. } else {
  1554. target[position++] = 0xd2;
  1555. targetView.setInt32(position, value);
  1556. position += 4;
  1557. }
  1558. } else {
  1559. let useFloat32;
  1560. if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
  1561. target[position++] = 0xca;
  1562. targetView.setFloat32(position, value);
  1563. let xShifted;
  1564. if (useFloat32 < 4 ||
  1565. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  1566. ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
  1567. position += 4;
  1568. return
  1569. } else
  1570. position--; // move back into position for writing a double
  1571. }
  1572. target[position++] = 0xcb;
  1573. targetView.setFloat64(position, value);
  1574. position += 8;
  1575. }
  1576. } else if (type === 'object' || type === 'function') {
  1577. if (!value)
  1578. target[position++] = 0xc0;
  1579. else {
  1580. if (referenceMap) {
  1581. let referee = referenceMap.get(value);
  1582. if (referee) {
  1583. if (!referee.id) {
  1584. let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
  1585. referee.id = idsToInsert.push(referee);
  1586. }
  1587. target[position++] = 0xd6; // fixext 4
  1588. target[position++] = 0x70; // "p" for pointer
  1589. targetView.setUint32(position, referee.id);
  1590. position += 4;
  1591. return
  1592. } else
  1593. referenceMap.set(value, { offset: position - start });
  1594. }
  1595. let constructor = value.constructor;
  1596. if (constructor === Object) {
  1597. writeObject(value);
  1598. } else if (constructor === Array) {
  1599. packArray(value);
  1600. } else if (constructor === Map) {
  1601. if (this.mapAsEmptyObject) target[position++] = 0x80;
  1602. else {
  1603. length = value.size;
  1604. if (length < 0x10) {
  1605. target[position++] = 0x80 | length;
  1606. } else if (length < 0x10000) {
  1607. target[position++] = 0xde;
  1608. target[position++] = length >> 8;
  1609. target[position++] = length & 0xff;
  1610. } else {
  1611. target[position++] = 0xdf;
  1612. targetView.setUint32(position, length);
  1613. position += 4;
  1614. }
  1615. for (let [key, entryValue] of value) {
  1616. pack(key);
  1617. pack(entryValue);
  1618. }
  1619. }
  1620. } else {
  1621. for (let i = 0, l = extensions.length; i < l; i++) {
  1622. let extensionClass = extensionClasses[i];
  1623. if (value instanceof extensionClass) {
  1624. let extension = extensions[i];
  1625. if (extension.write) {
  1626. if (extension.type) {
  1627. target[position++] = 0xd4; // one byte "tag" extension
  1628. target[position++] = extension.type;
  1629. target[position++] = 0;
  1630. }
  1631. let writeResult = extension.write.call(this, value);
  1632. if (writeResult === value) { // avoid infinite recursion
  1633. if (Array.isArray(value)) {
  1634. packArray(value);
  1635. } else {
  1636. writeObject(value);
  1637. }
  1638. } else {
  1639. pack(writeResult);
  1640. }
  1641. return
  1642. }
  1643. let currentTarget = target;
  1644. let currentTargetView = targetView;
  1645. let currentPosition = position;
  1646. target = null;
  1647. let result;
  1648. try {
  1649. result = extension.pack.call(this, value, (size) => {
  1650. // restore target and use it
  1651. target = currentTarget;
  1652. currentTarget = null;
  1653. position += size;
  1654. if (position > safeEnd)
  1655. makeRoom(position);
  1656. return {
  1657. target, targetView, position: position - size
  1658. }
  1659. }, pack);
  1660. } finally {
  1661. // restore current target information (unless already restored)
  1662. if (currentTarget) {
  1663. target = currentTarget;
  1664. targetView = currentTargetView;
  1665. position = currentPosition;
  1666. safeEnd = target.length - 10;
  1667. }
  1668. }
  1669. if (result) {
  1670. if (result.length + position > safeEnd)
  1671. makeRoom(result.length + position);
  1672. position = writeExtensionData(result, target, position, extension.type);
  1673. }
  1674. return
  1675. }
  1676. }
  1677. // check isArray after extensions, because extensions can extend Array
  1678. if (Array.isArray(value)) {
  1679. packArray(value);
  1680. } else {
  1681. // use this as an alternate mechanism for expressing how to serialize
  1682. if (value.toJSON) {
  1683. const json = value.toJSON();
  1684. // if for some reason value.toJSON returns itself it'll loop forever
  1685. if (json !== value)
  1686. return pack(json)
  1687. }
  1688. // if there is a writeFunction, use it, otherwise just encode as undefined
  1689. if (type === 'function')
  1690. return pack(this.writeFunction && this.writeFunction(value));
  1691. // no extension found, write as plain object
  1692. writeObject(value);
  1693. }
  1694. }
  1695. }
  1696. } else if (type === 'boolean') {
  1697. target[position++] = value ? 0xc3 : 0xc2;
  1698. } else if (type === 'bigint') {
  1699. if (value < 0x8000000000000000 && value >= -0x8000000000000000) {
  1700. // use a signed int as long as it fits
  1701. target[position++] = 0xd3;
  1702. targetView.setBigInt64(position, value);
  1703. } else if (value < 0x10000000000000000 && value > 0) {
  1704. // if we can fit an unsigned int, use that
  1705. target[position++] = 0xcf;
  1706. targetView.setBigUint64(position, value);
  1707. } else {
  1708. // overflow
  1709. if (this.largeBigIntToFloat) {
  1710. target[position++] = 0xcb;
  1711. targetView.setFloat64(position, Number(value));
  1712. } else if (this.largeBigIntToString) {
  1713. return pack(value.toString());
  1714. } else if (this.useBigIntExtension || this.moreTypes) {
  1715. let empty = value < 0 ? BigInt(-1) : BigInt(0);
  1716. let array;
  1717. if (value >> BigInt(0x10000) === empty) {
  1718. let mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow
  1719. let chunks = [];
  1720. while (true) {
  1721. chunks.push(value & mask);
  1722. if ((value >> BigInt(63)) === empty) break
  1723. value >>= BigInt(64);
  1724. }
  1725. array = new Uint8Array(new BigUint64Array(chunks).buffer);
  1726. array.reverse();
  1727. } else {
  1728. let invert = value < 0;
  1729. let string = (invert ? ~value : value).toString(16);
  1730. if (string.length % 2) {
  1731. string = '0' + string;
  1732. } else if (parseInt(string.charAt(0), 16) >= 8) {
  1733. string = '00' + string;
  1734. }
  1735. if (hasNodeBuffer$1) {
  1736. array = Buffer.from(string, 'hex');
  1737. } else {
  1738. array = new Uint8Array(string.length / 2);
  1739. for (let i = 0; i < array.length; i++) {
  1740. array[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);
  1741. }
  1742. }
  1743. if (invert) {
  1744. for (let i = 0; i < array.length; i++) array[i] = ~array[i];
  1745. }
  1746. }
  1747. if (array.length + position > safeEnd)
  1748. makeRoom(array.length + position);
  1749. position = writeExtensionData(array, target, position, 0x42);
  1750. return
  1751. } else {
  1752. throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
  1753. ' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +
  1754. ' largeBigIntToString to convert to string')
  1755. }
  1756. }
  1757. position += 8;
  1758. } else if (type === 'undefined') {
  1759. if (this.encodeUndefinedAsNil)
  1760. target[position++] = 0xc0;
  1761. else {
  1762. target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
  1763. target[position++] = 0;
  1764. target[position++] = 0;
  1765. }
  1766. } else {
  1767. throw new Error('Unknown type: ' + type)
  1768. }
  1769. };
  1770. const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {
  1771. // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
  1772. let keys;
  1773. if (this.skipValues) {
  1774. keys = [];
  1775. for (let key in object) {
  1776. if ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&
  1777. !this.skipValues.includes(object[key]))
  1778. keys.push(key);
  1779. }
  1780. } else {
  1781. keys = Object.keys(object);
  1782. }
  1783. let length = keys.length;
  1784. if (length < 0x10) {
  1785. target[position++] = 0x80 | length;
  1786. } else if (length < 0x10000) {
  1787. target[position++] = 0xde;
  1788. target[position++] = length >> 8;
  1789. target[position++] = length & 0xff;
  1790. } else {
  1791. target[position++] = 0xdf;
  1792. targetView.setUint32(position, length);
  1793. position += 4;
  1794. }
  1795. let key;
  1796. if (this.coercibleKeyAsNumber) {
  1797. for (let i = 0; i < length; i++) {
  1798. key = keys[i];
  1799. let num = Number(key);
  1800. pack(isNaN(num) ? key : num);
  1801. pack(object[key]);
  1802. }
  1803. } else {
  1804. for (let i = 0; i < length; i++) {
  1805. pack(key = keys[i]);
  1806. pack(object[key]);
  1807. }
  1808. }
  1809. } :
  1810. (object) => {
  1811. target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
  1812. let objectOffset = position - start;
  1813. position += 2;
  1814. let size = 0;
  1815. for (let key in object) {
  1816. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1817. pack(key);
  1818. pack(object[key]);
  1819. size++;
  1820. }
  1821. }
  1822. if (size > 0xffff) {
  1823. throw new Error('Object is too large to serialize with fast 16-bit map size,' +
  1824. ' use the "variableMapSize" option to serialize this object');
  1825. }
  1826. target[objectOffset++ + start] = size >> 8;
  1827. target[objectOffset + start] = size & 0xff;
  1828. };
  1829. const writeRecord = this.useRecords === false ? writePlainObject :
  1830. (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)
  1831. (object) => {
  1832. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1833. let objectOffset = position++ - start;
  1834. let wroteKeys;
  1835. for (let key in object) {
  1836. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1837. nextTransition = transition[key];
  1838. if (nextTransition)
  1839. transition = nextTransition;
  1840. else {
  1841. // record doesn't exist, create full new record and insert it
  1842. let keys = Object.keys(object);
  1843. let lastTransition = transition;
  1844. transition = structures.transitions;
  1845. let newTransitions = 0;
  1846. for (let i = 0, l = keys.length; i < l; i++) {
  1847. let key = keys[i];
  1848. nextTransition = transition[key];
  1849. if (!nextTransition) {
  1850. nextTransition = transition[key] = Object.create(null);
  1851. newTransitions++;
  1852. }
  1853. transition = nextTransition;
  1854. }
  1855. if (objectOffset + start + 1 == position) {
  1856. // first key, so we don't need to insert, we can just write record directly
  1857. position--;
  1858. newRecord(transition, keys, newTransitions);
  1859. } else // otherwise we need to insert the record, moving existing data after the record
  1860. insertNewRecord(transition, keys, objectOffset, newTransitions);
  1861. wroteKeys = true;
  1862. transition = lastTransition[key];
  1863. }
  1864. pack(object[key]);
  1865. }
  1866. }
  1867. if (!wroteKeys) {
  1868. let recordId = transition[RECORD_SYMBOL];
  1869. if (recordId)
  1870. target[objectOffset + start] = recordId;
  1871. else
  1872. insertNewRecord(transition, Object.keys(object), objectOffset, 0);
  1873. }
  1874. } :
  1875. (object) => {
  1876. let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
  1877. let newTransitions = 0;
  1878. for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1879. nextTransition = transition[key];
  1880. if (!nextTransition) {
  1881. nextTransition = transition[key] = Object.create(null);
  1882. newTransitions++;
  1883. }
  1884. transition = nextTransition;
  1885. }
  1886. let recordId = transition[RECORD_SYMBOL];
  1887. if (recordId) {
  1888. if (recordId >= 0x60 && useTwoByteRecords) {
  1889. target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
  1890. target[position++] = recordId >> 5;
  1891. } else
  1892. target[position++] = recordId;
  1893. } else {
  1894. newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
  1895. }
  1896. // now write the values
  1897. for (let key in object)
  1898. if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
  1899. pack(object[key]);
  1900. }
  1901. };
  1902. // create reference to useRecords if useRecords is a function
  1903. const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
  1904. const writeObject = checkUseRecords ? (object) => {
  1905. checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
  1906. } : writeRecord;
  1907. const makeRoom = (end) => {
  1908. let newSize;
  1909. if (end > 0x1000000) {
  1910. // special handling for really large buffers
  1911. if ((end - start) > MAX_BUFFER_SIZE)
  1912. throw new Error('Packed buffer would be larger than maximum buffer size')
  1913. newSize = Math.min(MAX_BUFFER_SIZE,
  1914. Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
  1915. } else // faster handling for smaller buffers
  1916. newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
  1917. let newBuffer = new ByteArrayAllocate(newSize);
  1918. targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
  1919. end = Math.min(end, target.length);
  1920. if (target.copy)
  1921. target.copy(newBuffer, 0, start, end);
  1922. else
  1923. newBuffer.set(target.slice(start, end));
  1924. position -= start;
  1925. start = 0;
  1926. safeEnd = newBuffer.length - 10;
  1927. return target = newBuffer
  1928. };
  1929. const newRecord = (transition, keys, newTransitions) => {
  1930. let recordId = structures.nextId;
  1931. if (!recordId)
  1932. recordId = 0x40;
  1933. if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
  1934. recordId = structures.nextOwnId;
  1935. if (!(recordId < maxStructureId))
  1936. recordId = sharedLimitId;
  1937. structures.nextOwnId = recordId + 1;
  1938. } else {
  1939. if (recordId >= maxStructureId)// cycle back around
  1940. recordId = sharedLimitId;
  1941. structures.nextId = recordId + 1;
  1942. }
  1943. let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
  1944. transition[RECORD_SYMBOL] = recordId;
  1945. transition.__keys__ = keys;
  1946. structures[recordId - 0x40] = keys;
  1947. if (recordId < sharedLimitId) {
  1948. keys.isShared = true;
  1949. structures.sharedLength = recordId - 0x3f;
  1950. hasSharedUpdate = true;
  1951. if (highByte >= 0) {
  1952. target[position++] = (recordId & 0x1f) + 0x60;
  1953. target[position++] = highByte;
  1954. } else {
  1955. target[position++] = recordId;
  1956. }
  1957. } else {
  1958. if (highByte >= 0) {
  1959. target[position++] = 0xd5; // fixext 2
  1960. target[position++] = 0x72; // "r" record defintion extension type
  1961. target[position++] = (recordId & 0x1f) + 0x60;
  1962. target[position++] = highByte;
  1963. } else {
  1964. target[position++] = 0xd4; // fixext 1
  1965. target[position++] = 0x72; // "r" record defintion extension type
  1966. target[position++] = recordId;
  1967. }
  1968. if (newTransitions)
  1969. transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
  1970. // record the removal of the id, we can maintain our shared structure
  1971. if (recordIdsToRemove.length >= maxOwnStructures)
  1972. recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
  1973. recordIdsToRemove.push(transition);
  1974. pack(keys);
  1975. }
  1976. };
  1977. const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
  1978. let mainTarget = target;
  1979. let mainPosition = position;
  1980. let mainSafeEnd = safeEnd;
  1981. let mainStart = start;
  1982. target = keysTarget;
  1983. position = 0;
  1984. start = 0;
  1985. if (!target)
  1986. keysTarget = target = new ByteArrayAllocate(8192);
  1987. safeEnd = target.length - 10;
  1988. newRecord(transition, keys, newTransitions);
  1989. keysTarget = target;
  1990. let keysPosition = position;
  1991. target = mainTarget;
  1992. position = mainPosition;
  1993. safeEnd = mainSafeEnd;
  1994. start = mainStart;
  1995. if (keysPosition > 1) {
  1996. let newEnd = position + keysPosition - 1;
  1997. if (newEnd > safeEnd)
  1998. makeRoom(newEnd);
  1999. let insertionPosition = insertionOffset + start;
  2000. target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
  2001. target.set(keysTarget.slice(0, keysPosition), insertionPosition);
  2002. position = newEnd;
  2003. } else {
  2004. target[insertionOffset + start] = keysTarget[0];
  2005. }
  2006. };
  2007. const writeStruct = (object) => {
  2008. let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
  2009. if (notifySharedUpdate)
  2010. return hasSharedUpdate = true;
  2011. position = newPosition;
  2012. let startTarget = target;
  2013. pack(value);
  2014. resetStructures();
  2015. if (startTarget !== target) {
  2016. return { position, targetView, target }; // indicate the buffer was re-allocated
  2017. }
  2018. return position;
  2019. }, this);
  2020. if (newPosition === 0) // bail and go to a msgpack object
  2021. return writeObject(object);
  2022. position = newPosition;
  2023. };
  2024. }
  2025. useBuffer(buffer) {
  2026. // this means we are finished using our own buffer and we can write over it safely
  2027. target = buffer;
  2028. target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));
  2029. targetView = target.dataView;
  2030. position = 0;
  2031. }
  2032. set position (value) {
  2033. position = value;
  2034. }
  2035. get position() {
  2036. return position;
  2037. }
  2038. clearSharedData() {
  2039. if (this.structures)
  2040. this.structures = [];
  2041. if (this.typedStructs)
  2042. this.typedStructs = [];
  2043. }
  2044. }
  2045. extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];
  2046. extensions = [{
  2047. pack(date, allocateForWrite, pack) {
  2048. let seconds = date.getTime() / 1000;
  2049. if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
  2050. // Timestamp 32
  2051. let { target, targetView, position} = allocateForWrite(6);
  2052. target[position++] = 0xd6;
  2053. target[position++] = 0xff;
  2054. targetView.setUint32(position, seconds);
  2055. } else if (seconds > 0 && seconds < 0x100000000) {
  2056. // Timestamp 64
  2057. let { target, targetView, position} = allocateForWrite(10);
  2058. target[position++] = 0xd7;
  2059. target[position++] = 0xff;
  2060. targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
  2061. targetView.setUint32(position + 4, seconds);
  2062. } else if (isNaN(seconds)) {
  2063. if (this.onInvalidDate) {
  2064. allocateForWrite(0);
  2065. return pack(this.onInvalidDate())
  2066. }
  2067. // Intentionally invalid timestamp
  2068. let { target, targetView, position} = allocateForWrite(3);
  2069. target[position++] = 0xd4;
  2070. target[position++] = 0xff;
  2071. target[position++] = 0xff;
  2072. } else {
  2073. // Timestamp 96
  2074. let { target, targetView, position} = allocateForWrite(15);
  2075. target[position++] = 0xc7;
  2076. target[position++] = 12;
  2077. target[position++] = 0xff;
  2078. targetView.setUint32(position, date.getMilliseconds() * 1000000);
  2079. targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
  2080. }
  2081. }
  2082. }, {
  2083. pack(set, allocateForWrite, pack) {
  2084. if (this.setAsEmptyObject) {
  2085. allocateForWrite(0);
  2086. return pack({})
  2087. }
  2088. let array = Array.from(set);
  2089. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2090. if (this.moreTypes) {
  2091. target[position++] = 0xd4;
  2092. target[position++] = 0x73; // 's' for Set
  2093. target[position++] = 0;
  2094. }
  2095. pack(array);
  2096. }
  2097. }, {
  2098. pack(error, allocateForWrite, pack) {
  2099. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2100. if (this.moreTypes) {
  2101. target[position++] = 0xd4;
  2102. target[position++] = 0x65; // 'e' for error
  2103. target[position++] = 0;
  2104. }
  2105. pack([ error.name, error.message, error.cause ]);
  2106. }
  2107. }, {
  2108. pack(regex, allocateForWrite, pack) {
  2109. let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
  2110. if (this.moreTypes) {
  2111. target[position++] = 0xd4;
  2112. target[position++] = 0x78; // 'x' for regeXp
  2113. target[position++] = 0;
  2114. }
  2115. pack([ regex.source, regex.flags ]);
  2116. }
  2117. }, {
  2118. pack(arrayBuffer, allocateForWrite) {
  2119. if (this.moreTypes)
  2120. writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
  2121. else
  2122. writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2123. }
  2124. }, {
  2125. pack(typedArray, allocateForWrite) {
  2126. let constructor = typedArray.constructor;
  2127. if (constructor !== ByteArray && this.moreTypes)
  2128. writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
  2129. else
  2130. writeBuffer(typedArray, allocateForWrite);
  2131. }
  2132. }, {
  2133. pack(arrayBuffer, allocateForWrite) {
  2134. if (this.moreTypes)
  2135. writeExtBuffer(arrayBuffer, 0x11, allocateForWrite);
  2136. else
  2137. writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
  2138. }
  2139. }, {
  2140. pack(c1, allocateForWrite) { // specific 0xC1 object
  2141. let { target, position} = allocateForWrite(1);
  2142. target[position] = 0xc1;
  2143. }
  2144. }];
  2145. function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
  2146. let length = typedArray.byteLength;
  2147. if (length + 1 < 0x100) {
  2148. var { target, position } = allocateForWrite(4 + length);
  2149. target[position++] = 0xc7;
  2150. target[position++] = length + 1;
  2151. } else if (length + 1 < 0x10000) {
  2152. var { target, position } = allocateForWrite(5 + length);
  2153. target[position++] = 0xc8;
  2154. target[position++] = (length + 1) >> 8;
  2155. target[position++] = (length + 1) & 0xff;
  2156. } else {
  2157. var { target, position, targetView } = allocateForWrite(7 + length);
  2158. target[position++] = 0xc9;
  2159. targetView.setUint32(position, length + 1); // plus one for the type byte
  2160. position += 4;
  2161. }
  2162. target[position++] = 0x74; // "t" for typed array
  2163. target[position++] = type;
  2164. if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
  2165. target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
  2166. }
  2167. function writeBuffer(buffer, allocateForWrite) {
  2168. let length = buffer.byteLength;
  2169. var target, position;
  2170. if (length < 0x100) {
  2171. var { target, position } = allocateForWrite(length + 2);
  2172. target[position++] = 0xc4;
  2173. target[position++] = length;
  2174. } else if (length < 0x10000) {
  2175. var { target, position } = allocateForWrite(length + 3);
  2176. target[position++] = 0xc5;
  2177. target[position++] = length >> 8;
  2178. target[position++] = length & 0xff;
  2179. } else {
  2180. var { target, position, targetView } = allocateForWrite(length + 5);
  2181. target[position++] = 0xc6;
  2182. targetView.setUint32(position, length);
  2183. position += 4;
  2184. }
  2185. target.set(buffer, position);
  2186. }
  2187. function writeExtensionData(result, target, position, type) {
  2188. let length = result.length;
  2189. switch (length) {
  2190. case 1:
  2191. target[position++] = 0xd4;
  2192. break
  2193. case 2:
  2194. target[position++] = 0xd5;
  2195. break
  2196. case 4:
  2197. target[position++] = 0xd6;
  2198. break
  2199. case 8:
  2200. target[position++] = 0xd7;
  2201. break
  2202. case 16:
  2203. target[position++] = 0xd8;
  2204. break
  2205. default:
  2206. if (length < 0x100) {
  2207. target[position++] = 0xc7;
  2208. target[position++] = length;
  2209. } else if (length < 0x10000) {
  2210. target[position++] = 0xc8;
  2211. target[position++] = length >> 8;
  2212. target[position++] = length & 0xff;
  2213. } else {
  2214. target[position++] = 0xc9;
  2215. target[position++] = length >> 24;
  2216. target[position++] = (length >> 16) & 0xff;
  2217. target[position++] = (length >> 8) & 0xff;
  2218. target[position++] = length & 0xff;
  2219. }
  2220. }
  2221. target[position++] = type;
  2222. target.set(result, position);
  2223. position += length;
  2224. return position
  2225. }
  2226. function insertIds(serialized, idsToInsert) {
  2227. // insert the ids that need to be referenced for structured clones
  2228. let nextId;
  2229. let distanceToMove = idsToInsert.length * 6;
  2230. let lastEnd = serialized.length - distanceToMove;
  2231. while (nextId = idsToInsert.pop()) {
  2232. let offset = nextId.offset;
  2233. let id = nextId.id;
  2234. serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
  2235. distanceToMove -= 6;
  2236. let position = offset + distanceToMove;
  2237. serialized[position++] = 0xd6;
  2238. serialized[position++] = 0x69; // 'i'
  2239. serialized[position++] = id >> 24;
  2240. serialized[position++] = (id >> 16) & 0xff;
  2241. serialized[position++] = (id >> 8) & 0xff;
  2242. serialized[position++] = id & 0xff;
  2243. lastEnd = offset;
  2244. }
  2245. return serialized
  2246. }
  2247. function writeBundles(start, pack, incrementPosition) {
  2248. if (bundledStrings.length > 0) {
  2249. targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
  2250. bundledStrings.stringsPosition = position - start;
  2251. let writeStrings = bundledStrings;
  2252. bundledStrings = null;
  2253. pack(writeStrings[0]);
  2254. pack(writeStrings[1]);
  2255. }
  2256. }
  2257. function addExtension(extension) {
  2258. if (extension.Class) {
  2259. if (!extension.pack && !extension.write)
  2260. throw new Error('Extension has no pack or write function')
  2261. if (extension.pack && !extension.type)
  2262. throw new Error('Extension has no type (numeric code to identify the extension)')
  2263. extensionClasses.unshift(extension.Class);
  2264. extensions.unshift(extension);
  2265. }
  2266. addExtension$1(extension);
  2267. }
  2268. function prepareStructures$1(structures, packr) {
  2269. structures.isCompatible = (existingStructures) => {
  2270. let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
  2271. if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
  2272. packr._mergeStructures(existingStructures);
  2273. return compatible;
  2274. };
  2275. return structures
  2276. }
  2277. function setWriteStructSlots(writeSlots, makeStructures) {
  2278. writeStructSlots = writeSlots;
  2279. prepareStructures$1 = makeStructures;
  2280. }
  2281. let defaultPackr = new Packr({ useRecords: false });
  2282. const pack = defaultPackr.pack;
  2283. const encode = defaultPackr.pack;
  2284. const Encoder = Packr;
  2285. const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
  2286. const REUSE_BUFFER_MODE = 512;
  2287. const RESET_BUFFER_MODE = 1024;
  2288. const RESERVE_START_SPACE = 2048;
  2289. 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)
  2290. const NUMBER = 0;
  2291. const UTF8 = 2;
  2292. const OBJECT_DATA = 1;
  2293. const DATE = 16;
  2294. const TYPE_NAMES = ['num', 'object', 'string', 'ascii'];
  2295. TYPE_NAMES[DATE] = 'date';
  2296. const float32Headers = [false, true, true, false, false, true, true, false];
  2297. let evalSupported;
  2298. try {
  2299. new Function('');
  2300. evalSupported = true;
  2301. } catch(error) {
  2302. // if eval variants are not supported, do not create inline object readers ever
  2303. }
  2304. let updatedPosition;
  2305. const hasNodeBuffer = typeof Buffer !== 'undefined';
  2306. let textEncoder, currentSource;
  2307. try {
  2308. textEncoder = new TextEncoder();
  2309. } catch (error) {}
  2310. const encodeUtf8 = hasNodeBuffer ? function(target, string, position) {
  2311. return target.utf8Write(string, position, target.byteLength - position)
  2312. } : (textEncoder && textEncoder.encodeInto) ?
  2313. function(target, string, position) {
  2314. return textEncoder.encodeInto(string, target.subarray(position)).written
  2315. } : false;
  2316. setWriteStructSlots(writeStruct, prepareStructures);
  2317. function writeStruct(object, target, encodingStart, position, structures, makeRoom, pack, packr) {
  2318. let typedStructs = packr.typedStructs || (packr.typedStructs = []);
  2319. // note that we rely on pack.js to load stored structures before we get to this point
  2320. let targetView = target.dataView;
  2321. let refsStartPosition = (typedStructs.lastStringStart || 100) + position;
  2322. let safeEnd = target.length - 10;
  2323. let start = position;
  2324. if (position > safeEnd) {
  2325. target = makeRoom(position);
  2326. targetView = target.dataView;
  2327. position -= encodingStart;
  2328. start -= encodingStart;
  2329. refsStartPosition -= encodingStart;
  2330. encodingStart = 0;
  2331. safeEnd = target.length - 10;
  2332. }
  2333. let refOffset, refPosition = refsStartPosition;
  2334. let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
  2335. let nextId = typedStructs.nextId || typedStructs.length;
  2336. let headerSize =
  2337. nextId < 0xf ? 1 :
  2338. nextId < 0xf0 ? 2 :
  2339. nextId < 0xf000 ? 3 :
  2340. nextId < 0xf00000 ? 4 : 0;
  2341. if (headerSize === 0)
  2342. return 0;
  2343. position += headerSize;
  2344. let queuedReferences = [];
  2345. let usedAscii0;
  2346. let keyIndex = 0;
  2347. for (let key in object) {
  2348. let value = object[key];
  2349. let nextTransition = transition[key];
  2350. if (!nextTransition) {
  2351. transition[key] = nextTransition = {
  2352. key,
  2353. parent: transition,
  2354. enumerationOffset: 0,
  2355. ascii0: null,
  2356. ascii8: null,
  2357. num8: null,
  2358. string16: null,
  2359. object16: null,
  2360. num32: null,
  2361. float64: null,
  2362. date64: null
  2363. };
  2364. }
  2365. if (position > safeEnd) {
  2366. target = makeRoom(position);
  2367. targetView = target.dataView;
  2368. position -= encodingStart;
  2369. start -= encodingStart;
  2370. refsStartPosition -= encodingStart;
  2371. refPosition -= encodingStart;
  2372. encodingStart = 0;
  2373. safeEnd = target.length - 10;
  2374. }
  2375. switch (typeof value) {
  2376. case 'number':
  2377. let number = value;
  2378. // first check to see if we are using a lot of ids and should default to wide/common format
  2379. if (nextId < 200 || !nextTransition.num64) {
  2380. if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
  2381. if (number < 0xf6 && number >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number < 0x20 && !nextTransition.num32)) {
  2382. transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1);
  2383. target[position++] = number;
  2384. } else {
  2385. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2386. targetView.setUint32(position, number, true);
  2387. position += 4;
  2388. }
  2389. break;
  2390. } else if (number < 0x100000000 && number >= -0x80000000) {
  2391. targetView.setFloat32(position, number, true);
  2392. if (float32Headers[target[position + 3] >>> 5]) {
  2393. let xShifted;
  2394. // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2395. if (((xShifted = number * mult10[((target[position + 3] & 0x7f) << 1) | (target[position + 2] >> 7)]) >> 0) === xShifted) {
  2396. transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4);
  2397. position += 4;
  2398. break;
  2399. }
  2400. }
  2401. }
  2402. }
  2403. transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8);
  2404. targetView.setFloat64(position, number, true);
  2405. position += 8;
  2406. break;
  2407. case 'string':
  2408. let strLength = value.length;
  2409. refOffset = refPosition - refsStartPosition;
  2410. if ((strLength << 2) + refPosition > safeEnd) {
  2411. target = makeRoom((strLength << 2) + refPosition);
  2412. targetView = target.dataView;
  2413. position -= encodingStart;
  2414. start -= encodingStart;
  2415. refsStartPosition -= encodingStart;
  2416. refPosition -= encodingStart;
  2417. encodingStart = 0;
  2418. safeEnd = target.length - 10;
  2419. }
  2420. if (strLength > ((0xff00 + refOffset) >> 2)) {
  2421. queuedReferences.push(key, value, position - start);
  2422. break;
  2423. }
  2424. let isNotAscii;
  2425. let strStart = refPosition;
  2426. if (strLength < 0x40) {
  2427. let i, c1, c2;
  2428. for (i = 0; i < strLength; i++) {
  2429. c1 = value.charCodeAt(i);
  2430. if (c1 < 0x80) {
  2431. target[refPosition++] = c1;
  2432. } else if (c1 < 0x800) {
  2433. isNotAscii = true;
  2434. target[refPosition++] = c1 >> 6 | 0xc0;
  2435. target[refPosition++] = c1 & 0x3f | 0x80;
  2436. } else if (
  2437. (c1 & 0xfc00) === 0xd800 &&
  2438. ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
  2439. ) {
  2440. isNotAscii = true;
  2441. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  2442. i++;
  2443. target[refPosition++] = c1 >> 18 | 0xf0;
  2444. target[refPosition++] = c1 >> 12 & 0x3f | 0x80;
  2445. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2446. target[refPosition++] = c1 & 0x3f | 0x80;
  2447. } else {
  2448. isNotAscii = true;
  2449. target[refPosition++] = c1 >> 12 | 0xe0;
  2450. target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
  2451. target[refPosition++] = c1 & 0x3f | 0x80;
  2452. }
  2453. }
  2454. } else {
  2455. refPosition += encodeUtf8(target, value, refPosition);
  2456. isNotAscii = refPosition - strStart > strLength;
  2457. }
  2458. if (refOffset < 0xa0 || (refOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
  2459. // short strings
  2460. if (isNotAscii) {
  2461. if (!(transition = nextTransition.string8)) {
  2462. if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
  2463. // we can safely change ascii to utf8 in place since they are compatible
  2464. transition.__type = UTF8;
  2465. nextTransition.ascii8 = null;
  2466. nextTransition.string8 = transition;
  2467. pack(null, 0, true); // special call to notify that structures have been updated
  2468. } else {
  2469. transition = createTypeTransition(nextTransition, UTF8, 1);
  2470. }
  2471. }
  2472. } else if (refOffset === 0 && !usedAscii0) {
  2473. usedAscii0 = true;
  2474. transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0);
  2475. break; // don't increment position
  2476. }// else ascii:
  2477. else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8)))
  2478. transition = createTypeTransition(nextTransition, ASCII, 1);
  2479. target[position++] = refOffset;
  2480. } else {
  2481. // TODO: Enable ascii16 at some point, but get the logic right
  2482. //if (isNotAscii)
  2483. transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2);
  2484. //else
  2485. //transition = nextTransition.ascii16 || createTypeTransition(nextTransition, ASCII, 2);
  2486. targetView.setUint16(position, refOffset, true);
  2487. position += 2;
  2488. }
  2489. break;
  2490. case 'object':
  2491. if (value) {
  2492. if (value.constructor === Date) {
  2493. transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8);
  2494. targetView.setFloat64(position, value.getTime(), true);
  2495. position += 8;
  2496. } else {
  2497. queuedReferences.push(key, value, keyIndex);
  2498. }
  2499. break;
  2500. } else { // null
  2501. nextTransition = anyType(nextTransition, position, targetView, -10); // match CBOR with this
  2502. if (nextTransition) {
  2503. transition = nextTransition;
  2504. position = updatedPosition;
  2505. } else queuedReferences.push(key, value, keyIndex);
  2506. }
  2507. break;
  2508. case 'boolean':
  2509. transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1);
  2510. target[position++] = value ? 0xf9 : 0xf8; // match CBOR with these
  2511. break;
  2512. case 'undefined':
  2513. nextTransition = anyType(nextTransition, position, targetView, -9); // match CBOR with this
  2514. if (nextTransition) {
  2515. transition = nextTransition;
  2516. position = updatedPosition;
  2517. } else queuedReferences.push(key, value, keyIndex);
  2518. break;
  2519. default:
  2520. queuedReferences.push(key, value, keyIndex);
  2521. }
  2522. keyIndex++;
  2523. }
  2524. for (let i = 0, l = queuedReferences.length; i < l;) {
  2525. let key = queuedReferences[i++];
  2526. let value = queuedReferences[i++];
  2527. let propertyIndex = queuedReferences[i++];
  2528. let nextTransition = transition[key];
  2529. if (!nextTransition) {
  2530. transition[key] = nextTransition = {
  2531. key,
  2532. parent: transition,
  2533. enumerationOffset: propertyIndex - keyIndex,
  2534. ascii0: null,
  2535. ascii8: null,
  2536. num8: null,
  2537. string16: null,
  2538. object16: null,
  2539. num32: null,
  2540. float64: null
  2541. };
  2542. }
  2543. let newPosition;
  2544. if (value) {
  2545. /*if (typeof value === 'string') { // TODO: we could re-enable long strings
  2546. if (position + value.length * 3 > safeEnd) {
  2547. target = makeRoom(position + value.length * 3);
  2548. position -= start;
  2549. targetView = target.dataView;
  2550. start = 0;
  2551. }
  2552. newPosition = position + target.utf8Write(value, position, 0xffffffff);
  2553. } else { */
  2554. let size;
  2555. refOffset = refPosition - refsStartPosition;
  2556. if (refOffset < 0xff00) {
  2557. transition = nextTransition.object16;
  2558. if (transition)
  2559. size = 2;
  2560. else if ((transition = nextTransition.object32))
  2561. size = 4;
  2562. else {
  2563. transition = createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2564. size = 2;
  2565. }
  2566. } else {
  2567. transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4);
  2568. size = 4;
  2569. }
  2570. newPosition = pack(value, refPosition);
  2571. //}
  2572. if (typeof newPosition === 'object') {
  2573. // re-allocated
  2574. refPosition = newPosition.position;
  2575. targetView = newPosition.targetView;
  2576. target = newPosition.target;
  2577. refsStartPosition -= encodingStart;
  2578. position -= encodingStart;
  2579. start -= encodingStart;
  2580. encodingStart = 0;
  2581. } else
  2582. refPosition = newPosition;
  2583. if (size === 2) {
  2584. targetView.setUint16(position, refOffset, true);
  2585. position += 2;
  2586. } else {
  2587. targetView.setUint32(position, refOffset, true);
  2588. position += 4;
  2589. }
  2590. } else { // null or undefined
  2591. transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2);
  2592. targetView.setInt16(position, value === null ? -10 : -9, true);
  2593. position += 2;
  2594. }
  2595. keyIndex++;
  2596. }
  2597. let recordId = transition[RECORD_SYMBOL];
  2598. if (recordId == null) {
  2599. recordId = packr.typedStructs.length;
  2600. let structure = [];
  2601. let nextTransition = transition;
  2602. let key, type;
  2603. while ((type = nextTransition.__type) !== undefined) {
  2604. let size = nextTransition.__size;
  2605. nextTransition = nextTransition.__parent;
  2606. key = nextTransition.key;
  2607. let property = [type, size, key];
  2608. if (nextTransition.enumerationOffset)
  2609. property.push(nextTransition.enumerationOffset);
  2610. structure.push(property);
  2611. nextTransition = nextTransition.parent;
  2612. }
  2613. structure.reverse();
  2614. transition[RECORD_SYMBOL] = recordId;
  2615. packr.typedStructs[recordId] = structure;
  2616. pack(null, 0, true); // special call to notify that structures have been updated
  2617. }
  2618. switch (headerSize) {
  2619. case 1:
  2620. if (recordId >= 0x10) return 0;
  2621. target[start] = recordId + 0x20;
  2622. break;
  2623. case 2:
  2624. if (recordId >= 0x100) return 0;
  2625. target[start] = 0x38;
  2626. target[start + 1] = recordId;
  2627. break;
  2628. case 3:
  2629. if (recordId >= 0x10000) return 0;
  2630. target[start] = 0x39;
  2631. targetView.setUint16(start + 1, recordId, true);
  2632. break;
  2633. case 4:
  2634. if (recordId >= 0x1000000) return 0;
  2635. targetView.setUint32(start, (recordId << 8) + 0x3a, true);
  2636. break;
  2637. }
  2638. if (position < refsStartPosition) {
  2639. if (refsStartPosition === refPosition)
  2640. return position; // no refs
  2641. // adjust positioning
  2642. target.copyWithin(position, refsStartPosition, refPosition);
  2643. refPosition += position - refsStartPosition;
  2644. typedStructs.lastStringStart = position - start;
  2645. } else if (position > refsStartPosition) {
  2646. if (refsStartPosition === refPosition)
  2647. return position; // no refs
  2648. typedStructs.lastStringStart = position - start;
  2649. return writeStruct(object, target, encodingStart, start, structures, makeRoom, pack, packr);
  2650. }
  2651. return refPosition;
  2652. }
  2653. function anyType(transition, position, targetView, value) {
  2654. let nextTransition;
  2655. if ((nextTransition = transition.ascii8 || transition.num8)) {
  2656. targetView.setInt8(position, value, true);
  2657. updatedPosition = position + 1;
  2658. return nextTransition;
  2659. }
  2660. if ((nextTransition = transition.string16 || transition.object16)) {
  2661. targetView.setInt16(position, value, true);
  2662. updatedPosition = position + 2;
  2663. return nextTransition;
  2664. }
  2665. if (nextTransition = transition.num32) {
  2666. targetView.setUint32(position, 0xe0000100 + value, true);
  2667. updatedPosition = position + 4;
  2668. return nextTransition;
  2669. }
  2670. // transition.float64
  2671. if (nextTransition = transition.num64) {
  2672. targetView.setFloat64(position, NaN, true);
  2673. targetView.setInt8(position, value);
  2674. updatedPosition = position + 8;
  2675. return nextTransition;
  2676. }
  2677. updatedPosition = position;
  2678. // TODO: can we do an "any" type where we defer the decision?
  2679. return;
  2680. }
  2681. function createTypeTransition(transition, type, size) {
  2682. let typeName = TYPE_NAMES[type] + (size << 3);
  2683. let newTransition = transition[typeName] || (transition[typeName] = Object.create(null));
  2684. newTransition.__type = type;
  2685. newTransition.__size = size;
  2686. newTransition.__parent = transition;
  2687. return newTransition;
  2688. }
  2689. function onLoadedStructures(sharedData) {
  2690. if (!(sharedData instanceof Map))
  2691. return sharedData;
  2692. let typed = sharedData.get('typed') || [];
  2693. if (Object.isFrozen(typed))
  2694. typed = typed.map(structure => structure.slice(0));
  2695. let named = sharedData.get('named');
  2696. let transitions = Object.create(null);
  2697. for (let i = 0, l = typed.length; i < l; i++) {
  2698. let structure = typed[i];
  2699. let transition = transitions;
  2700. for (let [type, size, key] of structure) {
  2701. let nextTransition = transition[key];
  2702. if (!nextTransition) {
  2703. transition[key] = nextTransition = {
  2704. key,
  2705. parent: transition,
  2706. enumerationOffset: 0,
  2707. ascii0: null,
  2708. ascii8: null,
  2709. num8: null,
  2710. string16: null,
  2711. object16: null,
  2712. num32: null,
  2713. float64: null,
  2714. date64: null,
  2715. };
  2716. }
  2717. transition = createTypeTransition(nextTransition, type, size);
  2718. }
  2719. transition[RECORD_SYMBOL] = i;
  2720. }
  2721. typed.transitions = transitions;
  2722. this.typedStructs = typed;
  2723. this.lastTypedStructuresLength = typed.length;
  2724. return named;
  2725. }
  2726. var sourceSymbol = Symbol.for('source');
  2727. function readStruct(src, position, srcEnd, unpackr) {
  2728. let recordId = src[position++] - 0x20;
  2729. if (recordId >= 24) {
  2730. switch(recordId) {
  2731. case 24: recordId = src[position++]; break;
  2732. // little endian:
  2733. case 25: recordId = src[position++] + (src[position++] << 8); break;
  2734. case 26: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16); break;
  2735. case 27: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16) + (src[position++] << 24); break;
  2736. }
  2737. }
  2738. let structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
  2739. if (!structure) {
  2740. // copy src buffer because getStructures will override it
  2741. src = Uint8Array.prototype.slice.call(src, position, srcEnd);
  2742. srcEnd -= position;
  2743. position = 0;
  2744. if (!unpackr.getStructures)
  2745. throw new Error(`Reference to shared structure ${recordId} without getStructures method`);
  2746. unpackr._mergeStructures(unpackr.getStructures());
  2747. if (!unpackr.typedStructs)
  2748. throw new Error('Could not find any shared typed structures');
  2749. unpackr.lastTypedStructuresLength = unpackr.typedStructs.length;
  2750. structure = unpackr.typedStructs[recordId];
  2751. if (!structure)
  2752. throw new Error('Could not find typed structure ' + recordId);
  2753. }
  2754. var construct = structure.construct;
  2755. var fullConstruct = structure.fullConstruct;
  2756. if (!construct) {
  2757. construct = structure.construct = function LazyObject() {
  2758. };
  2759. fullConstruct = structure.fullConstruct = function LoadedObject() {
  2760. };
  2761. fullConstruct.prototype = unpackr.structPrototype || {};
  2762. var prototype = construct.prototype = unpackr.structPrototype ? Object.create(unpackr.structPrototype) : {};
  2763. let properties = [];
  2764. let currentOffset = 0;
  2765. let lastRefProperty;
  2766. for (let i = 0, l = structure.length; i < l; i++) {
  2767. let definition = structure[i];
  2768. let [ type, size, key, enumerationOffset ] = definition;
  2769. if (key === '__proto__')
  2770. key = '__proto_';
  2771. let property = {
  2772. key,
  2773. offset: currentOffset,
  2774. };
  2775. if (enumerationOffset)
  2776. properties.splice(i + enumerationOffset, 0, property);
  2777. else
  2778. properties.push(property);
  2779. let getRef;
  2780. switch(size) { // TODO: Move into a separate function
  2781. case 0: getRef = () => 0; break;
  2782. case 1:
  2783. getRef = (source, position) => {
  2784. let ref = source.bytes[position + property.offset];
  2785. return ref >= 0xf6 ? toConstant(ref) : ref;
  2786. };
  2787. break;
  2788. case 2:
  2789. getRef = (source, position) => {
  2790. let src = source.bytes;
  2791. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2792. let ref = dataView.getUint16(position + property.offset, true);
  2793. return ref >= 0xff00 ? toConstant(ref & 0xff) : ref;
  2794. };
  2795. break;
  2796. case 4:
  2797. getRef = (source, position) => {
  2798. let src = source.bytes;
  2799. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2800. let ref = dataView.getUint32(position + property.offset, true);
  2801. return ref >= 0xffffff00 ? toConstant(ref & 0xff) : ref;
  2802. };
  2803. break;
  2804. }
  2805. property.getRef = getRef;
  2806. currentOffset += size;
  2807. let get;
  2808. switch(type) {
  2809. case ASCII:
  2810. if (lastRefProperty && !lastRefProperty.next)
  2811. lastRefProperty.next = property;
  2812. lastRefProperty = property;
  2813. property.multiGetCount = 0;
  2814. get = function(source) {
  2815. let src = source.bytes;
  2816. let position = source.position;
  2817. let refStart = currentOffset + position;
  2818. let ref = getRef(source, position);
  2819. if (typeof ref !== 'number') return ref;
  2820. let end, next = property.next;
  2821. while(next) {
  2822. end = next.getRef(source, position);
  2823. if (typeof end === 'number')
  2824. break;
  2825. else
  2826. end = null;
  2827. next = next.next;
  2828. }
  2829. if (end == null)
  2830. end = source.bytesEnd - refStart;
  2831. if (source.srcString) {
  2832. return source.srcString.slice(ref, end);
  2833. }
  2834. /*if (property.multiGetCount > 0) {
  2835. let asciiEnd;
  2836. next = firstRefProperty;
  2837. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2838. do {
  2839. asciiEnd = dataView.getUint16(source.position + next.offset, true);
  2840. if (asciiEnd < 0xff00)
  2841. break;
  2842. else
  2843. asciiEnd = null;
  2844. } while((next = next.next));
  2845. if (asciiEnd == null)
  2846. asciiEnd = source.bytesEnd - refStart
  2847. source.srcString = src.toString('latin1', refStart, refStart + asciiEnd);
  2848. return source.srcString.slice(ref, end);
  2849. }
  2850. if (source.prevStringGet) {
  2851. source.prevStringGet.multiGetCount += 2;
  2852. } else {
  2853. source.prevStringGet = property;
  2854. property.multiGetCount--;
  2855. }*/
  2856. return readString(src, ref + refStart, end - ref);
  2857. //return src.toString('latin1', ref + refStart, end + refStart);
  2858. };
  2859. break;
  2860. case UTF8: case OBJECT_DATA:
  2861. if (lastRefProperty && !lastRefProperty.next)
  2862. lastRefProperty.next = property;
  2863. lastRefProperty = property;
  2864. get = function(source) {
  2865. let position = source.position;
  2866. let refStart = currentOffset + position;
  2867. let ref = getRef(source, position);
  2868. if (typeof ref !== 'number') return ref;
  2869. let src = source.bytes;
  2870. let end, next = property.next;
  2871. while(next) {
  2872. end = next.getRef(source, position);
  2873. if (typeof end === 'number')
  2874. break;
  2875. else
  2876. end = null;
  2877. next = next.next;
  2878. }
  2879. if (end == null)
  2880. end = source.bytesEnd - refStart;
  2881. if (type === UTF8) {
  2882. return src.toString('utf8', ref + refStart, end + refStart);
  2883. } else {
  2884. currentSource = source;
  2885. try {
  2886. return unpackr.unpack(src, { start: ref + refStart, end: end + refStart });
  2887. } finally {
  2888. currentSource = null;
  2889. }
  2890. }
  2891. };
  2892. break;
  2893. case NUMBER:
  2894. switch(size) {
  2895. case 4:
  2896. get = function (source) {
  2897. let src = source.bytes;
  2898. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2899. let position = source.position + property.offset;
  2900. let value = dataView.getInt32(position, true);
  2901. if (value < 0x20000000) {
  2902. if (value > -0x1f000000)
  2903. return value;
  2904. if (value > -0x20000000)
  2905. return toConstant(value & 0xff);
  2906. }
  2907. let fValue = dataView.getFloat32(position, true);
  2908. // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
  2909. let multiplier = mult10[((src[position + 3] & 0x7f) << 1) | (src[position + 2] >> 7)];
  2910. return ((multiplier * fValue + (fValue > 0 ? 0.5 : -0.5)) >> 0) / multiplier;
  2911. };
  2912. break;
  2913. case 8:
  2914. get = function (source) {
  2915. let src = source.bytes;
  2916. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2917. let value = dataView.getFloat64(source.position + property.offset, true);
  2918. if (isNaN(value)) {
  2919. let byte = src[source.position + property.offset];
  2920. if (byte >= 0xf6)
  2921. return toConstant(byte);
  2922. }
  2923. return value;
  2924. };
  2925. break;
  2926. case 1:
  2927. get = function (source) {
  2928. let src = source.bytes;
  2929. let value = src[source.position + property.offset];
  2930. return value < 0xf6 ? value : toConstant(value);
  2931. };
  2932. break;
  2933. }
  2934. break;
  2935. case DATE:
  2936. get = function (source) {
  2937. let src = source.bytes;
  2938. let dataView = src.dataView || (src.dataView = new DataView(src.buffer, src.byteOffset, src.byteLength));
  2939. return new Date(dataView.getFloat64(source.position + property.offset, true));
  2940. };
  2941. break;
  2942. }
  2943. property.get = get;
  2944. }
  2945. // TODO: load the srcString for faster string decoding on toJSON
  2946. if (evalSupported) {
  2947. let objectLiteralProperties = [];
  2948. let args = [];
  2949. let i = 0;
  2950. let hasInheritedProperties;
  2951. for (let property of properties) { // assign in enumeration order
  2952. if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) {
  2953. // these properties are not eagerly evaluated and this can be used for creating properties
  2954. // that are not serialized as JSON
  2955. hasInheritedProperties = true;
  2956. continue;
  2957. }
  2958. Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true });
  2959. let valueFunction = 'v' + i++;
  2960. args.push(valueFunction);
  2961. objectLiteralProperties.push('o[' + JSON.stringify(property.key) + ']=' + valueFunction + '(s)');
  2962. }
  2963. if (hasInheritedProperties) {
  2964. objectLiteralProperties.push('__proto__:this');
  2965. }
  2966. let toObject = (new Function(...args, 'var c=this;return function(s){var o=new c();' + objectLiteralProperties.join(';') + ';return o;}')).apply(fullConstruct, properties.map(prop => prop.get));
  2967. Object.defineProperty(prototype, 'toJSON', {
  2968. value(omitUnderscoredProperties) {
  2969. return toObject.call(this, this[sourceSymbol]);
  2970. }
  2971. });
  2972. } else {
  2973. Object.defineProperty(prototype, 'toJSON', {
  2974. value(omitUnderscoredProperties) {
  2975. // return an enumerable object with own properties to JSON stringify
  2976. let resolved = {};
  2977. for (let i = 0, l = properties.length; i < l; i++) {
  2978. // TODO: check alwaysLazyProperty
  2979. let key = properties[i].key;
  2980. resolved[key] = this[key];
  2981. }
  2982. return resolved;
  2983. },
  2984. // not enumerable or anything
  2985. });
  2986. }
  2987. }
  2988. var instance = new construct();
  2989. instance[sourceSymbol] = {
  2990. bytes: src,
  2991. position,
  2992. srcString: '',
  2993. bytesEnd: srcEnd
  2994. };
  2995. return instance;
  2996. }
  2997. function toConstant(code) {
  2998. switch(code) {
  2999. case 0xf6: return null;
  3000. case 0xf7: return undefined;
  3001. case 0xf8: return false;
  3002. case 0xf9: return true;
  3003. }
  3004. throw new Error('Unknown constant');
  3005. }
  3006. function withSource(get) {
  3007. return function() {
  3008. return get(this[sourceSymbol]);
  3009. }
  3010. }
  3011. function saveState() {
  3012. if (currentSource) {
  3013. currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd);
  3014. currentSource.position = 0;
  3015. currentSource.bytesEnd = currentSource.bytes.length;
  3016. }
  3017. }
  3018. function prepareStructures(structures, packr) {
  3019. if (packr.typedStructs) {
  3020. let structMap = new Map();
  3021. structMap.set('named', structures);
  3022. structMap.set('typed', packr.typedStructs);
  3023. structures = structMap;
  3024. }
  3025. let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0;
  3026. structures.isCompatible = existing => {
  3027. let compatible = true;
  3028. if (existing instanceof Map) {
  3029. let named = existing.get('named') || [];
  3030. if (named.length !== (packr.lastNamedStructuresLength || 0))
  3031. compatible = false;
  3032. let typed = existing.get('typed') || [];
  3033. if (typed.length !== lastTypedStructuresLength)
  3034. compatible = false;
  3035. } else if (existing instanceof Array || Array.isArray(existing)) {
  3036. if (existing.length !== (packr.lastNamedStructuresLength || 0))
  3037. compatible = false;
  3038. }
  3039. if (!compatible)
  3040. packr._mergeStructures(existing);
  3041. return compatible;
  3042. };
  3043. packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length;
  3044. return structures;
  3045. }
  3046. setReadStruct(readStruct, onLoadedStructures, saveState);
  3047. class PackrStream extends stream.Transform {
  3048. constructor(options) {
  3049. if (!options)
  3050. options = {};
  3051. options.writableObjectMode = true;
  3052. super(options);
  3053. options.sequential = true;
  3054. this.packr = options.packr || new Packr(options);
  3055. }
  3056. _transform(value, encoding, callback) {
  3057. this.push(this.packr.pack(value));
  3058. callback();
  3059. }
  3060. }
  3061. class UnpackrStream extends stream.Transform {
  3062. constructor(options) {
  3063. if (!options)
  3064. options = {};
  3065. options.objectMode = true;
  3066. super(options);
  3067. options.structures = [];
  3068. this.unpackr = options.unpackr || new Unpackr(options);
  3069. }
  3070. _transform(chunk, encoding, callback) {
  3071. if (this.incompleteBuffer) {
  3072. chunk = Buffer.concat([this.incompleteBuffer, chunk]);
  3073. this.incompleteBuffer = null;
  3074. }
  3075. let values;
  3076. try {
  3077. values = this.unpackr.unpackMultiple(chunk);
  3078. } catch(error) {
  3079. if (error.incomplete) {
  3080. this.incompleteBuffer = chunk.slice(error.lastPosition);
  3081. values = error.values;
  3082. }
  3083. else
  3084. throw error
  3085. } finally {
  3086. for (let value of values || []) {
  3087. if (value === null)
  3088. value = this.getNullValue();
  3089. this.push(value);
  3090. }
  3091. }
  3092. if (callback) callback();
  3093. }
  3094. getNullValue() {
  3095. return Symbol.for(null)
  3096. }
  3097. }
  3098. /**
  3099. * Given an Iterable first argument, returns an Iterable where each value is packed as a Buffer
  3100. * If the argument is only Async Iterable, the return value will be an Async Iterable.
  3101. * @param {Iterable|Iterator|AsyncIterable|AsyncIterator} objectIterator - iterable source, like a Readable object stream, an array, Set, or custom object
  3102. * @param {options} [options] - msgpackr pack options
  3103. * @returns {IterableIterator|Promise.<AsyncIterableIterator>}
  3104. */
  3105. function packIter (objectIterator, options = {}) {
  3106. if (!objectIterator || typeof objectIterator !== 'object') {
  3107. throw new Error('first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable')
  3108. } else if (typeof objectIterator[Symbol.iterator] === 'function') {
  3109. return packIterSync(objectIterator, options)
  3110. } else if (typeof objectIterator.then === 'function' || typeof objectIterator[Symbol.asyncIterator] === 'function') {
  3111. return packIterAsync(objectIterator, options)
  3112. } else {
  3113. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise')
  3114. }
  3115. }
  3116. function * packIterSync (objectIterator, options) {
  3117. const packr = new Packr(options);
  3118. for (const value of objectIterator) {
  3119. yield packr.pack(value);
  3120. }
  3121. }
  3122. async function * packIterAsync (objectIterator, options) {
  3123. const packr = new Packr(options);
  3124. for await (const value of objectIterator) {
  3125. yield packr.pack(value);
  3126. }
  3127. }
  3128. /**
  3129. * Given an Iterable/Iterator input which yields buffers, returns an IterableIterator which yields sync decoded objects
  3130. * Or, given an Async Iterable/Iterator which yields promises resolving in buffers, returns an AsyncIterableIterator.
  3131. * @param {Iterable|Iterator|AsyncIterable|AsyncIterableIterator} bufferIterator
  3132. * @param {object} [options] - unpackr options
  3133. * @returns {IterableIterator|Promise.<AsyncIterableIterator}
  3134. */
  3135. function unpackIter (bufferIterator, options = {}) {
  3136. if (!bufferIterator || typeof bufferIterator !== 'object') {
  3137. throw new Error('first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise')
  3138. }
  3139. const unpackr = new Unpackr(options);
  3140. let incomplete;
  3141. const parser = (chunk) => {
  3142. let yields;
  3143. // if there's incomplete data from previous chunk, concatinate and try again
  3144. if (incomplete) {
  3145. chunk = Buffer.concat([incomplete, chunk]);
  3146. incomplete = undefined;
  3147. }
  3148. try {
  3149. yields = unpackr.unpackMultiple(chunk);
  3150. } catch (err) {
  3151. if (err.incomplete) {
  3152. incomplete = chunk.slice(err.lastPosition);
  3153. yields = err.values;
  3154. } else {
  3155. throw err
  3156. }
  3157. }
  3158. return yields
  3159. };
  3160. if (typeof bufferIterator[Symbol.iterator] === 'function') {
  3161. return (function * iter () {
  3162. for (const value of bufferIterator) {
  3163. yield * parser(value);
  3164. }
  3165. })()
  3166. } else if (typeof bufferIterator[Symbol.asyncIterator] === 'function') {
  3167. return (async function * iter () {
  3168. for await (const value of bufferIterator) {
  3169. yield * parser(value);
  3170. }
  3171. })()
  3172. }
  3173. }
  3174. const decodeIter = unpackIter;
  3175. const encodeIter = packIter;
  3176. const useRecords = false;
  3177. const mapsAsObjects = true;
  3178. const nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';
  3179. if (!nativeAccelerationDisabled) {
  3180. let extractor;
  3181. try {
  3182. if (typeof require == 'function')
  3183. extractor = require('msgpackr-extract');
  3184. else
  3185. 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');
  3186. if (extractor)
  3187. setExtractor(extractor.extractStrings);
  3188. } catch (error) {
  3189. // native module is optional
  3190. }
  3191. }
  3192. exports.ALWAYS = ALWAYS;
  3193. exports.C1 = C1;
  3194. exports.DECIMAL_FIT = DECIMAL_FIT;
  3195. exports.DECIMAL_ROUND = DECIMAL_ROUND;
  3196. exports.Decoder = Decoder;
  3197. exports.DecoderStream = UnpackrStream;
  3198. exports.Encoder = Encoder;
  3199. exports.EncoderStream = PackrStream;
  3200. exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS;
  3201. exports.NEVER = NEVER;
  3202. exports.Packr = Packr;
  3203. exports.PackrStream = PackrStream;
  3204. exports.Unpackr = Unpackr;
  3205. exports.UnpackrStream = UnpackrStream;
  3206. exports.addExtension = addExtension;
  3207. exports.clearSource = clearSource;
  3208. exports.decode = decode;
  3209. exports.decodeIter = decodeIter;
  3210. exports.encode = encode;
  3211. exports.encodeIter = encodeIter;
  3212. exports.mapsAsObjects = mapsAsObjects;
  3213. exports.pack = pack;
  3214. exports.roundFloat32 = roundFloat32;
  3215. exports.unpack = unpack;
  3216. exports.unpackMultiple = unpackMultiple;
  3217. exports.useRecords = useRecords;
  3218. //# sourceMappingURL=node.cjs.map