@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/README.md CHANGED
@@ -1,27 +1,32 @@
1
1
  # @konstit/csv
2
2
 
3
- A high-performance streaming CSV parsing library for Bun using a native C++ parser with SIMD acceleration (AVX2/NEON), streaming file access, filtering, and column selection.
4
-
5
- [Quick start](#quick-start) · [Choose an API](#choose-an-api) · [CLI](#cli) · [Documentation](#documentation)
6
-
7
- - Stream large files in batches, or parse a buffer you already have in memory.
8
- - Filter records and select columns before materializing results as JavaScript rows.
9
- - Reads [RFC 4180](https://www.rfc-editor.org/info/rfc4180) CSV. Set `strict: true` to reject malformed quoting.
10
- - Tested against [csv-spectrum](https://github.com/maxogden/csv-spectrum), selected [W3C CSVW](https://w3c.github.io/csvw/tests/) cases,
11
- and fixtures derived from [csvkit](https://github.com/wireservice/csvkit).
12
- - Stream compressed files:
13
- - zip
14
- - gzip
15
- - brotli
16
- - zstd
17
- - deflate
18
- - Auto detect delimiters, encoding and compression.
19
- - UTF-8 and Latin-1 have specialized native fast paths.
20
- - More encodings are supported out of the box, including Windows-1252, UTF-16LE, and Shift_JIS.
3
+ `@konstit/csv` is a Bun-native CSV parser accelerated with AVX2 and NEON. Its main API, `csv.rows()`, streams CSV files
4
+ and byte streams in batches of string arrays or objects keyed by column name.
5
+
6
+ [Quick start](#quick-start) · [Test corpus](#test-corpus) · [Choose an API](#choose-an-api) · [CLI](#cli) · [Documentation](#documentation)
7
+
8
+ - **Named columns and typed object rows.** Read headers from the input or supply your own. Select, filter, and transform
9
+ columns by name, and set `mapped: true` to emit objects.
10
+ - **Native filters and field transforms.** Filter source records before creating JavaScript rows, then trim, change
11
+ case, replace text, map values, or format dates in the accepted rows.
12
+ - **Compressed and legacy inputs.** Stream gzip, Brotli, Zstandard, deflate, and ZIP, including nested ZIP members selected
13
+ by path or glob. Detect compression, encoding, and delimiters automatically. UTF-8 and Latin-1
14
+ use native fast paths. Windows-1252, UTF-16, Shift_JIS, and CP949 are also supported.
15
+ - **Validation and format diagnostics.** Skip empty records with `skipEmptyLines`, cap logical record size with
16
+ `maxRecordBytes`, and validate quotes, field counts, and headers with strict mode. The CLI's `probe` command explains
17
+ format detection and can display a nested ZIP archive tree.
18
+
19
+ ## Test corpus
20
+
21
+ The compatibility suite covers valid and malformed CSV, including multiline fields, alternate delimiters, missing final
22
+ newlines, and uneven record widths. It uses [RFC 4180 fixtures](https://github.com/Konstit-Engenharia/csv-parser/tree/main/corpus/rfc4180),
23
+ selected [Pollock fixtures](https://github.com/Konstit-Engenharia/csv-parser/tree/main/corpus/pollock),
24
+ [csv-spectrum](https://github.com/maxogden/csv-spectrum), selected [W3C CSVW cases](https://w3c.github.io/csvw/tests/),
25
+ and fixtures derived from [csvkit](https://github.com/wireservice/csvkit).
21
26
 
22
27
  ## Installation
23
28
 
24
- Requires **Bun `^1.4.0`**. Published packages include native libraries for these targets:
29
+ Requires **Bun `^1.4.5`**. Published packages include native libraries for these targets:
25
30
 
26
31
  | Operating system | Architecture | CPU requirement |
27
32
  | ---------------- | ------------ | --------------- |
@@ -34,39 +39,13 @@ bun add @konstit/csv
34
39
  ```
35
40
 
36
41
  No native build is needed on supported targets. For building from source, see
37
- [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md).
42
+ [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/CONTRIBUTING.md).
38
43
 
39
44
  ## Quick start
40
45
 
41
- Parse a buffer with `await csv.parse()`. Save this example as `parse.ts`:
46
+ ### Stream a file
42
47
 
43
- ```ts
44
- import { csv } from '@konstit/csv';
45
-
46
- const input = Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n');
47
- const rows = await csv.parse(input);
48
-
49
- console.log(rows);
50
- // [
51
- // ['id', 'name', 'state'],
52
- // ['1', 'Ada', 'SP'],
53
- // ['2', 'Grace', 'RJ'],
54
- // ]
55
- ```
56
-
57
- ```sh
58
- bun parse.ts
59
- ```
60
-
61
- Each row is an array of strings. Headers remain ordinary records, and numeric-looking fields remain strings.
62
- File and buffer APIs default to a comma delimiter. Buffers default to UTF-8; file readers detect UTF-8, Latin-1,
63
- Windows-1252 or BOM-marked UTF-16 from the first 64 KiB after decompression. Set `delimiter: 'auto'` on a file
64
- to detect both from the same sample. To skip detection, pass the encoding and delimiter explicitly.
65
- UTF-8 and Latin-1 use native paths; other supported `Bun.Encoding` labels are transcoded to UTF-8.
66
-
67
- ## Stream a file
68
-
69
- For files that do not fit in memory, use `csv.rows()`. Create `data.csv` with the same sample data:
48
+ Create `data.csv` with these rows.
70
49
 
71
50
  ```csv
72
51
  id,name,state
@@ -74,6 +53,8 @@ id,name,state
74
53
  2,Grace,RJ
75
54
  ```
76
55
 
56
+ Save the code below as `rows.ts`. Run it with `bun rows.ts`.
57
+
77
58
  ```ts
78
59
  import { csv } from '@konstit/csv';
79
60
 
@@ -84,42 +65,39 @@ for await (const batch of csv.rows('data.csv')) {
84
65
  }
85
66
  ```
86
67
 
87
- Each iteration yields a **batch of rows** in file order, so use the inner loop to process individual records. Process
88
- batches as they arrive to avoid collecting the complete file in memory. The header is returned as the first row.
68
+ Each iteration yields a **batch of rows** in file order. The first row is the header, and every field is returned as a
69
+ string. Process batches as they arrive to avoid collecting the complete file in memory.
70
+
71
+ `csv.rows()`, `csv.batches()`, and `csv.count()` also accept a byte stream, such as a non-null `Response.body` or an async generator of `Uint8Array` chunks. Set `maxRecordBytes` to bound the size of an individual logical record.
89
72
 
90
73
  Pass `{ skipRows: 1, limit: 10 }` to skip the header and emit up to ten rows. With a filter, `skipRows` counts
91
74
  input records and `limit` counts matches across all batches.
92
75
 
93
- To count records without materializing rows:
94
-
95
- ```ts
96
- import { csv } from '@konstit/csv';
97
-
98
- console.log(await csv.count('data.csv')); // 3, including the header
99
- ```
76
+ ## Common operations
100
77
 
101
- ## Choose an API
78
+ These examples read the `data.csv` shown above.
102
79
 
103
- | Task | API | Result or lifecycle |
104
- | ---------------------------- | ----------------------------------------------------------- | --------------------------------------------------- |
105
- | Parse an in-memory buffer | `await csv.parse(buffer)` | All rows as arrays of strings |
106
- | Stream a file | `csv.rows(path)` | Async stream of row batches |
107
- | Count records | `await csv.count(path)` | Record count, optionally filtered |
108
- | Access native batches | `csv.batches(path, options)` | Use `using` to close each batch after its iteration |
109
- | Visit rows or scan columns | `batch.forEachRow()` / `batch.scanColumns()` | Read projected fields by position within the batch |
110
- | Supply your own input chunks | `NativeCsvParser` | Manual parser and batch disposal |
111
- | Find record-safe boundaries | `csv.findCsvSafeSplitOffsets()` / `csv.findCsvSafeShards()` | Advanced byte-range processing |
80
+ ### Filter records and select columns
112
81
 
113
- Start with `csv.rows()` for streaming records. Use batches or views when you need byte access or lower allocation
114
- overhead. Advanced applications can use the record-safe boundary helpers to divide an uncompressed CSV file into
115
- byte ranges for their own processing pipeline. See the [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md)
116
- for options and resource lifetimes.
82
+ Set `headers: true` to read and consume the input header. Use `mapped: true` to get objects keyed by the selected names.
117
83
 
118
- ## Common operations
84
+ ```ts
85
+ import { csv } from '@konstit/csv';
119
86
 
120
- These examples read the `data.csv` shown above.
87
+ for await (
88
+ const batch of csv.rows('data.csv', {
89
+ headers: true,
90
+ columns: ['name', 'id'],
91
+ where: (column) => column('state').equals('SP'),
92
+ mapped: true,
93
+ })
94
+ ) {
95
+ console.log(batch); // [{ name: 'Ada', id: '1' }]
96
+ }
97
+ ```
121
98
 
122
- ### Filter records and select columns
99
+ You can also supply column names in input order, use them in transforms, or build named filters for `csv.count()`.
100
+ [Named columns and object rows](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#named-columns-and-object-rows)
123
101
 
124
102
  Column indexes are zero-based **source column indexes**: `id` is `0`, `name` is `1`, and `state` is `2`.
125
103
  Filters use source indexes even when output columns are reordered.
@@ -140,7 +118,7 @@ for await (
140
118
  The filter also applies to the header, which does not match `'SP'` here. Combine conditions with `csv.all()`,
141
119
  `csv.any()`, and `csv.not()`. Filters support equality, membership, prefixes, and RE2 regular expressions.
142
120
 
143
- See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
121
+ See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#filters) for matching rules
144
122
  and supported regex syntax.
145
123
 
146
124
  ### Transform accepted rows
@@ -166,9 +144,9 @@ for await (
166
144
  // Grace, Rio de Janeiro
167
145
  ```
168
146
 
169
- Run `bun run examples/api-rows-transforms.ts` from the repository to try two more [streaming examples](https://github.com/Konstit-Engenharia/csv-parser/blob/main/examples/api-rows-transforms.ts) with sample orders. The first cleans names, cities, and amounts. The second formats order IDs using numbered and named captures.
147
+ Run `bun run examples/api-rows-transforms.ts` from a checkout to clean customer names, cities, and amounts by column name and format order IDs using regex captures. [Order transforms](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/examples/api-rows-transforms.ts)
170
148
 
171
- See [field transforms](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#field-transforms) for Unicode rules, replacement, value mapping, and date formatting.
149
+ See [field transforms](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#field-transforms) for Unicode rules, replacement, value mapping, and date formatting.
172
150
 
173
151
  ### Read compressed files
174
152
 
@@ -194,34 +172,64 @@ for await (
194
172
 
195
173
  File APIs and the CLI detect compression by default and read plain CSV, TSV, and text files directly.
196
174
  For a plain file with an unrecognized name, use `compression: 'none'` or `--compression none`.
197
- Decompression streams into the parser.
175
+ Regular gzip files use native read-ahead and can decompress large members in parallel with automatic or explicit gzip selection.
176
+ Gzip from pipes and other non-regular inputs uses Bun's `DecompressionStream`.
198
177
 
199
178
  ZIP archives automatically select the only data file, ignoring directories and OS metadata.
200
- For archives with multiple data files, select an entry with `compression: { format: 'zip', entry: 'data.csv' }`. See
201
- [Compression](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#compression-and-delimiter-detection)
179
+ For archives with multiple data files, select an entry with `compression: { format: 'zip', entry: 'data.csv' }`.
180
+ Use a selector such as `imports.zip!/data.csv` to read through a nested ZIP. See
181
+ [Compression](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#compression-and-delimiter-detection)
202
182
  for supported formats, detection rules, and limits.
203
183
 
184
+ For TSV exports with quoting disabled, use `quote: false` and `recordDelimiter: '\n'`.
185
+ Use `csv.batches()` with `output: 'raw-records'` to filter these files and access each record's original
186
+ decompressed bytes, including its line ending. See
187
+ [Raw record batches](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#raw-record-batches).
188
+
204
189
  ### Validate input
205
190
 
206
191
  ```ts
207
192
  import { csv } from '@konstit/csv';
208
193
 
209
- const rows = await csv.parse(
210
- Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n'),
211
- {
194
+ for await (
195
+ const batch of csv.rows('data.csv', {
196
+ headers: true,
212
197
  strict: true,
213
198
  expectedHeaders: ['id', 'name', 'state'],
214
199
  minDataRows: 1,
215
- },
216
- );
200
+ })
201
+ ) {
202
+ console.log(batch); // [['1', 'Ada', 'SP'], ['2', 'Grace', 'RJ']]
203
+ }
204
+ ```
217
205
 
218
- console.log(rows.length); // 3
206
+ Strict mode validates quote syntax and physical row widths before applying filters or projections. Header and minimum-row checks use the consumed input records. Syntax and width errors identify the one-based record and field. See [strict validation](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md#strict-validation).
207
+
208
+ ## Choose an API
209
+
210
+ | Task | API | Result or lifecycle |
211
+ | ---------------------------- | ----------------------------------------------------------- | --------------------------------------------------- |
212
+ | Stream a file or byte stream | `csv.rows(input, options)` | Async stream of row batches |
213
+ | Count records | `await csv.count(input, options)` | Record count, optionally filtered |
214
+ | Parse an in-memory buffer | `await csv.parse(buffer, options)` | All rows as arrays of strings |
215
+ | Access native batches | `csv.batches(input, options)` | Use `using` to close each batch after its iteration |
216
+ | Visit rows or scan columns | `batch.forEachRow()` / `batch.scanColumns()` | Read projected fields by position within the batch |
217
+ | Supply your own input chunks | `NativeCsvParser` | Manual parser and batch disposal |
218
+ | Find record-safe boundaries | `csv.findCsvSafeSplitOffsets()` / `csv.findCsvSafeShards()` | Advanced byte-range processing |
219
+
220
+ ```ts
221
+ import { csv } from '@konstit/csv';
222
+
223
+ const total = await csv.count('data.csv'); // 3, including the header
224
+ const rows = await csv.parse(
225
+ Buffer.from('id,name,state\n1,Ada,SP\n2,Grace,RJ\n'),
226
+ );
219
227
  ```
220
228
 
221
- Strict mode validates quote syntax and can check header and row-count requirements. It supports column selection
222
- with `csv.parse()` and `csv.rows()`, but cannot be combined with filters. See
223
- [Strict validation](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#strict-validation)
224
- for supported combinations.
229
+ The parsing and sharding APIs detect the delimiter by default. Pass a delimiter such as `','` to skip detection.
230
+ Buffers default to UTF-8.
231
+ File readers detect encoding from the first 64 KiB after decompression and use the same sample for `delimiter: 'auto'`. See the
232
+ [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md) for options and resource lifetimes.
225
233
 
226
234
  ## CLI
227
235
 
@@ -240,37 +248,41 @@ bunx @konstit/csv lines data.csv --json --skip-rows 1 --limit 2
240
248
  ```
241
249
 
242
250
  The CLI detects input encoding and delimiter by default. `probe --json` reports the file size in bytes,
243
- how much of the decompressed payload it inspected, and whether it reached the end. Use `--delimiter` or
244
- `--encoding` to inspect a known format. Without `--json`, `lines` writes normalized UTF-8 CSV.
251
+ how much of the decompressed payload it inspected, the sampled column range, and the detection evidence.
252
+ Use `--sample-size` to inspect a larger prefix, or `--compression`, `--delimiter`, and `--encoding` to
253
+ inspect a known format. Use `-` as the input path to read stdin with `count` or `lines`.
254
+ Without `--json`, `lines` writes normalized UTF-8 CSV.
245
255
  `count` and `lines` support column filters; `lines` also supports
246
256
  column selection. Use `bunx @konstit/csv lines --help` or read the
247
- [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md) for flags and output behavior.
257
+ [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/cli.md) for flags and output behavior.
258
+ From a checkout, use `bun run csv --help` to try the local CLI.
248
259
 
249
260
  ## Documentation
250
261
 
251
- - [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md): filters, encoding, compression,
262
+ - [Runnable examples](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/CONTRIBUTING.md#run-examples) for the API, all using the bundled orders CSV.
263
+ - [API guide](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/api.md): filters, encoding, compression,
252
264
  validation, typed options, batches, views, advanced byte boundaries, and manual parsing.
253
- - [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md): commands, filters, output formats,
265
+ - [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/cli.md): commands, filters, output formats,
254
266
  and option constraints.
255
- - [Benchmarks](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md): datasets, commands,
267
+ - [Benchmarks](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/benchmarks.md): datasets, commands,
256
268
  recorded measurements, and their limitations.
257
- - [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md): repository setup, examples,
269
+ - [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/CONTRIBUTING.md): repository setup, examples,
258
270
  validation, native development, and releases.
259
271
 
260
272
  ## Performance
261
273
 
262
274
  The parser uses native C++ with AVX2 on x64 and NEON on ARM64. Filtering and counting can avoid creating JavaScript
263
- rows for records you do not need. The [benchmark guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/benchmarks.md)
275
+ rows for records you do not need. The [benchmark guide](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/docs/benchmarks.md)
264
276
  records a full-file comparison, including memory use and reproduction commands. Results depend on the workload,
265
277
  hardware, and selected API.
266
278
 
267
279
  ## Contributing
268
280
 
269
- See [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/main/CONTRIBUTING.md) to run the project locally,
281
+ See [Contributing](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/CONTRIBUTING.md) to run the project locally,
270
282
  validate changes, or rebuild the native libraries.
271
283
 
272
284
  ## License
273
285
 
274
286
  MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See
275
- [LICENSE](https://github.com/Konstit-Engenharia/csv-parser/blob/main/LICENSE) and
276
- [third-party notices](https://github.com/Konstit-Engenharia/csv-parser/blob/main/THIRD_PARTY_NOTICES.md).
287
+ [LICENSE](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/LICENSE) and
288
+ [third-party notices](https://github.com/Konstit-Engenharia/csv-parser/blob/v0.7.0/THIRD_PARTY_NOTICES.md).
@@ -441,6 +441,33 @@ it and redistribute it freely, subject to the following restrictions:
441
441
  software.
442
442
  3. This notice may not be removed or altered from any source distribution.
443
443
 
444
+ ## rapidgzip and librapidarchive
445
+
446
+ - Source: https://github.com/mxmlnkn/librapidarchive
447
+ - Version: rapidgzip 0.16.2
448
+ - License: MIT
449
+ - Use in this project: DEFLATE block discovery and worker scheduling for parallel ZIP streaming.
450
+
451
+ Copyright (c) 2019-2023 Maximilian Knespel
452
+
453
+ Permission is hereby granted, free of charge, to any person obtaining a copy
454
+ of this software and associated documentation files (the "Software"), to deal
455
+ in the Software without restriction, including without limitation the rights
456
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
457
+ copies of the Software, and to permit persons to whom the Software is
458
+ furnished to do so, subject to the following conditions:
459
+
460
+ The above copyright notice and this permission notice shall be included in all
461
+ copies or substantial portions of the Software.
462
+
463
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
464
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
465
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
466
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
467
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
468
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
469
+ SOFTWARE.
470
+
444
471
  ## csv-spectrum
445
472
 
446
473
  - Source: https://github.com/maxogden/csv-spectrum
package/dist/api.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import type { NativeCsvBatch } from './batches.js';
2
- import type { CsvFileProbe } from './file-stream.js';
1
+ import { type MappedRowLayout, type NativeCsvBatch, type NativeCsvRawRecordBatch } from './batches.js';
2
+ import { type CsvFileProbe } from './file-stream.js';
3
3
  import { all, any, column, not, re } from './filter.js';
4
4
  import { transform } from './transforms.js';
5
- import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
5
+ import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvHeaderName, CsvHeaderSource, CsvInput, CsvMappedRow, CsvNamedCountOptions, CsvNamedRowsBatch, CsvNamedRowsOptions, CsvParseOptions, CsvProjectedParseOptions, CsvProjectedRow, CsvProjectedRowsOptions, CsvRawRecordBatchesOptions, CsvRequiredNamedRowsOptions, CsvRow, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
6
6
  /**
7
- * Parse one in-memory CSV buffer into materialized rows.
7
+ * Parse an in-memory CSV buffer into tuples in the requested projection order.
8
8
  *
9
9
  * Use this when the input is already buffered and a single promise containing all rows is suitable.
10
10
  * The buffer is parsed as one complete input, so a record may not be split across calls. Use
@@ -13,71 +13,92 @@ import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, C
13
13
  *
14
14
  * @typeParam TColumns - Literal projected column indexes, when a projection is supplied.
15
15
  * @param buffer - CSV bytes in a typed array or `DataView`.
16
- * @param suppliedOptions - Parser options for uncompressed bytes with a fixed delimiter.
16
+ * @param suppliedOptions - Parser options for uncompressed bytes.
17
17
  * @returns A promise that resolves to the materialized rows in input order.
18
- * @throws {Error} If the options request compression, automatic delimiter detection, or an
19
- * unsupported filtered strict-validation combination.
18
+ * @throws {Error} If buffer options are invalid or a consumed record fails validation.
20
19
  */
21
- export declare function parse<TColumns extends CsvColumns | undefined = undefined>(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParseOptions<TColumns>): Promise<CsvProjectedRow<TColumns>[]>;
20
+ export declare function parse<TColumns extends CsvColumns>(buffer: NodeJS.TypedArray | DataView, suppliedOptions: CsvProjectedParseOptions<TColumns>): Promise<CsvProjectedRow<TColumns>[]>;
22
21
  /**
23
- * Stream materialized rows from a CSV file.
22
+ * Parse an in-memory CSV buffer into materialized arrays in input order.
23
+ * Supply uncompressed bytes. The delimiter is detected by default. Use {@link rows} to stream a file.
24
+ */
25
+ export declare function parse<TColumns extends CsvColumns | undefined = undefined>(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParseOptions<TColumns>): Promise<CsvRow[]>;
26
+ /**
27
+ * Stream materialized rows from a filesystem path or byte stream.
24
28
  *
25
- * Each yielded value is one parser batch represented as ordinary string arrays. Options are
26
- * captured when this function is called, before iteration starts, so mutating the caller-owned
27
- * options object later does not change the stream. With `reuseArrays: true`, batches and their
29
+ * Batches contain string arrays by default. Set `headers: true` to read and consume the input header,
30
+ * or supply names in physical input order. Use them to address columns by name,
31
+ * and set `mapped: true` to emit fresh objects keyed by the selected header names. Options are
32
+ * captured when this function is called. With `reuseArrays: true`, batches and their array
28
33
  * rows are borrowed until the next iteration. Copy a row with `row.slice()` to retain it.
29
34
  *
30
- * @typeParam TColumns - Literal projected column indexes, when a projection is supplied.
31
- * @param path - Path to the CSV file.
32
- * @param options - File, projection, filter, and validation settings.
35
+ * @typeParam THeaders - Names supplied by the caller, or `true` to read them from input.
36
+ * @typeParam TColumns - Header names to emit in projection order.
37
+ * @typeParam TMapped - Whether to emit objects keyed by header name.
38
+ * @param path - A filesystem path or async iterable of byte chunks.
39
+ * @param options - Input, projection, filter, and validation settings.
33
40
  * @returns An async generator of row batches in file order.
34
- * @throws {Error} During iteration when the file cannot be read or the selected options are
35
- * incompatible, such as a filter combined with strict validation.
41
+ * @throws {Error} At invocation for invalid named options, or during iteration when reading or parsing fails.
36
42
  */
37
- export declare function rows<TColumns extends CsvColumns | undefined = undefined>(path: string, options?: CsvRowsOptions<TColumns>): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
38
- export declare function iterateRows<TColumns extends CsvColumns | undefined>(path: string, options: CsvRowsOptions<TColumns>, probeFormat?: CsvFileProbe): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
43
+ export declare function rows<const THeaders extends CsvHeaderSource, const TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[], const TMapped extends boolean | undefined = undefined>(path: CsvInput, options: CsvRequiredNamedRowsOptions<THeaders, TColumns, TMapped, 'columns' | 'mapped'>): AsyncGenerator<CsvNamedRowsBatch<THeaders, TColumns, TMapped>, void>;
44
+ /** Stream row batches with a required projection by header name. Array rows follow the requested column order. */
45
+ export declare function rows<const THeaders extends CsvHeaderSource, const TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[], const TMapped extends boolean | undefined = undefined>(path: CsvInput, options: CsvRequiredNamedRowsOptions<THeaders, TColumns, TMapped, 'columns'>): AsyncGenerator<CsvNamedRowsBatch<THeaders, TColumns, TMapped | undefined>, void>;
46
+ /** Stream row batches with an explicit choice of array or object output. Objects are keyed by the selected header names. */
47
+ export declare function rows<const THeaders extends CsvHeaderSource, const TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined = undefined, const TMapped extends boolean | undefined = undefined>(path: CsvInput, options: CsvRequiredNamedRowsOptions<THeaders, TColumns, TMapped, 'mapped'>): AsyncGenerator<CsvNamedRowsBatch<THeaders, TColumns | undefined, TMapped>, void>;
48
+ /** Stream row batches addressed by header name. Set `headers: true` to consume the input header, or supply names in input order. */
49
+ export declare function rows<const THeaders extends CsvHeaderSource, const TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined = undefined, const TMapped extends boolean | undefined = undefined>(path: CsvInput, options: CsvNamedRowsOptions<THeaders, TColumns, TMapped>): AsyncGenerator<CsvNamedRowsBatch<THeaders, TColumns | undefined, TMapped | undefined>, void>;
50
+ /** Stream batches of string tuples projected by zero-based input index, in the requested column order. */
51
+ export declare function rows<TColumns extends CsvColumns>(path: CsvInput, options: CsvProjectedRowsOptions<TColumns>): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
52
+ /** Stream batches of materialized string arrays from a file or byte stream, in input order. */
53
+ export declare function rows<TColumns extends CsvColumns | undefined = undefined>(path: CsvInput, options?: CsvRowsOptions<TColumns>): AsyncGenerator<CsvRow[], void>;
54
+ export declare function iterateRows(path: CsvInput, options: CsvRowsOptions<CsvColumns | undefined>, probeFormat?: CsvFileProbe): AsyncGenerator<CsvRow[], void>;
55
+ export declare function iterateRows(path: CsvInput, options: CsvRowsOptions<CsvColumns | undefined>, probeFormat: CsvFileProbe | undefined, layout: MappedRowLayout): AsyncGenerator<CsvMappedRow[], void>;
56
+ type BatchOptions = CsvBatchesOptions | CsvRawRecordBatchesOptions;
39
57
  /**
40
- * Stream native batches with explicit lifetime control.
58
+ * Stream disposable batches of original decompressed record bytes.
41
59
  *
42
- * Use this when you want low-allocation access to row views, byte ranges, and native-backed
43
- * column data. Every yielded batch owns native memory and must be closed after use; prefer
44
- * `for await (using batch of csv.batches(...))` to close each batch at the end of the iteration.
45
- * Options are captured at invocation time. Projection selects the stored fields in the requested
46
- * order. Accessors use output positions and filters use physical input indexes.
60
+ * Raw-record output uses the literal LF dialect. Filters address physical input indexes.
61
+ * Options are captured at invocation time.
62
+ * Use `for await (using batch of csv.batches(...))` to close each batch at the end of its iteration.
47
63
  *
48
- * @param path - Path to the CSV file.
49
- * @param options - File and parser options.
64
+ * @param path - A filesystem path or async iterable of byte chunks.
65
+ * @param options - Input and parser options.
50
66
  * @returns An async generator of disposable native batches.
51
- * @throws {Error} During iteration when the file or validation fails, or when strict validation
52
- * is combined with projection or filtering.
67
+ * @throws {Error} During iteration when reading, parsing, or validation fails.
53
68
  */
54
- export declare function batches(path: string, options?: CsvBatchesOptions): AsyncGenerator<NativeCsvBatch, void>;
69
+ export declare function batches(path: CsvInput, options: CsvRawRecordBatchesOptions): AsyncGenerator<NativeCsvRawRecordBatch, void>;
70
+ /** Stream disposable native field batches with row views, byte ranges, and column data. Close each batch after use. */
71
+ export declare function batches(path: CsvInput, options?: CsvBatchesOptions): AsyncGenerator<NativeCsvBatch, void>;
72
+ /** Stream disposable batches of parsed fields or original record bytes, depending on `output`. */
73
+ export declare function batches(path: CsvInput, options: BatchOptions): AsyncGenerator<NativeCsvBatch | NativeCsvRawRecordBatch, void>;
55
74
  /**
56
- * Count CSV records without materializing them.
75
+ * Count CSV records with optional predicates addressed by header name.
57
76
  *
58
77
  * Filters created with `csv.column()` and composed with `csv.all()`, `csv.any()`, or `csv.not()`
59
78
  * are evaluated by native fast paths. The input may be compressed or use automatic delimiter
60
- * detection.
79
+ * detection. With `headers: true`, the input header is consumed before counting data.
61
80
  *
62
- * @param path - Path to the CSV file.
63
- * @param suppliedOptions - File, filter, and validation settings.
81
+ * @param path - A filesystem path or async iterable of byte chunks.
82
+ * @param suppliedOptions - Input, filter, and validation settings.
64
83
  * @returns A promise containing the record count.
65
- * @throws {Error} If strict validation is combined with a filter or reading or parsing fails.
84
+ * @throws {Error} If reading, parsing, or validation fails.
66
85
  */
67
- export declare function count(path: string, suppliedOptions?: CsvCountOptions): Promise<number>;
86
+ export declare function count<const THeaders extends CsvHeaderSource>(path: CsvInput, suppliedOptions: CsvNamedCountOptions<THeaders>): Promise<number>;
87
+ /** Count CSV records without materializing rows. Filters address zero-based input columns. */
88
+ export declare function count(path: CsvInput, suppliedOptions?: CsvCountOptions): Promise<number>;
68
89
  /**
69
90
  * Find byte offsets that divide a CSV file only at record boundaries.
70
91
  *
71
92
  * The returned array contains shard start offsets followed by the terminal file boundary. Quoted
72
93
  * fields and embedded newlines are respected. The operation scans original UTF-8 or Latin-1
73
- * bytes in an uncompressed file with a fixed delimiter.
94
+ * bytes in an uncompressed file and detects the delimiter by default.
74
95
  *
75
96
  * @param path - Path to the uncompressed CSV file.
76
97
  * @param shardCount - Desired number of partitions; the result may contain fewer non-empty shards.
77
- * @param suppliedOptions - Explicit delimiter and file parser options. Compression is unavailable.
98
+ * @param suppliedOptions - File parser options, including an optional delimiter override.
78
99
  * @returns Monotonically increasing byte offsets, including `0` and the file-length boundary.
79
- * @throws {RangeError} If `shardCount` is not a positive integer.
80
- * @throws {Error} If the input is compressed, the encoding requires transcoding, or the delimiter is automatic or invalid.
100
+ * @throws {RangeError} If `shardCount` is not a positive safe integer.
101
+ * @throws {Error} If the scan fails, the encoding requires transcoding, or the delimiter cannot be resolved.
81
102
  */
82
103
  declare function findCsvSafeSplitOffsets(path: string, shardCount: number, suppliedOptions?: CsvShardingOptions): number[];
83
104
  /**
@@ -85,14 +106,14 @@ declare function findCsvSafeSplitOffsets(path: string, shardCount: number, suppl
85
106
  *
86
107
  * Shards use inclusive `start` and `end` offsets and never split quoted fields or embedded
87
108
  * newlines. A small file can produce fewer non-empty shards than requested. The operation
88
- * requires original UTF-8 or Latin-1 bytes in an uncompressed file with a fixed delimiter.
109
+ * requires original UTF-8 or Latin-1 bytes in an uncompressed file and detects the delimiter by default.
89
110
  *
90
111
  * @param path - Path to the uncompressed CSV file.
91
112
  * @param shardCount - Desired number of partitions; the result may contain fewer shards.
92
- * @param suppliedOptions - Explicit delimiter and file parser options. Compression is unavailable.
113
+ * @param suppliedOptions - File parser options, including an optional delimiter override.
93
114
  * @returns Non-empty, ordered byte ranges with inclusive endpoints.
94
- * @throws {RangeError} If `shardCount` is not a positive integer.
95
- * @throws {Error} If the input is compressed, the encoding requires transcoding, or the delimiter is automatic or invalid.
115
+ * @throws {RangeError} If `shardCount` is not a positive safe integer.
116
+ * @throws {Error} If the scan fails, the encoding requires transcoding, or the delimiter cannot be resolved.
96
117
  */
97
118
  declare function findCsvSafeShards(path: string, shardCount: number, suppliedOptions?: CsvShardingOptions): CsvShard[];
98
119
  /**
@@ -102,7 +123,7 @@ declare function findCsvSafeShards(path: string, shardCount: number, suppliedOpt
102
123
  * record-safe sharding helpers in one discoverable object.
103
124
  */
104
125
  export declare const csv: {
105
- /** Build a reusable field transform, then bind it to physical input columns with on(). */
126
+ /** Build a reusable field transform, then bind it to physical input columns with `on()`. */
106
127
  transform: typeof transform;
107
128
  /**
108
129
  * Combine one or more filters with logical AND semantics.
@@ -119,9 +140,9 @@ export declare const csv: {
119
140
  */
120
141
  any: typeof any;
121
142
  /**
122
- * Select a zero-based physical CSV column for building reusable filters.
143
+ * Select a zero-based physical CSV column for building filters and transforms.
123
144
  * @param columnIndex - Column index from 0 through 2024.
124
- * @returns An immutable column predicate builder.
145
+ * @returns An immutable column builder.
125
146
  */
126
147
  column: typeof column;
127
148
  /**
@@ -138,7 +159,7 @@ export declare const csv: {
138
159
  re: typeof re;
139
160
  /**
140
161
  * Parse one in-memory buffer into materialized rows.
141
- * Supply uncompressed bytes with a fixed delimiter.
162
+ * Supply uncompressed bytes. The delimiter is detected by default.
142
163
  * @param buffer - CSV bytes in a typed array or `DataView`.
143
164
  * @param suppliedOptions - In-memory parser and projection options.
144
165
  * @returns A promise containing materialized rows in input order.
@@ -153,7 +174,9 @@ export declare const csv: {
153
174
  /**
154
175
  * Stream materialized row batches from a CSV file.
155
176
  * Options are captured at invocation. Batches are yielded in file order.
156
- * @param path - Path to the CSV file.
177
+ * Set `headers: true` to read and consume the input header. Supply header names
178
+ * in physical order when the schema is already known. Use `mapped: true` for objects.
179
+ * @param path - A filesystem path or a single-pass source of CSV byte chunks.
157
180
  * @param options - File, projection, filter, and validation settings.
158
181
  * @returns An async generator of row batches.
159
182
  * @example
@@ -167,17 +190,21 @@ export declare const csv: {
167
190
  rows: typeof rows;
168
191
  /**
169
192
  * Stream disposable native-backed batches.
170
- * Columns select stored fields in output order. Filters address the input record.
193
+ * By default, columns select stored fields in output order. Use `output: 'raw-records'`
194
+ * to access original decompressed records in the literal LF dialect.
195
+ * Filters address the input record.
171
196
  * Close each yielded batch, or use `for await (using batch of ...)`.
172
- * @param path - Path to the CSV file.
197
+ * @param path - A filesystem path or a single-pass source of CSV byte chunks.
173
198
  * @param options - File and parser options.
174
- * @returns An async generator of `NativeCsvBatch` objects.
199
+ * @returns An async generator of disposable native batches.
175
200
  */
176
201
  batches: typeof batches;
177
202
  /**
178
203
  * Count CSV records without materializing them.
179
- * Counting supports compression and automatic encoding and delimiter detection. Filters require non-strict parsing.
180
- * @param path - Path to the CSV file.
204
+ * Counting supports compression and automatic encoding and delimiter detection.
205
+ * Use `headers` to build filters by column name. With `headers: true` the header is consumed before counting data.
206
+ * Strict validation checks physical records before applying filters.
207
+ * @param path - A filesystem path or a single-pass source of CSV byte chunks.
181
208
  * @param suppliedOptions - File, filter, and validation settings.
182
209
  * @returns A promise containing the record count.
183
210
  * @example
@@ -189,10 +216,10 @@ export declare const csv: {
189
216
  count: typeof count;
190
217
  /**
191
218
  * Find record-safe byte offsets, including the terminal file boundary.
192
- * Compressed input and automatic delimiter detection are unsupported.
219
+ * The delimiter is detected from a prefix of the uncompressed file by default.
193
220
  * @param path - Path to an uncompressed CSV file.
194
221
  * @param shardCount - Desired number of partitions.
195
- * @param suppliedOptions - Explicit delimiter and sharding options.
222
+ * @param suppliedOptions - Sharding options, including an optional delimiter override.
196
223
  * @returns Monotonically increasing byte offsets.
197
224
  */
198
225
  findCsvSafeSplitOffsets: typeof findCsvSafeSplitOffsets;
@@ -201,7 +228,7 @@ export declare const csv: {
201
228
  * Ranges use inclusive `start` and `end` offsets and may be fewer than requested.
202
229
  * @param path - Path to an uncompressed CSV file.
203
230
  * @param shardCount - Desired number of partitions.
204
- * @param suppliedOptions - Explicit delimiter and sharding options.
231
+ * @param suppliedOptions - Sharding options, including an optional delimiter override.
205
232
  * @returns Ordered, non-empty CSV byte ranges.
206
233
  */
207
234
  findCsvSafeShards: typeof findCsvSafeShards;