@konstit/csv 0.5.0 → 0.6.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 (44) hide show
  1. package/README.md +36 -3
  2. package/THIRD_PARTY_NOTICES.md +99 -0
  3. package/dist/api.d.ts +3 -0
  4. package/dist/api.js +34 -108
  5. package/dist/batches.d.ts +3 -4
  6. package/dist/batches.js +103 -29
  7. package/dist/cli-command.js +145 -75
  8. package/dist/cli-schema.d.ts +25 -5
  9. package/dist/cli-schema.js +48 -23
  10. package/dist/file-stream.d.ts +10 -3
  11. package/dist/file-stream.js +22 -17
  12. package/dist/files.js +32 -76
  13. package/dist/filter.d.ts +2 -3
  14. package/dist/filter.js +2 -0
  15. package/dist/index.d.ts +1 -1
  16. package/dist/inspect-file.d.ts +16 -6
  17. package/dist/inspect-file.js +67 -17
  18. package/dist/latin1-rows.d.ts +3 -3
  19. package/dist/latin1-rows.js +65 -15
  20. package/dist/materialize-field.d.ts +1 -0
  21. package/dist/materialize-field.js +10 -1
  22. package/dist/native.d.ts +47 -71
  23. package/dist/native.js +28 -86
  24. package/dist/normalize.d.ts +1 -40
  25. package/dist/normalize.js +25 -62
  26. package/dist/options-snapshot.d.ts +2 -2
  27. package/dist/options-snapshot.js +2 -0
  28. package/dist/parser.d.ts +17 -202
  29. package/dist/parser.js +152 -230
  30. package/dist/strict-schema.d.ts +1 -1
  31. package/dist/strict-schema.js +4 -3
  32. package/dist/transforms.d.ts +11 -0
  33. package/dist/transforms.js +192 -0
  34. package/dist/types.d.ts +77 -9
  35. package/dist/zip-reader.d.ts +2 -0
  36. package/dist/zip-reader.js +31 -21
  37. package/package.json +3 -2
  38. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  39. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  40. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  41. package/prebuilds/manifest.json +14 -8
  42. package/prebuilds/provenance/darwin-arm64.json +1 -1
  43. package/prebuilds/provenance/darwin-x64.json +1 -1
  44. package/prebuilds/provenance/linux-x64.json +1 -1
package/README.md CHANGED
@@ -87,6 +87,9 @@ for await (const batch of csv.rows('data.csv')) {
87
87
  Each iteration yields a **batch of rows** in file order, so use the inner loop to process individual records. Process
88
88
  batches as they arrive to avoid collecting the complete file in memory. The header is returned as the first row.
89
89
 
90
+ Pass `{ skipRows: 1, limit: 10 }` to skip the header and emit up to ten rows. With a filter, `skipRows` counts
91
+ input records and `limit` counts matches across all batches.
92
+
90
93
  To count records without materializing rows:
91
94
 
92
95
  ```ts
@@ -140,6 +143,33 @@ The filter also applies to the header, which does not match `'SP'` here. Combine
140
143
  See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
141
144
  and supported regex syntax.
142
145
 
146
+ ### Transform accepted rows
147
+
148
+ To print each person's name and state from `data.csv`, expand the state abbreviation in column 2. If you also supply `where`, it checks the original fields before the transforms run.
149
+
150
+ ```ts
151
+ import { csv } from '@konstit/csv';
152
+
153
+ const stateName = csv.column(2).map({ SP: 'São Paulo', RJ: 'Rio de Janeiro' });
154
+ for await (
155
+ const batch of csv.rows('data.csv', {
156
+ skipRows: 1,
157
+ columns: [1, 2],
158
+ transform: [stateName],
159
+ })
160
+ ) {
161
+ for (const [name, state,] of batch) {
162
+ console.log(`${name}, ${state}`);
163
+ }
164
+ }
165
+ // Ada, São Paulo
166
+ // Grace, Rio de Janeiro
167
+ ```
168
+
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.
170
+
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.
172
+
143
173
  ### Read compressed files
144
174
 
145
175
  Create a gzip copy of the sample file:
@@ -199,16 +229,19 @@ Inspect a file, count its records, or emit the first records as newline-delimite
199
229
 
200
230
  ```sh
201
231
  bunx @konstit/csv probe data.csv
232
+ bunx @konstit/csv probe tables.zip --zip-entry parts.tsv --json
202
233
 
203
234
  bunx @konstit/csv count data.csv
204
235
  # 3
205
236
 
206
- bunx @konstit/csv lines data.csv --json --limit 2
207
- # ["id","name","state"]
237
+ bunx @konstit/csv lines data.csv --json --skip-rows 1 --limit 2
208
238
  # ["1","Ada","SP"]
239
+ # ["2","Grace","RJ"]
209
240
  ```
210
241
 
211
- The CLI detects input encoding and delimiter by default. Without `--json`, `lines` writes normalized UTF-8 CSV.
242
+ 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.
212
245
  `count` and `lines` support column filters; `lines` also supports
213
246
  column selection. Use `bunx @konstit/csv lines --help` or read the
214
247
  [CLI guide](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/cli.md) for flags and output behavior.
@@ -2,6 +2,105 @@
2
2
 
3
3
  This file tracks third-party code incorporated into distributed native binaries and third-party test data, examples, and compatibility references used by this repository.
4
4
 
5
+ ## uni-algo and the Unicode Character Database
6
+
7
+ The native library uses [uni-algo v1.2.0](https://github.com/uni-algo/uni-algo/tree/v1.2.0) under its public domain license and incorporates its Unicode 15.1 data for normalization, casing and whitespace.
8
+ The Diacritic property table is derived from [Unicode 17.0 PropList.txt](https://www.unicode.org/Public/17.0.0/ucd/PropList.txt).
9
+
10
+ ### Unicode 15.1 data license
11
+
12
+ This software contains data derived from processing the Unicode data files.
13
+ The following license applies to the data files: https://www.unicode.org/license.txt
14
+
15
+ UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
16
+
17
+ See Terms of Use <https://www.unicode.org/copyright.html>
18
+ for definitions of Unicode Inc.'s Data Files and Software.
19
+
20
+ NOTICE TO USER: Carefully read the following legal agreement.
21
+ BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
22
+ DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
23
+ YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
24
+ TERMS AND CONDITIONS OF THIS AGREEMENT.
25
+ IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
26
+ THE DATA FILES OR SOFTWARE.
27
+
28
+ COPYRIGHT AND PERMISSION NOTICE
29
+
30
+ Copyright (c) 1991-2023 Unicode, Inc. All rights reserved.
31
+ Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining
34
+ a copy of the Unicode data files and any associated documentation
35
+ (the "Data Files") or Unicode software and any associated documentation
36
+ (the "Software") to deal in the Data Files or Software
37
+ without restriction, including without limitation the rights to use,
38
+ copy, modify, merge, publish, distribute, and/or sell copies of
39
+ the Data Files or Software, and to permit persons to whom the Data Files
40
+ or Software are furnished to do so, provided that either
41
+ (a) this copyright and permission notice appear with all copies
42
+ of the Data Files or Software, or
43
+ (b) this copyright and permission notice appear in associated
44
+ Documentation.
45
+
46
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
47
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
48
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
49
+ NONINFRINGEMENT OF THIRD PARTY RIGHTS.
50
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
51
+ NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
52
+ DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
53
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
54
+ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
55
+ PERFORMANCE OF THE DATA FILES OR SOFTWARE.
56
+
57
+ Except as contained in this notice, the name of a copyright holder
58
+ shall not be used in advertising or otherwise to promote the sale,
59
+ use or other dealings in these Data Files or Software without prior
60
+ written authorization of the copyright holder.
61
+
62
+ ### Unicode 17.0 Diacritic data
63
+
64
+ UNICODE LICENSE V3
65
+
66
+ COPYRIGHT AND PERMISSION NOTICE
67
+
68
+ Copyright © 1991-2026 Unicode, Inc.
69
+
70
+ NOTICE TO USER: Carefully read the following legal agreement. BY
71
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
72
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
73
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
74
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
75
+
76
+ Permission is hereby granted, free of charge, to any person obtaining a
77
+ copy of data files and any associated documentation (the "Data Files") or
78
+ software and any associated documentation (the "Software") to deal in the
79
+ Data Files or Software without restriction, including without limitation
80
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
81
+ copies of the Data Files or Software, and to permit persons to whom the
82
+ Data Files or Software are furnished to do so, provided that either (a)
83
+ this copyright and permission notice appear with all copies of the Data
84
+ Files or Software, or (b) this copyright and permission notice appear in
85
+ associated Documentation.
86
+
87
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
88
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
89
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
90
+ THIRD PARTY RIGHTS.
91
+
92
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
93
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
94
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
95
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
96
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
97
+ FILES OR SOFTWARE.
98
+
99
+ Except as contained in this notice, the name of a copyright holder shall
100
+ not be used in advertising or otherwise to promote the sale, use or other
101
+ dealings in these Data Files or Software without prior written
102
+ authorization of the copyright holder.
103
+
5
104
  ## RE2
6
105
 
7
106
  - Source: https://github.com/google/re2
package/dist/api.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { NativeCsvBatch } from './batches.js';
2
2
  import type { CsvFileProbe } from './file-stream.js';
3
3
  import { all, any, column, not, re } from './filter.js';
4
+ import { transform } from './transforms.js';
4
5
  import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
5
6
  /**
6
7
  * Parse one in-memory CSV buffer into materialized rows.
@@ -101,6 +102,8 @@ declare function findCsvSafeShards(path: string, shardCount: number, suppliedOpt
101
102
  * record-safe sharding helpers in one discoverable object.
102
103
  */
103
104
  export declare const csv: {
105
+ /** Build a reusable field transform, then bind it to physical input columns with on(). */
106
+ transform: typeof transform;
104
107
  /**
105
108
  * Combine one or more filters with logical AND semantics.
106
109
  * @param first - First filter in the group.
package/dist/api.js CHANGED
@@ -15,7 +15,10 @@ import {
15
15
  not,
16
16
  re
17
17
  } from "./filter.js";
18
- import { latin1Rows } from "./latin1-rows.js";
18
+ import {
19
+ canUseFilteredLatin1Cleanup,
20
+ latin1Rows
21
+ } from "./latin1-rows.js";
19
22
  import { latin1RowsParser } from "./native.js";
20
23
  import {
21
24
  normalizeFixedColumnsCount,
@@ -23,11 +26,14 @@ import {
23
26
  resolveInputEncoding
24
27
  } from "./normalize.js";
25
28
  import { snapshotCsvOptions } from "./options-snapshot.js";
26
- import { createPreparedParser } from "./parser.js";
27
29
  import {
28
- rejectStrictSchemaUnsupported,
29
- strictSchemaValidator
30
- } from "./strict-schema.js";
30
+ countFileChunks,
31
+ createPreparedParser,
32
+ parseFileChunks,
33
+ validateRowSelection
34
+ } from "./parser.js";
35
+ import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
36
+ import { transform } from "./transforms.js";
31
37
  export async function parse(buffer, suppliedOptions = {}) {
32
38
  const options = snapshotCsvOptions(suppliedOptions);
33
39
  if ("compression" in options && options.compression !== void 0)
@@ -39,16 +45,8 @@ export async function parse(buffer, suppliedOptions = {}) {
39
45
  const columns = options.columns;
40
46
  const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
41
47
  const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
42
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters);
43
- const validator = strictSchemaValidator(options);
44
- const batch = parser.writeBatch(input.bytes, !0);
45
- try {
46
- validator?.validateBatch(batch);
47
- validator?.finish();
48
- return materializeRows(batch, columns, projected);
49
- } finally {
50
- batch.close();
51
- }
48
+ using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters, options.transform);
49
+ return consumeBatchRows(parser.writeBatch(input.bytes, !0), columns, projected);
52
50
  }
53
51
  export function rows(path, options = {}) {
54
52
  return iterateRows(path, snapshotCsvOptions(options));
@@ -59,45 +57,19 @@ export async function* iterateRows(path, options, probeFormat) {
59
57
  const columns = options.columns;
60
58
  const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
61
59
  await using input = await prepareCsvFileInput(path, options, "read-ahead", probeFormat);
62
- const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
63
- const validator = strictSchemaValidator(options);
64
60
  const reusableRows = options.reuseArrays === !0 ? [] : void 0;
65
- if (options.strict !== !0 && validator === void 0 && input.parserEncoding === "latin1") {
61
+ if (options.strict !== !0 && input.parserEncoding === "latin1" && (!options.transform?.length || canUseFilteredLatin1Cleanup(columns, filters, options.transform))) {
62
+ validateRowSelection(options);
66
63
  const fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
67
- const createParser = latin1RowsParser(fixedColumns);
68
- yield* latin1Rows(input.chunks(), input.delimiter, columns, filters, createParser, reusableRows);
64
+ const createParser = latin1RowsParser(fixedColumns, Boolean(options.transform?.length));
65
+ const chunks = options.limit === 0 ? [] : input.chunks();
66
+ yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows, options);
69
67
  return;
70
68
  }
71
- using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters);
72
- for await (const chunk of input.chunks()) {
73
- const batch = parser.writeBatch(chunk);
74
- if (batch.rowCount > 0)
75
- try {
76
- validator?.validateBatch(batch);
77
- const values = materializeRows(batch, columns, projected, reusableRows);
78
- if (values.length > 0)
79
- yield values;
80
- } finally {
81
- batch.close();
82
- }
83
- else
84
- batch.close();
85
- }
86
- const batch = parser.endBatch();
87
- if (batch.rowCount > 0)
88
- try {
89
- validator?.validateBatch(batch);
90
- validator?.finish();
91
- const values = materializeRows(batch, columns, projected, reusableRows);
92
- if (values.length > 0)
93
- yield values;
94
- } finally {
95
- batch.close();
96
- }
97
- else {
98
- validator?.finish();
99
- batch.close();
100
- }
69
+ const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
70
+ using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, options.transform, "rows");
71
+ for await (const batch of parseFileChunks(input, parser, options.limit))
72
+ yield consumeBatchRows(batch, columns, projected, reusableRows);
101
73
  }
102
74
  export function batches(path, options = {}) {
103
75
  return iterateBatches(path, snapshotCsvOptions(options));
@@ -109,35 +81,8 @@ async function* iterateBatches(path, options) {
109
81
  if (options.strict === !0 && columns !== void 0)
110
82
  throw Error("strict CSV validation is not supported for projected batches; use csv.rows() for strict projection");
111
83
  await using input = await prepareCsvFileInput(path, options);
112
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters);
113
- const validator = strictSchemaValidator(options);
114
- for await (const chunk of input.chunks()) {
115
- const batch = parser.writeBatch(chunk);
116
- if (batch.rowCount > 0) {
117
- try {
118
- validator?.validateBatch(batch);
119
- } catch (error) {
120
- batch.close();
121
- throw error;
122
- }
123
- yield batch;
124
- } else
125
- batch.close();
126
- }
127
- const batch = parser.endBatch();
128
- if (batch.rowCount > 0) {
129
- try {
130
- validator?.validateBatch(batch);
131
- validator?.finish();
132
- } catch (error) {
133
- batch.close();
134
- throw error;
135
- }
136
- yield batch;
137
- } else {
138
- batch.close();
139
- validator?.finish();
140
- }
84
+ using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters, options.transform);
85
+ yield* parseFileChunks(input, parser, options.limit);
141
86
  }
142
87
  export async function count(path, suppliedOptions = {}) {
143
88
  const options = snapshotCsvOptions(suppliedOptions);
@@ -145,33 +90,7 @@ export async function count(path, suppliedOptions = {}) {
145
90
  await using input = await prepareCsvFileInput(path, options, "count");
146
91
  if (options.strict === !0 && filters !== void 0)
147
92
  throw Error("strict CSV validation is not supported for count filters");
148
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), void 0, filters);
149
- const validator = strictSchemaValidator(options);
150
- let total = 0;
151
- if (options.strict === !0 && filters === void 0) {
152
- for await (const chunk of input.chunks()) {
153
- const batch = parser.writeBatch(chunk);
154
- try {
155
- validator?.validateBatch(batch);
156
- total += batch.rowCount;
157
- } finally {
158
- batch.close();
159
- }
160
- }
161
- const batch = parser.endBatch();
162
- try {
163
- validator?.validateBatch(batch);
164
- validator?.finish();
165
- total += batch.rowCount;
166
- } finally {
167
- batch.close();
168
- }
169
- return total;
170
- }
171
- for await (const chunk of input.chunks())
172
- total += parser.writeCount(chunk);
173
- total += parser.endCount();
174
- return total;
93
+ return await countFileChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
175
94
  }
176
95
  function findCsvSafeSplitOffsets(path, shardCount, suppliedOptions = {}) {
177
96
  const options = snapshotCsvOptions(suppliedOptions);
@@ -189,6 +108,7 @@ function shardingDelimiter(options, operation) {
189
108
  return options.delimiter ?? ",";
190
109
  }
191
110
  export const csv = {
111
+ transform,
192
112
  all,
193
113
  any,
194
114
  column,
@@ -207,10 +127,16 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
207
127
  encoding,
208
128
  strict: options.strict,
209
129
  columns: options.columns,
210
- fixedColumns: options.fixedColumns
130
+ fixedColumns: options.fixedColumns,
131
+ skipRows: options.skipRows,
132
+ limit: options.limit,
133
+ expectedHeaders: options.expectedHeaders,
134
+ requireHeader: options.requireHeader,
135
+ minDataRows: options.minDataRows
211
136
  };
212
137
  }
213
- function materializeRows(batch, columns, projected, target = []) {
138
+ function consumeBatchRows(nativeBatch, columns, projected, target = []) {
139
+ using batch = nativeBatch;
214
140
  return batch.rowsInto(target, projected ? void 0 : columns);
215
141
  }
216
142
  function rejectFilteredStrictSchema(options) {
package/dist/batches.d.ts CHANGED
@@ -83,8 +83,7 @@ export declare class NativeCsvRowView {
83
83
  *
84
84
  * Missing fields are represented by empty strings, matching `rowsInto()`.
85
85
  *
86
- * @param columns Zero-based field indexes. Duplicate indexes are allowed for
87
- * this low-level accessor.
86
+ * @param columns Zero-based field indexes captured before the first read. Duplicate indexes are allowed.
88
87
  * @returns A newly allocated array of decoded UTF-8 strings.
89
88
  */
90
89
  pick(columns: CsvColumns): string[];
@@ -148,7 +147,7 @@ export declare class NativeCsvBatch {
148
147
  * missing field is represented by `''`.
149
148
  *
150
149
  * @param target Array to fill. It is truncated or extended to `rowCount`.
151
- * @param columns Optional zero-based field indexes relative to this batch.
150
+ * @param columns Optional zero-based field indexes captured before writing to the target.
152
151
  * Duplicate indexes are rejected.
153
152
  * @returns The same `target` array passed by the caller.
154
153
  * @throws {RangeError} If a column index is invalid, repeated, or an offset
@@ -259,7 +258,7 @@ export declare class NativeCsvBatch {
259
258
  * reported as `[-1, -1]`. Both `ranges` and `data` are reused/borrowed and
260
259
  * must be consumed synchronously by the callback.
261
260
  *
262
- * @param columns Zero-based field indexes relative to each row.
261
+ * @param columns Zero-based field indexes relative to each row, copied once at the start of the scan.
263
262
  * @param callback Receives `(rowIndex, ranges, data)` for each row.
264
263
  * @param startRow Inclusive first row; defaults to `0`.
265
264
  * @param endRow Exclusive end row; defaults to `rowCount`.
package/dist/batches.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { read } from "bun:ffi";
2
- import { decodeMaterializedField } from "./materialize-field.js";
2
+ import { isUtf8 } from "node:buffer";
3
+ import {
4
+ decodeMaterializedField,
5
+ prepareRow
6
+ } from "./materialize-field.js";
3
7
  import {
4
8
  EMPTY_BUFFER,
5
9
  native,
@@ -12,6 +16,8 @@ import {
12
16
  normalizeFilterColumn
13
17
  } from "./normalize.js";
14
18
  const visitBatchRows = Symbol("visitBatchRows");
19
+ const WINDOW_BYTES = 1024;
20
+ const MAX_WINDOW_FIELD_BYTES = 64;
15
21
 
16
22
  export class NativeCsvRowView {
17
23
  #data;
@@ -67,10 +73,11 @@ export class NativeCsvRowView {
67
73
  }
68
74
  pick(columns) {
69
75
  this.#requireActive();
76
+ const selectedColumns = [...columns];
70
77
  const values = [];
71
- values.length = columns.length;
72
- for (let index = 0;index < columns.length; ++index)
73
- values[index] = this.get(columns[index] ?? 0) ?? "";
78
+ values.length = selectedColumns.length;
79
+ for (let index = 0;index < selectedColumns.length; ++index)
80
+ values[index] = this.get(selectedColumns[index] ?? 0) ?? "";
74
81
  return values;
75
82
  }
76
83
  #rowRange(rowIndex) {
@@ -138,48 +145,83 @@ export class NativeCsvBatch {
138
145
  NativeCsvRowView[visitBatchRows](this, callback);
139
146
  }
140
147
  rowsInto(target, columns) {
141
- normalizeColumns(columns);
148
+ const selectedColumns = normalizeColumns(columns);
142
149
  const rowCount = this.rowCount;
143
150
  const totalFields = this.totalFields;
144
151
  const rowOffsetWords = this.#rowOffsetWordsView();
145
152
  const fieldOffsetWords = this.#fieldOffsetWordsView();
146
153
  const data = this.data();
154
+ const dataLength = data.byteLength;
147
155
  target.length = rowCount;
148
156
  if (columns !== void 0) {
149
157
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
150
- const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
151
- const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
152
- const existing = target[rowIndex];
153
- const row = existing === void 0 ? [] : existing;
154
- row.length = columns.length;
155
- for (let outputIndex = 0;outputIndex < columns.length; ++outputIndex) {
156
- const column = columns[outputIndex] ?? 0;
158
+ const fieldStart = offsetAt(rowOffsetWords, rowIndex, rowIndex, totalFields);
159
+ const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
160
+ const row = prepareRow(target[rowIndex], selectedColumns.length);
161
+ for (let outputIndex = 0;outputIndex < selectedColumns.length; ++outputIndex) {
162
+ const column = selectedColumns[outputIndex] ?? 0;
157
163
  const fieldIndex = fieldStart + column;
158
164
  if (fieldIndex >= fieldEnd) {
159
165
  row[outputIndex] = "";
160
166
  continue;
161
167
  }
162
- const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
163
- const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
168
+ const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", dataLength);
169
+ const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
164
170
  row[outputIndex] = decodeMaterializedField(data, start, end, "utf8");
165
171
  }
166
172
  target[rowIndex] = row;
167
173
  }
168
174
  return target;
169
175
  }
176
+ let windowStart = 0;
177
+ let windowEnd = 0;
178
+ let text = "";
179
+ let byteIndexed = !0;
180
+ let utf16Offsets;
181
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(this.#requireHandle());
182
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
183
+ let fieldStart = offsetAt(rowOffsetWords, 0, 0, totalFields);
184
+ let start = offsetAt(fieldOffsetWords, fieldStart, "field offset", dataLength);
170
185
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
171
- const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
172
- const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
173
- const existing = target[rowIndex];
174
- const row = existing === void 0 ? [] : existing;
175
- row.length = fieldEnd - fieldStart;
186
+ const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
187
+ const row = prepareRow(target[rowIndex], fieldEnd - fieldStart);
188
+ const leading = quotedRows?.[rowIndex] ?? 0;
189
+ const trailing = leading * 2;
176
190
  for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
177
- const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
178
- const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
191
+ const rawEnd = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
192
+ const end = rawEnd - trailing;
193
+ start += leading;
179
194
  const column = fieldIndex - fieldStart;
180
- row[column] = decodeMaterializedField(data, start, end, "utf8");
195
+ const length = end - start;
196
+ let value;
197
+ if (length > 2 && length <= MAX_WINDOW_FIELD_BYTES) {
198
+ if (start < windowStart || end > windowEnd) {
199
+ windowStart = start;
200
+ windowEnd = utf8WindowEnd(data, start);
201
+ text = decodeMaterializedField(data, start, windowEnd, "utf8");
202
+ byteIndexed = text.length === windowEnd - start;
203
+ if (!byteIndexed) {
204
+ utf16Offsets ??= new Int16Array(WINDOW_BYTES + 1);
205
+ if (!indexUtf16Boundaries(data.subarray(start, windowEnd), utf16Offsets))
206
+ text = "";
207
+ }
208
+ }
209
+ const from = start - windowStart;
210
+ const to = end - windowStart;
211
+ if (byteIndexed)
212
+ value = text.slice(from, to);
213
+ else if (text.length > 0 && utf16Offsets !== void 0) {
214
+ const first = utf16Offsets[from] ?? -1;
215
+ const last = utf16Offsets[to] ?? -1;
216
+ if (first >= 0 && last >= 0)
217
+ value = text.slice(first, last);
218
+ }
219
+ }
220
+ row[column] = value ?? decodeMaterializedField(data, start, end, "utf8");
221
+ start = rawEnd;
181
222
  }
182
223
  target[rowIndex] = row;
224
+ fieldStart = fieldEnd;
183
225
  }
184
226
  return target;
185
227
  }
@@ -294,17 +336,18 @@ export class NativeCsvBatch {
294
336
  scanColumns(columns, callback, startRow = 0, endRow = this.rowCount) {
295
337
  const resolvedEndRow = this.#resolveEndRow(endRow);
296
338
  this.#validateRowRange(startRow, resolvedEndRow);
339
+ const selectedColumns = [...columns];
297
340
  const rowOffsetWords = this.#rowOffsetWordsView();
298
341
  const fieldOffsetWords = this.#fieldOffsetWordsView();
299
342
  const data = this.data();
300
343
  const totalFields = this.totalFields;
301
- const ranges = new Float64Array(columns.length * 2);
344
+ const ranges = new Float64Array(selectedColumns.length * 2);
302
345
  for (let rowIndex = startRow;rowIndex < resolvedEndRow; ++rowIndex) {
303
346
  this.#requireHandle();
304
347
  const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
305
348
  const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
306
- for (let columnOffset = 0;columnOffset < columns.length; ++columnOffset) {
307
- const columnIndex = columns[columnOffset] ?? 0;
349
+ for (let columnOffset = 0;columnOffset < selectedColumns.length; ++columnOffset) {
350
+ const columnIndex = selectedColumns[columnOffset] ?? 0;
308
351
  const fieldIndex = rowStart + columnIndex;
309
352
  const rangeIndex = columnOffset * 2;
310
353
  if (fieldIndex < rowStart || fieldIndex >= rowEnd) {
@@ -383,18 +426,49 @@ const MAX_DIRECT_ROW_INDEX_EXCLUSIVE = Math.floor(2147483647 / BigUint64Array.BY
383
426
  function offsetWords(offsets) {
384
427
  return new Uint32Array(offsets.buffer, offsets.byteOffset, offsets.length * 2);
385
428
  }
429
+ function utf8WindowEnd(data, start) {
430
+ const limit = start + WINDOW_BYTES;
431
+ if (limit >= data.length)
432
+ return data.length;
433
+ let end = limit;
434
+ while (limit - end < 3 && (data[end] & 192) === 128)
435
+ --end;
436
+ return end;
437
+ }
438
+ function indexUtf16Boundaries(bytes, offsets) {
439
+ if (!isUtf8(bytes))
440
+ return !1;
441
+ let units = 0;
442
+ for (let i = 0;i < bytes.length; ++i) {
443
+ const byte = bytes[i];
444
+ if ((byte & 192) === 128)
445
+ offsets[i] = -1;
446
+ else {
447
+ offsets[i] = units;
448
+ units += byte >= 240 ? 2 : 1;
449
+ }
450
+ }
451
+ offsets[bytes.length] = units;
452
+ return !0;
453
+ }
386
454
  function offsetAt(offsets, index, label, upperBound) {
387
455
  const wordIndex = index * 2;
388
456
  const low = offsets[wordIndex];
389
457
  const high = offsets[wordIndex + 1];
390
- if (low === void 0 || high === void 0 || wordIndex % 2 !== 0)
391
- throw RangeError(`${label} index out of range: ${index}`);
458
+ if (high === 0 && low !== void 0 && low <= upperBound && Number.isInteger(index))
459
+ return low;
460
+ return checkedWideOffset(low, high, index, label, upperBound);
461
+ }
462
+ function checkedWideOffset(low, high, index, label, upperBound) {
463
+ const description = typeof label === "number" ? `row ${label} offset` : label;
464
+ if (low === void 0 || high === void 0 || !Number.isInteger(index))
465
+ throw RangeError(`${description} index out of range: ${index}`);
392
466
  if (high > MAX_SAFE_OFFSET_HIGH_WORD) {
393
467
  const value = BigInt(high) * UINT32_BASE_BIGINT + BigInt(low);
394
- throw RangeError(`${label} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
468
+ throw RangeError(`${description} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
395
469
  }
396
470
  const offset = low + high * UINT32_BASE;
397
471
  if (offset > upperBound)
398
- throw RangeError(`${label} exceeds backing storage: ${offset}`);
472
+ throw RangeError(`${description} exceeds backing storage: ${offset}`);
399
473
  return offset;
400
474
  }