@loaders.gl/csv 4.3.1 → 4.4.0-alpha.1
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.
- package/dist/csv-arrow-loader.d.ts +37 -0
- package/dist/csv-arrow-loader.d.ts.map +1 -0
- package/dist/csv-arrow-loader.js +23 -0
- package/dist/csv-format.d.ts +10 -0
- package/dist/csv-format.d.ts.map +1 -0
- package/dist/csv-format.js +12 -0
- package/dist/csv-loader.d.ts +6 -6
- package/dist/csv-loader.d.ts.map +1 -1
- package/dist/csv-loader.js +53 -20
- package/dist/csv-writer.d.ts +6 -5
- package/dist/csv-writer.d.ts.map +1 -1
- package/dist/csv-writer.js +2 -5
- package/dist/dist.dev.js +13318 -449
- package/dist/dist.min.js +23 -20
- package/dist/index.cjs +317 -262
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/lib/encoders/encode-csv.d.ts +1 -1
- package/dist/lib/encoders/encode-csv.d.ts.map +1 -1
- package/dist/lib/encoders/encode-csv.js +1 -1
- package/dist/papaparse/async-iterator-streamer.d.ts +1 -21
- package/dist/papaparse/async-iterator-streamer.d.ts.map +1 -1
- package/dist/papaparse/async-iterator-streamer.js +6 -6
- package/dist/papaparse/papa-constants.d.ts +12 -0
- package/dist/papaparse/papa-constants.d.ts.map +1 -0
- package/dist/papaparse/papa-constants.js +19 -0
- package/dist/papaparse/papa-parser.d.ts +110 -0
- package/dist/papaparse/papa-parser.d.ts.map +1 -0
- package/dist/papaparse/papa-parser.js +733 -0
- package/dist/papaparse/papa-writer.d.ts +22 -0
- package/dist/papaparse/papa-writer.d.ts.map +1 -0
- package/dist/papaparse/papa-writer.js +166 -0
- package/dist/papaparse/papaparse.d.ts +9 -113
- package/dist/papaparse/papaparse.d.ts.map +1 -1
- package/dist/papaparse/papaparse.js +13 -882
- package/package.json +5 -5
- package/src/csv-arrow-loader.ts +41 -0
- package/src/csv-format.ts +15 -0
- package/src/csv-loader.ts +58 -25
- package/src/csv-writer.ts +2 -5
- package/src/index.ts +3 -0
- package/src/lib/encoders/encode-csv.ts +2 -1
- package/src/papaparse/async-iterator-streamer.ts +6 -6
- package/src/papaparse/papa-constants.ts +23 -0
- package/src/papaparse/papa-parser.ts +872 -0
- package/src/papaparse/papa-writer.ts +219 -0
- package/src/papaparse/papaparse.ts +17 -1048
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
// loaders.gl
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
// Copyright (c) vis.gl contributors
|
|
4
|
+
// Copyright (c) 2015 Matthew Holt
|
|
5
|
+
// This is a fork of papaparse v5.0.0-beta.0 under MIT license
|
|
6
|
+
// https://github.com/mholt/PapaParse
|
|
7
|
+
/* eslint-disable no-continue, max-depth */
|
|
8
|
+
import { Papa } from "./papa-constants.js";
|
|
9
|
+
// const defaultConfig: Required<CSVParserConfig> = {
|
|
10
|
+
// dynamicTyping: false,
|
|
11
|
+
// dynamicTypingFunction: undefined!,
|
|
12
|
+
// transform: false
|
|
13
|
+
// };
|
|
14
|
+
export function CsvToJson(_input, _config = {}, Streamer = StringStreamer) {
|
|
15
|
+
const streamer = new Streamer(_config);
|
|
16
|
+
return streamer.stream(_input);
|
|
17
|
+
}
|
|
18
|
+
/** ChunkStreamer is the base prototype for various streamer implementations. */
|
|
19
|
+
export class ChunkStreamer {
|
|
20
|
+
_handle;
|
|
21
|
+
_config;
|
|
22
|
+
_finished = false;
|
|
23
|
+
_completed = false;
|
|
24
|
+
_input = null;
|
|
25
|
+
_baseIndex = 0;
|
|
26
|
+
_partialLine = '';
|
|
27
|
+
_rowCount = 0;
|
|
28
|
+
_start = 0;
|
|
29
|
+
isFirstChunk = true;
|
|
30
|
+
_completeResults = {
|
|
31
|
+
data: [],
|
|
32
|
+
errors: [],
|
|
33
|
+
meta: {}
|
|
34
|
+
};
|
|
35
|
+
constructor(config) {
|
|
36
|
+
// Deep-copy the config so we can edit it
|
|
37
|
+
const configCopy = { ...config };
|
|
38
|
+
if (configCopy.dynamicTypingFunction) {
|
|
39
|
+
configCopy.dynamicTyping = {};
|
|
40
|
+
}
|
|
41
|
+
// @ts-expect-error
|
|
42
|
+
configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings!
|
|
43
|
+
if (!config.step && !config.chunk) {
|
|
44
|
+
configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196
|
|
45
|
+
}
|
|
46
|
+
this._handle = new ParserHandle(configCopy);
|
|
47
|
+
this._handle.streamer = this;
|
|
48
|
+
this._config = configCopy; // persist the copy to the caller
|
|
49
|
+
}
|
|
50
|
+
// eslint-disable-next-line complexity, max-statements
|
|
51
|
+
parseChunk(chunk, isFakeChunk) {
|
|
52
|
+
// First chunk pre-processing
|
|
53
|
+
if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) {
|
|
54
|
+
const modifiedChunk = this._config.beforeFirstChunk(chunk);
|
|
55
|
+
if (modifiedChunk !== undefined)
|
|
56
|
+
chunk = modifiedChunk;
|
|
57
|
+
}
|
|
58
|
+
this.isFirstChunk = false;
|
|
59
|
+
// Rejoin the line we likely just split in two by chunking the file
|
|
60
|
+
const aggregate = this._partialLine + chunk;
|
|
61
|
+
this._partialLine = '';
|
|
62
|
+
let results = this._handle.parse(aggregate, this._baseIndex, !this._finished);
|
|
63
|
+
if (this._handle.paused() || this._handle.aborted())
|
|
64
|
+
return;
|
|
65
|
+
const lastIndex = results.meta.cursor;
|
|
66
|
+
if (!this._finished) {
|
|
67
|
+
this._partialLine = aggregate.substring(lastIndex - this._baseIndex);
|
|
68
|
+
this._baseIndex = lastIndex;
|
|
69
|
+
}
|
|
70
|
+
if (results && results.data)
|
|
71
|
+
this._rowCount += results.data.length;
|
|
72
|
+
const finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);
|
|
73
|
+
if (isFunction(this._config.chunk) && !isFakeChunk) {
|
|
74
|
+
this._config.chunk(results, this._handle);
|
|
75
|
+
if (this._handle.paused() || this._handle.aborted())
|
|
76
|
+
return;
|
|
77
|
+
results = undefined;
|
|
78
|
+
// @ts-expect-error
|
|
79
|
+
this._completeResults = undefined;
|
|
80
|
+
}
|
|
81
|
+
if (!this._config.step && !this._config.chunk) {
|
|
82
|
+
this._completeResults.data = this._completeResults.data.concat(results.data);
|
|
83
|
+
this._completeResults.errors = this._completeResults.errors.concat(results.errors);
|
|
84
|
+
this._completeResults.meta = results.meta;
|
|
85
|
+
}
|
|
86
|
+
if (!this._completed &&
|
|
87
|
+
finishedIncludingPreview &&
|
|
88
|
+
isFunction(this._config.complete) &&
|
|
89
|
+
(!results || !results.meta.aborted)) {
|
|
90
|
+
this._config.complete(this._completeResults, this._input);
|
|
91
|
+
this._completed = true;
|
|
92
|
+
}
|
|
93
|
+
// if (!finishedIncludingPreview && (!results || !results.meta.paused)) this._nextChunk();
|
|
94
|
+
// eslint-disable-next-line consistent-return
|
|
95
|
+
return results;
|
|
96
|
+
}
|
|
97
|
+
_sendError(error) {
|
|
98
|
+
if (isFunction(this._config.error))
|
|
99
|
+
this._config.error(error);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
class StringStreamer extends ChunkStreamer {
|
|
103
|
+
remaining;
|
|
104
|
+
constructor(config = {}) {
|
|
105
|
+
super(config);
|
|
106
|
+
}
|
|
107
|
+
stream(s) {
|
|
108
|
+
this.remaining = s;
|
|
109
|
+
return this._nextChunk();
|
|
110
|
+
}
|
|
111
|
+
_nextChunk() {
|
|
112
|
+
if (this._finished)
|
|
113
|
+
return;
|
|
114
|
+
const size = this._config.chunkSize;
|
|
115
|
+
const chunk = size ? this.remaining.substr(0, size) : this.remaining;
|
|
116
|
+
this.remaining = size ? this.remaining.substr(size) : '';
|
|
117
|
+
this._finished = !this.remaining;
|
|
118
|
+
// eslint-disable-next-line consistent-return
|
|
119
|
+
return this.parseChunk(chunk);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const FLOAT = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i;
|
|
123
|
+
const 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))/;
|
|
124
|
+
// Use one ParserHandle per entire CSV file or string
|
|
125
|
+
export class ParserHandle {
|
|
126
|
+
_config;
|
|
127
|
+
/** Number of times step was called (number of rows parsed) */
|
|
128
|
+
_stepCounter = 0;
|
|
129
|
+
/** Number of rows that have been parsed so far */
|
|
130
|
+
_rowCounter = 0;
|
|
131
|
+
/** The input being parsed */
|
|
132
|
+
_input;
|
|
133
|
+
/** The core parser being used */
|
|
134
|
+
_parser;
|
|
135
|
+
/** Whether we are paused or not */
|
|
136
|
+
_paused = false;
|
|
137
|
+
/** Whether the parser has aborted or not */
|
|
138
|
+
_aborted = false;
|
|
139
|
+
/** Temporary state between delimiter detection and processing results */
|
|
140
|
+
_delimiterError = false;
|
|
141
|
+
/** Fields are from the header row of the input, if there is one */
|
|
142
|
+
_fields = [];
|
|
143
|
+
/** The last results returned from the parser */
|
|
144
|
+
_results = {
|
|
145
|
+
data: [],
|
|
146
|
+
errors: [],
|
|
147
|
+
meta: {}
|
|
148
|
+
};
|
|
149
|
+
constructor(_config) {
|
|
150
|
+
// One goal is to minimize the use of regular expressions...
|
|
151
|
+
if (isFunction(_config.step)) {
|
|
152
|
+
const userStep = _config.step;
|
|
153
|
+
_config.step = (results) => {
|
|
154
|
+
this._results = results;
|
|
155
|
+
if (this.needsHeaderRow()) {
|
|
156
|
+
this.processResults();
|
|
157
|
+
}
|
|
158
|
+
// only call user's step function after header row
|
|
159
|
+
else {
|
|
160
|
+
this.processResults();
|
|
161
|
+
// It's possbile that this line was empty and there's no row here after all
|
|
162
|
+
if (!this._results.data || this._results.data.length === 0)
|
|
163
|
+
return;
|
|
164
|
+
this._stepCounter += results.data.length;
|
|
165
|
+
if (_config.preview && this._stepCounter > _config.preview) {
|
|
166
|
+
this._parser.abort();
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
userStep(this._results, this);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
this._config = _config;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Parses input. Most users won't need, and shouldn't mess with, the baseIndex
|
|
178
|
+
* and ignoreLastRow parameters. They are used by streamers (wrapper functions)
|
|
179
|
+
* when an input comes in multiple chunks, like from a file.
|
|
180
|
+
*/
|
|
181
|
+
parse(input, baseIndex, ignoreLastRow) {
|
|
182
|
+
const quoteChar = this._config.quoteChar || '"';
|
|
183
|
+
if (!this._config.newline)
|
|
184
|
+
this._config.newline = guessLineEndings(input, quoteChar);
|
|
185
|
+
this._delimiterError = false;
|
|
186
|
+
if (!this._config.delimiter) {
|
|
187
|
+
const delimGuess = this.guessDelimiter(input, this._config.newline, this._config.skipEmptyLines, this._config.comments, this._config.delimitersToGuess);
|
|
188
|
+
if (delimGuess.successful) {
|
|
189
|
+
this._config.delimiter = delimGuess.bestDelimiter;
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
this._delimiterError = true; // add error after parsing (otherwise it would be overwritten)
|
|
193
|
+
this._config.delimiter = Papa.DefaultDelimiter;
|
|
194
|
+
}
|
|
195
|
+
this._results.meta.delimiter = this._config.delimiter;
|
|
196
|
+
}
|
|
197
|
+
else if (isFunction(this._config.delimiter)) {
|
|
198
|
+
this._config.delimiter = this._config.delimiter(input);
|
|
199
|
+
this._results.meta.delimiter = this._config.delimiter;
|
|
200
|
+
}
|
|
201
|
+
const parserConfig = copy(this._config);
|
|
202
|
+
if (this._config.preview && this._config.header)
|
|
203
|
+
parserConfig.preview++; // to compensate for header row
|
|
204
|
+
this._input = input;
|
|
205
|
+
this._parser = new Parser(parserConfig);
|
|
206
|
+
this._results = this._parser.parse(this._input, baseIndex, ignoreLastRow);
|
|
207
|
+
this.processResults();
|
|
208
|
+
return this._paused ? { meta: { paused: true } } : this._results || { meta: { paused: false } };
|
|
209
|
+
}
|
|
210
|
+
paused() {
|
|
211
|
+
return this._paused;
|
|
212
|
+
}
|
|
213
|
+
pause() {
|
|
214
|
+
this._paused = true;
|
|
215
|
+
this._parser.abort();
|
|
216
|
+
this._input = this._input.substr(this._parser.getCharIndex());
|
|
217
|
+
}
|
|
218
|
+
resume() {
|
|
219
|
+
this._paused = false;
|
|
220
|
+
// @ts-expect-error
|
|
221
|
+
this.streamer.parseChunk(this._input, true);
|
|
222
|
+
}
|
|
223
|
+
aborted() {
|
|
224
|
+
return this._aborted;
|
|
225
|
+
}
|
|
226
|
+
abort() {
|
|
227
|
+
this._aborted = true;
|
|
228
|
+
this._parser.abort();
|
|
229
|
+
this._results.meta.aborted = true;
|
|
230
|
+
if (isFunction(this._config.complete)) {
|
|
231
|
+
this._config.complete(this._results);
|
|
232
|
+
}
|
|
233
|
+
this._input = '';
|
|
234
|
+
}
|
|
235
|
+
testEmptyLine(s) {
|
|
236
|
+
return this._config.skipEmptyLines === 'greedy'
|
|
237
|
+
? s.join('').trim() === ''
|
|
238
|
+
: s.length === 1 && s[0].length === 0;
|
|
239
|
+
}
|
|
240
|
+
processResults() {
|
|
241
|
+
if (this._results && this._delimiterError) {
|
|
242
|
+
this.addError('Delimiter', 'UndetectableDelimiter', `Unable to auto-detect delimiting character; defaulted to '${Papa.DefaultDelimiter}'`);
|
|
243
|
+
this._delimiterError = false;
|
|
244
|
+
}
|
|
245
|
+
if (this._config.skipEmptyLines) {
|
|
246
|
+
for (let i = 0; i < this._results.data.length; i++)
|
|
247
|
+
if (this.testEmptyLine(this._results.data[i]))
|
|
248
|
+
this._results.data.splice(i--, 1);
|
|
249
|
+
}
|
|
250
|
+
if (this.needsHeaderRow()) {
|
|
251
|
+
this.fillHeaderFields();
|
|
252
|
+
}
|
|
253
|
+
return this.applyHeaderAndDynamicTypingAndTransformation();
|
|
254
|
+
}
|
|
255
|
+
needsHeaderRow() {
|
|
256
|
+
return this._config.header && this._fields.length === 0;
|
|
257
|
+
}
|
|
258
|
+
fillHeaderFields() {
|
|
259
|
+
if (!this._results)
|
|
260
|
+
return;
|
|
261
|
+
const addHeder = (header) => {
|
|
262
|
+
if (isFunction(this._config.transformHeader))
|
|
263
|
+
header = this._config.transformHeader(header);
|
|
264
|
+
this._fields.push(header);
|
|
265
|
+
};
|
|
266
|
+
if (Array.isArray(this._results.data[0])) {
|
|
267
|
+
for (let i = 0; this.needsHeaderRow() && i < this._results.data.length; i++)
|
|
268
|
+
this._results.data[i].forEach(addHeder);
|
|
269
|
+
this._results.data.splice(0, 1);
|
|
270
|
+
}
|
|
271
|
+
// if _results.data[0] is not an array, we are in a step where _results.data is the row.
|
|
272
|
+
else {
|
|
273
|
+
this._results.data.forEach(addHeder);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
shouldApplyDynamicTyping(field) {
|
|
277
|
+
// Cache function values to avoid calling it for each row
|
|
278
|
+
if (this._config.dynamicTypingFunction && this._config.dynamicTyping?.[field] === undefined) {
|
|
279
|
+
this._config.dynamicTyping[field] = this._config.dynamicTypingFunction(field);
|
|
280
|
+
}
|
|
281
|
+
return (this._config.dynamicTyping?.[field] || this._config.dynamicTyping) === true;
|
|
282
|
+
}
|
|
283
|
+
parseDynamic(field, value) {
|
|
284
|
+
if (this.shouldApplyDynamicTyping(field)) {
|
|
285
|
+
if (value === 'true' || value === 'TRUE')
|
|
286
|
+
return true;
|
|
287
|
+
else if (value === 'false' || value === 'FALSE')
|
|
288
|
+
return false;
|
|
289
|
+
else if (FLOAT.test(value))
|
|
290
|
+
return parseFloat(value);
|
|
291
|
+
else if (ISO_DATE.test(value))
|
|
292
|
+
return new Date(value);
|
|
293
|
+
return value === '' ? null : value;
|
|
294
|
+
}
|
|
295
|
+
return value;
|
|
296
|
+
}
|
|
297
|
+
applyHeaderAndDynamicTypingAndTransformation() {
|
|
298
|
+
if (!this._results ||
|
|
299
|
+
!this._results.data ||
|
|
300
|
+
(!this._config.header && !this._config.dynamicTyping && !this._config.transform)) {
|
|
301
|
+
return this._results;
|
|
302
|
+
}
|
|
303
|
+
let incrementBy = 1;
|
|
304
|
+
if (!this._results.data[0] || Array.isArray(this._results.data[0])) {
|
|
305
|
+
this._results.data = this._results.data.map(this.processRow.bind(this));
|
|
306
|
+
incrementBy = this._results.data.length;
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
// @ts-expect-error
|
|
310
|
+
this._results.data = this.processRow(this._results.data, 0);
|
|
311
|
+
}
|
|
312
|
+
if (this._config.header && this._results.meta)
|
|
313
|
+
this._results.meta.fields = this._fields;
|
|
314
|
+
this._rowCounter += incrementBy;
|
|
315
|
+
return this._results;
|
|
316
|
+
}
|
|
317
|
+
processRow(rowSource, i) {
|
|
318
|
+
const row = this._config.header ? {} : [];
|
|
319
|
+
let j;
|
|
320
|
+
for (j = 0; j < rowSource.length; j++) {
|
|
321
|
+
let field = j;
|
|
322
|
+
let value = rowSource[j];
|
|
323
|
+
if (this._config.header)
|
|
324
|
+
field = j >= this._fields.length ? '__parsed_extra' : this._fields[j];
|
|
325
|
+
if (this._config.transform)
|
|
326
|
+
value = this._config.transform(value, field);
|
|
327
|
+
value = this.parseDynamic(field, value);
|
|
328
|
+
if (field === '__parsed_extra') {
|
|
329
|
+
row[field] = row[field] || [];
|
|
330
|
+
row[field].push(value);
|
|
331
|
+
}
|
|
332
|
+
else
|
|
333
|
+
row[field] = value;
|
|
334
|
+
}
|
|
335
|
+
if (this._config.header) {
|
|
336
|
+
if (j > this._fields.length)
|
|
337
|
+
this.addError('FieldMismatch', 'TooManyFields', `Too many fields: expected ${this._fields.length} fields but parsed ${j}`, this._rowCounter + i);
|
|
338
|
+
else if (j < this._fields.length)
|
|
339
|
+
this.addError('FieldMismatch', 'TooFewFields', `Too few fields: expected ${this._fields.length} fields but parsed ${j}`, this._rowCounter + i);
|
|
340
|
+
}
|
|
341
|
+
return row;
|
|
342
|
+
}
|
|
343
|
+
// eslint-disable-next-line complexity, max-statements
|
|
344
|
+
guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {
|
|
345
|
+
let bestDelim;
|
|
346
|
+
let bestDelta;
|
|
347
|
+
let fieldCountPrevRow;
|
|
348
|
+
delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];
|
|
349
|
+
for (let i = 0; i < delimitersToGuess.length; i++) {
|
|
350
|
+
const delim = delimitersToGuess[i];
|
|
351
|
+
let avgFieldCount = 0;
|
|
352
|
+
let delta = 0;
|
|
353
|
+
let emptyLinesCount = 0;
|
|
354
|
+
fieldCountPrevRow = undefined;
|
|
355
|
+
const preview = new Parser({
|
|
356
|
+
comments,
|
|
357
|
+
delimiter: delim,
|
|
358
|
+
newline,
|
|
359
|
+
preview: 10
|
|
360
|
+
}).parse(input);
|
|
361
|
+
for (let j = 0; j < preview.data.length; j++) {
|
|
362
|
+
if (skipEmptyLines && this.testEmptyLine(preview.data[j])) {
|
|
363
|
+
emptyLinesCount++;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const fieldCount = preview.data[j].length;
|
|
367
|
+
avgFieldCount += fieldCount;
|
|
368
|
+
if (typeof fieldCountPrevRow === 'undefined') {
|
|
369
|
+
fieldCountPrevRow = 0;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
else if (fieldCount > 1) {
|
|
373
|
+
delta += Math.abs(fieldCount - fieldCountPrevRow);
|
|
374
|
+
fieldCountPrevRow = fieldCount;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (preview.data.length > 0)
|
|
378
|
+
avgFieldCount /= preview.data.length - emptyLinesCount;
|
|
379
|
+
if ((typeof bestDelta === 'undefined' || delta > bestDelta) && avgFieldCount > 1.99) {
|
|
380
|
+
bestDelta = delta;
|
|
381
|
+
bestDelim = delim;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
this._config.delimiter = bestDelim;
|
|
385
|
+
return {
|
|
386
|
+
successful: Boolean(bestDelim),
|
|
387
|
+
bestDelimiter: bestDelim
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
addError(type, code, msg, row) {
|
|
391
|
+
this._results.errors.push({
|
|
392
|
+
type,
|
|
393
|
+
code,
|
|
394
|
+
message: msg,
|
|
395
|
+
row
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function guessLineEndings(input, quoteChar) {
|
|
400
|
+
input = input.substr(0, 1024 * 1024); // max length 1 MB
|
|
401
|
+
// Replace all the text inside quotes
|
|
402
|
+
const re = new RegExp(`${escapeRegExp(quoteChar)}([^]*?)${escapeRegExp(quoteChar)}`, 'gm');
|
|
403
|
+
input = input.replace(re, '');
|
|
404
|
+
const r = input.split('\r');
|
|
405
|
+
const n = input.split('\n');
|
|
406
|
+
const nAppearsFirst = n.length > 1 && n[0].length < r[0].length;
|
|
407
|
+
if (r.length === 1 || nAppearsFirst)
|
|
408
|
+
return '\n';
|
|
409
|
+
let numWithN = 0;
|
|
410
|
+
for (let i = 0; i < r.length; i++) {
|
|
411
|
+
if (r[i][0] === '\n')
|
|
412
|
+
numWithN++;
|
|
413
|
+
}
|
|
414
|
+
return numWithN >= r.length / 2 ? '\r\n' : '\r';
|
|
415
|
+
}
|
|
416
|
+
/** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
|
|
417
|
+
function escapeRegExp(string) {
|
|
418
|
+
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
|
419
|
+
}
|
|
420
|
+
/** The core parser implements speedy and correct CSV parsing */
|
|
421
|
+
// eslint-disable-next-line complexity, max-statements
|
|
422
|
+
export function Parser(config = {}) {
|
|
423
|
+
// Unpack the config object
|
|
424
|
+
let delim = config.delimiter;
|
|
425
|
+
let newline = config.newline;
|
|
426
|
+
let comments = config.comments;
|
|
427
|
+
const step = config.step;
|
|
428
|
+
const preview = config.preview;
|
|
429
|
+
const fastMode = config.fastMode;
|
|
430
|
+
let quoteChar;
|
|
431
|
+
/** Allows for no quoteChar by setting quoteChar to undefined in config */
|
|
432
|
+
if (config.quoteChar === undefined) {
|
|
433
|
+
quoteChar = '"';
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
quoteChar = config.quoteChar;
|
|
437
|
+
}
|
|
438
|
+
let escapeChar = quoteChar;
|
|
439
|
+
if (config.escapeChar !== undefined) {
|
|
440
|
+
escapeChar = config.escapeChar;
|
|
441
|
+
}
|
|
442
|
+
// Delimiter must be valid
|
|
443
|
+
if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1)
|
|
444
|
+
delim = ',';
|
|
445
|
+
// Comment character must be valid
|
|
446
|
+
if (comments === delim) {
|
|
447
|
+
throw new Error('Comment character same as delimiter');
|
|
448
|
+
}
|
|
449
|
+
else if (comments === true) {
|
|
450
|
+
comments = '#';
|
|
451
|
+
}
|
|
452
|
+
else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1) {
|
|
453
|
+
comments = false;
|
|
454
|
+
}
|
|
455
|
+
// Newline must be valid: \r, \n, or \r\n
|
|
456
|
+
if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
|
|
457
|
+
newline = '\n';
|
|
458
|
+
// We're gonna need these at the Parser scope
|
|
459
|
+
let cursor = 0;
|
|
460
|
+
let aborted = false;
|
|
461
|
+
// @ts-expect-error
|
|
462
|
+
// eslint-disable-next-line complexity, max-statements
|
|
463
|
+
this.parse = function (input, baseIndex, ignoreLastRow) {
|
|
464
|
+
// For some reason, in Chrome, this speeds things up (!?)
|
|
465
|
+
if (typeof input !== 'string')
|
|
466
|
+
throw new Error('Input must be a string');
|
|
467
|
+
// We don't need to compute some of these every time parse() is called,
|
|
468
|
+
// but having them in a more local scope seems to perform better
|
|
469
|
+
const inputLen = input.length;
|
|
470
|
+
const delimLen = delim.length;
|
|
471
|
+
const newlineLen = newline.length;
|
|
472
|
+
// @ts-expect-error
|
|
473
|
+
const commentsLen = comments.length;
|
|
474
|
+
const stepIsFunction = isFunction(step);
|
|
475
|
+
// Establish starting state
|
|
476
|
+
cursor = 0;
|
|
477
|
+
let data = [];
|
|
478
|
+
let errors = [];
|
|
479
|
+
let row = [];
|
|
480
|
+
let lastCursor = 0;
|
|
481
|
+
if (!input)
|
|
482
|
+
return returnable();
|
|
483
|
+
if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) {
|
|
484
|
+
const rows = input.split(newline);
|
|
485
|
+
for (let i = 0; i < rows.length; i++) {
|
|
486
|
+
const row = rows[i];
|
|
487
|
+
cursor += row.length;
|
|
488
|
+
if (i !== rows.length - 1)
|
|
489
|
+
cursor += newline.length;
|
|
490
|
+
else if (ignoreLastRow)
|
|
491
|
+
return returnable();
|
|
492
|
+
if (comments && row.substr(0, commentsLen) === comments)
|
|
493
|
+
continue;
|
|
494
|
+
if (stepIsFunction) {
|
|
495
|
+
data = [];
|
|
496
|
+
pushRow(row.split(delim));
|
|
497
|
+
doStep();
|
|
498
|
+
if (aborted)
|
|
499
|
+
return returnable();
|
|
500
|
+
}
|
|
501
|
+
else
|
|
502
|
+
pushRow(row.split(delim));
|
|
503
|
+
if (preview && i >= preview) {
|
|
504
|
+
data = data.slice(0, preview);
|
|
505
|
+
return returnable(true);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return returnable();
|
|
509
|
+
}
|
|
510
|
+
let nextDelim = input.indexOf(delim, cursor);
|
|
511
|
+
let nextNewline = input.indexOf(newline, cursor);
|
|
512
|
+
const quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');
|
|
513
|
+
let quoteSearch;
|
|
514
|
+
// Parser loop
|
|
515
|
+
for (;;) {
|
|
516
|
+
// Field has opening quote
|
|
517
|
+
if (input[cursor] === quoteChar) {
|
|
518
|
+
// Start our search for the closing quote where the cursor is
|
|
519
|
+
quoteSearch = cursor;
|
|
520
|
+
// Skip the opening quote
|
|
521
|
+
cursor++;
|
|
522
|
+
for (;;) {
|
|
523
|
+
// Find closing quote
|
|
524
|
+
quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
|
|
525
|
+
// No other quotes are found - no other delimiters
|
|
526
|
+
if (quoteSearch === -1) {
|
|
527
|
+
if (!ignoreLastRow) {
|
|
528
|
+
// No closing quote... what a pity
|
|
529
|
+
errors.push({
|
|
530
|
+
type: 'Quotes',
|
|
531
|
+
code: 'MissingQuotes',
|
|
532
|
+
message: 'Quoted field unterminated',
|
|
533
|
+
row: data.length, // row has yet to be inserted
|
|
534
|
+
index: cursor
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
return finish();
|
|
538
|
+
}
|
|
539
|
+
// Closing quote at EOF
|
|
540
|
+
if (quoteSearch === inputLen - 1) {
|
|
541
|
+
const value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
|
|
542
|
+
return finish(value);
|
|
543
|
+
}
|
|
544
|
+
// If this quote is escaped, it's part of the data; skip it
|
|
545
|
+
// If the quote character is the escape character, then check if the next character is the escape character
|
|
546
|
+
if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) {
|
|
547
|
+
quoteSearch++;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
// If the quote character is not the escape character, then check if the previous character was the escape character
|
|
551
|
+
if (quoteChar !== escapeChar &&
|
|
552
|
+
quoteSearch !== 0 &&
|
|
553
|
+
input[quoteSearch - 1] === escapeChar) {
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
// Check up to nextDelim or nextNewline, whichever is closest
|
|
557
|
+
const checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);
|
|
558
|
+
const spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);
|
|
559
|
+
// Closing quote followed by delimiter or 'unnecessary spaces + delimiter'
|
|
560
|
+
if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter] === delim) {
|
|
561
|
+
row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
|
|
562
|
+
cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
|
|
563
|
+
nextDelim = input.indexOf(delim, cursor);
|
|
564
|
+
nextNewline = input.indexOf(newline, cursor);
|
|
565
|
+
if (stepIsFunction) {
|
|
566
|
+
doStep();
|
|
567
|
+
if (aborted)
|
|
568
|
+
return returnable();
|
|
569
|
+
}
|
|
570
|
+
if (preview && data.length >= preview)
|
|
571
|
+
return returnable(true);
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
const spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
|
|
575
|
+
// Closing quote followed by newline or 'unnecessary spaces + newLine'
|
|
576
|
+
if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, newlineLen) === newline) {
|
|
577
|
+
row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
|
|
578
|
+
saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
|
|
579
|
+
nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field
|
|
580
|
+
if (stepIsFunction) {
|
|
581
|
+
doStep();
|
|
582
|
+
if (aborted)
|
|
583
|
+
return returnable();
|
|
584
|
+
}
|
|
585
|
+
if (preview && data.length >= preview)
|
|
586
|
+
return returnable(true);
|
|
587
|
+
break;
|
|
588
|
+
}
|
|
589
|
+
// 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
|
|
590
|
+
errors.push({
|
|
591
|
+
type: 'Quotes',
|
|
592
|
+
code: 'InvalidQuotes',
|
|
593
|
+
message: 'Trailing quote on quoted field is malformed',
|
|
594
|
+
row: data.length, // row has yet to be inserted
|
|
595
|
+
index: cursor
|
|
596
|
+
});
|
|
597
|
+
quoteSearch++;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
if (stepIsFunction) {
|
|
601
|
+
doStep();
|
|
602
|
+
if (aborted)
|
|
603
|
+
return returnable();
|
|
604
|
+
}
|
|
605
|
+
if (preview && data.length >= preview)
|
|
606
|
+
return returnable(true);
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
// Comment found at start of new line
|
|
610
|
+
if (comments && row.length === 0 && input.substr(cursor, commentsLen) === comments) {
|
|
611
|
+
if (nextNewline === -1)
|
|
612
|
+
// Comment ends at EOF
|
|
613
|
+
return returnable();
|
|
614
|
+
cursor = nextNewline + newlineLen;
|
|
615
|
+
nextNewline = input.indexOf(newline, cursor);
|
|
616
|
+
nextDelim = input.indexOf(delim, cursor);
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
// Next delimiter comes before next newline, so we've reached end of field
|
|
620
|
+
if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) {
|
|
621
|
+
row.push(input.substring(cursor, nextDelim));
|
|
622
|
+
cursor = nextDelim + delimLen;
|
|
623
|
+
nextDelim = input.indexOf(delim, cursor);
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
// End of row
|
|
627
|
+
if (nextNewline !== -1) {
|
|
628
|
+
row.push(input.substring(cursor, nextNewline));
|
|
629
|
+
saveRow(nextNewline + newlineLen);
|
|
630
|
+
if (stepIsFunction) {
|
|
631
|
+
doStep();
|
|
632
|
+
if (aborted)
|
|
633
|
+
return returnable();
|
|
634
|
+
}
|
|
635
|
+
if (preview && data.length >= preview)
|
|
636
|
+
return returnable(true);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
break;
|
|
640
|
+
}
|
|
641
|
+
return finish();
|
|
642
|
+
function pushRow(row) {
|
|
643
|
+
data.push(row);
|
|
644
|
+
lastCursor = cursor;
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* checks if there are extra spaces after closing quote and given index without any text
|
|
648
|
+
* if Yes, returns the number of spaces
|
|
649
|
+
*/
|
|
650
|
+
function extraSpaces(index) {
|
|
651
|
+
let spaceLength = 0;
|
|
652
|
+
if (index !== -1) {
|
|
653
|
+
const textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
|
|
654
|
+
if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
|
|
655
|
+
spaceLength = textBetweenClosingQuoteAndIndex.length;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return spaceLength;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Appends the remaining input from cursor to the end into
|
|
662
|
+
* row, saves the row, calls step, and returns the results.
|
|
663
|
+
*/
|
|
664
|
+
function finish(value) {
|
|
665
|
+
if (ignoreLastRow)
|
|
666
|
+
return returnable();
|
|
667
|
+
if (typeof value === 'undefined')
|
|
668
|
+
value = input.substr(cursor);
|
|
669
|
+
row.push(value);
|
|
670
|
+
cursor = inputLen; // important in case parsing is paused
|
|
671
|
+
pushRow(row);
|
|
672
|
+
if (stepIsFunction)
|
|
673
|
+
doStep();
|
|
674
|
+
return returnable();
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Appends the current row to the results. It sets the cursor
|
|
678
|
+
* to newCursor and finds the nextNewline. The caller should
|
|
679
|
+
* take care to execute user's step function and check for
|
|
680
|
+
* preview and end parsing if necessary.
|
|
681
|
+
*/
|
|
682
|
+
function saveRow(newCursor) {
|
|
683
|
+
cursor = newCursor;
|
|
684
|
+
pushRow(row);
|
|
685
|
+
row = [];
|
|
686
|
+
nextNewline = input.indexOf(newline, cursor);
|
|
687
|
+
}
|
|
688
|
+
/** Returns an object with the results, errors, and meta. */
|
|
689
|
+
function returnable(stopped, step) {
|
|
690
|
+
const isStep = step || false;
|
|
691
|
+
return {
|
|
692
|
+
data: isStep ? data[0] : data,
|
|
693
|
+
errors,
|
|
694
|
+
meta: {
|
|
695
|
+
delimiter: delim,
|
|
696
|
+
linebreak: newline,
|
|
697
|
+
aborted,
|
|
698
|
+
truncated: Boolean(stopped),
|
|
699
|
+
cursor: lastCursor + (baseIndex || 0)
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
/** Executes the user's step function and resets data & errors. */
|
|
704
|
+
function doStep() {
|
|
705
|
+
// @ts-expect-error
|
|
706
|
+
step(returnable(undefined, true));
|
|
707
|
+
data = [];
|
|
708
|
+
errors = [];
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
/** Sets the abort flag */
|
|
712
|
+
// @ts-expect-error
|
|
713
|
+
this.abort = function () {
|
|
714
|
+
aborted = true;
|
|
715
|
+
};
|
|
716
|
+
/** Gets the cursor position */
|
|
717
|
+
// @ts-expect-error
|
|
718
|
+
this.getCharIndex = function () {
|
|
719
|
+
return cursor;
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
/** Makes a deep copy of an array or object (mostly) */
|
|
723
|
+
function copy(obj) {
|
|
724
|
+
if (typeof obj !== 'object' || obj === null)
|
|
725
|
+
return obj;
|
|
726
|
+
const cpy = Array.isArray(obj) ? [] : {};
|
|
727
|
+
for (const key in obj)
|
|
728
|
+
cpy[key] = copy(obj[key]);
|
|
729
|
+
return cpy;
|
|
730
|
+
}
|
|
731
|
+
function isFunction(func) {
|
|
732
|
+
return typeof func === 'function';
|
|
733
|
+
}
|