@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.
Files changed (53) hide show
  1. package/README.md +113 -101
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +84 -57
  4. package/dist/api.js +211 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +36 -1
  8. package/dist/batches.js +241 -5
  9. package/dist/cli-command.d.ts +7 -7
  10. package/dist/cli-command.js +325 -164
  11. package/dist/cli-schema.d.ts +51 -21
  12. package/dist/cli-schema.js +126 -65
  13. package/dist/cli.js +1 -1
  14. package/dist/file-stream.d.ts +66 -18
  15. package/dist/file-stream.js +534 -199
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +50 -21
  18. package/dist/gzip-reader.d.ts +2 -0
  19. package/dist/gzip-reader.js +37 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +2 -2
  22. package/dist/inspect-file.d.ts +26 -3
  23. package/dist/inspect-file.js +169 -74
  24. package/dist/inspect-zip.d.ts +26 -0
  25. package/dist/inspect-zip.js +59 -0
  26. package/dist/latin1-rows.d.ts +11 -3
  27. package/dist/latin1-rows.js +276 -75
  28. package/dist/materialize-field.d.ts +6 -0
  29. package/dist/materialize-field.js +9 -0
  30. package/dist/native.d.ts +118 -20
  31. package/dist/native.js +53 -23
  32. package/dist/normalize.d.ts +7 -1
  33. package/dist/normalize.js +49 -9
  34. package/dist/options.d.ts +27 -12
  35. package/dist/parser.d.ts +34 -14
  36. package/dist/parser.js +296 -102
  37. package/dist/strict-schema.d.ts +7 -8
  38. package/dist/strict-schema.js +45 -83
  39. package/dist/transforms.d.ts +1 -3
  40. package/dist/transforms.js +17 -16
  41. package/dist/types.d.ts +192 -75
  42. package/dist/zip-entry.d.ts +14 -0
  43. package/dist/zip-entry.js +155 -0
  44. package/dist/zip-reader.d.ts +14 -3
  45. package/dist/zip-reader.js +65 -23
  46. package/package.json +34 -23
  47. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  48. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  49. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  50. package/prebuilds/manifest.json +18 -8
  51. package/prebuilds/provenance/darwin-arm64.json +1 -1
  52. package/prebuilds/provenance/darwin-x64.json +1 -1
  53. package/prebuilds/provenance/linux-x64.json +1 -1
package/dist/parser.js CHANGED
@@ -1,10 +1,19 @@
1
- import { NativeCsvBatch } from "./batches.js";
1
+ import { BatchPipeline } from "./batch-pipeline.js";
2
+ import {
3
+ NativeCsvBatch,
4
+ NativeCsvRawRecordBatch
5
+ } from "./batches.js";
6
+ import {
7
+ detectBufferDelimiter,
8
+ FILE_PROBE_SIZE
9
+ } from "./file-stream.js";
2
10
  import {
3
11
  EMPTY_BUFFER,
4
12
  native,
5
13
  u64ToSafeNumber
6
14
  } from "./native.js";
7
15
  import {
16
+ delimiterByte,
8
17
  encodingCode,
9
18
  normalizeChunk,
10
19
  normalizeColumns,
@@ -12,51 +21,139 @@ import {
12
21
  normalizeNativeFilterProgram,
13
22
  normalizeNativeFilters,
14
23
  projectionFilterProgram,
15
- rejectSelectedColumns
24
+ rejectSelectedColumns,
25
+ validateCsvDialect
16
26
  } from "./normalize.js";
17
27
  import {
18
28
  strictSchemaValidator
19
29
  } from "./strict-schema.js";
20
30
  import {
21
31
  prepareTransforms,
22
- selectTransforms,
23
32
  snapshotTransforms
24
33
  } from "./transforms.js";
25
34
  function destroyNativeCsvParser(handle) {
26
35
  native.symbols.csv_parser_destroy(handle);
27
36
  }
28
37
  export const nativeCsvParserFinalizer = new FinalizationRegistry(destroyNativeCsvParser);
29
- export async function* parseFileChunks(input, parser, limit) {
38
+ export async function readCsvHeader(nextChunk, options) {
39
+ using parser = createPreparedParser({
40
+ ...options,
41
+ columns: void 0,
42
+ skipRows: void 0,
43
+ limit: 1,
44
+ minDataRows: void 0
45
+ });
46
+ const pending = [];
47
+ let blankRecords = 0;
48
+ let endsWithCr = !1;
49
+ let names;
50
+ while (names === void 0) {
51
+ const next = await nextChunk();
52
+ if (next.done === !0) {
53
+ [names] = parser.end();
54
+ if (names === void 0)
55
+ throw Error("CSV input is missing a header record");
56
+ break;
57
+ }
58
+ const chunk = next.value;
59
+ if (chunk.length === 0)
60
+ continue;
61
+ [names] = parser.write(chunk);
62
+ if (names !== void 0) {
63
+ pending.push(chunk);
64
+ break;
65
+ }
66
+ if (pending.length === 0 && options.skipEmptyLines === !0 && chunk.every((byte) => byte === 10 || options.recordDelimiter === void 0 && byte === 13)) {
67
+ blankRecords = parser[physicalRows]();
68
+ endsWithCr = chunk.at(-1) === 13;
69
+ } else
70
+ pending.push(new Uint8Array(chunk));
71
+ }
72
+ function* prefix() {
73
+ let lines = blankRecords - Number(endsWithCr);
74
+ if (lines > 0) {
75
+ const buffer = new Uint8Array(Math.min(65536, lines)).fill(10);
76
+ while (lines > 0) {
77
+ const length = Math.min(lines, buffer.length);
78
+ yield buffer.subarray(0, length);
79
+ lines -= length;
80
+ }
81
+ }
82
+ if (endsWithCr)
83
+ yield Uint8Array.of(13);
84
+ yield* pending;
85
+ pending.length = 0;
86
+ }
87
+ return { value: { names, record: parser[physicalRows]() }, replay: prefix() };
88
+ }
89
+ export async function* parseFileChunks(input, parser, limit, openParseAhead) {
30
90
  let remaining = limit;
31
- if (remaining !== 0)
32
- for await (const chunk of input.chunks()) {
91
+ if (remaining !== 0) {
92
+ const cursor = input.chunks()[Symbol.asyncIterator]();
93
+ for await (const chunk of { [Symbol.asyncIterator]: () => cursor }) {
94
+ if (openParseAhead !== void 0 && input.canParseAhead) {
95
+ const ahead = openParseAhead(cursor, chunk, remaining);
96
+ openParseAhead = void 0;
97
+ if (ahead !== void 0) {
98
+ yield* ahead;
99
+ return;
100
+ }
101
+ }
33
102
  const batch = parser.writeBatch(chunk);
34
103
  const count = batch.rowCount;
104
+ if (remaining !== void 0) {
105
+ remaining -= count;
106
+ if (remaining === 0) {
107
+ try {
108
+ parser.writeBatch(EMPTY_BUFFER, !0).close();
109
+ } catch (error) {
110
+ batch.close();
111
+ throw error;
112
+ }
113
+ yield batch;
114
+ return;
115
+ }
116
+ }
35
117
  if (count > 0)
36
118
  yield batch;
37
119
  else
38
120
  batch.close();
39
- if (remaining !== void 0) {
40
- remaining -= count;
41
- if (remaining === 0)
42
- break;
43
- }
44
121
  }
45
- const final = parser.endBatch();
122
+ }
123
+ const final = parser.writeBatch(EMPTY_BUFFER, !0);
46
124
  if (final.rowCount > 0)
47
125
  yield final;
48
126
  else
49
127
  final.close();
50
128
  }
129
+ export function parseUtf8RowBatches(input, parser, limit) {
130
+ return parseFileChunks(input, parser, limit, (chunks, first, remaining) => parser[openPipeline](chunks, first, remaining));
131
+ }
132
+ export async function* parseRawRecordChunks(input, options, program) {
133
+ normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
134
+ const handle = createNativeCsvParser(options, input.delimiter, !0);
135
+ const parser = {
136
+ writeBatch(chunk, final = !1) {
137
+ const bytes = normalizeChunk(chunk);
138
+ const batch = native.symbols.csv_parser_write_raw_records(handle, bytes, bytes, final);
139
+ if (batch === null)
140
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
141
+ return new NativeCsvRawRecordBatch(batch);
142
+ }
143
+ };
144
+ nativeCsvParserFinalizer.register(parser, handle, parser);
145
+ try {
146
+ prepareNativeParser(handle, void 0, program);
147
+ yield* parseFileChunks(input, parser, options.limit);
148
+ } finally {
149
+ nativeCsvParserFinalizer.unregister(parser);
150
+ destroyNativeCsvParser(handle);
151
+ }
152
+ }
51
153
  export async function countFileChunks(input, options, filters) {
52
154
  const columns = options.fixedColumns !== void 0 && options.strict !== !0 && filters === void 0 ? [] : void 0;
53
155
  using parser = createPreparedParser(options, columns, filters);
54
156
  let total = 0;
55
- if (options.strict === !0) {
56
- for await (using batch of parseFileChunks(input, parser, options.limit))
57
- total += batch.rowCount;
58
- return total;
59
- }
60
157
  if (options.limit !== 0)
61
158
  for await (const chunk of input.chunks()) {
62
159
  total += parser.writeCount(chunk);
@@ -71,106 +168,146 @@ export function createPreparedParser(options, columns, program, transform, outpu
71
168
  return NativeCsvParser[createSchemaParser]({
72
169
  encoding: options.encoding,
73
170
  delimiter: options.delimiter,
171
+ quote: options.quote,
172
+ recordDelimiter: options.recordDelimiter,
74
173
  fixedColumns: options.fixedColumns,
174
+ maxRecordBytes: options.maxRecordBytes,
75
175
  strict: options.strict,
76
176
  skipRows: options.skipRows,
177
+ skipEmptyLines: options.skipEmptyLines,
77
178
  limit: options.limit,
78
179
  expectedHeaders: options.expectedHeaders,
79
180
  requireHeader: options.requireHeader,
80
181
  minDataRows: options.minDataRows,
81
182
  columns,
82
183
  filterProgram: program,
83
- transform: options.strict && options.columns && transform ? selectTransforms(transform, options.columns) : transform
184
+ transform
84
185
  }, output);
85
186
  }
86
187
  export function prepareNativeParser(handle, columns, program) {
188
+ return configureNativeWriter(columns, program)(handle);
189
+ }
190
+ function configureNativeWriter(columns, program) {
87
191
  const normalizedColumns = normalizeColumns(columns);
88
192
  const hasProjection = columns !== void 0;
89
193
  const columnCount = BigInt(normalizedColumns.length);
90
194
  const normalized = program === void 0 ? normalizeNativeFilters(void 0) : normalizeNativeFilterProgram(program);
91
195
  const filterCount = BigInt(normalized.filterCount);
92
196
  const valueCount = BigInt(normalized.valueCount);
93
- if (!native.symbols.csv_parser_prepare(handle, hasProjection, normalizedColumns, columnCount, normalized.descriptors, filterCount, normalized.valuesData, normalized.valuesData, normalized.valueOffsets, valueCount))
94
- throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
95
- return {
96
- writeBatch: (input, final) => native.symbols.csv_parser_write_prepared_batch(handle, input, input, final),
97
- writeCount: (input, final) => {
98
- const count = native.symbols.csv_parser_write_prepared_count(handle, input, input, final);
99
- if (count === 0xffffffffffffffffn)
100
- throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
101
- return count;
102
- }
197
+ return (handle) => {
198
+ if (!native.symbols.csv_parser_prepare(handle, hasProjection, normalizedColumns, columnCount, normalized.descriptors, filterCount, normalized.valuesData, normalized.valuesData, normalized.valueOffsets, valueCount))
199
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
200
+ return {
201
+ writeBatch: (input, final) => native.symbols.csv_parser_write_prepared_batch(handle, input, input, final),
202
+ writeCount: (input, final) => {
203
+ const count = native.symbols.csv_parser_write_prepared_count(handle, input, input, final);
204
+ if (count === 0xffffffffffffffffn)
205
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
206
+ return count;
207
+ }
208
+ };
103
209
  };
104
210
  }
105
- export function validateRowSelection({ skipRows, limit }) {
211
+ export function validateRowSelection({ skipRows, skipEmptyLines, limit }) {
106
212
  if (skipRows !== void 0 && (!Number.isSafeInteger(skipRows) || skipRows < 0))
107
213
  throw RangeError("skipRows must be a non-negative safe integer");
214
+ if (skipEmptyLines !== void 0 && typeof skipEmptyLines !== "boolean")
215
+ throw TypeError("skipEmptyLines must be a boolean");
108
216
  if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0))
109
217
  throw RangeError("limit must be a non-negative safe integer");
110
218
  }
111
- export function setRowSelection(handle, options, captureHeader = !1) {
219
+ export function setRowSelection(handle, options) {
220
+ if (options.skipEmptyLines === !0)
221
+ native.symbols.csv_parser_set_skip_empty_lines(handle);
112
222
  if (options.skipRows !== void 0 || options.limit !== void 0)
113
- native.symbols.csv_parser_set_row_selection(handle, BigInt(options.skipRows ?? 0), options.limit === void 0 ? 0xffffffffffffffffn : BigInt(options.limit), captureHeader);
223
+ native.symbols.csv_parser_set_row_selection(handle, BigInt(options.skipRows ?? 0), options.limit === void 0 ? 0xffffffffffffffffn : BigInt(options.limit), !1);
224
+ }
225
+ export function prepareNativeValidation({ strict, expectedHeaders, maxRecordBytes }) {
226
+ if (maxRecordBytes !== void 0 && (!Number.isSafeInteger(maxRecordBytes) || maxRecordBytes <= 0))
227
+ throw RangeError("maxRecordBytes must be a positive safe integer");
228
+ if (strict !== !0 && maxRecordBytes === void 0)
229
+ return;
230
+ const captureHeader = strict === !0 && expectedHeaders !== void 0;
231
+ const limit = BigInt(maxRecordBytes ?? 0);
232
+ return (handle) => native.symbols.csv_parser_set_validation(handle, strict === !0, captureHeader, limit);
114
233
  }
115
- function createNativeCsvParser(options, prepared = !1) {
116
- const { skipRows, limit } = options;
117
- validateRowSelection({ skipRows, limit });
118
- const delimiter = options.delimiter ?? ",";
119
- if (delimiter === "auto")
120
- throw Error("automatic delimiter detection is only supported by file APIs");
121
- if (delimiter.length !== 1)
122
- throw Error("delimiter must be one character");
234
+ function createNativeCsvParser(options, delimiter, prepared) {
235
+ const { quote, recordDelimiter } = options;
236
+ validateRowSelection(options);
237
+ validateCsvDialect(options);
123
238
  const encoding = encodingCode(options.encoding);
124
- const handle = prepared ? native.symbols.csv_parser_create_prepared(encoding, delimiter.charCodeAt(0), options.fixedColumns ?? 0) : native.symbols.csv_parser_create(encoding, delimiter.charCodeAt(0));
239
+ const separator = delimiterByte(delimiter, encoding === 1 ? "latin1" : "utf8");
240
+ const applyValidation = prepareNativeValidation(options);
241
+ const handle = quote === !1 || recordDelimiter !== void 0 ? native.symbols.csv_parser_create_dialect(encoding, separator, options.fixedColumns ?? 0, quote ?? !0, recordDelimiter === `
242
+ `) : prepared ? native.symbols.csv_parser_create_prepared(encoding, separator, options.fixedColumns ?? 0) : native.symbols.csv_parser_create(encoding, separator);
125
243
  if (handle === null)
126
244
  throw Error("failed to create native CSV parser");
127
- setRowSelection(handle, { skipRows, limit });
245
+ setRowSelection(handle, options);
246
+ applyValidation?.(handle);
128
247
  return handle;
129
248
  }
130
249
  const createSchemaParser = Symbol("createSchemaParser");
250
+ const physicalRows = Symbol("physicalRows");
251
+ const prepareForPipeline = Symbol("prepareForPipeline");
252
+ const openPipeline = Symbol("openPipeline");
131
253
 
132
254
  export class NativeCsvParser {
133
255
  #handle;
134
- #strict;
256
+ #writeMode;
257
+ #schemaFailure;
135
258
  #fixedColumns;
136
259
  #writer;
137
- #transformStrictBatch;
260
+ #detection;
138
261
  #validator;
139
- #captureSkippedHeader = !1;
140
262
  static [createSchemaParser](options, output) {
141
- const validator = strictSchemaValidator(options);
142
- const parser = new NativeCsvParser(options);
143
- if (output === "rows" && !parser.#strict && options.transform?.length)
263
+ const settings = output === "pipelined-rows" ? { ...options, [prepareForPipeline]: !0 } : options;
264
+ const parser = new NativeCsvParser(settings);
265
+ if (output !== "batches" && !options.strict && options.transform?.length)
144
266
  native.symbols.csv_parser_enable_transformed_quoted_spans(parser.#requireHandle());
145
- parser.#validator = validator;
146
- if (validator !== void 0 && (options.skipRows ?? 0) > 0) {
147
- parser.#captureSkippedHeader = !0;
148
- setRowSelection(parser.#requireHandle(), options, !0);
149
- }
150
267
  return parser;
151
268
  }
152
- constructor(options = {}) {
153
- rejectSelectedColumns(options);
154
- this.#strict = options.strict === !0;
269
+ constructor(supplied = {}) {
270
+ rejectSelectedColumns(supplied);
271
+ const automatic = supplied.delimiter === void 0 || supplied.delimiter === "auto";
272
+ const options = automatic ? { ...supplied } : supplied;
273
+ const strict = options.strict === !0;
274
+ this.#validator = strictSchemaValidator(options);
155
275
  this.#fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
156
276
  const { columns, filterProgram } = options;
157
277
  if (filterProgram !== void 0 && (options.equalsFilter !== void 0 || options.filters !== void 0))
158
278
  throw Error("filterProgram cannot be combined with equalsFilter or filters");
159
279
  const program = filterProgram === void 0 ? projectionFilterProgram(options) : filterProgram;
160
- if (this.#strict && (columns !== void 0 || program !== void 0))
161
- throw Error("strict CSV validation is not supported for projected batches or filters");
162
280
  const transforms = snapshotTransforms(options.transform);
163
- const prepared = columns !== void 0 || program !== void 0 || !this.#strict && Boolean(transforms?.length);
164
- const handle = createNativeCsvParser(options, prepared);
165
- try {
166
- const active = transforms?.length ? prepareTransforms(handle, transforms, columns) : !1;
167
- this.#transformStrictBatch = this.#strict && active;
168
- this.#writer = prepared ? prepareNativeParser(handle, columns, program) : void 0;
169
- } catch (error) {
170
- destroyNativeCsvParser(handle);
171
- throw error;
172
- }
281
+ const customDialect = options.quote === !1 || options.recordDelimiter !== void 0;
282
+ if (customDialect && strict)
283
+ throw Error("strict CSV validation requires the default quote and record delimiter settings");
284
+ const prepared = strict || options.maxRecordBytes !== void 0 || customDialect || columns !== void 0 || program !== void 0 || Boolean(transforms?.length) || prepareForPipeline in options;
285
+ const configure = prepared ? configureNativeWriter(columns, program) : void 0;
286
+ const transformColumns = automatic && columns !== void 0 ? [...columns] : columns;
287
+ const open = (delimiter) => {
288
+ const handle = createNativeCsvParser(options, delimiter, prepared);
289
+ try {
290
+ if (transforms?.length)
291
+ prepareTransforms(handle, transforms, transformColumns);
292
+ return { handle, writer: configure?.(handle) };
293
+ } catch (error) {
294
+ destroyNativeCsvParser(handle);
295
+ throw error;
296
+ }
297
+ };
298
+ const delimiter = automatic ? "," : supplied.delimiter;
299
+ const { handle, writer } = open(delimiter);
300
+ if (automatic)
301
+ this.#detection = {
302
+ open,
303
+ dialect: options,
304
+ delimiter,
305
+ selected: !1,
306
+ prefix: void 0,
307
+ length: 0
308
+ };
173
309
  this.#handle = handle;
310
+ this.#writer = writer;
174
311
  nativeCsvParserFinalizer.register(this, handle, this);
175
312
  }
176
313
  get closed() {
@@ -185,19 +322,35 @@ export class NativeCsvParser {
185
322
  }
186
323
  }
187
324
  writeBatch(chunk, final = !1) {
188
- const handle = this.#requireHandle();
189
- const input = normalizeChunk(chunk);
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);
325
+ this.#requireWritableHandle("materialize");
326
+ const input = this.#detectDelimiter(chunk, final);
327
+ const batch = this.#writeBatch(this.#requireHandle(), input, final);
328
+ this.#writeMode = "materialize";
329
+ return batch;
330
+ }
331
+ #writeBatch(handle, input, final) {
332
+ const batch = this.#writer !== void 0 ? this.#writer.writeBatch(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);
191
333
  if (batch === null)
192
334
  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);
335
+ const result = new NativeCsvBatch(batch);
336
+ try {
337
+ this.#validateSchema(final);
338
+ return result;
339
+ } catch (error) {
340
+ result.close();
341
+ throw error;
199
342
  }
200
- return this.#validatedBatch(batch, final);
343
+ }
344
+ [openPipeline](chunks, first, limit) {
345
+ const pipeline = BatchPipeline.start(this.#requireHandle(), this);
346
+ return pipeline === void 0 ? void 0 : this.#readPipeline(pipeline, chunks, first, limit);
347
+ }
348
+ async* #readPipeline(ahead, chunks, first, limit) {
349
+ using pipeline = ahead;
350
+ const validate = this.#validator === void 0 ? void 0 : (final) => this.#validateSchema(final);
351
+ const finishAtLimit = () => this.writeBatch(EMPTY_BUFFER, !0).close();
352
+ for await (const batch of pipeline.batches(chunks, first, limit, validate, finishAtLimit))
353
+ yield new NativeCsvBatch(batch);
201
354
  }
202
355
  end() {
203
356
  const batch = this.endBatch();
@@ -211,27 +364,37 @@ export class NativeCsvParser {
211
364
  return this.writeBatch(EMPTY_BUFFER, !0);
212
365
  }
213
366
  writeCount(chunk, final = !1) {
214
- if (this.#strict)
215
- throw Error("strict CSV validation is not supported for count");
367
+ this.#requireWritableHandle("count");
368
+ const input = this.#detectDelimiter(chunk, final);
369
+ const handle = this.#requireHandle();
216
370
  if (this.#writer === void 0 && this.#fixedColumns !== void 0) {
217
- using batch = this.writeBatch(chunk, final);
371
+ using batch = this.#writeBatch(handle, input, final);
372
+ this.#writeMode = "count";
218
373
  return batch.rowCount;
219
374
  }
220
- const handle = this.#requireHandle();
221
- const input = normalizeChunk(chunk);
222
- return u64ToSafeNumber(this.#writer === void 0 ? native.symbols.csv_parser_write_count(handle, input, input, final) : this.#writer.writeCount(input, final), "CSV parsed row count");
375
+ const count = u64ToSafeNumber(this.#writer === void 0 ? native.symbols.csv_parser_write_count(handle, input, input, final) : this.#writer.writeCount(input, final), "CSV parsed row count");
376
+ this.#validateSchema(final);
377
+ this.#writeMode = "count";
378
+ return count;
223
379
  }
224
380
  endCount() {
225
381
  return this.writeCount(EMPTY_BUFFER, !0);
226
382
  }
227
383
  reset() {
228
384
  native.symbols.csv_parser_reset_stream(this.#requireHandle());
385
+ if (this.#detection !== void 0) {
386
+ this.#detection.selected = !1;
387
+ this.#detection.length = 0;
388
+ }
389
+ this.#writeMode = void 0;
390
+ this.#schemaFailure = void 0;
229
391
  }
230
392
  close() {
231
393
  const handle = this.#handle;
232
394
  if (handle === null)
233
395
  return;
234
396
  this.#handle = null;
397
+ this.#detection = void 0;
235
398
  nativeCsvParserFinalizer.unregister(this);
236
399
  destroyNativeCsvParser(handle);
237
400
  }
@@ -243,30 +406,61 @@ export class NativeCsvParser {
243
406
  throw Error("native CSV parser is closed");
244
407
  return this.#handle;
245
408
  }
409
+ [physicalRows]() {
410
+ return u64ToSafeNumber(native.symbols.csv_parser_physical_rows(this.#requireHandle()), "CSV physical record count");
411
+ }
246
412
  #lastError() {
247
413
  return native.symbols.csv_parser_last_error(this.#requireHandle()) ?? "native parser error unavailable";
248
414
  }
249
- #validatedBatch(pointer, final) {
250
- const batch = new NativeCsvBatch(pointer);
251
- if (this.#validator === void 0)
252
- return batch;
253
- try {
254
- const handle = this.#requireHandle();
255
- if (this.#captureSkippedHeader) {
256
- const header = native.symbols.csv_parser_take_skipped_header(handle);
257
- if (header !== null) {
258
- using first = new NativeCsvBatch(header);
259
- this.#validator.validateBatch(first);
260
- }
261
- }
262
- this.#validator.validateBatch(batch);
263
- if (final) {
264
- const skipped = this.#captureSkippedHeader ? u64ToSafeNumber(native.symbols.csv_parser_skipped_rows(handle), "CSV skipped row count") : 0;
265
- this.#validator.finish(Math.max(0, skipped - 1));
415
+ #requireWritableHandle(mode) {
416
+ const handle = this.#requireHandle();
417
+ if (this.#schemaFailure !== void 0)
418
+ throw this.#schemaFailure.error;
419
+ const previous = this.#writeMode;
420
+ if (previous !== void 0 && previous !== mode && ((this.#detection?.length ?? 0) > 0 || native.symbols.csv_parser_has_pending_record(handle))) {
421
+ const pending = previous === "count" ? "count record" : "materialized record";
422
+ throw Error(`cannot switch CSV write modes while a ${pending} is pending`);
423
+ }
424
+ }
425
+ #detectDelimiter(chunk, final) {
426
+ const input = normalizeChunk(chunk);
427
+ const detection = this.#detection;
428
+ if (detection === void 0 || detection.selected)
429
+ return input;
430
+ const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
431
+ if (!final && detection.length + bytes.length <= FILE_PROBE_SIZE) {
432
+ if (bytes.length > 0) {
433
+ detection.prefix ??= new Uint8Array(FILE_PROBE_SIZE);
434
+ detection.prefix.set(bytes, detection.length);
435
+ detection.length += bytes.length;
266
436
  }
267
- return batch;
437
+ return EMPTY_BUFFER;
438
+ }
439
+ const buffered = detection.prefix === void 0 ? bytes : Buffer.concat([detection.prefix.subarray(0, detection.length), bytes]);
440
+ const delimiter = detectBufferDelimiter(buffered, "", final, detection.dialect);
441
+ if (delimiter !== detection.delimiter) {
442
+ const previous = this.#requireHandle();
443
+ const { handle, writer } = detection.open(delimiter);
444
+ nativeCsvParserFinalizer.unregister(this);
445
+ this.#handle = handle;
446
+ this.#writer = writer;
447
+ nativeCsvParserFinalizer.register(this, handle, this);
448
+ destroyNativeCsvParser(previous);
449
+ detection.delimiter = delimiter;
450
+ }
451
+ detection.selected = !0;
452
+ detection.length = 0;
453
+ detection.prefix = void 0;
454
+ return buffered;
455
+ }
456
+ #validateSchema(final) {
457
+ if (!this.#validator)
458
+ return;
459
+ const handle = this.#requireHandle();
460
+ try {
461
+ this.#validator.validateNative(handle, final);
268
462
  } catch (error) {
269
- batch.close();
463
+ this.#schemaFailure = { error };
270
464
  throw error;
271
465
  }
272
466
  }
@@ -1,14 +1,13 @@
1
- import type { NativeCsvBatch } from './batches.js';
2
- import type { CsvParserOptions, CsvRow } from './types.js';
1
+ import { NativeCsvBatch } from './batches.js';
2
+ import { type NativePointer } from './native.js';
3
+ import type { CsvParserOptions } from './types.js';
3
4
  type StrictSchemaOptions = Pick<CsvParserOptions, 'strict' | 'expectedHeaders' | 'requireHeader' | 'minDataRows'>;
4
5
  export declare class CsvStrictSchemaValidator {
5
6
  #private;
6
- constructor(suppliedOptions: StrictSchemaOptions);
7
- get enabled(): boolean;
8
- validateRows(rows: readonly CsvRow[]): void;
9
- validateBatch(batch: NativeCsvBatch): void;
10
- finish(skippedDataRows?: number): void;
7
+ constructor(options: StrictSchemaOptions);
8
+ validateNative(handle: NativePointer, final: boolean, encoding?: 'utf8' | 'latin1'): void;
9
+ validateHeader(batch: NativeCsvBatch, record: number, encoding?: 'utf8' | 'latin1'): void;
10
+ finish(records: number): void;
11
11
  }
12
12
  export declare function strictSchemaValidator(options: StrictSchemaOptions): CsvStrictSchemaValidator | undefined;
13
- export declare function rejectStrictSchemaUnsupported(options: StrictSchemaOptions, operation: string): void;
14
13
  export {};