sync.js 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303
  1. var global$1 = (typeof global !== "undefined" ? global :
  2. typeof self !== "undefined" ? self :
  3. typeof window !== "undefined" ? window : {});
  4. var lookup = [];
  5. var revLookup = [];
  6. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  7. var inited = false;
  8. function init () {
  9. inited = true;
  10. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  11. for (var i = 0, len = code.length; i < len; ++i) {
  12. lookup[i] = code[i];
  13. revLookup[code.charCodeAt(i)] = i;
  14. }
  15. revLookup['-'.charCodeAt(0)] = 62;
  16. revLookup['_'.charCodeAt(0)] = 63;
  17. }
  18. function toByteArray (b64) {
  19. if (!inited) {
  20. init();
  21. }
  22. var i, j, l, tmp, placeHolders, arr;
  23. var len = b64.length;
  24. if (len % 4 > 0) {
  25. throw new Error('Invalid string. Length must be a multiple of 4')
  26. }
  27. // the number of equal signs (place holders)
  28. // if there are two placeholders, than the two characters before it
  29. // represent one byte
  30. // if there is only one, then the three characters before it represent 2 bytes
  31. // this is just a cheap hack to not do indexOf twice
  32. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  33. // base64 is 4/3 + up to two characters of the original data
  34. arr = new Arr(len * 3 / 4 - placeHolders);
  35. // if there are placeholders, only get up to the last complete 4 chars
  36. l = placeHolders > 0 ? len - 4 : len;
  37. var L = 0;
  38. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  39. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  40. arr[L++] = (tmp >> 16) & 0xFF;
  41. arr[L++] = (tmp >> 8) & 0xFF;
  42. arr[L++] = tmp & 0xFF;
  43. }
  44. if (placeHolders === 2) {
  45. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  46. arr[L++] = tmp & 0xFF;
  47. } else if (placeHolders === 1) {
  48. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  49. arr[L++] = (tmp >> 8) & 0xFF;
  50. arr[L++] = tmp & 0xFF;
  51. }
  52. return arr
  53. }
  54. function tripletToBase64 (num) {
  55. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  56. }
  57. function encodeChunk (uint8, start, end) {
  58. var tmp;
  59. var output = [];
  60. for (var i = start; i < end; i += 3) {
  61. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  62. output.push(tripletToBase64(tmp));
  63. }
  64. return output.join('')
  65. }
  66. function fromByteArray (uint8) {
  67. if (!inited) {
  68. init();
  69. }
  70. var tmp;
  71. var len = uint8.length;
  72. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  73. var output = '';
  74. var parts = [];
  75. var maxChunkLength = 16383; // must be multiple of 3
  76. // go through the array every three bytes, we'll deal with trailing stuff later
  77. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  78. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  79. }
  80. // pad the end with zeros, but make sure to not forget the extra bytes
  81. if (extraBytes === 1) {
  82. tmp = uint8[len - 1];
  83. output += lookup[tmp >> 2];
  84. output += lookup[(tmp << 4) & 0x3F];
  85. output += '==';
  86. } else if (extraBytes === 2) {
  87. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  88. output += lookup[tmp >> 10];
  89. output += lookup[(tmp >> 4) & 0x3F];
  90. output += lookup[(tmp << 2) & 0x3F];
  91. output += '=';
  92. }
  93. parts.push(output);
  94. return parts.join('')
  95. }
  96. function read (buffer, offset, isLE, mLen, nBytes) {
  97. var e, m;
  98. var eLen = nBytes * 8 - mLen - 1;
  99. var eMax = (1 << eLen) - 1;
  100. var eBias = eMax >> 1;
  101. var nBits = -7;
  102. var i = isLE ? (nBytes - 1) : 0;
  103. var d = isLE ? -1 : 1;
  104. var s = buffer[offset + i];
  105. i += d;
  106. e = s & ((1 << (-nBits)) - 1);
  107. s >>= (-nBits);
  108. nBits += eLen;
  109. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  110. m = e & ((1 << (-nBits)) - 1);
  111. e >>= (-nBits);
  112. nBits += mLen;
  113. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  114. if (e === 0) {
  115. e = 1 - eBias;
  116. } else if (e === eMax) {
  117. return m ? NaN : ((s ? -1 : 1) * Infinity)
  118. } else {
  119. m = m + Math.pow(2, mLen);
  120. e = e - eBias;
  121. }
  122. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  123. }
  124. function write (buffer, value, offset, isLE, mLen, nBytes) {
  125. var e, m, c;
  126. var eLen = nBytes * 8 - mLen - 1;
  127. var eMax = (1 << eLen) - 1;
  128. var eBias = eMax >> 1;
  129. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  130. var i = isLE ? 0 : (nBytes - 1);
  131. var d = isLE ? 1 : -1;
  132. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  133. value = Math.abs(value);
  134. if (isNaN(value) || value === Infinity) {
  135. m = isNaN(value) ? 1 : 0;
  136. e = eMax;
  137. } else {
  138. e = Math.floor(Math.log(value) / Math.LN2);
  139. if (value * (c = Math.pow(2, -e)) < 1) {
  140. e--;
  141. c *= 2;
  142. }
  143. if (e + eBias >= 1) {
  144. value += rt / c;
  145. } else {
  146. value += rt * Math.pow(2, 1 - eBias);
  147. }
  148. if (value * c >= 2) {
  149. e++;
  150. c /= 2;
  151. }
  152. if (e + eBias >= eMax) {
  153. m = 0;
  154. e = eMax;
  155. } else if (e + eBias >= 1) {
  156. m = (value * c - 1) * Math.pow(2, mLen);
  157. e = e + eBias;
  158. } else {
  159. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  160. e = 0;
  161. }
  162. }
  163. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  164. e = (e << mLen) | m;
  165. eLen += mLen;
  166. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  167. buffer[offset + i - d] |= s * 128;
  168. }
  169. var toString = {}.toString;
  170. var isArray = Array.isArray || function (arr) {
  171. return toString.call(arr) == '[object Array]';
  172. };
  173. var INSPECT_MAX_BYTES = 50;
  174. /**
  175. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  176. * === true Use Uint8Array implementation (fastest)
  177. * === false Use Object implementation (most compatible, even IE6)
  178. *
  179. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  180. * Opera 11.6+, iOS 4.2+.
  181. *
  182. * Due to various browser bugs, sometimes the Object implementation will be used even
  183. * when the browser supports typed arrays.
  184. *
  185. * Note:
  186. *
  187. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  188. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  189. *
  190. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  191. *
  192. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  193. * incorrect length in some situations.
  194. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  195. * get the Object implementation, which is slower but behaves correctly.
  196. */
  197. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  198. ? global$1.TYPED_ARRAY_SUPPORT
  199. : true;
  200. /*
  201. * Export kMaxLength after typed array support is determined.
  202. */
  203. kMaxLength();
  204. function kMaxLength () {
  205. return Buffer.TYPED_ARRAY_SUPPORT
  206. ? 0x7fffffff
  207. : 0x3fffffff
  208. }
  209. function createBuffer (that, length) {
  210. if (kMaxLength() < length) {
  211. throw new RangeError('Invalid typed array length')
  212. }
  213. if (Buffer.TYPED_ARRAY_SUPPORT) {
  214. // Return an augmented `Uint8Array` instance, for best performance
  215. that = new Uint8Array(length);
  216. that.__proto__ = Buffer.prototype;
  217. } else {
  218. // Fallback: Return an object instance of the Buffer class
  219. if (that === null) {
  220. that = new Buffer(length);
  221. }
  222. that.length = length;
  223. }
  224. return that
  225. }
  226. /**
  227. * The Buffer constructor returns instances of `Uint8Array` that have their
  228. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  229. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  230. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  231. * returns a single octet.
  232. *
  233. * The `Uint8Array` prototype remains unmodified.
  234. */
  235. function Buffer (arg, encodingOrOffset, length) {
  236. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  237. return new Buffer(arg, encodingOrOffset, length)
  238. }
  239. // Common case.
  240. if (typeof arg === 'number') {
  241. if (typeof encodingOrOffset === 'string') {
  242. throw new Error(
  243. 'If encoding is specified then the first argument must be a string'
  244. )
  245. }
  246. return allocUnsafe(this, arg)
  247. }
  248. return from(this, arg, encodingOrOffset, length)
  249. }
  250. Buffer.poolSize = 8192; // not used by this implementation
  251. // TODO: Legacy, not needed anymore. Remove in next major version.
  252. Buffer._augment = function (arr) {
  253. arr.__proto__ = Buffer.prototype;
  254. return arr
  255. };
  256. function from (that, value, encodingOrOffset, length) {
  257. if (typeof value === 'number') {
  258. throw new TypeError('"value" argument must not be a number')
  259. }
  260. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  261. return fromArrayBuffer(that, value, encodingOrOffset, length)
  262. }
  263. if (typeof value === 'string') {
  264. return fromString(that, value, encodingOrOffset)
  265. }
  266. return fromObject(that, value)
  267. }
  268. /**
  269. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  270. * if value is a number.
  271. * Buffer.from(str[, encoding])
  272. * Buffer.from(array)
  273. * Buffer.from(buffer)
  274. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  275. **/
  276. Buffer.from = function (value, encodingOrOffset, length) {
  277. return from(null, value, encodingOrOffset, length)
  278. };
  279. if (Buffer.TYPED_ARRAY_SUPPORT) {
  280. Buffer.prototype.__proto__ = Uint8Array.prototype;
  281. Buffer.__proto__ = Uint8Array;
  282. if (typeof Symbol !== 'undefined' && Symbol.species &&
  283. Buffer[Symbol.species] === Buffer) ;
  284. }
  285. function assertSize (size) {
  286. if (typeof size !== 'number') {
  287. throw new TypeError('"size" argument must be a number')
  288. } else if (size < 0) {
  289. throw new RangeError('"size" argument must not be negative')
  290. }
  291. }
  292. function alloc (that, size, fill, encoding) {
  293. assertSize(size);
  294. if (size <= 0) {
  295. return createBuffer(that, size)
  296. }
  297. if (fill !== undefined) {
  298. // Only pay attention to encoding if it's a string. This
  299. // prevents accidentally sending in a number that would
  300. // be interpretted as a start offset.
  301. return typeof encoding === 'string'
  302. ? createBuffer(that, size).fill(fill, encoding)
  303. : createBuffer(that, size).fill(fill)
  304. }
  305. return createBuffer(that, size)
  306. }
  307. /**
  308. * Creates a new filled Buffer instance.
  309. * alloc(size[, fill[, encoding]])
  310. **/
  311. Buffer.alloc = function (size, fill, encoding) {
  312. return alloc(null, size, fill, encoding)
  313. };
  314. function allocUnsafe (that, size) {
  315. assertSize(size);
  316. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  317. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  318. for (var i = 0; i < size; ++i) {
  319. that[i] = 0;
  320. }
  321. }
  322. return that
  323. }
  324. /**
  325. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  326. * */
  327. Buffer.allocUnsafe = function (size) {
  328. return allocUnsafe(null, size)
  329. };
  330. /**
  331. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  332. */
  333. Buffer.allocUnsafeSlow = function (size) {
  334. return allocUnsafe(null, size)
  335. };
  336. function fromString (that, string, encoding) {
  337. if (typeof encoding !== 'string' || encoding === '') {
  338. encoding = 'utf8';
  339. }
  340. if (!Buffer.isEncoding(encoding)) {
  341. throw new TypeError('"encoding" must be a valid string encoding')
  342. }
  343. var length = byteLength(string, encoding) | 0;
  344. that = createBuffer(that, length);
  345. var actual = that.write(string, encoding);
  346. if (actual !== length) {
  347. // Writing a hex string, for example, that contains invalid characters will
  348. // cause everything after the first invalid character to be ignored. (e.g.
  349. // 'abxxcd' will be treated as 'ab')
  350. that = that.slice(0, actual);
  351. }
  352. return that
  353. }
  354. function fromArrayLike (that, array) {
  355. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  356. that = createBuffer(that, length);
  357. for (var i = 0; i < length; i += 1) {
  358. that[i] = array[i] & 255;
  359. }
  360. return that
  361. }
  362. function fromArrayBuffer (that, array, byteOffset, length) {
  363. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  364. if (byteOffset < 0 || array.byteLength < byteOffset) {
  365. throw new RangeError('\'offset\' is out of bounds')
  366. }
  367. if (array.byteLength < byteOffset + (length || 0)) {
  368. throw new RangeError('\'length\' is out of bounds')
  369. }
  370. if (byteOffset === undefined && length === undefined) {
  371. array = new Uint8Array(array);
  372. } else if (length === undefined) {
  373. array = new Uint8Array(array, byteOffset);
  374. } else {
  375. array = new Uint8Array(array, byteOffset, length);
  376. }
  377. if (Buffer.TYPED_ARRAY_SUPPORT) {
  378. // Return an augmented `Uint8Array` instance, for best performance
  379. that = array;
  380. that.__proto__ = Buffer.prototype;
  381. } else {
  382. // Fallback: Return an object instance of the Buffer class
  383. that = fromArrayLike(that, array);
  384. }
  385. return that
  386. }
  387. function fromObject (that, obj) {
  388. if (internalIsBuffer(obj)) {
  389. var len = checked(obj.length) | 0;
  390. that = createBuffer(that, len);
  391. if (that.length === 0) {
  392. return that
  393. }
  394. obj.copy(that, 0, 0, len);
  395. return that
  396. }
  397. if (obj) {
  398. if ((typeof ArrayBuffer !== 'undefined' &&
  399. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  400. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  401. return createBuffer(that, 0)
  402. }
  403. return fromArrayLike(that, obj)
  404. }
  405. if (obj.type === 'Buffer' && isArray(obj.data)) {
  406. return fromArrayLike(that, obj.data)
  407. }
  408. }
  409. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  410. }
  411. function checked (length) {
  412. // Note: cannot use `length < kMaxLength()` here because that fails when
  413. // length is NaN (which is otherwise coerced to zero.)
  414. if (length >= kMaxLength()) {
  415. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  416. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  417. }
  418. return length | 0
  419. }
  420. Buffer.isBuffer = isBuffer;
  421. function internalIsBuffer (b) {
  422. return !!(b != null && b._isBuffer)
  423. }
  424. Buffer.compare = function compare (a, b) {
  425. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  426. throw new TypeError('Arguments must be Buffers')
  427. }
  428. if (a === b) return 0
  429. var x = a.length;
  430. var y = b.length;
  431. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  432. if (a[i] !== b[i]) {
  433. x = a[i];
  434. y = b[i];
  435. break
  436. }
  437. }
  438. if (x < y) return -1
  439. if (y < x) return 1
  440. return 0
  441. };
  442. Buffer.isEncoding = function isEncoding (encoding) {
  443. switch (String(encoding).toLowerCase()) {
  444. case 'hex':
  445. case 'utf8':
  446. case 'utf-8':
  447. case 'ascii':
  448. case 'latin1':
  449. case 'binary':
  450. case 'base64':
  451. case 'ucs2':
  452. case 'ucs-2':
  453. case 'utf16le':
  454. case 'utf-16le':
  455. return true
  456. default:
  457. return false
  458. }
  459. };
  460. Buffer.concat = function concat (list, length) {
  461. if (!isArray(list)) {
  462. throw new TypeError('"list" argument must be an Array of Buffers')
  463. }
  464. if (list.length === 0) {
  465. return Buffer.alloc(0)
  466. }
  467. var i;
  468. if (length === undefined) {
  469. length = 0;
  470. for (i = 0; i < list.length; ++i) {
  471. length += list[i].length;
  472. }
  473. }
  474. var buffer = Buffer.allocUnsafe(length);
  475. var pos = 0;
  476. for (i = 0; i < list.length; ++i) {
  477. var buf = list[i];
  478. if (!internalIsBuffer(buf)) {
  479. throw new TypeError('"list" argument must be an Array of Buffers')
  480. }
  481. buf.copy(buffer, pos);
  482. pos += buf.length;
  483. }
  484. return buffer
  485. };
  486. function byteLength (string, encoding) {
  487. if (internalIsBuffer(string)) {
  488. return string.length
  489. }
  490. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  491. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  492. return string.byteLength
  493. }
  494. if (typeof string !== 'string') {
  495. string = '' + string;
  496. }
  497. var len = string.length;
  498. if (len === 0) return 0
  499. // Use a for loop to avoid recursion
  500. var loweredCase = false;
  501. for (;;) {
  502. switch (encoding) {
  503. case 'ascii':
  504. case 'latin1':
  505. case 'binary':
  506. return len
  507. case 'utf8':
  508. case 'utf-8':
  509. case undefined:
  510. return utf8ToBytes(string).length
  511. case 'ucs2':
  512. case 'ucs-2':
  513. case 'utf16le':
  514. case 'utf-16le':
  515. return len * 2
  516. case 'hex':
  517. return len >>> 1
  518. case 'base64':
  519. return base64ToBytes(string).length
  520. default:
  521. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  522. encoding = ('' + encoding).toLowerCase();
  523. loweredCase = true;
  524. }
  525. }
  526. }
  527. Buffer.byteLength = byteLength;
  528. function slowToString (encoding, start, end) {
  529. var loweredCase = false;
  530. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  531. // property of a typed array.
  532. // This behaves neither like String nor Uint8Array in that we set start/end
  533. // to their upper/lower bounds if the value passed is out of range.
  534. // undefined is handled specially as per ECMA-262 6th Edition,
  535. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  536. if (start === undefined || start < 0) {
  537. start = 0;
  538. }
  539. // Return early if start > this.length. Done here to prevent potential uint32
  540. // coercion fail below.
  541. if (start > this.length) {
  542. return ''
  543. }
  544. if (end === undefined || end > this.length) {
  545. end = this.length;
  546. }
  547. if (end <= 0) {
  548. return ''
  549. }
  550. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  551. end >>>= 0;
  552. start >>>= 0;
  553. if (end <= start) {
  554. return ''
  555. }
  556. if (!encoding) encoding = 'utf8';
  557. while (true) {
  558. switch (encoding) {
  559. case 'hex':
  560. return hexSlice(this, start, end)
  561. case 'utf8':
  562. case 'utf-8':
  563. return utf8Slice(this, start, end)
  564. case 'ascii':
  565. return asciiSlice(this, start, end)
  566. case 'latin1':
  567. case 'binary':
  568. return latin1Slice(this, start, end)
  569. case 'base64':
  570. return base64Slice(this, start, end)
  571. case 'ucs2':
  572. case 'ucs-2':
  573. case 'utf16le':
  574. case 'utf-16le':
  575. return utf16leSlice(this, start, end)
  576. default:
  577. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  578. encoding = (encoding + '').toLowerCase();
  579. loweredCase = true;
  580. }
  581. }
  582. }
  583. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  584. // Buffer instances.
  585. Buffer.prototype._isBuffer = true;
  586. function swap (b, n, m) {
  587. var i = b[n];
  588. b[n] = b[m];
  589. b[m] = i;
  590. }
  591. Buffer.prototype.swap16 = function swap16 () {
  592. var len = this.length;
  593. if (len % 2 !== 0) {
  594. throw new RangeError('Buffer size must be a multiple of 16-bits')
  595. }
  596. for (var i = 0; i < len; i += 2) {
  597. swap(this, i, i + 1);
  598. }
  599. return this
  600. };
  601. Buffer.prototype.swap32 = function swap32 () {
  602. var len = this.length;
  603. if (len % 4 !== 0) {
  604. throw new RangeError('Buffer size must be a multiple of 32-bits')
  605. }
  606. for (var i = 0; i < len; i += 4) {
  607. swap(this, i, i + 3);
  608. swap(this, i + 1, i + 2);
  609. }
  610. return this
  611. };
  612. Buffer.prototype.swap64 = function swap64 () {
  613. var len = this.length;
  614. if (len % 8 !== 0) {
  615. throw new RangeError('Buffer size must be a multiple of 64-bits')
  616. }
  617. for (var i = 0; i < len; i += 8) {
  618. swap(this, i, i + 7);
  619. swap(this, i + 1, i + 6);
  620. swap(this, i + 2, i + 5);
  621. swap(this, i + 3, i + 4);
  622. }
  623. return this
  624. };
  625. Buffer.prototype.toString = function toString () {
  626. var length = this.length | 0;
  627. if (length === 0) return ''
  628. if (arguments.length === 0) return utf8Slice(this, 0, length)
  629. return slowToString.apply(this, arguments)
  630. };
  631. Buffer.prototype.equals = function equals (b) {
  632. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  633. if (this === b) return true
  634. return Buffer.compare(this, b) === 0
  635. };
  636. Buffer.prototype.inspect = function inspect () {
  637. var str = '';
  638. var max = INSPECT_MAX_BYTES;
  639. if (this.length > 0) {
  640. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  641. if (this.length > max) str += ' ... ';
  642. }
  643. return '<Buffer ' + str + '>'
  644. };
  645. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  646. if (!internalIsBuffer(target)) {
  647. throw new TypeError('Argument must be a Buffer')
  648. }
  649. if (start === undefined) {
  650. start = 0;
  651. }
  652. if (end === undefined) {
  653. end = target ? target.length : 0;
  654. }
  655. if (thisStart === undefined) {
  656. thisStart = 0;
  657. }
  658. if (thisEnd === undefined) {
  659. thisEnd = this.length;
  660. }
  661. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  662. throw new RangeError('out of range index')
  663. }
  664. if (thisStart >= thisEnd && start >= end) {
  665. return 0
  666. }
  667. if (thisStart >= thisEnd) {
  668. return -1
  669. }
  670. if (start >= end) {
  671. return 1
  672. }
  673. start >>>= 0;
  674. end >>>= 0;
  675. thisStart >>>= 0;
  676. thisEnd >>>= 0;
  677. if (this === target) return 0
  678. var x = thisEnd - thisStart;
  679. var y = end - start;
  680. var len = Math.min(x, y);
  681. var thisCopy = this.slice(thisStart, thisEnd);
  682. var targetCopy = target.slice(start, end);
  683. for (var i = 0; i < len; ++i) {
  684. if (thisCopy[i] !== targetCopy[i]) {
  685. x = thisCopy[i];
  686. y = targetCopy[i];
  687. break
  688. }
  689. }
  690. if (x < y) return -1
  691. if (y < x) return 1
  692. return 0
  693. };
  694. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  695. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  696. //
  697. // Arguments:
  698. // - buffer - a Buffer to search
  699. // - val - a string, Buffer, or number
  700. // - byteOffset - an index into `buffer`; will be clamped to an int32
  701. // - encoding - an optional encoding, relevant is val is a string
  702. // - dir - true for indexOf, false for lastIndexOf
  703. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  704. // Empty buffer means no match
  705. if (buffer.length === 0) return -1
  706. // Normalize byteOffset
  707. if (typeof byteOffset === 'string') {
  708. encoding = byteOffset;
  709. byteOffset = 0;
  710. } else if (byteOffset > 0x7fffffff) {
  711. byteOffset = 0x7fffffff;
  712. } else if (byteOffset < -0x80000000) {
  713. byteOffset = -0x80000000;
  714. }
  715. byteOffset = +byteOffset; // Coerce to Number.
  716. if (isNaN(byteOffset)) {
  717. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  718. byteOffset = dir ? 0 : (buffer.length - 1);
  719. }
  720. // Normalize byteOffset: negative offsets start from the end of the buffer
  721. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  722. if (byteOffset >= buffer.length) {
  723. if (dir) return -1
  724. else byteOffset = buffer.length - 1;
  725. } else if (byteOffset < 0) {
  726. if (dir) byteOffset = 0;
  727. else return -1
  728. }
  729. // Normalize val
  730. if (typeof val === 'string') {
  731. val = Buffer.from(val, encoding);
  732. }
  733. // Finally, search either indexOf (if dir is true) or lastIndexOf
  734. if (internalIsBuffer(val)) {
  735. // Special case: looking for empty string/buffer always fails
  736. if (val.length === 0) {
  737. return -1
  738. }
  739. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  740. } else if (typeof val === 'number') {
  741. val = val & 0xFF; // Search for a byte value [0-255]
  742. if (Buffer.TYPED_ARRAY_SUPPORT &&
  743. typeof Uint8Array.prototype.indexOf === 'function') {
  744. if (dir) {
  745. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  746. } else {
  747. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  748. }
  749. }
  750. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  751. }
  752. throw new TypeError('val must be string, number or Buffer')
  753. }
  754. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  755. var indexSize = 1;
  756. var arrLength = arr.length;
  757. var valLength = val.length;
  758. if (encoding !== undefined) {
  759. encoding = String(encoding).toLowerCase();
  760. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  761. encoding === 'utf16le' || encoding === 'utf-16le') {
  762. if (arr.length < 2 || val.length < 2) {
  763. return -1
  764. }
  765. indexSize = 2;
  766. arrLength /= 2;
  767. valLength /= 2;
  768. byteOffset /= 2;
  769. }
  770. }
  771. function read (buf, i) {
  772. if (indexSize === 1) {
  773. return buf[i]
  774. } else {
  775. return buf.readUInt16BE(i * indexSize)
  776. }
  777. }
  778. var i;
  779. if (dir) {
  780. var foundIndex = -1;
  781. for (i = byteOffset; i < arrLength; i++) {
  782. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  783. if (foundIndex === -1) foundIndex = i;
  784. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  785. } else {
  786. if (foundIndex !== -1) i -= i - foundIndex;
  787. foundIndex = -1;
  788. }
  789. }
  790. } else {
  791. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  792. for (i = byteOffset; i >= 0; i--) {
  793. var found = true;
  794. for (var j = 0; j < valLength; j++) {
  795. if (read(arr, i + j) !== read(val, j)) {
  796. found = false;
  797. break
  798. }
  799. }
  800. if (found) return i
  801. }
  802. }
  803. return -1
  804. }
  805. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  806. return this.indexOf(val, byteOffset, encoding) !== -1
  807. };
  808. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  809. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  810. };
  811. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  812. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  813. };
  814. function hexWrite (buf, string, offset, length) {
  815. offset = Number(offset) || 0;
  816. var remaining = buf.length - offset;
  817. if (!length) {
  818. length = remaining;
  819. } else {
  820. length = Number(length);
  821. if (length > remaining) {
  822. length = remaining;
  823. }
  824. }
  825. // must be an even number of digits
  826. var strLen = string.length;
  827. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  828. if (length > strLen / 2) {
  829. length = strLen / 2;
  830. }
  831. for (var i = 0; i < length; ++i) {
  832. var parsed = parseInt(string.substr(i * 2, 2), 16);
  833. if (isNaN(parsed)) return i
  834. buf[offset + i] = parsed;
  835. }
  836. return i
  837. }
  838. function utf8Write (buf, string, offset, length) {
  839. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  840. }
  841. function asciiWrite (buf, string, offset, length) {
  842. return blitBuffer(asciiToBytes(string), buf, offset, length)
  843. }
  844. function latin1Write (buf, string, offset, length) {
  845. return asciiWrite(buf, string, offset, length)
  846. }
  847. function base64Write (buf, string, offset, length) {
  848. return blitBuffer(base64ToBytes(string), buf, offset, length)
  849. }
  850. function ucs2Write (buf, string, offset, length) {
  851. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  852. }
  853. Buffer.prototype.write = function write (string, offset, length, encoding) {
  854. // Buffer#write(string)
  855. if (offset === undefined) {
  856. encoding = 'utf8';
  857. length = this.length;
  858. offset = 0;
  859. // Buffer#write(string, encoding)
  860. } else if (length === undefined && typeof offset === 'string') {
  861. encoding = offset;
  862. length = this.length;
  863. offset = 0;
  864. // Buffer#write(string, offset[, length][, encoding])
  865. } else if (isFinite(offset)) {
  866. offset = offset | 0;
  867. if (isFinite(length)) {
  868. length = length | 0;
  869. if (encoding === undefined) encoding = 'utf8';
  870. } else {
  871. encoding = length;
  872. length = undefined;
  873. }
  874. // legacy write(string, encoding, offset, length) - remove in v0.13
  875. } else {
  876. throw new Error(
  877. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  878. )
  879. }
  880. var remaining = this.length - offset;
  881. if (length === undefined || length > remaining) length = remaining;
  882. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  883. throw new RangeError('Attempt to write outside buffer bounds')
  884. }
  885. if (!encoding) encoding = 'utf8';
  886. var loweredCase = false;
  887. for (;;) {
  888. switch (encoding) {
  889. case 'hex':
  890. return hexWrite(this, string, offset, length)
  891. case 'utf8':
  892. case 'utf-8':
  893. return utf8Write(this, string, offset, length)
  894. case 'ascii':
  895. return asciiWrite(this, string, offset, length)
  896. case 'latin1':
  897. case 'binary':
  898. return latin1Write(this, string, offset, length)
  899. case 'base64':
  900. // Warning: maxLength not taken into account in base64Write
  901. return base64Write(this, string, offset, length)
  902. case 'ucs2':
  903. case 'ucs-2':
  904. case 'utf16le':
  905. case 'utf-16le':
  906. return ucs2Write(this, string, offset, length)
  907. default:
  908. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  909. encoding = ('' + encoding).toLowerCase();
  910. loweredCase = true;
  911. }
  912. }
  913. };
  914. Buffer.prototype.toJSON = function toJSON () {
  915. return {
  916. type: 'Buffer',
  917. data: Array.prototype.slice.call(this._arr || this, 0)
  918. }
  919. };
  920. function base64Slice (buf, start, end) {
  921. if (start === 0 && end === buf.length) {
  922. return fromByteArray(buf)
  923. } else {
  924. return fromByteArray(buf.slice(start, end))
  925. }
  926. }
  927. function utf8Slice (buf, start, end) {
  928. end = Math.min(buf.length, end);
  929. var res = [];
  930. var i = start;
  931. while (i < end) {
  932. var firstByte = buf[i];
  933. var codePoint = null;
  934. var bytesPerSequence = (firstByte > 0xEF) ? 4
  935. : (firstByte > 0xDF) ? 3
  936. : (firstByte > 0xBF) ? 2
  937. : 1;
  938. if (i + bytesPerSequence <= end) {
  939. var secondByte, thirdByte, fourthByte, tempCodePoint;
  940. switch (bytesPerSequence) {
  941. case 1:
  942. if (firstByte < 0x80) {
  943. codePoint = firstByte;
  944. }
  945. break
  946. case 2:
  947. secondByte = buf[i + 1];
  948. if ((secondByte & 0xC0) === 0x80) {
  949. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  950. if (tempCodePoint > 0x7F) {
  951. codePoint = tempCodePoint;
  952. }
  953. }
  954. break
  955. case 3:
  956. secondByte = buf[i + 1];
  957. thirdByte = buf[i + 2];
  958. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  959. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  960. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  961. codePoint = tempCodePoint;
  962. }
  963. }
  964. break
  965. case 4:
  966. secondByte = buf[i + 1];
  967. thirdByte = buf[i + 2];
  968. fourthByte = buf[i + 3];
  969. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  970. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  971. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  972. codePoint = tempCodePoint;
  973. }
  974. }
  975. }
  976. }
  977. if (codePoint === null) {
  978. // we did not generate a valid codePoint so insert a
  979. // replacement char (U+FFFD) and advance only 1 byte
  980. codePoint = 0xFFFD;
  981. bytesPerSequence = 1;
  982. } else if (codePoint > 0xFFFF) {
  983. // encode to utf16 (surrogate pair dance)
  984. codePoint -= 0x10000;
  985. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  986. codePoint = 0xDC00 | codePoint & 0x3FF;
  987. }
  988. res.push(codePoint);
  989. i += bytesPerSequence;
  990. }
  991. return decodeCodePointsArray(res)
  992. }
  993. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  994. // the lowest limit is Chrome, with 0x10000 args.
  995. // We go 1 magnitude less, for safety
  996. var MAX_ARGUMENTS_LENGTH = 0x1000;
  997. function decodeCodePointsArray (codePoints) {
  998. var len = codePoints.length;
  999. if (len <= MAX_ARGUMENTS_LENGTH) {
  1000. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1001. }
  1002. // Decode in chunks to avoid "call stack size exceeded".
  1003. var res = '';
  1004. var i = 0;
  1005. while (i < len) {
  1006. res += String.fromCharCode.apply(
  1007. String,
  1008. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1009. );
  1010. }
  1011. return res
  1012. }
  1013. function asciiSlice (buf, start, end) {
  1014. var ret = '';
  1015. end = Math.min(buf.length, end);
  1016. for (var i = start; i < end; ++i) {
  1017. ret += String.fromCharCode(buf[i] & 0x7F);
  1018. }
  1019. return ret
  1020. }
  1021. function latin1Slice (buf, start, end) {
  1022. var ret = '';
  1023. end = Math.min(buf.length, end);
  1024. for (var i = start; i < end; ++i) {
  1025. ret += String.fromCharCode(buf[i]);
  1026. }
  1027. return ret
  1028. }
  1029. function hexSlice (buf, start, end) {
  1030. var len = buf.length;
  1031. if (!start || start < 0) start = 0;
  1032. if (!end || end < 0 || end > len) end = len;
  1033. var out = '';
  1034. for (var i = start; i < end; ++i) {
  1035. out += toHex(buf[i]);
  1036. }
  1037. return out
  1038. }
  1039. function utf16leSlice (buf, start, end) {
  1040. var bytes = buf.slice(start, end);
  1041. var res = '';
  1042. for (var i = 0; i < bytes.length; i += 2) {
  1043. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1044. }
  1045. return res
  1046. }
  1047. Buffer.prototype.slice = function slice (start, end) {
  1048. var len = this.length;
  1049. start = ~~start;
  1050. end = end === undefined ? len : ~~end;
  1051. if (start < 0) {
  1052. start += len;
  1053. if (start < 0) start = 0;
  1054. } else if (start > len) {
  1055. start = len;
  1056. }
  1057. if (end < 0) {
  1058. end += len;
  1059. if (end < 0) end = 0;
  1060. } else if (end > len) {
  1061. end = len;
  1062. }
  1063. if (end < start) end = start;
  1064. var newBuf;
  1065. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1066. newBuf = this.subarray(start, end);
  1067. newBuf.__proto__ = Buffer.prototype;
  1068. } else {
  1069. var sliceLen = end - start;
  1070. newBuf = new Buffer(sliceLen, undefined);
  1071. for (var i = 0; i < sliceLen; ++i) {
  1072. newBuf[i] = this[i + start];
  1073. }
  1074. }
  1075. return newBuf
  1076. };
  1077. /*
  1078. * Need to make sure that buffer isn't trying to write out of bounds.
  1079. */
  1080. function checkOffset (offset, ext, length) {
  1081. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1082. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1083. }
  1084. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1085. offset = offset | 0;
  1086. byteLength = byteLength | 0;
  1087. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1088. var val = this[offset];
  1089. var mul = 1;
  1090. var i = 0;
  1091. while (++i < byteLength && (mul *= 0x100)) {
  1092. val += this[offset + i] * mul;
  1093. }
  1094. return val
  1095. };
  1096. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1097. offset = offset | 0;
  1098. byteLength = byteLength | 0;
  1099. if (!noAssert) {
  1100. checkOffset(offset, byteLength, this.length);
  1101. }
  1102. var val = this[offset + --byteLength];
  1103. var mul = 1;
  1104. while (byteLength > 0 && (mul *= 0x100)) {
  1105. val += this[offset + --byteLength] * mul;
  1106. }
  1107. return val
  1108. };
  1109. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1110. if (!noAssert) checkOffset(offset, 1, this.length);
  1111. return this[offset]
  1112. };
  1113. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1114. if (!noAssert) checkOffset(offset, 2, this.length);
  1115. return this[offset] | (this[offset + 1] << 8)
  1116. };
  1117. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1118. if (!noAssert) checkOffset(offset, 2, this.length);
  1119. return (this[offset] << 8) | this[offset + 1]
  1120. };
  1121. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1122. if (!noAssert) checkOffset(offset, 4, this.length);
  1123. return ((this[offset]) |
  1124. (this[offset + 1] << 8) |
  1125. (this[offset + 2] << 16)) +
  1126. (this[offset + 3] * 0x1000000)
  1127. };
  1128. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1129. if (!noAssert) checkOffset(offset, 4, this.length);
  1130. return (this[offset] * 0x1000000) +
  1131. ((this[offset + 1] << 16) |
  1132. (this[offset + 2] << 8) |
  1133. this[offset + 3])
  1134. };
  1135. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1136. offset = offset | 0;
  1137. byteLength = byteLength | 0;
  1138. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1139. var val = this[offset];
  1140. var mul = 1;
  1141. var i = 0;
  1142. while (++i < byteLength && (mul *= 0x100)) {
  1143. val += this[offset + i] * mul;
  1144. }
  1145. mul *= 0x80;
  1146. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1147. return val
  1148. };
  1149. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1150. offset = offset | 0;
  1151. byteLength = byteLength | 0;
  1152. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1153. var i = byteLength;
  1154. var mul = 1;
  1155. var val = this[offset + --i];
  1156. while (i > 0 && (mul *= 0x100)) {
  1157. val += this[offset + --i] * mul;
  1158. }
  1159. mul *= 0x80;
  1160. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1161. return val
  1162. };
  1163. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1164. if (!noAssert) checkOffset(offset, 1, this.length);
  1165. if (!(this[offset] & 0x80)) return (this[offset])
  1166. return ((0xff - this[offset] + 1) * -1)
  1167. };
  1168. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1169. if (!noAssert) checkOffset(offset, 2, this.length);
  1170. var val = this[offset] | (this[offset + 1] << 8);
  1171. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1172. };
  1173. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1174. if (!noAssert) checkOffset(offset, 2, this.length);
  1175. var val = this[offset + 1] | (this[offset] << 8);
  1176. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1177. };
  1178. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1179. if (!noAssert) checkOffset(offset, 4, this.length);
  1180. return (this[offset]) |
  1181. (this[offset + 1] << 8) |
  1182. (this[offset + 2] << 16) |
  1183. (this[offset + 3] << 24)
  1184. };
  1185. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1186. if (!noAssert) checkOffset(offset, 4, this.length);
  1187. return (this[offset] << 24) |
  1188. (this[offset + 1] << 16) |
  1189. (this[offset + 2] << 8) |
  1190. (this[offset + 3])
  1191. };
  1192. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 4, this.length);
  1194. return read(this, offset, true, 23, 4)
  1195. };
  1196. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1197. if (!noAssert) checkOffset(offset, 4, this.length);
  1198. return read(this, offset, false, 23, 4)
  1199. };
  1200. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1201. if (!noAssert) checkOffset(offset, 8, this.length);
  1202. return read(this, offset, true, 52, 8)
  1203. };
  1204. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1205. if (!noAssert) checkOffset(offset, 8, this.length);
  1206. return read(this, offset, false, 52, 8)
  1207. };
  1208. function checkInt (buf, value, offset, ext, max, min) {
  1209. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1210. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1211. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1212. }
  1213. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1214. value = +value;
  1215. offset = offset | 0;
  1216. byteLength = byteLength | 0;
  1217. if (!noAssert) {
  1218. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1219. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1220. }
  1221. var mul = 1;
  1222. var i = 0;
  1223. this[offset] = value & 0xFF;
  1224. while (++i < byteLength && (mul *= 0x100)) {
  1225. this[offset + i] = (value / mul) & 0xFF;
  1226. }
  1227. return offset + byteLength
  1228. };
  1229. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1230. value = +value;
  1231. offset = offset | 0;
  1232. byteLength = byteLength | 0;
  1233. if (!noAssert) {
  1234. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1235. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1236. }
  1237. var i = byteLength - 1;
  1238. var mul = 1;
  1239. this[offset + i] = value & 0xFF;
  1240. while (--i >= 0 && (mul *= 0x100)) {
  1241. this[offset + i] = (value / mul) & 0xFF;
  1242. }
  1243. return offset + byteLength
  1244. };
  1245. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1246. value = +value;
  1247. offset = offset | 0;
  1248. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  1249. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1250. this[offset] = (value & 0xff);
  1251. return offset + 1
  1252. };
  1253. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1254. if (value < 0) value = 0xffff + value + 1;
  1255. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1256. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1257. (littleEndian ? i : 1 - i) * 8;
  1258. }
  1259. }
  1260. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1261. value = +value;
  1262. offset = offset | 0;
  1263. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1264. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1265. this[offset] = (value & 0xff);
  1266. this[offset + 1] = (value >>> 8);
  1267. } else {
  1268. objectWriteUInt16(this, value, offset, true);
  1269. }
  1270. return offset + 2
  1271. };
  1272. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1273. value = +value;
  1274. offset = offset | 0;
  1275. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1276. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1277. this[offset] = (value >>> 8);
  1278. this[offset + 1] = (value & 0xff);
  1279. } else {
  1280. objectWriteUInt16(this, value, offset, false);
  1281. }
  1282. return offset + 2
  1283. };
  1284. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1285. if (value < 0) value = 0xffffffff + value + 1;
  1286. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1287. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  1288. }
  1289. }
  1290. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1291. value = +value;
  1292. offset = offset | 0;
  1293. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1294. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1295. this[offset + 3] = (value >>> 24);
  1296. this[offset + 2] = (value >>> 16);
  1297. this[offset + 1] = (value >>> 8);
  1298. this[offset] = (value & 0xff);
  1299. } else {
  1300. objectWriteUInt32(this, value, offset, true);
  1301. }
  1302. return offset + 4
  1303. };
  1304. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1305. value = +value;
  1306. offset = offset | 0;
  1307. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1308. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1309. this[offset] = (value >>> 24);
  1310. this[offset + 1] = (value >>> 16);
  1311. this[offset + 2] = (value >>> 8);
  1312. this[offset + 3] = (value & 0xff);
  1313. } else {
  1314. objectWriteUInt32(this, value, offset, false);
  1315. }
  1316. return offset + 4
  1317. };
  1318. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1319. value = +value;
  1320. offset = offset | 0;
  1321. if (!noAssert) {
  1322. var limit = Math.pow(2, 8 * byteLength - 1);
  1323. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1324. }
  1325. var i = 0;
  1326. var mul = 1;
  1327. var sub = 0;
  1328. this[offset] = value & 0xFF;
  1329. while (++i < byteLength && (mul *= 0x100)) {
  1330. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1331. sub = 1;
  1332. }
  1333. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1334. }
  1335. return offset + byteLength
  1336. };
  1337. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1338. value = +value;
  1339. offset = offset | 0;
  1340. if (!noAssert) {
  1341. var limit = Math.pow(2, 8 * byteLength - 1);
  1342. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1343. }
  1344. var i = byteLength - 1;
  1345. var mul = 1;
  1346. var sub = 0;
  1347. this[offset + i] = value & 0xFF;
  1348. while (--i >= 0 && (mul *= 0x100)) {
  1349. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1350. sub = 1;
  1351. }
  1352. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1353. }
  1354. return offset + byteLength
  1355. };
  1356. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1357. value = +value;
  1358. offset = offset | 0;
  1359. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  1360. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1361. if (value < 0) value = 0xff + value + 1;
  1362. this[offset] = (value & 0xff);
  1363. return offset + 1
  1364. };
  1365. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1366. value = +value;
  1367. offset = offset | 0;
  1368. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1369. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1370. this[offset] = (value & 0xff);
  1371. this[offset + 1] = (value >>> 8);
  1372. } else {
  1373. objectWriteUInt16(this, value, offset, true);
  1374. }
  1375. return offset + 2
  1376. };
  1377. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1378. value = +value;
  1379. offset = offset | 0;
  1380. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1381. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1382. this[offset] = (value >>> 8);
  1383. this[offset + 1] = (value & 0xff);
  1384. } else {
  1385. objectWriteUInt16(this, value, offset, false);
  1386. }
  1387. return offset + 2
  1388. };
  1389. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1390. value = +value;
  1391. offset = offset | 0;
  1392. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1393. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1394. this[offset] = (value & 0xff);
  1395. this[offset + 1] = (value >>> 8);
  1396. this[offset + 2] = (value >>> 16);
  1397. this[offset + 3] = (value >>> 24);
  1398. } else {
  1399. objectWriteUInt32(this, value, offset, true);
  1400. }
  1401. return offset + 4
  1402. };
  1403. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1404. value = +value;
  1405. offset = offset | 0;
  1406. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1407. if (value < 0) value = 0xffffffff + value + 1;
  1408. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1409. this[offset] = (value >>> 24);
  1410. this[offset + 1] = (value >>> 16);
  1411. this[offset + 2] = (value >>> 8);
  1412. this[offset + 3] = (value & 0xff);
  1413. } else {
  1414. objectWriteUInt32(this, value, offset, false);
  1415. }
  1416. return offset + 4
  1417. };
  1418. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1419. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1420. if (offset < 0) throw new RangeError('Index out of range')
  1421. }
  1422. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1423. if (!noAssert) {
  1424. checkIEEE754(buf, value, offset, 4);
  1425. }
  1426. write(buf, value, offset, littleEndian, 23, 4);
  1427. return offset + 4
  1428. }
  1429. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1430. return writeFloat(this, value, offset, true, noAssert)
  1431. };
  1432. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1433. return writeFloat(this, value, offset, false, noAssert)
  1434. };
  1435. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1436. if (!noAssert) {
  1437. checkIEEE754(buf, value, offset, 8);
  1438. }
  1439. write(buf, value, offset, littleEndian, 52, 8);
  1440. return offset + 8
  1441. }
  1442. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1443. return writeDouble(this, value, offset, true, noAssert)
  1444. };
  1445. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1446. return writeDouble(this, value, offset, false, noAssert)
  1447. };
  1448. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1449. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1450. if (!start) start = 0;
  1451. if (!end && end !== 0) end = this.length;
  1452. if (targetStart >= target.length) targetStart = target.length;
  1453. if (!targetStart) targetStart = 0;
  1454. if (end > 0 && end < start) end = start;
  1455. // Copy 0 bytes; we're done
  1456. if (end === start) return 0
  1457. if (target.length === 0 || this.length === 0) return 0
  1458. // Fatal error conditions
  1459. if (targetStart < 0) {
  1460. throw new RangeError('targetStart out of bounds')
  1461. }
  1462. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1463. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1464. // Are we oob?
  1465. if (end > this.length) end = this.length;
  1466. if (target.length - targetStart < end - start) {
  1467. end = target.length - targetStart + start;
  1468. }
  1469. var len = end - start;
  1470. var i;
  1471. if (this === target && start < targetStart && targetStart < end) {
  1472. // descending copy from end
  1473. for (i = len - 1; i >= 0; --i) {
  1474. target[i + targetStart] = this[i + start];
  1475. }
  1476. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1477. // ascending copy from start
  1478. for (i = 0; i < len; ++i) {
  1479. target[i + targetStart] = this[i + start];
  1480. }
  1481. } else {
  1482. Uint8Array.prototype.set.call(
  1483. target,
  1484. this.subarray(start, start + len),
  1485. targetStart
  1486. );
  1487. }
  1488. return len
  1489. };
  1490. // Usage:
  1491. // buffer.fill(number[, offset[, end]])
  1492. // buffer.fill(buffer[, offset[, end]])
  1493. // buffer.fill(string[, offset[, end]][, encoding])
  1494. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1495. // Handle string cases:
  1496. if (typeof val === 'string') {
  1497. if (typeof start === 'string') {
  1498. encoding = start;
  1499. start = 0;
  1500. end = this.length;
  1501. } else if (typeof end === 'string') {
  1502. encoding = end;
  1503. end = this.length;
  1504. }
  1505. if (val.length === 1) {
  1506. var code = val.charCodeAt(0);
  1507. if (code < 256) {
  1508. val = code;
  1509. }
  1510. }
  1511. if (encoding !== undefined && typeof encoding !== 'string') {
  1512. throw new TypeError('encoding must be a string')
  1513. }
  1514. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1515. throw new TypeError('Unknown encoding: ' + encoding)
  1516. }
  1517. } else if (typeof val === 'number') {
  1518. val = val & 255;
  1519. }
  1520. // Invalid ranges are not set to a default, so can range check early.
  1521. if (start < 0 || this.length < start || this.length < end) {
  1522. throw new RangeError('Out of range index')
  1523. }
  1524. if (end <= start) {
  1525. return this
  1526. }
  1527. start = start >>> 0;
  1528. end = end === undefined ? this.length : end >>> 0;
  1529. if (!val) val = 0;
  1530. var i;
  1531. if (typeof val === 'number') {
  1532. for (i = start; i < end; ++i) {
  1533. this[i] = val;
  1534. }
  1535. } else {
  1536. var bytes = internalIsBuffer(val)
  1537. ? val
  1538. : utf8ToBytes(new Buffer(val, encoding).toString());
  1539. var len = bytes.length;
  1540. for (i = 0; i < end - start; ++i) {
  1541. this[i + start] = bytes[i % len];
  1542. }
  1543. }
  1544. return this
  1545. };
  1546. // HELPER FUNCTIONS
  1547. // ================
  1548. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  1549. function base64clean (str) {
  1550. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1551. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  1552. // Node converts strings with length < 2 to ''
  1553. if (str.length < 2) return ''
  1554. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1555. while (str.length % 4 !== 0) {
  1556. str = str + '=';
  1557. }
  1558. return str
  1559. }
  1560. function stringtrim (str) {
  1561. if (str.trim) return str.trim()
  1562. return str.replace(/^\s+|\s+$/g, '')
  1563. }
  1564. function toHex (n) {
  1565. if (n < 16) return '0' + n.toString(16)
  1566. return n.toString(16)
  1567. }
  1568. function utf8ToBytes (string, units) {
  1569. units = units || Infinity;
  1570. var codePoint;
  1571. var length = string.length;
  1572. var leadSurrogate = null;
  1573. var bytes = [];
  1574. for (var i = 0; i < length; ++i) {
  1575. codePoint = string.charCodeAt(i);
  1576. // is surrogate component
  1577. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1578. // last char was a lead
  1579. if (!leadSurrogate) {
  1580. // no lead yet
  1581. if (codePoint > 0xDBFF) {
  1582. // unexpected trail
  1583. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1584. continue
  1585. } else if (i + 1 === length) {
  1586. // unpaired lead
  1587. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1588. continue
  1589. }
  1590. // valid lead
  1591. leadSurrogate = codePoint;
  1592. continue
  1593. }
  1594. // 2 leads in a row
  1595. if (codePoint < 0xDC00) {
  1596. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1597. leadSurrogate = codePoint;
  1598. continue
  1599. }
  1600. // valid surrogate pair
  1601. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  1602. } else if (leadSurrogate) {
  1603. // valid bmp char, but last char was a lead
  1604. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1605. }
  1606. leadSurrogate = null;
  1607. // encode utf8
  1608. if (codePoint < 0x80) {
  1609. if ((units -= 1) < 0) break
  1610. bytes.push(codePoint);
  1611. } else if (codePoint < 0x800) {
  1612. if ((units -= 2) < 0) break
  1613. bytes.push(
  1614. codePoint >> 0x6 | 0xC0,
  1615. codePoint & 0x3F | 0x80
  1616. );
  1617. } else if (codePoint < 0x10000) {
  1618. if ((units -= 3) < 0) break
  1619. bytes.push(
  1620. codePoint >> 0xC | 0xE0,
  1621. codePoint >> 0x6 & 0x3F | 0x80,
  1622. codePoint & 0x3F | 0x80
  1623. );
  1624. } else if (codePoint < 0x110000) {
  1625. if ((units -= 4) < 0) break
  1626. bytes.push(
  1627. codePoint >> 0x12 | 0xF0,
  1628. codePoint >> 0xC & 0x3F | 0x80,
  1629. codePoint >> 0x6 & 0x3F | 0x80,
  1630. codePoint & 0x3F | 0x80
  1631. );
  1632. } else {
  1633. throw new Error('Invalid code point')
  1634. }
  1635. }
  1636. return bytes
  1637. }
  1638. function asciiToBytes (str) {
  1639. var byteArray = [];
  1640. for (var i = 0; i < str.length; ++i) {
  1641. // Node's code seems to be doing this and not & 0x7F..
  1642. byteArray.push(str.charCodeAt(i) & 0xFF);
  1643. }
  1644. return byteArray
  1645. }
  1646. function utf16leToBytes (str, units) {
  1647. var c, hi, lo;
  1648. var byteArray = [];
  1649. for (var i = 0; i < str.length; ++i) {
  1650. if ((units -= 2) < 0) break
  1651. c = str.charCodeAt(i);
  1652. hi = c >> 8;
  1653. lo = c % 256;
  1654. byteArray.push(lo);
  1655. byteArray.push(hi);
  1656. }
  1657. return byteArray
  1658. }
  1659. function base64ToBytes (str) {
  1660. return toByteArray(base64clean(str))
  1661. }
  1662. function blitBuffer (src, dst, offset, length) {
  1663. for (var i = 0; i < length; ++i) {
  1664. if ((i + offset >= dst.length) || (i >= src.length)) break
  1665. dst[i + offset] = src[i];
  1666. }
  1667. return i
  1668. }
  1669. function isnan (val) {
  1670. return val !== val // eslint-disable-line no-self-compare
  1671. }
  1672. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  1673. // The _isBuffer check is for Safari 5-7 support, because it's missing
  1674. // Object.prototype.constructor. Remove this eventually
  1675. function isBuffer(obj) {
  1676. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  1677. }
  1678. function isFastBuffer (obj) {
  1679. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  1680. }
  1681. // For Node v0.10 support. Remove this eventually.
  1682. function isSlowBuffer (obj) {
  1683. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  1684. }
  1685. class CsvError extends Error {
  1686. constructor(code, message, options, ...contexts) {
  1687. if(Array.isArray(message)) message = message.join(' ').trim();
  1688. super(message);
  1689. if(Error.captureStackTrace !== undefined){
  1690. Error.captureStackTrace(this, CsvError);
  1691. }
  1692. this.code = code;
  1693. for(const context of contexts){
  1694. for(const key in context){
  1695. const value = context[key];
  1696. this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
  1697. }
  1698. }
  1699. }
  1700. }
  1701. const is_object = function(obj){
  1702. return (typeof obj === 'object' && obj !== null && !Array.isArray(obj));
  1703. };
  1704. const normalize_columns_array = function(columns){
  1705. const normalizedColumns = [];
  1706. for(let i = 0, l = columns.length; i < l; i++){
  1707. const column = columns[i];
  1708. if(column === undefined || column === null || column === false){
  1709. normalizedColumns[i] = { disabled: true };
  1710. }else if(typeof column === 'string'){
  1711. normalizedColumns[i] = { name: column };
  1712. }else if(is_object(column)){
  1713. if(typeof column.name !== 'string'){
  1714. throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [
  1715. 'Option columns missing name:',
  1716. `property "name" is required at position ${i}`,
  1717. 'when column is an object literal'
  1718. ]);
  1719. }
  1720. normalizedColumns[i] = column;
  1721. }else {
  1722. throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [
  1723. 'Invalid column definition:',
  1724. 'expect a string or a literal object,',
  1725. `got ${JSON.stringify(column)} at position ${i}`
  1726. ]);
  1727. }
  1728. }
  1729. return normalizedColumns;
  1730. };
  1731. class ResizeableBuffer{
  1732. constructor(size=100){
  1733. this.size = size;
  1734. this.length = 0;
  1735. this.buf = Buffer.allocUnsafe(size);
  1736. }
  1737. prepend(val){
  1738. if(isBuffer(val)){
  1739. const length = this.length + val.length;
  1740. if(length >= this.size){
  1741. this.resize();
  1742. if(length >= this.size){
  1743. throw Error('INVALID_BUFFER_STATE');
  1744. }
  1745. }
  1746. const buf = this.buf;
  1747. this.buf = Buffer.allocUnsafe(this.size);
  1748. val.copy(this.buf, 0);
  1749. buf.copy(this.buf, val.length);
  1750. this.length += val.length;
  1751. }else {
  1752. const length = this.length++;
  1753. if(length === this.size){
  1754. this.resize();
  1755. }
  1756. const buf = this.clone();
  1757. this.buf[0] = val;
  1758. buf.copy(this.buf,1, 0, length);
  1759. }
  1760. }
  1761. append(val){
  1762. const length = this.length++;
  1763. if(length === this.size){
  1764. this.resize();
  1765. }
  1766. this.buf[length] = val;
  1767. }
  1768. clone(){
  1769. return Buffer.from(this.buf.slice(0, this.length));
  1770. }
  1771. resize(){
  1772. const length = this.length;
  1773. this.size = this.size * 2;
  1774. const buf = Buffer.allocUnsafe(this.size);
  1775. this.buf.copy(buf,0, 0, length);
  1776. this.buf = buf;
  1777. }
  1778. toString(encoding){
  1779. if(encoding){
  1780. return this.buf.slice(0, this.length).toString(encoding);
  1781. }else {
  1782. return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
  1783. }
  1784. }
  1785. toJSON(){
  1786. return this.toString('utf8');
  1787. }
  1788. reset(){
  1789. this.length = 0;
  1790. }
  1791. }
  1792. // white space characters
  1793. // https://en.wikipedia.org/wiki/Whitespace_character
  1794. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types
  1795. // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff
  1796. const np = 12;
  1797. const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  1798. const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  1799. const space = 32;
  1800. const tab = 9;
  1801. const init_state = function(options){
  1802. return {
  1803. bomSkipped: false,
  1804. bufBytesStart: 0,
  1805. castField: options.cast_function,
  1806. commenting: false,
  1807. // Current error encountered by a record
  1808. error: undefined,
  1809. enabled: options.from_line === 1,
  1810. escaping: false,
  1811. escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
  1812. // columns can be `false`, `true`, `Array`
  1813. expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
  1814. field: new ResizeableBuffer(20),
  1815. firstLineToHeaders: options.cast_first_line_to_header,
  1816. needMoreDataSize: Math.max(
  1817. // Skip if the remaining buffer smaller than comment
  1818. options.comment !== null ? options.comment.length : 0,
  1819. // Skip if the remaining buffer can be delimiter
  1820. ...options.delimiter.map((delimiter) => delimiter.length),
  1821. // Skip if the remaining buffer can be escape sequence
  1822. options.quote !== null ? options.quote.length : 0,
  1823. ),
  1824. previousBuf: undefined,
  1825. quoting: false,
  1826. stop: false,
  1827. rawBuffer: new ResizeableBuffer(100),
  1828. record: [],
  1829. recordHasError: false,
  1830. record_length: 0,
  1831. recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
  1832. trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]],
  1833. wasQuoting: false,
  1834. wasRowDelimiter: false,
  1835. timchars: [
  1836. Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding),
  1837. Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding),
  1838. Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding),
  1839. Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding),
  1840. Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding),
  1841. ]
  1842. };
  1843. };
  1844. const underscore = function(str){
  1845. return str.replace(/([A-Z])/g, function(_, match){
  1846. return '_' + match.toLowerCase();
  1847. });
  1848. };
  1849. const normalize_options = function(opts){
  1850. const options = {};
  1851. // Merge with user options
  1852. for(const opt in opts){
  1853. options[underscore(opt)] = opts[opt];
  1854. }
  1855. // Normalize option `encoding`
  1856. // Note: defined first because other options depends on it
  1857. // to convert chars/strings into buffers.
  1858. if(options.encoding === undefined || options.encoding === true){
  1859. options.encoding = 'utf8';
  1860. }else if(options.encoding === null || options.encoding === false){
  1861. options.encoding = null;
  1862. }else if(typeof options.encoding !== 'string' && options.encoding !== null){
  1863. throw new CsvError('CSV_INVALID_OPTION_ENCODING', [
  1864. 'Invalid option encoding:',
  1865. 'encoding must be a string or null to return a buffer,',
  1866. `got ${JSON.stringify(options.encoding)}`
  1867. ], options);
  1868. }
  1869. // Normalize option `bom`
  1870. if(options.bom === undefined || options.bom === null || options.bom === false){
  1871. options.bom = false;
  1872. }else if(options.bom !== true){
  1873. throw new CsvError('CSV_INVALID_OPTION_BOM', [
  1874. 'Invalid option bom:', 'bom must be true,',
  1875. `got ${JSON.stringify(options.bom)}`
  1876. ], options);
  1877. }
  1878. // Normalize option `cast`
  1879. options.cast_function = null;
  1880. if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){
  1881. options.cast = undefined;
  1882. }else if(typeof options.cast === 'function'){
  1883. options.cast_function = options.cast;
  1884. options.cast = true;
  1885. }else if(options.cast !== true){
  1886. throw new CsvError('CSV_INVALID_OPTION_CAST', [
  1887. 'Invalid option cast:', 'cast must be true or a function,',
  1888. `got ${JSON.stringify(options.cast)}`
  1889. ], options);
  1890. }
  1891. // Normalize option `cast_date`
  1892. if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){
  1893. options.cast_date = false;
  1894. }else if(options.cast_date === true){
  1895. options.cast_date = function(value){
  1896. const date = Date.parse(value);
  1897. return !isNaN(date) ? new Date(date) : value;
  1898. };
  1899. }else if (typeof options.cast_date !== 'function'){
  1900. throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [
  1901. 'Invalid option cast_date:', 'cast_date must be true or a function,',
  1902. `got ${JSON.stringify(options.cast_date)}`
  1903. ], options);
  1904. }
  1905. // Normalize option `columns`
  1906. options.cast_first_line_to_header = null;
  1907. if(options.columns === true){
  1908. // Fields in the first line are converted as-is to columns
  1909. options.cast_first_line_to_header = undefined;
  1910. }else if(typeof options.columns === 'function'){
  1911. options.cast_first_line_to_header = options.columns;
  1912. options.columns = true;
  1913. }else if(Array.isArray(options.columns)){
  1914. options.columns = normalize_columns_array(options.columns);
  1915. }else if(options.columns === undefined || options.columns === null || options.columns === false){
  1916. options.columns = false;
  1917. }else {
  1918. throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [
  1919. 'Invalid option columns:',
  1920. 'expect an array, a function or true,',
  1921. `got ${JSON.stringify(options.columns)}`
  1922. ], options);
  1923. }
  1924. // Normalize option `group_columns_by_name`
  1925. if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){
  1926. options.group_columns_by_name = false;
  1927. }else if(options.group_columns_by_name !== true){
  1928. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  1929. 'Invalid option group_columns_by_name:',
  1930. 'expect an boolean,',
  1931. `got ${JSON.stringify(options.group_columns_by_name)}`
  1932. ], options);
  1933. }else if(options.columns === false){
  1934. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  1935. 'Invalid option group_columns_by_name:',
  1936. 'the `columns` mode must be activated.'
  1937. ], options);
  1938. }
  1939. // Normalize option `comment`
  1940. if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){
  1941. options.comment = null;
  1942. }else {
  1943. if(typeof options.comment === 'string'){
  1944. options.comment = Buffer.from(options.comment, options.encoding);
  1945. }
  1946. if(!isBuffer(options.comment)){
  1947. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  1948. 'Invalid option comment:',
  1949. 'comment must be a buffer or a string,',
  1950. `got ${JSON.stringify(options.comment)}`
  1951. ], options);
  1952. }
  1953. }
  1954. // Normalize option `comment_no_infix`
  1955. if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){
  1956. options.comment_no_infix = false;
  1957. }else if(options.comment_no_infix !== true){
  1958. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  1959. 'Invalid option comment_no_infix:',
  1960. 'value must be a boolean,',
  1961. `got ${JSON.stringify(options.comment_no_infix)}`
  1962. ], options);
  1963. }
  1964. // Normalize option `delimiter`
  1965. const delimiter_json = JSON.stringify(options.delimiter);
  1966. if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
  1967. if(options.delimiter.length === 0){
  1968. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  1969. 'Invalid option delimiter:',
  1970. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  1971. `got ${delimiter_json}`
  1972. ], options);
  1973. }
  1974. options.delimiter = options.delimiter.map(function(delimiter){
  1975. if(delimiter === undefined || delimiter === null || delimiter === false){
  1976. return Buffer.from(',', options.encoding);
  1977. }
  1978. if(typeof delimiter === 'string'){
  1979. delimiter = Buffer.from(delimiter, options.encoding);
  1980. }
  1981. if(!isBuffer(delimiter) || delimiter.length === 0){
  1982. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  1983. 'Invalid option delimiter:',
  1984. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  1985. `got ${delimiter_json}`
  1986. ], options);
  1987. }
  1988. return delimiter;
  1989. });
  1990. // Normalize option `escape`
  1991. if(options.escape === undefined || options.escape === true){
  1992. options.escape = Buffer.from('"', options.encoding);
  1993. }else if(typeof options.escape === 'string'){
  1994. options.escape = Buffer.from(options.escape, options.encoding);
  1995. }else if (options.escape === null || options.escape === false){
  1996. options.escape = null;
  1997. }
  1998. if(options.escape !== null){
  1999. if(!isBuffer(options.escape)){
  2000. throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
  2001. }
  2002. }
  2003. // Normalize option `from`
  2004. if(options.from === undefined || options.from === null){
  2005. options.from = 1;
  2006. }else {
  2007. if(typeof options.from === 'string' && /\d+/.test(options.from)){
  2008. options.from = parseInt(options.from);
  2009. }
  2010. if(Number.isInteger(options.from)){
  2011. if(options.from < 0){
  2012. throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
  2013. }
  2014. }else {
  2015. throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
  2016. }
  2017. }
  2018. // Normalize option `from_line`
  2019. if(options.from_line === undefined || options.from_line === null){
  2020. options.from_line = 1;
  2021. }else {
  2022. if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){
  2023. options.from_line = parseInt(options.from_line);
  2024. }
  2025. if(Number.isInteger(options.from_line)){
  2026. if(options.from_line <= 0){
  2027. throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
  2028. }
  2029. }else {
  2030. throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
  2031. }
  2032. }
  2033. // Normalize options `ignore_last_delimiters`
  2034. if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){
  2035. options.ignore_last_delimiters = false;
  2036. }else if(typeof options.ignore_last_delimiters === 'number'){
  2037. options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
  2038. if(options.ignore_last_delimiters === 0){
  2039. options.ignore_last_delimiters = false;
  2040. }
  2041. }else if(typeof options.ignore_last_delimiters !== 'boolean'){
  2042. throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [
  2043. 'Invalid option `ignore_last_delimiters`:',
  2044. 'the value must be a boolean value or an integer,',
  2045. `got ${JSON.stringify(options.ignore_last_delimiters)}`
  2046. ], options);
  2047. }
  2048. if(options.ignore_last_delimiters === true && options.columns === false){
  2049. throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [
  2050. 'The option `ignore_last_delimiters`',
  2051. 'requires the activation of the `columns` option'
  2052. ], options);
  2053. }
  2054. // Normalize option `info`
  2055. if(options.info === undefined || options.info === null || options.info === false){
  2056. options.info = false;
  2057. }else if(options.info !== true){
  2058. throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
  2059. }
  2060. // Normalize option `max_record_size`
  2061. if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){
  2062. options.max_record_size = 0;
  2063. }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){
  2064. options.max_record_size = parseInt(options.max_record_size);
  2065. }else {
  2066. throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
  2067. }
  2068. // Normalize option `objname`
  2069. if(options.objname === undefined || options.objname === null || options.objname === false){
  2070. options.objname = undefined;
  2071. }else if(isBuffer(options.objname)){
  2072. if(options.objname.length === 0){
  2073. throw new Error(`Invalid Option: objname must be a non empty buffer`);
  2074. }
  2075. if(options.encoding === null);else {
  2076. options.objname = options.objname.toString(options.encoding);
  2077. }
  2078. }else if(typeof options.objname === 'string'){
  2079. if(options.objname.length === 0){
  2080. throw new Error(`Invalid Option: objname must be a non empty string`);
  2081. }
  2082. // Great, nothing to do
  2083. }else if(typeof options.objname === 'number');else {
  2084. throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
  2085. }
  2086. if(options.objname !== undefined){
  2087. if(typeof options.objname === 'number'){
  2088. if(options.columns !== false){
  2089. throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field');
  2090. }
  2091. }else { // A string or a buffer
  2092. if(options.columns === false){
  2093. throw Error('Invalid Option: objname field must be combined with columns or be defined as an index');
  2094. }
  2095. }
  2096. }
  2097. // Normalize option `on_record`
  2098. if(options.on_record === undefined || options.on_record === null){
  2099. options.on_record = undefined;
  2100. }else if(typeof options.on_record !== 'function'){
  2101. throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [
  2102. 'Invalid option `on_record`:',
  2103. 'expect a function,',
  2104. `got ${JSON.stringify(options.on_record)}`
  2105. ], options);
  2106. }
  2107. // Normalize option `quote`
  2108. if(options.quote === null || options.quote === false || options.quote === ''){
  2109. options.quote = null;
  2110. }else {
  2111. if(options.quote === undefined || options.quote === true){
  2112. options.quote = Buffer.from('"', options.encoding);
  2113. }else if(typeof options.quote === 'string'){
  2114. options.quote = Buffer.from(options.quote, options.encoding);
  2115. }
  2116. if(!isBuffer(options.quote)){
  2117. throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
  2118. }
  2119. }
  2120. // Normalize option `raw`
  2121. if(options.raw === undefined || options.raw === null || options.raw === false){
  2122. options.raw = false;
  2123. }else if(options.raw !== true){
  2124. throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
  2125. }
  2126. // Normalize option `record_delimiter`
  2127. if(options.record_delimiter === undefined){
  2128. options.record_delimiter = [];
  2129. }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){
  2130. if(options.record_delimiter.length === 0){
  2131. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  2132. 'Invalid option `record_delimiter`:',
  2133. 'value must be a non empty string or buffer,',
  2134. `got ${JSON.stringify(options.record_delimiter)}`
  2135. ], options);
  2136. }
  2137. options.record_delimiter = [options.record_delimiter];
  2138. }else if(!Array.isArray(options.record_delimiter)){
  2139. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  2140. 'Invalid option `record_delimiter`:',
  2141. 'value must be a string, a buffer or array of string|buffer,',
  2142. `got ${JSON.stringify(options.record_delimiter)}`
  2143. ], options);
  2144. }
  2145. options.record_delimiter = options.record_delimiter.map(function(rd, i){
  2146. if(typeof rd !== 'string' && ! isBuffer(rd)){
  2147. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  2148. 'Invalid option `record_delimiter`:',
  2149. 'value must be a string, a buffer or array of string|buffer',
  2150. `at index ${i},`,
  2151. `got ${JSON.stringify(rd)}`
  2152. ], options);
  2153. }else if(rd.length === 0){
  2154. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  2155. 'Invalid option `record_delimiter`:',
  2156. 'value must be a non empty string or buffer',
  2157. `at index ${i},`,
  2158. `got ${JSON.stringify(rd)}`
  2159. ], options);
  2160. }
  2161. if(typeof rd === 'string'){
  2162. rd = Buffer.from(rd, options.encoding);
  2163. }
  2164. return rd;
  2165. });
  2166. // Normalize option `relax_column_count`
  2167. if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){
  2168. options.relax_column_count = false;
  2169. }else {
  2170. throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
  2171. }
  2172. if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){
  2173. options.relax_column_count_less = false;
  2174. }else {
  2175. throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
  2176. }
  2177. if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){
  2178. options.relax_column_count_more = false;
  2179. }else {
  2180. throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
  2181. }
  2182. // Normalize option `relax_quotes`
  2183. if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){
  2184. options.relax_quotes = false;
  2185. }else {
  2186. throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
  2187. }
  2188. // Normalize option `skip_empty_lines`
  2189. if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){
  2190. options.skip_empty_lines = false;
  2191. }else {
  2192. throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
  2193. }
  2194. // Normalize option `skip_records_with_empty_values`
  2195. if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){
  2196. options.skip_records_with_empty_values = false;
  2197. }else {
  2198. throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
  2199. }
  2200. // Normalize option `skip_records_with_error`
  2201. if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){
  2202. options.skip_records_with_error = false;
  2203. }else {
  2204. throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
  2205. }
  2206. // Normalize option `rtrim`
  2207. if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){
  2208. options.rtrim = false;
  2209. }else if(options.rtrim !== true){
  2210. throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
  2211. }
  2212. // Normalize option `ltrim`
  2213. if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){
  2214. options.ltrim = false;
  2215. }else if(options.ltrim !== true){
  2216. throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
  2217. }
  2218. // Normalize option `trim`
  2219. if(options.trim === undefined || options.trim === null || options.trim === false){
  2220. options.trim = false;
  2221. }else if(options.trim !== true){
  2222. throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
  2223. }
  2224. // Normalize options `trim`, `ltrim` and `rtrim`
  2225. if(options.trim === true && opts.ltrim !== false){
  2226. options.ltrim = true;
  2227. }else if(options.ltrim !== true){
  2228. options.ltrim = false;
  2229. }
  2230. if(options.trim === true && opts.rtrim !== false){
  2231. options.rtrim = true;
  2232. }else if(options.rtrim !== true){
  2233. options.rtrim = false;
  2234. }
  2235. // Normalize option `to`
  2236. if(options.to === undefined || options.to === null){
  2237. options.to = -1;
  2238. }else {
  2239. if(typeof options.to === 'string' && /\d+/.test(options.to)){
  2240. options.to = parseInt(options.to);
  2241. }
  2242. if(Number.isInteger(options.to)){
  2243. if(options.to <= 0){
  2244. throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
  2245. }
  2246. }else {
  2247. throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
  2248. }
  2249. }
  2250. // Normalize option `to_line`
  2251. if(options.to_line === undefined || options.to_line === null){
  2252. options.to_line = -1;
  2253. }else {
  2254. if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){
  2255. options.to_line = parseInt(options.to_line);
  2256. }
  2257. if(Number.isInteger(options.to_line)){
  2258. if(options.to_line <= 0){
  2259. throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
  2260. }
  2261. }else {
  2262. throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
  2263. }
  2264. }
  2265. return options;
  2266. };
  2267. const isRecordEmpty = function(record){
  2268. return record.every((field) => field == null || field.toString && field.toString().trim() === '');
  2269. };
  2270. const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  2271. const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  2272. const boms = {
  2273. // Note, the following are equals:
  2274. // Buffer.from("\ufeff")
  2275. // Buffer.from([239, 187, 191])
  2276. // Buffer.from('EFBBBF', 'hex')
  2277. 'utf8': Buffer.from([239, 187, 191]),
  2278. // Note, the following are equals:
  2279. // Buffer.from "\ufeff", 'utf16le
  2280. // Buffer.from([255, 254])
  2281. 'utf16le': Buffer.from([255, 254])
  2282. };
  2283. const transform = function(original_options = {}) {
  2284. const info = {
  2285. bytes: 0,
  2286. comment_lines: 0,
  2287. empty_lines: 0,
  2288. invalid_field_length: 0,
  2289. lines: 1,
  2290. records: 0
  2291. };
  2292. const options = normalize_options(original_options);
  2293. return {
  2294. info: info,
  2295. original_options: original_options,
  2296. options: options,
  2297. state: init_state(options),
  2298. __needMoreData: function(i, bufLen, end){
  2299. if(end) return false;
  2300. const {encoding, escape, quote} = this.options;
  2301. const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state;
  2302. const numOfCharLeft = bufLen - i - 1;
  2303. const requiredLength = Math.max(
  2304. needMoreDataSize,
  2305. // Skip if the remaining buffer smaller than record delimiter
  2306. // If "record_delimiter" is yet to be discovered:
  2307. // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
  2308. // 2. We set the length to windows line ending in the current encoding
  2309. // Note, that encoding is known from user or bom discovery at that point
  2310. // recordDelimiterMaxLength,
  2311. recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength,
  2312. // Skip if remaining buffer can be an escaped quote
  2313. quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0,
  2314. // Skip if remaining buffer can be record delimiter following the closing quote
  2315. quoting ? (quote.length + recordDelimiterMaxLength) : 0,
  2316. );
  2317. return numOfCharLeft < requiredLength;
  2318. },
  2319. // Central parser implementation
  2320. parse: function(nextBuf, end, push, close){
  2321. const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options;
  2322. let {comment, escape, quote, record_delimiter} = this.options;
  2323. const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state;
  2324. let buf;
  2325. if(previousBuf === undefined){
  2326. if(nextBuf === undefined){
  2327. // Handle empty string
  2328. close();
  2329. return;
  2330. }else {
  2331. buf = nextBuf;
  2332. }
  2333. }else if(previousBuf !== undefined && nextBuf === undefined){
  2334. buf = previousBuf;
  2335. }else {
  2336. buf = Buffer.concat([previousBuf, nextBuf]);
  2337. }
  2338. // Handle UTF BOM
  2339. if(bomSkipped === false){
  2340. if(bom === false){
  2341. this.state.bomSkipped = true;
  2342. }else if(buf.length < 3){
  2343. // No enough data
  2344. if(end === false){
  2345. // Wait for more data
  2346. this.state.previousBuf = buf;
  2347. return;
  2348. }
  2349. }else {
  2350. for(const encoding in boms){
  2351. if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){
  2352. // Skip BOM
  2353. const bomLength = boms[encoding].length;
  2354. this.state.bufBytesStart += bomLength;
  2355. buf = buf.slice(bomLength);
  2356. // Renormalize original options with the new encoding
  2357. this.options = normalize_options({...this.original_options, encoding: encoding});
  2358. // Options will re-evaluate the Buffer with the new encoding
  2359. ({comment, escape, quote } = this.options);
  2360. break;
  2361. }
  2362. }
  2363. this.state.bomSkipped = true;
  2364. }
  2365. }
  2366. const bufLen = buf.length;
  2367. let pos;
  2368. for(pos = 0; pos < bufLen; pos++){
  2369. // Ensure we get enough space to look ahead
  2370. // There should be a way to move this out of the loop
  2371. if(this.__needMoreData(pos, bufLen, end)){
  2372. break;
  2373. }
  2374. if(this.state.wasRowDelimiter === true){
  2375. this.info.lines++;
  2376. this.state.wasRowDelimiter = false;
  2377. }
  2378. if(to_line !== -1 && this.info.lines > to_line){
  2379. this.state.stop = true;
  2380. close();
  2381. return;
  2382. }
  2383. // Auto discovery of record_delimiter, unix, mac and windows supported
  2384. if(this.state.quoting === false && record_delimiter.length === 0){
  2385. const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
  2386. if(record_delimiterCount){
  2387. record_delimiter = this.options.record_delimiter;
  2388. }
  2389. }
  2390. const chr = buf[pos];
  2391. if(raw === true){
  2392. rawBuffer.append(chr);
  2393. }
  2394. if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){
  2395. this.state.wasRowDelimiter = true;
  2396. }
  2397. // Previous char was a valid escape char
  2398. // treat the current char as a regular char
  2399. if(this.state.escaping === true){
  2400. this.state.escaping = false;
  2401. }else {
  2402. // Escape is only active inside quoted fields
  2403. // We are quoting, the char is an escape chr and there is a chr to escape
  2404. // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){
  2405. if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){
  2406. if(escapeIsQuote){
  2407. if(this.__isQuote(buf, pos+escape.length)){
  2408. this.state.escaping = true;
  2409. pos += escape.length - 1;
  2410. continue;
  2411. }
  2412. }else {
  2413. this.state.escaping = true;
  2414. pos += escape.length - 1;
  2415. continue;
  2416. }
  2417. }
  2418. // Not currently escaping and chr is a quote
  2419. // TODO: need to compare bytes instead of single char
  2420. if(this.state.commenting === false && this.__isQuote(buf, pos)){
  2421. if(this.state.quoting === true){
  2422. const nextChr = buf[pos+quote.length];
  2423. const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length);
  2424. const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr);
  2425. const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr);
  2426. const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length);
  2427. // Escape a quote
  2428. // Treat next char as a regular character
  2429. if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){
  2430. pos += escape.length - 1;
  2431. }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){
  2432. this.state.quoting = false;
  2433. this.state.wasQuoting = true;
  2434. pos += quote.length - 1;
  2435. continue;
  2436. }else if(relax_quotes === false){
  2437. const err = this.__error(
  2438. new CsvError('CSV_INVALID_CLOSING_QUOTE', [
  2439. 'Invalid Closing Quote:',
  2440. `got "${String.fromCharCode(nextChr)}"`,
  2441. `at line ${this.info.lines}`,
  2442. 'instead of delimiter, record delimiter, trimable character',
  2443. '(if activated) or comment',
  2444. ], this.options, this.__infoField())
  2445. );
  2446. if(err !== undefined) return err;
  2447. }else {
  2448. this.state.quoting = false;
  2449. this.state.wasQuoting = true;
  2450. this.state.field.prepend(quote);
  2451. pos += quote.length - 1;
  2452. }
  2453. }else {
  2454. if(this.state.field.length !== 0){
  2455. // In relax_quotes mode, treat opening quote preceded by chrs as regular
  2456. if(relax_quotes === false){
  2457. const info = this.__infoField();
  2458. const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
  2459. const err = this.__error(
  2460. new CsvError('INVALID_OPENING_QUOTE', [
  2461. 'Invalid Opening Quote:',
  2462. `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
  2463. bom ? `(${bom} bom)` : undefined
  2464. ], this.options, info, {
  2465. field: this.state.field,
  2466. })
  2467. );
  2468. if(err !== undefined) return err;
  2469. }
  2470. }else {
  2471. this.state.quoting = true;
  2472. pos += quote.length - 1;
  2473. continue;
  2474. }
  2475. }
  2476. }
  2477. if(this.state.quoting === false){
  2478. const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
  2479. if(recordDelimiterLength !== 0){
  2480. // Do not emit comments which take a full line
  2481. const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
  2482. if(skipCommentLine){
  2483. this.info.comment_lines++;
  2484. // Skip full comment line
  2485. }else {
  2486. // Activate records emition if above from_line
  2487. if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){
  2488. this.state.enabled = true;
  2489. this.__resetField();
  2490. this.__resetRecord();
  2491. pos += recordDelimiterLength - 1;
  2492. continue;
  2493. }
  2494. // Skip if line is empty and skip_empty_lines activated
  2495. if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){
  2496. this.info.empty_lines++;
  2497. pos += recordDelimiterLength - 1;
  2498. continue;
  2499. }
  2500. this.info.bytes = this.state.bufBytesStart + pos;
  2501. const errField = this.__onField();
  2502. if(errField !== undefined) return errField;
  2503. this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
  2504. const errRecord = this.__onRecord(push);
  2505. if(errRecord !== undefined) return errRecord;
  2506. if(to !== -1 && this.info.records >= to){
  2507. this.state.stop = true;
  2508. close();
  2509. return;
  2510. }
  2511. }
  2512. this.state.commenting = false;
  2513. pos += recordDelimiterLength - 1;
  2514. continue;
  2515. }
  2516. if(this.state.commenting){
  2517. continue;
  2518. }
  2519. const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr);
  2520. if(commentCount !== 0 && (comment_no_infix === false || this.state.field.length === 0)){
  2521. this.state.commenting = true;
  2522. continue;
  2523. }
  2524. const delimiterLength = this.__isDelimiter(buf, pos, chr);
  2525. if(delimiterLength !== 0){
  2526. this.info.bytes = this.state.bufBytesStart + pos;
  2527. const errField = this.__onField();
  2528. if(errField !== undefined) return errField;
  2529. pos += delimiterLength - 1;
  2530. continue;
  2531. }
  2532. }
  2533. }
  2534. if(this.state.commenting === false){
  2535. if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){
  2536. return this.__error(
  2537. new CsvError('CSV_MAX_RECORD_SIZE', [
  2538. 'Max Record Size:',
  2539. 'record exceed the maximum number of tolerated bytes',
  2540. `of ${max_record_size}`,
  2541. `at line ${this.info.lines}`,
  2542. ], this.options, this.__infoField())
  2543. );
  2544. }
  2545. }
  2546. const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
  2547. // rtrim in non quoting is handle in __onField
  2548. const rappend = rtrim === false || this.state.wasQuoting === false;
  2549. if(lappend === true && rappend === true){
  2550. this.state.field.append(chr);
  2551. }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){
  2552. return this.__error(
  2553. new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [
  2554. 'Invalid Closing Quote:',
  2555. 'found non trimable byte after quote',
  2556. `at line ${this.info.lines}`,
  2557. ], this.options, this.__infoField())
  2558. );
  2559. }else {
  2560. if(lappend === false){
  2561. pos += this.__isCharTrimable(buf, pos) - 1;
  2562. }
  2563. continue;
  2564. }
  2565. }
  2566. if(end === true){
  2567. // Ensure we are not ending in a quoting state
  2568. if(this.state.quoting === true){
  2569. const err = this.__error(
  2570. new CsvError('CSV_QUOTE_NOT_CLOSED', [
  2571. 'Quote Not Closed:',
  2572. `the parsing is finished with an opening quote at line ${this.info.lines}`,
  2573. ], this.options, this.__infoField())
  2574. );
  2575. if(err !== undefined) return err;
  2576. }else {
  2577. // Skip last line if it has no characters
  2578. if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){
  2579. this.info.bytes = this.state.bufBytesStart + pos;
  2580. const errField = this.__onField();
  2581. if(errField !== undefined) return errField;
  2582. const errRecord = this.__onRecord(push);
  2583. if(errRecord !== undefined) return errRecord;
  2584. }else if(this.state.wasRowDelimiter === true){
  2585. this.info.empty_lines++;
  2586. }else if(this.state.commenting === true){
  2587. this.info.comment_lines++;
  2588. }
  2589. }
  2590. }else {
  2591. this.state.bufBytesStart += pos;
  2592. this.state.previousBuf = buf.slice(pos);
  2593. }
  2594. if(this.state.wasRowDelimiter === true){
  2595. this.info.lines++;
  2596. this.state.wasRowDelimiter = false;
  2597. }
  2598. },
  2599. __onRecord: function(push){
  2600. const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options;
  2601. const {enabled, record} = this.state;
  2602. if(enabled === false){
  2603. return this.__resetRecord();
  2604. }
  2605. // Convert the first line into column names
  2606. const recordLength = record.length;
  2607. if(columns === true){
  2608. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  2609. this.__resetRecord();
  2610. return;
  2611. }
  2612. return this.__firstLineToColumns(record);
  2613. }
  2614. if(columns === false && this.info.records === 0){
  2615. this.state.expectedRecordLength = recordLength;
  2616. }
  2617. if(recordLength !== this.state.expectedRecordLength){
  2618. const err = columns === false ?
  2619. new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [
  2620. 'Invalid Record Length:',
  2621. `expect ${this.state.expectedRecordLength},`,
  2622. `got ${recordLength} on line ${this.info.lines}`,
  2623. ], this.options, this.__infoField(), {
  2624. record: record,
  2625. })
  2626. :
  2627. new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [
  2628. 'Invalid Record Length:',
  2629. `columns length is ${columns.length},`, // rename columns
  2630. `got ${recordLength} on line ${this.info.lines}`,
  2631. ], this.options, this.__infoField(), {
  2632. record: record,
  2633. });
  2634. if(relax_column_count === true ||
  2635. (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) ||
  2636. (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){
  2637. this.info.invalid_field_length++;
  2638. this.state.error = err;
  2639. // Error is undefined with skip_records_with_error
  2640. }else {
  2641. const finalErr = this.__error(err);
  2642. if(finalErr) return finalErr;
  2643. }
  2644. }
  2645. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  2646. this.__resetRecord();
  2647. return;
  2648. }
  2649. if(this.state.recordHasError === true){
  2650. this.__resetRecord();
  2651. this.state.recordHasError = false;
  2652. return;
  2653. }
  2654. this.info.records++;
  2655. if(from === 1 || this.info.records >= from){
  2656. const {objname} = this.options;
  2657. // With columns, records are object
  2658. if(columns !== false){
  2659. const obj = {};
  2660. // Transform record array to an object
  2661. for(let i = 0, l = record.length; i < l; i++){
  2662. if(columns[i] === undefined || columns[i].disabled) continue;
  2663. // Turn duplicate columns into an array
  2664. if (group_columns_by_name === true && obj[columns[i].name] !== undefined) {
  2665. if (Array.isArray(obj[columns[i].name])) {
  2666. obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
  2667. } else {
  2668. obj[columns[i].name] = [obj[columns[i].name], record[i]];
  2669. }
  2670. } else {
  2671. obj[columns[i].name] = record[i];
  2672. }
  2673. }
  2674. // Without objname (default)
  2675. if(raw === true || info === true){
  2676. const extRecord = Object.assign(
  2677. {record: obj},
  2678. (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}),
  2679. (info === true ? {info: this.__infoRecord()}: {})
  2680. );
  2681. const err = this.__push(
  2682. objname === undefined ? extRecord : [obj[objname], extRecord]
  2683. , push);
  2684. if(err){
  2685. return err;
  2686. }
  2687. }else {
  2688. const err = this.__push(
  2689. objname === undefined ? obj : [obj[objname], obj]
  2690. , push);
  2691. if(err){
  2692. return err;
  2693. }
  2694. }
  2695. // Without columns, records are array
  2696. }else {
  2697. if(raw === true || info === true){
  2698. const extRecord = Object.assign(
  2699. {record: record},
  2700. raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {},
  2701. info === true ? {info: this.__infoRecord()}: {}
  2702. );
  2703. const err = this.__push(
  2704. objname === undefined ? extRecord : [record[objname], extRecord]
  2705. , push);
  2706. if(err){
  2707. return err;
  2708. }
  2709. }else {
  2710. const err = this.__push(
  2711. objname === undefined ? record : [record[objname], record]
  2712. , push);
  2713. if(err){
  2714. return err;
  2715. }
  2716. }
  2717. }
  2718. }
  2719. this.__resetRecord();
  2720. },
  2721. __firstLineToColumns: function(record){
  2722. const {firstLineToHeaders} = this.state;
  2723. try{
  2724. const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
  2725. if(!Array.isArray(headers)){
  2726. return this.__error(
  2727. new CsvError('CSV_INVALID_COLUMN_MAPPING', [
  2728. 'Invalid Column Mapping:',
  2729. 'expect an array from column function,',
  2730. `got ${JSON.stringify(headers)}`
  2731. ], this.options, this.__infoField(), {
  2732. headers: headers,
  2733. })
  2734. );
  2735. }
  2736. const normalizedHeaders = normalize_columns_array(headers);
  2737. this.state.expectedRecordLength = normalizedHeaders.length;
  2738. this.options.columns = normalizedHeaders;
  2739. this.__resetRecord();
  2740. return;
  2741. }catch(err){
  2742. return err;
  2743. }
  2744. },
  2745. __resetRecord: function(){
  2746. if(this.options.raw === true){
  2747. this.state.rawBuffer.reset();
  2748. }
  2749. this.state.error = undefined;
  2750. this.state.record = [];
  2751. this.state.record_length = 0;
  2752. },
  2753. __onField: function(){
  2754. const {cast, encoding, rtrim, max_record_size} = this.options;
  2755. const {enabled, wasQuoting} = this.state;
  2756. // Short circuit for the from_line options
  2757. if(enabled === false){
  2758. return this.__resetField();
  2759. }
  2760. let field = this.state.field.toString(encoding);
  2761. if(rtrim === true && wasQuoting === false){
  2762. field = field.trimRight();
  2763. }
  2764. if(cast === true){
  2765. const [err, f] = this.__cast(field);
  2766. if(err !== undefined) return err;
  2767. field = f;
  2768. }
  2769. this.state.record.push(field);
  2770. // Increment record length if record size must not exceed a limit
  2771. if(max_record_size !== 0 && typeof field === 'string'){
  2772. this.state.record_length += field.length;
  2773. }
  2774. this.__resetField();
  2775. },
  2776. __resetField: function(){
  2777. this.state.field.reset();
  2778. this.state.wasQuoting = false;
  2779. },
  2780. __push: function(record, push){
  2781. const {on_record} = this.options;
  2782. if(on_record !== undefined){
  2783. const info = this.__infoRecord();
  2784. try{
  2785. record = on_record.call(null, record, info);
  2786. }catch(err){
  2787. return err;
  2788. }
  2789. if(record === undefined || record === null){ return; }
  2790. }
  2791. push(record);
  2792. },
  2793. // Return a tuple with the error and the casted value
  2794. __cast: function(field){
  2795. const {columns, relax_column_count} = this.options;
  2796. const isColumns = Array.isArray(columns);
  2797. // Dont loose time calling cast
  2798. // because the final record is an object
  2799. // and this field can't be associated to a key present in columns
  2800. if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){
  2801. return [undefined, undefined];
  2802. }
  2803. if(this.state.castField !== null){
  2804. try{
  2805. const info = this.__infoField();
  2806. return [undefined, this.state.castField.call(null, field, info)];
  2807. }catch(err){
  2808. return [err];
  2809. }
  2810. }
  2811. if(this.__isFloat(field)){
  2812. return [undefined, parseFloat(field)];
  2813. }else if(this.options.cast_date !== false){
  2814. const info = this.__infoField();
  2815. return [undefined, this.options.cast_date.call(null, field, info)];
  2816. }
  2817. return [undefined, field];
  2818. },
  2819. // Helper to test if a character is a space or a line delimiter
  2820. __isCharTrimable: function(buf, pos){
  2821. const isTrim = (buf, pos) => {
  2822. const {timchars} = this.state;
  2823. loop1: for(let i = 0; i < timchars.length; i++){
  2824. const timchar = timchars[i];
  2825. for(let j = 0; j < timchar.length; j++){
  2826. if(timchar[j] !== buf[pos+j]) continue loop1;
  2827. }
  2828. return timchar.length;
  2829. }
  2830. return 0;
  2831. };
  2832. return isTrim(buf, pos);
  2833. },
  2834. // Keep it in case we implement the `cast_int` option
  2835. // __isInt(value){
  2836. // // return Number.isInteger(parseInt(value))
  2837. // // return !isNaN( parseInt( obj ) );
  2838. // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
  2839. // }
  2840. __isFloat: function(value){
  2841. return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery
  2842. },
  2843. __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){
  2844. if(sourceBuf[0] !== firstByte) return 0;
  2845. const sourceLength = sourceBuf.length;
  2846. for(let i = 1; i < sourceLength; i++){
  2847. if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0;
  2848. }
  2849. return sourceLength;
  2850. },
  2851. __isDelimiter: function(buf, pos, chr){
  2852. const {delimiter, ignore_last_delimiters} = this.options;
  2853. if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){
  2854. return 0;
  2855. }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){
  2856. return 0;
  2857. }
  2858. loop1: for(let i = 0; i < delimiter.length; i++){
  2859. const del = delimiter[i];
  2860. if(del[0] === chr){
  2861. for(let j = 1; j < del.length; j++){
  2862. if(del[j] !== buf[pos+j]) continue loop1;
  2863. }
  2864. return del.length;
  2865. }
  2866. }
  2867. return 0;
  2868. },
  2869. __isRecordDelimiter: function(chr, buf, pos){
  2870. const {record_delimiter} = this.options;
  2871. const recordDelimiterLength = record_delimiter.length;
  2872. loop1: for(let i = 0; i < recordDelimiterLength; i++){
  2873. const rd = record_delimiter[i];
  2874. const rdLength = rd.length;
  2875. if(rd[0] !== chr){
  2876. continue;
  2877. }
  2878. for(let j = 1; j < rdLength; j++){
  2879. if(rd[j] !== buf[pos+j]){
  2880. continue loop1;
  2881. }
  2882. }
  2883. return rd.length;
  2884. }
  2885. return 0;
  2886. },
  2887. __isEscape: function(buf, pos, chr){
  2888. const {escape} = this.options;
  2889. if(escape === null) return false;
  2890. const l = escape.length;
  2891. if(escape[0] === chr){
  2892. for(let i = 0; i < l; i++){
  2893. if(escape[i] !== buf[pos+i]){
  2894. return false;
  2895. }
  2896. }
  2897. return true;
  2898. }
  2899. return false;
  2900. },
  2901. __isQuote: function(buf, pos){
  2902. const {quote} = this.options;
  2903. if(quote === null) return false;
  2904. const l = quote.length;
  2905. for(let i = 0; i < l; i++){
  2906. if(quote[i] !== buf[pos+i]){
  2907. return false;
  2908. }
  2909. }
  2910. return true;
  2911. },
  2912. __autoDiscoverRecordDelimiter: function(buf, pos){
  2913. const { encoding } = this.options;
  2914. // Note, we don't need to cache this information in state,
  2915. // It is only called on the first line until we find out a suitable
  2916. // record delimiter.
  2917. const rds = [
  2918. // Important, the windows line ending must be before mac os 9
  2919. Buffer.from('\r\n', encoding),
  2920. Buffer.from('\n', encoding),
  2921. Buffer.from('\r', encoding),
  2922. ];
  2923. loop: for(let i = 0; i < rds.length; i++){
  2924. const l = rds[i].length;
  2925. for(let j = 0; j < l; j++){
  2926. if(rds[i][j] !== buf[pos + j]){
  2927. continue loop;
  2928. }
  2929. }
  2930. this.options.record_delimiter.push(rds[i]);
  2931. this.state.recordDelimiterMaxLength = rds[i].length;
  2932. return rds[i].length;
  2933. }
  2934. return 0;
  2935. },
  2936. __error: function(msg){
  2937. const {encoding, raw, skip_records_with_error} = this.options;
  2938. const err = typeof msg === 'string' ? new Error(msg) : msg;
  2939. if(skip_records_with_error){
  2940. this.state.recordHasError = true;
  2941. if(this.options.on_skip !== undefined){
  2942. this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  2943. }
  2944. // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  2945. return undefined;
  2946. }else {
  2947. return err;
  2948. }
  2949. },
  2950. __infoDataSet: function(){
  2951. return {
  2952. ...this.info,
  2953. columns: this.options.columns
  2954. };
  2955. },
  2956. __infoRecord: function(){
  2957. const {columns, raw, encoding} = this.options;
  2958. return {
  2959. ...this.__infoDataSet(),
  2960. error: this.state.error,
  2961. header: columns === true,
  2962. index: this.state.record.length,
  2963. raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
  2964. };
  2965. },
  2966. __infoField: function(){
  2967. const {columns} = this.options;
  2968. const isColumns = Array.isArray(columns);
  2969. return {
  2970. ...this.__infoRecord(),
  2971. column: isColumns === true ?
  2972. (columns.length > this.state.record.length ?
  2973. columns[this.state.record.length].name :
  2974. null
  2975. ) :
  2976. this.state.record.length,
  2977. quoting: this.state.wasQuoting,
  2978. };
  2979. }
  2980. };
  2981. };
  2982. const parse = function(data, opts={}){
  2983. if(typeof data === 'string'){
  2984. data = Buffer.from(data);
  2985. }
  2986. const records = opts && opts.objname ? {} : [];
  2987. const parser = transform(opts);
  2988. const push = (record) => {
  2989. if(parser.options.objname === undefined)
  2990. records.push(record);
  2991. else {
  2992. records[record[0]] = record[1];
  2993. }
  2994. };
  2995. const close = () => {};
  2996. const err1 = parser.parse(data, false, push, close);
  2997. if(err1 !== undefined) throw err1;
  2998. const err2 = parser.parse(undefined, true, push, close);
  2999. if(err2 !== undefined) throw err2;
  3000. return records;
  3001. };
  3002. export { CsvError, parse };