@konstit/csv 0.5.1 → 0.6.0
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 +27 -0
- package/THIRD_PARTY_NOTICES.md +99 -0
- package/dist/api.d.ts +3 -0
- package/dist/api.js +19 -19
- package/dist/batches.js +92 -20
- package/dist/cli-command.js +107 -2
- package/dist/cli-schema.d.ts +4 -0
- package/dist/cli-schema.js +11 -1
- package/dist/file-stream.d.ts +3 -0
- package/dist/file-stream.js +10 -6
- package/dist/files.js +1 -2
- package/dist/filter.d.ts +2 -2
- package/dist/filter.js +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/latin1-rows.d.ts +3 -2
- package/dist/latin1-rows.js +52 -12
- package/dist/materialize-field.d.ts +1 -0
- package/dist/materialize-field.js +10 -1
- package/dist/native.d.ts +26 -2
- package/dist/native.js +19 -3
- package/dist/options-snapshot.d.ts +2 -2
- package/dist/options-snapshot.js +2 -0
- package/dist/parser.d.ts +4 -4
- package/dist/parser.js +27 -6
- package/dist/transforms.d.ts +11 -0
- package/dist/transforms.js +192 -0
- package/dist/types.d.ts +41 -5
- package/package.json +1 -1
- 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 +14 -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/files.js
CHANGED
|
@@ -110,6 +110,5 @@ export async function countCsvFile(path, suppliedOptions = {}) {
|
|
|
110
110
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
111
111
|
rejectStrictSchemaUnsupported(options, "count");
|
|
112
112
|
await using input = await prepareCsvFileInput(path, options, "count");
|
|
113
|
-
|
|
114
|
-
return await countFileChunks(input, parser, options);
|
|
113
|
+
return await countFileChunks(input, { ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
115
114
|
}
|
package/dist/filter.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { CsvColumn, CsvFilter, CsvNativeFilterProgramEntry, CsvRegex } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Select a reusable zero-based physical CSV column for building native filters.
|
|
4
4
|
*
|
|
@@ -17,7 +17,7 @@ import type { CsvFilter, CsvFilterColumn, CsvNativeFilterProgramEntry, CsvRegex
|
|
|
17
17
|
* const filter = state.isOneOf(['SP', 'RJ']);
|
|
18
18
|
* ```
|
|
19
19
|
*/
|
|
20
|
-
export declare function column(columnIndex: number):
|
|
20
|
+
export declare function column(columnIndex: number): CsvColumn;
|
|
21
21
|
/**
|
|
22
22
|
* Match rows for which every supplied filter matches.
|
|
23
23
|
*
|
package/dist/filter.js
CHANGED
|
@@ -3,10 +3,12 @@ import {
|
|
|
3
3
|
normalizeNativeFilterProgram,
|
|
4
4
|
validateRegex
|
|
5
5
|
} from "./normalize.js";
|
|
6
|
+
import { transformMethods } from "./transforms.js";
|
|
6
7
|
const nativeProgramByFilter = new WeakMap;
|
|
7
8
|
export function column(columnIndex) {
|
|
8
9
|
const selectedColumn = normalizeFilterColumn(columnIndex);
|
|
9
10
|
return Object.freeze({
|
|
11
|
+
...transformMethods(selectedColumn),
|
|
10
12
|
equals: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, value: copyFieldValue(value, "equals value") })),
|
|
11
13
|
doesNotEqual: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, notEquals: copyFieldValue(value, "doesNotEqual value") })),
|
|
12
14
|
isOneOf: (values) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, values: copyFieldValues(values, "isOneOf values") })),
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterOperator, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
|
|
1
|
+
export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumn, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterOperator, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvTransform, CsvTransformChain, CsvTransformMethods, CsvTransformOptions, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
|
|
2
2
|
export { csv } from './api.js';
|
|
3
3
|
export { NativeCsvBatch, NativeCsvRowView } from './batches.js';
|
|
4
4
|
export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
|
package/dist/latin1-rows.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type NativePointer } from './native.js';
|
|
2
|
-
import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow } from './types.js';
|
|
3
|
-
export declare function
|
|
2
|
+
import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, CsvTransformOptions } from './types.js';
|
|
3
|
+
export declare function canUseFilteredLatin1Cleanup(columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, transforms: readonly CsvTransform[]): boolean;
|
|
4
|
+
export declare function latin1Rows(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[], options?: Pick<CsvParserOptions, 'limit' | 'skipRows'> & CsvTransformOptions): AsyncGenerator<CsvRow[], void>;
|
|
4
5
|
export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
|
package/dist/latin1-rows.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { isAscii } from "node:buffer";
|
|
1
2
|
import {
|
|
2
3
|
copyLatin1Range,
|
|
3
|
-
|
|
4
|
+
decodeMaterializedField,
|
|
5
|
+
latin1Pair,
|
|
6
|
+
prepareRow
|
|
4
7
|
} from "./materialize-field.js";
|
|
5
8
|
import {
|
|
6
9
|
EMPTY_BUFFER,
|
|
@@ -15,6 +18,25 @@ import {
|
|
|
15
18
|
prepareNativeParser,
|
|
16
19
|
setRowSelection
|
|
17
20
|
} from "./parser.js";
|
|
21
|
+
import {
|
|
22
|
+
hasOnlyCleanupTransforms,
|
|
23
|
+
prepareTransforms
|
|
24
|
+
} from "./transforms.js";
|
|
25
|
+
const WINDOW_BYTES = 1024;
|
|
26
|
+
const MAX_WINDOW_FIELD_BYTES = 64;
|
|
27
|
+
var RowStorage;
|
|
28
|
+
((RowStorage) => {
|
|
29
|
+
RowStorage[RowStorage.QuotedSpan = 1] = "QuotedSpan";
|
|
30
|
+
RowStorage[RowStorage.PackedUtf8 = 2] = "PackedUtf8";
|
|
31
|
+
})(RowStorage ||= {});
|
|
32
|
+
export function canUseFilteredLatin1Cleanup(columns, filters, transforms) {
|
|
33
|
+
return columns === void 0 && filters !== void 0 && hasOnlyCleanupTransforms(transforms) && filters.every((entry) => {
|
|
34
|
+
if ("operator" in entry)
|
|
35
|
+
return entry.operator === "all";
|
|
36
|
+
const operand = "value" in entry ? entry.value : ("notEquals" in entry) ? entry.notEquals : void 0;
|
|
37
|
+
return typeof operand === "string" ? Buffer.byteLength(operand) === operand.length : operand !== void 0 && isAscii(operand);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
18
40
|
export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
|
|
19
41
|
if (delimiter === "auto")
|
|
20
42
|
throw Error("automatic delimiter detection is only supported by file APIs");
|
|
@@ -27,6 +49,8 @@ export async function* latin1Rows(chunks, delimiter, columns, filters, createPar
|
|
|
27
49
|
nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
|
|
28
50
|
try {
|
|
29
51
|
setRowSelection(parser, options);
|
|
52
|
+
if (options.transform?.length)
|
|
53
|
+
prepareTransforms(parser, options.transform, columns);
|
|
30
54
|
const prepared = prepareNativeParser(parser, columns, filters);
|
|
31
55
|
let remaining = options.limit;
|
|
32
56
|
if (remaining === 0)
|
|
@@ -72,13 +96,26 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
|
|
|
72
96
|
rows.length = rowCount;
|
|
73
97
|
let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
|
|
74
98
|
let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
|
|
99
|
+
let windowStart = 0;
|
|
100
|
+
let windowEnd = 0;
|
|
101
|
+
let text = "";
|
|
75
102
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
76
103
|
const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
|
|
77
|
-
const
|
|
78
|
-
const trailing = leading * 2;
|
|
79
|
-
const row = reusableRows?.[rowIndex] ?? [];
|
|
104
|
+
const storage = quotedRows?.[rowIndex] ?? 0;
|
|
80
105
|
const width = fieldEnd - fieldStart;
|
|
81
|
-
row
|
|
106
|
+
const row = prepareRow(reusableRows?.[rowIndex], width);
|
|
107
|
+
if (storage === 2 /* PackedUtf8 */) {
|
|
108
|
+
for (let column = 0;column < width; ++column) {
|
|
109
|
+
const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
|
|
110
|
+
row[column] = decodeMaterializedField(bytes, start, end, "utf8");
|
|
111
|
+
start = end;
|
|
112
|
+
}
|
|
113
|
+
rows[rowIndex] = row;
|
|
114
|
+
fieldStart = fieldEnd;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const leading = storage === 1 /* QuotedSpan */ ? 1 : 0;
|
|
118
|
+
const trailing = leading * 2;
|
|
82
119
|
for (let column = 0;column < width; ++column) {
|
|
83
120
|
const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
|
|
84
121
|
const payload = start + leading;
|
|
@@ -94,16 +131,19 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
|
|
|
94
131
|
case 2:
|
|
95
132
|
row[column] = latin1Pair(view.getUint16(payload, !0));
|
|
96
133
|
break;
|
|
97
|
-
case 3:
|
|
98
|
-
row[column] = latin1Pair(view.getUint16(payload, !0)) + String.fromCharCode(view.getUint8(payload + 2));
|
|
99
|
-
break;
|
|
100
|
-
case 4:
|
|
101
|
-
row[column] = latin1Pair(view.getUint16(payload, !0)) + latin1Pair(view.getUint16(payload + 2, !0));
|
|
102
|
-
break;
|
|
103
134
|
default:
|
|
104
135
|
if (length < 0)
|
|
105
136
|
throw RangeError("CSV field span exceeds its backing range");
|
|
106
|
-
|
|
137
|
+
if (length > MAX_WINDOW_FIELD_BYTES) {
|
|
138
|
+
row[column] = copyLatin1Range(bytes, payload, payloadEnd);
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
if (payloadEnd > windowEnd) {
|
|
142
|
+
windowStart = payload;
|
|
143
|
+
windowEnd = Math.min(payload + WINDOW_BYTES, dataLength);
|
|
144
|
+
text = copyLatin1Range(bytes, windowStart, windowEnd);
|
|
145
|
+
}
|
|
146
|
+
row[column] = text.slice(payload - windowStart, payloadEnd - windowStart);
|
|
107
147
|
}
|
|
108
148
|
start = end;
|
|
109
149
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare function prepareRow(row: string[] | undefined, width: number): string[];
|
|
1
2
|
export declare function latin1Pair(key: number): string;
|
|
2
3
|
export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
|
|
3
4
|
export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
const LATIN1_SINGLE = Array.from({ length: 256 }, (_, byte) => String.fromCharCode(byte));
|
|
2
2
|
const bufferPrototype = Buffer.prototype;
|
|
3
3
|
const latin1Slice = bufferPrototype.latin1Slice;
|
|
4
|
+
const utf8Slice = bufferPrototype.utf8Slice;
|
|
4
5
|
const LATIN1_PAIRS = Array.from({ length: 65536 });
|
|
6
|
+
export function prepareRow(row, width) {
|
|
7
|
+
if (row === void 0)
|
|
8
|
+
return Array(width);
|
|
9
|
+
row.length = width;
|
|
10
|
+
return row;
|
|
11
|
+
}
|
|
5
12
|
export function latin1Pair(key) {
|
|
6
13
|
const cached = LATIN1_PAIRS[key];
|
|
7
14
|
if (cached !== void 0)
|
|
@@ -27,5 +34,7 @@ export function decodeMaterializedField(data, start, end, encoding) {
|
|
|
27
34
|
if (first < 128 && second < 128)
|
|
28
35
|
return latin1Pair(first | second << 8);
|
|
29
36
|
}
|
|
30
|
-
|
|
37
|
+
if (encoding === "latin1")
|
|
38
|
+
return copyLatin1Range(data, start, end);
|
|
39
|
+
return typeof utf8Slice === "function" ? utf8Slice.call(data, start, end) : data.toString("utf8", start, end);
|
|
31
40
|
}
|
package/dist/native.d.ts
CHANGED
|
@@ -13,7 +13,23 @@ export declare const EMPTY_BUFFER: Uint8Array<ArrayBuffer>;
|
|
|
13
13
|
export declare const EMPTY_U32: Uint32Array<ArrayBuffer>;
|
|
14
14
|
export declare const DEFAULT_CHUNK_SIZE: number;
|
|
15
15
|
export declare const native: import("bun:ffi").Library<{
|
|
16
|
-
readonly
|
|
16
|
+
readonly csv_parser_add_transform: {
|
|
17
|
+
readonly args: readonly ["ptr", "u32", "u32"];
|
|
18
|
+
readonly returns: "bool";
|
|
19
|
+
};
|
|
20
|
+
readonly csv_parser_add_transform_with_default: {
|
|
21
|
+
readonly args: readonly ["ptr", "u32", "u32", "buffer", "buffer_length"];
|
|
22
|
+
readonly returns: "bool";
|
|
23
|
+
};
|
|
24
|
+
readonly csv_parser_transform_pair: {
|
|
25
|
+
readonly args: readonly ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"];
|
|
26
|
+
readonly returns: "bool";
|
|
27
|
+
};
|
|
28
|
+
readonly csv_parser_transform_validated_batch: {
|
|
29
|
+
readonly args: readonly ["ptr", "ptr"];
|
|
30
|
+
readonly returns: "ptr";
|
|
31
|
+
};
|
|
32
|
+
readonly csv_probe_format_v2: {
|
|
17
33
|
readonly args: readonly ["buffer", "u32", "bool", "bool", "ptr"];
|
|
18
34
|
readonly returns: "u32";
|
|
19
35
|
};
|
|
@@ -29,6 +45,10 @@ export declare const native: import("bun:ffi").Library<{
|
|
|
29
45
|
readonly args: readonly ["int", "u8", "u32"];
|
|
30
46
|
readonly returns: "ptr";
|
|
31
47
|
};
|
|
48
|
+
readonly csv_parser_enable_transformed_quoted_spans: {
|
|
49
|
+
readonly args: readonly ["ptr"];
|
|
50
|
+
readonly returns: "void";
|
|
51
|
+
};
|
|
32
52
|
readonly csv_parser_set_row_selection: {
|
|
33
53
|
readonly args: readonly ["ptr", "u64", "u64", "bool"];
|
|
34
54
|
readonly returns: "void";
|
|
@@ -181,6 +201,10 @@ export declare const native: import("bun:ffi").Library<{
|
|
|
181
201
|
readonly args: readonly ["u8", "u32"];
|
|
182
202
|
readonly returns: "ptr";
|
|
183
203
|
};
|
|
204
|
+
readonly csv_parser_create_latin1_cleanup_rows: {
|
|
205
|
+
readonly args: readonly ["u8", "u32"];
|
|
206
|
+
readonly returns: "ptr";
|
|
207
|
+
};
|
|
184
208
|
readonly csv_batch_quoted_rows_ptr: {
|
|
185
209
|
readonly args: readonly ["ptr"];
|
|
186
210
|
readonly returns: "ptr";
|
|
@@ -190,7 +214,7 @@ export declare const native: import("bun:ffi").Library<{
|
|
|
190
214
|
readonly returns: "ptr";
|
|
191
215
|
};
|
|
192
216
|
}>;
|
|
193
|
-
export declare function latin1RowsParser(fixedColumns: number | undefined): (delimiter: number) => NativePointer | null;
|
|
217
|
+
export declare function latin1RowsParser(fixedColumns: number | undefined, cleanup?: boolean): (delimiter: number) => NativePointer | null;
|
|
194
218
|
export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
|
|
195
219
|
export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
|
|
196
220
|
export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
|
package/dist/native.js
CHANGED
|
@@ -19,7 +19,20 @@ export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0);
|
|
|
19
19
|
export const EMPTY_U32 = new Uint32Array(1);
|
|
20
20
|
export const DEFAULT_CHUNK_SIZE = 1048576;
|
|
21
21
|
const CSV_SYMBOLS = {
|
|
22
|
-
|
|
22
|
+
csv_parser_add_transform: { args: ["ptr", "u32", "u32"], returns: "bool" },
|
|
23
|
+
csv_parser_add_transform_with_default: {
|
|
24
|
+
args: [
|
|
25
|
+
"ptr",
|
|
26
|
+
"u32",
|
|
27
|
+
"u32",
|
|
28
|
+
"buffer",
|
|
29
|
+
"buffer_length"
|
|
30
|
+
],
|
|
31
|
+
returns: "bool"
|
|
32
|
+
},
|
|
33
|
+
csv_parser_transform_pair: { args: ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"], returns: "bool" },
|
|
34
|
+
csv_parser_transform_validated_batch: { args: ["ptr", "ptr"], returns: "ptr" },
|
|
35
|
+
csv_probe_format_v2: {
|
|
23
36
|
args: [
|
|
24
37
|
"buffer",
|
|
25
38
|
"u32",
|
|
@@ -38,6 +51,7 @@ const CSV_SYMBOLS = {
|
|
|
38
51
|
returns: "ptr"
|
|
39
52
|
},
|
|
40
53
|
csv_parser_create_prepared: { args: ["int", "u8", "u32"], returns: "ptr" },
|
|
54
|
+
csv_parser_enable_transformed_quoted_spans: { args: ["ptr"], returns: "void" },
|
|
41
55
|
csv_parser_set_row_selection: { args: ["ptr", "u64", "u64", "bool"], returns: "void" },
|
|
42
56
|
csv_parser_take_skipped_header: { args: ["ptr"], returns: "ptr" },
|
|
43
57
|
csv_parser_skipped_rows: { args: ["ptr"], returns: "u64" },
|
|
@@ -175,6 +189,7 @@ const CSV_SYMBOLS = {
|
|
|
175
189
|
},
|
|
176
190
|
csv_parser_create_latin1_rows_with_quoted_spans: { args: ["u8"], returns: "ptr" },
|
|
177
191
|
csv_parser_create_latin1_quoted_rows: { args: ["u8", "u32"], returns: "ptr" },
|
|
192
|
+
csv_parser_create_latin1_cleanup_rows: { args: ["u8", "u32"], returns: "ptr" },
|
|
178
193
|
csv_batch_quoted_rows_ptr: { args: ["ptr"], returns: "ptr" },
|
|
179
194
|
csv_parser_create_latin1_rows_with_fixed_columns: {
|
|
180
195
|
args: ["u8", "u32"],
|
|
@@ -182,8 +197,9 @@ const CSV_SYMBOLS = {
|
|
|
182
197
|
}
|
|
183
198
|
};
|
|
184
199
|
export const native = dlopen(resolveNativeLibraryPath(process.env.CSV_NATIVE_LIBRARY_PATH), CSV_SYMBOLS);
|
|
185
|
-
export function latin1RowsParser(fixedColumns) {
|
|
186
|
-
|
|
200
|
+
export function latin1RowsParser(fixedColumns, cleanup = !1) {
|
|
201
|
+
const create = cleanup ? native.symbols.csv_parser_create_latin1_cleanup_rows : native.symbols.csv_parser_create_latin1_quoted_rows;
|
|
202
|
+
return (delimiter) => create(delimiter, fixedColumns ?? 0);
|
|
187
203
|
}
|
|
188
204
|
export function resolveNativeLibraryPath(configuredPath) {
|
|
189
205
|
const root = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { CsvApiFileOptions, CsvNativeProjectionOptions } from './types.js';
|
|
1
|
+
import type { CsvApiFileOptions, CsvNativeProjectionOptions, CsvTransformOptions } from './types.js';
|
|
2
2
|
/** Own the mutable option values while retaining opaque immutable filter handles. */
|
|
3
|
-
export declare function snapshotCsvOptions<TOptions extends CsvApiFileOptions & CsvNativeProjectionOptions>(options: TOptions): TOptions;
|
|
3
|
+
export declare function snapshotCsvOptions<TOptions extends CsvApiFileOptions & CsvNativeProjectionOptions & CsvTransformOptions>(options: TOptions): TOptions;
|
package/dist/options-snapshot.js
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
MAX_PROJECTION_LENGTH,
|
|
4
4
|
rejectSelectedColumns
|
|
5
5
|
} from "./normalize.js";
|
|
6
|
+
import { snapshotTransforms } from "./transforms.js";
|
|
6
7
|
const snapshots = new WeakSet;
|
|
7
8
|
export function snapshotCsvOptions(options) {
|
|
8
9
|
if (snapshots.has(options))
|
|
@@ -13,6 +14,7 @@ export function snapshotCsvOptions(options) {
|
|
|
13
14
|
throw RangeError(`filter count out of range: ${captured.filters.length}`);
|
|
14
15
|
const snapshot = Object.freeze({
|
|
15
16
|
...captured,
|
|
17
|
+
transform: snapshotTransforms(captured.transform),
|
|
16
18
|
columns: snapshotColumns(captured.columns),
|
|
17
19
|
expectedHeaders: captured.expectedHeaders === void 0 ? void 0 : Object.freeze([...captured.expectedHeaders]),
|
|
18
20
|
compression: typeof captured.compression === "object" && captured.compression !== null ? Object.freeze({ ...captured.compression }) : captured.compression,
|
package/dist/parser.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { NativeCsvBatch } from './batches.js';
|
|
2
2
|
import type { CsvFileInput } from './file-stream.js';
|
|
3
3
|
import { type NativePointer } from './native.js';
|
|
4
|
-
import type { CsvColumns, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, NativeCsvParserOptions } from './types.js';
|
|
4
|
+
import type { CsvColumns, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, NativeCsvParserOptions } from './types.js';
|
|
5
5
|
export declare const nativeCsvParserFinalizer: FinalizationRegistry<NativePointer>;
|
|
6
6
|
export declare function parseFileChunks(input: CsvFileInput, parser: NativeCsvParser, limit: number | undefined): AsyncGenerator<NativeCsvBatch, void>;
|
|
7
|
-
export declare function countFileChunks(input: CsvFileInput,
|
|
8
|
-
export declare function createPreparedParser(options: CsvParserOptions, columns?: CsvColumns, program?: readonly CsvNativeFilterProgramEntry[]): NativeCsvParser;
|
|
7
|
+
export declare function countFileChunks(input: CsvFileInput, options: CsvParserOptions, filters?: readonly CsvNativeFilterProgramEntry[]): Promise<number>;
|
|
8
|
+
export declare function createPreparedParser(options: CsvParserOptions, columns?: CsvColumns, program?: readonly CsvNativeFilterProgramEntry[], transform?: readonly CsvTransform[], output?: 'batches' | 'rows'): NativeCsvParser;
|
|
9
9
|
interface PreparedNativeWriter {
|
|
10
10
|
writeBatch(input: NodeJS.TypedArray | DataView, final: boolean): NativePointer | null;
|
|
11
11
|
writeCount(input: NodeJS.TypedArray | DataView, final: boolean): bigint | number;
|
|
@@ -51,7 +51,7 @@ declare const createSchemaParser: unique symbol;
|
|
|
51
51
|
*/
|
|
52
52
|
export declare class NativeCsvParser {
|
|
53
53
|
#private;
|
|
54
|
-
static [createSchemaParser](options: NativeCsvParserOptions): NativeCsvParser;
|
|
54
|
+
static [createSchemaParser](options: NativeCsvParserOptions, output: 'batches' | 'rows'): NativeCsvParser;
|
|
55
55
|
/**
|
|
56
56
|
* Creates an open parser.
|
|
57
57
|
*
|
package/dist/parser.js
CHANGED
|
@@ -17,6 +17,11 @@ import {
|
|
|
17
17
|
import {
|
|
18
18
|
strictSchemaValidator
|
|
19
19
|
} from "./strict-schema.js";
|
|
20
|
+
import {
|
|
21
|
+
prepareTransforms,
|
|
22
|
+
selectTransforms,
|
|
23
|
+
snapshotTransforms
|
|
24
|
+
} from "./transforms.js";
|
|
20
25
|
function destroyNativeCsvParser(handle) {
|
|
21
26
|
native.symbols.csv_parser_destroy(handle);
|
|
22
27
|
}
|
|
@@ -43,7 +48,9 @@ export async function* parseFileChunks(input, parser, limit) {
|
|
|
43
48
|
else
|
|
44
49
|
final.close();
|
|
45
50
|
}
|
|
46
|
-
export async function countFileChunks(input,
|
|
51
|
+
export async function countFileChunks(input, options, filters) {
|
|
52
|
+
const columns = options.fixedColumns !== void 0 && options.strict !== !0 && filters === void 0 ? [] : void 0;
|
|
53
|
+
using parser = createPreparedParser(options, columns, filters);
|
|
47
54
|
let total = 0;
|
|
48
55
|
if (options.strict === !0) {
|
|
49
56
|
for await (using batch of parseFileChunks(input, parser, options.limit))
|
|
@@ -58,7 +65,7 @@ export async function countFileChunks(input, parser, options) {
|
|
|
58
65
|
}
|
|
59
66
|
return total + parser.endCount();
|
|
60
67
|
}
|
|
61
|
-
export function createPreparedParser(options, columns, program) {
|
|
68
|
+
export function createPreparedParser(options, columns, program, transform, output = "batches") {
|
|
62
69
|
if (options.columns !== columns)
|
|
63
70
|
normalizeColumns(options.columns);
|
|
64
71
|
return NativeCsvParser[createSchemaParser]({
|
|
@@ -72,8 +79,9 @@ export function createPreparedParser(options, columns, program) {
|
|
|
72
79
|
requireHeader: options.requireHeader,
|
|
73
80
|
minDataRows: options.minDataRows,
|
|
74
81
|
columns,
|
|
75
|
-
filterProgram: program
|
|
76
|
-
|
|
82
|
+
filterProgram: program,
|
|
83
|
+
transform: options.strict && options.columns && transform ? selectTransforms(transform, options.columns) : transform
|
|
84
|
+
}, output);
|
|
77
85
|
}
|
|
78
86
|
export function prepareNativeParser(handle, columns, program) {
|
|
79
87
|
const normalizedColumns = normalizeColumns(columns);
|
|
@@ -126,11 +134,14 @@ export class NativeCsvParser {
|
|
|
126
134
|
#strict;
|
|
127
135
|
#fixedColumns;
|
|
128
136
|
#writer;
|
|
137
|
+
#transformStrictBatch;
|
|
129
138
|
#validator;
|
|
130
139
|
#captureSkippedHeader = !1;
|
|
131
|
-
static [createSchemaParser](options) {
|
|
140
|
+
static [createSchemaParser](options, output) {
|
|
132
141
|
const validator = strictSchemaValidator(options);
|
|
133
142
|
const parser = new NativeCsvParser(options);
|
|
143
|
+
if (output === "rows" && !parser.#strict && options.transform?.length)
|
|
144
|
+
native.symbols.csv_parser_enable_transformed_quoted_spans(parser.#requireHandle());
|
|
134
145
|
parser.#validator = validator;
|
|
135
146
|
if (validator !== void 0 && (options.skipRows ?? 0) > 0) {
|
|
136
147
|
parser.#captureSkippedHeader = !0;
|
|
@@ -148,9 +159,12 @@ export class NativeCsvParser {
|
|
|
148
159
|
const program = filterProgram === void 0 ? projectionFilterProgram(options) : filterProgram;
|
|
149
160
|
if (this.#strict && (columns !== void 0 || program !== void 0))
|
|
150
161
|
throw Error("strict CSV validation is not supported for projected batches or filters");
|
|
151
|
-
const
|
|
162
|
+
const transforms = snapshotTransforms(options.transform);
|
|
163
|
+
const prepared = columns !== void 0 || program !== void 0 || !this.#strict && Boolean(transforms?.length);
|
|
152
164
|
const handle = createNativeCsvParser(options, prepared);
|
|
153
165
|
try {
|
|
166
|
+
const active = transforms?.length ? prepareTransforms(handle, transforms, columns) : !1;
|
|
167
|
+
this.#transformStrictBatch = this.#strict && active;
|
|
154
168
|
this.#writer = prepared ? prepareNativeParser(handle, columns, program) : void 0;
|
|
155
169
|
} catch (error) {
|
|
156
170
|
destroyNativeCsvParser(handle);
|
|
@@ -176,6 +190,13 @@ export class NativeCsvParser {
|
|
|
176
190
|
const batch = this.#writer !== void 0 ? this.#writer.writeBatch(input, final) : this.#strict && this.#fixedColumns !== void 0 ? native.symbols.csv_parser_write_strict_fixed_batch(handle, input, input, final, this.#fixedColumns) : this.#strict ? native.symbols.csv_parser_write_strict_batch(handle, input, input, final) : this.#fixedColumns !== void 0 ? native.symbols.csv_parser_write_fixed_batch(handle, input, input, final, this.#fixedColumns) : native.symbols.csv_parser_write_batch(handle, input, input, final);
|
|
177
191
|
if (batch === null)
|
|
178
192
|
throw Error(`native CSV parser failed: ${this.#lastError()}`);
|
|
193
|
+
if (this.#transformStrictBatch) {
|
|
194
|
+
using _original = this.#validatedBatch(batch, final);
|
|
195
|
+
const result = native.symbols.csv_parser_transform_validated_batch(handle, batch);
|
|
196
|
+
if (!result)
|
|
197
|
+
throw Error(`native CSV parser failed: ${this.#lastError()}`);
|
|
198
|
+
return new NativeCsvBatch(result);
|
|
199
|
+
}
|
|
179
200
|
return this.#validatedBatch(batch, final);
|
|
180
201
|
}
|
|
181
202
|
end() {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type NativePointer } from './native.js';
|
|
2
|
+
import type { CsvColumns, CsvTransform, CsvTransformChain, CsvTransformMethods } from './types.js';
|
|
3
|
+
/** Start a reusable chain. Choose physical columns after defining its steps. */
|
|
4
|
+
export declare function transform(): CsvTransformMethods<CsvTransformChain>;
|
|
5
|
+
export declare function transformMethods(column: number): CsvTransformMethods;
|
|
6
|
+
export declare function snapshotTransforms(transforms: readonly CsvTransform[] | undefined): readonly CsvTransform[] | undefined;
|
|
7
|
+
export declare function hasOnlyCleanupTransforms(tokens: readonly CsvTransform[]): boolean;
|
|
8
|
+
/** Strict row projection happens after full-width validation and transformation. */
|
|
9
|
+
export declare function selectTransforms(tokens: readonly CsvTransform[], columns: CsvColumns): readonly CsvTransform[];
|
|
10
|
+
/** Copy each selected chain into its parser. Native writes never reference caller-owned data. */
|
|
11
|
+
export declare function prepareTransforms(handle: NativePointer, tokens: readonly CsvTransform[], selected: CsvColumns | undefined): boolean;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import {
|
|
2
|
+
native
|
|
3
|
+
} from "./native.js";
|
|
4
|
+
import {
|
|
5
|
+
MAX_COLUMN_INDEX,
|
|
6
|
+
normalizeColumnIndex,
|
|
7
|
+
normalizeRegex
|
|
8
|
+
} from "./normalize.js";
|
|
9
|
+
var Op;
|
|
10
|
+
((Op) => {
|
|
11
|
+
Op[Op.Trim = 0] = "Trim";
|
|
12
|
+
Op[Op.Upper = 1] = "Upper";
|
|
13
|
+
Op[Op.Lower = 2] = "Lower";
|
|
14
|
+
Op[Op.Unaccent = 3] = "Unaccent";
|
|
15
|
+
Op[Op.ReplaceLiteral = 4] = "ReplaceLiteral";
|
|
16
|
+
Op[Op.Map = 5] = "Map";
|
|
17
|
+
Op[Op.DateYmd = 6] = "DateYmd";
|
|
18
|
+
Op[Op.DateDmy = 7] = "DateDmy";
|
|
19
|
+
Op[Op.DateDmySlash = 8] = "DateDmySlash";
|
|
20
|
+
Op[Op.ReplaceRegex = 9] = "ReplaceRegex";
|
|
21
|
+
})(Op ||= {});
|
|
22
|
+
const bindings = new WeakMap;
|
|
23
|
+
export function transform() {
|
|
24
|
+
return Object.freeze(methods((step) => createChain({ step, previous: void 0 })));
|
|
25
|
+
}
|
|
26
|
+
export function transformMethods(column) {
|
|
27
|
+
return methods((step) => createChain({ step, previous: void 0 }, [column]));
|
|
28
|
+
}
|
|
29
|
+
function createChain(chain, columns) {
|
|
30
|
+
const token = Object.freeze({
|
|
31
|
+
...methods((step) => createChain({ step, previous: chain }, columns)),
|
|
32
|
+
on: (...targets) => {
|
|
33
|
+
if (!targets.length)
|
|
34
|
+
throw RangeError("on() requires at least one transform column");
|
|
35
|
+
if (targets.length > MAX_COLUMN_INDEX + 1)
|
|
36
|
+
throw RangeError("too many transform columns");
|
|
37
|
+
const seen = new Set;
|
|
38
|
+
for (const column of targets) {
|
|
39
|
+
normalizeColumnIndex(column, "transform column");
|
|
40
|
+
if (seen.has(column))
|
|
41
|
+
throw RangeError(`transform column repeated: ${column}`);
|
|
42
|
+
seen.add(column);
|
|
43
|
+
}
|
|
44
|
+
return createChain(chain, targets);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
if (columns !== void 0)
|
|
48
|
+
bindings.set(token, { chain, columns });
|
|
49
|
+
return token;
|
|
50
|
+
}
|
|
51
|
+
function methods(append) {
|
|
52
|
+
return {
|
|
53
|
+
trim: () => append({ kind: 0 /* Trim */ }),
|
|
54
|
+
upper: () => append({ kind: 1 /* Upper */ }),
|
|
55
|
+
lower: () => append({ kind: 2 /* Lower */ }),
|
|
56
|
+
unaccent: () => append({ kind: 3 /* Unaccent */ }),
|
|
57
|
+
replace: (search, replacement) => {
|
|
58
|
+
requireText(replacement);
|
|
59
|
+
if (search instanceof RegExp) {
|
|
60
|
+
const pattern = normalizeRegex({ source: search.source, flags: search.flags.replace("g", "") });
|
|
61
|
+
return append({ kind: 9 /* ReplaceRegex */, search: pattern, replacement });
|
|
62
|
+
}
|
|
63
|
+
requireText(search);
|
|
64
|
+
if (search.length === 0)
|
|
65
|
+
throw RangeError("replace search string must not be empty");
|
|
66
|
+
return append({ kind: 4 /* ReplaceLiteral */, search, replacement });
|
|
67
|
+
},
|
|
68
|
+
map: (values, defaultValue) => {
|
|
69
|
+
if (defaultValue !== void 0)
|
|
70
|
+
requireText(defaultValue);
|
|
71
|
+
const captured = new Map;
|
|
72
|
+
for (const [key, value] of mappingEntries(values)) {
|
|
73
|
+
requireText(key);
|
|
74
|
+
requireText(value);
|
|
75
|
+
captured.set(key, value);
|
|
76
|
+
}
|
|
77
|
+
return append({ kind: 5 /* Map */, values: captured, defaultValue });
|
|
78
|
+
},
|
|
79
|
+
date: (format, defaultValue) => {
|
|
80
|
+
if (defaultValue !== void 0)
|
|
81
|
+
requireText(defaultValue);
|
|
82
|
+
switch (format) {
|
|
83
|
+
case "YYYY-MM-DD":
|
|
84
|
+
return append({ kind: 6 /* DateYmd */, defaultValue });
|
|
85
|
+
case "DD-MM-YYYY":
|
|
86
|
+
return append({ kind: 7 /* DateDmy */, defaultValue });
|
|
87
|
+
case "DD/MM/YYYY":
|
|
88
|
+
return append({ kind: 8 /* DateDmySlash */, defaultValue });
|
|
89
|
+
default:
|
|
90
|
+
throw TypeError("date() format must be YYYY-MM-DD, DD-MM-YYYY or DD/MM/YYYY");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function mappingEntries(values) {
|
|
96
|
+
if (values !== null && typeof values === "object") {
|
|
97
|
+
if (typeof values.get === "function" && typeof values.entries === "function")
|
|
98
|
+
return values.entries();
|
|
99
|
+
const prototype = Object.getPrototypeOf(values);
|
|
100
|
+
if (prototype === null || Object.getPrototypeOf(prototype) === null)
|
|
101
|
+
return Object.entries(values);
|
|
102
|
+
}
|
|
103
|
+
throw TypeError("map() requires a map or plain object of strings");
|
|
104
|
+
}
|
|
105
|
+
function requireText(value) {
|
|
106
|
+
if (typeof value !== "string" || !value.isWellFormed())
|
|
107
|
+
throw TypeError("transform operands must be well-formed strings");
|
|
108
|
+
}
|
|
109
|
+
export function snapshotTransforms(transforms) {
|
|
110
|
+
if (transforms === void 0)
|
|
111
|
+
return;
|
|
112
|
+
if (!Array.isArray(transforms))
|
|
113
|
+
throw TypeError("transform must be an array of column transforms");
|
|
114
|
+
if (transforms.length > MAX_COLUMN_INDEX + 1)
|
|
115
|
+
throw RangeError("too many transform columns");
|
|
116
|
+
const captured = [...transforms];
|
|
117
|
+
const seen = new Set;
|
|
118
|
+
for (const token of captured) {
|
|
119
|
+
const binding = bindings.get(token);
|
|
120
|
+
if (!binding)
|
|
121
|
+
throw TypeError("transform requires a bound chain; call chain.on(column) or start with csv.column(column)");
|
|
122
|
+
for (const column of binding.columns) {
|
|
123
|
+
if (seen.has(column))
|
|
124
|
+
throw RangeError(`transform column repeated: ${column}`);
|
|
125
|
+
seen.add(column);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return Object.freeze(captured);
|
|
129
|
+
}
|
|
130
|
+
const cleanupOps = new Set([0 /* Trim */, 1 /* Upper */, 2 /* Lower */, 3 /* Unaccent */]);
|
|
131
|
+
export function hasOnlyCleanupTransforms(tokens) {
|
|
132
|
+
return tokens.every((token) => {
|
|
133
|
+
const binding = bindings.get(token);
|
|
134
|
+
for (let node = binding?.chain;node; node = node.previous)
|
|
135
|
+
if (!cleanupOps.has(node.step.kind))
|
|
136
|
+
return !1;
|
|
137
|
+
return binding !== void 0;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
export function selectTransforms(tokens, columns) {
|
|
141
|
+
const selected = new Set(columns);
|
|
142
|
+
const result = [];
|
|
143
|
+
for (const token of tokens) {
|
|
144
|
+
const binding = bindings.get(token);
|
|
145
|
+
if (!binding)
|
|
146
|
+
throw TypeError("expected a bound transform chain");
|
|
147
|
+
const targets = binding.columns.filter((column) => selected.has(column));
|
|
148
|
+
if (targets.length)
|
|
149
|
+
result.push(targets.length === binding.columns.length ? token : createChain(binding.chain, targets));
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
export function prepareTransforms(handle, tokens, selected) {
|
|
154
|
+
const columns = selected === void 0 ? void 0 : new Set(selected);
|
|
155
|
+
let active = !1;
|
|
156
|
+
for (const token of tokens) {
|
|
157
|
+
const binding = bindings.get(token);
|
|
158
|
+
if (!binding)
|
|
159
|
+
throw TypeError("expected a bound transform chain");
|
|
160
|
+
const targets = columns ? binding.columns.filter((column) => columns.has(column)) : binding.columns;
|
|
161
|
+
if (!targets.length)
|
|
162
|
+
continue;
|
|
163
|
+
const steps = [];
|
|
164
|
+
for (let node = binding.chain;node; node = node.previous)
|
|
165
|
+
steps.push(node.step);
|
|
166
|
+
steps.reverse();
|
|
167
|
+
for (const column of targets)
|
|
168
|
+
for (const step of steps) {
|
|
169
|
+
const fallback = "defaultValue" in step && step.defaultValue !== void 0 ? Buffer.from(step.defaultValue) : void 0;
|
|
170
|
+
const added = fallback !== void 0 ? native.symbols.csv_parser_add_transform_with_default(handle, column, step.kind, fallback, fallback) : native.symbols.csv_parser_add_transform(handle, column, step.kind);
|
|
171
|
+
if (!added)
|
|
172
|
+
throw Error("native parser rejected transform step");
|
|
173
|
+
if (step.kind === 4 /* ReplaceLiteral */ || step.kind === 9 /* ReplaceRegex */)
|
|
174
|
+
addPair(handle, column, step.search, step.replacement);
|
|
175
|
+
if (step.kind === 5 /* Map */)
|
|
176
|
+
for (const [key, value] of step.values)
|
|
177
|
+
addPair(handle, column, key, value);
|
|
178
|
+
}
|
|
179
|
+
active = !0;
|
|
180
|
+
}
|
|
181
|
+
return active;
|
|
182
|
+
}
|
|
183
|
+
function addPair(handle, column, key, value) {
|
|
184
|
+
const first = typeof key === "string" ? Buffer.from(key) : key;
|
|
185
|
+
const second = Buffer.from(value);
|
|
186
|
+
if (!native.symbols.csv_parser_transform_pair(handle, column, first, first, second, second)) {
|
|
187
|
+
const error = native.symbols.csv_parser_last_error(handle);
|
|
188
|
+
if (error)
|
|
189
|
+
throw SyntaxError(error);
|
|
190
|
+
throw Error("native parser rejected transform operands");
|
|
191
|
+
}
|
|
192
|
+
}
|