@loaders.gl/csv 3.4.11 → 3.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,7 +14,7 @@ var _papaparse = _interopRequireDefault(require("./papaparse/papaparse"));
14
14
  var _asyncIteratorStreamer = _interopRequireDefault(require("./papaparse/async-iterator-streamer"));
15
15
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
16
16
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
- var VERSION = typeof "3.4.11" !== 'undefined' ? "3.4.11" : 'latest';
17
+ var VERSION = typeof "3.4.12" !== 'undefined' ? "3.4.12" : 'latest';
18
18
  var DEFAULT_CSV_LOADER_OPTIONS = {
19
19
  csv: {
20
20
  shape: 'object-row-table',
@@ -1,7 +1,7 @@
1
1
  import { AsyncQueue, TableBatchBuilder, convertToArrayRow, convertToObjectRow } from '@loaders.gl/schema';
2
2
  import Papa from './papaparse/papaparse';
3
3
  import AsyncIteratorStreamer from './papaparse/async-iterator-streamer';
4
- const VERSION = typeof "3.4.11" !== 'undefined' ? "3.4.11" : 'latest';
4
+ const VERSION = typeof "3.4.12" !== 'undefined' ? "3.4.12" : 'latest';
5
5
  const DEFAULT_CSV_LOADER_OPTIONS = {
6
6
  csv: {
7
7
  shape: 'object-row-table',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loaders.gl/csv",
3
- "version": "3.4.11",
3
+ "version": "3.4.12",
4
4
  "description": "Framework-independent loader for CSV and DSV table formats",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -30,11 +30,11 @@
30
30
  "build-bundle": "esbuild src/bundle.ts --bundle --outfile=dist/dist.min.js"
31
31
  },
32
32
  "dependencies": {
33
- "@loaders.gl/loader-utils": "3.4.11",
34
- "@loaders.gl/schema": "3.4.11"
33
+ "@loaders.gl/loader-utils": "3.4.12",
34
+ "@loaders.gl/schema": "3.4.12"
35
35
  },
36
36
  "devDependencies": {
37
37
  "d3-dsv": "^1.2.0"
38
38
  },
39
- "gitHead": "2b8d490d2372e70dd89eef8f6b215a5205c16621"
39
+ "gitHead": "85254762ae3082f608a863291deef09f2b40c6cf"
40
40
  }
package/dist/bundle.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- const moduleExports = require('./index');
4
- globalThis.loaders = globalThis.loaders || {};
5
- module.exports = Object.assign(globalThis.loaders, moduleExports);
@@ -1,267 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports._typecheckCSVLoader = exports.CSVLoader = void 0;
7
- const schema_1 = require("@loaders.gl/schema");
8
- const papaparse_1 = __importDefault(require("./papaparse/papaparse"));
9
- const async_iterator_streamer_1 = __importDefault(require("./papaparse/async-iterator-streamer"));
10
- // __VERSION__ is injected by babel-plugin-version-inline
11
- // @ts-ignore TS2304: Cannot find name '__VERSION__'.
12
- const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';
13
- const DEFAULT_CSV_LOADER_OPTIONS = {
14
- csv: {
15
- shape: 'object-row-table',
16
- optimizeMemoryUsage: false,
17
- // CSV options
18
- header: 'auto',
19
- columnPrefix: 'column',
20
- // delimiter: auto
21
- // newline: auto
22
- quoteChar: '"',
23
- escapeChar: '"',
24
- dynamicTyping: true,
25
- comments: false,
26
- skipEmptyLines: true,
27
- // transform: null?
28
- delimitersToGuess: [',', '\t', '|', ';']
29
- // fastMode: auto
30
- }
31
- };
32
- exports.CSVLoader = {
33
- id: 'csv',
34
- module: 'csv',
35
- name: 'CSV',
36
- version: VERSION,
37
- extensions: ['csv', 'tsv', 'dsv'],
38
- mimeTypes: ['text/csv', 'text/tab-separated-values', 'text/dsv'],
39
- category: 'table',
40
- parse: async (arrayBuffer, options) => parseCSV(new TextDecoder().decode(arrayBuffer), options),
41
- parseText: (text, options) => parseCSV(text, options),
42
- parseInBatches: parseCSVInBatches,
43
- // @ts-ignore
44
- // testText: null,
45
- options: DEFAULT_CSV_LOADER_OPTIONS
46
- };
47
- async function parseCSV(csvText, options) {
48
- // Apps can call the parse method directly, we so apply default options here
49
- const csvOptions = { ...DEFAULT_CSV_LOADER_OPTIONS.csv, ...options?.csv };
50
- const firstRow = readFirstRow(csvText);
51
- const header = csvOptions.header === 'auto' ? isHeaderRow(firstRow) : Boolean(csvOptions.header);
52
- const parseWithHeader = header;
53
- const papaparseConfig = {
54
- // dynamicTyping: true,
55
- ...csvOptions,
56
- header: parseWithHeader,
57
- download: false,
58
- transformHeader: parseWithHeader ? duplicateColumnTransformer() : undefined,
59
- error: (e) => {
60
- throw new Error(e);
61
- }
62
- };
63
- const result = papaparse_1.default.parse(csvText, papaparseConfig);
64
- let { data: rows } = result;
65
- const headerRow = result.meta.fields || generateHeader(csvOptions.columnPrefix, firstRow.length);
66
- switch (csvOptions.shape) {
67
- case 'object-row-table':
68
- rows = rows.map((row) => (Array.isArray(row) ? (0, schema_1.convertToObjectRow)(row, headerRow) : row));
69
- break;
70
- case 'array-row-table':
71
- rows = rows.map((row) => (Array.isArray(row) ? row : (0, schema_1.convertToArrayRow)(row, headerRow)));
72
- break;
73
- default:
74
- }
75
- /*
76
- if (!header && shape === 'object-row-table') {
77
- // If the dataset has no header, transform the array result into an object shape with an
78
- // autogenerated header
79
- return result.data.map((row) =>
80
- row.reduce((acc, value, i) => {
81
- acc[headerRow[i]] = value;
82
- return acc;
83
- }, {})
84
- );
85
- }
86
- */
87
- return rows;
88
- }
89
- // TODO - support batch size 0 = no batching/single batch?
90
- function parseCSVInBatches(asyncIterator, options) {
91
- // Papaparse does not support standard batch size handling
92
- // TODO - investigate papaparse chunks mode
93
- options = { ...options };
94
- if (options.batchSize === 'auto') {
95
- options.batchSize = 4000;
96
- }
97
- // Apps can call the parse method directly, we so apply default options here
98
- const csvOptions = { ...DEFAULT_CSV_LOADER_OPTIONS.csv, ...options?.csv };
99
- const asyncQueue = new schema_1.AsyncQueue();
100
- let isFirstRow = true;
101
- let headerRow = null;
102
- let tableBatchBuilder = null;
103
- let schema = null;
104
- const config = {
105
- // dynamicTyping: true, // Convert numbers and boolean values in rows from strings,
106
- ...csvOptions,
107
- header: false,
108
- download: false,
109
- // chunkSize is set to 5MB explicitly (same as Papaparse default) due to a bug where the
110
- // streaming parser gets stuck if skipEmptyLines and a step callback are both supplied.
111
- // See https://github.com/mholt/PapaParse/issues/465
112
- chunkSize: 1024 * 1024 * 5,
113
- // skipEmptyLines is set to a boolean value if supplied. Greedy is set to true
114
- // skipEmptyLines is handled manually given two bugs where the streaming parser gets stuck if
115
- // both of the skipEmptyLines and step callback options are provided:
116
- // - true doesn't work unless chunkSize is set: https://github.com/mholt/PapaParse/issues/465
117
- // - greedy doesn't work: https://github.com/mholt/PapaParse/issues/825
118
- skipEmptyLines: false,
119
- // step is called on every row
120
- // eslint-disable-next-line complexity
121
- step(results) {
122
- let row = results.data;
123
- if (csvOptions.skipEmptyLines) {
124
- // Manually reject lines that are empty
125
- const collapsedRow = row.flat().join('').trim();
126
- if (collapsedRow === '') {
127
- return;
128
- }
129
- }
130
- const bytesUsed = results.meta.cursor;
131
- // Check if we need to save a header row
132
- if (isFirstRow && !headerRow) {
133
- // Auto detects or can be forced with csvOptions.header
134
- const header = csvOptions.header === 'auto' ? isHeaderRow(row) : Boolean(csvOptions.header);
135
- if (header) {
136
- headerRow = row.map(duplicateColumnTransformer());
137
- return;
138
- }
139
- }
140
- // If first data row, we can deduce the schema
141
- if (isFirstRow) {
142
- isFirstRow = false;
143
- if (!headerRow) {
144
- headerRow = generateHeader(csvOptions.columnPrefix, row.length);
145
- }
146
- schema = deduceSchema(row, headerRow);
147
- }
148
- if (csvOptions.optimizeMemoryUsage) {
149
- // A workaround to allocate new strings and don't retain pointers to original strings.
150
- // https://bugs.chromium.org/p/v8/issues/detail?id=2869
151
- row = JSON.parse(JSON.stringify(row));
152
- }
153
- // Add the row
154
- tableBatchBuilder =
155
- tableBatchBuilder ||
156
- new schema_1.TableBatchBuilder(schema, {
157
- // @ts-expect-error
158
- shape: csvOptions.shape || 'array-row-table',
159
- ...options
160
- });
161
- try {
162
- tableBatchBuilder.addRow(row);
163
- // If a batch has been completed, emit it
164
- const batch = tableBatchBuilder && tableBatchBuilder.getFullBatch({ bytesUsed });
165
- if (batch) {
166
- asyncQueue.enqueue(batch);
167
- }
168
- }
169
- catch (error) {
170
- asyncQueue.enqueue(error);
171
- }
172
- },
173
- // complete is called when all rows have been read
174
- complete(results) {
175
- try {
176
- const bytesUsed = results.meta.cursor;
177
- // Ensure any final (partial) batch gets emitted
178
- const batch = tableBatchBuilder && tableBatchBuilder.getFinalBatch({ bytesUsed });
179
- if (batch) {
180
- asyncQueue.enqueue(batch);
181
- }
182
- }
183
- catch (error) {
184
- asyncQueue.enqueue(error);
185
- }
186
- asyncQueue.close();
187
- }
188
- };
189
- papaparse_1.default.parse(asyncIterator, config, async_iterator_streamer_1.default);
190
- // TODO - Does it matter if we return asyncIterable or asyncIterator
191
- // return asyncQueue[Symbol.asyncIterator]();
192
- return asyncQueue;
193
- }
194
- /**
195
- * Checks if a certain row is a header row
196
- * @param row the row to check
197
- * @returns true if the row looks like a header
198
- */
199
- function isHeaderRow(row) {
200
- return row && row.every((value) => typeof value === 'string');
201
- }
202
- /**
203
- * Reads, parses, and returns the first row of a CSV text
204
- * @param csvText the csv text to parse
205
- * @returns the first row
206
- */
207
- function readFirstRow(csvText) {
208
- const result = papaparse_1.default.parse(csvText, {
209
- download: false,
210
- dynamicTyping: true,
211
- preview: 1
212
- });
213
- return result.data[0];
214
- }
215
- /**
216
- * Creates a transformer that renames duplicate columns. This is needed as Papaparse doesn't handle
217
- * duplicate header columns and would use the latest occurrence by default.
218
- * See the header option in https://www.papaparse.com/docs#config
219
- * @returns a transform function that returns sanitized names for duplicate fields
220
- */
221
- function duplicateColumnTransformer() {
222
- const observedColumns = new Set();
223
- return (col) => {
224
- let colName = col;
225
- let counter = 1;
226
- while (observedColumns.has(colName)) {
227
- colName = `${col}.${counter}`;
228
- counter++;
229
- }
230
- observedColumns.add(colName);
231
- return colName;
232
- };
233
- }
234
- /**
235
- * Generates the header of a CSV given a prefix and a column count
236
- * @param columnPrefix the columnPrefix to use
237
- * @param count the count of column names to generate
238
- * @returns an array of column names
239
- */
240
- function generateHeader(columnPrefix, count = 0) {
241
- const headers = [];
242
- for (let i = 0; i < count; i++) {
243
- headers.push(`${columnPrefix}${i + 1}`);
244
- }
245
- return headers;
246
- }
247
- function deduceSchema(row, headerRow) {
248
- const schema = headerRow ? {} : [];
249
- for (let i = 0; i < row.length; i++) {
250
- const columnName = (headerRow && headerRow[i]) || i;
251
- const value = row[i];
252
- switch (typeof value) {
253
- case 'number':
254
- case 'boolean':
255
- // TODO - booleans could be handled differently...
256
- schema[columnName] = { name: String(columnName), index: i, type: Float32Array };
257
- break;
258
- case 'string':
259
- default:
260
- schema[columnName] = { name: String(columnName), index: i, type: Array };
261
- // We currently only handle numeric rows
262
- // TODO we could offer a function to map strings to numbers?
263
- }
264
- }
265
- return schema;
266
- }
267
- exports._typecheckCSVLoader = exports.CSVLoader;
@@ -1,6 +0,0 @@
1
- "use strict";
2
- /* @typedef {import('@loaders.gl/loader-utils').Writer} Writer */
3
- /*
4
- * CSV exporter
5
- * type {Writer}
6
- */
package/dist/index.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CSVLoader = void 0;
4
- var csv_loader_1 = require("./csv-loader");
5
- Object.defineProperty(exports, "CSVLoader", { enumerable: true, get: function () { return csv_loader_1.CSVLoader; } });
@@ -1,63 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- // A custom papaparse `Streamer` for async iterators
4
- // Ideally this can be contributed back to papaparse
5
- // Or papaparse can expose Streamer API so we can extend without forking.
6
- var __importDefault = (this && this.__importDefault) || function (mod) {
7
- return (mod && mod.__esModule) ? mod : { "default": mod };
8
- };
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- /* eslint-disable no-invalid-this */
11
- // Note: papaparse is not an ES6 module
12
- const papaparse_1 = __importDefault(require("./papaparse"));
13
- const { ChunkStreamer } = papaparse_1.default;
14
- function AsyncIteratorStreamer(config) {
15
- config = config || {};
16
- ChunkStreamer.call(this, config);
17
- this.textDecoder = new TextDecoder(this._config.encoding);
18
- // Implement ChunkStreamer base class methods
19
- // this.pause = function() {
20
- // ChunkStreamer.prototype.pause.apply(this, arguments);
21
- // };
22
- // this.resume = function() {
23
- // ChunkStreamer.prototype.resume.apply(this, arguments);
24
- // this._input.resume();
25
- // };
26
- this.stream = async function (asyncIterator) {
27
- this._input = asyncIterator;
28
- try {
29
- // ES2018 version
30
- // TODO - check for pause and abort flags?
31
- for await (const chunk of asyncIterator) {
32
- this.parseChunk(this.getStringChunk(chunk));
33
- }
34
- // ES5 VERSION
35
- // while (true) {
36
- // asyncIterator.next().then(function(value) {
37
- // if (value.done) {
38
- // // finalize iterator?
39
- // }
40
- // }
41
- // const = await ;
42
- // if (done) return total;
43
- // total += value.length;
44
- // }
45
- this._finished = true;
46
- this.parseChunk('');
47
- }
48
- catch (error) {
49
- // Inform ChunkStreamer base class of error
50
- this._sendError(error);
51
- }
52
- };
53
- this._nextChunk = function nextChunk() {
54
- // Left empty, as async iterator automatically pulls next chunk
55
- };
56
- // HELPER METHODS
57
- this.getStringChunk = function (chunk) {
58
- return typeof chunk === 'string' ? chunk : this.textDecoder.decode(chunk, { stream: true });
59
- };
60
- }
61
- exports.default = AsyncIteratorStreamer;
62
- AsyncIteratorStreamer.prototype = Object.create(ChunkStreamer.prototype);
63
- AsyncIteratorStreamer.prototype.constructor = AsyncIteratorStreamer;
@@ -1,935 +0,0 @@
1
- "use strict";
2
- // @ts-nocheck
3
- // This is a fork of papaparse
4
- // https://github.com/mholt/PapaParse
5
- /* @license
6
- Papa Parse
7
- v5.0.0-beta.0
8
- https://github.com/mholt/PapaParse
9
- License: MIT
10
- */
11
- // FORK SUMMARY:
12
- // - Adopt ES6 exports
13
- // - Implement new AsyncIteratorStreamer
14
- // - Remove non Async Iterator streamers (can all be handled by new streamer)
15
- // - Remove unused Worker support (loaders.gl worker system used instead)
16
- // - Remove unused jQuery plugin support
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- /* eslint-disable */
19
- const BYTE_ORDER_MARK = '\ufeff';
20
- const Papa = {
21
- parse: CsvToJson,
22
- unparse: JsonToCsv,
23
- RECORD_SEP: String.fromCharCode(30),
24
- UNIT_SEP: String.fromCharCode(31),
25
- BYTE_ORDER_MARK,
26
- BAD_DELIMITERS: ['\r', '\n', '"', BYTE_ORDER_MARK],
27
- WORKERS_SUPPORTED: false,
28
- NODE_STREAM_INPUT: 1,
29
- // Configurable chunk sizes for local and remote files, respectively
30
- LocalChunkSize: 1024 * 1024 * 10,
31
- RemoteChunkSize: 1024 * 1024 * 5,
32
- DefaultDelimiter: ',',
33
- // Exposed for testing and development only
34
- Parser: Parser,
35
- ParserHandle: ParserHandle,
36
- // BEGIN FORK
37
- ChunkStreamer: ChunkStreamer,
38
- StringStreamer: StringStreamer
39
- };
40
- exports.default = Papa;
41
- /*
42
- Papa.NetworkStreamer = NetworkStreamer;
43
- Papa.FileStreamer = FileStreamer;
44
- Papa.ReadableStreamStreamer = ReadableStreamStreamer;
45
- if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
46
- Papa.DuplexStreamStreamer = DuplexStreamStreamer;
47
- }
48
- */
49
- // END FORK
50
- // BEGIN FORK
51
- // Adds an argument to papa.parse
52
- // function CsvToJson(_input, _config)
53
- function CsvToJson(_input, _config, UserDefinedStreamer // BEGIN FORK
54
- ) {
55
- _config = _config || {};
56
- var dynamicTyping = _config.dynamicTyping || false;
57
- if (isFunction(dynamicTyping)) {
58
- _config.dynamicTypingFunction = dynamicTyping;
59
- // Will be filled on first row call
60
- dynamicTyping = {};
61
- }
62
- _config.dynamicTyping = dynamicTyping;
63
- _config.transform = isFunction(_config.transform) ? _config.transform : false;
64
- if (_config.worker && Papa.WORKERS_SUPPORTED) {
65
- var w = newWorker();
66
- w.userStep = _config.step;
67
- w.userChunk = _config.chunk;
68
- w.userComplete = _config.complete;
69
- w.userError = _config.error;
70
- _config.step = isFunction(_config.step);
71
- _config.chunk = isFunction(_config.chunk);
72
- _config.complete = isFunction(_config.complete);
73
- _config.error = isFunction(_config.error);
74
- delete _config.worker; // prevent infinite loop
75
- w.postMessage({
76
- input: _input,
77
- config: _config,
78
- workerId: w.id
79
- });
80
- return;
81
- }
82
- var streamer = null;
83
- /*
84
- if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined') {
85
- // create a node Duplex stream for use
86
- // with .pipe
87
- streamer = new DuplexStreamStreamer(_config);
88
- return streamer.getStream();
89
- } else
90
- */
91
- if (typeof _input === 'string') {
92
- // if (_config.download) streamer = new NetworkStreamer(_config);
93
- // else
94
- streamer = new StringStreamer(_config);
95
- }
96
- /*
97
- else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on)) {
98
- streamer = new ReadableStreamStreamer(_config);
99
- } else if ((globalThis.File && _input instanceof File) || _input instanceof Object)
100
- // ...Safari. (see issue #106)
101
- streamer = new FileStreamer(_config);
102
- */
103
- // BEGIN FORK
104
- if (!streamer) {
105
- streamer = new UserDefinedStreamer(_config);
106
- }
107
- // END FORK
108
- return streamer.stream(_input);
109
- }
110
- function JsonToCsv(_input, _config) {
111
- // Default configuration
112
- /** whether to surround every datum with quotes */
113
- var _quotes = false;
114
- /** whether to write headers */
115
- var _writeHeader = true;
116
- /** delimiting character(s) */
117
- var _delimiter = ',';
118
- /** newline character(s) */
119
- var _newline = '\r\n';
120
- /** quote character */
121
- var _quoteChar = '"';
122
- /** escaped quote character, either "" or <config.escapeChar>" */
123
- var _escapedQuote = _quoteChar + _quoteChar;
124
- /** whether to skip empty lines */
125
- var _skipEmptyLines = false;
126
- /** the columns (keys) we expect when we unparse objects */
127
- var _columns = null;
128
- unpackConfig();
129
- var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g');
130
- if (typeof _input === 'string')
131
- _input = JSON.parse(_input);
132
- if (Array.isArray(_input)) {
133
- if (!_input.length || Array.isArray(_input[0]))
134
- return serialize(null, _input, _skipEmptyLines);
135
- else if (typeof _input[0] === 'object')
136
- return serialize(_columns || objectKeys(_input[0]), _input, _skipEmptyLines);
137
- }
138
- else if (typeof _input === 'object') {
139
- if (typeof _input.data === 'string')
140
- _input.data = JSON.parse(_input.data);
141
- if (Array.isArray(_input.data)) {
142
- if (!_input.fields)
143
- _input.fields = _input.meta && _input.meta.fields;
144
- if (!_input.fields)
145
- _input.fields = Array.isArray(_input.data[0]) ? _input.fields : objectKeys(_input.data[0]);
146
- if (!Array.isArray(_input.data[0]) && typeof _input.data[0] !== 'object')
147
- _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf']
148
- }
149
- return serialize(_input.fields || [], _input.data || [], _skipEmptyLines);
150
- }
151
- // Default (any valid paths should return before this)
152
- throw new Error('Unable to serialize unrecognized input');
153
- function unpackConfig() {
154
- if (typeof _config !== 'object')
155
- return;
156
- if (typeof _config.delimiter === 'string' &&
157
- !Papa.BAD_DELIMITERS.filter(function (value) {
158
- return _config.delimiter.indexOf(value) !== -1;
159
- }).length) {
160
- _delimiter = _config.delimiter;
161
- }
162
- if (typeof _config.quotes === 'boolean' || Array.isArray(_config.quotes))
163
- _quotes = _config.quotes;
164
- if (typeof _config.skipEmptyLines === 'boolean' || typeof _config.skipEmptyLines === 'string')
165
- _skipEmptyLines = _config.skipEmptyLines;
166
- if (typeof _config.newline === 'string')
167
- _newline = _config.newline;
168
- if (typeof _config.quoteChar === 'string')
169
- _quoteChar = _config.quoteChar;
170
- if (typeof _config.header === 'boolean')
171
- _writeHeader = _config.header;
172
- if (Array.isArray(_config.columns)) {
173
- if (_config.columns.length === 0)
174
- throw new Error('Option columns is empty');
175
- _columns = _config.columns;
176
- }
177
- if (_config.escapeChar !== undefined) {
178
- _escapedQuote = _config.escapeChar + _quoteChar;
179
- }
180
- }
181
- /** Turns an object's keys into an array */
182
- function objectKeys(obj) {
183
- if (typeof obj !== 'object')
184
- return [];
185
- var keys = [];
186
- for (var key in obj)
187
- keys.push(key);
188
- return keys;
189
- }
190
- /** The double for loop that iterates the data and writes out a CSV string including header row */
191
- function serialize(fields, data, skipEmptyLines) {
192
- var csv = '';
193
- if (typeof fields === 'string')
194
- fields = JSON.parse(fields);
195
- if (typeof data === 'string')
196
- data = JSON.parse(data);
197
- var hasHeader = Array.isArray(fields) && fields.length > 0;
198
- var dataKeyedByField = !Array.isArray(data[0]);
199
- // If there a header row, write it first
200
- if (hasHeader && _writeHeader) {
201
- for (var i = 0; i < fields.length; i++) {
202
- if (i > 0)
203
- csv += _delimiter;
204
- csv += safe(fields[i], i);
205
- }
206
- if (data.length > 0)
207
- csv += _newline;
208
- }
209
- // Then write out the data
210
- for (var row = 0; row < data.length; row++) {
211
- var maxCol = hasHeader ? fields.length : data[row].length;
212
- var emptyLine = false;
213
- var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;
214
- if (skipEmptyLines && !hasHeader) {
215
- emptyLine =
216
- skipEmptyLines === 'greedy'
217
- ? data[row].join('').trim() === ''
218
- : data[row].length === 1 && data[row][0].length === 0;
219
- }
220
- if (skipEmptyLines === 'greedy' && hasHeader) {
221
- var line = [];
222
- for (var c = 0; c < maxCol; c++) {
223
- var cx = dataKeyedByField ? fields[c] : c;
224
- line.push(data[row][cx]);
225
- }
226
- emptyLine = line.join('').trim() === '';
227
- }
228
- if (!emptyLine) {
229
- for (var col = 0; col < maxCol; col++) {
230
- if (col > 0 && !nullLine)
231
- csv += _delimiter;
232
- var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
233
- csv += safe(data[row][colIdx], col);
234
- }
235
- if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine))) {
236
- csv += _newline;
237
- }
238
- }
239
- }
240
- return csv;
241
- }
242
- /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */
243
- function safe(str, col) {
244
- if (typeof str === 'undefined' || str === null)
245
- return '';
246
- if (str.constructor === Date)
247
- return JSON.stringify(str).slice(1, 25);
248
- str = str.toString().replace(quoteCharRegex, _escapedQuote);
249
- var needsQuotes = (typeof _quotes === 'boolean' && _quotes) ||
250
- (Array.isArray(_quotes) && _quotes[col]) ||
251
- hasAny(str, Papa.BAD_DELIMITERS) ||
252
- str.indexOf(_delimiter) > -1 ||
253
- str.charAt(0) === ' ' ||
254
- str.charAt(str.length - 1) === ' ';
255
- return needsQuotes ? _quoteChar + str + _quoteChar : str;
256
- }
257
- function hasAny(str, substrings) {
258
- for (var i = 0; i < substrings.length; i++)
259
- if (str.indexOf(substrings[i]) > -1)
260
- return true;
261
- return false;
262
- }
263
- }
264
- /** ChunkStreamer is the base prototype for various streamer implementations. */
265
- function ChunkStreamer(config) {
266
- this._handle = null;
267
- this._finished = false;
268
- this._completed = false;
269
- this._input = null;
270
- this._baseIndex = 0;
271
- this._partialLine = '';
272
- this._rowCount = 0;
273
- this._start = 0;
274
- this._nextChunk = null;
275
- this.isFirstChunk = true;
276
- this._completeResults = {
277
- data: [],
278
- errors: [],
279
- meta: {}
280
- };
281
- replaceConfig.call(this, config);
282
- this.parseChunk = function (chunk, isFakeChunk) {
283
- // First chunk pre-processing
284
- if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) {
285
- var modifiedChunk = this._config.beforeFirstChunk(chunk);
286
- if (modifiedChunk !== undefined)
287
- chunk = modifiedChunk;
288
- }
289
- this.isFirstChunk = false;
290
- // Rejoin the line we likely just split in two by chunking the file
291
- var aggregate = this._partialLine + chunk;
292
- this._partialLine = '';
293
- var results = this._handle.parse(aggregate, this._baseIndex, !this._finished);
294
- if (this._handle.paused() || this._handle.aborted())
295
- return;
296
- var lastIndex = results.meta.cursor;
297
- if (!this._finished) {
298
- this._partialLine = aggregate.substring(lastIndex - this._baseIndex);
299
- this._baseIndex = lastIndex;
300
- }
301
- if (results && results.data)
302
- this._rowCount += results.data.length;
303
- var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);
304
- if (isFunction(this._config.chunk) && !isFakeChunk) {
305
- this._config.chunk(results, this._handle);
306
- if (this._handle.paused() || this._handle.aborted())
307
- return;
308
- results = undefined;
309
- this._completeResults = undefined;
310
- }
311
- if (!this._config.step && !this._config.chunk) {
312
- this._completeResults.data = this._completeResults.data.concat(results.data);
313
- this._completeResults.errors = this._completeResults.errors.concat(results.errors);
314
- this._completeResults.meta = results.meta;
315
- }
316
- if (!this._completed &&
317
- finishedIncludingPreview &&
318
- isFunction(this._config.complete) &&
319
- (!results || !results.meta.aborted)) {
320
- this._config.complete(this._completeResults, this._input);
321
- this._completed = true;
322
- }
323
- if (!finishedIncludingPreview && (!results || !results.meta.paused))
324
- this._nextChunk();
325
- return results;
326
- };
327
- this._sendError = function (error) {
328
- if (isFunction(this._config.error))
329
- this._config.error(error);
330
- };
331
- function replaceConfig(config) {
332
- // Deep-copy the config so we can edit it
333
- var configCopy = copy(config);
334
- configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings!
335
- if (!config.step && !config.chunk)
336
- configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196
337
- this._handle = new ParserHandle(configCopy);
338
- this._handle.streamer = this;
339
- this._config = configCopy; // persist the copy to the caller
340
- }
341
- }
342
- function StringStreamer(config) {
343
- config = config || {};
344
- ChunkStreamer.call(this, config);
345
- var remaining;
346
- this.stream = function (s) {
347
- remaining = s;
348
- return this._nextChunk();
349
- };
350
- this._nextChunk = function () {
351
- if (this._finished)
352
- return;
353
- var size = this._config.chunkSize;
354
- var chunk = size ? remaining.substr(0, size) : remaining;
355
- remaining = size ? remaining.substr(size) : '';
356
- this._finished = !remaining;
357
- return this.parseChunk(chunk);
358
- };
359
- }
360
- StringStreamer.prototype = Object.create(StringStreamer.prototype);
361
- StringStreamer.prototype.constructor = StringStreamer;
362
- // Use one ParserHandle per entire CSV file or string
363
- function ParserHandle(_config) {
364
- // One goal is to minimize the use of regular expressions...
365
- var FLOAT = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i;
366
- 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))/;
367
- var self = this;
368
- var _stepCounter = 0; // Number of times step was called (number of rows parsed)
369
- var _rowCounter = 0; // Number of rows that have been parsed so far
370
- var _input; // The input being parsed
371
- var _parser; // The core parser being used
372
- var _paused = false; // Whether we are paused or not
373
- var _aborted = false; // Whether the parser has aborted or not
374
- var _delimiterError; // Temporary state between delimiter detection and processing results
375
- var _fields = []; // Fields are from the header row of the input, if there is one
376
- var _results = {
377
- // The last results returned from the parser
378
- data: [],
379
- errors: [],
380
- meta: {}
381
- };
382
- if (isFunction(_config.step)) {
383
- var userStep = _config.step;
384
- _config.step = function (results) {
385
- _results = results;
386
- if (needsHeaderRow())
387
- processResults();
388
- // only call user's step function after header row
389
- else {
390
- processResults();
391
- // It's possbile that this line was empty and there's no row here after all
392
- if (!_results.data || _results.data.length === 0)
393
- return;
394
- _stepCounter += results.data.length;
395
- if (_config.preview && _stepCounter > _config.preview)
396
- _parser.abort();
397
- else
398
- userStep(_results, self);
399
- }
400
- };
401
- }
402
- /**
403
- * Parses input. Most users won't need, and shouldn't mess with, the baseIndex
404
- * and ignoreLastRow parameters. They are used by streamers (wrapper functions)
405
- * when an input comes in multiple chunks, like from a file.
406
- */
407
- this.parse = function (input, baseIndex, ignoreLastRow) {
408
- var quoteChar = _config.quoteChar || '"';
409
- if (!_config.newline)
410
- _config.newline = guessLineEndings(input, quoteChar);
411
- _delimiterError = false;
412
- if (!_config.delimiter) {
413
- var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess);
414
- if (delimGuess.successful)
415
- _config.delimiter = delimGuess.bestDelimiter;
416
- else {
417
- _delimiterError = true; // add error after parsing (otherwise it would be overwritten)
418
- _config.delimiter = Papa.DefaultDelimiter;
419
- }
420
- _results.meta.delimiter = _config.delimiter;
421
- }
422
- else if (isFunction(_config.delimiter)) {
423
- _config.delimiter = _config.delimiter(input);
424
- _results.meta.delimiter = _config.delimiter;
425
- }
426
- var parserConfig = copy(_config);
427
- if (_config.preview && _config.header)
428
- parserConfig.preview++; // to compensate for header row
429
- _input = input;
430
- _parser = new Parser(parserConfig);
431
- _results = _parser.parse(_input, baseIndex, ignoreLastRow);
432
- processResults();
433
- return _paused ? { meta: { paused: true } } : _results || { meta: { paused: false } };
434
- };
435
- this.paused = function () {
436
- return _paused;
437
- };
438
- this.pause = function () {
439
- _paused = true;
440
- _parser.abort();
441
- _input = _input.substr(_parser.getCharIndex());
442
- };
443
- this.resume = function () {
444
- _paused = false;
445
- self.streamer.parseChunk(_input, true);
446
- };
447
- this.aborted = function () {
448
- return _aborted;
449
- };
450
- this.abort = function () {
451
- _aborted = true;
452
- _parser.abort();
453
- _results.meta.aborted = true;
454
- if (isFunction(_config.complete))
455
- _config.complete(_results);
456
- _input = '';
457
- };
458
- function testEmptyLine(s) {
459
- return _config.skipEmptyLines === 'greedy'
460
- ? s.join('').trim() === ''
461
- : s.length === 1 && s[0].length === 0;
462
- }
463
- function processResults() {
464
- if (_results && _delimiterError) {
465
- addError('Delimiter', 'UndetectableDelimiter', "Unable to auto-detect delimiting character; defaulted to '" + Papa.DefaultDelimiter + "'");
466
- _delimiterError = false;
467
- }
468
- if (_config.skipEmptyLines) {
469
- for (var i = 0; i < _results.data.length; i++)
470
- if (testEmptyLine(_results.data[i]))
471
- _results.data.splice(i--, 1);
472
- }
473
- if (needsHeaderRow())
474
- fillHeaderFields();
475
- return applyHeaderAndDynamicTypingAndTransformation();
476
- }
477
- function needsHeaderRow() {
478
- return _config.header && _fields.length === 0;
479
- }
480
- function fillHeaderFields() {
481
- if (!_results)
482
- return;
483
- function addHeder(header) {
484
- if (isFunction(_config.transformHeader))
485
- header = _config.transformHeader(header);
486
- _fields.push(header);
487
- }
488
- if (Array.isArray(_results.data[0])) {
489
- for (var i = 0; needsHeaderRow() && i < _results.data.length; i++)
490
- _results.data[i].forEach(addHeder);
491
- _results.data.splice(0, 1);
492
- }
493
- // if _results.data[0] is not an array, we are in a step where _results.data is the row.
494
- else
495
- _results.data.forEach(addHeder);
496
- }
497
- function shouldApplyDynamicTyping(field) {
498
- // Cache function values to avoid calling it for each row
499
- if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {
500
- _config.dynamicTyping[field] = _config.dynamicTypingFunction(field);
501
- }
502
- return (_config.dynamicTyping[field] || _config.dynamicTyping) === true;
503
- }
504
- function parseDynamic(field, value) {
505
- if (shouldApplyDynamicTyping(field)) {
506
- if (value === 'true' || value === 'TRUE')
507
- return true;
508
- else if (value === 'false' || value === 'FALSE')
509
- return false;
510
- else if (FLOAT.test(value))
511
- return parseFloat(value);
512
- else if (ISO_DATE.test(value))
513
- return new Date(value);
514
- else
515
- return value === '' ? null : value;
516
- }
517
- return value;
518
- }
519
- function applyHeaderAndDynamicTypingAndTransformation() {
520
- if (!_results ||
521
- !_results.data ||
522
- (!_config.header && !_config.dynamicTyping && !_config.transform))
523
- return _results;
524
- function processRow(rowSource, i) {
525
- var row = _config.header ? {} : [];
526
- var j;
527
- for (j = 0; j < rowSource.length; j++) {
528
- var field = j;
529
- var value = rowSource[j];
530
- if (_config.header)
531
- field = j >= _fields.length ? '__parsed_extra' : _fields[j];
532
- if (_config.transform)
533
- value = _config.transform(value, field);
534
- value = parseDynamic(field, value);
535
- if (field === '__parsed_extra') {
536
- row[field] = row[field] || [];
537
- row[field].push(value);
538
- }
539
- else
540
- row[field] = value;
541
- }
542
- if (_config.header) {
543
- if (j > _fields.length)
544
- addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
545
- else if (j < _fields.length)
546
- addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
547
- }
548
- return row;
549
- }
550
- var incrementBy = 1;
551
- if (!_results.data[0] || Array.isArray(_results.data[0])) {
552
- _results.data = _results.data.map(processRow);
553
- incrementBy = _results.data.length;
554
- }
555
- else
556
- _results.data = processRow(_results.data, 0);
557
- if (_config.header && _results.meta)
558
- _results.meta.fields = _fields;
559
- _rowCounter += incrementBy;
560
- return _results;
561
- }
562
- function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {
563
- var bestDelim, bestDelta, fieldCountPrevRow;
564
- delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];
565
- for (var i = 0; i < delimitersToGuess.length; i++) {
566
- var delim = delimitersToGuess[i];
567
- var delta = 0, avgFieldCount = 0, emptyLinesCount = 0;
568
- fieldCountPrevRow = undefined;
569
- var preview = new Parser({
570
- comments: comments,
571
- delimiter: delim,
572
- newline: newline,
573
- preview: 10
574
- }).parse(input);
575
- for (var j = 0; j < preview.data.length; j++) {
576
- if (skipEmptyLines && testEmptyLine(preview.data[j])) {
577
- emptyLinesCount++;
578
- continue;
579
- }
580
- var fieldCount = preview.data[j].length;
581
- avgFieldCount += fieldCount;
582
- if (typeof fieldCountPrevRow === 'undefined') {
583
- fieldCountPrevRow = 0;
584
- continue;
585
- }
586
- else if (fieldCount > 1) {
587
- delta += Math.abs(fieldCount - fieldCountPrevRow);
588
- fieldCountPrevRow = fieldCount;
589
- }
590
- }
591
- if (preview.data.length > 0)
592
- avgFieldCount /= preview.data.length - emptyLinesCount;
593
- if ((typeof bestDelta === 'undefined' || delta > bestDelta) && avgFieldCount > 1.99) {
594
- bestDelta = delta;
595
- bestDelim = delim;
596
- }
597
- }
598
- _config.delimiter = bestDelim;
599
- return {
600
- successful: !!bestDelim,
601
- bestDelimiter: bestDelim
602
- };
603
- }
604
- function guessLineEndings(input, quoteChar) {
605
- input = input.substr(0, 1024 * 1024); // max length 1 MB
606
- // Replace all the text inside quotes
607
- var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm');
608
- input = input.replace(re, '');
609
- var r = input.split('\r');
610
- var n = input.split('\n');
611
- var nAppearsFirst = n.length > 1 && n[0].length < r[0].length;
612
- if (r.length === 1 || nAppearsFirst)
613
- return '\n';
614
- var numWithN = 0;
615
- for (var i = 0; i < r.length; i++) {
616
- if (r[i][0] === '\n')
617
- numWithN++;
618
- }
619
- return numWithN >= r.length / 2 ? '\r\n' : '\r';
620
- }
621
- function addError(type, code, msg, row) {
622
- _results.errors.push({
623
- type: type,
624
- code: code,
625
- message: msg,
626
- row: row
627
- });
628
- }
629
- }
630
- /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
631
- function escapeRegExp(string) {
632
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
633
- }
634
- /** The core parser implements speedy and correct CSV parsing */
635
- function Parser(config) {
636
- // Unpack the config object
637
- config = config || {};
638
- var delim = config.delimiter;
639
- var newline = config.newline;
640
- var comments = config.comments;
641
- var step = config.step;
642
- var preview = config.preview;
643
- var fastMode = config.fastMode;
644
- var quoteChar;
645
- /** Allows for no quoteChar by setting quoteChar to undefined in config */
646
- if (config.quoteChar === undefined) {
647
- quoteChar = '"';
648
- }
649
- else {
650
- quoteChar = config.quoteChar;
651
- }
652
- var escapeChar = quoteChar;
653
- if (config.escapeChar !== undefined) {
654
- escapeChar = config.escapeChar;
655
- }
656
- // Delimiter must be valid
657
- if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1)
658
- delim = ',';
659
- // Comment character must be valid
660
- if (comments === delim)
661
- throw new Error('Comment character same as delimiter');
662
- else if (comments === true)
663
- comments = '#';
664
- else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1)
665
- comments = false;
666
- // Newline must be valid: \r, \n, or \r\n
667
- if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
668
- newline = '\n';
669
- // We're gonna need these at the Parser scope
670
- var cursor = 0;
671
- var aborted = false;
672
- this.parse = function (input, baseIndex, ignoreLastRow) {
673
- // For some reason, in Chrome, this speeds things up (!?)
674
- if (typeof input !== 'string')
675
- throw new Error('Input must be a string');
676
- // We don't need to compute some of these every time parse() is called,
677
- // but having them in a more local scope seems to perform better
678
- var inputLen = input.length, delimLen = delim.length, newlineLen = newline.length, commentsLen = comments.length;
679
- var stepIsFunction = isFunction(step);
680
- // Establish starting state
681
- cursor = 0;
682
- var data = [], errors = [], row = [], lastCursor = 0;
683
- if (!input)
684
- return returnable();
685
- if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) {
686
- var rows = input.split(newline);
687
- for (var i = 0; i < rows.length; i++) {
688
- row = rows[i];
689
- cursor += row.length;
690
- if (i !== rows.length - 1)
691
- cursor += newline.length;
692
- else if (ignoreLastRow)
693
- return returnable();
694
- if (comments && row.substr(0, commentsLen) === comments)
695
- continue;
696
- if (stepIsFunction) {
697
- data = [];
698
- pushRow(row.split(delim));
699
- doStep();
700
- if (aborted)
701
- return returnable();
702
- }
703
- else
704
- pushRow(row.split(delim));
705
- if (preview && i >= preview) {
706
- data = data.slice(0, preview);
707
- return returnable(true);
708
- }
709
- }
710
- return returnable();
711
- }
712
- var nextDelim = input.indexOf(delim, cursor);
713
- var nextNewline = input.indexOf(newline, cursor);
714
- var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');
715
- var quoteSearch;
716
- // Parser loop
717
- for (;;) {
718
- // Field has opening quote
719
- if (input[cursor] === quoteChar) {
720
- // Start our search for the closing quote where the cursor is
721
- quoteSearch = cursor;
722
- // Skip the opening quote
723
- cursor++;
724
- for (;;) {
725
- // Find closing quote
726
- quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
727
- //No other quotes are found - no other delimiters
728
- if (quoteSearch === -1) {
729
- if (!ignoreLastRow) {
730
- // No closing quote... what a pity
731
- errors.push({
732
- type: 'Quotes',
733
- code: 'MissingQuotes',
734
- message: 'Quoted field unterminated',
735
- row: data.length,
736
- index: cursor
737
- });
738
- }
739
- return finish();
740
- }
741
- // Closing quote at EOF
742
- if (quoteSearch === inputLen - 1) {
743
- var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
744
- return finish(value);
745
- }
746
- // If this quote is escaped, it's part of the data; skip it
747
- // If the quote character is the escape character, then check if the next character is the escape character
748
- if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) {
749
- quoteSearch++;
750
- continue;
751
- }
752
- // If the quote character is not the escape character, then check if the previous character was the escape character
753
- if (quoteChar !== escapeChar &&
754
- quoteSearch !== 0 &&
755
- input[quoteSearch - 1] === escapeChar) {
756
- continue;
757
- }
758
- // Check up to nextDelim or nextNewline, whichever is closest
759
- var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);
760
- var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);
761
- // Closing quote followed by delimiter or 'unnecessary spaces + delimiter'
762
- if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter] === delim) {
763
- row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
764
- cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
765
- nextDelim = input.indexOf(delim, cursor);
766
- nextNewline = input.indexOf(newline, cursor);
767
- if (stepIsFunction) {
768
- doStep();
769
- if (aborted)
770
- return returnable();
771
- }
772
- if (preview && data.length >= preview)
773
- return returnable(true);
774
- break;
775
- }
776
- var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
777
- // Closing quote followed by newline or 'unnecessary spaces + newLine'
778
- if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, newlineLen) === newline) {
779
- row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
780
- saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
781
- nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field
782
- if (stepIsFunction) {
783
- doStep();
784
- if (aborted)
785
- return returnable();
786
- }
787
- if (preview && data.length >= preview)
788
- return returnable(true);
789
- break;
790
- }
791
- // 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
792
- errors.push({
793
- type: 'Quotes',
794
- code: 'InvalidQuotes',
795
- message: 'Trailing quote on quoted field is malformed',
796
- row: data.length,
797
- index: cursor
798
- });
799
- quoteSearch++;
800
- continue;
801
- }
802
- if (stepIsFunction) {
803
- doStep();
804
- if (aborted)
805
- return returnable();
806
- }
807
- if (preview && data.length >= preview)
808
- return returnable(true);
809
- continue;
810
- }
811
- // Comment found at start of new line
812
- if (comments && row.length === 0 && input.substr(cursor, commentsLen) === comments) {
813
- if (nextNewline === -1)
814
- // Comment ends at EOF
815
- return returnable();
816
- cursor = nextNewline + newlineLen;
817
- nextNewline = input.indexOf(newline, cursor);
818
- nextDelim = input.indexOf(delim, cursor);
819
- continue;
820
- }
821
- // Next delimiter comes before next newline, so we've reached end of field
822
- if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) {
823
- row.push(input.substring(cursor, nextDelim));
824
- cursor = nextDelim + delimLen;
825
- nextDelim = input.indexOf(delim, cursor);
826
- continue;
827
- }
828
- // End of row
829
- if (nextNewline !== -1) {
830
- row.push(input.substring(cursor, nextNewline));
831
- saveRow(nextNewline + newlineLen);
832
- if (stepIsFunction) {
833
- doStep();
834
- if (aborted)
835
- return returnable();
836
- }
837
- if (preview && data.length >= preview)
838
- return returnable(true);
839
- continue;
840
- }
841
- break;
842
- }
843
- return finish();
844
- function pushRow(row) {
845
- data.push(row);
846
- lastCursor = cursor;
847
- }
848
- /**
849
- * checks if there are extra spaces after closing quote and given index without any text
850
- * if Yes, returns the number of spaces
851
- */
852
- function extraSpaces(index) {
853
- var spaceLength = 0;
854
- if (index !== -1) {
855
- var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
856
- if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
857
- spaceLength = textBetweenClosingQuoteAndIndex.length;
858
- }
859
- }
860
- return spaceLength;
861
- }
862
- /**
863
- * Appends the remaining input from cursor to the end into
864
- * row, saves the row, calls step, and returns the results.
865
- */
866
- function finish(value) {
867
- if (ignoreLastRow)
868
- return returnable();
869
- if (typeof value === 'undefined')
870
- value = input.substr(cursor);
871
- row.push(value);
872
- cursor = inputLen; // important in case parsing is paused
873
- pushRow(row);
874
- if (stepIsFunction)
875
- doStep();
876
- return returnable();
877
- }
878
- /**
879
- * Appends the current row to the results. It sets the cursor
880
- * to newCursor and finds the nextNewline. The caller should
881
- * take care to execute user's step function and check for
882
- * preview and end parsing if necessary.
883
- */
884
- function saveRow(newCursor) {
885
- cursor = newCursor;
886
- pushRow(row);
887
- row = [];
888
- nextNewline = input.indexOf(newline, cursor);
889
- }
890
- /** Returns an object with the results, errors, and meta. */
891
- function returnable(stopped, step) {
892
- var isStep = step || false;
893
- return {
894
- data: isStep ? data[0] : data,
895
- errors: errors,
896
- meta: {
897
- delimiter: delim,
898
- linebreak: newline,
899
- aborted: aborted,
900
- truncated: !!stopped,
901
- cursor: lastCursor + (baseIndex || 0)
902
- }
903
- };
904
- }
905
- /** Executes the user's step function and resets data & errors. */
906
- function doStep() {
907
- step(returnable(undefined, true));
908
- data = [];
909
- errors = [];
910
- }
911
- };
912
- /** Sets the abort flag */
913
- this.abort = function () {
914
- aborted = true;
915
- };
916
- /** Gets the cursor position */
917
- this.getCharIndex = function () {
918
- return cursor;
919
- };
920
- }
921
- function notImplemented() {
922
- throw new Error('Not implemented.');
923
- }
924
- /** Makes a deep copy of an array or object (mostly) */
925
- function copy(obj) {
926
- if (typeof obj !== 'object' || obj === null)
927
- return obj;
928
- var cpy = Array.isArray(obj) ? [] : {};
929
- for (var key in obj)
930
- cpy[key] = copy(obj[key]);
931
- return cpy;
932
- }
933
- function isFunction(func) {
934
- return typeof func === 'function';
935
- }