@konstit/csv 0.6.0 → 0.7.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 +113 -101
- package/THIRD_PARTY_NOTICES.md +27 -0
- package/dist/api.d.ts +84 -57
- package/dist/api.js +211 -40
- package/dist/batch-pipeline.d.ts +10 -0
- package/dist/batch-pipeline.js +83 -0
- package/dist/batches.d.ts +36 -1
- package/dist/batches.js +241 -5
- package/dist/cli-command.d.ts +7 -7
- package/dist/cli-command.js +325 -164
- package/dist/cli-schema.d.ts +51 -21
- package/dist/cli-schema.js +126 -65
- package/dist/cli.js +1 -1
- package/dist/file-stream.d.ts +66 -18
- package/dist/file-stream.js +534 -199
- package/dist/files.d.ts +17 -37
- package/dist/files.js +50 -21
- package/dist/gzip-reader.d.ts +2 -0
- package/dist/gzip-reader.js +37 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/inspect-file.d.ts +26 -3
- package/dist/inspect-file.js +169 -74
- package/dist/inspect-zip.d.ts +26 -0
- package/dist/inspect-zip.js +59 -0
- package/dist/latin1-rows.d.ts +11 -3
- package/dist/latin1-rows.js +276 -75
- package/dist/materialize-field.d.ts +6 -0
- package/dist/materialize-field.js +9 -0
- package/dist/native.d.ts +118 -20
- package/dist/native.js +53 -23
- package/dist/normalize.d.ts +7 -1
- package/dist/normalize.js +49 -9
- package/dist/options.d.ts +27 -12
- package/dist/parser.d.ts +34 -14
- package/dist/parser.js +296 -102
- package/dist/strict-schema.d.ts +7 -8
- package/dist/strict-schema.js +45 -83
- package/dist/transforms.d.ts +1 -3
- package/dist/transforms.js +17 -16
- package/dist/types.d.ts +192 -75
- package/dist/zip-entry.d.ts +14 -0
- package/dist/zip-entry.js +155 -0
- package/dist/zip-reader.d.ts +14 -3
- package/dist/zip-reader.js +65 -23
- package/package.json +34 -23
- 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 +18 -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/api.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
|
+
mappedBatchRows,
|
|
3
|
+
utf8BatchSlices
|
|
4
|
+
} from "./batches.js";
|
|
5
|
+
import {
|
|
6
|
+
detectBufferDelimiter,
|
|
2
7
|
prepareCsvFileInput,
|
|
3
|
-
rejectAutoDelimiterSharding,
|
|
4
8
|
rejectCompressedSharding
|
|
5
9
|
} from "./file-stream.js";
|
|
6
10
|
import {
|
|
@@ -19,8 +23,12 @@ import {
|
|
|
19
23
|
canUseFilteredLatin1Cleanup,
|
|
20
24
|
latin1Rows
|
|
21
25
|
} from "./latin1-rows.js";
|
|
26
|
+
import { sliceRowBatch } from "./materialize-field.js";
|
|
22
27
|
import { latin1RowsParser } from "./native.js";
|
|
23
28
|
import {
|
|
29
|
+
MAX_COLUMN_INDEX,
|
|
30
|
+
MAX_PROJECTION_LENGTH,
|
|
31
|
+
normalizeColumns,
|
|
24
32
|
normalizeFixedColumnsCount,
|
|
25
33
|
prepareCsvBufferInput,
|
|
26
34
|
resolveInputEncoding
|
|
@@ -30,82 +38,245 @@ import {
|
|
|
30
38
|
countFileChunks,
|
|
31
39
|
createPreparedParser,
|
|
32
40
|
parseFileChunks,
|
|
41
|
+
parseRawRecordChunks,
|
|
42
|
+
parseUtf8RowBatches,
|
|
43
|
+
readCsvHeader,
|
|
33
44
|
validateRowSelection
|
|
34
45
|
} from "./parser.js";
|
|
35
|
-
import {
|
|
46
|
+
import { strictSchemaValidator } from "./strict-schema.js";
|
|
36
47
|
import { transform } from "./transforms.js";
|
|
37
48
|
export async function parse(buffer, suppliedOptions = {}) {
|
|
38
49
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
39
50
|
if ("compression" in options && options.compression !== void 0)
|
|
40
51
|
throw Error("parse() does not support compression; pass decompressed bytes or use a file API");
|
|
41
|
-
if (options.delimiter === "auto")
|
|
42
|
-
throw Error("parse() does not support automatic delimiter detection; specify delimiter or use a file API");
|
|
43
|
-
rejectFilteredStrictSchema(options);
|
|
44
52
|
const filters = toNativeFilters(options.where);
|
|
45
53
|
const columns = options.columns;
|
|
46
|
-
const projected = filters !== void 0 ||
|
|
54
|
+
const projected = filters !== void 0 || columns !== void 0;
|
|
47
55
|
const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
|
|
48
|
-
|
|
49
|
-
|
|
56
|
+
const delimiter = options.delimiter === void 0 || options.delimiter === "auto" ? detectBufferDelimiter(input.bytes, "", !0, options) : options.delimiter;
|
|
57
|
+
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, delimiter), projected ? columns : void 0, filters, options.transform);
|
|
58
|
+
return consumeBatchRows(parser.writeBatch(input.bytes, !0));
|
|
50
59
|
}
|
|
51
60
|
export function rows(path, options = {}) {
|
|
52
|
-
|
|
61
|
+
if (options.mapped !== void 0 && typeof options.mapped !== "boolean")
|
|
62
|
+
throw TypeError("mapped must be a boolean");
|
|
63
|
+
if (options.mapped === !0 && options.headers === void 0)
|
|
64
|
+
throw TypeError("mapped rows require headers");
|
|
65
|
+
const maxBatchRows = options.maxBatchRows;
|
|
66
|
+
if (maxBatchRows !== void 0) {
|
|
67
|
+
if (!Number.isSafeInteger(maxBatchRows) || maxBatchRows < 1)
|
|
68
|
+
throw RangeError("maxBatchRows must be a positive safe integer");
|
|
69
|
+
if (options.reuseArrays === !0)
|
|
70
|
+
throw TypeError("maxBatchRows requires owned rows");
|
|
71
|
+
}
|
|
72
|
+
return options.headers === void 0 ? iterateRows(path, snapshotCsvOptions(options)) : rowsWithHeaders(path, options);
|
|
73
|
+
}
|
|
74
|
+
function rowsWithHeaders(path, supplied) {
|
|
75
|
+
const { headers, columns, mapped, where, transform, ...fileOptions } = supplied;
|
|
76
|
+
if (mapped === !0 && fileOptions.reuseArrays === !0)
|
|
77
|
+
throw TypeError("reuseArrays requires array rows");
|
|
78
|
+
if (columns !== void 0 && !Array.isArray(columns))
|
|
79
|
+
throw TypeError("columns must be an array of header names");
|
|
80
|
+
if (columns !== void 0 && columns.length > MAX_PROJECTION_LENGTH)
|
|
81
|
+
throw RangeError(`selected column count out of range: ${columns.length}`);
|
|
82
|
+
const selected = columns === void 0 ? void 0 : [...columns];
|
|
83
|
+
if (selected !== void 0 && new Set(selected).size !== selected.length)
|
|
84
|
+
throw RangeError("selected header names must be unique");
|
|
85
|
+
if (headers === !0) {
|
|
86
|
+
const options = snapshotCsvOptions({
|
|
87
|
+
...fileOptions,
|
|
88
|
+
where: typeof where === "function" ? void 0 : where,
|
|
89
|
+
transform: typeof transform === "function" ? void 0 : transform
|
|
90
|
+
});
|
|
91
|
+
return iterateRowsWithReadHeader(path, options, {
|
|
92
|
+
columns: selected,
|
|
93
|
+
mapped,
|
|
94
|
+
where: typeof where === "function" ? where : options.where,
|
|
95
|
+
transform: typeof transform === "function" ? transform : options.transform
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const { options, layout } = bindNamedRows(fileOptions, headers, { columns: selected, mapped, where, transform });
|
|
99
|
+
return layout === void 0 ? iterateRows(path, options) : iterateRows(path, options, void 0, layout);
|
|
53
100
|
}
|
|
54
|
-
|
|
55
|
-
|
|
101
|
+
function bindNamedRows(fileOptions, names, { columns: selected, mapped, where, transform }) {
|
|
102
|
+
const resolve = headerIndexes(names);
|
|
103
|
+
const physicalColumns = selected?.map(resolve);
|
|
104
|
+
const keys = mapped === !0 ? selected ?? [...names] : void 0;
|
|
105
|
+
const namedColumn = (name) => column(resolve(name));
|
|
106
|
+
const filter = bindNamedFilter(where, namedColumn);
|
|
107
|
+
const transforms = typeof transform === "function" ? transform(namedColumn) : transform;
|
|
108
|
+
if (typeof transform === "function" && transforms === void 0)
|
|
109
|
+
throw TypeError("transform callback must return an array of column transforms");
|
|
110
|
+
const options = snapshotCsvOptions({
|
|
111
|
+
...fileOptions,
|
|
112
|
+
columns: physicalColumns,
|
|
113
|
+
where: filter,
|
|
114
|
+
transform: transforms
|
|
115
|
+
});
|
|
116
|
+
if (keys === void 0)
|
|
117
|
+
return { options };
|
|
118
|
+
const template = keys.includes("__proto__") ? Object.fromEntries(keys.map((name) => [name, ""])) : void 0;
|
|
119
|
+
return { options, layout: { keys, template } };
|
|
120
|
+
}
|
|
121
|
+
function headerIndexes(names) {
|
|
122
|
+
if (!Array.isArray(names))
|
|
123
|
+
throw TypeError("headers must be an array of strings or true");
|
|
124
|
+
if (names.length > MAX_COLUMN_INDEX + 1)
|
|
125
|
+
throw RangeError(`header count out of range: ${names.length}`);
|
|
126
|
+
const indexes = new Map;
|
|
127
|
+
for (const [index, name] of names.entries()) {
|
|
128
|
+
if (typeof name !== "string")
|
|
129
|
+
throw TypeError(`header at index ${index} must be a string`);
|
|
130
|
+
if (indexes.has(name))
|
|
131
|
+
throw RangeError(`duplicate header: ${JSON.stringify(name)}`);
|
|
132
|
+
indexes.set(name, index);
|
|
133
|
+
}
|
|
134
|
+
return (name) => {
|
|
135
|
+
if (typeof name !== "string")
|
|
136
|
+
throw TypeError("column name must be a string");
|
|
137
|
+
const index = indexes.get(name);
|
|
138
|
+
if (index === void 0)
|
|
139
|
+
throw RangeError(`unknown header: ${JSON.stringify(name)}`);
|
|
140
|
+
return index;
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function bindNamedFilter(where, namedColumn) {
|
|
144
|
+
if (typeof where !== "function")
|
|
145
|
+
return where;
|
|
146
|
+
const filter = where(namedColumn);
|
|
147
|
+
if (filter === void 0)
|
|
148
|
+
throw TypeError("where callback must return a filter");
|
|
149
|
+
return filter;
|
|
150
|
+
}
|
|
151
|
+
async function prepareInputWithReadHeader(path, options, mode, resources) {
|
|
152
|
+
validateRowSelection(options);
|
|
153
|
+
const input = resources.use(await prepareCsvFileInput(path, options, mode));
|
|
154
|
+
const { names, record } = await input.readPrefix((next) => readCsvHeader(next, toParserOptions(options, input.parserEncoding, input.delimiter)));
|
|
155
|
+
return { input, names, skipRows: Math.max(record, options.skipRows ?? 0) };
|
|
156
|
+
}
|
|
157
|
+
async function* iterateRowsWithReadHeader(path, fileOptions, bindings) {
|
|
158
|
+
await using resources = new AsyncDisposableStack;
|
|
159
|
+
const { input, names, skipRows } = await prepareInputWithReadHeader(path, fileOptions, "read-ahead", resources);
|
|
160
|
+
const { options, layout } = bindNamedRows({ ...fileOptions, skipRows }, names, bindings);
|
|
161
|
+
const filters = toNativeFilters(options.where);
|
|
162
|
+
if (options.limit === 0) {
|
|
163
|
+
strictSchemaValidator(options)?.finish(1);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
yield* iteratePreparedRows(input, options, filters, layout);
|
|
167
|
+
}
|
|
168
|
+
export async function* iterateRows(path, options, probeFormat, layout) {
|
|
56
169
|
const filters = toNativeFilters(options.where);
|
|
57
|
-
const columns = options.columns;
|
|
58
|
-
const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
|
|
59
170
|
await using input = await prepareCsvFileInput(path, options, "read-ahead", probeFormat);
|
|
171
|
+
yield* iteratePreparedRows(input, options, filters, layout);
|
|
172
|
+
}
|
|
173
|
+
async function* iteratePreparedRows(input, options, filters, layout) {
|
|
174
|
+
const columns = options.columns;
|
|
175
|
+
const projected = filters !== void 0 || columns !== void 0;
|
|
60
176
|
const reusableRows = options.reuseArrays === !0 ? [] : void 0;
|
|
61
|
-
|
|
177
|
+
const transforms = options.transform;
|
|
178
|
+
if (input.parserEncoding === "latin1" && options.quote !== !1 && options.recordDelimiter === void 0 && (!transforms?.length || options.strict !== !0 && options.maxRecordBytes === void 0 && canUseFilteredLatin1Cleanup(columns, filters, transforms))) {
|
|
62
179
|
validateRowSelection(options);
|
|
63
180
|
const fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
|
|
64
|
-
const createParser = latin1RowsParser(fixedColumns, Boolean(
|
|
65
|
-
|
|
66
|
-
|
|
181
|
+
const createParser = latin1RowsParser(fixedColumns, Boolean(transforms?.length));
|
|
182
|
+
if (layout === void 0)
|
|
183
|
+
yield* latin1Rows(input, input.delimiter, columns, filters, createParser, reusableRows, options);
|
|
184
|
+
else
|
|
185
|
+
yield* latin1Rows(input, input.delimiter, columns, filters, createParser, layout, options);
|
|
67
186
|
return;
|
|
68
187
|
}
|
|
69
188
|
const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
189
|
+
const canPipeline = input.parserEncoding === "utf8" && input.canParseAhead !== void 0;
|
|
190
|
+
using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, transforms, canPipeline ? "pipelined-rows" : "rows");
|
|
191
|
+
const batches = canPipeline ? parseUtf8RowBatches(input, parser, options.limit) : parseFileChunks(input, parser, options.limit);
|
|
192
|
+
const maxBatchRows = options.maxBatchRows;
|
|
193
|
+
for await (const batch of batches) {
|
|
194
|
+
let rows;
|
|
195
|
+
{
|
|
196
|
+
using nativeBatch = batch;
|
|
197
|
+
if (maxBatchRows !== void 0 && input.parserEncoding === "utf8" && nativeBatch.rowCount > maxBatchRows) {
|
|
198
|
+
yield* nativeBatch[utf8BatchSlices](maxBatchRows, layout);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
rows = layout === void 0 ? nativeBatch.rowsInto(reusableRows ?? []) : nativeBatch[mappedBatchRows](layout, "utf8");
|
|
202
|
+
}
|
|
203
|
+
if (maxBatchRows !== void 0 && rows.length > maxBatchRows)
|
|
204
|
+
yield* sliceRowBatch(rows, maxBatchRows);
|
|
205
|
+
else
|
|
206
|
+
yield rows;
|
|
207
|
+
}
|
|
73
208
|
}
|
|
74
209
|
export function batches(path, options = {}) {
|
|
75
210
|
return iterateBatches(path, snapshotCsvOptions(options));
|
|
76
211
|
}
|
|
77
212
|
async function* iterateBatches(path, options) {
|
|
78
|
-
rejectFilteredStrictSchema(options);
|
|
79
213
|
const filters = toNativeFilters(options.where);
|
|
80
|
-
const columns = options
|
|
81
|
-
if (options.
|
|
82
|
-
|
|
83
|
-
|
|
214
|
+
const { columns, encoding: requestedEncoding, strict, transform } = options;
|
|
215
|
+
if (options.output === "raw-records") {
|
|
216
|
+
if (options.quote !== !1 || options.recordDelimiter !== `
|
|
217
|
+
`)
|
|
218
|
+
throw TypeError("raw-records output requires quote: false and recordDelimiter: LF");
|
|
219
|
+
if (columns !== void 0 || transform !== void 0 || strict === !0)
|
|
220
|
+
throw TypeError("raw-records output does not support projection, transforms, or strict CSV validation");
|
|
221
|
+
const encoding = requestedEncoding === "auto" ? void 0 : resolveInputEncoding(requestedEncoding);
|
|
222
|
+
if (typeof encoding !== "string")
|
|
223
|
+
throw TypeError("raw-records output requires a native UTF-8 or Latin-1 encoding");
|
|
224
|
+
await using input = await prepareCsvFileInput(path, { ...options, encoding }, "raw-records");
|
|
225
|
+
yield* parseRawRecordChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (options.output !== void 0 && options.output !== "fields")
|
|
229
|
+
throw TypeError("output must be fields or raw-records");
|
|
230
|
+
await using input = await prepareCsvFileInput(path, options, "batches");
|
|
84
231
|
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters, options.transform);
|
|
85
232
|
yield* parseFileChunks(input, parser, options.limit);
|
|
86
233
|
}
|
|
87
234
|
export async function count(path, suppliedOptions = {}) {
|
|
88
|
-
|
|
235
|
+
if (suppliedOptions.headers === !0) {
|
|
236
|
+
const { headers: _headers, where, ...fileOptions } = suppliedOptions;
|
|
237
|
+
const options = snapshotCsvOptions({ ...fileOptions, where: typeof where === "function" ? void 0 : where });
|
|
238
|
+
await using resources = new AsyncDisposableStack;
|
|
239
|
+
const { input, names, skipRows } = await prepareInputWithReadHeader(path, options, "count", resources);
|
|
240
|
+
const resolve = headerIndexes(names);
|
|
241
|
+
const filter = bindNamedFilter(where, (name) => column(resolve(name)));
|
|
242
|
+
const filters = toNativeFilters(filter);
|
|
243
|
+
if (options.limit === 0) {
|
|
244
|
+
normalizeColumns(options.columns);
|
|
245
|
+
strictSchemaValidator(options)?.finish(1);
|
|
246
|
+
return 0;
|
|
247
|
+
}
|
|
248
|
+
return await countFileChunks(input, toParserOptions({ ...options, skipRows }, input.parserEncoding, input.delimiter), filters);
|
|
249
|
+
}
|
|
250
|
+
let options;
|
|
251
|
+
if (suppliedOptions.headers === void 0)
|
|
252
|
+
options = snapshotCsvOptions(suppliedOptions);
|
|
253
|
+
else {
|
|
254
|
+
const { headers, where, ...fileOptions } = suppliedOptions;
|
|
255
|
+
const resolve = headerIndexes(headers);
|
|
256
|
+
options = snapshotCsvOptions({ ...fileOptions, where: bindNamedFilter(where, (name) => column(resolve(name))) });
|
|
257
|
+
}
|
|
89
258
|
const filters = toNativeFilters(options.where);
|
|
90
259
|
await using input = await prepareCsvFileInput(path, options, "count");
|
|
91
|
-
if (options.strict === !0 && filters !== void 0)
|
|
92
|
-
throw Error("strict CSV validation is not supported for count filters");
|
|
93
260
|
return await countFileChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
|
|
94
261
|
}
|
|
95
262
|
function findCsvSafeSplitOffsets(path, shardCount, suppliedOptions = {}) {
|
|
96
263
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
97
|
-
|
|
264
|
+
const encoding = shardingEncoding(options, "CSV split offset scanning");
|
|
265
|
+
return findCsvSafeSplitOffsetsNative(path, shardCount, options.delimiter, encoding);
|
|
98
266
|
}
|
|
99
267
|
function findCsvSafeShards(path, shardCount, suppliedOptions = {}) {
|
|
100
268
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
101
|
-
|
|
269
|
+
const encoding = shardingEncoding(options, "CSV shard scanning");
|
|
270
|
+
return findCsvSafeShardsNative(path, shardCount, options.delimiter, encoding);
|
|
102
271
|
}
|
|
103
|
-
function
|
|
272
|
+
function shardingEncoding(options, operation) {
|
|
104
273
|
rejectCompressedSharding(options, operation);
|
|
105
|
-
|
|
106
|
-
|
|
274
|
+
if ("quote" in options && options.quote === !1 || "recordDelimiter" in options && options.recordDelimiter !== void 0)
|
|
275
|
+
throw Error(`${operation} requires the default quote and record delimiter settings`);
|
|
276
|
+
const encoding = resolveInputEncoding(options.encoding);
|
|
277
|
+
if (typeof encoding !== "string")
|
|
107
278
|
throw Error(`${operation} requires a native UTF-8 or Latin-1 encoding because offsets refer to the source file`);
|
|
108
|
-
return
|
|
279
|
+
return encoding;
|
|
109
280
|
}
|
|
110
281
|
export const csv = {
|
|
111
282
|
transform,
|
|
@@ -125,23 +296,23 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
|
|
|
125
296
|
return {
|
|
126
297
|
delimiter,
|
|
127
298
|
encoding,
|
|
299
|
+
quote: options.quote,
|
|
300
|
+
recordDelimiter: options.recordDelimiter,
|
|
128
301
|
strict: options.strict,
|
|
129
302
|
columns: options.columns,
|
|
130
303
|
fixedColumns: options.fixedColumns,
|
|
304
|
+
maxRecordBytes: options.maxRecordBytes,
|
|
131
305
|
skipRows: options.skipRows,
|
|
306
|
+
skipEmptyLines: options.skipEmptyLines,
|
|
132
307
|
limit: options.limit,
|
|
133
308
|
expectedHeaders: options.expectedHeaders,
|
|
134
309
|
requireHeader: options.requireHeader,
|
|
135
310
|
minDataRows: options.minDataRows
|
|
136
311
|
};
|
|
137
312
|
}
|
|
138
|
-
function consumeBatchRows(nativeBatch
|
|
313
|
+
function consumeBatchRows(nativeBatch) {
|
|
139
314
|
using batch = nativeBatch;
|
|
140
|
-
return batch.
|
|
141
|
-
}
|
|
142
|
-
function rejectFilteredStrictSchema(options) {
|
|
143
|
-
if (options.where !== void 0)
|
|
144
|
-
rejectStrictSchemaUnsupported(options, "filtered rows");
|
|
315
|
+
return batch.rows();
|
|
145
316
|
}
|
|
146
317
|
function toNativeFilters(where) {
|
|
147
318
|
return nativeFilterProgramFor(where);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type NativePointer } from './native.js';
|
|
2
|
+
export declare class BatchPipeline implements Disposable {
|
|
3
|
+
#private;
|
|
4
|
+
static start(parser: NativePointer, owner: object, compactOffsets?: BigUint64Array): BatchPipeline | undefined;
|
|
5
|
+
private constructor();
|
|
6
|
+
readonly recycle: (batch: NativePointer) => void;
|
|
7
|
+
/** Transfers ownership of each nonempty batch to the caller. */
|
|
8
|
+
batches(chunks: AsyncIterator<Uint8Array, void>, first: Uint8Array, remaining: number | undefined, validate: ((final: boolean) => void) | undefined, finishAtLimit: (() => void) | undefined): AsyncGenerator<NativePointer, void>;
|
|
9
|
+
[Symbol.dispose](): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EMPTY_BUFFER,
|
|
3
|
+
native,
|
|
4
|
+
u64ToSafeNumber
|
|
5
|
+
} from "./native.js";
|
|
6
|
+
import { normalizeChunk } from "./normalize.js";
|
|
7
|
+
function closePipeline(lifetime) {
|
|
8
|
+
native.symbols.csv_parser_batch_pipeline_destroy(lifetime.handle);
|
|
9
|
+
lifetime.input = void 0;
|
|
10
|
+
}
|
|
11
|
+
const finalizer = new FinalizationRegistry(closePipeline);
|
|
12
|
+
|
|
13
|
+
export class BatchPipeline {
|
|
14
|
+
#lifetime;
|
|
15
|
+
#offsets;
|
|
16
|
+
#parser;
|
|
17
|
+
static start(parser, owner, compactOffsets) {
|
|
18
|
+
const offsets = compactOffsets ?? new BigUint64Array(1);
|
|
19
|
+
const handle = native.symbols.csv_parser_batch_pipeline_start(parser, compactOffsets !== void 0);
|
|
20
|
+
return handle === null ? void 0 : new BatchPipeline(handle, parser, owner, offsets);
|
|
21
|
+
}
|
|
22
|
+
constructor(handle, parser, owner, offsets) {
|
|
23
|
+
this.#lifetime = { handle, parserOwner: owner, input: void 0 };
|
|
24
|
+
this.#offsets = offsets;
|
|
25
|
+
this.#parser = parser;
|
|
26
|
+
finalizer.register(this, this.#lifetime, this);
|
|
27
|
+
}
|
|
28
|
+
recycle = (batch) => {
|
|
29
|
+
native.symbols.csv_parser_batch_pipeline_recycle(this.#lifetime.handle, batch);
|
|
30
|
+
};
|
|
31
|
+
#submit(input, final) {
|
|
32
|
+
const bytes = normalizeChunk(input);
|
|
33
|
+
if (!native.symbols.csv_parser_batch_pipeline_submit(this.#lifetime.handle, bytes, bytes, final))
|
|
34
|
+
throw Error("failed to submit the next native CSV batch");
|
|
35
|
+
this.#lifetime.input = bytes;
|
|
36
|
+
}
|
|
37
|
+
async* batches(chunks, first, remaining, validate, finishAtLimit) {
|
|
38
|
+
let final = !1;
|
|
39
|
+
this.#submit(first, final);
|
|
40
|
+
while (!0) {
|
|
41
|
+
const lastWrite = final;
|
|
42
|
+
const batch = native.symbols.csv_parser_batch_pipeline_take(this.#lifetime.handle, this.#offsets);
|
|
43
|
+
this.#lifetime.input = void 0;
|
|
44
|
+
if (batch === null)
|
|
45
|
+
throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(this.#parser) ?? "native parser error unavailable"}`);
|
|
46
|
+
let rowCount;
|
|
47
|
+
let atLimit;
|
|
48
|
+
try {
|
|
49
|
+
validate?.(lastWrite);
|
|
50
|
+
rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
|
|
51
|
+
atLimit = remaining === rowCount;
|
|
52
|
+
if (atLimit && !lastWrite)
|
|
53
|
+
finishAtLimit?.();
|
|
54
|
+
} catch (error) {
|
|
55
|
+
native.symbols.csv_batch_destroy(batch);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
let nextFailure;
|
|
59
|
+
if (!lastWrite && !atLimit)
|
|
60
|
+
try {
|
|
61
|
+
const next = await chunks.next();
|
|
62
|
+
final = next.done === !0;
|
|
63
|
+
this.#submit(next.done === !0 ? EMPTY_BUFFER : next.value, final);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
nextFailure = { error };
|
|
66
|
+
}
|
|
67
|
+
if (rowCount > 0)
|
|
68
|
+
yield batch;
|
|
69
|
+
else
|
|
70
|
+
this.recycle(batch);
|
|
71
|
+
if (nextFailure !== void 0)
|
|
72
|
+
throw nextFailure.error;
|
|
73
|
+
if (lastWrite || atLimit)
|
|
74
|
+
return;
|
|
75
|
+
if (remaining !== void 0)
|
|
76
|
+
remaining -= rowCount;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
[Symbol.dispose]() {
|
|
80
|
+
if (finalizer.unregister(this))
|
|
81
|
+
closePipeline(this.#lifetime);
|
|
82
|
+
}
|
|
83
|
+
}
|
package/dist/batches.d.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { type NativePointer } from './native.js';
|
|
2
|
-
import type { CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvFieldRange, CsvRow, CsvScanColumnsCallback, NativeCsvRowCallback } from './types.js';
|
|
2
|
+
import type { CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvFieldRange, CsvMappedRow, CsvRow, CsvScanColumnsCallback, NativeCsvRowCallback } from './types.js';
|
|
3
3
|
declare const visitBatchRows: unique symbol;
|
|
4
|
+
export declare const mappedBatchRows: unique symbol;
|
|
5
|
+
export declare const utf8BatchSlices: unique symbol;
|
|
6
|
+
export declare const recycleBatch: unique symbol;
|
|
7
|
+
export interface MappedRowLayout {
|
|
8
|
+
readonly keys: readonly string[];
|
|
9
|
+
readonly template: Record<string, string> | undefined;
|
|
10
|
+
}
|
|
4
11
|
/**
|
|
5
12
|
* A reusable, low-allocation view over one row in a {@link NativeCsvBatch}.
|
|
6
13
|
*
|
|
@@ -154,6 +161,9 @@ export declare class NativeCsvBatch {
|
|
|
154
161
|
* exceeds the batch backing storage.
|
|
155
162
|
*/
|
|
156
163
|
rowsInto(target: CsvRow[], columns?: CsvColumns): CsvRow[];
|
|
164
|
+
/** Borrow the batch across slices. The caller disposes it if iteration ends early. */
|
|
165
|
+
[utf8BatchSlices](maxBatchRows: number, layout?: MappedRowLayout): Generator<CsvRow[] | CsvMappedRow[], void>;
|
|
166
|
+
[mappedBatchRows](layout: MappedRowLayout, encoding: 'latin1' | 'utf8'): CsvMappedRow[];
|
|
157
167
|
/**
|
|
158
168
|
* Returns the concatenated field bytes as a borrowed `Buffer`.
|
|
159
169
|
*
|
|
@@ -283,7 +293,32 @@ export declare class NativeCsvBatch {
|
|
|
283
293
|
* Calling `close()` more than once is safe.
|
|
284
294
|
*/
|
|
285
295
|
close(): void;
|
|
296
|
+
[recycleBatch](recycle: (batch: NativePointer) => void): void;
|
|
286
297
|
/** Implements `using` / explicit resource management. */
|
|
287
298
|
[Symbol.dispose](): void;
|
|
288
299
|
}
|
|
300
|
+
/**
|
|
301
|
+
* Owns a batch of original decompressed records. Consume or copy borrowed bytes
|
|
302
|
+
* before closing the batch. Each batch can be disposed independently of its iterator.
|
|
303
|
+
*/
|
|
304
|
+
export declare class NativeCsvRawRecordBatch {
|
|
305
|
+
#private;
|
|
306
|
+
/**
|
|
307
|
+
* Wraps an owned native raw-record batch handle. Get batches from `csv.batches()`.
|
|
308
|
+
* @internal
|
|
309
|
+
*/
|
|
310
|
+
constructor(handle: NativePointer);
|
|
311
|
+
/** Whether the native storage has been released. */
|
|
312
|
+
get closed(): boolean;
|
|
313
|
+
/** Number of accepted records in this batch. */
|
|
314
|
+
get rowCount(): number;
|
|
315
|
+
/** Returns the original decompressed bytes for a zero-based row, including its LF when present. */
|
|
316
|
+
rowBytes(rowIndex: number): Uint8Array;
|
|
317
|
+
/** Returns the physical field count for a zero-based row, including empty fields. */
|
|
318
|
+
rowFieldCount(rowIndex: number): number;
|
|
319
|
+
/** Releases the native storage and invalidates borrowed bytes. Safe to call more than once. */
|
|
320
|
+
close(): void;
|
|
321
|
+
/** Releases the native storage at the end of a `using` scope. */
|
|
322
|
+
[Symbol.dispose](): void;
|
|
323
|
+
}
|
|
289
324
|
export {};
|