@contrail/cli 3.4.4-alpha.7adb62a → 3.4.4-alpha.9fbce6b

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