@konstit/csv 0.4.3 → 0.5.1

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 (64) hide show
  1. package/README.md +50 -28
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +39 -249
  4. package/dist/api.js +56 -394
  5. package/dist/batches.d.ts +8 -57
  6. package/dist/batches.js +77 -52
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +315 -0
  9. package/dist/cli-schema.d.ts +127 -0
  10. package/dist/cli-schema.js +234 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +62 -3
  13. package/dist/file-stream.js +242 -36
  14. package/dist/files.d.ts +11 -11
  15. package/dist/files.js +38 -79
  16. package/dist/filter.d.ts +5 -8
  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 +22 -0
  22. package/dist/inspect-file.js +138 -0
  23. package/dist/latin1-rows.d.ts +4 -3
  24. package/dist/latin1-rows.js +72 -24
  25. package/dist/materialize-field.d.ts +2 -0
  26. package/dist/materialize-field.js +20 -15
  27. package/dist/native.d.ts +50 -78
  28. package/dist/native.js +36 -112
  29. package/dist/normalize.d.ts +14 -40
  30. package/dist/normalize.js +66 -64
  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 +23 -209
  35. package/dist/parser.js +146 -261
  36. package/dist/strict-schema.d.ts +6 -4
  37. package/dist/strict-schema.js +4 -3
  38. package/dist/types.d.ts +119 -221
  39. package/dist/zip-reader.d.ts +13 -1
  40. package/dist/zip-reader.js +36 -17
  41. package/package.json +36 -33
  42. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  43. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  44. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  45. package/prebuilds/manifest.json +9 -8
  46. package/prebuilds/provenance/darwin-arm64.json +1 -1
  47. package/prebuilds/provenance/darwin-x64.json +1 -1
  48. package/prebuilds/provenance/linux-x64.json +1 -1
  49. package/dist/worker-count.d.ts +0 -34
  50. package/dist/worker-count.js +0 -101
  51. package/dist/worker-factory.d.ts +0 -3
  52. package/dist/worker-factory.js +0 -9
  53. package/dist/worker-filter.d.ts +0 -29
  54. package/dist/worker-filter.js +0 -46
  55. package/dist/worker-module.d.ts +0 -1
  56. package/dist/worker-module.js +0 -4
  57. package/dist/worker-pool.d.ts +0 -93
  58. package/dist/worker-pool.js +0 -298
  59. package/dist/worker-rows.d.ts +0 -36
  60. package/dist/worker-rows.js +0 -127
  61. package/dist/workers/count.worker.d.ts +0 -1
  62. package/dist/workers/count.worker.js +0 -36
  63. package/dist/workers/rows.worker.d.ts +0 -1
  64. 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. */
@@ -184,20 +189,29 @@ export interface CsvShard {
184
189
  /** Inclusive end byte offset in the file. */
185
190
  end: number;
186
191
  }
192
+ interface CsvRowSelectionOptions {
193
+ /** Number of initial input records to skip, including any header, before filtering. Defaults to zero. */
194
+ readonly skipRows?: number;
195
+ /** Maximum number of matching rows to emit or count across the entire input. Defaults to unlimited. */
196
+ readonly limit?: number;
197
+ }
187
198
  /**
188
199
  * Parser configuration shared by in-memory parsing and file APIs.
189
200
  *
190
201
  * Options are readonly and are captured at operation invocation time, before
191
202
  * asynchronous iteration begins. Start a new operation to apply changed arrays
192
203
  * or values.
204
+ *
205
+ * @typeParam TEncoding - Defaults to the native parser's labels. File and buffer
206
+ * parsing accept the full {@link CsvEncoding} set.
193
207
  */
194
- export interface CsvParserOptions {
208
+ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeEncoding> extends CsvRowSelectionOptions {
195
209
  /** 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. */
210
+ readonly encoding?: TEncoding;
211
+ /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
198
212
  readonly delimiter?: CsvDelimiter;
199
213
  /** Physical columns to emit from each row, in the requested output order. */
200
- readonly selectedColumns?: CsvColumns;
214
+ readonly columns?: CsvColumns;
201
215
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
202
216
  readonly fixedColumns?: number;
203
217
  /** Enable RFC-style quote and schema validation. Defaults to `false`. */
@@ -213,12 +227,14 @@ export interface CsvParserOptions {
213
227
  * File input options, including parser settings and stream controls.
214
228
  *
215
229
  * 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.
230
+ * into memory. Byte-offset sharding requires an uncompressed file.
217
231
  */
218
- export interface CsvFileOptions extends CsvParserOptions {
232
+ export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
233
+ /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
234
+ readonly encoding?: CsvFileEncoding;
219
235
  /** Read-stream chunk size in bytes. Defaults to 1 MiB. */
220
236
  readonly chunkSize?: number;
221
- /** Optional compression format or ZIP entry selection. */
237
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
222
238
  readonly compression?: CsvCompression;
223
239
  }
224
240
  /**
@@ -227,9 +243,11 @@ export interface CsvFileOptions extends CsvParserOptions {
227
243
  * Compression is excluded because compressed byte streams cannot be split into
228
244
  * independently readable file ranges.
229
245
  */
230
- export type CsvShardingOptions = Omit<CsvFileOptions, 'compression'> & {
246
+ export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'encoding' | keyof CsvRowSelectionOptions> & {
231
247
  /** Compression is unsupported for byte-offset sharding. */
232
248
  readonly compression?: never;
249
+ /** Sharding scans raw file bytes and supports native encodings only. */
250
+ readonly encoding?: CsvNativeEncoding;
233
251
  };
234
252
  /** Native equality predicate used by projection and count fast paths. */
235
253
  export interface CsvEqualsFilter {
@@ -278,7 +296,7 @@ export interface CsvRegexFilter {
278
296
  *
279
297
  * High-level row and count APIs normally use the opaque `CsvFilter` returned by
280
298
  * the filter factories instead. High-level options copy operands at invocation
281
- * time; low-level parser calls normalize their operands for each write.
299
+ * time. The manual parser captures its operands at construction.
282
300
  */
283
301
  export type CsvNativeFilter = CsvEqualsFilter | CsvInFilter | CsvNotInFilter | CsvNotEqualsFilter | CsvRegexFilter | CsvStartsWithFilter;
284
302
  /**
@@ -289,137 +307,100 @@ export type CsvNativeFilter = CsvEqualsFilter | CsvInFilter | CsvNotInFilter | C
289
307
  */
290
308
  export interface CsvNativeProjectionOptions {
291
309
  /** Physical columns to emit, in output order. */
292
- readonly selectedColumns?: CsvColumns;
293
- /** One equality predicate for the direct native fast path. */
310
+ readonly columns?: CsvColumns;
311
+ /** One equality predicate on a physical column. */
294
312
  readonly equalsFilter?: CsvEqualsFilter;
295
313
  /** Native predicates combined for the operation. */
296
314
  readonly filters?: readonly CsvNativeFilter[];
297
315
  }
298
316
  /**
299
- * Common file options for the high-level `csv` API.
317
+ * Boolean operation in a postfix filter program accepted by `NativeCsvParser`.
300
318
  *
301
- * Use `columns` for the preferred projection spelling. `selectedColumns` is a
302
- * legacy alias; supplying both is rejected.
319
+ * Predicates push results onto a stack. An operator consumes the most recent
320
+ * results and pushes one combined result. Missing columns produce an unknown
321
+ * result, which remains unknown under `not` and does not select a row by itself.
303
322
  */
304
- 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
- /** Opaque filter created by `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. */
310
- readonly where?: CsvFilter;
323
+ export interface CsvNativeFilterOperator {
324
+ /** Number of preceding stack results to consume; positive, and exactly one for `not`. */
325
+ readonly operandCount: number;
326
+ /** Combine operands with AND, OR, or unary negation. */
327
+ readonly operator: 'all' | 'any' | 'not';
311
328
  }
312
329
  /**
313
- * Type-safe mutually exclusive projection fields.
330
+ * Predicate or boolean operator in a low-level postfix filter program.
314
331
  *
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.
332
+ * Place predicates before the operators that consume them. A complete program
333
+ * must leave exactly one result on the stack and contain at most 4096 entries.
334
+ * Most applications can use `csv.column()` and its boolean combinators instead.
318
335
  */
319
- export type CsvColumnSelection<TColumns extends CsvColumns | undefined> = {
320
- /** Preferred projection spelling; indexes are emitted in this order. */
336
+ export type CsvNativeFilterProgramEntry = CsvNativeFilter | CsvNativeFilterOperator;
337
+ /** Projection and filter settings captured when a manual parser is constructed. */
338
+ export interface NativeCsvParserOptions extends CsvParserOptions, CsvNativeProjectionOptions {
339
+ /** Postfix Boolean program. Supply only one of `filterProgram`, `filters`, or `equalsFilter`. */
340
+ readonly filterProgram?: readonly CsvNativeFilterProgramEntry[];
341
+ }
342
+ /** Common file options for the high-level `csv` API. */
343
+ export interface CsvApiFileOptions extends CsvFileOptions {
344
+ /** Opaque filter created by `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. */
345
+ readonly where?: CsvFilter;
346
+ }
347
+ /** Retains the literal input indexes and their order for projected row types. */
348
+ export interface CsvColumnSelection<TColumns extends CsvColumns | undefined> {
349
+ /** Physical columns to emit from each row, in the requested output order. */
321
350
  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). */
351
+ }
352
+ /** Shared operation properties have declarations that editors can use for hover documentation. */
353
+ interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends CsvColumnSelection<TColumns>, CsvRowSelectionOptions {
354
+ /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
355
+ readonly delimiter?: CsvDelimiter;
356
+ /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
357
+ readonly fixedColumns?: number;
358
+ /** Expected first-row field values, checked in strict mode. */
359
+ readonly expectedHeaders?: readonly string[];
360
+ /** Require a first row when strict schema validation is enabled. */
361
+ readonly requireHeader?: boolean;
362
+ /** Minimum number of data rows after the header, checked in strict mode. */
363
+ readonly minDataRows?: number;
364
+ /** Read-stream chunk size in bytes. Defaults to 1 MiB. Used by file operations only. */
365
+ readonly chunkSize?: number;
366
+ }
367
+ /** File operations support encoding detection and streamed decompression. */
368
+ interface CsvFileOperationOptions<TColumns extends CsvColumns | undefined> extends CsvOperationOptions<TColumns> {
369
+ /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
370
+ readonly encoding?: CsvFileEncoding;
371
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
372
+ readonly compression?: CsvCompression;
373
+ }
374
+ /** Non-strict operations can filter input records. */
375
+ interface CsvFilteredOperationOptions {
376
+ /** Enable RFC-style quote and schema validation. Defaults to `false`. Requires unfiltered input. */
345
377
  readonly strict?: false | undefined;
346
- /** Optional immutable filter created by the CSV filter factories. */
378
+ /** Filter records with `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. Requires `strict` to be false or omitted. */
347
379
  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`. */
380
+ }
381
+ /** Strict validation requires unfiltered input. */
382
+ interface CsvStrictOperationOptions {
383
+ /** Enable RFC-style quote and schema validation. Requires unfiltered input. */
352
384
  readonly strict: true;
353
- /** Filters are excluded when strict validation is enabled. */
385
+ /** Filtering is unavailable with strict validation, which checks every input record. */
354
386
  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
- };
387
+ }
388
+ /** Each branch keeps its documented properties and enforces the strict/filter constraint. */
389
+ type CsvValidationOptions = CsvFilteredOperationOptions | CsvStrictOperationOptions;
374
390
  /** 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;
391
+ export type CsvParseOptions<TColumns extends CsvColumns | undefined = undefined> = CsvOperationOptions<TColumns> & CsvValidationOptions & {
392
+ /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
393
+ readonly encoding?: CsvEncoding;
391
394
  };
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;
395
+ /** Options for streaming materialized rows in file order. */
396
+ export type CsvRowsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvFileOperationOptions<TColumns> & CsvValidationOptions & {
397
+ /** Refill the batch and its row arrays across iterations. Copy any row you want to keep. Defaults to false. */
398
+ readonly reuseArrays?: boolean;
418
399
  };
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>;
400
+ /** Strict native batches require unfiltered, unprojected input. */
401
+ export type CsvBatchesOptions = (CsvFileOperationOptions<CsvColumns | undefined> & CsvFilteredOperationOptions) | (CsvFileOperationOptions<undefined> & CsvStrictOperationOptions);
402
+ /** Options accepted by `csv.count()`. */
403
+ export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> & CsvValidationOptions;
423
404
  /**
424
405
  * Materialized row type inferred from a literal projection tuple.
425
406
  *
@@ -430,33 +411,6 @@ export type CsvWorkerPoolOptions<TColumns extends CsvColumns | undefined = undef
430
411
  export type CsvProjectedRow<TColumns extends CsvColumns | undefined> = TColumns extends readonly unknown[] ? {
431
412
  -readonly [Index in keyof TColumns]: string;
432
413
  } : 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
414
  /**
461
415
  * Synchronous callback invoked by `NativeCsvBatch.forEachRow()`.
462
416
  *
@@ -490,60 +444,4 @@ export type CsvColumnBytesCallback = (rowIndex: number, bytes: Uint8Array) => vo
490
444
  * array and buffer are reused for each row.
491
445
  */
492
446
  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
447
  export {};
@@ -1,2 +1,14 @@
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
+ get entryName(): string;
7
+ enableReadAhead(chunkSize: number): void;
8
+ read(output: Uint8Array): number;
9
+ lastError(): string;
10
+ chunks(outputSize: number, readAhead?: boolean): Generator<Uint8Array, void>;
11
+ close(): void;
12
+ [Symbol.dispose](): void;
13
+ }
14
+ export declare function readZipEntryChunks(path: string, options: CsvZipCompression, chunkSize: number, readAhead?: boolean): AsyncGenerator<Uint8Array, void>;
@@ -1,5 +1,7 @@
1
1
  import {
2
2
  native,
3
+ requirePtr,
4
+ toArrayBuffer,
3
5
  u64ToSafeNumber
4
6
  } from "./native.js";
5
7
  const DEFAULT_MAXIMUM_DECOMPRESSED_BYTES = 68719476736;
@@ -11,7 +13,7 @@ function destroyNativeZipReader(handle) {
11
13
  native.symbols.csv_zip_reader_destroy(handle);
12
14
  }
13
15
 
14
- class NativeZipReader {
16
+ export class NativeZipReader {
15
17
  #handle;
16
18
  constructor(path, options) {
17
19
  if (path.includes("\x00"))
@@ -35,12 +37,43 @@ class NativeZipReader {
35
37
  get status() {
36
38
  return native.symbols.csv_zip_reader_status(this.#requireHandle());
37
39
  }
40
+ get entryName() {
41
+ const length = new Uint32Array(1);
42
+ const name = native.symbols.csv_zip_reader_entry_name(this.#requireHandle(), length);
43
+ return Buffer.from(toArrayBuffer(requirePtr(name), 0, length[0])).toString("utf8");
44
+ }
45
+ enableReadAhead(chunkSize) {
46
+ native.symbols.csv_zip_reader_enable_read_ahead(this.#requireHandle(), chunkSize);
47
+ }
38
48
  read(output) {
39
49
  return u64ToSafeNumber(native.symbols.csv_zip_reader_read(this.#requireHandle(), output, output), "ZIP decompressed chunk length");
40
50
  }
41
51
  lastError() {
42
52
  return native.symbols.csv_zip_reader_last_error(this.#requireHandle())?.toString() ?? "ZIP reader error unavailable";
43
53
  }
54
+ *chunks(outputSize, readAhead = !1) {
55
+ const reusableBuffer = readAhead ? new Uint8Array(outputSize) : void 0;
56
+ let startProducer = readAhead;
57
+ while (!0) {
58
+ const output = reusableBuffer ?? new Uint8Array(outputSize);
59
+ const written = this.read(output);
60
+ const status = this.status;
61
+ if (status === ZIP_READER_ERROR)
62
+ throw Error(`native ZIP reader failed: ${this.lastError()}`);
63
+ if (written > output.byteLength)
64
+ throw Error("native ZIP reader returned an invalid output length");
65
+ if (written !== 0)
66
+ yield output.subarray(0, written);
67
+ if (status === ZIP_READER_DONE)
68
+ return;
69
+ if (written === 0)
70
+ throw Error("native ZIP reader made no progress");
71
+ if (startProducer) {
72
+ this.enableReadAhead(outputSize);
73
+ startProducer = !1;
74
+ }
75
+ }
76
+ }
44
77
  close() {
45
78
  const handle = this.#handle;
46
79
  if (handle === null)
@@ -58,24 +91,10 @@ class NativeZipReader {
58
91
  return this.#handle;
59
92
  }
60
93
  }
61
- export async function* readZipEntryChunks(path, options, chunkSize) {
94
+ export async function* readZipEntryChunks(path, options, chunkSize, readAhead = !1) {
62
95
  const outputSize = positiveUint32(chunkSize, "ZIP output chunk size");
63
96
  using reader = new NativeZipReader(path, options);
64
- while (!0) {
65
- const output = new Uint8Array(outputSize);
66
- const written = reader.read(output);
67
- const status = reader.status;
68
- if (status === ZIP_READER_ERROR)
69
- throw Error(`native ZIP reader failed: ${reader.lastError()}`);
70
- if (written > output.byteLength)
71
- throw Error("native ZIP reader returned an invalid output length");
72
- if (written !== 0)
73
- yield output.subarray(0, written);
74
- if (status === ZIP_READER_DONE)
75
- return;
76
- if (written === 0)
77
- throw Error("native ZIP reader made no progress");
78
- }
97
+ yield* reader.chunks(outputSize, readAhead);
79
98
  }
80
99
  function positiveSafeInteger(value, label) {
81
100
  if (!Number.isSafeInteger(value) || value <= 0)