@konstit/csv 0.4.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.
- package/LICENSE +21 -0
- package/README.md +554 -0
- package/THIRD_PARTY_NOTICES.md +365 -0
- package/dist/api.d.ts +81 -0
- package/dist/api.js +515 -0
- package/dist/batches.d.ts +47 -0
- package/dist/batches.js +348 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +605 -0
- package/dist/file-stream.d.ts +11 -0
- package/dist/file-stream.js +290 -0
- package/dist/files.d.ts +8 -0
- package/dist/files.js +150 -0
- package/dist/filter.d.ts +8 -0
- package/dist/filter.js +82 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +19 -0
- package/dist/native.d.ts +199 -0
- package/dist/native.js +275 -0
- package/dist/normalize.d.ts +56 -0
- package/dist/normalize.js +365 -0
- package/dist/options.d.ts +17 -0
- package/dist/options.js +12 -0
- package/dist/parser.d.ts +32 -0
- package/dist/parser.js +254 -0
- package/dist/runtime.d.ts +5 -0
- package/dist/runtime.js +12 -0
- package/dist/strict-schema.d.ts +12 -0
- package/dist/strict-schema.js +90 -0
- package/dist/types.d.ts +181 -0
- package/dist/types.js +0 -0
- package/dist/worker-count.d.ts +2 -0
- package/dist/worker-count.js +96 -0
- package/dist/worker-factory.d.ts +3 -0
- package/dist/worker-factory.js +9 -0
- package/dist/worker-filter.d.ts +29 -0
- package/dist/worker-filter.js +46 -0
- package/dist/worker-module.d.ts +1 -0
- package/dist/worker-module.js +4 -0
- package/dist/worker-pool.d.ts +17 -0
- package/dist/worker-pool.js +290 -0
- package/dist/worker-rows.d.ts +8 -0
- package/dist/worker-rows.js +118 -0
- package/dist/workers/count.worker.d.ts +1 -0
- package/dist/workers/count.worker.js +49 -0
- package/dist/workers/rows.worker.d.ts +1 -0
- package/dist/workers/rows.worker.js +85 -0
- package/dist/zip-reader.d.ts +2 -0
- package/dist/zip-reader.js +89 -0
- package/package.json +122 -0
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +48 -0
- package/prebuilds/provenance/darwin-arm64.json +1 -0
- package/prebuilds/provenance/darwin-x64.json +1 -0
- package/prebuilds/provenance/linux-x64.json +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
# @konstit/csv
|
|
2
|
+
|
|
3
|
+
A high-performance CSV toolkit for Bun, powered by a native C++ parser. Stream large and compressed files, select
|
|
4
|
+
columns, apply composable filters, and process data in parallel without loading the complete dataset into memory.
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
|
|
8
|
+
- Stream CSV files or parse in-memory buffers without loading a complete file into memory.
|
|
9
|
+
- Read materialized rows, native batches, reusable row views, or columnar batch views.
|
|
10
|
+
- Select and reorder zero-based input columns before materialization.
|
|
11
|
+
- Filter inside the native parser with `equals`, `doesNotEqual`, `isOneOf`, `isNoneOf`, `startsWith`, and RE2 regular expressions.
|
|
12
|
+
- Compose nested native filters with `csv.all()`, `csv.any()`, and `csv.not()`.
|
|
13
|
+
- Process file shards in parallel with Bun workers or reuse workers through `csv.workerPool()`.
|
|
14
|
+
- Find CSV-safe split offsets without breaking quoted records or embedded newlines.
|
|
15
|
+
- Stream gzip, deflate, deflate-raw, Brotli, Zstandard, and ZIP input into serial APIs.
|
|
16
|
+
- Select an exact ZIP entry or use `entry: '*'` when the archive contains exactly one file.
|
|
17
|
+
- Detect comma, tab, semicolon, pipe, colon, caret, and tilde delimiters for serial file operations.
|
|
18
|
+
- Decode UTF-8 and Latin-1 input and emit UTF-8 strings.
|
|
19
|
+
- Validate strict quote syntax, fixed column counts, headers, and minimum data-row counts.
|
|
20
|
+
- Use typed option helpers, immutable filters, and explicit resource disposal from TypeScript.
|
|
21
|
+
- Run native C++20 parsing with AVX2 on x64 and NEON on ARM64.
|
|
22
|
+
|
|
23
|
+
## Setup
|
|
24
|
+
|
|
25
|
+
The repository and packaged release artifacts include native libraries for macOS 13+ ARM64/x64 and Linux x64. After
|
|
26
|
+
`bun install`, a fresh clone can run the Bun API, examples, and tests without compiling native code.
|
|
27
|
+
|
|
28
|
+
To rebuild the native libraries while developing C++ code:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
bun install
|
|
32
|
+
bun run build:native
|
|
33
|
+
bun run stage:native
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Native development requires CMake 3.25+, Ninja, Git, and Clang/AppleClang. CMake downloads pinned Highway and
|
|
37
|
+
unordered_dense sources during the first configure; native test configurations also download pinned Catch2 sources.
|
|
38
|
+
The downloaded sources are reused from `.cache/fetchcontent/`.
|
|
39
|
+
|
|
40
|
+
The native build writes architecture-specific outputs under `build/<platform>-<arch>/`. On macOS, `bun run build:native`
|
|
41
|
+
builds both `darwin-arm64` and `darwin-x64`. The FFI loader uses the tracked library under
|
|
42
|
+
`prebuilds/<platform>-<arch>/` by default. Set `CSV_NATIVE_LIBRARY_PATH` to an absolute library path to test a specific
|
|
43
|
+
local build. Target-specific and legacy build paths remain development fallbacks when no tracked prebuild exists.
|
|
44
|
+
|
|
45
|
+
On macOS, build and stage the Linux x64 prebuild with Docker Desktop:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
bun run prebuilds:linux
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The command caches an Ubuntu 24.04 image with Clang, CMake, and Ninja, mounts the repository at `/work`, builds the
|
|
52
|
+
existing `linux-x64-release` preset, and stages `prebuilds/linux-x64/libcsv_native.so`.
|
|
53
|
+
|
|
54
|
+
Tracked prebuilds are the native release inputs. Use the manual `Update prebuilds` workflow to rebuild and test all
|
|
55
|
+
targets. The workflow records the runner and toolchain, signs each binary with a GitHub build attestation, and creates one
|
|
56
|
+
`tracked-prebuilds-<commit>` artifact. Download that artifact, replace `prebuilds/`, and commit the result. Run this
|
|
57
|
+
workflow once before the first release that uses this policy because the existing binaries have no build attestations.
|
|
58
|
+
|
|
59
|
+
For a manual multi-host update without attestations, build and stage all targets, then record and verify the binaries and
|
|
60
|
+
native source inputs:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
bun scripts/verify-native-package.ts --update-manifest
|
|
64
|
+
bun run verify:native-package
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
This local route produces checksum metadata only. Release publication requires the attested workflow output.
|
|
68
|
+
|
|
69
|
+
Normal CI verifies and tests the tracked Linux prebuild without compiling native code. A separate `Native source`
|
|
70
|
+
workflow builds and tests Linux x64 only when native source or build files change. Package release jobs do not rebuild
|
|
71
|
+
native code. Release publication also verifies that each committed binary was signed by the `Update prebuilds` workflow
|
|
72
|
+
and that its attested source inputs match the release commit.
|
|
73
|
+
|
|
74
|
+
The supported native targets are Clang C++20 builds for macOS ARM64/x64 and Linux x64. ARM64 requires NEON, and x64
|
|
75
|
+
requires AVX2. CPUs without those instruction sets are not supported. Target-specific configuration is available through
|
|
76
|
+
CMake presets, for example:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
cmake --preset darwin-arm64-release
|
|
80
|
+
cmake --build --preset darwin-arm64-release
|
|
81
|
+
cmake --preset linux-x64-sanitize
|
|
82
|
+
cmake --build --preset linux-x64-sanitize
|
|
83
|
+
ctest --preset linux-x64-sanitize
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
If no matching library exists, imports fail with:
|
|
87
|
+
|
|
88
|
+
```txt
|
|
89
|
+
native library not found. Run: bun run build:native
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Package assembly is separate from publication. `bun run build:package` verifies the committed native libraries, uses
|
|
93
|
+
Bun's transpiler for runtime JavaScript, and uses TypeScript for declarations. It does not rebuild native code. The
|
|
94
|
+
JavaScript and declarations are written to `dist/`. The `Package` workflow packs the tracked prebuilds once, attests the
|
|
95
|
+
tarball, and smoke-tests that exact file on Linux x64 and macOS ARM64/x64. Run the workflow with a release tag to create a
|
|
96
|
+
draft release, attach the tested tarball, publish the immutable release, and publish the same tarball through the protected
|
|
97
|
+
`npm-publish` environment. Leave the release tag empty to build and test without publishing.
|
|
98
|
+
|
|
99
|
+
## Quick Start
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { csv } from '@konstit/csv';
|
|
103
|
+
|
|
104
|
+
const path = 'corpus/large/example.csv';
|
|
105
|
+
|
|
106
|
+
for await (
|
|
107
|
+
const rows of csv.rows(path, {
|
|
108
|
+
delimiter: ';',
|
|
109
|
+
columns: [0, 1, 2],
|
|
110
|
+
chunkSize: 8 * 1024 * 1024,
|
|
111
|
+
})
|
|
112
|
+
) {
|
|
113
|
+
for (const row of rows) {
|
|
114
|
+
console.log(row);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
In this repo, `corpus/large/example.csv` is semicolon-delimited. Pass `delimiter: ';'` for examples and benchmarks that read it.
|
|
120
|
+
|
|
121
|
+
### Large corpus files
|
|
122
|
+
|
|
123
|
+
The files in `corpus/large/` are too large to commit to this repository. Download and prepare them with Bun. The script
|
|
124
|
+
requires `unzip` and skips files that already exist:
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
bun scripts/download-large-corpus.ts
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- `example.csv` is an approximately 6 GB ISO-8859-1-encoded Brazilian government data dump after extraction. Download
|
|
131
|
+
it from [Arquivos Receita](https://arquivos.receitafederal.gov.br/public.php/dav/files/gn672Ad4CF8N6TK/Dados/Cadastros/CNPJ/2026-08/Estabelecimentos0.zip).
|
|
132
|
+
- `formatted_addresses_tagged.random.tsv.gz` is part of the libpostal training data and remains compressed for the
|
|
133
|
+
benchmarks. Download it from the
|
|
134
|
+
[Internet Archive](https://archive.org/download/libpostal-parser-training-data-20170304/formatted_addresses_tagged.random.tsv.gz).
|
|
135
|
+
|
|
136
|
+
For manual downloads, place both files in `corpus/large/` before running benchmarks or examples that use them.
|
|
137
|
+
|
|
138
|
+
## Library API
|
|
139
|
+
|
|
140
|
+
Import the `csv` namespace for file-oriented helpers:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { csv } from '@konstit/csv';
|
|
144
|
+
|
|
145
|
+
const rowCount = await csv.count('data.csv', { delimiter: ';' });
|
|
146
|
+
|
|
147
|
+
const selected = csv.rows('data.csv', {
|
|
148
|
+
delimiter: ';',
|
|
149
|
+
columns: [0, 2],
|
|
150
|
+
where: csv.all(
|
|
151
|
+
csv.column(2).isOneOf(['SP', 'RJ']),
|
|
152
|
+
csv.column(1).startsWith('A'),
|
|
153
|
+
csv.column(3).hasMatch(/^[0-9]{5}-[0-9]{3}$/),
|
|
154
|
+
),
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
const compressed = csv.rows('data.csv.gz', {
|
|
158
|
+
compression: 'auto',
|
|
159
|
+
delimiter: 'auto',
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const zipped = csv.rows('export.zip', {
|
|
163
|
+
compression: { format: 'zip', entry: 'data/export.csv' },
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Supported helpers:
|
|
168
|
+
|
|
169
|
+
- `csv.parse(buffer, options)` parses one buffer and returns rows.
|
|
170
|
+
- `csv.rows(path, options)` streams materialized row arrays.
|
|
171
|
+
- `csv.batches(path, options)` streams `NativeCsvBatch` objects.
|
|
172
|
+
- `csv.withBatches(path, options, callback)` owns batch close handling around a callback.
|
|
173
|
+
- `csv.count(path, options)` counts rows, optionally with native filters.
|
|
174
|
+
- `csv.withRowViews(path, options, callback)` streams reusable row views with managed lifetimes.
|
|
175
|
+
- `csv.withColumnarBatches(path, options, callback)` streams reusable columnar batch views.
|
|
176
|
+
- `csv.workerPool(path, options)` creates a reusable pool for repeated parallel operations.
|
|
177
|
+
- `csv.findCsvSafeSplitOffsets(path, count, options)` and `csv.findCsvSafeShards(path, count, options)` split files at record boundaries.
|
|
178
|
+
|
|
179
|
+
### Filters
|
|
180
|
+
|
|
181
|
+
Filters select a zero-based physical column first. Each condition method returns a complete, validated, immutable filter.
|
|
182
|
+
The selected column is reusable, and one filter can be reused across row, count, and worker APIs:
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
const state = csv.column(2);
|
|
186
|
+
const isSP = state.equals('SP');
|
|
187
|
+
const isSouthEast = state.isOneOf(['SP', 'RJ']);
|
|
188
|
+
|
|
189
|
+
await csv.count('data.csv', { where: isSP });
|
|
190
|
+
await csv.count('data.csv', { where: isSouthEast, workerCount: 4 });
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
The condition methods are `equals`, `doesNotEqual`, `isOneOf`, `isNoneOf`, `startsWith`, and `hasMatch`. Binary
|
|
194
|
+
`Buffer` and `Uint8Array` operands are copied during construction so later caller mutation cannot change a filter.
|
|
195
|
+
The `where` option accepts only filters created by this API; TypeScript object-literal predicates are not supported.
|
|
196
|
+
If a row does not contain the selected column, it does not match, including for `doesNotEqual` and `isNoneOf`.
|
|
197
|
+
Use `hasMatch()` for regular expressions:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
const selected = csv.rows('data.csv', {
|
|
201
|
+
where: csv.column(1).hasMatch(/^ana$/iu),
|
|
202
|
+
});
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Regex filters use statically linked RE2 and search the field. Use `^` and `$` for a full-field match. The supported flags
|
|
206
|
+
are `i`, `m`, `s`, and `u`. Unicode matching is enabled by default; `u` documents the JavaScript pattern intent. The
|
|
207
|
+
`g`, `d`, `y`, and `v` flags are rejected. RE2 does not support lookaround or backreferences. `hasMatch()` converts
|
|
208
|
+
JavaScript Unicode escapes and escaped `/` characters, then validates the RE2 expression immediately. A compiled
|
|
209
|
+
pattern is limited to 4096 UTF-8 bytes, and one operation can use at most 32 regex filters.
|
|
210
|
+
|
|
211
|
+
Use `csv.all()` when every child must match, `csv.any()` when at least one child must match, and `csv.not()` to negate
|
|
212
|
+
one child. Groups can be nested. `all` and `any` require at least one filter:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
const filter = csv.all(
|
|
216
|
+
csv.any(
|
|
217
|
+
csv.column(2).equals('SP'),
|
|
218
|
+
csv.column(2).equals('RJ'),
|
|
219
|
+
),
|
|
220
|
+
csv.not(csv.column(1).startsWith('B')),
|
|
221
|
+
);
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Boolean groups are evaluated by the native parser. A predicate for a missing column has an unknown result. `csv.not()`
|
|
225
|
+
keeps that result unknown, so a missing column does not become a match. `csv.any()` still matches when another child is
|
|
226
|
+
true.
|
|
227
|
+
|
|
228
|
+
Serial file operations accept `compression: 'auto' | 'gzip' | 'deflate' | 'deflate-raw' | 'brotli' | 'zstd'`.
|
|
229
|
+
Decompression streams into the parser and does not buffer the complete file. `auto` reads at most four prefix bytes and
|
|
230
|
+
combines signatures with `.gz`, `.gzip`, `.zst`, `.zstd`, `.br`, `.zz`, `.zlib`, `.deflate`, or `.deflate-raw`.
|
|
231
|
+
Signature and extension mismatches fail. A `.deflate` file without a zlib wrapper requires explicit `deflate-raw`.
|
|
232
|
+
Compressed input does not support worker pools, parallel operations, or CSV byte-offset sharding.
|
|
233
|
+
|
|
234
|
+
ZIP input uses `compression: { format: 'zip', entry: 'path/in/archive.csv' }`. The selected stored or DEFLATE entry
|
|
235
|
+
is decoded in bounded native chunks with zlib-ng AVX2 or NEON acceleration. Entry names must match exactly. Use
|
|
236
|
+
`entry: '*'` to select the file when the archive contains exactly one file; directory entries are ignored. Archives
|
|
237
|
+
with zero or multiple files fail in this mode. Encrypted entries and compression methods other than stored and
|
|
238
|
+
DEFLATE fail. The defaults limit output to 64 GiB and the declared compression ratio to 1000. Use
|
|
239
|
+
`maxDecompressedBytes` and `maxCompressionRatio` to set lower application limits or to permit a larger trusted entry.
|
|
240
|
+
|
|
241
|
+
Serial file operations also accept `delimiter: 'auto'`. Detection probes at most 64 KiB of decompressed data and
|
|
242
|
+
ignores separators inside quoted fields. It checks comma, tab, semicolon, pipe, colon, caret, and tilde. The `.csv`,
|
|
243
|
+
`.tsv`, `.tab`, and `.psv` extensions are confirmed hints, including before a compression extension such as `.gz`.
|
|
244
|
+
Empty, single-column, inconsistent, and ambiguous probes fail with an error. Omitted `delimiter` still means comma.
|
|
245
|
+
Automatic delimiter detection does not support in-memory parsing, workers, parallel operations, or byte-offset sharding.
|
|
246
|
+
|
|
247
|
+
`delimiter` suggests common CSV delimiters in TypeScript while accepting any string. Runtime parsing still requires
|
|
248
|
+
exactly one character unless a serial file operation uses `auto`.
|
|
249
|
+
|
|
250
|
+
## Strict Validation
|
|
251
|
+
|
|
252
|
+
`strict: true` validates RFC-style quote syntax for row materialization:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
await csv.parse(Buffer.from('id,name\n1,"Ada'), { strict: true });
|
|
256
|
+
// throws: native CSV parser failed: strict CSV quote syntax error: unterminated quoted field
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Strict mode also validates optional schema metadata during row parsing:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
await csv.parse(Buffer.from('id,name\n1,Ada\n'), {
|
|
263
|
+
strict: true,
|
|
264
|
+
expectedHeaders: ['id', 'name'],
|
|
265
|
+
minDataRows: 1,
|
|
266
|
+
});
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
- `expectedHeaders` validates the first row exactly.
|
|
270
|
+
- `requireHeader` rejects empty input when a header row is required.
|
|
271
|
+
- `minDataRows` validates row count after the header row.
|
|
272
|
+
|
|
273
|
+
Strict mode currently covers row batches, `count()` without filters, `fixedColumns`, and row schema metadata. Projected
|
|
274
|
+
batches and count filters reject `strict: true` explicitly until they have strict native variants.
|
|
275
|
+
|
|
276
|
+
## Typed Options
|
|
277
|
+
|
|
278
|
+
Use the option factories when you want literal-preserving inference without repeating `satisfies` everywhere:
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
import {
|
|
282
|
+
csv,
|
|
283
|
+
defineCountOptions,
|
|
284
|
+
defineRowsOptions,
|
|
285
|
+
} from '@konstit/csv';
|
|
286
|
+
|
|
287
|
+
const columns = [0, 2] as const;
|
|
288
|
+
|
|
289
|
+
const rowOptions = defineRowsOptions({
|
|
290
|
+
columns,
|
|
291
|
+
delimiter: ';',
|
|
292
|
+
where: csv.column(1).equals('SP'),
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
const countOptions = defineCountOptions({
|
|
296
|
+
strict: true,
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
for await (const rows of csv.rows('data.csv', rowOptions)) {
|
|
300
|
+
console.log(rows);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
console.log(await csv.count('data.csv', countOptions));
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
The public option types reject combinations unsupported by the native path, including strict validation with filters or
|
|
307
|
+
workers. `columns` and the legacy `selectedColumns` alias are mutually exclusive. Each operation accepts only the
|
|
308
|
+
options supported by its native path.
|
|
309
|
+
|
|
310
|
+
Column indexes are integers from `0` through `2024`. A projection may contain at most 2024 columns and must not repeat
|
|
311
|
+
an index. A filter can contain at most 2024 predicates and 4096 total predicates and Boolean operators. Invalid values
|
|
312
|
+
fail before parsing begins.
|
|
313
|
+
|
|
314
|
+
## Batch API
|
|
315
|
+
|
|
316
|
+
Use batches when you need low allocation row access or byte ranges.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import { csv } from '@konstit/csv';
|
|
320
|
+
|
|
321
|
+
await csv.withBatches(
|
|
322
|
+
'data.csv',
|
|
323
|
+
{ delimiter: ';' },
|
|
324
|
+
(batch) => {
|
|
325
|
+
batch.forEachRow((row) => {
|
|
326
|
+
console.log({
|
|
327
|
+
rowIndex: row.rowIndex,
|
|
328
|
+
first: row.getPhysical(0),
|
|
329
|
+
bytes: row.bytes(0),
|
|
330
|
+
range: row.range(0),
|
|
331
|
+
selected: row.pickPhysical([0, 2]),
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
},
|
|
335
|
+
);
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
`row.get()`, `row.getPhysical()`, `row.pick()`, and `row.pickPhysical()` all read physical CSV column indexes.
|
|
339
|
+
If you requested projected columns elsewhere in the API, `row.selectedColumns` is metadata that lets you map projected
|
|
340
|
+
positions back to source columns.
|
|
341
|
+
|
|
342
|
+
If you use `csv.batches()` directly, declare each batch with `using` so it is disposed after its iteration:
|
|
343
|
+
|
|
344
|
+
```ts
|
|
345
|
+
for await (using batch of csv.batches('data.csv', { delimiter: ';' })) {
|
|
346
|
+
console.log(batch.rowCount);
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
`NativeCsvBatch` exposes:
|
|
351
|
+
|
|
352
|
+
- `rowCount`, `totalFields`
|
|
353
|
+
- `rows()`
|
|
354
|
+
- `rowsInto(target, columns?)`
|
|
355
|
+
- `forEachRow(callback)`
|
|
356
|
+
- `data()`, `dataView()`
|
|
357
|
+
- `rowOffsets()`, `fieldOffsets()`
|
|
358
|
+
- `rowFieldCount(rowIndex)`
|
|
359
|
+
- `fieldRange(rowIndex, columnIndex)`
|
|
360
|
+
- `fieldBytes(rowIndex, columnIndex)`
|
|
361
|
+
- `fieldBuffer(rowIndex, columnIndex)`
|
|
362
|
+
- `fieldString(rowIndex, columnIndex)`
|
|
363
|
+
- `countWhereEquals(columnIndex, value)`
|
|
364
|
+
- `close()`
|
|
365
|
+
|
|
366
|
+
`rowOffsets()` and `fieldOffsets()` return `BigUint64Array`. Convert individual offsets to `number` only after checking
|
|
367
|
+
that they are within `Number.MAX_SAFE_INTEGER` and the associated backing data. `scanColumns()` supplies its
|
|
368
|
+
JavaScript-safe numeric ranges in a `Float64Array`.
|
|
369
|
+
|
|
370
|
+
## Manual Parser API
|
|
371
|
+
|
|
372
|
+
Use `NativeCsvParser` when you already own chunking:
|
|
373
|
+
|
|
374
|
+
```ts
|
|
375
|
+
import { NativeCsvParser } from '@konstit/csv';
|
|
376
|
+
|
|
377
|
+
using parser = new NativeCsvParser({ delimiter: ';' });
|
|
378
|
+
const rowsBuffer: string[][] = [];
|
|
379
|
+
|
|
380
|
+
using batch = parser.writeBatch(Buffer.from('1;Ana\n2;Bia\n'), true);
|
|
381
|
+
console.log(batch.rowsInto(rowsBuffer));
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Always dispose parser-owned batches and the parser. `NativeCsvParser` supports row batches, projected batches, and direct
|
|
385
|
+
count filters.
|
|
386
|
+
|
|
387
|
+
Resource objects expose `close()`, `dispose()`, `closed`, and `Symbol.dispose`, so explicit-resource-management syntax works
|
|
388
|
+
in Bun:
|
|
389
|
+
|
|
390
|
+
```ts
|
|
391
|
+
using parser = new NativeCsvParser({ delimiter: ';' });
|
|
392
|
+
using batch = parser.writeBatch(Buffer.from('1;Ana\n'), true);
|
|
393
|
+
console.log(batch.rows());
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
## CLI
|
|
397
|
+
|
|
398
|
+
Count every CSV record in a file, including the header row:
|
|
399
|
+
|
|
400
|
+
```sh
|
|
401
|
+
bunx @konstit/csv count data.csv
|
|
402
|
+
bunx @konstit/csv count data.csv --delimiter ';' --chunk-size 262144
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
With Bun 1.4 or newer, install the command globally and use its shorter form:
|
|
406
|
+
|
|
407
|
+
```sh
|
|
408
|
+
bun add --global @konstit/csv
|
|
409
|
+
csv count data.csv
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Stream parsed records as normalized UTF-8 CSV:
|
|
413
|
+
|
|
414
|
+
```sh
|
|
415
|
+
csv lines data.csv
|
|
416
|
+
csv lines data.csv --limit 10
|
|
417
|
+
csv lines data.csv --json --limit 10
|
|
418
|
+
csv lines data.csv --columns 0,2 --where-eq 3=active --limit 10
|
|
419
|
+
csv lines input.tsv --delimiter $'\t' --output-delimiter ',' > selected.csv
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
`--limit N` stops after matching output record `N`, numbered from 1. A quoted field can contain embedded newlines, but
|
|
423
|
+
its enclosing record counts as one. The header counts only when it is emitted. Early stop validates only the consumed
|
|
424
|
+
input prefix, so `--limit` cannot be combined with `--min-data-rows`. With `--strict`, a limit requires a fixed input
|
|
425
|
+
delimiter and either an omitted chunk size or `--chunk-size 1`; the CLI uses one-byte chunks to avoid strict read-ahead.
|
|
426
|
+
`--strict` with `--limit` cannot use `--compression`, including `auto`.
|
|
427
|
+
|
|
428
|
+
`lines` writes normalized UTF-8 CSV, not the original source bytes. The default output uses commas, LF record endings,
|
|
429
|
+
and standard quote escaping. Use `--output-delimiter` to select another safe ASCII delimiter. `--columns` selects the
|
|
430
|
+
output fields and their order. Filters still use the original input column indexes.
|
|
431
|
+
|
|
432
|
+
Use `--json` for newline-delimited JSON. Each output line is one array of strings, including the header when it is
|
|
433
|
+
emitted. JSON output escapes embedded field newlines and quotes. Stdout contains only JSON records. Diagnostics remain
|
|
434
|
+
on stderr. `--json` cannot be combined with `--output-delimiter`.
|
|
435
|
+
|
|
436
|
+
The CLI uses one process and exposes the serial file, parser, projection, and filter fields as flags. It does not expose
|
|
437
|
+
`workerCount`. Run `csv count --help` or `csv lines --help` for the complete list. Friendly filter flags use
|
|
438
|
+
`column=value`. Repeat `--where-in` or `--where-noin` for each value. Different filter clauses combine with AND. CLI
|
|
439
|
+
filter values are strings; use the TypeScript API for `workerCount` and binary `Buffer` or `Uint8Array` values.
|
|
440
|
+
|
|
441
|
+
```sh
|
|
442
|
+
csv count data.csv --delimiter ';' --where-eq 2=SP
|
|
443
|
+
csv count data.csv --where-neq 2=SP
|
|
444
|
+
csv count data.csv --where-in 2=SP --where-in 2=RJ --where-prefix 1=A
|
|
445
|
+
csv count data.csv --where-noin 2=SP --where-noin 2=RJ
|
|
446
|
+
csv count data.csv --where-regex '1=/^A/i'
|
|
447
|
+
csv lines data.csv --where-in 2=SP --where-in 2=RJ --limit 25
|
|
448
|
+
csv lines data.csv --columns 0,1 --json --limit 25
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
The large corpus file in this repository is semicolon-delimited:
|
|
452
|
+
|
|
453
|
+
```sh
|
|
454
|
+
csv lines corpus/large/example.csv --delimiter ';' --limit 10
|
|
455
|
+
csv lines corpus/large/example.csv --delimiter ';' --columns 0,1,2 --limit 100 > sample.csv
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
For generated or advanced CLI filters, `--where <json>` accepts a CLI-only serializable filter shape. This JSON shape
|
|
459
|
+
is separate from the TypeScript filter API:
|
|
460
|
+
|
|
461
|
+
```sh
|
|
462
|
+
csv count data.csv --where '{"all":[{"any":[{"column":2,"equals":"SP"},{"column":2,"equals":"RJ"}]},{"not":{"column":1,"startsWith":"B"}}]}'
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
CLI JSON filters can nest `all`, `any`, and `not`. Friendly filter flags still combine with AND.
|
|
466
|
+
|
|
467
|
+
## Examples
|
|
468
|
+
|
|
469
|
+
```sh
|
|
470
|
+
bun run example:first-rows
|
|
471
|
+
bun run example:api:rows
|
|
472
|
+
bun run example:api:count
|
|
473
|
+
bun run example:api:batches
|
|
474
|
+
bun run example:api:typed-options
|
|
475
|
+
bun run example:api:strict-options
|
|
476
|
+
bun run example:api:worker-count
|
|
477
|
+
bun run example:api:worker-rows
|
|
478
|
+
bun run example:api:worker-pool
|
|
479
|
+
bun run example:api:shards
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
Example environment variables:
|
|
483
|
+
|
|
484
|
+
- `CSV_EXAMPLE_FILE`: Input file for examples. It defaults to `CSV_BENCH_FILE`, then
|
|
485
|
+
`corpus/large/example.csv`.
|
|
486
|
+
- `CSV_BENCH_FILE`: Input file for benchmarks. It also provides the example input when `CSV_EXAMPLE_FILE` is not set.
|
|
487
|
+
- `CSV_EXAMPLE_DELIMITER`: Field delimiter for examples. It defaults to `CSV_BENCH_DELIMITER`, then `;`.
|
|
488
|
+
- `CSV_BENCH_DELIMITER`: Field delimiter for benchmarks. It also provides the example delimiter when
|
|
489
|
+
`CSV_EXAMPLE_DELIMITER` is not set.
|
|
490
|
+
- `CSV_EXAMPLE_CHUNK_SIZE`: Number of bytes read per chunk by examples. It defaults to `CSV_BENCH_CHUNK_SIZE`, then
|
|
491
|
+
8 MiB.
|
|
492
|
+
- `CSV_BENCH_CHUNK_SIZE`: Number of bytes read per chunk by benchmarks. It also provides the example chunk size when
|
|
493
|
+
`CSV_EXAMPLE_CHUNK_SIZE` is not set.
|
|
494
|
+
- `CSV_EXAMPLE_COLUMNS`: Comma-separated, zero-based column indexes selected by examples. The default is `0,1,2`.
|
|
495
|
+
- `CSV_EXAMPLE_LIMIT`: Maximum number of rows printed by examples. It defaults to `CSV_PRINT_ROWS`, then `10`. This
|
|
496
|
+
limits output, but some examples can still parse more rows.
|
|
497
|
+
- `CSV_PRINT_ROWS`: Fallback output limit used when `CSV_EXAMPLE_LIMIT` is not set.
|
|
498
|
+
- `CSV_EXAMPLE_FILTER_COLUMN`: Zero-based column index used by examples with a filter. It defaults to the first selected
|
|
499
|
+
column, usually `0`.
|
|
500
|
+
- `CSV_EXAMPLE_FILTER_VALUE`: Match value used by examples with a filter. If it is not set, those examples do not apply
|
|
501
|
+
the optional filter.
|
|
502
|
+
|
|
503
|
+
## Validation
|
|
504
|
+
|
|
505
|
+
```sh
|
|
506
|
+
bun run test
|
|
507
|
+
bun run lint
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
Install the repository's pre-push hook once per clone:
|
|
511
|
+
|
|
512
|
+
```sh
|
|
513
|
+
bun run hooks:install
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
Before every push, the hook builds the host's native libraries and the Linux x64 library, checks TypeScript and C++
|
|
517
|
+
formatting, runs the linters and type checker, runs the Bun test suite against the new host build, and runs the native
|
|
518
|
+
test suite. Building Linux x64 requires Docker to be installed and running. Run the same checks manually with
|
|
519
|
+
`bun run prepush`. The hook only validates the push. It does not publish packages.
|
|
520
|
+
|
|
521
|
+
### Full-file filtered materialization benchmark
|
|
522
|
+
|
|
523
|
+
This benchmark compares `csv.rows()` with `csv-parser` after `iconv-lite` decodes ISO-8859-1 input. Both commands parse
|
|
524
|
+
the complete `corpus/large/example.csv` file, apply equivalent column filters, and materialize every field in each
|
|
525
|
+
matching row. `@konstit/csv` applies the filters in native code; the `csv-parser` pipeline applies them to its
|
|
526
|
+
materialized JavaScript rows.
|
|
527
|
+
|
|
528
|
+
```sh
|
|
529
|
+
bun run bench:csv-parser:example
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
In the recorded `hyperfine -r 2` result, both commands produced 11,516,955 rows, 345,508,650 cells, and 1,808,786,228
|
|
533
|
+
characters from the 6,780,467,695-byte corpus:
|
|
534
|
+
|
|
535
|
+
| Implementation | Mean time | Throughput | Relative result |
|
|
536
|
+
| -------------------------------- | --------: | ----------: | ---------------: |
|
|
537
|
+
| `@konstit/csv` with `csv.rows()` | 45.223 s | 143.0 MiB/s | **2.32× faster** |
|
|
538
|
+
| `iconv-lite` + `csv-parser` | 104.835 s | 61.7 MiB/s | Baseline |
|
|
539
|
+
|
|
540
|
+
For this workload, `@konstit/csv` was 2.32× faster and completed in 56.9% less time. This result contains only two runs
|
|
541
|
+
on one machine, so use it as a measured workload result, not a universal performance guarantee. Full-file benchmarks
|
|
542
|
+
are long CPU-bound runs. Run them separately when comparing numbers. `hyperfine` must be available on `PATH`.
|
|
543
|
+
|
|
544
|
+
Small correctness/performance smoke:
|
|
545
|
+
|
|
546
|
+
```sh
|
|
547
|
+
bun run bench:regression-smoke
|
|
548
|
+
bun run bench:csv-parser:guard
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
## License
|
|
552
|
+
|
|
553
|
+
MIT © 2026 KONSTIT ENGENHARIA E TECNOLOGIA LTDA. See [`LICENSE`](./LICENSE) and
|
|
554
|
+
[`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
|