From 2621a684cad755cb715d581cae519f602c6131f3 Mon Sep 17 00:00:00 2001 From: Mykola Grybyk Date: Sun, 5 May 2024 23:13:50 +0200 Subject: [PATCH 1/4] try another csv to json libs --- dist/index.js | 2450 +++++++++++++++++++++++++++++++++++++++++++++ dist/licenses.txt | 702 +++++++++++++ package-lock.json | 24 +- package.json | 5 +- src/csvReport.ts | 26 + 5 files changed, 3205 insertions(+), 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index e0c4116..0a7dfef 100644 --- a/dist/index.js +++ b/dist/index.js @@ -12357,6 +12357,504 @@ try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; +/***/ }), + +/***/ 224: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +let csvToJson = __nccwpck_require__(8717); + +const encodingOps = { + utf8: 'utf8', + ucs2: 'ucs2', + utf16le: 'utf16le', + latin1: 'latin1', + ascii: 'ascii', + base64: 'base64', + hex: 'hex' +}; + +/** + * Prints a digit as Number type (for example 32 instead of '32') + */ +exports.formatValueByType = function (active = true) { + csvToJson.formatValueByType(active); + return this; +}; + +/** + * If enabled, allows fields wrapped by quotation marks to be parsed correctly and not splitted + */ +exports.supportQuotedField = function (active = false) { + csvToJson.supportQuotedField(active); + return this; +}; +/** + * Defines the field delimiter which will be used to split the fields + */ +exports.fieldDelimiter = function (delimiter) { + csvToJson.fieldDelimiter(delimiter); + return this; +}; + +/** + * Defines the index where the header is defined + */ +exports.indexHeader = function (index) { + csvToJson.indexHeader(index); + return this; +}; + +/** + * Defines how to match and parse a sub array + */ +exports.parseSubArray = function (delimiter, separator) { + csvToJson.parseSubArray(delimiter, separator); + return this; +}; + +/** + * Defines a custom encoding to decode a file + */ +exports.customEncoding = function (encoding) { + csvToJson.encoding = encoding; + return this; +}; + +/** + * Defines a custom encoding to decode a file + */ +exports.utf8Encoding = function utf8Encoding() { + csvToJson.encoding = encodingOps.utf8; + return this; +}; + +/** + * Defines ucs2 encoding to decode a file + */ +exports.ucs2Encoding = function () { + csvToJson.encoding = encodingOps.ucs2; + return this; +}; + +/** + * Defines utf16le encoding to decode a file + */ +exports.utf16leEncoding = function () { + csvToJson.encoding = encodingOps.utf16le; + return this; +}; + +/** + * Defines latin1 encoding to decode a file + */ +exports.latin1Encoding = function () { + csvToJson.encoding = encodingOps.latin1; + return this; +}; + +/** + * Defines ascii encoding to decode a file + */ +exports.asciiEncoding = function () { + csvToJson.encoding = encodingOps.ascii; + return this; +}; + +/** + * Defines base64 encoding to decode a file + */ +exports.base64Encoding = function () { + this.csvToJson = encodingOps.base64; + return this; +}; + +/** + * Defines hex encoding to decode a file + */ +exports.hexEncoding = function () { + this.csvToJson = encodingOps.hex; + return this; +}; + +/** + * Parses .csv file and put its content into a file in json format. + * @param {inputFileName} path/filename + * @param {outputFileName} path/filename + * + */ +exports.generateJsonFileFromCsv = function(inputFileName, outputFileName) { + if (!inputFileName) { + throw new Error("inputFileName is not defined!!!"); + } + if (!outputFileName) { + throw new Error("outputFileName is not defined!!!"); + } + csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); +}; + +/** + * Parses .csv file and put its content into an Array of Object in json format. + * @param {inputFileName} path/filename + * @return {Array} Array of Object in json format + * + */ +exports.getJsonFromCsv = function(inputFileName) { + if (!inputFileName) { + throw new Error("inputFileName is not defined!!!"); + } + return csvToJson.getJsonFromCsv(inputFileName); +}; + +exports.csvStringToJson = function(csvString) { + return csvToJson.csvStringToJson(csvString); +}; + +/** + * Parses .csv file and put its content into a file in json format. + * @param {inputFileName} path/filename + * @param {outputFileName} path/filename + * + * @deprecated Use generateJsonFileFromCsv() + */ +exports.jsonToCsv = function(inputFileName, outputFileName) { + csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); +}; + + +/***/ }), + +/***/ 8717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +let fileUtils = __nccwpck_require__(6114); +let stringUtils = __nccwpck_require__(6494); +let jsonUtils = __nccwpck_require__(4166); + +const newLine = /\r?\n/; +const defaultFieldDelimiter = ";"; + +class CsvToJson { + + formatValueByType(active) { + this.printValueFormatByType = active; + return this; + } + + supportQuotedField(active) { + this.isSupportQuotedField = active; + return this; + } + + fieldDelimiter(delimiter) { + this.delimiter = delimiter; + return this; + } + + indexHeader(indexHeader) { + if(isNaN(indexHeader)){ + throw new Error('The index Header must be a Number!'); + } + this.indexHeader = indexHeader; + return this; + } + + + parseSubArray(delimiter = '*',separator = ',') { + this.parseSubArrayDelimiter = delimiter; + this.parseSubArraySeparator = separator; + } + + encoding(encoding){ + this.encoding = encoding; + return this; + } + + generateJsonFileFromCsv(fileInputName, fileOutputName) { + let jsonStringified = this.getJsonFromCsvStringified(fileInputName); + fileUtils.writeFile(jsonStringified, fileOutputName); + } + + getJsonFromCsvStringified(fileInputName) { + let json = this.getJsonFromCsv(fileInputName); + let jsonStringified = JSON.stringify(json, undefined, 1); + jsonUtils.validateJson(jsonStringified); + return jsonStringified; + } + + getJsonFromCsv(fileInputName) { + let parsedCsv = fileUtils.readFile(fileInputName, this.encoding); + return this.csvToJson(parsedCsv); + } + + csvStringToJson(csvString) { + return this.csvToJson(csvString); + } + + csvToJson(parsedCsv) { + this.validateInputConfig(); + let lines = parsedCsv.split(newLine); + let fieldDelimiter = this.getFieldDelimiter(); + let index = this.getIndexHeader(); + let headers; + + if(this.isSupportQuotedField){ + headers = this.split(lines[index]); + } else { + headers = lines[index].split(fieldDelimiter); + } + + while(!stringUtils.hasContent(headers) && index <= lines.length){ + index = index + 1; + headers = lines[index].split(fieldDelimiter); + } + + let jsonResult = []; + for (let i = (index + 1); i < lines.length; i++) { + let currentLine; + if(this.isSupportQuotedField){ + currentLine = this.split(lines[i]); + } + else{ + currentLine = lines[i].split(fieldDelimiter); + } + if (stringUtils.hasContent(currentLine)) { + jsonResult.push(this.buildJsonResult(headers, currentLine)); + } + } + return jsonResult; + } + + getFieldDelimiter() { + if (this.delimiter) { + return this.delimiter; + } + return defaultFieldDelimiter; + } + + getIndexHeader(){ + if(this.indexHeader !== null && !isNaN(this.indexHeader)){ + return this.indexHeader; + } + return 0; + } + + buildJsonResult(headers, currentLine) { + let jsonObject = {}; + for (let j = 0; j < headers.length; j++) { + let propertyName = stringUtils.trimPropertyName(headers[j]); + let value = currentLine[j]; + + if(this.isParseSubArray(value)){ + value = this.buildJsonSubArray(value); + } + + if (this.printValueFormatByType && !Array.isArray(value)) { + value = stringUtils.getValueFormatByType(currentLine[j]); + } + + jsonObject[propertyName] = value; + } + return jsonObject; + } + + buildJsonSubArray(value) { + let extractedValues = value.substring( + value.indexOf(this.parseSubArrayDelimiter) + 1, + value.lastIndexOf(this.parseSubArrayDelimiter) + ); + extractedValues.trim(); + value = extractedValues.split(this.parseSubArraySeparator); + if(this.printValueFormatByType){ + for(let i=0; i < value.length; i++){ + value[i] = stringUtils.getValueFormatByType(value[i]); + } + } + return value; + } + + isParseSubArray(value){ + if(this.parseSubArrayDelimiter){ + if (value && (value.indexOf(this.parseSubArrayDelimiter) === 0 && value.lastIndexOf(this.parseSubArrayDelimiter) === (value.length - 1))) { + return true; + } + } + return false; + } + + validateInputConfig(){ + if(this.isSupportQuotedField) { + if(this.getFieldDelimiter() === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field delimiter as quote -> ["]'); + } + if(this.parseSubArraySeparator === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArraySeparator as quote -> ["]'); + } + if(this.parseSubArrayDelimiter === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArrayDelimiter as quote -> ["]'); + } + } + } + + hasQuotes(line) { + return line.includes('"'); + } + + split(line) { + if(line.length == 0){ + return []; + } + let delim = this.getFieldDelimiter(); + let subSplits = ['']; + if (this.hasQuotes(line)) { + let chars = line.split(''); + + let subIndex = 0; + let startQuote = false; + let isDouble = false; + chars.forEach((c, i, arr) => { + if (isDouble) { //when run into double just pop it into current and move on + subSplits[subIndex] += c; + isDouble = false; + return; + } + + if (c != '"' && c != delim ) { + subSplits[subIndex] += c; + } else if(c == delim && startQuote){ + subSplits[subIndex] += c; + } else if( c == delim ){ + subIndex++ + subSplits[subIndex] = ''; + return; + } else { + if (arr[i + 1] === '"') { + //Double quote + isDouble = true; + //subSplits[subIndex] += c; //Skip because this is escaped quote + } else { + if (!startQuote) { + startQuote = true; + //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value + } else { + //end + startQuote = false; + //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value + } + } + } + }); + if(startQuote){ + throw new Error('Row contains mismatched quotes!'); + } + return subSplits; + } else { + return line.split(delim); + } + } +} + +module.exports = new CsvToJson(); + + +/***/ }), + +/***/ 6114: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +let fs = __nccwpck_require__(7147); + +class FileUtils { + + readFile(fileInputName, encoding) { + return fs.readFileSync(fileInputName, encoding).toString(); + } + + writeFile(json, fileOutputName) { + fs.writeFile(fileOutputName, json, function (err) { + if (err) { + throw err; + } else { + console.log('File saved: ' + fileOutputName); + } + }); + } + +} +module.exports = new FileUtils(); + + +/***/ }), + +/***/ 4166: +/***/ ((module) => { + + + +class JsonUtil { + + validateJson(json) { + try { + JSON.parse(json); + } catch (err) { + throw Error('Parsed csv has generated an invalid json!!!\n' + err); + } + } + +} + +module.exports = new JsonUtil(); + +/***/ }), + +/***/ 6494: +/***/ ((module) => { + + + +class StringUtils { + + trimPropertyName(value) { + return value.replace(/\s/g, ''); + } + + getValueFormatByType(value) { + if(value === undefined || value === ''){ + return String(); + } + //is Number + let isNumber = !isNaN(value); + if (isNumber) { + return Number(value); + } + // is Boolean + if(value === "true" || value === "false"){ + return JSON.parse(value.toLowerCase()); + } + return String(value); + } + + hasContent(values) { + if (values.length > 0) { + for (let i = 0; i < values.length; i++) { + if (values[i]) { + return true; + } + } + } + return false; + } +} + +module.exports = new StringUtils(); + + /***/ }), /***/ 1356: @@ -15763,6 +16261,1932 @@ function onceStrict (fn) { } +/***/ }), + +/***/ 877: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + +/* @license +Papa Parse +v5.4.1 +https://github.com/mholt/PapaParse +License: MIT +*/ + +(function(root, factory) +{ + /* globals define */ + if (typeof define === 'function' && define.amd) + { + // AMD. Register as an anonymous module. + define([], factory); + } + else if (true) + { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } + else + {} + // in strict mode we cannot access arguments.callee, so we need a named reference to + // stringify the factory method for the blob worker + // eslint-disable-next-line func-name +}(this, function moduleFactory() +{ + 'use strict'; + + var global = (function() { + // alternative method, similar to `Function('return this')()` + // but without using `eval` (which is disabled when + // using Content Security Policy). + + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + + // When running tests none of the above have been defined + return {}; + })(); + + + function getWorkerBlob() { + var URL = global.URL || global.webkitURL || null; + var code = moduleFactory.toString(); + return Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ", '(', code, ')();'], {type: 'text/javascript'}))); + } + + var IS_WORKER = !global.document && !!global.postMessage, + IS_PAPA_WORKER = global.IS_PAPA_WORKER || false; + + var workers = {}, workerIdCounter = 0; + + var Papa = {}; + + Papa.parse = CsvToJson; + Papa.unparse = JsonToCsv; + + Papa.RECORD_SEP = String.fromCharCode(30); + Papa.UNIT_SEP = String.fromCharCode(31); + Papa.BYTE_ORDER_MARK = '\ufeff'; + Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK]; + Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker; + Papa.NODE_STREAM_INPUT = 1; + + // Configurable chunk sizes for local and remote files, respectively + Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB + Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB + Papa.DefaultDelimiter = ','; // Used if not specified and detection fails + + // Exposed for testing and development only + Papa.Parser = Parser; + Papa.ParserHandle = ParserHandle; + Papa.NetworkStreamer = NetworkStreamer; + Papa.FileStreamer = FileStreamer; + Papa.StringStreamer = StringStreamer; + Papa.ReadableStreamStreamer = ReadableStreamStreamer; + if (typeof PAPA_BROWSER_CONTEXT === 'undefined') { + Papa.DuplexStreamStreamer = DuplexStreamStreamer; + } + + if (global.jQuery) + { + var $ = global.jQuery; + $.fn.parse = function(options) + { + var config = options.config || {}; + var queue = []; + + this.each(function(idx) + { + var supported = $(this).prop('tagName').toUpperCase() === 'INPUT' + && $(this).attr('type').toLowerCase() === 'file' + && global.FileReader; + + if (!supported || !this.files || this.files.length === 0) + return true; // continue to next input element + + for (var i = 0; i < this.files.length; i++) + { + queue.push({ + file: this.files[i], + inputElem: this, + instanceConfig: $.extend({}, config) + }); + } + }); + + parseNextFile(); // begin parsing + return this; // maintains chainability + + + function parseNextFile() + { + if (queue.length === 0) + { + if (isFunction(options.complete)) + options.complete(); + return; + } + + var f = queue[0]; + + if (isFunction(options.before)) + { + var returned = options.before(f.file, f.inputElem); + + if (typeof returned === 'object') + { + if (returned.action === 'abort') + { + error('AbortError', f.file, f.inputElem, returned.reason); + return; // Aborts all queued files immediately + } + else if (returned.action === 'skip') + { + fileComplete(); // parse the next file in the queue, if any + return; + } + else if (typeof returned.config === 'object') + f.instanceConfig = $.extend(f.instanceConfig, returned.config); + } + else if (returned === 'skip') + { + fileComplete(); // parse the next file in the queue, if any + return; + } + } + + // Wrap up the user's complete callback, if any, so that ours also gets executed + var userCompleteFunc = f.instanceConfig.complete; + f.instanceConfig.complete = function(results) + { + if (isFunction(userCompleteFunc)) + userCompleteFunc(results, f.file, f.inputElem); + fileComplete(); + }; + + Papa.parse(f.file, f.instanceConfig); + } + + function error(name, file, elem, reason) + { + if (isFunction(options.error)) + options.error({name: name}, file, elem, reason); + } + + function fileComplete() + { + queue.splice(0, 1); + parseNextFile(); + } + }; + } + + + if (IS_PAPA_WORKER) + { + global.onmessage = workerThreadReceivedMessage; + } + + + + + function CsvToJson(_input, _config) + { + _config = _config || {}; + var dynamicTyping = _config.dynamicTyping || false; + if (isFunction(dynamicTyping)) { + _config.dynamicTypingFunction = dynamicTyping; + // Will be filled on first row call + dynamicTyping = {}; + } + _config.dynamicTyping = dynamicTyping; + + _config.transform = isFunction(_config.transform) ? _config.transform : false; + + if (_config.worker && Papa.WORKERS_SUPPORTED) + { + var w = newWorker(); + + w.userStep = _config.step; + w.userChunk = _config.chunk; + w.userComplete = _config.complete; + w.userError = _config.error; + + _config.step = isFunction(_config.step); + _config.chunk = isFunction(_config.chunk); + _config.complete = isFunction(_config.complete); + _config.error = isFunction(_config.error); + delete _config.worker; // prevent infinite loop + + w.postMessage({ + input: _input, + config: _config, + workerId: w.id + }); + + return; + } + + var streamer = null; + if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined') + { + // create a node Duplex stream for use + // with .pipe + streamer = new DuplexStreamStreamer(_config); + return streamer.getStream(); + } + else if (typeof _input === 'string') + { + _input = stripBom(_input); + if (_config.download) + streamer = new NetworkStreamer(_config); + else + streamer = new StringStreamer(_config); + } + else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on)) + { + streamer = new ReadableStreamStreamer(_config); + } + else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106) + streamer = new FileStreamer(_config); + + return streamer.stream(_input); + + // Strip character from UTF-8 BOM encoded files that cause issue parsing the file + function stripBom(string) { + if (string.charCodeAt(0) === 0xfeff) { + return string.slice(1); + } + return string; + } + } + + + + + + + function JsonToCsv(_input, _config) + { + // Default configuration + + /** whether to surround every datum with quotes */ + var _quotes = false; + + /** whether to write headers */ + var _writeHeader = true; + + /** delimiting character(s) */ + var _delimiter = ','; + + /** newline character(s) */ + var _newline = '\r\n'; + + /** quote character */ + var _quoteChar = '"'; + + /** escaped quote character, either "" or " */ + var _escapedQuote = _quoteChar + _quoteChar; + + /** whether to skip empty lines */ + var _skipEmptyLines = false; + + /** the columns (keys) we expect when we unparse objects */ + var _columns = null; + + /** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */ + var _escapeFormulae = false; + + unpackConfig(); + + var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g'); + + if (typeof _input === 'string') + _input = JSON.parse(_input); + + if (Array.isArray(_input)) + { + if (!_input.length || Array.isArray(_input[0])) + return serialize(null, _input, _skipEmptyLines); + else if (typeof _input[0] === 'object') + return serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines); + } + else if (typeof _input === 'object') + { + if (typeof _input.data === 'string') + _input.data = JSON.parse(_input.data); + + if (Array.isArray(_input.data)) + { + if (!_input.fields) + _input.fields = _input.meta && _input.meta.fields || _columns; + + if (!_input.fields) + _input.fields = Array.isArray(_input.data[0]) + ? _input.fields + : typeof _input.data[0] === 'object' + ? Object.keys(_input.data[0]) + : []; + + if (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object') + _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf'] + } + + return serialize(_input.fields || [], _input.data || [], _skipEmptyLines); + } + + // Default (any valid paths should return before this) + throw new Error('Unable to serialize unrecognized input'); + + + function unpackConfig() + { + if (typeof _config !== 'object') + return; + + if (typeof _config.delimiter === 'string' + && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length) + { + _delimiter = _config.delimiter; + } + + if (typeof _config.quotes === 'boolean' + || typeof _config.quotes === 'function' + || Array.isArray(_config.quotes)) + _quotes = _config.quotes; + + if (typeof _config.skipEmptyLines === 'boolean' + || typeof _config.skipEmptyLines === 'string') + _skipEmptyLines = _config.skipEmptyLines; + + if (typeof _config.newline === 'string') + _newline = _config.newline; + + if (typeof _config.quoteChar === 'string') + _quoteChar = _config.quoteChar; + + if (typeof _config.header === 'boolean') + _writeHeader = _config.header; + + if (Array.isArray(_config.columns)) { + + if (_config.columns.length === 0) throw new Error('Option columns is empty'); + + _columns = _config.columns; + } + + if (_config.escapeChar !== undefined) { + _escapedQuote = _config.escapeChar + _quoteChar; + } + + if (typeof _config.escapeFormulae === 'boolean' || _config.escapeFormulae instanceof RegExp) { + _escapeFormulae = _config.escapeFormulae instanceof RegExp ? _config.escapeFormulae : /^[=+\-@\t\r].*$/; + } + } + + /** The double for loop that iterates the data and writes out a CSV string including header row */ + function serialize(fields, data, skipEmptyLines) + { + var csv = ''; + + if (typeof fields === 'string') + fields = JSON.parse(fields); + if (typeof data === 'string') + data = JSON.parse(data); + + var hasHeader = Array.isArray(fields) && fields.length > 0; + var dataKeyedByField = !(Array.isArray(data[0])); + + // If there a header row, write it first + if (hasHeader && _writeHeader) + { + for (var i = 0; i < fields.length; i++) + { + if (i > 0) + csv += _delimiter; + csv += safe(fields[i], i); + } + if (data.length > 0) + csv += _newline; + } + + // Then write out the data + for (var row = 0; row < data.length; row++) + { + var maxCol = hasHeader ? fields.length : data[row].length; + + var emptyLine = false; + var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0; + if (skipEmptyLines && !hasHeader) + { + emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0; + } + if (skipEmptyLines === 'greedy' && hasHeader) { + var line = []; + for (var c = 0; c < maxCol; c++) { + var cx = dataKeyedByField ? fields[c] : c; + line.push(data[row][cx]); + } + emptyLine = line.join('').trim() === ''; + } + if (!emptyLine) + { + for (var col = 0; col < maxCol; col++) + { + if (col > 0 && !nullLine) + csv += _delimiter; + var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; + csv += safe(data[row][colIdx], col); + } + if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine))) + { + csv += _newline; + } + } + } + return csv; + } + + /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */ + function safe(str, col) + { + if (typeof str === 'undefined' || str === null) + return ''; + + if (str.constructor === Date) + return JSON.stringify(str).slice(1, 25); + + var needsQuotes = false; + + if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) { + str = "'" + str; + needsQuotes = true; + } + + var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote); + + needsQuotes = needsQuotes + || _quotes === true + || (typeof _quotes === 'function' && _quotes(str, col)) + || (Array.isArray(_quotes) && _quotes[col]) + || hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS) + || escapedQuoteStr.indexOf(_delimiter) > -1 + || escapedQuoteStr.charAt(0) === ' ' + || escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' '; + + return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr; + } + + function hasAny(str, substrings) + { + for (var i = 0; i < substrings.length; i++) + if (str.indexOf(substrings[i]) > -1) + return true; + return false; + } + } + + /** ChunkStreamer is the base prototype for various streamer implementations. */ + function ChunkStreamer(config) + { + this._handle = null; + this._finished = false; + this._completed = false; + this._halted = false; + this._input = null; + this._baseIndex = 0; + this._partialLine = ''; + this._rowCount = 0; + this._start = 0; + this._nextChunk = null; + this.isFirstChunk = true; + this._completeResults = { + data: [], + errors: [], + meta: {} + }; + replaceConfig.call(this, config); + + this.parseChunk = function(chunk, isFakeChunk) + { + // First chunk pre-processing + if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) + { + var modifiedChunk = this._config.beforeFirstChunk(chunk); + if (modifiedChunk !== undefined) + chunk = modifiedChunk; + } + this.isFirstChunk = false; + this._halted = false; + + // Rejoin the line we likely just split in two by chunking the file + var aggregate = this._partialLine + chunk; + this._partialLine = ''; + + var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); + + if (this._handle.paused() || this._handle.aborted()) { + this._halted = true; + return; + } + + var lastIndex = results.meta.cursor; + + if (!this._finished) + { + this._partialLine = aggregate.substring(lastIndex - this._baseIndex); + this._baseIndex = lastIndex; + } + + if (results && results.data) + this._rowCount += results.data.length; + + var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); + + if (IS_PAPA_WORKER) + { + global.postMessage({ + results: results, + workerId: Papa.WORKER_ID, + finished: finishedIncludingPreview + }); + } + else if (isFunction(this._config.chunk) && !isFakeChunk) + { + this._config.chunk(results, this._handle); + if (this._handle.paused() || this._handle.aborted()) { + this._halted = true; + return; + } + results = undefined; + this._completeResults = undefined; + } + + if (!this._config.step && !this._config.chunk) { + this._completeResults.data = this._completeResults.data.concat(results.data); + this._completeResults.errors = this._completeResults.errors.concat(results.errors); + this._completeResults.meta = results.meta; + } + + if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) { + this._config.complete(this._completeResults, this._input); + this._completed = true; + } + + if (!finishedIncludingPreview && (!results || !results.meta.paused)) + this._nextChunk(); + + return results; + }; + + this._sendError = function(error) + { + if (isFunction(this._config.error)) + this._config.error(error); + else if (IS_PAPA_WORKER && this._config.error) + { + global.postMessage({ + workerId: Papa.WORKER_ID, + error: error, + finished: false + }); + } + }; + + function replaceConfig(config) + { + // Deep-copy the config so we can edit it + var configCopy = copy(config); + configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! + if (!config.step && !config.chunk) + configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 + this._handle = new ParserHandle(configCopy); + this._handle.streamer = this; + this._config = configCopy; // persist the copy to the caller + } + } + + + function NetworkStreamer(config) + { + config = config || {}; + if (!config.chunkSize) + config.chunkSize = Papa.RemoteChunkSize; + ChunkStreamer.call(this, config); + + var xhr; + + if (IS_WORKER) + { + this._nextChunk = function() + { + this._readChunk(); + this._chunkLoaded(); + }; + } + else + { + this._nextChunk = function() + { + this._readChunk(); + }; + } + + this.stream = function(url) + { + this._input = url; + this._nextChunk(); // Starts streaming + }; + + this._readChunk = function() + { + if (this._finished) + { + this._chunkLoaded(); + return; + } + + xhr = new XMLHttpRequest(); + + if (this._config.withCredentials) + { + xhr.withCredentials = this._config.withCredentials; + } + + if (!IS_WORKER) + { + xhr.onload = bindFunction(this._chunkLoaded, this); + xhr.onerror = bindFunction(this._chunkError, this); + } + + xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER); + // Headers can only be set when once the request state is OPENED + if (this._config.downloadRequestHeaders) + { + var headers = this._config.downloadRequestHeaders; + + for (var headerName in headers) + { + xhr.setRequestHeader(headerName, headers[headerName]); + } + } + + if (this._config.chunkSize) + { + var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive + xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end); + } + + try { + xhr.send(this._config.downloadRequestBody); + } + catch (err) { + this._chunkError(err.message); + } + + if (IS_WORKER && xhr.status === 0) + this._chunkError(); + }; + + this._chunkLoaded = function() + { + if (xhr.readyState !== 4) + return; + + if (xhr.status < 200 || xhr.status >= 400) + { + this._chunkError(); + return; + } + + // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte + this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length; + this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr); + this.parseChunk(xhr.responseText); + }; + + this._chunkError = function(errorMessage) + { + var errorText = xhr.statusText || errorMessage; + this._sendError(new Error(errorText)); + }; + + function getFileSize(xhr) + { + var contentRange = xhr.getResponseHeader('Content-Range'); + if (contentRange === null) { // no content range, then finish! + return -1; + } + return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1)); + } + } + NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype); + NetworkStreamer.prototype.constructor = NetworkStreamer; + + + function FileStreamer(config) + { + config = config || {}; + if (!config.chunkSize) + config.chunkSize = Papa.LocalChunkSize; + ChunkStreamer.call(this, config); + + var reader, slice; + + // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862 + // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76 + var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105 + + this.stream = function(file) + { + this._input = file; + slice = file.slice || file.webkitSlice || file.mozSlice; + + if (usingAsyncReader) + { + reader = new FileReader(); // Preferred method of reading files, even in workers + reader.onload = bindFunction(this._chunkLoaded, this); + reader.onerror = bindFunction(this._chunkError, this); + } + else + reader = new FileReaderSync(); // Hack for running in a web worker in Firefox + + this._nextChunk(); // Starts streaming + }; + + this._nextChunk = function() + { + if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) + this._readChunk(); + }; + + this._readChunk = function() + { + var input = this._input; + if (this._config.chunkSize) + { + var end = Math.min(this._start + this._config.chunkSize, this._input.size); + input = slice.call(input, this._start, end); + } + var txt = reader.readAsText(input, this._config.encoding); + if (!usingAsyncReader) + this._chunkLoaded({ target: { result: txt } }); // mimic the async signature + }; + + this._chunkLoaded = function(event) + { + // Very important to increment start each time before handling results + this._start += this._config.chunkSize; + this._finished = !this._config.chunkSize || this._start >= this._input.size; + this.parseChunk(event.target.result); + }; + + this._chunkError = function() + { + this._sendError(reader.error); + }; + + } + FileStreamer.prototype = Object.create(ChunkStreamer.prototype); + FileStreamer.prototype.constructor = FileStreamer; + + + function StringStreamer(config) + { + config = config || {}; + ChunkStreamer.call(this, config); + + var remaining; + this.stream = function(s) + { + remaining = s; + return this._nextChunk(); + }; + this._nextChunk = function() + { + if (this._finished) return; + var size = this._config.chunkSize; + var chunk; + if(size) { + chunk = remaining.substring(0, size); + remaining = remaining.substring(size); + } else { + chunk = remaining; + remaining = ''; + } + this._finished = !remaining; + return this.parseChunk(chunk); + }; + } + StringStreamer.prototype = Object.create(StringStreamer.prototype); + StringStreamer.prototype.constructor = StringStreamer; + + + function ReadableStreamStreamer(config) + { + config = config || {}; + + ChunkStreamer.call(this, config); + + var queue = []; + var parseOnData = true; + var streamHasEnded = false; + + this.pause = function() + { + ChunkStreamer.prototype.pause.apply(this, arguments); + this._input.pause(); + }; + + this.resume = function() + { + ChunkStreamer.prototype.resume.apply(this, arguments); + this._input.resume(); + }; + + this.stream = function(stream) + { + this._input = stream; + + this._input.on('data', this._streamData); + this._input.on('end', this._streamEnd); + this._input.on('error', this._streamError); + }; + + this._checkIsFinished = function() + { + if (streamHasEnded && queue.length === 1) { + this._finished = true; + } + }; + + this._nextChunk = function() + { + this._checkIsFinished(); + if (queue.length) + { + this.parseChunk(queue.shift()); + } + else + { + parseOnData = true; + } + }; + + this._streamData = bindFunction(function(chunk) + { + try + { + queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding)); + + if (parseOnData) + { + parseOnData = false; + this._checkIsFinished(); + this.parseChunk(queue.shift()); + } + } + catch (error) + { + this._streamError(error); + } + }, this); + + this._streamError = bindFunction(function(error) + { + this._streamCleanUp(); + this._sendError(error); + }, this); + + this._streamEnd = bindFunction(function() + { + this._streamCleanUp(); + streamHasEnded = true; + this._streamData(''); + }, this); + + this._streamCleanUp = bindFunction(function() + { + this._input.removeListener('data', this._streamData); + this._input.removeListener('end', this._streamEnd); + this._input.removeListener('error', this._streamError); + }, this); + } + ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype); + ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer; + + + function DuplexStreamStreamer(_config) { + var Duplex = (__nccwpck_require__(2781).Duplex); + var config = copy(_config); + var parseOnWrite = true; + var writeStreamHasFinished = false; + var parseCallbackQueue = []; + var stream = null; + + this._onCsvData = function(results) + { + var data = results.data; + if (!stream.push(data) && !this._handle.paused()) { + // the writeable consumer buffer has filled up + // so we need to pause until more items + // can be processed + this._handle.pause(); + } + }; + + this._onCsvComplete = function() + { + // node will finish the read stream when + // null is pushed + stream.push(null); + }; + + config.step = bindFunction(this._onCsvData, this); + config.complete = bindFunction(this._onCsvComplete, this); + ChunkStreamer.call(this, config); + + this._nextChunk = function() + { + if (writeStreamHasFinished && parseCallbackQueue.length === 1) { + this._finished = true; + } + if (parseCallbackQueue.length) { + parseCallbackQueue.shift()(); + } else { + parseOnWrite = true; + } + }; + + this._addToParseQueue = function(chunk, callback) + { + // add to queue so that we can indicate + // completion via callback + // node will automatically pause the incoming stream + // when too many items have been added without their + // callback being invoked + parseCallbackQueue.push(bindFunction(function() { + this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding)); + if (isFunction(callback)) { + return callback(); + } + }, this)); + if (parseOnWrite) { + parseOnWrite = false; + this._nextChunk(); + } + }; + + this._onRead = function() + { + if (this._handle.paused()) { + // the writeable consumer can handle more data + // so resume the chunk parsing + this._handle.resume(); + } + }; + + this._onWrite = function(chunk, encoding, callback) + { + this._addToParseQueue(chunk, callback); + }; + + this._onWriteComplete = function() + { + writeStreamHasFinished = true; + // have to write empty string + // so parser knows its done + this._addToParseQueue(''); + }; + + this.getStream = function() + { + return stream; + }; + stream = new Duplex({ + readableObjectMode: true, + decodeStrings: false, + read: bindFunction(this._onRead, this), + write: bindFunction(this._onWrite, this) + }); + stream.once('finish', bindFunction(this._onWriteComplete, this)); + } + if (typeof PAPA_BROWSER_CONTEXT === 'undefined') { + DuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype); + DuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer; + } + + + // Use one ParserHandle per entire CSV file or string + function ParserHandle(_config) + { + // One goal is to minimize the use of regular expressions... + var MAX_FLOAT = Math.pow(2, 53); + var MIN_FLOAT = -MAX_FLOAT; + var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/; + var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/; + var self = this; + var _stepCounter = 0; // Number of times step was called (number of rows parsed) + var _rowCounter = 0; // Number of rows that have been parsed so far + var _input; // The input being parsed + var _parser; // The core parser being used + var _paused = false; // Whether we are paused or not + var _aborted = false; // Whether the parser has aborted or not + var _delimiterError; // Temporary state between delimiter detection and processing results + var _fields = []; // Fields are from the header row of the input, if there is one + var _results = { // The last results returned from the parser + data: [], + errors: [], + meta: {} + }; + + if (isFunction(_config.step)) + { + var userStep = _config.step; + _config.step = function(results) + { + _results = results; + + if (needsHeaderRow()) + processResults(); + else // only call user's step function after header row + { + processResults(); + + // It's possbile that this line was empty and there's no row here after all + if (_results.data.length === 0) + return; + + _stepCounter += results.data.length; + if (_config.preview && _stepCounter > _config.preview) + _parser.abort(); + else { + _results.data = _results.data[0]; + userStep(_results, self); + } + } + }; + } + + /** + * Parses input. Most users won't need, and shouldn't mess with, the baseIndex + * and ignoreLastRow parameters. They are used by streamers (wrapper functions) + * when an input comes in multiple chunks, like from a file. + */ + this.parse = function(input, baseIndex, ignoreLastRow) + { + var quoteChar = _config.quoteChar || '"'; + if (!_config.newline) + _config.newline = guessLineEndings(input, quoteChar); + + _delimiterError = false; + if (!_config.delimiter) + { + var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess); + if (delimGuess.successful) + _config.delimiter = delimGuess.bestDelimiter; + else + { + _delimiterError = true; // add error after parsing (otherwise it would be overwritten) + _config.delimiter = Papa.DefaultDelimiter; + } + _results.meta.delimiter = _config.delimiter; + } + else if(isFunction(_config.delimiter)) + { + _config.delimiter = _config.delimiter(input); + _results.meta.delimiter = _config.delimiter; + } + + var parserConfig = copy(_config); + if (_config.preview && _config.header) + parserConfig.preview++; // to compensate for header row + + _input = input; + _parser = new Parser(parserConfig); + _results = _parser.parse(_input, baseIndex, ignoreLastRow); + processResults(); + return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } }); + }; + + this.paused = function() + { + return _paused; + }; + + this.pause = function() + { + _paused = true; + _parser.abort(); + + // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring, + // otherwise we can get duplicate content within a row + _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex()); + }; + + this.resume = function() + { + if(self.streamer._halted) { + _paused = false; + self.streamer.parseChunk(_input, true); + } else { + // Bugfix: #636 In case the processing hasn't halted yet + // wait for it to halt in order to resume + setTimeout(self.resume, 3); + } + }; + + this.aborted = function() + { + return _aborted; + }; + + this.abort = function() + { + _aborted = true; + _parser.abort(); + _results.meta.aborted = true; + if (isFunction(_config.complete)) + _config.complete(_results); + _input = ''; + }; + + function testEmptyLine(s) { + return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; + } + + function testFloat(s) { + if (FLOAT.test(s)) { + var floatValue = parseFloat(s); + if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) { + return true; + } + } + return false; + } + + function processResults() + { + if (_results && _delimiterError) + { + addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); + _delimiterError = false; + } + + if (_config.skipEmptyLines) + { + _results.data = _results.data.filter(function(d) { + return !testEmptyLine(d); + }); + } + + if (needsHeaderRow()) + fillHeaderFields(); + + return applyHeaderAndDynamicTypingAndTransformation(); + } + + function needsHeaderRow() + { + return _config.header && _fields.length === 0; + } + + function fillHeaderFields() + { + if (!_results) + return; + + function addHeader(header, i) + { + if (isFunction(_config.transformHeader)) + header = _config.transformHeader(header, i); + + _fields.push(header); + } + + if (Array.isArray(_results.data[0])) + { + for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) + _results.data[i].forEach(addHeader); + + _results.data.splice(0, 1); + } + // if _results.data[0] is not an array, we are in a step where _results.data is the row. + else + _results.data.forEach(addHeader); + } + + function shouldApplyDynamicTyping(field) { + // Cache function values to avoid calling it for each row + if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { + _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); + } + return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; + } + + function parseDynamic(field, value) + { + if (shouldApplyDynamicTyping(field)) + { + if (value === 'true' || value === 'TRUE') + return true; + else if (value === 'false' || value === 'FALSE') + return false; + else if (testFloat(value)) + return parseFloat(value); + else if (ISO_DATE.test(value)) + return new Date(value); + else + return (value === '' ? null : value); + } + return value; + } + + function applyHeaderAndDynamicTypingAndTransformation() + { + if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) + return _results; + + function processRow(rowSource, i) + { + var row = _config.header ? {} : []; + + var j; + for (j = 0; j < rowSource.length; j++) + { + var field = j; + var value = rowSource[j]; + + if (_config.header) + field = j >= _fields.length ? '__parsed_extra' : _fields[j]; + + if (_config.transform) + value = _config.transform(value,field); + + value = parseDynamic(field, value); + + if (field === '__parsed_extra') + { + row[field] = row[field] || []; + row[field].push(value); + } + else + row[field] = value; + } + + + if (_config.header) + { + if (j > _fields.length) + addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); + else if (j < _fields.length) + addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); + } + + return row; + } + + var incrementBy = 1; + if (!_results.data.length || Array.isArray(_results.data[0])) + { + _results.data = _results.data.map(processRow); + incrementBy = _results.data.length; + } + else + _results.data = processRow(_results.data, 0); + + + if (_config.header && _results.meta) + _results.meta.fields = _fields; + + _rowCounter += incrementBy; + return _results; + } + + function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { + var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount; + + delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; + + for (var i = 0; i < delimitersToGuess.length; i++) { + var delim = delimitersToGuess[i]; + var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; + fieldCountPrevRow = undefined; + + var preview = new Parser({ + comments: comments, + delimiter: delim, + newline: newline, + preview: 10 + }).parse(input); + + for (var j = 0; j < preview.data.length; j++) { + if (skipEmptyLines && testEmptyLine(preview.data[j])) { + emptyLinesCount++; + continue; + } + var fieldCount = preview.data[j].length; + avgFieldCount += fieldCount; + + if (typeof fieldCountPrevRow === 'undefined') { + fieldCountPrevRow = fieldCount; + continue; + } + else if (fieldCount > 0) { + delta += Math.abs(fieldCount - fieldCountPrevRow); + fieldCountPrevRow = fieldCount; + } + } + + if (preview.data.length > 0) + avgFieldCount /= (preview.data.length - emptyLinesCount); + + if ((typeof bestDelta === 'undefined' || delta <= bestDelta) + && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) { + bestDelta = delta; + bestDelim = delim; + maxFieldCount = avgFieldCount; + } + } + + _config.delimiter = bestDelim; + + return { + successful: !!bestDelim, + bestDelimiter: bestDelim + }; + } + + function guessLineEndings(input, quoteChar) + { + input = input.substring(0, 1024 * 1024); // max length 1 MB + // Replace all the text inside quotes + var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm'); + input = input.replace(re, ''); + + var r = input.split('\r'); + + var n = input.split('\n'); + + var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length); + + if (r.length === 1 || nAppearsFirst) + return '\n'; + + var numWithN = 0; + for (var i = 0; i < r.length; i++) + { + if (r[i][0] === '\n') + numWithN++; + } + + return numWithN >= r.length / 2 ? '\r\n' : '\r'; + } + + function addError(type, code, msg, row) + { + var error = { + type: type, + code: code, + message: msg + }; + if(row !== undefined) { + error.row = row; + } + _results.errors.push(error); + } + } + + /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */ + function escapeRegExp(string) + { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string + } + + /** The core parser implements speedy and correct CSV parsing */ + function Parser(config) + { + // Unpack the config object + config = config || {}; + var delim = config.delimiter; + var newline = config.newline; + var comments = config.comments; + var step = config.step; + var preview = config.preview; + var fastMode = config.fastMode; + var quoteChar; + if (config.quoteChar === undefined || config.quoteChar === null) { + quoteChar = '"'; + } else { + quoteChar = config.quoteChar; + } + var escapeChar = quoteChar; + if (config.escapeChar !== undefined) { + escapeChar = config.escapeChar; + } + + // Delimiter must be valid + if (typeof delim !== 'string' + || Papa.BAD_DELIMITERS.indexOf(delim) > -1) + delim = ','; + + // Comment character must be valid + if (comments === delim) + throw new Error('Comment character same as delimiter'); + else if (comments === true) + comments = '#'; + else if (typeof comments !== 'string' + || Papa.BAD_DELIMITERS.indexOf(comments) > -1) + comments = false; + + // Newline must be valid: \r, \n, or \r\n + if (newline !== '\n' && newline !== '\r' && newline !== '\r\n') + newline = '\n'; + + // We're gonna need these at the Parser scope + var cursor = 0; + var aborted = false; + + this.parse = function(input, baseIndex, ignoreLastRow) + { + // For some reason, in Chrome, this speeds things up (!?) + if (typeof input !== 'string') + throw new Error('Input must be a string'); + + // We don't need to compute some of these every time parse() is called, + // but having them in a more local scope seems to perform better + var inputLen = input.length, + delimLen = delim.length, + newlineLen = newline.length, + commentsLen = comments.length; + var stepIsFunction = isFunction(step); + + // Establish starting state + cursor = 0; + var data = [], errors = [], row = [], lastCursor = 0; + + if (!input) + return returnable(); + + // Rename headers if there are duplicates + if (config.header && !baseIndex) + { + var firstLine = input.split(newline)[0]; + var headers = firstLine.split(delim); + var separator = '_'; + var headerMap = []; + var headerCount = {}; + var duplicateHeaders = false; + + for (var j in headers) { + var header = headers[j]; + if (isFunction(config.transformHeader)) + header = config.transformHeader(header, j); + var headerName = header; + + var count = headerCount[header] || 0; + if (count > 0) { + duplicateHeaders = true; + headerName = header + separator + count; + } + headerCount[header] = count + 1; + // In case it already exists, we add more separtors + while (headerMap.includes(headerName)) { + headerName = headerName + separator + count; + } + headerMap.push(headerName); + } + if (duplicateHeaders) { + var editedInput = input.split(newline); + editedInput[0] = headerMap.join(delim); + input = editedInput.join(newline); + } + } + if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) + { + var rows = input.split(newline); + for (var i = 0; i < rows.length; i++) + { + row = rows[i]; + cursor += row.length; + if (i !== rows.length - 1) + cursor += newline.length; + else if (ignoreLastRow) + return returnable(); + if (comments && row.substring(0, commentsLen) === comments) + continue; + if (stepIsFunction) + { + data = []; + pushRow(row.split(delim)); + doStep(); + if (aborted) + return returnable(); + } + else + pushRow(row.split(delim)); + if (preview && i >= preview) + { + data = data.slice(0, preview); + return returnable(true); + } + } + return returnable(); + } + + var nextDelim = input.indexOf(delim, cursor); + var nextNewline = input.indexOf(newline, cursor); + var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g'); + var quoteSearch = input.indexOf(quoteChar, cursor); + + // Parser loop + for (;;) + { + // Field has opening quote + if (input[cursor] === quoteChar) + { + // Start our search for the closing quote where the cursor is + quoteSearch = cursor; + + // Skip the opening quote + cursor++; + + for (;;) + { + // Find closing quote + quoteSearch = input.indexOf(quoteChar, quoteSearch + 1); + + //No other quotes are found - no other delimiters + if (quoteSearch === -1) + { + if (!ignoreLastRow) { + // No closing quote... what a pity + errors.push({ + type: 'Quotes', + code: 'MissingQuotes', + message: 'Quoted field unterminated', + row: data.length, // row has yet to be inserted + index: cursor + }); + } + return finish(); + } + + // Closing quote at EOF + if (quoteSearch === inputLen - 1) + { + var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); + return finish(value); + } + + // If this quote is escaped, it's part of the data; skip it + // If the quote character is the escape character, then check if the next character is the escape character + if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) + { + quoteSearch++; + continue; + } + + // If the quote character is not the escape character, then check if the previous character was the escape character + if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar) + { + continue; + } + + if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) { + nextDelim = input.indexOf(delim, (quoteSearch + 1)); + } + if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) { + nextNewline = input.indexOf(newline, (quoteSearch + 1)); + } + // Check up to nextDelim or nextNewline, whichever is closest + var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline); + var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo); + + // Closing quote followed by delimiter or 'unnecessary spaces + delimiter' + if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim) + { + row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); + cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; + + // If char after following delimiter is not quoteChar, we find next quote char position + if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar) + { + quoteSearch = input.indexOf(quoteChar, cursor); + } + nextDelim = input.indexOf(delim, cursor); + nextNewline = input.indexOf(newline, cursor); + break; + } + + var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); + + // Closing quote followed by newline or 'unnecessary spaces + newLine' + if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline) + { + row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); + saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); + nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field + quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line + + if (stepIsFunction) + { + doStep(); + if (aborted) + return returnable(); + } + + if (preview && data.length >= preview) + return returnable(true); + + break; + } + + + // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string + errors.push({ + type: 'Quotes', + code: 'InvalidQuotes', + message: 'Trailing quote on quoted field is malformed', + row: data.length, // row has yet to be inserted + index: cursor + }); + + quoteSearch++; + continue; + + } + + continue; + } + + // Comment found at start of new line + if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments) + { + if (nextNewline === -1) // Comment ends at EOF + return returnable(); + cursor = nextNewline + newlineLen; + nextNewline = input.indexOf(newline, cursor); + nextDelim = input.indexOf(delim, cursor); + continue; + } + + // Next delimiter comes before next newline, so we've reached end of field + if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) + { + row.push(input.substring(cursor, nextDelim)); + cursor = nextDelim + delimLen; + // we look for next delimiter char + nextDelim = input.indexOf(delim, cursor); + continue; + } + + // End of row + if (nextNewline !== -1) + { + row.push(input.substring(cursor, nextNewline)); + saveRow(nextNewline + newlineLen); + + if (stepIsFunction) + { + doStep(); + if (aborted) + return returnable(); + } + + if (preview && data.length >= preview) + return returnable(true); + + continue; + } + + break; + } + + + return finish(); + + + function pushRow(row) + { + data.push(row); + lastCursor = cursor; + } + + /** + * checks if there are extra spaces after closing quote and given index without any text + * if Yes, returns the number of spaces + */ + function extraSpaces(index) { + var spaceLength = 0; + if (index !== -1) { + var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); + if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { + spaceLength = textBetweenClosingQuoteAndIndex.length; + } + } + return spaceLength; + } + + /** + * Appends the remaining input from cursor to the end into + * row, saves the row, calls step, and returns the results. + */ + function finish(value) + { + if (ignoreLastRow) + return returnable(); + if (typeof value === 'undefined') + value = input.substring(cursor); + row.push(value); + cursor = inputLen; // important in case parsing is paused + pushRow(row); + if (stepIsFunction) + doStep(); + return returnable(); + } + + /** + * Appends the current row to the results. It sets the cursor + * to newCursor and finds the nextNewline. The caller should + * take care to execute user's step function and check for + * preview and end parsing if necessary. + */ + function saveRow(newCursor) + { + cursor = newCursor; + pushRow(row); + row = []; + nextNewline = input.indexOf(newline, cursor); + } + + /** Returns an object with the results, errors, and meta. */ + function returnable(stopped) + { + return { + data: data, + errors: errors, + meta: { + delimiter: delim, + linebreak: newline, + aborted: aborted, + truncated: !!stopped, + cursor: lastCursor + (baseIndex || 0) + } + }; + } + + /** Executes the user's step function and resets data & errors. */ + function doStep() + { + step(returnable()); + data = []; + errors = []; + } + }; + + /** Sets the abort flag */ + this.abort = function() + { + aborted = true; + }; + + /** Gets the cursor position */ + this.getCharIndex = function() + { + return cursor; + }; + } + + + function newWorker() + { + if (!Papa.WORKERS_SUPPORTED) + return false; + + var workerUrl = getWorkerBlob(); + var w = new global.Worker(workerUrl); + w.onmessage = mainThreadReceivedMessage; + w.id = workerIdCounter++; + workers[w.id] = w; + return w; + } + + /** Callback when main thread receives a message */ + function mainThreadReceivedMessage(e) + { + var msg = e.data; + var worker = workers[msg.workerId]; + var aborted = false; + + if (msg.error) + worker.userError(msg.error, msg.file); + else if (msg.results && msg.results.data) + { + var abort = function() { + aborted = true; + completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); + }; + + var handle = { + abort: abort, + pause: notImplemented, + resume: notImplemented + }; + + if (isFunction(worker.userStep)) + { + for (var i = 0; i < msg.results.data.length; i++) + { + worker.userStep({ + data: msg.results.data[i], + errors: msg.results.errors, + meta: msg.results.meta + }, handle); + if (aborted) + break; + } + delete msg.results; // free memory ASAP + } + else if (isFunction(worker.userChunk)) + { + worker.userChunk(msg.results, handle, msg.file); + delete msg.results; + } + } + + if (msg.finished && !aborted) + completeWorker(msg.workerId, msg.results); + } + + function completeWorker(workerId, results) { + var worker = workers[workerId]; + if (isFunction(worker.userComplete)) + worker.userComplete(results); + worker.terminate(); + delete workers[workerId]; + } + + function notImplemented() { + throw new Error('Not implemented.'); + } + + /** Callback when worker thread receives a message */ + function workerThreadReceivedMessage(e) + { + var msg = e.data; + + if (typeof Papa.WORKER_ID === 'undefined' && msg) + Papa.WORKER_ID = msg.workerId; + + if (typeof msg.input === 'string') + { + global.postMessage({ + workerId: Papa.WORKER_ID, + results: Papa.parse(msg.input, msg.config), + finished: true + }); + } + else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106) + { + var results = Papa.parse(msg.input, msg.config); + if (results) + global.postMessage({ + workerId: Papa.WORKER_ID, + results: results, + finished: true + }); + } + } + + /** Makes a deep copy of an array or object (mostly) */ + function copy(obj) + { + if (typeof obj !== 'object' || obj === null) + return obj; + var cpy = Array.isArray(obj) ? [] : {}; + for (var key in obj) + cpy[key] = copy(obj[key]); + return cpy; + } + + function bindFunction(f, self) + { + return function() { f.apply(self, arguments); }; + } + + function isFunction(func) + { + return typeof func === 'function'; + } + + return Papa; +})); + + /***/ }), /***/ 8551: @@ -39098,6 +41522,11 @@ var external_path_ = __nccwpck_require__(1017); // EXTERNAL MODULE: ./node_modules/csvtojson/v2/index.js var v2 = __nccwpck_require__(7463); var v2_default = /*#__PURE__*/__nccwpck_require__.n(v2); +// EXTERNAL MODULE: ./node_modules/convert-csv-to-json/index.js +var convert_csv_to_json = __nccwpck_require__(224); +// EXTERNAL MODULE: ./node_modules/papaparse/papaparse.js +var papaparse = __nccwpck_require__(877); +var papaparse_default = /*#__PURE__*/__nccwpck_require__.n(papaparse); // EXTERNAL MODULE: ./src/isFileExists.ts var isFileExists = __nccwpck_require__(2139); ;// CONCATENATED MODULE: ./src/report_chart.ts @@ -39110,6 +41539,8 @@ const chartReport = Buffer.from('PCEtLSByZXBvcnQtYWN0aW9uIC0tPgo8IWRvY3R5cGUgaHR + + const csvExt = '.csv'; const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const dataFile = external_path_.join(reportBaseDir, 'data.json'); @@ -39127,6 +41558,25 @@ const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const filesContent = []; if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await v2_default()().fromFile(sourceReportDir); + const json2 = convert_csv_to_json.getJsonFromCsv(sourceReportDir); + const json3 = await new Promise((resolve) => papaparse_default().parse(sourceReportDir, { + complete(results) { + resolve(results); + }, + })); + const jsonStr = JSON.stringify(json); + const jsonStr2 = JSON.stringify(json2); + const jsonStr3 = JSON.stringify(json3); + console.log('jsonStr === jsonStr2', jsonStr === jsonStr2); + console.log('jsonStr === jsonStr3', jsonStr === jsonStr3); + console.log('jsonStr2 === jsonStr3', jsonStr2 === jsonStr3); + console.log('-'.repeat(60)); + console.log(jsonStr); + console.log('^'.repeat(60)); + console.log(jsonStr2); + console.log('^'.repeat(60)); + console.log(jsonStr3); + console.log('-'.repeat(60)); filesContent.push({ name: external_path_.basename(sourceReportDir, external_path_.extname(sourceReportDir)), json }); } else { diff --git a/dist/licenses.txt b/dist/licenses.txt index bf11c2e..3d22c0e 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -483,6 +483,684 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +convert-csv-to-json +ISC + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + + csvtojson MIT Copyright (C) 2013 Keyang Xiang @@ -596,6 +1274,30 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +papaparse +MIT +The MIT License (MIT) + +Copyright (c) 2015 Matthew Holt + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + strip-bom MIT The MIT License (MIT) diff --git a/package-lock.json b/package-lock.json index a3f18e6..dda4781 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,11 +13,14 @@ "@actions/core": "^1.10.1", "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", - "csvtojson": "^2.0.10" + "convert-csv-to-json": "^2.46.0", + "csvtojson": "^2.0.10", + "papaparse": "^5.4.1" }, "devDependencies": { "@playwright/test": "^1.43.1", "@types/node": "^20.12.8", + "@types/papaparse": "^5.3.14", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@vercel/ncc": "^0.38.1", @@ -629,6 +632,15 @@ "undici-types": "~5.26.4" } }, + "node_modules/@types/papaparse": { + "version": "5.3.14", + "resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.3.14.tgz", + "integrity": "sha512-LxJ4iEFcpqc6METwp9f6BV6VVc43m6MfH0VqFosHvrUgfXiFe6ww7R3itkOQ+TCK6Y+Iv/+RnnvtRZnkc5Kc9g==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/semver": { "version": "7.5.8", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", @@ -1380,6 +1392,11 @@ "node": ">=8" } }, + "node_modules/convert-csv-to-json": { + "version": "2.46.0", + "resolved": "https://registry.npmjs.org/convert-csv-to-json/-/convert-csv-to-json-2.46.0.tgz", + "integrity": "sha512-Q7PjRjhECa5nBUEGbsKXvB8YaygVUesF/sYnaoCPTWoiwJEDCbLd2CcFDE1y80Q347IaTQukCQSCP2fR5IW+5g==" + }, "node_modules/cookie": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", @@ -4056,6 +4073,11 @@ "node": ">= 14" } }, + "node_modules/papaparse": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.4.1.tgz", + "integrity": "sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw==" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", diff --git a/package.json b/package.json index 83edcdf..baca91c 100644 --- a/package.json +++ b/package.json @@ -35,11 +35,14 @@ "@actions/core": "^1.10.1", "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", - "csvtojson": "^2.0.10" + "convert-csv-to-json": "^2.46.0", + "csvtojson": "^2.0.10", + "papaparse": "^5.4.1" }, "devDependencies": { "@playwright/test": "^1.43.1", "@types/node": "^20.12.8", + "@types/papaparse": "^5.3.14", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@vercel/ncc": "^0.38.1", diff --git a/src/csvReport.ts b/src/csvReport.ts index 08f4b40..9dd45fa 100644 --- a/src/csvReport.ts +++ b/src/csvReport.ts @@ -1,6 +1,8 @@ import * as fs from 'fs/promises' import * as path from 'path' import csvtojson from 'csvtojson' +import csvToJson from 'convert-csv-to-json' +import Papa from 'papaparse' import { isFileExist } from './isFileExists.js' import { chartReport } from './report_chart.js' @@ -28,6 +30,30 @@ export const csvReport = async ( const filesContent: Array<{ name: string; json: Array> }> = [] if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await csvtojson().fromFile(sourceReportDir) + const json2 = csvToJson.getJsonFromCsv(sourceReportDir) + const json3 = await new Promise((resolve) => + Papa.parse(sourceReportDir, { + complete(results) { + resolve(results) + }, + }) + ) + const jsonStr = JSON.stringify(json) + const jsonStr2 = JSON.stringify(json2) + const jsonStr3 = JSON.stringify(json3) + + console.log('jsonStr === jsonStr2', jsonStr === jsonStr2) + console.log('jsonStr === jsonStr3', jsonStr === jsonStr3) + console.log('jsonStr2 === jsonStr3', jsonStr2 === jsonStr3) + + console.log('-'.repeat(60)) + console.log(jsonStr) + console.log('^'.repeat(60)) + console.log(jsonStr2) + console.log('^'.repeat(60)) + console.log(jsonStr3) + console.log('-'.repeat(60)) + filesContent.push({ name: path.basename(sourceReportDir, path.extname(sourceReportDir)), json }) } else { const csvFiles = (await fs.readdir(sourceReportDir, { withFileTypes: true })) From 23f94e21534723df2e4ad907b465b1b0c1c70a60 Mon Sep 17 00:00:00 2001 From: Mykola Grybyk Date: Sun, 5 May 2024 23:21:21 +0200 Subject: [PATCH 2/4] another attempt --- dist/index.js | 3 ++- src/csvReport.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index 0a7dfef..370149e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -41558,8 +41558,9 @@ const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const filesContent = []; if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await v2_default()().fromFile(sourceReportDir); - const json2 = convert_csv_to_json.getJsonFromCsv(sourceReportDir); + const json2 = convert_csv_to_json.parseSubArray('*', ',').getJsonFromCsv(sourceReportDir); const json3 = await new Promise((resolve) => papaparse_default().parse(sourceReportDir, { + delimiter: ',', complete(results) { resolve(results); }, diff --git a/src/csvReport.ts b/src/csvReport.ts index 9dd45fa..309aaaf 100644 --- a/src/csvReport.ts +++ b/src/csvReport.ts @@ -30,9 +30,10 @@ export const csvReport = async ( const filesContent: Array<{ name: string; json: Array> }> = [] if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await csvtojson().fromFile(sourceReportDir) - const json2 = csvToJson.getJsonFromCsv(sourceReportDir) + const json2 = csvToJson.parseSubArray('*', ',').getJsonFromCsv(sourceReportDir) const json3 = await new Promise((resolve) => Papa.parse(sourceReportDir, { + delimiter: ',', complete(results) { resolve(results) }, From 0b31dbff104457014bf86b4ce423d56d6cf633da Mon Sep 17 00:00:00 2001 From: Mykola Grybyk Date: Sun, 5 May 2024 23:27:18 +0200 Subject: [PATCH 3/4] remove papaparse due to critical vulnerability --- dist/index.js | 1943 +-------------------------------------------- dist/licenses.txt | 24 - package-lock.json | 18 +- package.json | 4 +- src/csvReport.ts | 17 +- 5 files changed, 5 insertions(+), 2001 deletions(-) diff --git a/dist/index.js b/dist/index.js index 370149e..5d448f4 100644 --- a/dist/index.js +++ b/dist/index.js @@ -16261,1932 +16261,6 @@ function onceStrict (fn) { } -/***/ }), - -/***/ 877: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - -/* @license -Papa Parse -v5.4.1 -https://github.com/mholt/PapaParse -License: MIT -*/ - -(function(root, factory) -{ - /* globals define */ - if (typeof define === 'function' && define.amd) - { - // AMD. Register as an anonymous module. - define([], factory); - } - else if (true) - { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } - else - {} - // in strict mode we cannot access arguments.callee, so we need a named reference to - // stringify the factory method for the blob worker - // eslint-disable-next-line func-name -}(this, function moduleFactory() -{ - 'use strict'; - - var global = (function() { - // alternative method, similar to `Function('return this')()` - // but without using `eval` (which is disabled when - // using Content Security Policy). - - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof global !== 'undefined') { return global; } - - // When running tests none of the above have been defined - return {}; - })(); - - - function getWorkerBlob() { - var URL = global.URL || global.webkitURL || null; - var code = moduleFactory.toString(); - return Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ", '(', code, ')();'], {type: 'text/javascript'}))); - } - - var IS_WORKER = !global.document && !!global.postMessage, - IS_PAPA_WORKER = global.IS_PAPA_WORKER || false; - - var workers = {}, workerIdCounter = 0; - - var Papa = {}; - - Papa.parse = CsvToJson; - Papa.unparse = JsonToCsv; - - Papa.RECORD_SEP = String.fromCharCode(30); - Papa.UNIT_SEP = String.fromCharCode(31); - Papa.BYTE_ORDER_MARK = '\ufeff'; - Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK]; - Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker; - Papa.NODE_STREAM_INPUT = 1; - - // Configurable chunk sizes for local and remote files, respectively - Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB - Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB - Papa.DefaultDelimiter = ','; // Used if not specified and detection fails - - // Exposed for testing and development only - Papa.Parser = Parser; - Papa.ParserHandle = ParserHandle; - Papa.NetworkStreamer = NetworkStreamer; - Papa.FileStreamer = FileStreamer; - Papa.StringStreamer = StringStreamer; - Papa.ReadableStreamStreamer = ReadableStreamStreamer; - if (typeof PAPA_BROWSER_CONTEXT === 'undefined') { - Papa.DuplexStreamStreamer = DuplexStreamStreamer; - } - - if (global.jQuery) - { - var $ = global.jQuery; - $.fn.parse = function(options) - { - var config = options.config || {}; - var queue = []; - - this.each(function(idx) - { - var supported = $(this).prop('tagName').toUpperCase() === 'INPUT' - && $(this).attr('type').toLowerCase() === 'file' - && global.FileReader; - - if (!supported || !this.files || this.files.length === 0) - return true; // continue to next input element - - for (var i = 0; i < this.files.length; i++) - { - queue.push({ - file: this.files[i], - inputElem: this, - instanceConfig: $.extend({}, config) - }); - } - }); - - parseNextFile(); // begin parsing - return this; // maintains chainability - - - function parseNextFile() - { - if (queue.length === 0) - { - if (isFunction(options.complete)) - options.complete(); - return; - } - - var f = queue[0]; - - if (isFunction(options.before)) - { - var returned = options.before(f.file, f.inputElem); - - if (typeof returned === 'object') - { - if (returned.action === 'abort') - { - error('AbortError', f.file, f.inputElem, returned.reason); - return; // Aborts all queued files immediately - } - else if (returned.action === 'skip') - { - fileComplete(); // parse the next file in the queue, if any - return; - } - else if (typeof returned.config === 'object') - f.instanceConfig = $.extend(f.instanceConfig, returned.config); - } - else if (returned === 'skip') - { - fileComplete(); // parse the next file in the queue, if any - return; - } - } - - // Wrap up the user's complete callback, if any, so that ours also gets executed - var userCompleteFunc = f.instanceConfig.complete; - f.instanceConfig.complete = function(results) - { - if (isFunction(userCompleteFunc)) - userCompleteFunc(results, f.file, f.inputElem); - fileComplete(); - }; - - Papa.parse(f.file, f.instanceConfig); - } - - function error(name, file, elem, reason) - { - if (isFunction(options.error)) - options.error({name: name}, file, elem, reason); - } - - function fileComplete() - { - queue.splice(0, 1); - parseNextFile(); - } - }; - } - - - if (IS_PAPA_WORKER) - { - global.onmessage = workerThreadReceivedMessage; - } - - - - - function CsvToJson(_input, _config) - { - _config = _config || {}; - var dynamicTyping = _config.dynamicTyping || false; - if (isFunction(dynamicTyping)) { - _config.dynamicTypingFunction = dynamicTyping; - // Will be filled on first row call - dynamicTyping = {}; - } - _config.dynamicTyping = dynamicTyping; - - _config.transform = isFunction(_config.transform) ? _config.transform : false; - - if (_config.worker && Papa.WORKERS_SUPPORTED) - { - var w = newWorker(); - - w.userStep = _config.step; - w.userChunk = _config.chunk; - w.userComplete = _config.complete; - w.userError = _config.error; - - _config.step = isFunction(_config.step); - _config.chunk = isFunction(_config.chunk); - _config.complete = isFunction(_config.complete); - _config.error = isFunction(_config.error); - delete _config.worker; // prevent infinite loop - - w.postMessage({ - input: _input, - config: _config, - workerId: w.id - }); - - return; - } - - var streamer = null; - if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined') - { - // create a node Duplex stream for use - // with .pipe - streamer = new DuplexStreamStreamer(_config); - return streamer.getStream(); - } - else if (typeof _input === 'string') - { - _input = stripBom(_input); - if (_config.download) - streamer = new NetworkStreamer(_config); - else - streamer = new StringStreamer(_config); - } - else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on)) - { - streamer = new ReadableStreamStreamer(_config); - } - else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106) - streamer = new FileStreamer(_config); - - return streamer.stream(_input); - - // Strip character from UTF-8 BOM encoded files that cause issue parsing the file - function stripBom(string) { - if (string.charCodeAt(0) === 0xfeff) { - return string.slice(1); - } - return string; - } - } - - - - - - - function JsonToCsv(_input, _config) - { - // Default configuration - - /** whether to surround every datum with quotes */ - var _quotes = false; - - /** whether to write headers */ - var _writeHeader = true; - - /** delimiting character(s) */ - var _delimiter = ','; - - /** newline character(s) */ - var _newline = '\r\n'; - - /** quote character */ - var _quoteChar = '"'; - - /** escaped quote character, either "" or " */ - var _escapedQuote = _quoteChar + _quoteChar; - - /** whether to skip empty lines */ - var _skipEmptyLines = false; - - /** the columns (keys) we expect when we unparse objects */ - var _columns = null; - - /** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */ - var _escapeFormulae = false; - - unpackConfig(); - - var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g'); - - if (typeof _input === 'string') - _input = JSON.parse(_input); - - if (Array.isArray(_input)) - { - if (!_input.length || Array.isArray(_input[0])) - return serialize(null, _input, _skipEmptyLines); - else if (typeof _input[0] === 'object') - return serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines); - } - else if (typeof _input === 'object') - { - if (typeof _input.data === 'string') - _input.data = JSON.parse(_input.data); - - if (Array.isArray(_input.data)) - { - if (!_input.fields) - _input.fields = _input.meta && _input.meta.fields || _columns; - - if (!_input.fields) - _input.fields = Array.isArray(_input.data[0]) - ? _input.fields - : typeof _input.data[0] === 'object' - ? Object.keys(_input.data[0]) - : []; - - if (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object') - _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf'] - } - - return serialize(_input.fields || [], _input.data || [], _skipEmptyLines); - } - - // Default (any valid paths should return before this) - throw new Error('Unable to serialize unrecognized input'); - - - function unpackConfig() - { - if (typeof _config !== 'object') - return; - - if (typeof _config.delimiter === 'string' - && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length) - { - _delimiter = _config.delimiter; - } - - if (typeof _config.quotes === 'boolean' - || typeof _config.quotes === 'function' - || Array.isArray(_config.quotes)) - _quotes = _config.quotes; - - if (typeof _config.skipEmptyLines === 'boolean' - || typeof _config.skipEmptyLines === 'string') - _skipEmptyLines = _config.skipEmptyLines; - - if (typeof _config.newline === 'string') - _newline = _config.newline; - - if (typeof _config.quoteChar === 'string') - _quoteChar = _config.quoteChar; - - if (typeof _config.header === 'boolean') - _writeHeader = _config.header; - - if (Array.isArray(_config.columns)) { - - if (_config.columns.length === 0) throw new Error('Option columns is empty'); - - _columns = _config.columns; - } - - if (_config.escapeChar !== undefined) { - _escapedQuote = _config.escapeChar + _quoteChar; - } - - if (typeof _config.escapeFormulae === 'boolean' || _config.escapeFormulae instanceof RegExp) { - _escapeFormulae = _config.escapeFormulae instanceof RegExp ? _config.escapeFormulae : /^[=+\-@\t\r].*$/; - } - } - - /** The double for loop that iterates the data and writes out a CSV string including header row */ - function serialize(fields, data, skipEmptyLines) - { - var csv = ''; - - if (typeof fields === 'string') - fields = JSON.parse(fields); - if (typeof data === 'string') - data = JSON.parse(data); - - var hasHeader = Array.isArray(fields) && fields.length > 0; - var dataKeyedByField = !(Array.isArray(data[0])); - - // If there a header row, write it first - if (hasHeader && _writeHeader) - { - for (var i = 0; i < fields.length; i++) - { - if (i > 0) - csv += _delimiter; - csv += safe(fields[i], i); - } - if (data.length > 0) - csv += _newline; - } - - // Then write out the data - for (var row = 0; row < data.length; row++) - { - var maxCol = hasHeader ? fields.length : data[row].length; - - var emptyLine = false; - var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0; - if (skipEmptyLines && !hasHeader) - { - emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0; - } - if (skipEmptyLines === 'greedy' && hasHeader) { - var line = []; - for (var c = 0; c < maxCol; c++) { - var cx = dataKeyedByField ? fields[c] : c; - line.push(data[row][cx]); - } - emptyLine = line.join('').trim() === ''; - } - if (!emptyLine) - { - for (var col = 0; col < maxCol; col++) - { - if (col > 0 && !nullLine) - csv += _delimiter; - var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; - csv += safe(data[row][colIdx], col); - } - if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine))) - { - csv += _newline; - } - } - } - return csv; - } - - /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */ - function safe(str, col) - { - if (typeof str === 'undefined' || str === null) - return ''; - - if (str.constructor === Date) - return JSON.stringify(str).slice(1, 25); - - var needsQuotes = false; - - if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) { - str = "'" + str; - needsQuotes = true; - } - - var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote); - - needsQuotes = needsQuotes - || _quotes === true - || (typeof _quotes === 'function' && _quotes(str, col)) - || (Array.isArray(_quotes) && _quotes[col]) - || hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS) - || escapedQuoteStr.indexOf(_delimiter) > -1 - || escapedQuoteStr.charAt(0) === ' ' - || escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' '; - - return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr; - } - - function hasAny(str, substrings) - { - for (var i = 0; i < substrings.length; i++) - if (str.indexOf(substrings[i]) > -1) - return true; - return false; - } - } - - /** ChunkStreamer is the base prototype for various streamer implementations. */ - function ChunkStreamer(config) - { - this._handle = null; - this._finished = false; - this._completed = false; - this._halted = false; - this._input = null; - this._baseIndex = 0; - this._partialLine = ''; - this._rowCount = 0; - this._start = 0; - this._nextChunk = null; - this.isFirstChunk = true; - this._completeResults = { - data: [], - errors: [], - meta: {} - }; - replaceConfig.call(this, config); - - this.parseChunk = function(chunk, isFakeChunk) - { - // First chunk pre-processing - if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) - { - var modifiedChunk = this._config.beforeFirstChunk(chunk); - if (modifiedChunk !== undefined) - chunk = modifiedChunk; - } - this.isFirstChunk = false; - this._halted = false; - - // Rejoin the line we likely just split in two by chunking the file - var aggregate = this._partialLine + chunk; - this._partialLine = ''; - - var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); - - if (this._handle.paused() || this._handle.aborted()) { - this._halted = true; - return; - } - - var lastIndex = results.meta.cursor; - - if (!this._finished) - { - this._partialLine = aggregate.substring(lastIndex - this._baseIndex); - this._baseIndex = lastIndex; - } - - if (results && results.data) - this._rowCount += results.data.length; - - var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); - - if (IS_PAPA_WORKER) - { - global.postMessage({ - results: results, - workerId: Papa.WORKER_ID, - finished: finishedIncludingPreview - }); - } - else if (isFunction(this._config.chunk) && !isFakeChunk) - { - this._config.chunk(results, this._handle); - if (this._handle.paused() || this._handle.aborted()) { - this._halted = true; - return; - } - results = undefined; - this._completeResults = undefined; - } - - if (!this._config.step && !this._config.chunk) { - this._completeResults.data = this._completeResults.data.concat(results.data); - this._completeResults.errors = this._completeResults.errors.concat(results.errors); - this._completeResults.meta = results.meta; - } - - if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) { - this._config.complete(this._completeResults, this._input); - this._completed = true; - } - - if (!finishedIncludingPreview && (!results || !results.meta.paused)) - this._nextChunk(); - - return results; - }; - - this._sendError = function(error) - { - if (isFunction(this._config.error)) - this._config.error(error); - else if (IS_PAPA_WORKER && this._config.error) - { - global.postMessage({ - workerId: Papa.WORKER_ID, - error: error, - finished: false - }); - } - }; - - function replaceConfig(config) - { - // Deep-copy the config so we can edit it - var configCopy = copy(config); - configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! - if (!config.step && !config.chunk) - configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 - this._handle = new ParserHandle(configCopy); - this._handle.streamer = this; - this._config = configCopy; // persist the copy to the caller - } - } - - - function NetworkStreamer(config) - { - config = config || {}; - if (!config.chunkSize) - config.chunkSize = Papa.RemoteChunkSize; - ChunkStreamer.call(this, config); - - var xhr; - - if (IS_WORKER) - { - this._nextChunk = function() - { - this._readChunk(); - this._chunkLoaded(); - }; - } - else - { - this._nextChunk = function() - { - this._readChunk(); - }; - } - - this.stream = function(url) - { - this._input = url; - this._nextChunk(); // Starts streaming - }; - - this._readChunk = function() - { - if (this._finished) - { - this._chunkLoaded(); - return; - } - - xhr = new XMLHttpRequest(); - - if (this._config.withCredentials) - { - xhr.withCredentials = this._config.withCredentials; - } - - if (!IS_WORKER) - { - xhr.onload = bindFunction(this._chunkLoaded, this); - xhr.onerror = bindFunction(this._chunkError, this); - } - - xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER); - // Headers can only be set when once the request state is OPENED - if (this._config.downloadRequestHeaders) - { - var headers = this._config.downloadRequestHeaders; - - for (var headerName in headers) - { - xhr.setRequestHeader(headerName, headers[headerName]); - } - } - - if (this._config.chunkSize) - { - var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive - xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end); - } - - try { - xhr.send(this._config.downloadRequestBody); - } - catch (err) { - this._chunkError(err.message); - } - - if (IS_WORKER && xhr.status === 0) - this._chunkError(); - }; - - this._chunkLoaded = function() - { - if (xhr.readyState !== 4) - return; - - if (xhr.status < 200 || xhr.status >= 400) - { - this._chunkError(); - return; - } - - // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte - this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length; - this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr); - this.parseChunk(xhr.responseText); - }; - - this._chunkError = function(errorMessage) - { - var errorText = xhr.statusText || errorMessage; - this._sendError(new Error(errorText)); - }; - - function getFileSize(xhr) - { - var contentRange = xhr.getResponseHeader('Content-Range'); - if (contentRange === null) { // no content range, then finish! - return -1; - } - return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1)); - } - } - NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype); - NetworkStreamer.prototype.constructor = NetworkStreamer; - - - function FileStreamer(config) - { - config = config || {}; - if (!config.chunkSize) - config.chunkSize = Papa.LocalChunkSize; - ChunkStreamer.call(this, config); - - var reader, slice; - - // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862 - // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76 - var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105 - - this.stream = function(file) - { - this._input = file; - slice = file.slice || file.webkitSlice || file.mozSlice; - - if (usingAsyncReader) - { - reader = new FileReader(); // Preferred method of reading files, even in workers - reader.onload = bindFunction(this._chunkLoaded, this); - reader.onerror = bindFunction(this._chunkError, this); - } - else - reader = new FileReaderSync(); // Hack for running in a web worker in Firefox - - this._nextChunk(); // Starts streaming - }; - - this._nextChunk = function() - { - if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) - this._readChunk(); - }; - - this._readChunk = function() - { - var input = this._input; - if (this._config.chunkSize) - { - var end = Math.min(this._start + this._config.chunkSize, this._input.size); - input = slice.call(input, this._start, end); - } - var txt = reader.readAsText(input, this._config.encoding); - if (!usingAsyncReader) - this._chunkLoaded({ target: { result: txt } }); // mimic the async signature - }; - - this._chunkLoaded = function(event) - { - // Very important to increment start each time before handling results - this._start += this._config.chunkSize; - this._finished = !this._config.chunkSize || this._start >= this._input.size; - this.parseChunk(event.target.result); - }; - - this._chunkError = function() - { - this._sendError(reader.error); - }; - - } - FileStreamer.prototype = Object.create(ChunkStreamer.prototype); - FileStreamer.prototype.constructor = FileStreamer; - - - function StringStreamer(config) - { - config = config || {}; - ChunkStreamer.call(this, config); - - var remaining; - this.stream = function(s) - { - remaining = s; - return this._nextChunk(); - }; - this._nextChunk = function() - { - if (this._finished) return; - var size = this._config.chunkSize; - var chunk; - if(size) { - chunk = remaining.substring(0, size); - remaining = remaining.substring(size); - } else { - chunk = remaining; - remaining = ''; - } - this._finished = !remaining; - return this.parseChunk(chunk); - }; - } - StringStreamer.prototype = Object.create(StringStreamer.prototype); - StringStreamer.prototype.constructor = StringStreamer; - - - function ReadableStreamStreamer(config) - { - config = config || {}; - - ChunkStreamer.call(this, config); - - var queue = []; - var parseOnData = true; - var streamHasEnded = false; - - this.pause = function() - { - ChunkStreamer.prototype.pause.apply(this, arguments); - this._input.pause(); - }; - - this.resume = function() - { - ChunkStreamer.prototype.resume.apply(this, arguments); - this._input.resume(); - }; - - this.stream = function(stream) - { - this._input = stream; - - this._input.on('data', this._streamData); - this._input.on('end', this._streamEnd); - this._input.on('error', this._streamError); - }; - - this._checkIsFinished = function() - { - if (streamHasEnded && queue.length === 1) { - this._finished = true; - } - }; - - this._nextChunk = function() - { - this._checkIsFinished(); - if (queue.length) - { - this.parseChunk(queue.shift()); - } - else - { - parseOnData = true; - } - }; - - this._streamData = bindFunction(function(chunk) - { - try - { - queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding)); - - if (parseOnData) - { - parseOnData = false; - this._checkIsFinished(); - this.parseChunk(queue.shift()); - } - } - catch (error) - { - this._streamError(error); - } - }, this); - - this._streamError = bindFunction(function(error) - { - this._streamCleanUp(); - this._sendError(error); - }, this); - - this._streamEnd = bindFunction(function() - { - this._streamCleanUp(); - streamHasEnded = true; - this._streamData(''); - }, this); - - this._streamCleanUp = bindFunction(function() - { - this._input.removeListener('data', this._streamData); - this._input.removeListener('end', this._streamEnd); - this._input.removeListener('error', this._streamError); - }, this); - } - ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype); - ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer; - - - function DuplexStreamStreamer(_config) { - var Duplex = (__nccwpck_require__(2781).Duplex); - var config = copy(_config); - var parseOnWrite = true; - var writeStreamHasFinished = false; - var parseCallbackQueue = []; - var stream = null; - - this._onCsvData = function(results) - { - var data = results.data; - if (!stream.push(data) && !this._handle.paused()) { - // the writeable consumer buffer has filled up - // so we need to pause until more items - // can be processed - this._handle.pause(); - } - }; - - this._onCsvComplete = function() - { - // node will finish the read stream when - // null is pushed - stream.push(null); - }; - - config.step = bindFunction(this._onCsvData, this); - config.complete = bindFunction(this._onCsvComplete, this); - ChunkStreamer.call(this, config); - - this._nextChunk = function() - { - if (writeStreamHasFinished && parseCallbackQueue.length === 1) { - this._finished = true; - } - if (parseCallbackQueue.length) { - parseCallbackQueue.shift()(); - } else { - parseOnWrite = true; - } - }; - - this._addToParseQueue = function(chunk, callback) - { - // add to queue so that we can indicate - // completion via callback - // node will automatically pause the incoming stream - // when too many items have been added without their - // callback being invoked - parseCallbackQueue.push(bindFunction(function() { - this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding)); - if (isFunction(callback)) { - return callback(); - } - }, this)); - if (parseOnWrite) { - parseOnWrite = false; - this._nextChunk(); - } - }; - - this._onRead = function() - { - if (this._handle.paused()) { - // the writeable consumer can handle more data - // so resume the chunk parsing - this._handle.resume(); - } - }; - - this._onWrite = function(chunk, encoding, callback) - { - this._addToParseQueue(chunk, callback); - }; - - this._onWriteComplete = function() - { - writeStreamHasFinished = true; - // have to write empty string - // so parser knows its done - this._addToParseQueue(''); - }; - - this.getStream = function() - { - return stream; - }; - stream = new Duplex({ - readableObjectMode: true, - decodeStrings: false, - read: bindFunction(this._onRead, this), - write: bindFunction(this._onWrite, this) - }); - stream.once('finish', bindFunction(this._onWriteComplete, this)); - } - if (typeof PAPA_BROWSER_CONTEXT === 'undefined') { - DuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype); - DuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer; - } - - - // Use one ParserHandle per entire CSV file or string - function ParserHandle(_config) - { - // One goal is to minimize the use of regular expressions... - var MAX_FLOAT = Math.pow(2, 53); - var MIN_FLOAT = -MAX_FLOAT; - var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/; - var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/; - var self = this; - var _stepCounter = 0; // Number of times step was called (number of rows parsed) - var _rowCounter = 0; // Number of rows that have been parsed so far - var _input; // The input being parsed - var _parser; // The core parser being used - var _paused = false; // Whether we are paused or not - var _aborted = false; // Whether the parser has aborted or not - var _delimiterError; // Temporary state between delimiter detection and processing results - var _fields = []; // Fields are from the header row of the input, if there is one - var _results = { // The last results returned from the parser - data: [], - errors: [], - meta: {} - }; - - if (isFunction(_config.step)) - { - var userStep = _config.step; - _config.step = function(results) - { - _results = results; - - if (needsHeaderRow()) - processResults(); - else // only call user's step function after header row - { - processResults(); - - // It's possbile that this line was empty and there's no row here after all - if (_results.data.length === 0) - return; - - _stepCounter += results.data.length; - if (_config.preview && _stepCounter > _config.preview) - _parser.abort(); - else { - _results.data = _results.data[0]; - userStep(_results, self); - } - } - }; - } - - /** - * Parses input. Most users won't need, and shouldn't mess with, the baseIndex - * and ignoreLastRow parameters. They are used by streamers (wrapper functions) - * when an input comes in multiple chunks, like from a file. - */ - this.parse = function(input, baseIndex, ignoreLastRow) - { - var quoteChar = _config.quoteChar || '"'; - if (!_config.newline) - _config.newline = guessLineEndings(input, quoteChar); - - _delimiterError = false; - if (!_config.delimiter) - { - var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess); - if (delimGuess.successful) - _config.delimiter = delimGuess.bestDelimiter; - else - { - _delimiterError = true; // add error after parsing (otherwise it would be overwritten) - _config.delimiter = Papa.DefaultDelimiter; - } - _results.meta.delimiter = _config.delimiter; - } - else if(isFunction(_config.delimiter)) - { - _config.delimiter = _config.delimiter(input); - _results.meta.delimiter = _config.delimiter; - } - - var parserConfig = copy(_config); - if (_config.preview && _config.header) - parserConfig.preview++; // to compensate for header row - - _input = input; - _parser = new Parser(parserConfig); - _results = _parser.parse(_input, baseIndex, ignoreLastRow); - processResults(); - return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } }); - }; - - this.paused = function() - { - return _paused; - }; - - this.pause = function() - { - _paused = true; - _parser.abort(); - - // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring, - // otherwise we can get duplicate content within a row - _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex()); - }; - - this.resume = function() - { - if(self.streamer._halted) { - _paused = false; - self.streamer.parseChunk(_input, true); - } else { - // Bugfix: #636 In case the processing hasn't halted yet - // wait for it to halt in order to resume - setTimeout(self.resume, 3); - } - }; - - this.aborted = function() - { - return _aborted; - }; - - this.abort = function() - { - _aborted = true; - _parser.abort(); - _results.meta.aborted = true; - if (isFunction(_config.complete)) - _config.complete(_results); - _input = ''; - }; - - function testEmptyLine(s) { - return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; - } - - function testFloat(s) { - if (FLOAT.test(s)) { - var floatValue = parseFloat(s); - if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) { - return true; - } - } - return false; - } - - function processResults() - { - if (_results && _delimiterError) - { - addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\''); - _delimiterError = false; - } - - if (_config.skipEmptyLines) - { - _results.data = _results.data.filter(function(d) { - return !testEmptyLine(d); - }); - } - - if (needsHeaderRow()) - fillHeaderFields(); - - return applyHeaderAndDynamicTypingAndTransformation(); - } - - function needsHeaderRow() - { - return _config.header && _fields.length === 0; - } - - function fillHeaderFields() - { - if (!_results) - return; - - function addHeader(header, i) - { - if (isFunction(_config.transformHeader)) - header = _config.transformHeader(header, i); - - _fields.push(header); - } - - if (Array.isArray(_results.data[0])) - { - for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) - _results.data[i].forEach(addHeader); - - _results.data.splice(0, 1); - } - // if _results.data[0] is not an array, we are in a step where _results.data is the row. - else - _results.data.forEach(addHeader); - } - - function shouldApplyDynamicTyping(field) { - // Cache function values to avoid calling it for each row - if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { - _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); - } - return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; - } - - function parseDynamic(field, value) - { - if (shouldApplyDynamicTyping(field)) - { - if (value === 'true' || value === 'TRUE') - return true; - else if (value === 'false' || value === 'FALSE') - return false; - else if (testFloat(value)) - return parseFloat(value); - else if (ISO_DATE.test(value)) - return new Date(value); - else - return (value === '' ? null : value); - } - return value; - } - - function applyHeaderAndDynamicTypingAndTransformation() - { - if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform)) - return _results; - - function processRow(rowSource, i) - { - var row = _config.header ? {} : []; - - var j; - for (j = 0; j < rowSource.length; j++) - { - var field = j; - var value = rowSource[j]; - - if (_config.header) - field = j >= _fields.length ? '__parsed_extra' : _fields[j]; - - if (_config.transform) - value = _config.transform(value,field); - - value = parseDynamic(field, value); - - if (field === '__parsed_extra') - { - row[field] = row[field] || []; - row[field].push(value); - } - else - row[field] = value; - } - - - if (_config.header) - { - if (j > _fields.length) - addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); - else if (j < _fields.length) - addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i); - } - - return row; - } - - var incrementBy = 1; - if (!_results.data.length || Array.isArray(_results.data[0])) - { - _results.data = _results.data.map(processRow); - incrementBy = _results.data.length; - } - else - _results.data = processRow(_results.data, 0); - - - if (_config.header && _results.meta) - _results.meta.fields = _fields; - - _rowCounter += incrementBy; - return _results; - } - - function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { - var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount; - - delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; - - for (var i = 0; i < delimitersToGuess.length; i++) { - var delim = delimitersToGuess[i]; - var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; - fieldCountPrevRow = undefined; - - var preview = new Parser({ - comments: comments, - delimiter: delim, - newline: newline, - preview: 10 - }).parse(input); - - for (var j = 0; j < preview.data.length; j++) { - if (skipEmptyLines && testEmptyLine(preview.data[j])) { - emptyLinesCount++; - continue; - } - var fieldCount = preview.data[j].length; - avgFieldCount += fieldCount; - - if (typeof fieldCountPrevRow === 'undefined') { - fieldCountPrevRow = fieldCount; - continue; - } - else if (fieldCount > 0) { - delta += Math.abs(fieldCount - fieldCountPrevRow); - fieldCountPrevRow = fieldCount; - } - } - - if (preview.data.length > 0) - avgFieldCount /= (preview.data.length - emptyLinesCount); - - if ((typeof bestDelta === 'undefined' || delta <= bestDelta) - && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) { - bestDelta = delta; - bestDelim = delim; - maxFieldCount = avgFieldCount; - } - } - - _config.delimiter = bestDelim; - - return { - successful: !!bestDelim, - bestDelimiter: bestDelim - }; - } - - function guessLineEndings(input, quoteChar) - { - input = input.substring(0, 1024 * 1024); // max length 1 MB - // Replace all the text inside quotes - var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm'); - input = input.replace(re, ''); - - var r = input.split('\r'); - - var n = input.split('\n'); - - var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length); - - if (r.length === 1 || nAppearsFirst) - return '\n'; - - var numWithN = 0; - for (var i = 0; i < r.length; i++) - { - if (r[i][0] === '\n') - numWithN++; - } - - return numWithN >= r.length / 2 ? '\r\n' : '\r'; - } - - function addError(type, code, msg, row) - { - var error = { - type: type, - code: code, - message: msg - }; - if(row !== undefined) { - error.row = row; - } - _results.errors.push(error); - } - } - - /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */ - function escapeRegExp(string) - { - return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string - } - - /** The core parser implements speedy and correct CSV parsing */ - function Parser(config) - { - // Unpack the config object - config = config || {}; - var delim = config.delimiter; - var newline = config.newline; - var comments = config.comments; - var step = config.step; - var preview = config.preview; - var fastMode = config.fastMode; - var quoteChar; - if (config.quoteChar === undefined || config.quoteChar === null) { - quoteChar = '"'; - } else { - quoteChar = config.quoteChar; - } - var escapeChar = quoteChar; - if (config.escapeChar !== undefined) { - escapeChar = config.escapeChar; - } - - // Delimiter must be valid - if (typeof delim !== 'string' - || Papa.BAD_DELIMITERS.indexOf(delim) > -1) - delim = ','; - - // Comment character must be valid - if (comments === delim) - throw new Error('Comment character same as delimiter'); - else if (comments === true) - comments = '#'; - else if (typeof comments !== 'string' - || Papa.BAD_DELIMITERS.indexOf(comments) > -1) - comments = false; - - // Newline must be valid: \r, \n, or \r\n - if (newline !== '\n' && newline !== '\r' && newline !== '\r\n') - newline = '\n'; - - // We're gonna need these at the Parser scope - var cursor = 0; - var aborted = false; - - this.parse = function(input, baseIndex, ignoreLastRow) - { - // For some reason, in Chrome, this speeds things up (!?) - if (typeof input !== 'string') - throw new Error('Input must be a string'); - - // We don't need to compute some of these every time parse() is called, - // but having them in a more local scope seems to perform better - var inputLen = input.length, - delimLen = delim.length, - newlineLen = newline.length, - commentsLen = comments.length; - var stepIsFunction = isFunction(step); - - // Establish starting state - cursor = 0; - var data = [], errors = [], row = [], lastCursor = 0; - - if (!input) - return returnable(); - - // Rename headers if there are duplicates - if (config.header && !baseIndex) - { - var firstLine = input.split(newline)[0]; - var headers = firstLine.split(delim); - var separator = '_'; - var headerMap = []; - var headerCount = {}; - var duplicateHeaders = false; - - for (var j in headers) { - var header = headers[j]; - if (isFunction(config.transformHeader)) - header = config.transformHeader(header, j); - var headerName = header; - - var count = headerCount[header] || 0; - if (count > 0) { - duplicateHeaders = true; - headerName = header + separator + count; - } - headerCount[header] = count + 1; - // In case it already exists, we add more separtors - while (headerMap.includes(headerName)) { - headerName = headerName + separator + count; - } - headerMap.push(headerName); - } - if (duplicateHeaders) { - var editedInput = input.split(newline); - editedInput[0] = headerMap.join(delim); - input = editedInput.join(newline); - } - } - if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) - { - var rows = input.split(newline); - for (var i = 0; i < rows.length; i++) - { - row = rows[i]; - cursor += row.length; - if (i !== rows.length - 1) - cursor += newline.length; - else if (ignoreLastRow) - return returnable(); - if (comments && row.substring(0, commentsLen) === comments) - continue; - if (stepIsFunction) - { - data = []; - pushRow(row.split(delim)); - doStep(); - if (aborted) - return returnable(); - } - else - pushRow(row.split(delim)); - if (preview && i >= preview) - { - data = data.slice(0, preview); - return returnable(true); - } - } - return returnable(); - } - - var nextDelim = input.indexOf(delim, cursor); - var nextNewline = input.indexOf(newline, cursor); - var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g'); - var quoteSearch = input.indexOf(quoteChar, cursor); - - // Parser loop - for (;;) - { - // Field has opening quote - if (input[cursor] === quoteChar) - { - // Start our search for the closing quote where the cursor is - quoteSearch = cursor; - - // Skip the opening quote - cursor++; - - for (;;) - { - // Find closing quote - quoteSearch = input.indexOf(quoteChar, quoteSearch + 1); - - //No other quotes are found - no other delimiters - if (quoteSearch === -1) - { - if (!ignoreLastRow) { - // No closing quote... what a pity - errors.push({ - type: 'Quotes', - code: 'MissingQuotes', - message: 'Quoted field unterminated', - row: data.length, // row has yet to be inserted - index: cursor - }); - } - return finish(); - } - - // Closing quote at EOF - if (quoteSearch === inputLen - 1) - { - var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); - return finish(value); - } - - // If this quote is escaped, it's part of the data; skip it - // If the quote character is the escape character, then check if the next character is the escape character - if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) - { - quoteSearch++; - continue; - } - - // If the quote character is not the escape character, then check if the previous character was the escape character - if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar) - { - continue; - } - - if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) { - nextDelim = input.indexOf(delim, (quoteSearch + 1)); - } - if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) { - nextNewline = input.indexOf(newline, (quoteSearch + 1)); - } - // Check up to nextDelim or nextNewline, whichever is closest - var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline); - var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo); - - // Closing quote followed by delimiter or 'unnecessary spaces + delimiter' - if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim) - { - row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); - cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; - - // If char after following delimiter is not quoteChar, we find next quote char position - if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar) - { - quoteSearch = input.indexOf(quoteChar, cursor); - } - nextDelim = input.indexOf(delim, cursor); - nextNewline = input.indexOf(newline, cursor); - break; - } - - var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); - - // Closing quote followed by newline or 'unnecessary spaces + newLine' - if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline) - { - row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); - saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); - nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field - quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line - - if (stepIsFunction) - { - doStep(); - if (aborted) - return returnable(); - } - - if (preview && data.length >= preview) - return returnable(true); - - break; - } - - - // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string - errors.push({ - type: 'Quotes', - code: 'InvalidQuotes', - message: 'Trailing quote on quoted field is malformed', - row: data.length, // row has yet to be inserted - index: cursor - }); - - quoteSearch++; - continue; - - } - - continue; - } - - // Comment found at start of new line - if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments) - { - if (nextNewline === -1) // Comment ends at EOF - return returnable(); - cursor = nextNewline + newlineLen; - nextNewline = input.indexOf(newline, cursor); - nextDelim = input.indexOf(delim, cursor); - continue; - } - - // Next delimiter comes before next newline, so we've reached end of field - if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) - { - row.push(input.substring(cursor, nextDelim)); - cursor = nextDelim + delimLen; - // we look for next delimiter char - nextDelim = input.indexOf(delim, cursor); - continue; - } - - // End of row - if (nextNewline !== -1) - { - row.push(input.substring(cursor, nextNewline)); - saveRow(nextNewline + newlineLen); - - if (stepIsFunction) - { - doStep(); - if (aborted) - return returnable(); - } - - if (preview && data.length >= preview) - return returnable(true); - - continue; - } - - break; - } - - - return finish(); - - - function pushRow(row) - { - data.push(row); - lastCursor = cursor; - } - - /** - * checks if there are extra spaces after closing quote and given index without any text - * if Yes, returns the number of spaces - */ - function extraSpaces(index) { - var spaceLength = 0; - if (index !== -1) { - var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); - if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { - spaceLength = textBetweenClosingQuoteAndIndex.length; - } - } - return spaceLength; - } - - /** - * Appends the remaining input from cursor to the end into - * row, saves the row, calls step, and returns the results. - */ - function finish(value) - { - if (ignoreLastRow) - return returnable(); - if (typeof value === 'undefined') - value = input.substring(cursor); - row.push(value); - cursor = inputLen; // important in case parsing is paused - pushRow(row); - if (stepIsFunction) - doStep(); - return returnable(); - } - - /** - * Appends the current row to the results. It sets the cursor - * to newCursor and finds the nextNewline. The caller should - * take care to execute user's step function and check for - * preview and end parsing if necessary. - */ - function saveRow(newCursor) - { - cursor = newCursor; - pushRow(row); - row = []; - nextNewline = input.indexOf(newline, cursor); - } - - /** Returns an object with the results, errors, and meta. */ - function returnable(stopped) - { - return { - data: data, - errors: errors, - meta: { - delimiter: delim, - linebreak: newline, - aborted: aborted, - truncated: !!stopped, - cursor: lastCursor + (baseIndex || 0) - } - }; - } - - /** Executes the user's step function and resets data & errors. */ - function doStep() - { - step(returnable()); - data = []; - errors = []; - } - }; - - /** Sets the abort flag */ - this.abort = function() - { - aborted = true; - }; - - /** Gets the cursor position */ - this.getCharIndex = function() - { - return cursor; - }; - } - - - function newWorker() - { - if (!Papa.WORKERS_SUPPORTED) - return false; - - var workerUrl = getWorkerBlob(); - var w = new global.Worker(workerUrl); - w.onmessage = mainThreadReceivedMessage; - w.id = workerIdCounter++; - workers[w.id] = w; - return w; - } - - /** Callback when main thread receives a message */ - function mainThreadReceivedMessage(e) - { - var msg = e.data; - var worker = workers[msg.workerId]; - var aborted = false; - - if (msg.error) - worker.userError(msg.error, msg.file); - else if (msg.results && msg.results.data) - { - var abort = function() { - aborted = true; - completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } }); - }; - - var handle = { - abort: abort, - pause: notImplemented, - resume: notImplemented - }; - - if (isFunction(worker.userStep)) - { - for (var i = 0; i < msg.results.data.length; i++) - { - worker.userStep({ - data: msg.results.data[i], - errors: msg.results.errors, - meta: msg.results.meta - }, handle); - if (aborted) - break; - } - delete msg.results; // free memory ASAP - } - else if (isFunction(worker.userChunk)) - { - worker.userChunk(msg.results, handle, msg.file); - delete msg.results; - } - } - - if (msg.finished && !aborted) - completeWorker(msg.workerId, msg.results); - } - - function completeWorker(workerId, results) { - var worker = workers[workerId]; - if (isFunction(worker.userComplete)) - worker.userComplete(results); - worker.terminate(); - delete workers[workerId]; - } - - function notImplemented() { - throw new Error('Not implemented.'); - } - - /** Callback when worker thread receives a message */ - function workerThreadReceivedMessage(e) - { - var msg = e.data; - - if (typeof Papa.WORKER_ID === 'undefined' && msg) - Papa.WORKER_ID = msg.workerId; - - if (typeof msg.input === 'string') - { - global.postMessage({ - workerId: Papa.WORKER_ID, - results: Papa.parse(msg.input, msg.config), - finished: true - }); - } - else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106) - { - var results = Papa.parse(msg.input, msg.config); - if (results) - global.postMessage({ - workerId: Papa.WORKER_ID, - results: results, - finished: true - }); - } - } - - /** Makes a deep copy of an array or object (mostly) */ - function copy(obj) - { - if (typeof obj !== 'object' || obj === null) - return obj; - var cpy = Array.isArray(obj) ? [] : {}; - for (var key in obj) - cpy[key] = copy(obj[key]); - return cpy; - } - - function bindFunction(f, self) - { - return function() { f.apply(self, arguments); }; - } - - function isFunction(func) - { - return typeof func === 'function'; - } - - return Papa; -})); - - /***/ }), /***/ 8551: @@ -41524,9 +39598,6 @@ var v2 = __nccwpck_require__(7463); var v2_default = /*#__PURE__*/__nccwpck_require__.n(v2); // EXTERNAL MODULE: ./node_modules/convert-csv-to-json/index.js var convert_csv_to_json = __nccwpck_require__(224); -// EXTERNAL MODULE: ./node_modules/papaparse/papaparse.js -var papaparse = __nccwpck_require__(877); -var papaparse_default = /*#__PURE__*/__nccwpck_require__.n(papaparse); // EXTERNAL MODULE: ./src/isFileExists.ts var isFileExists = __nccwpck_require__(2139); ;// CONCATENATED MODULE: ./src/report_chart.ts @@ -41540,7 +39611,6 @@ const chartReport = Buffer.from('PCEtLSByZXBvcnQtYWN0aW9uIC0tPgo8IWRvY3R5cGUgaHR - const csvExt = '.csv'; const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const dataFile = external_path_.join(reportBaseDir, 'data.json'); @@ -41558,25 +39628,14 @@ const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const filesContent = []; if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await v2_default()().fromFile(sourceReportDir); - const json2 = convert_csv_to_json.parseSubArray('*', ',').getJsonFromCsv(sourceReportDir); - const json3 = await new Promise((resolve) => papaparse_default().parse(sourceReportDir, { - delimiter: ',', - complete(results) { - resolve(results); - }, - })); + const json2 = convert_csv_to_json.fieldDelimiter(',').getJsonFromCsv(sourceReportDir); const jsonStr = JSON.stringify(json); const jsonStr2 = JSON.stringify(json2); - const jsonStr3 = JSON.stringify(json3); console.log('jsonStr === jsonStr2', jsonStr === jsonStr2); - console.log('jsonStr === jsonStr3', jsonStr === jsonStr3); - console.log('jsonStr2 === jsonStr3', jsonStr2 === jsonStr3); console.log('-'.repeat(60)); console.log(jsonStr); console.log('^'.repeat(60)); console.log(jsonStr2); - console.log('^'.repeat(60)); - console.log(jsonStr3); console.log('-'.repeat(60)); filesContent.push({ name: external_path_.basename(sourceReportDir, external_path_.extname(sourceReportDir)), json }); } diff --git a/dist/licenses.txt b/dist/licenses.txt index 3d22c0e..8713385 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -1274,30 +1274,6 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -papaparse -MIT -The MIT License (MIT) - -Copyright (c) 2015 Matthew Holt - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - strip-bom MIT The MIT License (MIT) diff --git a/package-lock.json b/package-lock.json index dda4781..ce41786 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,13 +14,11 @@ "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", "convert-csv-to-json": "^2.46.0", - "csvtojson": "^2.0.10", - "papaparse": "^5.4.1" + "csvtojson": "^2.0.10" }, "devDependencies": { "@playwright/test": "^1.43.1", "@types/node": "^20.12.8", - "@types/papaparse": "^5.3.14", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@vercel/ncc": "^0.38.1", @@ -632,15 +630,6 @@ "undici-types": "~5.26.4" } }, - "node_modules/@types/papaparse": { - "version": "5.3.14", - "resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.3.14.tgz", - "integrity": "sha512-LxJ4iEFcpqc6METwp9f6BV6VVc43m6MfH0VqFosHvrUgfXiFe6ww7R3itkOQ+TCK6Y+Iv/+RnnvtRZnkc5Kc9g==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/semver": { "version": "7.5.8", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", @@ -4073,11 +4062,6 @@ "node": ">= 14" } }, - "node_modules/papaparse": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.4.1.tgz", - "integrity": "sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw==" - }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", diff --git a/package.json b/package.json index baca91c..ae5632c 100644 --- a/package.json +++ b/package.json @@ -36,13 +36,11 @@ "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", "convert-csv-to-json": "^2.46.0", - "csvtojson": "^2.0.10", - "papaparse": "^5.4.1" + "csvtojson": "^2.0.10" }, "devDependencies": { "@playwright/test": "^1.43.1", "@types/node": "^20.12.8", - "@types/papaparse": "^5.3.14", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@vercel/ncc": "^0.38.1", diff --git a/src/csvReport.ts b/src/csvReport.ts index 309aaaf..b00d27f 100644 --- a/src/csvReport.ts +++ b/src/csvReport.ts @@ -2,7 +2,6 @@ import * as fs from 'fs/promises' import * as path from 'path' import csvtojson from 'csvtojson' import csvToJson from 'convert-csv-to-json' -import Papa from 'papaparse' import { isFileExist } from './isFileExists.js' import { chartReport } from './report_chart.js' @@ -30,29 +29,17 @@ export const csvReport = async ( const filesContent: Array<{ name: string; json: Array> }> = [] if (sourceReportDir.toLowerCase().endsWith(csvExt)) { const json = await csvtojson().fromFile(sourceReportDir) - const json2 = csvToJson.parseSubArray('*', ',').getJsonFromCsv(sourceReportDir) - const json3 = await new Promise((resolve) => - Papa.parse(sourceReportDir, { - delimiter: ',', - complete(results) { - resolve(results) - }, - }) - ) + const json2 = csvToJson.fieldDelimiter(',').getJsonFromCsv(sourceReportDir) + const jsonStr = JSON.stringify(json) const jsonStr2 = JSON.stringify(json2) - const jsonStr3 = JSON.stringify(json3) console.log('jsonStr === jsonStr2', jsonStr === jsonStr2) - console.log('jsonStr === jsonStr3', jsonStr === jsonStr3) - console.log('jsonStr2 === jsonStr3', jsonStr2 === jsonStr3) console.log('-'.repeat(60)) console.log(jsonStr) console.log('^'.repeat(60)) console.log(jsonStr2) - console.log('^'.repeat(60)) - console.log(jsonStr3) console.log('-'.repeat(60)) filesContent.push({ name: path.basename(sourceReportDir, path.extname(sourceReportDir)), json }) From b5998947713feeb5f4bcc31edf28f32a9c4224dd Mon Sep 17 00:00:00 2001 From: Mykola Grybyk Date: Sun, 5 May 2024 23:40:01 +0200 Subject: [PATCH 4/4] remove csvtojson --- dist/index.js | 10069 ++------------------------------------------ dist/licenses.txt | 125 - package-lock.json | 43 +- package.json | 3 +- src/csvReport.ts | 18 +- 5 files changed, 393 insertions(+), 9865 deletions(-) diff --git a/dist/index.js b/dist/index.js index 5d448f4..29522b0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -6431,9785 +6431,527 @@ function removeHook(state, name, method) { /***/ }), -/***/ 5490: -/***/ ((module) => { +/***/ 224: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -function any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} -Promise.any = function (promises) { - return any(promises); -}; +let csvToJson = __nccwpck_require__(8717); -Promise.prototype.any = function () { - return any(this); +const encodingOps = { + utf8: 'utf8', + ucs2: 'ucs2', + utf16le: 'utf16le', + latin1: 'latin1', + ascii: 'ascii', + base64: 'base64', + hex: 'hex' }; +/** + * Prints a digit as Number type (for example 32 instead of '32') + */ +exports.formatValueByType = function (active = true) { + csvToJson.formatValueByType(active); + return this; }; - -/***/ }), - -/***/ 8061: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = __nccwpck_require__(6203); -var Queue = __nccwpck_require__(878); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; +/** + * If enabled, allows fields wrapped by quotation marks to be parsed correctly and not splitted + */ +exports.supportQuotedField = function (active = false) { + csvToJson.supportQuotedField(active); + return this; }; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; +/** + * Defines the field delimiter which will be used to split the fields + */ +exports.fieldDelimiter = function (delimiter) { + csvToJson.fieldDelimiter(delimiter); + return this; }; -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; +/** + * Defines the index where the header is defined + */ +exports.indexHeader = function (index) { + csvToJson.indexHeader(index); + return this; }; - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); - } +/** + * Defines how to match and parse a sub array + */ +exports.parseSubArray = function (delimiter, separator) { + csvToJson.parseSubArray(delimiter, separator); + return this; }; -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } +/** + * Defines a custom encoding to decode a file + */ +exports.customEncoding = function (encoding) { + csvToJson.encoding = encoding; + return this; }; -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} - -Async.prototype.invokeLater = AsyncInvokeLater; -Async.prototype.invoke = AsyncInvoke; -Async.prototype.settlePromises = AsyncSettlePromises; - - -function _drainQueue(queue) { - while (queue.length() > 0) { - _drainQueueStep(queue); - } -} - -function _drainQueueStep(queue) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - } else { - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -} - -Async.prototype._drainQueues = function () { - _drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - _drainQueue(this._lateQueue); +/** + * Defines a custom encoding to decode a file + */ +exports.utf8Encoding = function utf8Encoding() { + csvToJson.encoding = encodingOps.utf8; + return this; }; -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } +/** + * Defines ucs2 encoding to decode a file + */ +exports.ucs2Encoding = function () { + csvToJson.encoding = encodingOps.ucs2; + return this; }; -Async.prototype._reset = function () { - this._isTickUsed = false; +/** + * Defines utf16le encoding to decode a file + */ +exports.utf16leEncoding = function () { + csvToJson.encoding = encodingOps.utf16le; + return this; }; -module.exports = Async; -module.exports.firstLineError = firstLineError; - - -/***/ }), - -/***/ 3767: -/***/ ((module) => { - - -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); +/** + * Defines latin1 encoding to decode a file + */ +exports.latin1Encoding = function () { + csvToJson.encoding = encodingOps.latin1; + return this; }; -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +/** + * Defines ascii encoding to decode a file + */ +exports.asciiEncoding = function () { + csvToJson.encoding = encodingOps.ascii; + return this; }; -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } +/** + * Defines base64 encoding to decode a file + */ +exports.base64Encoding = function () { + this.csvToJson = encodingOps.base64; + return this; }; -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); +/** + * Defines hex encoding to decode a file + */ +exports.hexEncoding = function () { + this.csvToJson = encodingOps.hex; + return this; }; -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; +/** + * Parses .csv file and put its content into a file in json format. + * @param {inputFileName} path/filename + * @param {outputFileName} path/filename + * + */ +exports.generateJsonFileFromCsv = function(inputFileName, outputFileName) { + if (!inputFileName) { + throw new Error("inputFileName is not defined!!!"); + } + if (!outputFileName) { + throw new Error("outputFileName is not defined!!!"); + } + csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); }; -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } +/** + * Parses .csv file and put its content into an Array of Object in json format. + * @param {inputFileName} path/filename + * @return {Array} Array of Object in json format + * + */ +exports.getJsonFromCsv = function(inputFileName) { + if (!inputFileName) { + throw new Error("inputFileName is not defined!!!"); + } + return csvToJson.getJsonFromCsv(inputFileName); }; -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; +exports.csvStringToJson = function(csvString) { + return csvToJson.csvStringToJson(csvString); }; -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; +/** + * Parses .csv file and put its content into a file in json format. + * @param {inputFileName} path/filename + * @param {outputFileName} path/filename + * + * @deprecated Use generateJsonFileFromCsv() + */ +exports.jsonToCsv = function(inputFileName, outputFileName) { + csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); }; /***/ }), -/***/ 8710: +/***/ 8717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = __nccwpck_require__(3694)(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - - -/***/ }), - -/***/ 924: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = __nccwpck_require__(7448); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (true) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; +let fileUtils = __nccwpck_require__(6114); +let stringUtils = __nccwpck_require__(6494); +let jsonUtils = __nccwpck_require__(4166); -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; +const newLine = /\r?\n/; +const defaultFieldDelimiter = ";"; -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; +class CsvToJson { -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; + formatValueByType(active) { + this.printValueFormatByType = active; + return this; + } -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} + supportQuotedField(active) { + this.isSupportQuotedField = active; + return this; + } -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} + fieldDelimiter(delimiter) { + this.delimiter = delimiter; + return this; + } -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - if (true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } + indexHeader(indexHeader) { + if(isNaN(indexHeader)){ + throw new Error('The index Header must be a Number!'); } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; + this.indexHeader = indexHeader; + return this; + } -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; + parseSubArray(delimiter = '*',separator = ',') { + this.parseSubArrayDelimiter = delimiter; + this.parseSubArraySeparator = separator; + } -/***/ }), + encoding(encoding){ + this.encoding = encoding; + return this; + } -/***/ 6616: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + generateJsonFileFromCsv(fileInputName, fileOutputName) { + let jsonStringified = this.getJsonFromCsvStringified(fileInputName); + fileUtils.writeFile(jsonStringified, fileOutputName); + } + getJsonFromCsvStringified(fileInputName) { + let json = this.getJsonFromCsv(fileInputName); + let jsonStringified = JSON.stringify(json, undefined, 1); + jsonUtils.validateJson(jsonStringified); + return jsonStringified; + } -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = __nccwpck_require__(7448); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; + getJsonFromCsv(fileInputName) { + let parsedCsv = fileUtils.readFile(fileInputName, this.encoding); + return this.csvToJson(parsedCsv); + } -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); + csvStringToJson(csvString) { + return this.csvToJson(csvString); + } - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; + csvToJson(parsedCsv) { + this.validateInputConfig(); + let lines = parsedCsv.split(newLine); + let fieldDelimiter = this.getFieldDelimiter(); + let index = this.getIndexHeader(); + let headers; + + if(this.isSupportQuotedField){ + headers = this.split(lines[index]); } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - - -/***/ }), - -/***/ 8985: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(NEXT_FILTER) { -var util = __nccwpck_require__(7448); -var getKeys = (__nccwpck_require__(3062).keys); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - - -/***/ }), - -/***/ 5422: -/***/ ((module) => { - - -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - - -/***/ }), - -/***/ 6004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, Context, - enableAsyncHooks, disableAsyncHooks) { -var async = Promise._async; -var Warning = (__nccwpck_require__(5816).Warning); -var util = __nccwpck_require__(7448); -var es5 = __nccwpck_require__(3062); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - ( false || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -var deferUnhandledRejectionCheck; -(function() { - var promises = []; - - function unhandledRejectionCheck() { - for (var i = 0; i < promises.length; ++i) { - promises[i]._notifyUnhandledRejection(); - } - unhandledRejectionClear(); - } - - function unhandledRejectionClear() { - promises.length = 0; - } - - deferUnhandledRejectionCheck = function(promise) { - promises.push(promise); - setTimeout(unhandledRejectionCheck, 1); - }; - - es5.defineProperty(Promise, "_unhandledRejectionCheck", { - value: unhandledRejectionCheck - }); - es5.defineProperty(Promise, "_unhandledRejectionClear", { - value: unhandledRejectionClear - }); -})(); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - deferUnhandledRejectionCheck(this); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var context = Promise._getContext(); - possiblyUnhandledRejection = util.contextBind(context, fn); -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var context = Promise._getContext(); - unhandledRejectionHandled = util.contextBind(context, fn); -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; - Context.deactivateLongStackTraces(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; - Context.activateLongStackTraces(); + headers = lines[index].split(fieldDelimiter); } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - - -var legacyHandlers = { - unhandledrejection: { - before: function() { - var ret = util.global.onunhandledrejection; - util.global.onunhandledrejection = null; - return ret; - }, - after: function(fn) { - util.global.onunhandledrejection = fn; - } - }, - rejectionhandled: { - before: function() { - var ret = util.global.onrejectionhandled; - util.global.onrejectionhandled = null; - return ret; - }, - after: function(fn) { - util.global.onrejectionhandled = fn; - } + + while(!stringUtils.hasContent(headers) && index <= lines.length){ + index = index + 1; + headers = lines[index].split(fieldDelimiter); } -}; -var fireDomEvent = (function() { - var dispatch = function(legacy, e) { - if (legacy) { - var fn; - try { - fn = legacy.before(); - return !util.global.dispatchEvent(e); - } finally { - legacy.after(fn); - } - } else { - return !util.global.dispatchEvent(e); + let jsonResult = []; + for (let i = (index + 1); i < lines.length; i++) { + let currentLine; + if(this.isSupportQuotedField){ + currentLine = this.split(lines[i]); } - }; - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var eventData = { - detail: event, - cancelable: true - }; - var domEvent = new CustomEvent(name, eventData); - es5.defineProperty( - domEvent, "promise", {value: event.promise}); - es5.defineProperty( - domEvent, "reason", {value: event.reason}); - - return dispatch(legacyHandlers[name], domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = new Event(name, { - cancelable: true - }); - domEvent.detail = event; - es5.defineProperty(domEvent, "promise", {value: event.promise}); - es5.defineProperty(domEvent, "reason", {value: event.reason}); - return dispatch(legacyHandlers[name], domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name, false, true, - event); - return dispatch(legacyHandlers[name], domEvent); - }; + else{ + currentLine = lines[i].split(fieldDelimiter); } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; + if (stringUtils.hasContent(currentLine)) { + jsonResult.push(this.buildJsonResult(headers, currentLine)); } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; + } + return jsonResult; + } -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; + getFieldDelimiter() { + if (this.delimiter) { + return this.delimiter; } + return defaultFieldDelimiter; + } - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; + getIndexHeader(){ + if(this.indexHeader !== null && !isNaN(this.indexHeader)){ + return this.indexHeader; } + return 0; + } - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; + buildJsonResult(headers, currentLine) { + let jsonObject = {}; + for (let j = 0; j < headers.length; j++) { + let propertyName = stringUtils.trimPropertyName(headers[j]); + let value = currentLine[j]; - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { - var prev = config.asyncHooks; - var cur = !!opts.asyncHooks; - if (prev !== cur) { - config.asyncHooks = cur; - if (cur) { - enableAsyncHooks(); - } else { - disableAsyncHooks(); - } - } - } - return Promise; -}; + if(this.isParseSubArray(value)){ + value = this.buildJsonSubArray(value); + } -function defaultFireEvent() { return false; } + if (this.printValueFormatByType && !Array.isArray(value)) { + value = stringUtils.getValueFormatByType(currentLine[j]); + } -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; + jsonObject[propertyName] = value; } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._dereferenceTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; + return jsonObject; + } -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function longStackTracesDereferenceTrace() { - this._trace = undefined; -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = (firstLineError.stack || "").split("\n"); - var lastStackLines = (lastLineError.stack || "").split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false, - asyncHooks: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - asyncHooks: function() { - return config.asyncHooks; - }, - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - - -/***/ }), - -/***/ 8277: -/***/ ((module) => { - - -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - - -/***/ }), - -/***/ 838: -/***/ ((module) => { - - -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - - - -/***/ }), - -/***/ 5816: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var es5 = __nccwpck_require__(3062); -var Objectfreeze = es5.freeze; -var util = __nccwpck_require__(7448); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - - -/***/ }), - -/***/ 3062: -/***/ ((module) => { - -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - - -/***/ }), - -/***/ 2223: -/***/ ((module) => { - - -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - - -/***/ }), - -/***/ 7304: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = __nccwpck_require__(7448); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = __nccwpck_require__(8985)(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - - -/***/ }), - -/***/ 8619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = __nccwpck_require__(5816); -var TypeError = errors.TypeError; -var util = __nccwpck_require__(7448); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - - -/***/ }), - -/***/ 5248: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { -var util = __nccwpck_require__(7448); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (true) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var context = Promise._getContext(); - holder.fn = util.contextBind(context, holder.fn); - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i ];}; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - - -/***/ }), - -/***/ 8150: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var util = __nccwpck_require__(7448); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var context = Promise._getContext(); - this._callback = util.contextBind(context, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); - if (util.isArray(promises)) { - for (var i = 0; i < promises.length; ++i) { - var maybePromise = promises[i]; - if (maybePromise instanceof Promise) { - maybePromise.suppressUnhandledRejections(); - } - } - } -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - - -/***/ }), - -/***/ 7415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = __nccwpck_require__(7448); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - - -/***/ }), - -/***/ 4315: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var util = __nccwpck_require__(7448); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = __nccwpck_require__(5816); -var OperationalError = errors.OperationalError; -var es5 = __nccwpck_require__(3062); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - - -/***/ }), - -/***/ 5447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise) { -var util = __nccwpck_require__(7448); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - - -/***/ }), - -/***/ 3694: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = __nccwpck_require__(7448); -util.setReflectHandler(reflectHandler); - -var getDomain = function() { - var domain = process.domain; - if (domain === undefined) { - return null; - } - return domain; -}; -var getContextDefault = function() { - return null; -}; -var getContextDomain = function() { - return { - domain: getDomain(), - async: null - }; -}; -var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? - (__nccwpck_require__(852).AsyncResource) : null; -var getContextAsyncHooks = function() { - return { - domain: getDomain(), - async: new AsyncResource("Bluebird::Promise") - }; -}; -var getContext = util.isNode ? getContextDomain : getContextDefault; -util.notEnumerableProp(Promise, "_getContext", getContext); -var enableAsyncHooks = function() { - getContext = getContextAsyncHooks; - util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); -}; -var disableAsyncHooks = function() { - getContext = getContextDomain; - util.notEnumerableProp(Promise, "_getContext", getContextDomain); -}; - -var es5 = __nccwpck_require__(3062); -var Async = __nccwpck_require__(8061); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = __nccwpck_require__(5816); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = __nccwpck_require__(9787)(Promise, INTERNAL); -var PromiseArray = - __nccwpck_require__(5307)(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = __nccwpck_require__(5422)(Promise); - /*jshint unused:false*/ -var createContext = Context.create; - -var debug = __nccwpck_require__(6004)(Promise, Context, - enableAsyncHooks, disableAsyncHooks); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - __nccwpck_require__(7304)(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = __nccwpck_require__(8985)(NEXT_FILTER); -var nodebackForPromise = __nccwpck_require__(4315); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - - if (typeof fn !== "function") { - throw new TypeError("The last argument to .catch() " + - "must be a function, got " + util.toString(fn)); - } - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var context = getContext(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: util.contextBind(context, handler), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, - receiver, context); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - var bitField = this._bitField; - this._bitField = bitField | - (((bitField & 536870912) >> 2) ^ - 134217728); -}; - -Promise.prototype._setNoAsyncGuarantee = function() { - this._bitField = (this._bitField | 536870912) & - (~134217728); -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - context -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = util.contextBind(context, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = util.contextBind(context, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - util.contextBind(context, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - util.contextBind(context, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(maybePromise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - this._dereferenceTrace(); - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -if (typeof Symbol !== "undefined" && Symbol.toStringTag) { - es5.defineProperty(Promise.prototype, Symbol.toStringTag, { - get: function () { - return "Object"; - } - }); -} - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -__nccwpck_require__(7415)(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -__nccwpck_require__(3767)(Promise, INTERNAL, tryConvertToPromise, debug); -__nccwpck_require__(6616)(Promise, PromiseArray, apiRejection, debug); -__nccwpck_require__(8277)(Promise); -__nccwpck_require__(6653)(Promise); -__nccwpck_require__(5248)( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); -Promise.Promise = Promise; -Promise.version = "3.7.2"; -__nccwpck_require__(924)(Promise); -__nccwpck_require__(8619)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -__nccwpck_require__(8150)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(5447)(Promise); -__nccwpck_require__(3047)(Promise, INTERNAL); -__nccwpck_require__(5261)(Promise, PromiseArray, tryConvertToPromise, apiRejection); -__nccwpck_require__(256)(Promise, INTERNAL, tryConvertToPromise, apiRejection); -__nccwpck_require__(8959)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(6087)(Promise, PromiseArray, debug); -__nccwpck_require__(1156)(Promise, PromiseArray, apiRejection); -__nccwpck_require__(2114)(Promise, INTERNAL, debug); -__nccwpck_require__(880)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -__nccwpck_require__(5490)(Promise); -__nccwpck_require__(838)(Promise, INTERNAL); -__nccwpck_require__(2223)(Promise, INTERNAL); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - - -/***/ }), - -/***/ 5307: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = __nccwpck_require__(7448); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - values.suppressUnhandledRejections(); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - - -/***/ }), - -/***/ 3047: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = __nccwpck_require__(7448); -var nodebackForPromise = __nccwpck_require__(4315); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = (__nccwpck_require__(5816).TypeError); -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (true) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - - -/***/ }), - -/***/ 5261: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(7448); -var isObject = util.isObject; -var es5 = __nccwpck_require__(3062); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - - -/***/ }), - -/***/ 878: -/***/ ((module) => { - - -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; - -module.exports = Queue; - - -/***/ }), - -/***/ 256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(7448); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - - -/***/ }), - -/***/ 8959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var util = __nccwpck_require__(7448); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var context = Promise._getContext(); - this._fn = util.contextBind(context, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - for (var j = i; j < length; ++j) { - var maybePromise = values[j]; - if (maybePromise instanceof Promise) { - maybePromise.suppressUnhandledRejections(); - } - } - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - - if ((i & 127) === 0) { - value._setNoAsyncGuarantee(); - } - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - - -/***/ }), - -/***/ 6203: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var util = __nccwpck_require__(7448); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova)) && - ("classList" in document.documentElement)) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - - -/***/ }), - -/***/ 6087: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = __nccwpck_require__(7448); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.allSettled = function (promises) { - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - - -/***/ }), - -/***/ 1156: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = __nccwpck_require__(7448); -var RangeError = (__nccwpck_require__(5816).RangeError); -var AggregateError = (__nccwpck_require__(5816).AggregateError); -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - - -/***/ }), - -/***/ 6653: -/***/ ((module) => { - - -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - - -/***/ }), - -/***/ 9787: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, INTERNAL) { -var util = __nccwpck_require__(7448); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - - -/***/ }), - -/***/ 2114: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function(Promise, INTERNAL, debug) { -var util = __nccwpck_require__(7448); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - - -/***/ }), - -/***/ 880: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = __nccwpck_require__(7448); - var TypeError = (__nccwpck_require__(5816).TypeError); - var inherits = (__nccwpck_require__(7448).inherits); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; - - -/***/ }), - -/***/ 7448: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - - -var es5 = __nccwpck_require__(3062); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var receiver = new FakeConstructor(); - function ic() { - return typeof receiver.foo; - } - ic(); - ic(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); -} - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if (classString(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -var reflectHandler; -function contextBind(ctx, cb) { - if (ctx === null || - typeof cb !== "function" || - cb === reflectHandler) { - return cb; - } - - if (ctx.domain !== null) { - cb = ctx.domain.bind(cb); - } - - var async = ctx.async; - if (async !== null) { - var old = cb; - cb = function() { - var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];}; - args[0] = old; - args[1] = this; - return async.runInAsyncScope.apply(async, args); - }; - } - return cb; -} - -var ret = { - setReflectHandler: function(fn) { - reflectHandler = fn; - }, - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - contextBind: contextBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version; - if (process.versions && process.versions.node) { - version = process.versions.node.split(".").map(Number); - } else if (process.version) { - version = process.version.split(".").map(Number); - } - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); -ret.nodeSupportsAsyncResource = ret.isNode && (function() { - var supportsAsync = false; - try { - var res = (__nccwpck_require__(852).AsyncResource); - supportsAsync = typeof res.prototype.runInAsyncScope === "function"; - } catch (e) { - supportsAsync = false; - } - return supportsAsync; -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - - -/***/ }), - -/***/ 224: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -let csvToJson = __nccwpck_require__(8717); - -const encodingOps = { - utf8: 'utf8', - ucs2: 'ucs2', - utf16le: 'utf16le', - latin1: 'latin1', - ascii: 'ascii', - base64: 'base64', - hex: 'hex' -}; - -/** - * Prints a digit as Number type (for example 32 instead of '32') - */ -exports.formatValueByType = function (active = true) { - csvToJson.formatValueByType(active); - return this; -}; - -/** - * If enabled, allows fields wrapped by quotation marks to be parsed correctly and not splitted - */ -exports.supportQuotedField = function (active = false) { - csvToJson.supportQuotedField(active); - return this; -}; -/** - * Defines the field delimiter which will be used to split the fields - */ -exports.fieldDelimiter = function (delimiter) { - csvToJson.fieldDelimiter(delimiter); - return this; -}; - -/** - * Defines the index where the header is defined - */ -exports.indexHeader = function (index) { - csvToJson.indexHeader(index); - return this; -}; - -/** - * Defines how to match and parse a sub array - */ -exports.parseSubArray = function (delimiter, separator) { - csvToJson.parseSubArray(delimiter, separator); - return this; -}; - -/** - * Defines a custom encoding to decode a file - */ -exports.customEncoding = function (encoding) { - csvToJson.encoding = encoding; - return this; -}; - -/** - * Defines a custom encoding to decode a file - */ -exports.utf8Encoding = function utf8Encoding() { - csvToJson.encoding = encodingOps.utf8; - return this; -}; - -/** - * Defines ucs2 encoding to decode a file - */ -exports.ucs2Encoding = function () { - csvToJson.encoding = encodingOps.ucs2; - return this; -}; - -/** - * Defines utf16le encoding to decode a file - */ -exports.utf16leEncoding = function () { - csvToJson.encoding = encodingOps.utf16le; - return this; -}; - -/** - * Defines latin1 encoding to decode a file - */ -exports.latin1Encoding = function () { - csvToJson.encoding = encodingOps.latin1; - return this; -}; - -/** - * Defines ascii encoding to decode a file - */ -exports.asciiEncoding = function () { - csvToJson.encoding = encodingOps.ascii; - return this; -}; - -/** - * Defines base64 encoding to decode a file - */ -exports.base64Encoding = function () { - this.csvToJson = encodingOps.base64; - return this; -}; - -/** - * Defines hex encoding to decode a file - */ -exports.hexEncoding = function () { - this.csvToJson = encodingOps.hex; - return this; -}; - -/** - * Parses .csv file and put its content into a file in json format. - * @param {inputFileName} path/filename - * @param {outputFileName} path/filename - * - */ -exports.generateJsonFileFromCsv = function(inputFileName, outputFileName) { - if (!inputFileName) { - throw new Error("inputFileName is not defined!!!"); - } - if (!outputFileName) { - throw new Error("outputFileName is not defined!!!"); - } - csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); -}; - -/** - * Parses .csv file and put its content into an Array of Object in json format. - * @param {inputFileName} path/filename - * @return {Array} Array of Object in json format - * - */ -exports.getJsonFromCsv = function(inputFileName) { - if (!inputFileName) { - throw new Error("inputFileName is not defined!!!"); - } - return csvToJson.getJsonFromCsv(inputFileName); -}; - -exports.csvStringToJson = function(csvString) { - return csvToJson.csvStringToJson(csvString); -}; - -/** - * Parses .csv file and put its content into a file in json format. - * @param {inputFileName} path/filename - * @param {outputFileName} path/filename - * - * @deprecated Use generateJsonFileFromCsv() - */ -exports.jsonToCsv = function(inputFileName, outputFileName) { - csvToJson.generateJsonFileFromCsv(inputFileName, outputFileName); -}; - - -/***/ }), - -/***/ 8717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -let fileUtils = __nccwpck_require__(6114); -let stringUtils = __nccwpck_require__(6494); -let jsonUtils = __nccwpck_require__(4166); - -const newLine = /\r?\n/; -const defaultFieldDelimiter = ";"; - -class CsvToJson { - - formatValueByType(active) { - this.printValueFormatByType = active; - return this; - } - - supportQuotedField(active) { - this.isSupportQuotedField = active; - return this; - } - - fieldDelimiter(delimiter) { - this.delimiter = delimiter; - return this; - } - - indexHeader(indexHeader) { - if(isNaN(indexHeader)){ - throw new Error('The index Header must be a Number!'); - } - this.indexHeader = indexHeader; - return this; - } - - - parseSubArray(delimiter = '*',separator = ',') { - this.parseSubArrayDelimiter = delimiter; - this.parseSubArraySeparator = separator; - } - - encoding(encoding){ - this.encoding = encoding; - return this; - } - - generateJsonFileFromCsv(fileInputName, fileOutputName) { - let jsonStringified = this.getJsonFromCsvStringified(fileInputName); - fileUtils.writeFile(jsonStringified, fileOutputName); - } - - getJsonFromCsvStringified(fileInputName) { - let json = this.getJsonFromCsv(fileInputName); - let jsonStringified = JSON.stringify(json, undefined, 1); - jsonUtils.validateJson(jsonStringified); - return jsonStringified; - } - - getJsonFromCsv(fileInputName) { - let parsedCsv = fileUtils.readFile(fileInputName, this.encoding); - return this.csvToJson(parsedCsv); - } - - csvStringToJson(csvString) { - return this.csvToJson(csvString); - } - - csvToJson(parsedCsv) { - this.validateInputConfig(); - let lines = parsedCsv.split(newLine); - let fieldDelimiter = this.getFieldDelimiter(); - let index = this.getIndexHeader(); - let headers; - - if(this.isSupportQuotedField){ - headers = this.split(lines[index]); - } else { - headers = lines[index].split(fieldDelimiter); - } - - while(!stringUtils.hasContent(headers) && index <= lines.length){ - index = index + 1; - headers = lines[index].split(fieldDelimiter); - } - - let jsonResult = []; - for (let i = (index + 1); i < lines.length; i++) { - let currentLine; - if(this.isSupportQuotedField){ - currentLine = this.split(lines[i]); - } - else{ - currentLine = lines[i].split(fieldDelimiter); - } - if (stringUtils.hasContent(currentLine)) { - jsonResult.push(this.buildJsonResult(headers, currentLine)); - } - } - return jsonResult; - } - - getFieldDelimiter() { - if (this.delimiter) { - return this.delimiter; - } - return defaultFieldDelimiter; - } - - getIndexHeader(){ - if(this.indexHeader !== null && !isNaN(this.indexHeader)){ - return this.indexHeader; - } - return 0; - } - - buildJsonResult(headers, currentLine) { - let jsonObject = {}; - for (let j = 0; j < headers.length; j++) { - let propertyName = stringUtils.trimPropertyName(headers[j]); - let value = currentLine[j]; - - if(this.isParseSubArray(value)){ - value = this.buildJsonSubArray(value); - } - - if (this.printValueFormatByType && !Array.isArray(value)) { - value = stringUtils.getValueFormatByType(currentLine[j]); - } - - jsonObject[propertyName] = value; - } - return jsonObject; - } - - buildJsonSubArray(value) { - let extractedValues = value.substring( - value.indexOf(this.parseSubArrayDelimiter) + 1, - value.lastIndexOf(this.parseSubArrayDelimiter) - ); - extractedValues.trim(); - value = extractedValues.split(this.parseSubArraySeparator); - if(this.printValueFormatByType){ - for(let i=0; i < value.length; i++){ - value[i] = stringUtils.getValueFormatByType(value[i]); - } - } - return value; - } - - isParseSubArray(value){ - if(this.parseSubArrayDelimiter){ - if (value && (value.indexOf(this.parseSubArrayDelimiter) === 0 && value.lastIndexOf(this.parseSubArrayDelimiter) === (value.length - 1))) { - return true; - } - } - return false; - } - - validateInputConfig(){ - if(this.isSupportQuotedField) { - if(this.getFieldDelimiter() === '"'){ - throw new Error('When SupportQuotedFields is enabled you cannot defined the field delimiter as quote -> ["]'); - } - if(this.parseSubArraySeparator === '"'){ - throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArraySeparator as quote -> ["]'); - } - if(this.parseSubArrayDelimiter === '"'){ - throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArrayDelimiter as quote -> ["]'); - } - } - } - - hasQuotes(line) { - return line.includes('"'); - } - - split(line) { - if(line.length == 0){ - return []; - } - let delim = this.getFieldDelimiter(); - let subSplits = ['']; - if (this.hasQuotes(line)) { - let chars = line.split(''); - - let subIndex = 0; - let startQuote = false; - let isDouble = false; - chars.forEach((c, i, arr) => { - if (isDouble) { //when run into double just pop it into current and move on - subSplits[subIndex] += c; - isDouble = false; - return; - } - - if (c != '"' && c != delim ) { - subSplits[subIndex] += c; - } else if(c == delim && startQuote){ - subSplits[subIndex] += c; - } else if( c == delim ){ - subIndex++ - subSplits[subIndex] = ''; - return; - } else { - if (arr[i + 1] === '"') { - //Double quote - isDouble = true; - //subSplits[subIndex] += c; //Skip because this is escaped quote - } else { - if (!startQuote) { - startQuote = true; - //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value - } else { - //end - startQuote = false; - //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value - } - } - } - }); - if(startQuote){ - throw new Error('Row contains mismatched quotes!'); - } - return subSplits; - } else { - return line.split(delim); - } - } -} - -module.exports = new CsvToJson(); - - -/***/ }), - -/***/ 6114: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -let fs = __nccwpck_require__(7147); - -class FileUtils { - - readFile(fileInputName, encoding) { - return fs.readFileSync(fileInputName, encoding).toString(); - } - - writeFile(json, fileOutputName) { - fs.writeFile(fileOutputName, json, function (err) { - if (err) { - throw err; - } else { - console.log('File saved: ' + fileOutputName); - } - }); - } - -} -module.exports = new FileUtils(); - - -/***/ }), - -/***/ 4166: -/***/ ((module) => { - - - -class JsonUtil { - - validateJson(json) { - try { - JSON.parse(json); - } catch (err) { - throw Error('Parsed csv has generated an invalid json!!!\n' + err); - } - } - -} - -module.exports = new JsonUtil(); - -/***/ }), - -/***/ 6494: -/***/ ((module) => { - - - -class StringUtils { - - trimPropertyName(value) { - return value.replace(/\s/g, ''); - } - - getValueFormatByType(value) { - if(value === undefined || value === ''){ - return String(); - } - //is Number - let isNumber = !isNaN(value); - if (isNumber) { - return Number(value); - } - // is Boolean - if(value === "true" || value === "false"){ - return JSON.parse(value.toLowerCase()); - } - return String(value); - } - - hasContent(values) { - if (values.length > 0) { - for (let i = 0; i < values.length; i++) { - if (values[i]) { - return true; - } - } - } - return false; - } -} - -module.exports = new StringUtils(); - - -/***/ }), - -/***/ 1356: -/***/ (function(__unused_webpack_module, exports) { - - -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var CSVError = /** @class */ (function (_super) { - __extends(CSVError, _super); - function CSVError(err, line, extra) { - var _this = _super.call(this, "Error: " + err + ". JSON Line number: " + line + (extra ? " near: " + extra : "")) || this; - _this.err = err; - _this.line = line; - _this.extra = extra; - _this.name = "CSV Parse Error"; - return _this; - } - CSVError.column_mismatched = function (index, extra) { - return new CSVError("column_mismatched", index, extra); - }; - CSVError.unclosed_quote = function (index, extra) { - return new CSVError("unclosed_quote", index, extra); - }; - CSVError.fromJSON = function (obj) { - return new CSVError(obj.err, obj.line, obj.extra); - }; - CSVError.prototype.toJSON = function () { - return { - err: this.err, - line: this.line, - extra: this.extra - }; - }; - return CSVError; -}(Error)); -exports["default"] = CSVError; -//# sourceMappingURL=CSVError.js.map - -/***/ }), - -/***/ 6991: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var stream_1 = __nccwpck_require__(2781); -var Parameters_1 = __nccwpck_require__(4708); -var ParseRuntime_1 = __nccwpck_require__(3407); -var bluebird_1 = __importDefault(__nccwpck_require__(8710)); -// import { ProcessorFork } from "./ProcessFork"; -var ProcessorLocal_1 = __nccwpck_require__(148); -var Result_1 = __nccwpck_require__(5413); -var Converter = /** @class */ (function (_super) { - __extends(Converter, _super); - function Converter(param, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, options) || this; - _this.options = options; - _this.params = Parameters_1.mergeParams(param); - _this.runtime = ParseRuntime_1.initParseRuntime(_this); - _this.result = new Result_1.Result(_this); - // if (this.params.fork) { - // this.processor = new ProcessorFork(this); - // } else { - _this.processor = new ProcessorLocal_1.ProcessorLocal(_this); - // } - _this.once("error", function (err) { - // console.log("BBB"); - //wait for next cycle to emit the errors. - setImmediate(function () { - _this.result.processError(err); - _this.emit("done", err); - }); - }); - _this.once("done", function () { - _this.processor.destroy(); - }); - return _this; - } - Converter.prototype.preRawData = function (onRawData) { - this.runtime.preRawDataHook = onRawData; - return this; - }; - Converter.prototype.preFileLine = function (onFileLine) { - this.runtime.preFileLineHook = onFileLine; - return this; - }; - Converter.prototype.subscribe = function (onNext, onError, onCompleted) { - this.parseRuntime.subscribe = { - onNext: onNext, - onError: onError, - onCompleted: onCompleted - }; - return this; - }; - Converter.prototype.fromFile = function (filePath, options) { - var _this = this; - var fs = __nccwpck_require__(7147); - // var rs = null; - // this.wrapCallback(cb, function () { - // if (rs && rs.destroy) { - // rs.destroy(); - // } - // }); - fs.exists(filePath, function (exist) { - if (exist) { - var rs = fs.createReadStream(filePath, options); - rs.pipe(_this); - } - else { - _this.emit('error', new Error("File does not exist. Check to make sure the file path to your csv is correct.")); - } - }); - return this; - }; - Converter.prototype.fromStream = function (readStream) { - readStream.pipe(this); - return this; - }; - Converter.prototype.fromString = function (csvString) { - var csv = csvString.toString(); - var read = new stream_1.Readable(); - var idx = 0; - read._read = function (size) { - if (idx >= csvString.length) { - this.push(null); - } - else { - var str = csvString.substr(idx, size); - this.push(str); - idx += size; - } - }; - return this.fromStream(read); - }; - Converter.prototype.then = function (onfulfilled, onrejected) { - var _this = this; - return new bluebird_1.default(function (resolve, reject) { - _this.parseRuntime.then = { - onfulfilled: function (value) { - if (onfulfilled) { - resolve(onfulfilled(value)); - } - else { - resolve(value); - } - }, - onrejected: function (err) { - if (onrejected) { - resolve(onrejected(err)); - } - else { - reject(err); - } - } - }; - }); - }; - Object.defineProperty(Converter.prototype, "parseParam", { - get: function () { - return this.params; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Converter.prototype, "parseRuntime", { - get: function () { - return this.runtime; - }, - enumerable: true, - configurable: true - }); - Converter.prototype._transform = function (chunk, encoding, cb) { - var _this = this; - this.processor.process(chunk) - .then(function (result) { - // console.log(result); - if (result.length > 0) { - _this.runtime.started = true; - return _this.result.processResult(result); - } - }) - .then(function () { - _this.emit("drained"); - cb(); - }, function (error) { - _this.runtime.hasError = true; - _this.runtime.error = error; - _this.emit("error", error); - cb(); - }); - }; - Converter.prototype._flush = function (cb) { - var _this = this; - this.processor.flush() - .then(function (data) { - if (data.length > 0) { - return _this.result.processResult(data); - } - }) - .then(function () { - _this.processEnd(cb); - }, function (err) { - _this.emit("error", err); - cb(); - }); - }; - Converter.prototype.processEnd = function (cb) { - this.result.endProcess(); - this.emit("done"); - cb(); - }; - Object.defineProperty(Converter.prototype, "parsedLineNumber", { - get: function () { - return this.runtime.parsedLineNumber; - }, - enumerable: true, - configurable: true - }); - return Converter; -}(stream_1.Transform)); -exports.Converter = Converter; -//# sourceMappingURL=Converter.js.map - -/***/ }), - -/***/ 4708: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function mergeParams(params) { - var defaultParam = { - delimiter: ',', - ignoreColumns: undefined, - includeColumns: undefined, - quote: '"', - trim: true, - checkType: false, - ignoreEmpty: false, - // fork: false, - noheader: false, - headers: undefined, - flatKeys: false, - maxRowLength: 0, - checkColumn: false, - escape: '"', - colParser: {}, - eol: undefined, - alwaysSplitAtEOL: false, - output: "json", - nullObject: false, - downstreamFormat: "line", - needEmitAll: true - }; - if (!params) { - params = {}; - } - for (var key in params) { - if (params.hasOwnProperty(key)) { - if (Array.isArray(params[key])) { - defaultParam[key] = [].concat(params[key]); - } - else { - defaultParam[key] = params[key]; - } - } - } - return defaultParam; -} -exports.mergeParams = mergeParams; -//# sourceMappingURL=Parameters.js.map - -/***/ }), - -/***/ 3407: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function initParseRuntime(converter) { - var params = converter.parseParam; - var rtn = { - needProcessIgnoreColumn: false, - needProcessIncludeColumn: false, - selectedColumns: undefined, - ended: false, - hasError: false, - error: undefined, - delimiter: converter.parseParam.delimiter, - eol: converter.parseParam.eol, - columnConv: [], - headerType: [], - headerTitle: [], - headerFlag: [], - headers: undefined, - started: false, - parsedLineNumber: 0, - columnValueSetter: [], - }; - if (params.ignoreColumns) { - rtn.needProcessIgnoreColumn = true; - } - if (params.includeColumns) { - rtn.needProcessIncludeColumn = true; - } - return rtn; -} -exports.initParseRuntime = initParseRuntime; -//# sourceMappingURL=ParseRuntime.js.map - -/***/ }), - -/***/ 7337: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var Processor = /** @class */ (function () { - function Processor(converter) { - this.converter = converter; - this.params = converter.parseParam; - this.runtime = converter.parseRuntime; - } - return Processor; -}()); -exports.Processor = Processor; -//# sourceMappingURL=Processor.js.map - -/***/ }), - -/***/ 148: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var Processor_1 = __nccwpck_require__(7337); -var bluebird_1 = __importDefault(__nccwpck_require__(8710)); -var dataClean_1 = __nccwpck_require__(483); -var getEol_1 = __importDefault(__nccwpck_require__(5819)); -var fileline_1 = __nccwpck_require__(228); -var util_1 = __nccwpck_require__(6935); -var rowSplit_1 = __nccwpck_require__(5950); -var lineToJson_1 = __importDefault(__nccwpck_require__(9297)); -var CSVError_1 = __importDefault(__nccwpck_require__(1356)); -var ProcessorLocal = /** @class */ (function (_super) { - __extends(ProcessorLocal, _super); - function ProcessorLocal() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.rowSplit = new rowSplit_1.RowSplit(_this.converter); - _this.eolEmitted = false; - _this._needEmitEol = undefined; - _this.headEmitted = false; - _this._needEmitHead = undefined; - return _this; - } - ProcessorLocal.prototype.flush = function () { - var _this = this; - if (this.runtime.csvLineBuffer && this.runtime.csvLineBuffer.length > 0) { - var buf = this.runtime.csvLineBuffer; - this.runtime.csvLineBuffer = undefined; - return this.process(buf, true) - .then(function (res) { - if (_this.runtime.csvLineBuffer && _this.runtime.csvLineBuffer.length > 0) { - return bluebird_1.default.reject(CSVError_1.default.unclosed_quote(_this.runtime.parsedLineNumber, _this.runtime.csvLineBuffer.toString())); - } - else { - return bluebird_1.default.resolve(res); - } - }); - } - else { - return bluebird_1.default.resolve([]); - } - }; - ProcessorLocal.prototype.destroy = function () { - return bluebird_1.default.resolve(); - }; - Object.defineProperty(ProcessorLocal.prototype, "needEmitEol", { - get: function () { - if (this._needEmitEol === undefined) { - this._needEmitEol = this.converter.listeners("eol").length > 0; - } - return this._needEmitEol; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ProcessorLocal.prototype, "needEmitHead", { - get: function () { - if (this._needEmitHead === undefined) { - this._needEmitHead = this.converter.listeners("header").length > 0; - } - return this._needEmitHead; - }, - enumerable: true, - configurable: true - }); - ProcessorLocal.prototype.process = function (chunk, finalChunk) { - var _this = this; - if (finalChunk === void 0) { finalChunk = false; } - var csvString; - if (finalChunk) { - csvString = chunk.toString(); - } - else { - csvString = dataClean_1.prepareData(chunk, this.converter.parseRuntime); - } - return bluebird_1.default.resolve() - .then(function () { - if (_this.runtime.preRawDataHook) { - return _this.runtime.preRawDataHook(csvString); - } - else { - return csvString; - } - }) - .then(function (csv) { - if (csv && csv.length > 0) { - return _this.processCSV(csv, finalChunk); - } - else { - return bluebird_1.default.resolve([]); - } - }); - }; - ProcessorLocal.prototype.processCSV = function (csv, finalChunk) { - var _this = this; - var params = this.params; - var runtime = this.runtime; - if (!runtime.eol) { - getEol_1.default(csv, runtime); - } - if (this.needEmitEol && !this.eolEmitted && runtime.eol) { - this.converter.emit("eol", runtime.eol); - this.eolEmitted = true; - } - // trim csv file has initial blank lines. - if (params.ignoreEmpty && !runtime.started) { - csv = util_1.trimLeft(csv); - } - var stringToLineResult = fileline_1.stringToLines(csv, runtime); - if (!finalChunk) { - this.prependLeftBuf(util_1.bufFromString(stringToLineResult.partial)); - } - else { - stringToLineResult.lines.push(stringToLineResult.partial); - stringToLineResult.partial = ""; - } - if (stringToLineResult.lines.length > 0) { - var prom = void 0; - if (runtime.preFileLineHook) { - prom = this.runPreLineHook(stringToLineResult.lines); - } - else { - prom = bluebird_1.default.resolve(stringToLineResult.lines); - } - return prom.then(function (lines) { - if (!runtime.started - && !_this.runtime.headers) { - return _this.processDataWithHead(lines); - } - else { - return _this.processCSVBody(lines); - } - }); - } - else { - return bluebird_1.default.resolve([]); - } - }; - ProcessorLocal.prototype.processDataWithHead = function (lines) { - if (this.params.noheader) { - if (this.params.headers) { - this.runtime.headers = this.params.headers; - } - else { - this.runtime.headers = []; - } - } - else { - var left = ""; - var headerRow = []; - while (lines.length) { - var line = left + lines.shift(); - var row = this.rowSplit.parse(line); - if (row.closed) { - headerRow = row.cells; - left = ""; - break; - } - else { - left = line + getEol_1.default(line, this.runtime); - } - } - this.prependLeftBuf(util_1.bufFromString(left)); - if (headerRow.length === 0) { - return []; - } - if (this.params.headers) { - this.runtime.headers = this.params.headers; - } - else { - this.runtime.headers = headerRow; - } - } - if (this.runtime.needProcessIgnoreColumn || this.runtime.needProcessIncludeColumn) { - this.filterHeader(); - } - if (this.needEmitHead && !this.headEmitted) { - this.converter.emit("header", this.runtime.headers); - this.headEmitted = true; - } - return this.processCSVBody(lines); - }; - ProcessorLocal.prototype.filterHeader = function () { - this.runtime.selectedColumns = []; - if (this.runtime.headers) { - var headers = this.runtime.headers; - for (var i = 0; i < headers.length; i++) { - if (this.params.ignoreColumns) { - if (this.params.ignoreColumns.test(headers[i])) { - if (this.params.includeColumns && this.params.includeColumns.test(headers[i])) { - this.runtime.selectedColumns.push(i); - } - else { - continue; - } - } - else { - this.runtime.selectedColumns.push(i); - } - } - else if (this.params.includeColumns) { - if (this.params.includeColumns.test(headers[i])) { - this.runtime.selectedColumns.push(i); - } - } - else { - this.runtime.selectedColumns.push(i); - } - // if (this.params.includeColumns && this.params.includeColumns.test(headers[i])){ - // this.runtime.selectedColumns.push(i); - // }else{ - // if (this.params.ignoreColumns && this.params.ignoreColumns.test(headers[i])){ - // continue; - // }else{ - // if (this.params.ignoreColumns && !this.params.includeColumns){ - // this.runtime.selectedColumns.push(i); - // } - // } - // } - } - this.runtime.headers = util_1.filterArray(this.runtime.headers, this.runtime.selectedColumns); - } - }; - ProcessorLocal.prototype.processCSVBody = function (lines) { - if (this.params.output === "line") { - return lines; - } - else { - var result = this.rowSplit.parseMultiLines(lines); - this.prependLeftBuf(util_1.bufFromString(result.partial)); - if (this.params.output === "csv") { - return result.rowsCells; - } - else { - return lineToJson_1.default(result.rowsCells, this.converter); - } - } - // var jsonArr = linesToJson(lines.lines, params, this.recordNum); - // this.processResult(jsonArr); - // this.lastIndex += jsonArr.length; - // this.recordNum += jsonArr.length; - }; - ProcessorLocal.prototype.prependLeftBuf = function (buf) { - if (buf) { - if (this.runtime.csvLineBuffer) { - this.runtime.csvLineBuffer = Buffer.concat([buf, this.runtime.csvLineBuffer]); - } - else { - this.runtime.csvLineBuffer = buf; - } - } - }; - ProcessorLocal.prototype.runPreLineHook = function (lines) { - var _this = this; - return new bluebird_1.default(function (resolve, reject) { - processLineHook(lines, _this.runtime, 0, function (err) { - if (err) { - reject(err); - } - else { - resolve(lines); - } - }); - }); - }; - return ProcessorLocal; -}(Processor_1.Processor)); -exports.ProcessorLocal = ProcessorLocal; -function processLineHook(lines, runtime, offset, cb) { - if (offset >= lines.length) { - cb(); - } - else { - if (runtime.preFileLineHook) { - var line = lines[offset]; - var res = runtime.preFileLineHook(line, runtime.parsedLineNumber + offset); - offset++; - if (res && res.then) { - res.then(function (value) { - lines[offset - 1] = value; - processLineHook(lines, runtime, offset, cb); - }); - } - else { - lines[offset - 1] = res; - while (offset < lines.length) { - lines[offset] = runtime.preFileLineHook(lines[offset], runtime.parsedLineNumber + offset); - offset++; - } - cb(); - } - } - else { - cb(); - } - } -} -//# sourceMappingURL=ProcessorLocal.js.map - -/***/ }), - -/***/ 5413: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bluebird_1 = __importDefault(__nccwpck_require__(8710)); -var os_1 = __nccwpck_require__(2037); -var Result = /** @class */ (function () { - function Result(converter) { - this.converter = converter; - this.finalResult = []; - } - Object.defineProperty(Result.prototype, "needEmitLine", { - get: function () { - return !!this.converter.parseRuntime.subscribe && !!this.converter.parseRuntime.subscribe.onNext || this.needPushDownstream; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Result.prototype, "needPushDownstream", { - get: function () { - if (this._needPushDownstream === undefined) { - this._needPushDownstream = this.converter.listeners("data").length > 0 || this.converter.listeners("readable").length > 0; - } - return this._needPushDownstream; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Result.prototype, "needEmitAll", { - get: function () { - return !!this.converter.parseRuntime.then && this.converter.parseParam.needEmitAll; - // return !!this.converter.parseRuntime.then; - }, - enumerable: true, - configurable: true - }); - Result.prototype.processResult = function (resultLines) { - var _this = this; - var startPos = this.converter.parseRuntime.parsedLineNumber; - if (this.needPushDownstream && this.converter.parseParam.downstreamFormat === "array") { - if (startPos === 0) { - pushDownstream(this.converter, "[" + os_1.EOL); - } - } - // let prom: P; - return new bluebird_1.default(function (resolve, reject) { - if (_this.needEmitLine) { - processLineByLine(resultLines, _this.converter, 0, _this.needPushDownstream, function (err) { - if (err) { - reject(err); - } - else { - _this.appendFinalResult(resultLines); - resolve(); - } - }); - // resolve(); - } - else { - _this.appendFinalResult(resultLines); - resolve(); - } - }); - }; - Result.prototype.appendFinalResult = function (lines) { - if (this.needEmitAll) { - this.finalResult = this.finalResult.concat(lines); - } - this.converter.parseRuntime.parsedLineNumber += lines.length; - }; - Result.prototype.processError = function (err) { - if (this.converter.parseRuntime.subscribe && this.converter.parseRuntime.subscribe.onError) { - this.converter.parseRuntime.subscribe.onError(err); - } - if (this.converter.parseRuntime.then && this.converter.parseRuntime.then.onrejected) { - this.converter.parseRuntime.then.onrejected(err); - } - }; - Result.prototype.endProcess = function () { - if (this.converter.parseRuntime.then && this.converter.parseRuntime.then.onfulfilled) { - if (this.needEmitAll) { - this.converter.parseRuntime.then.onfulfilled(this.finalResult); - } - else { - this.converter.parseRuntime.then.onfulfilled([]); - } - } - if (this.converter.parseRuntime.subscribe && this.converter.parseRuntime.subscribe.onCompleted) { - this.converter.parseRuntime.subscribe.onCompleted(); - } - if (this.needPushDownstream && this.converter.parseParam.downstreamFormat === "array") { - pushDownstream(this.converter, "]" + os_1.EOL); - } - }; - return Result; -}()); -exports.Result = Result; -function processLineByLine(lines, conv, offset, needPushDownstream, cb) { - if (offset >= lines.length) { - cb(); - } - else { - if (conv.parseRuntime.subscribe && conv.parseRuntime.subscribe.onNext) { - var hook_1 = conv.parseRuntime.subscribe.onNext; - var nextLine_1 = lines[offset]; - var res = hook_1(nextLine_1, conv.parseRuntime.parsedLineNumber + offset); - offset++; - // if (isAsync === undefined) { - if (res && res.then) { - res.then(function () { - processRecursive(lines, hook_1, conv, offset, needPushDownstream, cb, nextLine_1); - }, cb); - } - else { - // processRecursive(lines, hook, conv, offset, needPushDownstream, cb, nextLine, false); - if (needPushDownstream) { - pushDownstream(conv, nextLine_1); - } - while (offset < lines.length) { - var line = lines[offset]; - hook_1(line, conv.parseRuntime.parsedLineNumber + offset); - offset++; - if (needPushDownstream) { - pushDownstream(conv, line); - } - } - cb(); - } - // } else if (isAsync === true) { - // (res as PromiseLike).then(function () { - // processRecursive(lines, hook, conv, offset, needPushDownstream, cb, nextLine, true); - // }, cb); - // } else if (isAsync === false) { - // processRecursive(lines, hook, conv, offset, needPushDownstream, cb, nextLine, false); - // } - } - else { - if (needPushDownstream) { - while (offset < lines.length) { - var line = lines[offset++]; - pushDownstream(conv, line); - } - } - cb(); - } - } -} -function processRecursive(lines, hook, conv, offset, needPushDownstream, cb, res) { - if (needPushDownstream) { - pushDownstream(conv, res); - } - processLineByLine(lines, conv, offset, needPushDownstream, cb); -} -function pushDownstream(conv, res) { - if (typeof res === "object" && !conv.options.objectMode) { - var data = JSON.stringify(res); - conv.push(data + (conv.parseParam.downstreamFormat === "array" ? "," + os_1.EOL : os_1.EOL), "utf8"); - } - else { - conv.push(res); - } -} -//# sourceMappingURL=Result.js.map - -/***/ }), - -/***/ 483: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var strip_bom_1 = __importDefault(__nccwpck_require__(8551)); -/** - * For each data chunk coming to parser: - * 1. append the data to the buffer that is left from last chunk - * 2. check if utf8 chars being split, if does, stripe the bytes and add to left buffer. - * 3. stripBom - */ -function prepareData(chunk, runtime) { - var workChunk = concatLeftChunk(chunk, runtime); - runtime.csvLineBuffer = undefined; - var cleanCSVString = cleanUtf8Split(workChunk, runtime).toString("utf8"); - if (runtime.started === false) { - return strip_bom_1.default(cleanCSVString); - } - else { - return cleanCSVString; - } -} -exports.prepareData = prepareData; -/** - * append data to buffer that is left form last chunk - */ -function concatLeftChunk(chunk, runtime) { - if (runtime.csvLineBuffer && runtime.csvLineBuffer.length > 0) { - return Buffer.concat([runtime.csvLineBuffer, chunk]); - } - else { - return chunk; - } -} -/** - * check if utf8 chars being split, if does, stripe the bytes and add to left buffer. - */ -function cleanUtf8Split(chunk, runtime) { - var idx = chunk.length - 1; - /** - * From Keyang: - * The code below is to check if a single utf8 char (which could be multiple bytes) being split. - * If the char being split, the buffer from two chunk needs to be concat - * check how utf8 being encoded to understand the code below. - * If anyone has any better way to do this, please let me know. - */ - if ((chunk[idx] & 1 << 7) != 0) { - while ((chunk[idx] & 3 << 6) === 128) { - idx--; - } - idx--; - } - if (idx != chunk.length - 1) { - runtime.csvLineBuffer = chunk.slice(idx + 1); - return chunk.slice(0, idx + 1); - // var _cb=cb; - // var self=this; - // cb=function(){ - // if (self._csvLineBuffer){ - // self._csvLineBuffer=Buffer.concat([bufFromString(self._csvLineBuffer,"utf8"),left]); - // }else{ - // self._csvLineBuffer=left; - // } - // _cb(); - // } - } - else { - return chunk; - } -} -//# sourceMappingURL=dataClean.js.map - -/***/ }), - -/***/ 228: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var getEol_1 = __importDefault(__nccwpck_require__(5819)); -// const getEol = require("./getEol"); -/** - * convert data chunk to file lines array - * @param {string} data data chunk as utf8 string - * @param {object} param Converter param object - * @return {Object} {lines:[line1,line2...],partial:String} - */ -function stringToLines(data, param) { - var eol = getEol_1.default(data, param); - var lines = data.split(eol); - var partial = lines.pop() || ""; - return { lines: lines, partial: partial }; -} -exports.stringToLines = stringToLines; -; -//# sourceMappingURL=fileline.js.map - -/***/ }), - -/***/ 5819: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//return first eol found from a data chunk. -function default_1(data, param) { - if (!param.eol && data) { - for (var i = 0, len = data.length; i < len; i++) { - if (data[i] === "\r") { - if (data[i + 1] === "\n") { - param.eol = "\r\n"; - break; - } - else if (data[i + 1]) { - param.eol = "\r"; - break; - } - } - else if (data[i] === "\n") { - param.eol = "\n"; - break; - } - } - } - return param.eol || "\n"; -} -exports["default"] = default_1; -; -//# sourceMappingURL=getEol.js.map - -/***/ }), - -/***/ 7463: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var Converter_1 = __nccwpck_require__(6991); -var helper = function (param, options) { - return new Converter_1.Converter(param, options); -}; -helper["csv"] = helper; -helper["Converter"] = Converter_1.Converter; -module.exports = helper; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9297: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var CSVError_1 = __importDefault(__nccwpck_require__(1356)); -var set_1 = __importDefault(__nccwpck_require__(2900)); -var numReg = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/; -function default_1(csvRows, conv) { - var res = []; - for (var i = 0, len = csvRows.length; i < len; i++) { - var r = processRow(csvRows[i], conv, i); - if (r) { - res.push(r); - } - } - return res; -} -exports["default"] = default_1; -; -function processRow(row, conv, index) { - if (conv.parseParam.checkColumn && conv.parseRuntime.headers && row.length !== conv.parseRuntime.headers.length) { - throw (CSVError_1.default.column_mismatched(conv.parseRuntime.parsedLineNumber + index)); - } - var headRow = conv.parseRuntime.headers || []; - var resultRow = convertRowToJson(row, headRow, conv); - if (resultRow) { - return resultRow; - } - else { - return null; - } -} -function convertRowToJson(row, headRow, conv) { - var hasValue = false; - var resultRow = {}; - for (var i = 0, len = row.length; i < len; i++) { - var item = row[i]; - if (conv.parseParam.ignoreEmpty && item === '') { - continue; - } - hasValue = true; - var head = headRow[i]; - if (!head || head === "") { - head = headRow[i] = "field" + (i + 1); - } - var convFunc = getConvFunc(head, i, conv); - if (convFunc) { - var convRes = convFunc(item, head, resultRow, row, i); - if (convRes !== undefined) { - setPath(resultRow, head, convRes, conv, i); - } - } - else { - // var flag = getFlag(head, i, param); - // if (flag === 'omit') { - // continue; - // } - if (conv.parseParam.checkType) { - var convertFunc = checkType(item, head, i, conv); - item = convertFunc(item); - } - if (item !== undefined) { - setPath(resultRow, head, item, conv, i); - } - } - } - if (hasValue) { - return resultRow; - } - else { - return null; - } -} -var builtInConv = { - "string": stringType, - "number": numberType, - "omit": function () { } -}; -function getConvFunc(head, i, conv) { - if (conv.parseRuntime.columnConv[i] !== undefined) { - return conv.parseRuntime.columnConv[i]; - } - else { - var flag = conv.parseParam.colParser[head]; - if (flag === undefined) { - return conv.parseRuntime.columnConv[i] = null; - } - if (typeof flag === "object") { - flag = flag.cellParser || "string"; - } - if (typeof flag === "string") { - flag = flag.trim().toLowerCase(); - var builtInFunc = builtInConv[flag]; - if (builtInFunc) { - return conv.parseRuntime.columnConv[i] = builtInFunc; - } - else { - return conv.parseRuntime.columnConv[i] = null; - } - } - else if (typeof flag === "function") { - return conv.parseRuntime.columnConv[i] = flag; - } - else { - return conv.parseRuntime.columnConv[i] = null; - } - } -} -function setPath(resultJson, head, value, conv, headIdx) { - if (!conv.parseRuntime.columnValueSetter[headIdx]) { - if (conv.parseParam.flatKeys) { - conv.parseRuntime.columnValueSetter[headIdx] = flatSetter; - } - else { - if (head.indexOf(".") > -1) { - var headArr = head.split("."); - var jsonHead = true; - while (headArr.length > 0) { - var headCom = headArr.shift(); - if (headCom.length === 0) { - jsonHead = false; - break; - } - } - if (!jsonHead || conv.parseParam.colParser[head] && conv.parseParam.colParser[head].flat) { - conv.parseRuntime.columnValueSetter[headIdx] = flatSetter; - } - else { - conv.parseRuntime.columnValueSetter[headIdx] = jsonSetter; - } - } - else { - conv.parseRuntime.columnValueSetter[headIdx] = flatSetter; - } - } - } - if (conv.parseParam.nullObject === true && value === "null") { - value = null; - } - conv.parseRuntime.columnValueSetter[headIdx](resultJson, head, value); - // flatSetter(resultJson, head, value); -} -function flatSetter(resultJson, head, value) { - resultJson[head] = value; -} -function jsonSetter(resultJson, head, value) { - set_1.default(resultJson, head, value); -} -function checkType(item, head, headIdx, conv) { - if (conv.parseRuntime.headerType[headIdx]) { - return conv.parseRuntime.headerType[headIdx]; - } - else if (head.indexOf('number#!') > -1) { - return conv.parseRuntime.headerType[headIdx] = numberType; - } - else if (head.indexOf('string#!') > -1) { - return conv.parseRuntime.headerType[headIdx] = stringType; - } - else if (conv.parseParam.checkType) { - return conv.parseRuntime.headerType[headIdx] = dynamicType; - } - else { - return conv.parseRuntime.headerType[headIdx] = stringType; - } -} -function numberType(item) { - var rtn = parseFloat(item); - if (isNaN(rtn)) { - return item; - } - return rtn; -} -function stringType(item) { - return item.toString(); -} -function dynamicType(item) { - var trimed = item.trim(); - if (trimed === "") { - return stringType(item); - } - if (numReg.test(trimed)) { - return numberType(item); - } - else if (trimed.length === 5 && trimed.toLowerCase() === "false" || trimed.length === 4 && trimed.toLowerCase() === "true") { - return booleanType(item); - } - else if (trimed[0] === "{" && trimed[trimed.length - 1] === "}" || trimed[0] === "[" && trimed[trimed.length - 1] === "]") { - return jsonType(item); - } - else { - return stringType(item); - } -} -function booleanType(item) { - var trimed = item.trim(); - if (trimed.length === 5 && trimed.toLowerCase() === "false") { - return false; - } - else { - return true; - } -} -function jsonType(item) { - try { - return JSON.parse(item); - } - catch (e) { - return item; - } -} -//# sourceMappingURL=lineToJson.js.map - -/***/ }), - -/***/ 5950: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var getEol_1 = __importDefault(__nccwpck_require__(5819)); -var util_1 = __nccwpck_require__(6935); -var defaulDelimiters = [",", "|", "\t", ";", ":"]; -var RowSplit = /** @class */ (function () { - function RowSplit(conv) { - this.conv = conv; - this.cachedRegExp = {}; - this.delimiterEmitted = false; - this._needEmitDelimiter = undefined; - this.quote = conv.parseParam.quote; - this.trim = conv.parseParam.trim; - this.escape = conv.parseParam.escape; - } - Object.defineProperty(RowSplit.prototype, "needEmitDelimiter", { - get: function () { - if (this._needEmitDelimiter === undefined) { - this._needEmitDelimiter = this.conv.listeners("delimiter").length > 0; - } - return this._needEmitDelimiter; - }, - enumerable: true, - configurable: true - }); - RowSplit.prototype.parse = function (fileline) { - if (fileline.length === 0 || (this.conv.parseParam.ignoreEmpty && fileline.trim().length === 0)) { - return { cells: [], closed: true }; - } - var quote = this.quote; - var trim = this.trim; - var escape = this.escape; - if (this.conv.parseRuntime.delimiter instanceof Array || this.conv.parseRuntime.delimiter.toLowerCase() === "auto") { - this.conv.parseRuntime.delimiter = this.getDelimiter(fileline); - } - if (this.needEmitDelimiter && !this.delimiterEmitted) { - this.conv.emit("delimiter", this.conv.parseRuntime.delimiter); - this.delimiterEmitted = true; - } - var delimiter = this.conv.parseRuntime.delimiter; - var rowArr = fileline.split(delimiter); - if (quote === "off") { - if (trim) { - for (var i = 0; i < rowArr.length; i++) { - rowArr[i] = rowArr[i].trim(); - } - } - return { cells: rowArr, closed: true }; - } - else { - return this.toCSVRow(rowArr, trim, quote, delimiter); - } - }; - RowSplit.prototype.toCSVRow = function (rowArr, trim, quote, delimiter) { - var row = []; - var inquote = false; - var quoteBuff = ''; - for (var i = 0, rowLen = rowArr.length; i < rowLen; i++) { - var e = rowArr[i]; - if (!inquote && trim) { - e = util_1.trimLeft(e); - } - var len = e.length; - if (!inquote) { - if (len === 2 && e === this.quote + this.quote) { - row.push(""); - continue; - } - else if (this.isQuoteOpen(e)) { //quote open - e = e.substr(1); - if (this.isQuoteClose(e)) { //quote close - e = e.substring(0, e.lastIndexOf(quote)); - e = this.escapeQuote(e); - row.push(e); - continue; - } - else if (e.indexOf(quote) !== -1) { - var count = 0; - var prev = ""; - for (var _i = 0, e_1 = e; _i < e_1.length; _i++) { - var c = e_1[_i]; - // count quotes only if previous character is not escape char - if (c === quote && prev !== this.escape) { - count++; - prev = ""; - } - else { - // save previous char to temp variable - prev = c; - } - } - if (count % 2 === 1) { - if (trim) { - e = util_1.trimRight(e); - } - row.push(quote + e); - continue; - } - else { - inquote = true; - quoteBuff += e; - continue; - } - } - else { - inquote = true; - quoteBuff += e; - continue; - } - } - else { - if (trim) { - e = util_1.trimRight(e); - } - row.push(e); - continue; - } - } - else { //previous quote not closed - if (this.isQuoteClose(e)) { //close double quote - inquote = false; - e = e.substr(0, len - 1); - quoteBuff += delimiter + e; - quoteBuff = this.escapeQuote(quoteBuff); - if (trim) { - quoteBuff = util_1.trimRight(quoteBuff); - } - row.push(quoteBuff); - quoteBuff = ""; - } - else { - quoteBuff += delimiter + e; - } - } - } - // if (!inquote && param._needFilterRow) { - // row = filterRow(row, param); - // } - return { cells: row, closed: !inquote }; - }; - RowSplit.prototype.getDelimiter = function (fileline) { - var checker; - if (this.conv.parseParam.delimiter === "auto") { - checker = defaulDelimiters; - } - else if (this.conv.parseParam.delimiter instanceof Array) { - checker = this.conv.parseParam.delimiter; - } - else { - return this.conv.parseParam.delimiter; - } - var count = 0; - var rtn = ","; - checker.forEach(function (delim) { - var delimCount = fileline.split(delim).length; - if (delimCount > count) { - rtn = delim; - count = delimCount; - } - }); - return rtn; - }; - RowSplit.prototype.isQuoteOpen = function (str) { - var quote = this.quote; - var escape = this.escape; - return str[0] === quote && (str[1] !== quote || - str[1] === escape && (str[2] === quote || str.length === 2)); - }; - RowSplit.prototype.isQuoteClose = function (str) { - var quote = this.quote; - var escape = this.escape; - if (this.conv.parseParam.trim) { - str = util_1.trimRight(str); - } - var count = 0; - var idx = str.length - 1; - while (str[idx] === quote || str[idx] === escape) { - idx--; - count++; - } - return count % 2 !== 0; - }; - // private twoDoubleQuote(str: string): string { - // var twoQuote = this.quote + this.quote; - // var curIndex = -1; - // while ((curIndex = str.indexOf(twoQuote, curIndex)) > -1) { - // str = str.substring(0, curIndex) + str.substring(++curIndex); - // } - // return str; - // } - RowSplit.prototype.escapeQuote = function (segment) { - var key = "es|" + this.quote + "|" + this.escape; - if (this.cachedRegExp[key] === undefined) { - this.cachedRegExp[key] = new RegExp('\\' + this.escape + '\\' + this.quote, 'g'); - } - var regExp = this.cachedRegExp[key]; - // console.log(regExp,segment); - return segment.replace(regExp, this.quote); - }; - RowSplit.prototype.parseMultiLines = function (lines) { - var csvLines = []; - var left = ""; - while (lines.length) { - var line = left + lines.shift(); - var row = this.parse(line); - if (row.cells.length === 0 && this.conv.parseParam.ignoreEmpty) { - continue; - } - if (row.closed || this.conv.parseParam.alwaysSplitAtEOL) { - if (this.conv.parseRuntime.selectedColumns) { - csvLines.push(util_1.filterArray(row.cells, this.conv.parseRuntime.selectedColumns)); - } - else { - csvLines.push(row.cells); - } - left = ""; - } - else { - left = line + (getEol_1.default(line, this.conv.parseRuntime) || "\n"); - } - } - return { rowsCells: csvLines, partial: left }; - }; - return RowSplit; -}()); -exports.RowSplit = RowSplit; -//# sourceMappingURL=rowSplit.js.map - -/***/ }), - -/***/ 6935: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function bufFromString(str) { - var length = Buffer.byteLength(str); - var buffer = Buffer.allocUnsafe - ? Buffer.allocUnsafe(length) - : new Buffer(length); - buffer.write(str); - return buffer; -} -exports.bufFromString = bufFromString; -function emptyBuffer() { - var buffer = Buffer.allocUnsafe - ? Buffer.allocUnsafe(0) - : new Buffer(0); - return buffer; -} -exports.emptyBuffer = emptyBuffer; -function filterArray(arr, filter) { - var rtn = []; - for (var i = 0; i < arr.length; i++) { - if (filter.indexOf(i) > -1) { - rtn.push(arr[i]); - } - } - return rtn; -} -exports.filterArray = filterArray; -exports.trimLeft = String.prototype.trimLeft ? function trimLeftNative(str) { - return str.trimLeft(); -} : function trimLeftRegExp(str) { - return str.replace(/^\s+/, ""); -}; -exports.trimRight = String.prototype.trimRight ? function trimRightNative(str) { - return str.trimRight(); -} : function trimRightRegExp(str) { - return str.replace(/\s+$/, ""); -}; -//# sourceMappingURL=util.js.map - -/***/ }), - -/***/ 8932: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; - } - -} - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 5481: -/***/ ((module, exports) => { - - -exports = module.exports = function(bytes) -{ - var i = 0; - while(i < bytes.length) - { - if( (// ASCII - bytes[i] == 0x09 || - bytes[i] == 0x0A || - bytes[i] == 0x0D || - (0x20 <= bytes[i] && bytes[i] <= 0x7E) - ) - ) { - i += 1; - continue; - } - - if( (// non-overlong 2-byte - (0xC2 <= bytes[i] && bytes[i] <= 0xDF) && - (0x80 <= bytes[i+1] && bytes[i+1] <= 0xBF) - ) - ) { - i += 2; - continue; - } - - if( (// excluding overlongs - bytes[i] == 0xE0 && - (0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && - (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) - ) || - (// straight 3-byte - ((0xE1 <= bytes[i] && bytes[i] <= 0xEC) || - bytes[i] == 0xEE || - bytes[i] == 0xEF) && - (0x80 <= bytes[i + 1] && bytes[i+1] <= 0xBF) && - (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF) - ) || - (// excluding surrogates - bytes[i] == 0xED && - (0x80 <= bytes[i+1] && bytes[i+1] <= 0x9F) && - (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF) - ) - ) { - i += 3; - continue; - } - - if( (// planes 1-3 - bytes[i] == 0xF0 && - (0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && - (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && - (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) - ) || - (// planes 4-15 - (0xF1 <= bytes[i] && bytes[i] <= 0xF3) && - (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) && - (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && - (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) - ) || - (// plane 16 - bytes[i] == 0xF4 && - (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) && - (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) && - (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF) - ) - ) { - i += 4; - continue; - } - - return false; - } - - return true; -} - - -/***/ }), - -/***/ 5902: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var hashClear = __nccwpck_require__(1789), - hashDelete = __nccwpck_require__(712), - hashGet = __nccwpck_require__(5804), - hashHas = __nccwpck_require__(5232), - hashSet = __nccwpck_require__(7320); - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - -module.exports = Hash; - - -/***/ }), - -/***/ 6608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var listCacheClear = __nccwpck_require__(9792), - listCacheDelete = __nccwpck_require__(7716), - listCacheGet = __nccwpck_require__(5789), - listCacheHas = __nccwpck_require__(9386), - listCacheSet = __nccwpck_require__(7399); - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -module.exports = ListCache; - - -/***/ }), - -/***/ 881: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getNative = __nccwpck_require__(4479), - root = __nccwpck_require__(9882); - -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'); - -module.exports = Map; - - -/***/ }), - -/***/ 938: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var mapCacheClear = __nccwpck_require__(1610), - mapCacheDelete = __nccwpck_require__(6657), - mapCacheGet = __nccwpck_require__(1372), - mapCacheHas = __nccwpck_require__(609), - mapCacheSet = __nccwpck_require__(5582); - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; - -module.exports = MapCache; - - -/***/ }), - -/***/ 9213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var root = __nccwpck_require__(9882); - -/** Built-in value references. */ -var Symbol = root.Symbol; - -module.exports = Symbol; - - -/***/ }), - -/***/ 4356: -/***/ ((module) => { - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -module.exports = arrayMap; - - -/***/ }), - -/***/ 9725: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var baseAssignValue = __nccwpck_require__(3868), - eq = __nccwpck_require__(1901); - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } -} - -module.exports = assignValue; - - -/***/ }), - -/***/ 6752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var eq = __nccwpck_require__(1901); - -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; -} - -module.exports = assocIndexOf; - - -/***/ }), - -/***/ 3868: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var defineProperty = __nccwpck_require__(416); - -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} - -module.exports = baseAssignValue; - - -/***/ }), - -/***/ 7497: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Symbol = __nccwpck_require__(9213), - getRawTag = __nccwpck_require__(923), - objectToString = __nccwpck_require__(4200); - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -module.exports = baseGetTag; - - -/***/ }), - -/***/ 411: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var isFunction = __nccwpck_require__(7799), - isMasked = __nccwpck_require__(9058), - isObject = __nccwpck_require__(3334), - toSource = __nccwpck_require__(6928); - -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} - -module.exports = baseIsNative; - - -/***/ }), - -/***/ 8580: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var assignValue = __nccwpck_require__(9725), - castPath = __nccwpck_require__(2688), - isIndex = __nccwpck_require__(2936), - isObject = __nccwpck_require__(3334), - toKey = __nccwpck_require__(9071); - -/** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ -function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; -} - -module.exports = baseSet; - - -/***/ }), - -/***/ 6792: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Symbol = __nccwpck_require__(9213), - arrayMap = __nccwpck_require__(4356), - isArray = __nccwpck_require__(4869), - isSymbol = __nccwpck_require__(6403); - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -module.exports = baseToString; - - -/***/ }), - -/***/ 2688: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var isArray = __nccwpck_require__(4869), - isKey = __nccwpck_require__(9084), - stringToPath = __nccwpck_require__(1853), - toString = __nccwpck_require__(2931); - -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); -} - -module.exports = castPath; - - -/***/ }), - -/***/ 8380: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var root = __nccwpck_require__(9882); - -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; - -module.exports = coreJsData; - - -/***/ }), - -/***/ 416: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getNative = __nccwpck_require__(4479); - -var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); - -module.exports = defineProperty; - - -/***/ }), - -/***/ 2085: -/***/ ((module) => { - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -module.exports = freeGlobal; - - -/***/ }), - -/***/ 9980: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var isKeyable = __nccwpck_require__(3308); - -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} - -module.exports = getMapData; - - -/***/ }), - -/***/ 4479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var baseIsNative = __nccwpck_require__(411), - getValue = __nccwpck_require__(3542); - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} - -module.exports = getNative; - - -/***/ }), - -/***/ 923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Symbol = __nccwpck_require__(9213); - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; -} - -module.exports = getRawTag; - - -/***/ }), - -/***/ 3542: -/***/ ((module) => { - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} - -module.exports = getValue; - - -/***/ }), - -/***/ 1789: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var nativeCreate = __nccwpck_require__(3041); - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; -} - -module.exports = hashClear; - - -/***/ }), - -/***/ 712: -/***/ ((module) => { - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} - -module.exports = hashDelete; - - -/***/ }), - -/***/ 5804: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var nativeCreate = __nccwpck_require__(3041); - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} - -module.exports = hashGet; - - -/***/ }), - -/***/ 5232: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var nativeCreate = __nccwpck_require__(3041); - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); -} - -module.exports = hashHas; - - -/***/ }), - -/***/ 7320: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var nativeCreate = __nccwpck_require__(3041); - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} - -module.exports = hashSet; - - -/***/ }), - -/***/ 2936: -/***/ ((module) => { - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -module.exports = isIndex; - - -/***/ }), - -/***/ 9084: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var isArray = __nccwpck_require__(4869), - isSymbol = __nccwpck_require__(6403); - -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} - -module.exports = isKey; - - -/***/ }), - -/***/ 3308: -/***/ ((module) => { - -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} - -module.exports = isKeyable; - - -/***/ }), - -/***/ 9058: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var coreJsData = __nccwpck_require__(8380); - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); - -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} - -module.exports = isMasked; - - -/***/ }), - -/***/ 9792: -/***/ ((module) => { - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -module.exports = listCacheClear; - - -/***/ }), - -/***/ 7716: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var assocIndexOf = __nccwpck_require__(6752); - -/** Used for built-in method references. */ -var arrayProto = Array.prototype; - -/** Built-in value references. */ -var splice = arrayProto.splice; - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; -} - -module.exports = listCacheDelete; - - -/***/ }), - -/***/ 5789: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var assocIndexOf = __nccwpck_require__(6752); - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; -} - -module.exports = listCacheGet; - - -/***/ }), - -/***/ 9386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var assocIndexOf = __nccwpck_require__(6752); - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} - -module.exports = listCacheHas; - - -/***/ }), - -/***/ 7399: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var assocIndexOf = __nccwpck_require__(6752); - -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} - -module.exports = listCacheSet; - - -/***/ }), - -/***/ 1610: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Hash = __nccwpck_require__(5902), - ListCache = __nccwpck_require__(6608), - Map = __nccwpck_require__(881); - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} - -module.exports = mapCacheClear; - - -/***/ }), - -/***/ 6657: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getMapData = __nccwpck_require__(9980); - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} - -module.exports = mapCacheDelete; - - -/***/ }), - -/***/ 1372: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getMapData = __nccwpck_require__(9980); - -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} - -module.exports = mapCacheGet; - - -/***/ }), - -/***/ 609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getMapData = __nccwpck_require__(9980); - -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} - -module.exports = mapCacheHas; - - -/***/ }), - -/***/ 5582: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getMapData = __nccwpck_require__(9980); - -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} - -module.exports = mapCacheSet; - - -/***/ }), - -/***/ 9422: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var memoize = __nccwpck_require__(9885); - -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; - -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; -} - -module.exports = memoizeCapped; - - -/***/ }), - -/***/ 3041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var getNative = __nccwpck_require__(4479); - -/* Built-in method references that are verified to be native. */ -var nativeCreate = getNative(Object, 'create'); - -module.exports = nativeCreate; - - -/***/ }), - -/***/ 4200: -/***/ ((module) => { - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString.call(value); -} - -module.exports = objectToString; - - -/***/ }), - -/***/ 9882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var freeGlobal = __nccwpck_require__(2085); - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -module.exports = root; - - -/***/ }), - -/***/ 1853: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var memoizeCapped = __nccwpck_require__(9422); - -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; - -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); - -module.exports = stringToPath; - - -/***/ }), - -/***/ 9071: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var isSymbol = __nccwpck_require__(6403); - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -module.exports = toKey; - - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -/** Used for built-in method references. */ -var funcProto = Function.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} + buildJsonSubArray(value) { + let extractedValues = value.substring( + value.indexOf(this.parseSubArrayDelimiter) + 1, + value.lastIndexOf(this.parseSubArrayDelimiter) + ); + extractedValues.trim(); + value = extractedValues.split(this.parseSubArraySeparator); + if(this.printValueFormatByType){ + for(let i=0; i < value.length; i++){ + value[i] = stringUtils.getValueFormatByType(value[i]); + } + } + return value; } - return ''; -} -module.exports = toSource; + isParseSubArray(value){ + if(this.parseSubArrayDelimiter){ + if (value && (value.indexOf(this.parseSubArrayDelimiter) === 0 && value.lastIndexOf(this.parseSubArrayDelimiter) === (value.length - 1))) { + return true; + } + } + return false; + } + validateInputConfig(){ + if(this.isSupportQuotedField) { + if(this.getFieldDelimiter() === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field delimiter as quote -> ["]'); + } + if(this.parseSubArraySeparator === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArraySeparator as quote -> ["]'); + } + if(this.parseSubArrayDelimiter === '"'){ + throw new Error('When SupportQuotedFields is enabled you cannot defined the field parseSubArrayDelimiter as quote -> ["]'); + } + } + } -/***/ }), + hasQuotes(line) { + return line.includes('"'); + } -/***/ 1901: -/***/ ((module) => { + split(line) { + if(line.length == 0){ + return []; + } + let delim = this.getFieldDelimiter(); + let subSplits = ['']; + if (this.hasQuotes(line)) { + let chars = line.split(''); -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); + let subIndex = 0; + let startQuote = false; + let isDouble = false; + chars.forEach((c, i, arr) => { + if (isDouble) { //when run into double just pop it into current and move on + subSplits[subIndex] += c; + isDouble = false; + return; + } + + if (c != '"' && c != delim ) { + subSplits[subIndex] += c; + } else if(c == delim && startQuote){ + subSplits[subIndex] += c; + } else if( c == delim ){ + subIndex++ + subSplits[subIndex] = ''; + return; + } else { + if (arr[i + 1] === '"') { + //Double quote + isDouble = true; + //subSplits[subIndex] += c; //Skip because this is escaped quote + } else { + if (!startQuote) { + startQuote = true; + //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value + } else { + //end + startQuote = false; + //subSplits[subIndex] += c; //Skip because we don't want quotes wrapping value + } + } + } + }); + if(startQuote){ + throw new Error('Row contains mismatched quotes!'); + } + return subSplits; + } else { + return line.split(delim); + } + } } -module.exports = eq; +module.exports = new CsvToJson(); /***/ }), -/***/ 4869: -/***/ ((module) => { - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +/***/ 6114: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = isArray; -/***/ }), +let fs = __nccwpck_require__(7147); -/***/ 7799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +class FileUtils { -var baseGetTag = __nccwpck_require__(7497), - isObject = __nccwpck_require__(3334); + readFile(fileInputName, encoding) { + return fs.readFileSync(fileInputName, encoding).toString(); + } -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; + writeFile(json, fileOutputName) { + fs.writeFile(fileOutputName, json, function (err) { + if (err) { + throw err; + } else { + console.log('File saved: ' + fileOutputName); + } + }); + } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } - -module.exports = isFunction; +module.exports = new FileUtils(); /***/ }), -/***/ 3334: +/***/ 4166: /***/ ((module) => { -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -module.exports = isObject; -/***/ }), +class JsonUtil { -/***/ 5926: -/***/ ((module) => { + validateJson(json) { + try { + JSON.parse(json); + } catch (err) { + throw Error('Parsed csv has generated an invalid json!!!\n' + err); + } + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; } -module.exports = isObjectLike; - +module.exports = new JsonUtil(); /***/ }), -/***/ 6403: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var baseGetTag = __nccwpck_require__(7497), - isObjectLike = __nccwpck_require__(5926); - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -module.exports = isSymbol; - +/***/ 6494: +/***/ ((module) => { -/***/ }), -/***/ 9885: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var MapCache = __nccwpck_require__(938); +class StringUtils { -/** Error message constants. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + trimPropertyName(value) { + return value.replace(/\s/g, ''); + } -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; + getValueFormatByType(value) { + if(value === undefined || value === ''){ + return String(); + } + //is Number + let isNumber = !isNaN(value); + if (isNumber) { + return Number(value); + } + // is Boolean + if(value === "true" || value === "false"){ + return JSON.parse(value.toLowerCase()); + } + return String(value); + } - if (cache.has(key)) { - return cache.get(key); + hasContent(values) { + if (values.length > 0) { + for (let i = 0; i < values.length; i++) { + if (values[i]) { + return true; + } + } + } + return false; } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; } -// Expose `MapCache`. -memoize.Cache = MapCache; - -module.exports = memoize; +module.exports = new StringUtils(); /***/ }), -/***/ 2900: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 8932: +/***/ ((__unused_webpack_module, exports) => { -var baseSet = __nccwpck_require__(8580); -/** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ -function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); -} -module.exports = set; +Object.defineProperty(exports, "__esModule", ({ value: true })); +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) -/***/ }), + /* istanbul ignore next */ -/***/ 2931: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } -var baseToString = __nccwpck_require__(6792); + this.name = 'Deprecation'; + } -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); } -module.exports = toString; +exports.Deprecation = Deprecation; /***/ }), @@ -16261,30 +7003,6 @@ function onceStrict (fn) { } -/***/ }), - -/***/ 8551: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var isUtf8 = __nccwpck_require__(5481); - -module.exports = function (x) { - // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string - // conversion translates it to FEFF (UTF-16 BOM) - if (typeof x === 'string' && x.charCodeAt(0) === 0xFEFF) { - return x.slice(1); - } - - if (Buffer.isBuffer(x) && isUtf8(x) && - x[0] === 0xEF && x[1] === 0xBB && x[2] === 0xBF) { - return x.slice(3); - } - - return x; -}; - - /***/ }), /***/ 4294: @@ -39593,9 +30311,6 @@ __nccwpck_require__.d(__webpack_exports__, { var promises_ = __nccwpck_require__(3292); // EXTERNAL MODULE: external "path" var external_path_ = __nccwpck_require__(1017); -// EXTERNAL MODULE: ./node_modules/csvtojson/v2/index.js -var v2 = __nccwpck_require__(7463); -var v2_default = /*#__PURE__*/__nccwpck_require__.n(v2); // EXTERNAL MODULE: ./node_modules/convert-csv-to-json/index.js var convert_csv_to_json = __nccwpck_require__(224); // EXTERNAL MODULE: ./src/isFileExists.ts @@ -39610,7 +30325,6 @@ const chartReport = Buffer.from('PCEtLSByZXBvcnQtYWN0aW9uIC0tPgo8IWRvY3R5cGUgaHR - const csvExt = '.csv'; const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { const dataFile = external_path_.join(reportBaseDir, 'data.json'); @@ -39627,16 +30341,7 @@ const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { } const filesContent = []; if (sourceReportDir.toLowerCase().endsWith(csvExt)) { - const json = await v2_default()().fromFile(sourceReportDir); - const json2 = convert_csv_to_json.fieldDelimiter(',').getJsonFromCsv(sourceReportDir); - const jsonStr = JSON.stringify(json); - const jsonStr2 = JSON.stringify(json2); - console.log('jsonStr === jsonStr2', jsonStr === jsonStr2); - console.log('-'.repeat(60)); - console.log(jsonStr); - console.log('^'.repeat(60)); - console.log(jsonStr2); - console.log('-'.repeat(60)); + const json = convert_csv_to_json.fieldDelimiter(',').getJsonFromCsv(sourceReportDir); filesContent.push({ name: external_path_.basename(sourceReportDir, external_path_.extname(sourceReportDir)), json }); } else { @@ -39644,7 +30349,7 @@ const csvReport = async (sourceReportDir, reportBaseDir, reportId, meta) => { .filter((f) => f.isFile() && external_path_.extname(f.name) === csvExt) .sort((a, b) => a.name.localeCompare(b.name)); for (const csvFile of csvFiles) { - const json = await v2_default()().fromFile(external_path_.join(sourceReportDir, csvFile.name)); + const json = convert_csv_to_json.fieldDelimiter(',').getJsonFromCsv(external_path_.join(sourceReportDir, csvFile.name)); filesContent.push({ name: external_path_.basename(csvFile.name, csvExt), json }); } } diff --git a/dist/licenses.txt b/dist/licenses.txt index 8713385..6eb30a9 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -458,31 +458,6 @@ Apache-2.0 limitations under the License. -bluebird -MIT -The MIT License (MIT) - -Copyright (c) 2013-2018 Petka Antonov - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - convert-csv-to-json ISC GNU GENERAL PUBLIC LICENSE @@ -1161,17 +1136,6 @@ Public License instead of this License. But first, please read . -csvtojson -MIT -Copyright (C) 2013 Keyang Xiang - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - deprecation ISC The ISC License @@ -1191,70 +1155,6 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -is-utf8 -MIT -The MIT License (MIT) - -Copyright (C) 2014 Wei Fanzhe - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -   -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -lodash -MIT -Copyright OpenJS Foundation and other contributors - -Based on Underscore.js, copyright Jeremy Ashkenas, -DocumentCloud and Investigative Reporters & Editors - -This software consists of voluntary contributions made by many -individuals. For exact contribution history, see the revision history -available at https://github.com/lodash/lodash - -The following license applies to all parts of this software except as -documented below: - -==== - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==== - -Copyright and related rights for sample code are waived via CC0. Sample -code is defined as all source code displayed within the prose of the -documentation. - -CC0: http://creativecommons.org/publicdomain/zero/1.0/ - -==== - -Files located in the node_modules and vendor directories are externally -maintained libraries used by this software which have their own -licenses; we recommend you read them, as their terms may differ from the -terms above. - - once ISC The ISC License @@ -1274,31 +1174,6 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -strip-bom -MIT -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - tunnel MIT The MIT License (MIT) diff --git a/package-lock.json b/package-lock.json index ce41786..3d97d1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,8 +13,7 @@ "@actions/core": "^1.10.1", "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", - "convert-csv-to-json": "^2.46.0", - "csvtojson": "^2.0.10" + "convert-csv-to-json": "^2.46.0" }, "devDependencies": { "@playwright/test": "^1.43.1", @@ -1161,11 +1160,6 @@ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==" }, - "node_modules/bluebird": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", - "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" - }, "node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", @@ -1442,22 +1436,6 @@ "integrity": "sha512-N3ASg0C4kNPUaNxt1XAvzHIVuzdtr8KLgfk1O8WDyimp1GisPAHESupArO2ieHk9QWbrJ/WkQODyh21Ps/xhxw==", "dev": true }, - "node_modules/csvtojson": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/csvtojson/-/csvtojson-2.0.10.tgz", - "integrity": "sha512-lUWFxGKyhraKCW8Qghz6Z0f2l/PqB1W3AO0HKJzGIQ5JRSlR651ekJDiGJbBT4sRNNv5ddnSGVEnsxP9XRCVpQ==", - "dependencies": { - "bluebird": "^3.5.1", - "lodash": "^4.17.3", - "strip-bom": "^2.0.0" - }, - "bin": { - "csvtojson": "bin/csvtojson" - }, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/data-uri-to-buffer": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", @@ -3222,11 +3200,6 @@ "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", "dev": true }, - "node_modules/is-utf8": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", - "integrity": "sha512-rMYPYvCzsXywIsldgLaSoPlw5PfoB/ssr7hY4pLfcodrA5M/eArza1a9VmTiNIBNMjOGr1Ow9mTyU2o69U6U9Q==" - }, "node_modules/is-weakref": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", @@ -3494,7 +3467,8 @@ "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true }, "node_modules/lodash.merge": { "version": "4.6.2", @@ -5033,17 +5007,6 @@ "node": ">=6" } }, - "node_modules/strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", - "dependencies": { - "is-utf8": "^0.2.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", diff --git a/package.json b/package.json index ae5632c..82480b8 100644 --- a/package.json +++ b/package.json @@ -35,8 +35,7 @@ "@actions/core": "^1.10.1", "@actions/github": "^6.0.0", "@actions/io": "^1.1.3", - "convert-csv-to-json": "^2.46.0", - "csvtojson": "^2.0.10" + "convert-csv-to-json": "^2.46.0" }, "devDependencies": { "@playwright/test": "^1.43.1", diff --git a/src/csvReport.ts b/src/csvReport.ts index b00d27f..705d39d 100644 --- a/src/csvReport.ts +++ b/src/csvReport.ts @@ -1,6 +1,5 @@ import * as fs from 'fs/promises' import * as path from 'path' -import csvtojson from 'csvtojson' import csvToJson from 'convert-csv-to-json' import { isFileExist } from './isFileExists.js' import { chartReport } from './report_chart.js' @@ -28,20 +27,7 @@ export const csvReport = async ( } const filesContent: Array<{ name: string; json: Array> }> = [] if (sourceReportDir.toLowerCase().endsWith(csvExt)) { - const json = await csvtojson().fromFile(sourceReportDir) - const json2 = csvToJson.fieldDelimiter(',').getJsonFromCsv(sourceReportDir) - - const jsonStr = JSON.stringify(json) - const jsonStr2 = JSON.stringify(json2) - - console.log('jsonStr === jsonStr2', jsonStr === jsonStr2) - - console.log('-'.repeat(60)) - console.log(jsonStr) - console.log('^'.repeat(60)) - console.log(jsonStr2) - console.log('-'.repeat(60)) - + const json = csvToJson.fieldDelimiter(',').getJsonFromCsv(sourceReportDir) filesContent.push({ name: path.basename(sourceReportDir, path.extname(sourceReportDir)), json }) } else { const csvFiles = (await fs.readdir(sourceReportDir, { withFileTypes: true })) @@ -49,7 +35,7 @@ export const csvReport = async ( .sort((a, b) => a.name.localeCompare(b.name)) for (const csvFile of csvFiles) { - const json = await csvtojson().fromFile(path.join(sourceReportDir, csvFile.name)) + const json = csvToJson.fieldDelimiter(',').getJsonFromCsv(path.join(sourceReportDir, csvFile.name)) filesContent.push({ name: path.basename(csvFile.name, csvExt), json }) } }