@konstit/csv 0.4.1 → 0.4.3
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/README.md +136 -463
- package/dist/api.d.ts +356 -21
- package/dist/api.js +64 -93
- package/dist/batches.d.ts +291 -0
- package/dist/batches.js +72 -43
- package/dist/file-stream.d.ts +2 -2
- package/dist/file-stream.js +5 -2
- package/dist/files.d.ts +148 -2
- package/dist/files.js +30 -24
- package/dist/filter.d.ts +82 -0
- package/dist/latin1-rows.d.ts +3 -0
- package/dist/latin1-rows.js +84 -0
- package/dist/materialize-field.d.ts +1 -0
- package/dist/materialize-field.js +26 -0
- package/dist/native.d.ts +29 -0
- package/dist/native.js +44 -3
- package/dist/normalize.d.ts +18 -1
- package/dist/normalize.js +10 -0
- package/dist/options-snapshot.d.ts +3 -0
- package/dist/options-snapshot.js +50 -0
- package/dist/options.d.ts +44 -3
- package/dist/parser.d.ts +307 -1
- package/dist/parser.js +121 -8
- package/dist/strict-schema.d.ts +1 -1
- package/dist/strict-schema.js +4 -1
- package/dist/types.d.ts +435 -67
- package/dist/worker-count.d.ts +33 -1
- package/dist/worker-count.js +6 -1
- package/dist/worker-pool.d.ts +77 -1
- package/dist/worker-pool.js +11 -3
- package/dist/worker-rows.d.ts +31 -3
- package/dist/worker-rows.js +11 -2
- package/dist/workers/count.worker.js +13 -26
- package/dist/workers/rows.worker.js +23 -52
- package/package.json +23 -10
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +8 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
package/dist/batches.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { decodeMaterializedField } from "./materialize-field.js";
|
|
1
2
|
import {
|
|
2
3
|
EMPTY_BUFFER,
|
|
3
4
|
native,
|
|
@@ -12,13 +13,15 @@ import {
|
|
|
12
13
|
|
|
13
14
|
export class NativeCsvRowView {
|
|
14
15
|
#data;
|
|
15
|
-
#
|
|
16
|
+
#rowOffsetWords;
|
|
16
17
|
#fieldOffsets;
|
|
18
|
+
#fieldOffsetWords;
|
|
17
19
|
#rowIndex;
|
|
18
20
|
constructor(data, rowOffsets, fieldOffsets, rowIndex = 0) {
|
|
19
21
|
this.#data = data;
|
|
20
|
-
this.#
|
|
22
|
+
this.#rowOffsetWords = offsetWords(rowOffsets);
|
|
21
23
|
this.#fieldOffsets = fieldOffsets;
|
|
24
|
+
this.#fieldOffsetWords = offsetWords(fieldOffsets);
|
|
22
25
|
this.#rowIndex = rowIndex;
|
|
23
26
|
}
|
|
24
27
|
get rowIndex() {
|
|
@@ -39,8 +42,8 @@ export class NativeCsvRowView {
|
|
|
39
42
|
if (fieldIndex < rowStart || fieldIndex >= rowEnd)
|
|
40
43
|
return null;
|
|
41
44
|
return {
|
|
42
|
-
start: offsetAt(this.#
|
|
43
|
-
end: offsetAt(this.#
|
|
45
|
+
start: offsetAt(this.#fieldOffsetWords, fieldIndex, "field offset", this.#data.byteLength),
|
|
46
|
+
end: offsetAt(this.#fieldOffsetWords, fieldIndex + 1, "field offset", this.#data.byteLength)
|
|
44
47
|
};
|
|
45
48
|
}
|
|
46
49
|
range(columnIndex) {
|
|
@@ -88,8 +91,8 @@ export class NativeCsvRowView {
|
|
|
88
91
|
}
|
|
89
92
|
#rowRange(rowIndex) {
|
|
90
93
|
const maxFieldIndex = this.#fieldOffsets.length - 1;
|
|
91
|
-
const rowStart = offsetAt(this.#
|
|
92
|
-
const rowEnd = offsetAt(this.#
|
|
94
|
+
const rowStart = offsetAt(this.#rowOffsetWords, rowIndex, `row ${rowIndex} offset`, maxFieldIndex);
|
|
95
|
+
const rowEnd = offsetAt(this.#rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, maxFieldIndex);
|
|
93
96
|
if (rowEnd < rowStart)
|
|
94
97
|
throw RangeError(`row ${rowIndex} offsets are not monotonic`);
|
|
95
98
|
return [rowStart, rowEnd];
|
|
@@ -101,7 +104,9 @@ export class NativeCsvBatch {
|
|
|
101
104
|
#data;
|
|
102
105
|
#dataView;
|
|
103
106
|
#rowOffsets;
|
|
107
|
+
#rowOffsetWords;
|
|
104
108
|
#fieldOffsets;
|
|
109
|
+
#fieldOffsetWords;
|
|
105
110
|
constructor(handle) {
|
|
106
111
|
this.#handle = handle;
|
|
107
112
|
}
|
|
@@ -130,14 +135,14 @@ export class NativeCsvBatch {
|
|
|
130
135
|
normalizeColumns(columns);
|
|
131
136
|
const rowCount = this.rowCount;
|
|
132
137
|
const totalFields = this.totalFields;
|
|
133
|
-
const
|
|
134
|
-
const
|
|
138
|
+
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
139
|
+
const fieldOffsetWords = this.#fieldOffsetWordsView();
|
|
135
140
|
const data = this.data();
|
|
136
141
|
target.length = rowCount;
|
|
137
142
|
if (columns !== void 0) {
|
|
138
143
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
139
|
-
const fieldStart = offsetAt(
|
|
140
|
-
const fieldEnd = offsetAt(
|
|
144
|
+
const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
145
|
+
const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
141
146
|
const existing = target[rowIndex];
|
|
142
147
|
const row = existing === void 0 ? [] : existing;
|
|
143
148
|
row.length = columns.length;
|
|
@@ -148,25 +153,25 @@ export class NativeCsvBatch {
|
|
|
148
153
|
row[outputIndex] = "";
|
|
149
154
|
continue;
|
|
150
155
|
}
|
|
151
|
-
const start = offsetAt(
|
|
152
|
-
const end = offsetAt(
|
|
153
|
-
row[outputIndex] = data
|
|
156
|
+
const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
|
|
157
|
+
const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
|
|
158
|
+
row[outputIndex] = decodeMaterializedField(data, start, end, "utf8");
|
|
154
159
|
}
|
|
155
160
|
target[rowIndex] = row;
|
|
156
161
|
}
|
|
157
162
|
return target;
|
|
158
163
|
}
|
|
159
164
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
160
|
-
const fieldStart = offsetAt(
|
|
161
|
-
const fieldEnd = offsetAt(
|
|
165
|
+
const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
166
|
+
const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
162
167
|
const existing = target[rowIndex];
|
|
163
168
|
const row = existing === void 0 ? [] : existing;
|
|
164
169
|
row.length = fieldEnd - fieldStart;
|
|
165
170
|
for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
|
|
166
|
-
const start = offsetAt(
|
|
167
|
-
const end = offsetAt(
|
|
171
|
+
const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
|
|
172
|
+
const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
|
|
168
173
|
const column = fieldIndex - fieldStart;
|
|
169
|
-
row[column] = data
|
|
174
|
+
row[column] = decodeMaterializedField(data, start, end, "utf8");
|
|
170
175
|
}
|
|
171
176
|
target[rowIndex] = row;
|
|
172
177
|
}
|
|
@@ -209,24 +214,24 @@ export class NativeCsvBatch {
|
|
|
209
214
|
return this.#fieldOffsets;
|
|
210
215
|
}
|
|
211
216
|
rowFieldCount(rowIndex) {
|
|
212
|
-
const
|
|
213
|
-
const start = offsetAt(
|
|
214
|
-
const end = offsetAt(
|
|
217
|
+
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
218
|
+
const start = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, this.totalFields);
|
|
219
|
+
const end = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, this.totalFields);
|
|
215
220
|
return end - start;
|
|
216
221
|
}
|
|
217
222
|
fieldRange(rowIndex, columnIndex) {
|
|
218
|
-
const
|
|
219
|
-
const
|
|
223
|
+
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
224
|
+
const fieldOffsetWords = this.#fieldOffsetWordsView();
|
|
220
225
|
const totalFields = this.totalFields;
|
|
221
226
|
const dataLength = this.dataLength;
|
|
222
|
-
const rowStart = offsetAt(
|
|
223
|
-
const rowEnd = offsetAt(
|
|
227
|
+
const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
228
|
+
const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
224
229
|
const fieldIndex = rowStart + columnIndex;
|
|
225
230
|
if (fieldIndex < rowStart || fieldIndex >= rowEnd)
|
|
226
231
|
return null;
|
|
227
232
|
return {
|
|
228
|
-
start: offsetAt(
|
|
229
|
-
end: offsetAt(
|
|
233
|
+
start: offsetAt(fieldOffsetWords, fieldIndex, "field offset", dataLength),
|
|
234
|
+
end: offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength)
|
|
230
235
|
};
|
|
231
236
|
}
|
|
232
237
|
fieldBuffer(rowIndex, columnIndex) {
|
|
@@ -248,19 +253,19 @@ export class NativeCsvBatch {
|
|
|
248
253
|
return this.data().toString("utf8", range.start, range.end);
|
|
249
254
|
}
|
|
250
255
|
forEachColumnRange(columnIndex, callback, startRow = 0, endRow = this.rowCount) {
|
|
251
|
-
const
|
|
252
|
-
const
|
|
256
|
+
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
257
|
+
const fieldOffsetWords = this.#fieldOffsetWordsView();
|
|
253
258
|
const totalFields = this.totalFields;
|
|
254
259
|
const dataLength = this.dataLength;
|
|
255
260
|
const resolvedEndRow = this.#resolveEndRow(endRow);
|
|
256
261
|
this.#validateRowRange(startRow, resolvedEndRow);
|
|
257
262
|
for (let rowIndex = startRow;rowIndex < resolvedEndRow; ++rowIndex) {
|
|
258
|
-
const rowStart = offsetAt(
|
|
259
|
-
const rowEnd = offsetAt(
|
|
263
|
+
const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
264
|
+
const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
260
265
|
const fieldIndex = rowStart + columnIndex;
|
|
261
266
|
if (fieldIndex < rowStart || fieldIndex >= rowEnd)
|
|
262
267
|
continue;
|
|
263
|
-
callback(rowIndex, offsetAt(
|
|
268
|
+
callback(rowIndex, offsetAt(fieldOffsetWords, fieldIndex, "field offset", dataLength), offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength));
|
|
264
269
|
}
|
|
265
270
|
}
|
|
266
271
|
forEachColumnBytes(columnIndex, callback, startRow = 0, endRow = this.rowCount) {
|
|
@@ -272,14 +277,14 @@ export class NativeCsvBatch {
|
|
|
272
277
|
scanColumns(columns, callback, startRow = 0, endRow = this.rowCount) {
|
|
273
278
|
const resolvedEndRow = this.#resolveEndRow(endRow);
|
|
274
279
|
this.#validateRowRange(startRow, resolvedEndRow);
|
|
275
|
-
const
|
|
276
|
-
const
|
|
280
|
+
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
281
|
+
const fieldOffsetWords = this.#fieldOffsetWordsView();
|
|
277
282
|
const data = this.data();
|
|
278
283
|
const totalFields = this.totalFields;
|
|
279
284
|
const ranges = new Float64Array(columns.length * 2);
|
|
280
285
|
for (let rowIndex = startRow;rowIndex < resolvedEndRow; ++rowIndex) {
|
|
281
|
-
const rowStart = offsetAt(
|
|
282
|
-
const rowEnd = offsetAt(
|
|
286
|
+
const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
287
|
+
const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
283
288
|
for (let columnOffset = 0;columnOffset < columns.length; ++columnOffset) {
|
|
284
289
|
const columnIndex = columns[columnOffset] ?? 0;
|
|
285
290
|
const fieldIndex = rowStart + columnIndex;
|
|
@@ -289,8 +294,8 @@ export class NativeCsvBatch {
|
|
|
289
294
|
ranges[rangeIndex + 1] = -1;
|
|
290
295
|
continue;
|
|
291
296
|
}
|
|
292
|
-
ranges[rangeIndex] = offsetAt(
|
|
293
|
-
ranges[rangeIndex + 1] = offsetAt(
|
|
297
|
+
ranges[rangeIndex] = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
|
|
298
|
+
ranges[rangeIndex + 1] = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
|
|
294
299
|
}
|
|
295
300
|
callback(rowIndex, ranges, data);
|
|
296
301
|
}
|
|
@@ -308,7 +313,9 @@ export class NativeCsvBatch {
|
|
|
308
313
|
this.#data = void 0;
|
|
309
314
|
this.#dataView = void 0;
|
|
310
315
|
this.#rowOffsets = void 0;
|
|
316
|
+
this.#rowOffsetWords = void 0;
|
|
311
317
|
this.#fieldOffsets = void 0;
|
|
318
|
+
this.#fieldOffsetWords = void 0;
|
|
312
319
|
}
|
|
313
320
|
}
|
|
314
321
|
dispose() {
|
|
@@ -322,6 +329,18 @@ export class NativeCsvBatch {
|
|
|
322
329
|
throw Error("native CSV batch is closed");
|
|
323
330
|
return this.#handle;
|
|
324
331
|
}
|
|
332
|
+
#rowOffsetWordsView() {
|
|
333
|
+
const rowOffsets = this.rowOffsets();
|
|
334
|
+
if (this.#rowOffsetWords === void 0)
|
|
335
|
+
this.#rowOffsetWords = offsetWords(rowOffsets);
|
|
336
|
+
return this.#rowOffsetWords;
|
|
337
|
+
}
|
|
338
|
+
#fieldOffsetWordsView() {
|
|
339
|
+
const fieldOffsets = this.fieldOffsets();
|
|
340
|
+
if (this.#fieldOffsetWords === void 0)
|
|
341
|
+
this.#fieldOffsetWords = offsetWords(fieldOffsets);
|
|
342
|
+
return this.#fieldOffsetWords;
|
|
343
|
+
}
|
|
325
344
|
#resolveEndRow(endRow) {
|
|
326
345
|
if (Number.isNaN(endRow))
|
|
327
346
|
throw RangeError(`row index out of range: ${endRow}`);
|
|
@@ -335,14 +354,24 @@ export class NativeCsvBatch {
|
|
|
335
354
|
throw RangeError(`row index out of range: ${endRow}`);
|
|
336
355
|
}
|
|
337
356
|
}
|
|
357
|
+
const UINT32_BASE = 4294967296;
|
|
358
|
+
const UINT32_BASE_BIGINT = 0x100000000n;
|
|
359
|
+
const MAX_SAFE_OFFSET_HIGH_WORD = 2097151;
|
|
360
|
+
function offsetWords(offsets) {
|
|
361
|
+
return new Uint32Array(offsets.buffer, offsets.byteOffset, offsets.length * 2);
|
|
362
|
+
}
|
|
338
363
|
function offsetAt(offsets, index, label, upperBound) {
|
|
339
|
-
const
|
|
340
|
-
|
|
364
|
+
const wordIndex = index * 2;
|
|
365
|
+
const low = offsets[wordIndex];
|
|
366
|
+
const high = offsets[wordIndex + 1];
|
|
367
|
+
if (low === void 0 || high === void 0 || wordIndex % 2 !== 0)
|
|
341
368
|
throw RangeError(`${label} index out of range: ${index}`);
|
|
342
|
-
if (
|
|
369
|
+
if (high > MAX_SAFE_OFFSET_HIGH_WORD) {
|
|
370
|
+
const value = BigInt(high) * UINT32_BASE_BIGINT + BigInt(low);
|
|
343
371
|
throw RangeError(`${label} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
|
|
344
|
-
|
|
372
|
+
}
|
|
373
|
+
const offset = low + high * UINT32_BASE;
|
|
345
374
|
if (offset > upperBound)
|
|
346
|
-
throw RangeError(`${label} exceeds backing storage: ${
|
|
375
|
+
throw RangeError(`${label} exceeds backing storage: ${offset}`);
|
|
347
376
|
return offset;
|
|
348
377
|
}
|
package/dist/file-stream.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ interface CsvFileInput extends AsyncDisposable {
|
|
|
3
3
|
readonly delimiter: CsvDelimiter;
|
|
4
4
|
chunks(): AsyncIterable<Uint8Array>;
|
|
5
5
|
}
|
|
6
|
-
export declare function prepareCsvFileInput(path: string,
|
|
7
|
-
export declare function readCsvFileChunks(path: string,
|
|
6
|
+
export declare function prepareCsvFileInput(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter'>): Promise<CsvFileInput>;
|
|
7
|
+
export declare function readCsvFileChunks(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression'>): AsyncIterable<Uint8Array>;
|
|
8
8
|
export declare function rejectCompressedSharding(options: Pick<CsvFileOptions, 'compression'>, operation: string): void;
|
|
9
9
|
export declare function rejectAutoDelimiterSharding(options: Pick<CsvFileOptions, 'delimiter'>, operation: string): void;
|
|
10
10
|
export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
|
package/dist/file-stream.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createReadStream } from "node:fs";
|
|
2
2
|
import { extname } from "node:path";
|
|
3
3
|
import { DEFAULT_CHUNK_SIZE } from "./native.js";
|
|
4
|
+
import { snapshotCsvOptions } from "./options-snapshot.js";
|
|
4
5
|
import { readZipEntryChunks } from "./zip-reader.js";
|
|
5
6
|
const DELIMITER_PROBE_SIZE = 65536;
|
|
6
7
|
const MAX_DELIMITER_PROBE_ROWS = 128;
|
|
@@ -24,7 +25,8 @@ const COMPRESSION_EXTENSIONS = [
|
|
|
24
25
|
".gz",
|
|
25
26
|
".zz"
|
|
26
27
|
];
|
|
27
|
-
export async function prepareCsvFileInput(path,
|
|
28
|
+
export async function prepareCsvFileInput(path, suppliedOptions) {
|
|
29
|
+
const options = snapshotCsvOptions(suppliedOptions);
|
|
28
30
|
const configuredDelimiter = options.delimiter ?? ",";
|
|
29
31
|
if (configuredDelimiter !== "auto") {
|
|
30
32
|
let opened = !1;
|
|
@@ -77,7 +79,8 @@ export async function prepareCsvFileInput(path, options) {
|
|
|
77
79
|
throw error;
|
|
78
80
|
}
|
|
79
81
|
}
|
|
80
|
-
export function readCsvFileChunks(path,
|
|
82
|
+
export function readCsvFileChunks(path, suppliedOptions) {
|
|
83
|
+
const options = snapshotCsvOptions(suppliedOptions);
|
|
81
84
|
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
82
85
|
if (options.compression === void 0)
|
|
83
86
|
return createReadStream(path, { highWaterMark: chunkSize });
|
package/dist/files.d.ts
CHANGED
|
@@ -1,8 +1,154 @@
|
|
|
1
1
|
import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Parse one complete in-memory CSV buffer into materialized rows.
|
|
4
|
+
*
|
|
5
|
+
* The buffer is treated as the complete input, so quoted records may span the
|
|
6
|
+
* buffer but parser state is not retained after this call. `selectedColumns`
|
|
7
|
+
* projects zero-based physical columns in the returned rows. The supplied
|
|
8
|
+
* options are captured when the function is called; changing an options array
|
|
9
|
+
* while parsing cannot change the operation.
|
|
10
|
+
*
|
|
11
|
+
* Automatic delimiter detection and file compression are file-only features.
|
|
12
|
+
* Use an explicit one-character delimiter for in-memory input.
|
|
13
|
+
*
|
|
14
|
+
* @param buffer Complete CSV bytes to parse.
|
|
15
|
+
* @param suppliedOptions Parser, projection, and strict-schema options.
|
|
16
|
+
* @returns Materialized rows. Each row is a newly allocated array of strings.
|
|
17
|
+
* @throws If the buffer, delimiter, projection, or strict-schema options are invalid, or if CSV parsing fails.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { parseCsvBuffer } from '@konstit/csv';
|
|
22
|
+
*
|
|
23
|
+
* const rows = parseCsvBuffer(Buffer.from('id,name\n1,Ada\n'));
|
|
24
|
+
* // rows[0] is ['id', 'name']
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions): CsvRow[];
|
|
28
|
+
/**
|
|
29
|
+
* Count rows in bytes known to contain one record per physical line.
|
|
30
|
+
*
|
|
31
|
+
* This is a structural newline counter rather than a CSV parser: newlines in
|
|
32
|
+
* quoted fields are counted as row boundaries. The native counter counts each
|
|
33
|
+
* LF byte; a final byte other than LF or CR adds one unterminated row. Thus a
|
|
34
|
+
* CRLF ending counts once through its LF, while a standalone CR is not a row
|
|
35
|
+
* separator. Use it only for trusted newline-delimited data.
|
|
36
|
+
*
|
|
37
|
+
* @param buffer Newline-delimited bytes. Typed-array views are counted from their visible byte range.
|
|
38
|
+
* @returns The number of physical lines, represented as a safe JavaScript number.
|
|
39
|
+
* @throws If the count cannot be represented safely as a JavaScript number.
|
|
40
|
+
*/
|
|
3
41
|
export declare function countTrustedNewlineRows(buffer: NodeJS.TypedArray | DataView): number;
|
|
42
|
+
/**
|
|
43
|
+
* Find byte offsets at which a CSV file can be split without breaking a record.
|
|
44
|
+
*
|
|
45
|
+
* Returned offsets include `0` and the file byte length. Intermediate offsets
|
|
46
|
+
* are chosen at record boundaries, including records containing quoted
|
|
47
|
+
* newlines, and approximate the requested number of shards. The file is read
|
|
48
|
+
* as raw bytes, so this low-level helper accepts only an explicit
|
|
49
|
+
* one-character delimiter.
|
|
50
|
+
*
|
|
51
|
+
* @param path Path to the uncompressed CSV file.
|
|
52
|
+
* @param shardCount Desired number of shards. It must be a positive integer.
|
|
53
|
+
* @param delimiter One-byte CSV delimiter; defaults to `,`.
|
|
54
|
+
* @returns Nondecreasing byte offsets suitable as half-open shard starts and ends.
|
|
55
|
+
* @throws {RangeError} If `shardCount` is not a positive integer.
|
|
56
|
+
* @throws If `delimiter` is not exactly one character or the native scan fails.
|
|
57
|
+
*/
|
|
4
58
|
export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string): number[];
|
|
59
|
+
/**
|
|
60
|
+
* Return inclusive, record-safe byte ranges for parallel CSV processing.
|
|
61
|
+
*
|
|
62
|
+
* The ranges are derived from {@link findCsvSafeSplitOffsets}. Empty ranges
|
|
63
|
+
* are omitted, so a small file can produce fewer ranges than `shardCount`.
|
|
64
|
+
* `start` and `end` are byte offsets in the uncompressed file and both ends
|
|
65
|
+
* are inclusive.
|
|
66
|
+
*
|
|
67
|
+
* @param path Path to the uncompressed CSV file.
|
|
68
|
+
* @param shardCount Desired number of shards. It must be a positive integer.
|
|
69
|
+
* @param delimiter One-byte CSV delimiter; defaults to `,`.
|
|
70
|
+
* @returns Non-empty, record-safe ranges in file order.
|
|
71
|
+
* @throws {RangeError} If `shardCount` is not a positive integer.
|
|
72
|
+
* @throws If `delimiter` is not exactly one character or the native scan fails.
|
|
73
|
+
*/
|
|
5
74
|
export declare function findCsvSafeShards(path: string, shardCount: number, delimiter?: string): CsvShard[];
|
|
75
|
+
/**
|
|
76
|
+
* Stream materialized row arrays from a CSV file.
|
|
77
|
+
*
|
|
78
|
+
* Each yielded value contains the rows parsed from one input chunk. Rows are
|
|
79
|
+
* ordinary strings and remain usable after the next batch is yielded. File
|
|
80
|
+
* compression and automatic delimiter detection are supported by
|
|
81
|
+
* `CsvFileOptions`.
|
|
82
|
+
*
|
|
83
|
+
* Options are snapshotted when this function is called, before iteration
|
|
84
|
+
* begins. Do not rely on mutating an options object while consuming the
|
|
85
|
+
* generator to reconfigure the stream.
|
|
86
|
+
*
|
|
87
|
+
* @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
|
|
88
|
+
* @param options File and parser options. `selectedColumns` selects physical columns for each row.
|
|
89
|
+
* @returns An async generator of non-empty row batches.
|
|
90
|
+
* @throws When iteration encounters an I/O, decompression, parsing, or strict-schema error.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* import { parseCsvFile } from '@konstit/csv';
|
|
95
|
+
*
|
|
96
|
+
* for await (const rows of parseCsvFile('data.csv', { selectedColumns: [0, 2] })) {
|
|
97
|
+
* for (const row of rows) console.log(row);
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
6
101
|
export declare function parseCsvFile(path: string, options?: CsvFileOptions): AsyncGenerator<CsvRow[], void>;
|
|
102
|
+
/**
|
|
103
|
+
* Stream rows using native projection and native filter evaluation.
|
|
104
|
+
*
|
|
105
|
+
* This lower-level file API is useful when the selected columns or native
|
|
106
|
+
* filter descriptors are already prepared. `selectedColumns` is the returned
|
|
107
|
+
* projection, while `equalsFilter` and `filters` are evaluated against
|
|
108
|
+
* physical columns before materialization. Options are snapshotted at call
|
|
109
|
+
* time, including nested filter values.
|
|
110
|
+
*
|
|
111
|
+
* Strict mode is not supported for projected batches, including strict CSV
|
|
112
|
+
* quote parsing and strict schema metadata. Use `parseCsvFile` when strict
|
|
113
|
+
* validation is required.
|
|
114
|
+
*
|
|
115
|
+
* @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
|
|
116
|
+
* @param options Native projection/filter and file parser options.
|
|
117
|
+
* @returns An async generator of non-empty projected row batches.
|
|
118
|
+
* @throws When strict mode is enabled, or when I/O, decompression, filter, or parsing errors occur during iteration.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* import { parseCsvFileProjected } from '@konstit/csv';
|
|
123
|
+
*
|
|
124
|
+
* for await (const rows of parseCsvFileProjected('data.csv', {
|
|
125
|
+
* selectedColumns: [2, 0],
|
|
126
|
+
* equalsFilter: { column: 1, value: 'active' },
|
|
127
|
+
* })) {
|
|
128
|
+
* console.log(rows);
|
|
129
|
+
* }
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
7
132
|
export declare function parseCsvFileProjected(path: string, options?: CsvFileOptions & CsvNativeProjectionOptions): AsyncGenerator<CsvRow[], void>;
|
|
8
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Count logical CSV records in a file without materializing row strings.
|
|
135
|
+
*
|
|
136
|
+
* The parser honors quoted newlines and supports the same compression and
|
|
137
|
+
* delimiter options as serial file parsing. With `strict: true`, quote syntax
|
|
138
|
+
* is validated while counting. Strict schema metadata is intentionally not
|
|
139
|
+
* supported by this counting path; use row parsing when headers or minimum
|
|
140
|
+
* data-row constraints must be checked.
|
|
141
|
+
*
|
|
142
|
+
* @param path Path to the CSV file (or compressed/ZIP input selected by `suppliedOptions.compression`).
|
|
143
|
+
* @param suppliedOptions File and parser options.
|
|
144
|
+
* @returns A promise for the logical CSV record count.
|
|
145
|
+
* @throws When strict schema metadata is requested, the file cannot be read or decompressed, parsing fails, or the count exceeds safe integer range.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* import { countCsvFile } from '@konstit/csv';
|
|
150
|
+
*
|
|
151
|
+
* const rows = await countCsvFile('data.csv', { delimiter: ';' });
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
export declare function countCsvFile(path: string, suppliedOptions?: CsvFileOptions): Promise<number>;
|
package/dist/files.js
CHANGED
|
@@ -7,26 +7,30 @@ import {
|
|
|
7
7
|
requirePtr,
|
|
8
8
|
toArrayBuffer
|
|
9
9
|
} from "./native.js";
|
|
10
|
-
import {
|
|
11
|
-
|
|
10
|
+
import {
|
|
11
|
+
normalizeChunk,
|
|
12
|
+
projectionFilterProgram
|
|
13
|
+
} from "./normalize.js";
|
|
14
|
+
import { snapshotCsvOptions } from "./options-snapshot.js";
|
|
15
|
+
import {
|
|
16
|
+
createPreparedParser,
|
|
17
|
+
NativeCsvParser
|
|
18
|
+
} from "./parser.js";
|
|
12
19
|
import {
|
|
13
20
|
rejectStrictSchemaUnsupported,
|
|
14
21
|
strictSchemaValidator
|
|
15
22
|
} from "./strict-schema.js";
|
|
16
|
-
export function parseCsvBuffer(buffer,
|
|
17
|
-
const
|
|
23
|
+
export function parseCsvBuffer(buffer, suppliedOptions = {}) {
|
|
24
|
+
const options = snapshotCsvOptions(suppliedOptions);
|
|
25
|
+
using parser = new NativeCsvParser(options);
|
|
18
26
|
const validator = strictSchemaValidator(options);
|
|
27
|
+
const batch = parser.writeBatch(buffer, !0);
|
|
19
28
|
try {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
validator?.finish();
|
|
24
|
-
return batch.rowsInto([], options.selectedColumns);
|
|
25
|
-
} finally {
|
|
26
|
-
batch.close();
|
|
27
|
-
}
|
|
29
|
+
validator?.validateBatch(batch);
|
|
30
|
+
validator?.finish();
|
|
31
|
+
return batch.rowsInto([], options.selectedColumns);
|
|
28
32
|
} finally {
|
|
29
|
-
|
|
33
|
+
batch.close();
|
|
30
34
|
}
|
|
31
35
|
}
|
|
32
36
|
export function countTrustedNewlineRows(buffer) {
|
|
@@ -67,7 +71,10 @@ export function findCsvSafeShards(path, shardCount, delimiter = ",") {
|
|
|
67
71
|
}
|
|
68
72
|
return shards;
|
|
69
73
|
}
|
|
70
|
-
export
|
|
74
|
+
export function parseCsvFile(path, options = {}) {
|
|
75
|
+
return iterateCsvFile(path, snapshotCsvOptions(options));
|
|
76
|
+
}
|
|
77
|
+
async function* iterateCsvFile(path, options) {
|
|
71
78
|
await using input = await prepareCsvFileInput(path, options);
|
|
72
79
|
using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
|
|
73
80
|
const validator = strictSchemaValidator(options);
|
|
@@ -93,17 +100,15 @@ export async function* parseCsvFile(path, options = {}) {
|
|
|
93
100
|
batch.close();
|
|
94
101
|
}
|
|
95
102
|
}
|
|
96
|
-
export
|
|
103
|
+
export function parseCsvFileProjected(path, options = {}) {
|
|
104
|
+
return iterateCsvFileProjected(path, snapshotCsvOptions(options));
|
|
105
|
+
}
|
|
106
|
+
async function* iterateCsvFileProjected(path, options) {
|
|
97
107
|
rejectStrictSchemaUnsupported(options, "projected file parsing");
|
|
98
108
|
await using input = await prepareCsvFileInput(path, options);
|
|
99
|
-
using parser =
|
|
100
|
-
const projectionOptions = {
|
|
101
|
-
selectedColumns: options.selectedColumns,
|
|
102
|
-
equalsFilter: options.equalsFilter,
|
|
103
|
-
filters: options.filters
|
|
104
|
-
};
|
|
109
|
+
using parser = createPreparedParser({ ...options, delimiter: input.delimiter }, options.selectedColumns, projectionFilterProgram(options), !0);
|
|
105
110
|
for await (const chunk of input.chunks()) {
|
|
106
|
-
const batch = parser.
|
|
111
|
+
const batch = parser.writeBatch(chunk);
|
|
107
112
|
try {
|
|
108
113
|
const rows = batch.rows();
|
|
109
114
|
if (rows.length > 0)
|
|
@@ -112,7 +117,7 @@ export async function* parseCsvFileProjected(path, options = {}) {
|
|
|
112
117
|
batch.close();
|
|
113
118
|
}
|
|
114
119
|
}
|
|
115
|
-
const batch = parser.
|
|
120
|
+
const batch = parser.endBatch();
|
|
116
121
|
try {
|
|
117
122
|
const rows = batch.rows();
|
|
118
123
|
if (rows.length > 0)
|
|
@@ -121,7 +126,8 @@ export async function* parseCsvFileProjected(path, options = {}) {
|
|
|
121
126
|
batch.close();
|
|
122
127
|
}
|
|
123
128
|
}
|
|
124
|
-
export async function countCsvFile(path,
|
|
129
|
+
export async function countCsvFile(path, suppliedOptions = {}) {
|
|
130
|
+
const options = snapshotCsvOptions(suppliedOptions);
|
|
125
131
|
rejectStrictSchemaUnsupported(options, "count");
|
|
126
132
|
await using input = await prepareCsvFileInput(path, options);
|
|
127
133
|
using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
|
package/dist/filter.d.ts
CHANGED
|
@@ -1,8 +1,90 @@
|
|
|
1
1
|
import type { CsvNativeFilterProgramEntry } from './normalize.js';
|
|
2
2
|
import type { CsvFilter, CsvFilterColumn, CsvRegex } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Select a reusable zero-based physical CSV column for building native filters.
|
|
5
|
+
*
|
|
6
|
+
* The returned column exposes predicate methods such as `equals()` and `hasMatch()`. Predicate
|
|
7
|
+
* operands are copied when the filter is created, so later mutation of a `Buffer`, `Uint8Array`,
|
|
8
|
+
* or values array cannot change the filter. A selected column can be reused to create many
|
|
9
|
+
* independent filters.
|
|
10
|
+
*
|
|
11
|
+
* @param columnIndex - Zero-based physical column index, from 0 through 2024.
|
|
12
|
+
* @returns An immutable column predicate builder.
|
|
13
|
+
* @throws {RangeError} If `columnIndex` is not an integer in the supported range.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const state = csv.column(2);
|
|
18
|
+
* const filter = state.isOneOf(['SP', 'RJ']);
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
3
21
|
export declare function column(columnIndex: number): CsvFilterColumn;
|
|
22
|
+
/**
|
|
23
|
+
* Match rows for which every supplied filter matches.
|
|
24
|
+
*
|
|
25
|
+
* Groups can be nested, and the resulting filter can be reused across row, count, and worker
|
|
26
|
+
* operations. A missing physical column remains unknown rather than becoming a match through
|
|
27
|
+
* negation; the native evaluator applies the CSV filter's three-valued semantics.
|
|
28
|
+
*
|
|
29
|
+
* @param first - First filter in the group.
|
|
30
|
+
* @param rest - Additional filters that must also match.
|
|
31
|
+
* @returns An immutable conjunction filter.
|
|
32
|
+
* @throws {RangeError} If no filter is supplied.
|
|
33
|
+
* @throws {TypeError} If any filter was not created by this filter API.
|
|
34
|
+
*/
|
|
4
35
|
export declare function all(first: CsvFilter, ...rest: readonly CsvFilter[]): CsvFilter;
|
|
36
|
+
/**
|
|
37
|
+
* Match rows for which at least one supplied filter matches.
|
|
38
|
+
*
|
|
39
|
+
* Groups can be nested, and the resulting filter can be reused across row, count, and worker
|
|
40
|
+
* operations. A missing column does not match by itself, but another matching child can still make
|
|
41
|
+
* the group match.
|
|
42
|
+
*
|
|
43
|
+
* @param first - First filter in the group.
|
|
44
|
+
* @param rest - Additional filters, any one of which may match.
|
|
45
|
+
* @returns An immutable disjunction filter.
|
|
46
|
+
* @throws {RangeError} If no filter is supplied.
|
|
47
|
+
* @throws {TypeError} If any filter was not created by this filter API.
|
|
48
|
+
*/
|
|
5
49
|
export declare function any(first: CsvFilter, ...rest: readonly CsvFilter[]): CsvFilter;
|
|
50
|
+
/**
|
|
51
|
+
* Negate one native filter.
|
|
52
|
+
*
|
|
53
|
+
* The resulting filter preserves the evaluator's unknown result for a missing column. Use this
|
|
54
|
+
* with filters created by {@link column}, {@link all}, or {@link any}; filters are immutable and
|
|
55
|
+
* safe to reuse across operations.
|
|
56
|
+
*
|
|
57
|
+
* @param filter - Filter to negate.
|
|
58
|
+
* @returns An immutable negation filter.
|
|
59
|
+
* @throws {TypeError} If `filter` was not created by this filter API.
|
|
60
|
+
*/
|
|
6
61
|
export declare function not(filter: CsvFilter): CsvFilter;
|
|
62
|
+
/**
|
|
63
|
+
* Validate and brand a JavaScript regular expression for native matching.
|
|
64
|
+
*
|
|
65
|
+
* Validation happens immediately using the parser's RE2-compatible engine. Supported flags are
|
|
66
|
+
* `i`, `m`, `s`, and `u`; global, sticky, indices, and `v` flags are rejected. The returned
|
|
67
|
+
* branded descriptor is used by low-level `CsvRegexFilter` values; `CsvFilterColumn.hasMatch()`
|
|
68
|
+
* accepts a `RegExp` and creates this descriptor internally.
|
|
69
|
+
*
|
|
70
|
+
* @param pattern - JavaScript regular expression to validate and copy.
|
|
71
|
+
* @returns An immutable validated regular expression descriptor.
|
|
72
|
+
* @throws {TypeError} If `pattern` is not a `RegExp`.
|
|
73
|
+
* @throws {SyntaxError} If the pattern is invalid for the native RE2 engine.
|
|
74
|
+
* @throws {Error} If the expression uses unsupported flags.
|
|
75
|
+
* @throws {RangeError} If the UTF-8 pattern exceeds the native size limit.
|
|
76
|
+
*/
|
|
7
77
|
export declare function re(pattern: RegExp): CsvRegex;
|
|
78
|
+
/**
|
|
79
|
+
* Resolve the native program associated with an opaque filter handle.
|
|
80
|
+
*
|
|
81
|
+
* This internal bridge lets the high-level API translate a `where` filter while preserving
|
|
82
|
+
* identity-based validation. It is not part of the package root API; callers should pass filters
|
|
83
|
+
* directly to `where` instead.
|
|
84
|
+
*
|
|
85
|
+
* @internal
|
|
86
|
+
* @param filter - Filter created by this module, or `undefined` when no filter is configured.
|
|
87
|
+
* @returns The immutable native filter program, or `undefined` when no filter is supplied.
|
|
88
|
+
* @throws {TypeError} If a non-native or foreign filter object is supplied.
|
|
89
|
+
*/
|
|
8
90
|
export declare function nativeFilterProgramFor(filter: CsvFilter | undefined): readonly CsvNativeFilterProgramEntry[] | undefined;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { CsvNativeFilterProgramEntry } from './normalize.js';
|
|
2
|
+
import type { CsvColumns, CsvDelimiter, CsvRow } from './types.js';
|
|
3
|
+
export declare function latin1Rows(chunks: AsyncIterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined): AsyncGenerator<CsvRow[], void>;
|