@konstit/csv 0.4.3 → 0.5.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 (63) hide show
  1. package/README.md +42 -26
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +39 -249
  4. package/dist/api.js +40 -304
  5. package/dist/batches.d.ts +5 -53
  6. package/dist/batches.js +66 -43
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +350 -0
  9. package/dist/cli-schema.d.ts +111 -0
  10. package/dist/cli-schema.js +219 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +57 -2
  13. package/dist/file-stream.js +241 -36
  14. package/dist/files.d.ts +11 -11
  15. package/dist/files.js +11 -9
  16. package/dist/filter.d.ts +4 -6
  17. package/dist/format-bytes.d.ts +1 -0
  18. package/dist/format-bytes.js +11 -0
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -14
  21. package/dist/inspect-file.d.ts +12 -0
  22. package/dist/inspect-file.js +88 -0
  23. package/dist/latin1-rows.d.ts +3 -1
  24. package/dist/latin1-rows.js +61 -23
  25. package/dist/materialize-field.d.ts +2 -0
  26. package/dist/materialize-field.js +20 -15
  27. package/dist/native.d.ts +29 -9
  28. package/dist/native.js +27 -29
  29. package/dist/normalize.d.ts +15 -2
  30. package/dist/normalize.js +41 -2
  31. package/dist/options-snapshot.js +3 -2
  32. package/dist/options.d.ts +4 -30
  33. package/dist/options.js +0 -6
  34. package/dist/parser.d.ts +14 -15
  35. package/dist/parser.js +38 -54
  36. package/dist/strict-schema.d.ts +5 -3
  37. package/dist/types.d.ts +88 -222
  38. package/dist/zip-reader.d.ts +11 -1
  39. package/dist/zip-reader.js +12 -3
  40. package/package.json +34 -32
  41. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  42. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  43. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  44. package/prebuilds/manifest.json +9 -8
  45. package/prebuilds/provenance/darwin-arm64.json +1 -1
  46. package/prebuilds/provenance/darwin-x64.json +1 -1
  47. package/prebuilds/provenance/linux-x64.json +1 -1
  48. package/dist/worker-count.d.ts +0 -34
  49. package/dist/worker-count.js +0 -101
  50. package/dist/worker-factory.d.ts +0 -3
  51. package/dist/worker-factory.js +0 -9
  52. package/dist/worker-filter.d.ts +0 -29
  53. package/dist/worker-filter.js +0 -46
  54. package/dist/worker-module.d.ts +0 -1
  55. package/dist/worker-module.js +0 -4
  56. package/dist/worker-pool.d.ts +0 -93
  57. package/dist/worker-pool.js +0 -298
  58. package/dist/worker-rows.d.ts +0 -36
  59. package/dist/worker-rows.js +0 -127
  60. package/dist/workers/count.worker.d.ts +0 -1
  61. package/dist/workers/count.worker.js +0 -36
  62. package/dist/workers/rows.worker.d.ts +0 -1
  63. package/dist/workers/rows.worker.js +0 -56
package/dist/types.d.ts CHANGED
@@ -2,21 +2,28 @@ import type { NativeCsvRowView } from './batches.js';
2
2
  /**
3
3
  * Text encoding used when CSV fields are decoded into JavaScript strings.
4
4
  *
5
- * `utf8` is the default. The `latin1`, `iso88591`, and `iso-8859-1` spellings
6
- * select the same single-byte decoding path.
5
+ * The values are labels accepted by Bun's `TextDecoder`. `utf8` is the
6
+ * default. The `latin1`, `iso88591`, and `iso-8859-1` spellings retain the
7
+ * parser's native Latin-1 byte mapping.
7
8
  */
8
- export type CsvEncoding = 'utf8' | 'latin1' | 'iso88591' | 'iso-8859-1';
9
+ export type CsvEncoding = Bun.Encoding;
10
+ /** File readers accept explicit encoding labels or infer an encoding from the decompressed prefix. */
11
+ export type CsvFileEncoding = CsvEncoding | 'auto';
12
+ /** Encoding labels that can be passed directly to the native parser. */
13
+ export type CsvNativeEncoding = 'unicode-1-1-utf-8' | 'unicode11utf8' | 'unicode20utf8' | 'utf-8' | 'utf8' | 'x-unicode20utf8' | 'latin1' | 'iso88591' | 'iso-8859-1';
9
14
  /**
10
15
  * Selects one CSV entry from a ZIP archive.
11
16
  *
12
- * ZIP input is available to serial file operations. The `entry` name must
13
- * match the archive member exactly; use `'*'` only when the archive contains
14
- * exactly one file entry.
17
+ * ZIP input is available to file parsing operations. The `entry` name must
18
+ * match the archive member exactly. `'*'` selects the only file after ignoring
19
+ * directories and OS metadata. This includes files in `__MACOSX/` or
20
+ * `.AppleDouble/` directories, `._*` files, and the case-insensitive filenames
21
+ * `.DS_Store`, `Thumbs.db`, `ehthumbs.db`, `ehthumbs_vista.db`, and `desktop.ini`.
15
22
  */
16
23
  export interface CsvZipCompression {
17
24
  /** ZIP is the selected container format. */
18
25
  readonly format: 'zip';
19
- /** Archive member containing the CSV data, or `'*'` for an unambiguous single-file archive. */
26
+ /** Exact archive member name, or `'*'` for the only file after ignoring directories and OS metadata. */
20
27
  readonly entry: string;
21
28
  /**
22
29
  * Maximum allowed decompressed-to-compressed byte ratio for the selected entry.
@@ -35,16 +42,17 @@ export interface CsvZipCompression {
35
42
  /**
36
43
  * Compression accepted for file input.
37
44
  *
38
- * `'auto'` detects the supported compression format from the input prefix and
39
- * filename. A ZIP object selects one archive entry. Compression is supported
40
- * for serial file operations; worker, parallel, and byte-offset sharding APIs
41
- * require uncompressed input.
45
+ * The default, `'auto'`, detects compression, reads recognized text files
46
+ * directly, and selects the only ZIP data file after ignoring directories and
47
+ * OS metadata. ZIP input requires a regular file. Use `'none'` to read raw bytes.
48
+ * A ZIP object selects an exact entry or custom ZIP limits. Byte-offset sharding
49
+ * requires an uncompressed file.
42
50
  */
43
- export type CsvCompression = Bun.CompressionFormat | 'auto' | CsvZipCompression;
51
+ export type CsvCompression = Bun.CompressionFormat | 'auto' | 'none' | CsvZipCompression;
44
52
  /**
45
53
  * Field delimiter used by the CSV parser.
46
54
  *
47
- * Omit the option to use comma. `'auto'` is supported by serial file
55
+ * Omit the option to use comma. `'auto'` is supported by file parsing
48
56
  * operations and probes the input for a stable common delimiter. Other strings
49
57
  * are accepted by TypeScript, but runtime parsing requires one character.
50
58
  */
@@ -173,10 +181,7 @@ export interface CsvFieldRange {
173
181
  end: number;
174
182
  }
175
183
  /**
176
- * Inclusive byte range assigned to one worker shard of an uncompressed CSV file.
177
- *
178
- * The range boundaries are chosen at record boundaries, so a worker can parse
179
- * the shard independently.
184
+ * Inclusive byte range containing complete records from an uncompressed CSV file.
180
185
  */
181
186
  export interface CsvShard {
182
187
  /** Inclusive start byte offset in the file. */
@@ -190,14 +195,17 @@ export interface CsvShard {
190
195
  * Options are readonly and are captured at operation invocation time, before
191
196
  * asynchronous iteration begins. Start a new operation to apply changed arrays
192
197
  * or values.
198
+ *
199
+ * @typeParam TEncoding - Defaults to the native parser's labels. File and buffer
200
+ * parsing accept the full {@link CsvEncoding} set.
193
201
  */
194
- export interface CsvParserOptions {
202
+ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeEncoding> {
195
203
  /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
196
- readonly encoding?: CsvEncoding;
197
- /** Field separator. Defaults to comma; `'auto'` is for serial file input. */
204
+ readonly encoding?: TEncoding;
205
+ /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
198
206
  readonly delimiter?: CsvDelimiter;
199
207
  /** Physical columns to emit from each row, in the requested output order. */
200
- readonly selectedColumns?: CsvColumns;
208
+ readonly columns?: CsvColumns;
201
209
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
202
210
  readonly fixedColumns?: number;
203
211
  /** Enable RFC-style quote and schema validation. Defaults to `false`. */
@@ -213,12 +221,14 @@ export interface CsvParserOptions {
213
221
  * File input options, including parser settings and stream controls.
214
222
  *
215
223
  * Compression is streamed into the parser and does not load the complete file
216
- * into memory. Compressed input cannot be used with parallel or sharded APIs.
224
+ * into memory. Byte-offset sharding requires an uncompressed file.
217
225
  */
218
- export interface CsvFileOptions extends CsvParserOptions {
226
+ export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
227
+ /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
228
+ readonly encoding?: CsvFileEncoding;
219
229
  /** Read-stream chunk size in bytes. Defaults to 1 MiB. */
220
230
  readonly chunkSize?: number;
221
- /** Optional compression format or ZIP entry selection. */
231
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
222
232
  readonly compression?: CsvCompression;
223
233
  }
224
234
  /**
@@ -227,9 +237,11 @@ export interface CsvFileOptions extends CsvParserOptions {
227
237
  * Compression is excluded because compressed byte streams cannot be split into
228
238
  * independently readable file ranges.
229
239
  */
230
- export type CsvShardingOptions = Omit<CsvFileOptions, 'compression'> & {
240
+ export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'encoding'> & {
231
241
  /** Compression is unsupported for byte-offset sharding. */
232
242
  readonly compression?: never;
243
+ /** Sharding scans raw file bytes and supports native encodings only. */
244
+ readonly encoding?: CsvNativeEncoding;
233
245
  };
234
246
  /** Native equality predicate used by projection and count fast paths. */
235
247
  export interface CsvEqualsFilter {
@@ -289,137 +301,74 @@ export type CsvNativeFilter = CsvEqualsFilter | CsvInFilter | CsvNotInFilter | C
289
301
  */
290
302
  export interface CsvNativeProjectionOptions {
291
303
  /** Physical columns to emit, in output order. */
292
- readonly selectedColumns?: CsvColumns;
304
+ readonly columns?: CsvColumns;
293
305
  /** One equality predicate for the direct native fast path. */
294
306
  readonly equalsFilter?: CsvEqualsFilter;
295
307
  /** Native predicates combined for the operation. */
296
308
  readonly filters?: readonly CsvNativeFilter[];
297
309
  }
298
- /**
299
- * Common file options for the high-level `csv` API.
300
- *
301
- * Use `columns` for the preferred projection spelling. `selectedColumns` is a
302
- * legacy alias; supplying both is rejected.
303
- */
310
+ /** Common file options for the high-level `csv` API. */
304
311
  export interface CsvApiFileOptions extends CsvFileOptions {
305
- /** Preferred physical-column projection for materialized row APIs. */
306
- readonly columns?: CsvColumns;
307
- /** Number of workers for parallel operations; values greater than one enable sharding. */
308
- readonly workerCount?: number;
309
312
  /** Opaque filter created by `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. */
310
313
  readonly where?: CsvFilter;
311
314
  }
312
- /**
313
- * Type-safe mutually exclusive projection fields.
314
- *
315
- * The generic preserves a literal tuple such as `readonly [0, 2]`, allowing
316
- * materialized rows and row views to retain their projected positions in the
317
- * resulting TypeScript type.
318
- */
319
- export type CsvColumnSelection<TColumns extends CsvColumns | undefined> = {
320
- /** Preferred projection spelling; indexes are emitted in this order. */
315
+ /** Retains the literal input indexes and their order for projected row types. */
316
+ export interface CsvColumnSelection<TColumns extends CsvColumns | undefined> {
317
+ /** Physical columns to emit from each row, in the requested output order. */
321
318
  readonly columns?: TColumns;
322
- /** Deliberately excluded when `columns` is supplied. */
323
- readonly selectedColumns?: never;
324
- } | {
325
- /** Deliberately excluded when the legacy alias is supplied. */
326
- readonly columns?: never;
327
- /** Legacy projection spelling; indexes are emitted in this order. */
328
- readonly selectedColumns?: TColumns;
329
- };
330
- /** Internal common API options after removing the mutually exclusive projection fields. */
331
- type CsvApiOptionsWithoutSelection = Omit<CsvApiFileOptions, 'columns' | 'selectedColumns'>;
332
- /** Apply `Omit` to each member of a union independently. */
333
- type CsvDistributiveOmit<T, TKeys extends PropertyKey> = T extends unknown ? Omit<T, TKeys> : never;
334
- /** Internal serial option base shared by row and batch APIs. */
335
- type CsvOptionsWithoutWhereWorkerCount<TColumns extends CsvColumns | undefined> = Omit<CsvApiOptionsWithoutSelection, 'where' | 'workerCount'> & CsvColumnSelection<TColumns>;
336
- /**
337
- * Options for one-process row parsing, row views, and batch streaming.
338
- *
339
- * `strict: true` selects validated parsing and cannot be combined with `where`.
340
- * `workerCount` is restricted to `1` for this serial shape. The generic keeps a
341
- * literal projection tuple when supplied.
342
- */
343
- export type CsvSingleThreadRowsOptions<TColumns extends CsvColumns | undefined = undefined> = (CsvDistributiveOmit<CsvOptionsWithoutWhereWorkerCount<TColumns>, 'strict'> & {
344
- /** Disable strict quote/schema validation (the default serial mode). */
319
+ }
320
+ /** Shared operation properties have declarations that editors can use for hover documentation. */
321
+ interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends CsvColumnSelection<TColumns> {
322
+ /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
323
+ readonly delimiter?: CsvDelimiter;
324
+ /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
325
+ readonly fixedColumns?: number;
326
+ /** Expected first-row field values, checked in strict mode. */
327
+ readonly expectedHeaders?: readonly string[];
328
+ /** Require a first row when strict schema validation is enabled. */
329
+ readonly requireHeader?: boolean;
330
+ /** Minimum number of data rows after the header, checked in strict mode. */
331
+ readonly minDataRows?: number;
332
+ /** Read-stream chunk size in bytes. Defaults to 1 MiB. Used by file operations only. */
333
+ readonly chunkSize?: number;
334
+ }
335
+ /** File operations support encoding detection and streamed decompression. */
336
+ interface CsvFileOperationOptions<TColumns extends CsvColumns | undefined> extends CsvOperationOptions<TColumns> {
337
+ /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
338
+ readonly encoding?: CsvFileEncoding;
339
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
340
+ readonly compression?: CsvCompression;
341
+ }
342
+ /** Non-strict operations can filter input records. */
343
+ interface CsvFilteredOperationOptions {
344
+ /** Enable RFC-style quote and schema validation. Defaults to `false`. Requires unfiltered input. */
345
345
  readonly strict?: false | undefined;
346
- /** Optional immutable filter created by the CSV filter factories. */
346
+ /** Filter records with `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. Requires `strict` to be false or omitted. */
347
347
  readonly where?: CsvFilter | undefined;
348
- /** Serial mode uses one worker; omit this field to use the default. */
349
- readonly workerCount?: 1 | undefined;
350
- }) | (CsvDistributiveOmit<CsvOptionsWithoutWhereWorkerCount<TColumns>, 'strict'> & {
351
- /** Enable strict quote/schema validation; strict mode cannot use `where`. */
348
+ }
349
+ /** Strict validation requires unfiltered input. */
350
+ interface CsvStrictOperationOptions {
351
+ /** Enable RFC-style quote and schema validation. Requires unfiltered input. */
352
352
  readonly strict: true;
353
- /** Filters are excluded when strict validation is enabled. */
353
+ /** Filtering is unavailable with strict validation, which checks every input record. */
354
354
  readonly where?: undefined;
355
- /** Strict parsing remains single-threaded. */
356
- readonly workerCount?: 1 | undefined;
357
- });
358
- /**
359
- * Options for sharded row parsing with multiple workers.
360
- *
361
- * Set `workerCount` to the desired number of workers. Parallel operations do
362
- * not support compression, automatic delimiter detection, or strict parsing.
363
- */
364
- export type CsvParallelRowsOptions<TColumns extends CsvColumns | undefined = undefined> = Omit<CsvApiOptionsWithoutSelection, 'compression' | 'where' | 'workerCount' | 'strict'> & CsvColumnSelection<TColumns> & {
365
- /** Compressed input cannot be byte-offset sharded. */
366
- readonly compression?: never;
367
- /** Optional immutable filter applied in each worker. */
368
- readonly where?: CsvFilter | undefined;
369
- /** Required worker count; must be an integer greater than one. */
370
- readonly workerCount: number;
371
- /** Strict validation is unsupported for parallel parsing. */
372
- readonly strict?: false | undefined;
373
- };
355
+ }
356
+ /** Each branch keeps its documented properties and enforces the strict/filter constraint. */
357
+ type CsvValidationOptions = CsvFilteredOperationOptions | CsvStrictOperationOptions;
374
358
  /** Options for parsing an in-memory buffer into materialized rows. */
375
- export type CsvParseOptions<TColumns extends CsvColumns | undefined = undefined> = CsvDistributiveOmit<CsvSingleThreadRowsOptions<TColumns>, 'compression'>;
376
- /** Options accepted by `csv.rows()`, serial or parallel. */
377
- export type CsvRowsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvSingleThreadRowsOptions<TColumns> | CsvParallelRowsOptions<TColumns>;
378
- /** Options accepted by `csv.batches()` and `csv.withBatches()`. */
379
- export type CsvBatchesOptions = CsvSingleThreadRowsOptions<CsvColumns | undefined>;
380
- /** Options accepted by reusable row-view callbacks. */
381
- export type CsvRowViewsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvSingleThreadRowsOptions<TColumns>;
382
- /**
383
- * Options accepted by columnar-batch callbacks.
384
- *
385
- * Columnar batches expose raw projected bytes and therefore always use
386
- * non-strict parsing when a projection tuple is supplied.
387
- */
388
- export type CsvColumnarBatchOptions<TColumns extends CsvColumns | undefined = undefined> = [TColumns] extends [undefined] ? CsvSingleThreadRowsOptions<TColumns> : CsvDistributiveOmit<CsvSingleThreadRowsOptions<TColumns>, 'strict'> & {
389
- /** Strict validation is unavailable for projected columnar batches. */
390
- readonly strict?: false | undefined;
359
+ export type CsvParseOptions<TColumns extends CsvColumns | undefined = undefined> = CsvOperationOptions<TColumns> & CsvValidationOptions & {
360
+ /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
361
+ readonly encoding?: CsvEncoding;
391
362
  };
392
- /** Internal serial count option union used by the exported `CsvCountOptions`. */
393
- type CsvCountSingleThreadOptions = (Omit<CsvApiOptionsWithoutSelection, 'where' | 'workerCount' | 'strict'> & CsvColumnSelection<CsvColumns | undefined> & {
394
- /** Disable strict validation (the default serial count mode). */
395
- readonly strict?: false | undefined;
396
- /** Optional immutable filter evaluated by the native count path. */
397
- readonly where?: CsvFilter | undefined;
398
- /** Serial mode uses one worker; omit this field to use the default. */
399
- readonly workerCount?: 1 | undefined;
400
- }) | (Omit<CsvApiOptionsWithoutSelection, 'where' | 'workerCount' | 'strict'> & CsvColumnSelection<CsvColumns | undefined> & {
401
- /** Enable strict quote/schema validation; filtered strict counts are unsupported. */
402
- readonly strict: true;
403
- /** Filters are excluded when strict validation is enabled. */
404
- readonly where?: undefined;
405
- /** Strict counting remains single-threaded. */
406
- readonly workerCount?: 1 | undefined;
407
- });
408
- /** Options for counting rows with multiple workers. */
409
- export type CsvParallelCountOptions = Omit<CsvApiOptionsWithoutSelection, 'compression' | 'where' | 'workerCount' | 'strict'> & CsvColumnSelection<CsvColumns | undefined> & {
410
- /** Compressed input cannot be byte-offset sharded. */
411
- readonly compression?: never;
412
- /** Optional immutable filter evaluated in each worker. */
413
- readonly where?: CsvFilter | undefined;
414
- /** Required worker count; must be an integer greater than one. */
415
- readonly workerCount: number;
416
- /** Strict validation is unsupported for parallel counting. */
417
- readonly strict?: false | undefined;
363
+ /** Options for streaming materialized rows in file order. */
364
+ export type CsvRowsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvFileOperationOptions<TColumns> & CsvValidationOptions & {
365
+ /** Refill the batch and its row arrays across iterations. Copy any row you want to keep. Defaults to false. */
366
+ readonly reuseArrays?: boolean;
418
367
  };
419
- /** Options accepted by `csv.count()`, serial or parallel. */
420
- export type CsvCountOptions = CsvCountSingleThreadOptions | CsvParallelCountOptions;
421
- /** Options captured when a reusable `CsvWorkerPool` is created. */
422
- export type CsvWorkerPoolOptions<TColumns extends CsvColumns | undefined = undefined> = CsvParallelRowsOptions<TColumns>;
368
+ /** Strict native batches require unfiltered, unprojected input. */
369
+ export type CsvBatchesOptions = (CsvFileOperationOptions<CsvColumns | undefined> & CsvFilteredOperationOptions) | (CsvFileOperationOptions<undefined> & CsvStrictOperationOptions);
370
+ /** Options accepted by `csv.count()`. */
371
+ export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> & CsvValidationOptions;
423
372
  /**
424
373
  * Materialized row type inferred from a literal projection tuple.
425
374
  *
@@ -430,33 +379,6 @@ export type CsvWorkerPoolOptions<TColumns extends CsvColumns | undefined = undef
430
379
  export type CsvProjectedRow<TColumns extends CsvColumns | undefined> = TColumns extends readonly unknown[] ? {
431
380
  -readonly [Index in keyof TColumns]: string;
432
381
  } : CsvRow;
433
- /**
434
- * Reusable, low-allocation view of one materialized row.
435
- *
436
- * The view is valid only during the synchronous callback that receives it. Its
437
- * accessors address the fields stored in the current batch: unfiltered rows
438
- * use physical CSV indexes, while a filtered operation with a projection uses
439
- * projected output positions. `selectedColumns` maps those output positions
440
- * back to physical indexes. Missing fields return `null` from scalar accessors
441
- * and become empty strings in `pick()` and `pickPhysical()`.
442
- *
443
- * @typeParam TSelectedColumns - Literal selected-column indexes, when supplied.
444
- */
445
- export type CsvRowView<TSelectedColumns extends CsvColumns | undefined = undefined> = Pick<NativeCsvRowView, 'rowIndex' | 'fieldCount' | 'fieldRange' | 'range' | 'fieldBytes' | 'bytes' | 'fieldBuffer' | 'buffer' | 'fieldString' | 'getPhysical' | 'get' | 'pickPhysical' | 'pick'> & {
446
- /** Selected output columns requested for the stream, when present. */
447
- readonly selectedColumns: TSelectedColumns;
448
- };
449
- /**
450
- * Synchronous callback invoked for each reusable row view.
451
- *
452
- * Copy values that must outlive the callback; the view is rebound for the next
453
- * row and released when the callback returns.
454
- *
455
- * @typeParam TSelectedColumns - Literal selected-column indexes, when supplied.
456
- * @param row - Reusable view positioned at `rowIndex`.
457
- * @param rowIndex - Zero-based row index within the current batch.
458
- */
459
- export type CsvRowViewCallback<TSelectedColumns extends CsvColumns | undefined = undefined> = (row: CsvRowView<TSelectedColumns>, rowIndex: number) => void;
460
382
  /**
461
383
  * Synchronous callback invoked by `NativeCsvBatch.forEachRow()`.
462
384
  *
@@ -490,60 +412,4 @@ export type CsvColumnBytesCallback = (rowIndex: number, bytes: Uint8Array) => vo
490
412
  * array and buffer are reused for each row.
491
413
  */
492
414
  export type CsvScanColumnsCallback = (rowIndex: number, ranges: Float64Array, data: Buffer) => void;
493
- /**
494
- * Reusable raw-data view over one columnar batch.
495
- *
496
- * This view is valid only during the synchronous callback that receives it and
497
- * is rebound for the next batch. Its arrays and byte views alias native batch
498
- * storage, so copy data that must outlive the callback.
499
- *
500
- * @typeParam TSelectedColumns - Literal selected-column indexes, when supplied.
501
- */
502
- export interface CsvColumnarBatchView<TSelectedColumns extends CsvColumns | undefined = undefined> {
503
- /** Number of rows represented by the batch. */
504
- readonly rowCount: number;
505
- /** Total number of fields across all rows in the batch. */
506
- readonly totalFields: number;
507
- /** Number of bytes in the backing field-data buffer. */
508
- readonly dataLength: number;
509
- /**
510
- * Selected output columns requested for this batch, mapping output positions
511
- * to physical CSV indexes.
512
- *
513
- * Column indexes passed to this view's methods address stored batch fields;
514
- * when this property is defined, those indexes are projected output
515
- * positions.
516
- */
517
- readonly selectedColumns: TSelectedColumns;
518
- /** Return the batch's field bytes as a `Buffer` view. */
519
- data(): Buffer;
520
- /** Return the batch's field bytes as a `Uint8Array` view. */
521
- dataView(): Uint8Array;
522
- /** Return `rowCount + 1` cumulative field indexes for row boundaries. */
523
- rowOffsets(): BigUint64Array;
524
- /** Return `totalFields + 1` cumulative byte offsets for field boundaries. */
525
- fieldOffsets(): BigUint64Array;
526
- /** Return the number of fields in one row. */
527
- rowFieldCount(rowIndex: number): number;
528
- /** Return a field's half-open byte range, or `null` when the column is missing. */
529
- fieldRange(rowIndex: number, columnIndex: number): CsvFieldRange | null;
530
- /** Return a field's raw bytes, or `null` when the column is missing. */
531
- fieldBytes(rowIndex: number, columnIndex: number): Uint8Array | null;
532
- /** Return a field's `Buffer` view, or `null` when the column is missing. */
533
- fieldBuffer(rowIndex: number, columnIndex: number): Buffer | null;
534
- /** Visit byte ranges for one column in the half-open row interval `[startRow, endRow)`. */
535
- forEachColumnRange(columnIndex: number, callback: CsvColumnRangeCallback, startRow?: number, endRow?: number): void;
536
- /** Visit raw bytes for one column in the half-open row interval `[startRow, endRow)`. */
537
- forEachColumnBytes(columnIndex: number, callback: CsvColumnBytesCallback, startRow?: number, endRow?: number): void;
538
- /** Visit several column ranges per row; missing fields are reported as `[-1, -1]`. */
539
- scanColumns(columns: CsvColumns, callback: CsvScanColumnsCallback, startRow?: number, endRow?: number): void;
540
- }
541
- /**
542
- * Synchronous callback invoked for each reusable columnar batch view.
543
- *
544
- * @typeParam TSelectedColumns - Literal selected-column indexes, when supplied.
545
- * @param batch - Reusable raw-data view for the current batch.
546
- * @param batchIndex - Zero-based batch index for the operation.
547
- */
548
- export type CsvColumnarBatchCallback<TSelectedColumns extends CsvColumns | undefined = undefined> = (batch: CsvColumnarBatchView<TSelectedColumns>, batchIndex: number) => void;
549
415
  export {};
@@ -1,2 +1,12 @@
1
1
  import type { CsvZipCompression } from './types.js';
2
- export declare function readZipEntryChunks(path: string, options: CsvZipCompression, chunkSize: number): AsyncGenerator<Uint8Array, void>;
2
+ export declare class NativeZipReader {
3
+ #private;
4
+ constructor(path: string, options: CsvZipCompression);
5
+ get status(): number;
6
+ enableReadAhead(chunkSize: number): void;
7
+ read(output: Uint8Array): number;
8
+ lastError(): string;
9
+ close(): void;
10
+ [Symbol.dispose](): void;
11
+ }
12
+ export declare function readZipEntryChunks(path: string, options: CsvZipCompression, chunkSize: number, readAhead?: boolean): AsyncGenerator<Uint8Array, void>;
@@ -11,7 +11,7 @@ function destroyNativeZipReader(handle) {
11
11
  native.symbols.csv_zip_reader_destroy(handle);
12
12
  }
13
13
 
14
- class NativeZipReader {
14
+ export class NativeZipReader {
15
15
  #handle;
16
16
  constructor(path, options) {
17
17
  if (path.includes("\x00"))
@@ -35,6 +35,9 @@ class NativeZipReader {
35
35
  get status() {
36
36
  return native.symbols.csv_zip_reader_status(this.#requireHandle());
37
37
  }
38
+ enableReadAhead(chunkSize) {
39
+ native.symbols.csv_zip_reader_enable_read_ahead(this.#requireHandle(), chunkSize);
40
+ }
38
41
  read(output) {
39
42
  return u64ToSafeNumber(native.symbols.csv_zip_reader_read(this.#requireHandle(), output, output), "ZIP decompressed chunk length");
40
43
  }
@@ -58,11 +61,13 @@ class NativeZipReader {
58
61
  return this.#handle;
59
62
  }
60
63
  }
61
- export async function* readZipEntryChunks(path, options, chunkSize) {
64
+ export async function* readZipEntryChunks(path, options, chunkSize, readAhead = !1) {
62
65
  const outputSize = positiveUint32(chunkSize, "ZIP output chunk size");
63
66
  using reader = new NativeZipReader(path, options);
67
+ const reusableBuffer = readAhead ? new Uint8Array(outputSize) : void 0;
68
+ let startProducer = readAhead;
64
69
  while (!0) {
65
- const output = new Uint8Array(outputSize);
70
+ const output = reusableBuffer ?? new Uint8Array(outputSize);
66
71
  const written = reader.read(output);
67
72
  const status = reader.status;
68
73
  if (status === ZIP_READER_ERROR)
@@ -75,6 +80,10 @@ export async function* readZipEntryChunks(path, options, chunkSize) {
75
80
  return;
76
81
  if (written === 0)
77
82
  throw Error("native ZIP reader made no progress");
83
+ if (startProducer) {
84
+ reader.enableReadAhead(outputSize);
85
+ startProducer = !1;
86
+ }
78
87
  }
79
88
  }
80
89
  function positiveSafeInteger(value, label) {
package/package.json CHANGED
@@ -1,7 +1,20 @@
1
1
  {
2
2
  "name": "@konstit/csv",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "Bun-native CSV parser with streaming rows, filters, and low-allocation batches.",
5
+ "keywords": [
6
+ "AVX2",
7
+ "NEON",
8
+ "bun",
9
+ "cli",
10
+ "compressed",
11
+ "csv",
12
+ "filters",
13
+ "native",
14
+ "parser",
15
+ "streaming"
16
+ ],
17
+ "license": "MIT",
5
18
  "author": {
6
19
  "name": "KONSTIT ENGENHARIA E TECNOLOGIA LTDA",
7
20
  "email": "opensource@konstit.com.br"
@@ -18,19 +31,9 @@
18
31
  "email": "marcelo.marchioro@konstit.com.br"
19
32
  }
20
33
  ],
21
- "license": "MIT",
22
- "type": "module",
23
- "module": "./dist/index.js",
24
- "types": "./dist/index.d.ts",
25
34
  "bin": {
26
35
  "csv": "./dist/cli.js"
27
36
  },
28
- "exports": {
29
- ".": {
30
- "types": "./dist/index.d.ts",
31
- "import": "./dist/index.js"
32
- }
33
- },
34
37
  "files": [
35
38
  "dist",
36
39
  "prebuilds",
@@ -38,18 +41,15 @@
38
41
  "README.md",
39
42
  "THIRD_PARTY_NOTICES.md"
40
43
  ],
41
- "keywords": [
42
- "csv",
43
- "parser",
44
- "streaming",
45
- "compressed",
46
- "filters",
47
- "bun",
48
- "native",
49
- "cli",
50
- "AVX2",
51
- "NEON"
52
- ],
44
+ "type": "module",
45
+ "module": "./dist/index.js",
46
+ "types": "./dist/index.d.ts",
47
+ "exports": {
48
+ ".": {
49
+ "types": "./dist/index.d.ts",
50
+ "import": "./dist/index.js"
51
+ }
52
+ },
53
53
  "publishConfig": {
54
54
  "access": "public"
55
55
  },
@@ -70,13 +70,13 @@
70
70
  "hooks:install": "git config core.hooksPath .githooks",
71
71
  "bench:native-csv-parser": "bun run bench -- csv.bench.ts",
72
72
  "bench:csv-parser:example": "bun run build:native && hyperfine -r 2 --show-output --command-name '@konstit/csv csv.rows() iso88591' 'bun bench/csv-parser/example-file.ts konstit-csv' --command-name 'iconv-lite iso88591 + csv-parser' 'bun bench/csv-parser/example-file.ts csv-parser'",
73
- "bench:csv-parser:worker-materialize": "bun run bench -- csv-parser/example-file-worker-materialize.bench.ts",
74
73
  "bench:csv-parser:guard": "bun run build:native && bun bench/csv-parser/regression-guard.ts",
75
74
  "bench:csv-parser:synthetic:latin1": "bun run bench -- csv-parser/synthetic-latin1.bench.ts",
76
75
  "bench:csv-parser:synthetic:utf8": "bun run bench -- csv-parser/synthetic-utf8.bench.ts",
77
76
  "bench:example": "bun run bench -- example-file.bench.ts",
78
77
  "bench:field-access": "bun run bench -- field-access.bench.ts",
79
78
  "bench:latin1-decode": "bun run bench -- latin1-decode.bench.ts",
79
+ "bench:libs-comparison": "bun run build:native && bun bench/comparison/libs-comparison.ts",
80
80
  "bench:materialization:serial": "bun run bench -- materialization-serial.bench.ts",
81
81
  "bench:native-filters": "bun run bench -- native-filters.bench.ts",
82
82
  "bench:native": "bun run build:native && bun scripts/native-bench.ts",
@@ -86,19 +86,12 @@
86
86
  "bench:synthetic:latin1": "bun run bench -- synthetic-latin1.bench.ts",
87
87
  "bench:synthetic:utf8": "bun run bench -- synthetic-utf8.bench.ts",
88
88
  "bench:fixed-columns": "bun run bench -- fixed-columns.bench.ts",
89
- "bench:workers:materialize": "bun run bench -- workers/materialization.bench.ts",
90
- "bench:workers:all-columns": "bun run bench -- workers/example-file-all-columns.bench.ts",
91
- "bench:workers:native-sink": "bun run bench -- workers/native-sink.bench.ts",
92
- "bench:workers:shared-ipc": "bun run bench -- workers/shared-ipc.bench.ts",
93
89
  "example:api:batches": "bun examples/api-batches.ts",
94
90
  "example:api:count": "bun examples/api-count.ts",
95
- "example:api:worker-count": "bun examples/api-worker-count.ts",
96
- "example:api:worker-pool": "bun examples/api-worker-pool.ts",
97
91
  "example:api:rows": "bun examples/api-rows.ts",
98
92
  "example:api:shards": "bun examples/api-shards.ts",
99
93
  "example:api:strict-options": "bun examples/api-strict-options.ts",
100
94
  "example:api:typed-options": "bun examples/api-typed-options.ts",
101
- "example:api:worker-rows": "bun examples/api-worker-rows.ts",
102
95
  "example:first-rows": "bun examples/print-first-rows.ts",
103
96
  "profile:cpu": "bun run build:native && mkdir -p profiles && bun --cpu-prof-md --cpu-prof-dir profiles bench/profile-runtime.ts",
104
97
  "profile:cpu:csv-parser": "bun run build:native && mkdir -p profiles && bun --cpu-prof-md --cpu-prof-dir profiles bench/csv-parser/profile-runtime.ts",
@@ -115,21 +108,30 @@
115
108
  "fmt:native:check": "find native bench test -type f -name '*.cpp' -print0 | xargs -0 clang-format --dry-run --Werror",
116
109
  "prepush": "bun run build:native && bun run build:native:linux && bun run fmt:check && bun run fmt:native:check && bun run lint && bun run test:source-native && bun scripts/test-native.ts",
117
110
  "bench": "bun run build:native && bun run scripts/bench.ts",
118
- "test": "bun test --parallel"
111
+ "test": "bun test --parallel",
112
+ "csv": "bun --silent src/cli.ts"
119
113
  },
120
114
  "devDependencies": {
121
115
  "@biomejs/biome": "2.6.5",
122
116
  "@types/bun": "1.4.4",
117
+ "@types/papaparse": "5.5.2",
118
+ "csv-parse": "7.0.3",
123
119
  "csv-parser": "3.2.1",
124
120
  "csv-spectrum": "2.0.0",
125
121
  "dprint": "0.64.3",
122
+ "fast-csv": "5.0.8",
126
123
  "iconv-lite": "0.7.3",
127
124
  "mitata": "1.0.34",
128
125
  "oxlint": "1.91.0",
129
126
  "oxlint-tsgolint": "7.0.2006",
127
+ "papaparse": "5.7.1",
128
+ "turbocsv": "0.3.4",
130
129
  "typescript": "^5.9.3"
131
130
  },
132
131
  "engines": {
133
132
  "bun": "^1.4.0"
133
+ },
134
+ "dependencies": {
135
+ "@konstit/cli": "0.0.6"
134
136
  }
135
137
  }