@konstit/csv 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +152 -463
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +169 -44
  4. package/dist/api.js +75 -368
  5. package/dist/batches.d.ts +250 -7
  6. package/dist/batches.js +135 -83
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +350 -0
  9. package/dist/cli-schema.d.ts +111 -0
  10. package/dist/cli-schema.js +219 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +57 -2
  13. package/dist/file-stream.js +244 -36
  14. package/dist/files.d.ts +149 -3
  15. package/dist/files.js +37 -29
  16. package/dist/filter.d.ts +80 -0
  17. package/dist/format-bytes.d.ts +1 -0
  18. package/dist/format-bytes.js +11 -0
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -14
  21. package/dist/inspect-file.d.ts +12 -0
  22. package/dist/inspect-file.js +88 -0
  23. package/dist/latin1-rows.d.ts +5 -0
  24. package/dist/latin1-rows.js +122 -0
  25. package/dist/materialize-field.d.ts +3 -0
  26. package/dist/materialize-field.js +31 -0
  27. package/dist/native.d.ts +51 -2
  28. package/dist/native.js +43 -4
  29. package/dist/normalize.d.ts +32 -2
  30. package/dist/normalize.js +51 -2
  31. package/dist/options-snapshot.d.ts +3 -0
  32. package/dist/options-snapshot.js +51 -0
  33. package/dist/options.d.ts +25 -10
  34. package/dist/options.js +0 -6
  35. package/dist/parser.d.ts +309 -4
  36. package/dist/parser.js +128 -31
  37. package/dist/strict-schema.d.ts +5 -3
  38. package/dist/strict-schema.js +4 -1
  39. package/dist/types.d.ts +355 -121
  40. package/dist/zip-reader.d.ts +11 -1
  41. package/dist/zip-reader.js +12 -3
  42. package/package.json +44 -29
  43. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  44. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  45. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  46. package/prebuilds/manifest.json +9 -8
  47. package/prebuilds/provenance/darwin-arm64.json +1 -1
  48. package/prebuilds/provenance/darwin-x64.json +1 -1
  49. package/prebuilds/provenance/linux-x64.json +1 -1
  50. package/dist/worker-count.d.ts +0 -2
  51. package/dist/worker-count.js +0 -96
  52. package/dist/worker-factory.d.ts +0 -3
  53. package/dist/worker-factory.js +0 -9
  54. package/dist/worker-filter.d.ts +0 -29
  55. package/dist/worker-filter.js +0 -46
  56. package/dist/worker-module.d.ts +0 -1
  57. package/dist/worker-module.js +0 -4
  58. package/dist/worker-pool.d.ts +0 -17
  59. package/dist/worker-pool.js +0 -290
  60. package/dist/worker-rows.d.ts +0 -8
  61. package/dist/worker-rows.js +0 -118
  62. package/dist/workers/count.worker.d.ts +0 -1
  63. package/dist/workers/count.worker.js +0 -49
  64. package/dist/workers/rows.worker.d.ts +0 -1
  65. package/dist/workers/rows.worker.js +0 -85
package/dist/filter.d.ts CHANGED
@@ -1,8 +1,88 @@
1
1
  import type { CsvNativeFilterProgramEntry } from './normalize.js';
2
2
  import type { CsvFilter, CsvFilterColumn, CsvRegex } from './types.js';
3
+ /**
4
+ * Select a reusable zero-based physical CSV column for building native filters.
5
+ *
6
+ * The returned column exposes predicate methods such as `equals()` and `hasMatch()`. Predicate
7
+ * operands are copied when the filter is created, so later mutation of a `Buffer`, `Uint8Array`,
8
+ * or values array cannot change the filter. A selected column can be reused to create many
9
+ * independent filters.
10
+ *
11
+ * @param columnIndex - Zero-based physical column index, from 0 through 2024.
12
+ * @returns An immutable column predicate builder.
13
+ * @throws {RangeError} If `columnIndex` is not an integer in the supported range.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const state = csv.column(2);
18
+ * const filter = state.isOneOf(['SP', 'RJ']);
19
+ * ```
20
+ */
3
21
  export declare function column(columnIndex: number): CsvFilterColumn;
22
+ /**
23
+ * Match rows for which every supplied filter matches.
24
+ *
25
+ * Groups can be nested, and the resulting filter can be reused for both rows and counts.
26
+ * A missing physical column remains unknown under negation.
27
+ *
28
+ * @param first - First filter in the group.
29
+ * @param rest - Additional filters that must also match.
30
+ * @returns An immutable conjunction filter.
31
+ * @throws {RangeError} If no filter is supplied.
32
+ * @throws {TypeError} If any filter was not created by this filter API.
33
+ */
4
34
  export declare function all(first: CsvFilter, ...rest: readonly CsvFilter[]): CsvFilter;
35
+ /**
36
+ * Match rows for which at least one supplied filter matches.
37
+ *
38
+ * Groups can be nested, and the resulting filter can be reused for both rows and counts.
39
+ * Another matching child can satisfy the group when one child's column is missing.
40
+ *
41
+ * @param first - First filter in the group.
42
+ * @param rest - Additional filters, any one of which may match.
43
+ * @returns An immutable disjunction filter.
44
+ * @throws {RangeError} If no filter is supplied.
45
+ * @throws {TypeError} If any filter was not created by this filter API.
46
+ */
5
47
  export declare function any(first: CsvFilter, ...rest: readonly CsvFilter[]): CsvFilter;
48
+ /**
49
+ * Negate one native filter.
50
+ *
51
+ * The resulting filter preserves the evaluator's unknown result for a missing column. Use this
52
+ * with filters created by {@link column}, {@link all}, or {@link any}; filters are immutable and
53
+ * safe to reuse across operations.
54
+ *
55
+ * @param filter - Filter to negate.
56
+ * @returns An immutable negation filter.
57
+ * @throws {TypeError} If `filter` was not created by this filter API.
58
+ */
6
59
  export declare function not(filter: CsvFilter): CsvFilter;
60
+ /**
61
+ * Validate and brand a JavaScript regular expression for native matching.
62
+ *
63
+ * Validation happens immediately using the parser's RE2-compatible engine. Supported flags are
64
+ * `i`, `m`, `s`, and `u`; global, sticky, indices, and `v` flags are rejected. The returned
65
+ * branded descriptor is used by low-level `CsvRegexFilter` values; `CsvFilterColumn.hasMatch()`
66
+ * accepts a `RegExp` and creates this descriptor internally.
67
+ *
68
+ * @param pattern - JavaScript regular expression to validate and copy.
69
+ * @returns An immutable validated regular expression descriptor.
70
+ * @throws {TypeError} If `pattern` is not a `RegExp`.
71
+ * @throws {SyntaxError} If the pattern is invalid for the native RE2 engine.
72
+ * @throws {Error} If the expression uses unsupported flags.
73
+ * @throws {RangeError} If the UTF-8 pattern exceeds the native size limit.
74
+ */
7
75
  export declare function re(pattern: RegExp): CsvRegex;
76
+ /**
77
+ * Resolve the native program associated with an opaque filter handle.
78
+ *
79
+ * This internal bridge lets the high-level API translate a `where` filter while preserving
80
+ * identity-based validation. It is not part of the package root API; callers should pass filters
81
+ * directly to `where` instead.
82
+ *
83
+ * @internal
84
+ * @param filter - Filter created by this module, or `undefined` when no filter is configured.
85
+ * @returns The immutable native filter program, or `undefined` when no filter is supplied.
86
+ * @throws {TypeError} If a non-native or foreign filter object is supplied.
87
+ */
8
88
  export declare function nativeFilterProgramFor(filter: CsvFilter | undefined): readonly CsvNativeFilterProgramEntry[] | undefined;
@@ -0,0 +1 @@
1
+ export declare function formatBytes(bytes: number): string;
@@ -0,0 +1,11 @@
1
+ export function formatBytes(bytes) {
2
+ const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
3
+ let value = bytes;
4
+ let unitIndex = 0;
5
+ while (unitIndex < units.length - 1 && value >= 1024) {
6
+ value /= 1024;
7
+ ++unitIndex;
8
+ }
9
+ const unit = units[unitIndex] ?? "B";
10
+ return `${value.toFixed(value >= 10 || unit === "B" ? 0 : 1)} ${unit}`;
11
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnarBatchCallback, CsvColumnarBatchOptions, CsvColumnarBatchView, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeFilter, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParallelCountOptions, CsvParallelRowsOptions, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvRowView, CsvRowViewCallback, CsvRowViewsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvSingleThreadRowsOptions, CsvStartsWithFilter, CsvWorkerPoolOptions, CsvZipCompression, NativeCsvRowCallback, } from './types.js';
2
- export { csv, CsvWorkerPool, findCsvSafeShards, findCsvSafeSplitOffsets, forEachColumnarBatches, forEachRowViews, parallelCount, parallelRows, withColumnarBatches, withRowViews, workerPool, } from './api.js';
1
+ export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvRowCallback, } from './types.js';
2
+ export { csv } from './api.js';
3
3
  export { NativeCsvBatch, NativeCsvRowView } from './batches.js';
4
4
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
5
- export { defineColumnarOptions, defineCountOptions, defineRowsOptions, defineRowViewOptions } from './options.js';
5
+ export { defineCountOptions, defineRowsOptions } from './options.js';
6
6
  export { NativeCsvParser } from './parser.js';
package/dist/index.js CHANGED
@@ -1,19 +1,7 @@
1
1
  import { requireBunRuntime } from "./runtime.js";
2
2
  requireBunRuntime();
3
- export {
4
- csv,
5
- CsvWorkerPool,
6
- findCsvSafeShards,
7
- findCsvSafeSplitOffsets,
8
- forEachColumnarBatches,
9
- forEachRowViews,
10
- parallelCount,
11
- parallelRows,
12
- withColumnarBatches,
13
- withRowViews,
14
- workerPool
15
- } from "./api.js";
3
+ export { csv } from "./api.js";
16
4
  export { NativeCsvBatch, NativeCsvRowView } from "./batches.js";
17
5
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from "./files.js";
18
- export { defineColumnarOptions, defineCountOptions, defineRowsOptions, defineRowViewOptions } from "./options.js";
6
+ export { defineCountOptions, defineRowsOptions } from "./options.js";
19
7
  export { NativeCsvParser } from "./parser.js";
@@ -0,0 +1,12 @@
1
+ import type { CsvFileProbe } from './file-stream.js';
2
+ interface FileInspection {
3
+ size: number;
4
+ compression: Bun.CompressionFormat | 'zip' | 'none';
5
+ encoding: ReturnType<CsvFileProbe>['encoding'];
6
+ delimiter: string | undefined;
7
+ lineEnding: string;
8
+ firstRecordColumns: number | undefined;
9
+ }
10
+ /** Inspect a bounded sample of the CSV payload; size always refers to the file on disk. */
11
+ export declare function inspectCsvFile(path: string, zipEntry?: string): Promise<FileInspection>;
12
+ export {};
@@ -0,0 +1,88 @@
1
+ import { stat } from "node:fs/promises";
2
+ import {
3
+ compressionFromExtension,
4
+ compressionFromPrefix,
5
+ DELIMITER_CANDIDATES,
6
+ FILE_PROBE_SIZE,
7
+ isZipSignature,
8
+ readCsvFileChunks,
9
+ scanCsvFileFormat,
10
+ selectDelimiter
11
+ } from "./file-stream.js";
12
+ export async function inspectCsvFile(path, zipEntry) {
13
+ const info = await stat(path);
14
+ if (!info.isFile())
15
+ throw Error("probe requires a regular file");
16
+ const raw = await Bun.file(path).slice(0, FILE_PROBE_SIZE + 1).bytes();
17
+ const zip = isZipSignature(raw);
18
+ if (zipEntry !== void 0 && !zip)
19
+ throw Error("--zip-entry requires a ZIP archive");
20
+ let compression = zip ? { format: "zip", entry: zipEntry ?? "*" } : compressionFromPrefix(path, raw);
21
+ let sample = raw;
22
+ if (compression !== void 0)
23
+ try {
24
+ sample = await readCompressedSample(path, compression);
25
+ } catch (error) {
26
+ if (compression !== "deflate" || compressionFromExtension(path) !== void 0 || !(error instanceof TypeError) || raw.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
27
+ throw error;
28
+ compression = void 0;
29
+ }
30
+ const eof = sample.length <= FILE_PROBE_SIZE;
31
+ const { bytes, counts, encoding } = scanCsvFileFormat(sample.subarray(0, FILE_PROBE_SIZE), eof, !0);
32
+ const choice = selectDelimiter(zip ? zipEntry ?? "*" : path, counts);
33
+ const delimiter = "delimiter" in choice ? choice.delimiter : void 0;
34
+ return {
35
+ size: info.size,
36
+ compression: typeof compression === "object" ? "zip" : compression ?? "none",
37
+ encoding,
38
+ delimiter,
39
+ ...inspectRecords(bytes, eof, delimiter)
40
+ };
41
+ }
42
+ async function readCompressedSample(path, compression) {
43
+ const sample = new Uint8Array(FILE_PROBE_SIZE + 1);
44
+ let length = 0;
45
+ for await (const chunk of readCsvFileChunks(path, { compression, chunkSize: sample.length })) {
46
+ const take = Math.min(chunk.length, sample.length - length);
47
+ sample.set(chunk.subarray(0, take), length);
48
+ length += take;
49
+ if (length === sample.length)
50
+ break;
51
+ }
52
+ return sample.subarray(0, length);
53
+ }
54
+ function inspectRecords(bytes, eof, delimiter) {
55
+ const separator = delimiter?.charCodeAt(0);
56
+ const endings = new Set;
57
+ let quoted = !1;
58
+ let firstRecord = !0;
59
+ let columns = 1;
60
+ let unknownWidth = !1;
61
+ for (let i = 0;i < bytes.length; ++i) {
62
+ const byte = bytes[i];
63
+ if (byte === 34)
64
+ quoted = !quoted;
65
+ else if (!quoted) {
66
+ if (byte === 13 || byte === 10) {
67
+ firstRecord = !1;
68
+ if (byte === 13 && bytes[i + 1] === 10) {
69
+ endings.add("CRLF");
70
+ ++i;
71
+ } else if (byte === 13 && i + 1 === bytes.length && !eof)
72
+ break;
73
+ else
74
+ endings.add(byte === 10 ? "LF" : "CR");
75
+ } else if (firstRecord) {
76
+ if (byte === separator)
77
+ ++columns;
78
+ else if (separator === void 0 && DELIMITER_CANDIDATES.some((candidate) => candidate.byte === byte))
79
+ unknownWidth = !0;
80
+ }
81
+ }
82
+ }
83
+ const firstComplete = !firstRecord || eof && !quoted;
84
+ return {
85
+ firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns : void 0,
86
+ lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown")
87
+ };
88
+ }
@@ -0,0 +1,5 @@
1
+ import { type NativePointer } from './native.js';
2
+ import type { CsvNativeFilterProgramEntry } from './normalize.js';
3
+ import type { CsvColumns, CsvDelimiter, CsvRow } from './types.js';
4
+ export declare function latin1Rows(chunks: AsyncIterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[]): AsyncGenerator<CsvRow[], void>;
5
+ export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
@@ -0,0 +1,122 @@
1
+ import {
2
+ copyLatin1Range,
3
+ latin1Pair
4
+ } from "./materialize-field.js";
5
+ import {
6
+ EMPTY_BUFFER,
7
+ native,
8
+ requirePtr,
9
+ toArrayBuffer,
10
+ u64ToSafeNumber
11
+ } from "./native.js";
12
+ import { normalizeChunk } from "./normalize.js";
13
+ import {
14
+ nativeCsvParserFinalizer,
15
+ prepareNativeParser
16
+ } from "./parser.js";
17
+ export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows) {
18
+ if (delimiter === "auto")
19
+ throw Error("automatic delimiter detection is only supported by file APIs");
20
+ if (delimiter.length !== 1)
21
+ throw Error("delimiter must be one character");
22
+ const parser = createParser(delimiter.charCodeAt(0));
23
+ if (parser === null)
24
+ throw Error("failed to create native CSV parser");
25
+ const lifetime = {};
26
+ nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
27
+ try {
28
+ const prepared = prepareNativeParser(parser, columns, filters);
29
+ for await (const chunk of chunks) {
30
+ const input = normalizeChunk(chunk);
31
+ const batch = prepared.writeBatch(input, !1);
32
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
33
+ if (rows.length > 0)
34
+ yield rows;
35
+ }
36
+ const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
37
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
38
+ if (rows.length > 0)
39
+ yield rows;
40
+ } finally {
41
+ nativeCsvParserFinalizer.unregister(lifetime);
42
+ native.symbols.csv_parser_destroy(parser);
43
+ }
44
+ }
45
+ function consumeLatin1Batch(parser, batch, reusableRows) {
46
+ if (batch === null)
47
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(parser) ?? "native parser error unavailable"}`);
48
+ try {
49
+ const rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
50
+ if (rowCount === 0)
51
+ return [];
52
+ const totalFields = u64ToSafeNumber(native.symbols.csv_batch_total_fields(batch), "CSV batch field count");
53
+ const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
54
+ const data = dataLength === 0 ? EMPTY_BUFFER : new Uint8Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_data_ptr(batch)), 0, dataLength));
55
+ const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
56
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
57
+ const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
58
+ const fieldOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch)), 0, (totalFields + 1) * 8));
59
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(batch);
60
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
61
+ const rows = reusableRows ?? [];
62
+ rows.length = rowCount;
63
+ let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
64
+ let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
65
+ for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
66
+ const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
67
+ const leading = quotedRows?.[rowIndex] ?? 0;
68
+ const trailing = leading * 2;
69
+ const row = reusableRows?.[rowIndex] ?? [];
70
+ const width = fieldEnd - fieldStart;
71
+ row.length = width;
72
+ for (let column = 0;column < width; ++column) {
73
+ const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
74
+ const payload = start + leading;
75
+ const payloadEnd = end - trailing;
76
+ const length = payloadEnd - payload;
77
+ switch (length) {
78
+ case 0:
79
+ row[column] = "";
80
+ break;
81
+ case 1:
82
+ row[column] = String.fromCharCode(view.getUint8(payload));
83
+ break;
84
+ case 2:
85
+ row[column] = latin1Pair(view.getUint16(payload, !0));
86
+ break;
87
+ case 3:
88
+ row[column] = latin1Pair(view.getUint16(payload, !0)) + String.fromCharCode(view.getUint8(payload + 2));
89
+ break;
90
+ case 4:
91
+ row[column] = latin1Pair(view.getUint16(payload, !0)) + latin1Pair(view.getUint16(payload + 2, !0));
92
+ break;
93
+ default:
94
+ if (length < 0)
95
+ throw RangeError("CSV field span exceeds its backing range");
96
+ row[column] = copyLatin1Range(bytes, payload, payloadEnd);
97
+ }
98
+ start = end;
99
+ }
100
+ rows[rowIndex] = row;
101
+ fieldStart = fieldEnd;
102
+ }
103
+ return rows;
104
+ } finally {
105
+ native.symbols.csv_batch_destroy(batch);
106
+ }
107
+ }
108
+ export function checkedOffset(words, index, upperBound) {
109
+ const low = words[index * 2];
110
+ const high = words[index * 2 + 1];
111
+ if (low !== void 0 && high === 0 && low <= upperBound)
112
+ return low;
113
+ return checkedWideOffset(low, high, upperBound);
114
+ }
115
+ function checkedWideOffset(low, high, upperBound) {
116
+ if (low === void 0 || high === void 0 || high > 2097151)
117
+ throw RangeError("CSV batch offset out of range");
118
+ const offset = low + high * 4294967296;
119
+ if (offset > upperBound)
120
+ throw RangeError("CSV batch offset exceeds backing storage");
121
+ return offset;
122
+ }
@@ -0,0 +1,3 @@
1
+ export declare function latin1Pair(key: number): string;
2
+ export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
3
+ export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
@@ -0,0 +1,31 @@
1
+ const LATIN1_SINGLE = Array.from({ length: 256 }, (_, byte) => String.fromCharCode(byte));
2
+ const bufferPrototype = Buffer.prototype;
3
+ const latin1Slice = bufferPrototype.latin1Slice;
4
+ const LATIN1_PAIRS = Array.from({ length: 65536 });
5
+ export function latin1Pair(key) {
6
+ const cached = LATIN1_PAIRS[key];
7
+ if (cached !== void 0)
8
+ return cached;
9
+ const value = String.fromCharCode(key & 255, key >>> 8);
10
+ LATIN1_PAIRS[key] = value;
11
+ return value;
12
+ }
13
+ export function copyLatin1Range(data, start, end) {
14
+ return typeof latin1Slice === "function" ? latin1Slice.call(data, start, end) : data.toString("latin1", start, end);
15
+ }
16
+ export function decodeMaterializedField(data, start, end, encoding) {
17
+ const length = end - start;
18
+ if (length === 0)
19
+ return "";
20
+ if (length === 1) {
21
+ const first = data[start];
22
+ return first < 128 || encoding === "latin1" ? LATIN1_SINGLE[first] : "\uFFFD";
23
+ }
24
+ if (length === 2) {
25
+ const first = data[start] ?? 128;
26
+ const second = data[start + 1] ?? 128;
27
+ if (first < 128 && second < 128)
28
+ return latin1Pair(first | second << 8);
29
+ }
30
+ return encoding === "latin1" ? copyLatin1Range(data, start, end) : data.toString("utf8", start, end);
31
+ }
package/dist/native.d.ts CHANGED
@@ -1,11 +1,22 @@
1
- import { type Library, type Pointer } from 'bun:ffi';
1
+ import { type Pointer } from 'bun:ffi';
2
2
  export type { Pointer } from 'bun:ffi';
3
3
  export { toArrayBuffer } from 'bun:ffi';
4
+ /**
5
+ * Address of a native CSV resource, represented by Bun FFI as a pointer or bigint.
6
+ *
7
+ * A handle must originate from the matching native CSV ABI and remain valid for
8
+ * the operation using it. Wrapping a batch handle in `NativeCsvBatch` transfers
9
+ * responsibility for releasing that resource to the batch.
10
+ */
4
11
  export type NativePointer = Pointer | bigint;
5
12
  export declare const EMPTY_BUFFER: Uint8Array<ArrayBuffer>;
6
13
  export declare const EMPTY_U32: Uint32Array<ArrayBuffer>;
7
14
  export declare const DEFAULT_CHUNK_SIZE: number;
8
- export declare const native: Library<{
15
+ export declare const native: import("bun:ffi").Library<{
16
+ readonly csv_probe_format: {
17
+ readonly args: readonly ["buffer", "u32", "bool", "bool", "ptr"];
18
+ readonly returns: "u32";
19
+ };
9
20
  readonly csv_runtime_supports_avx2: {
10
21
  readonly args: readonly [];
11
22
  readonly returns: "int";
@@ -174,6 +185,10 @@ export declare const native: Library<{
174
185
  readonly args: readonly ["ptr"];
175
186
  readonly returns: "void";
176
187
  };
188
+ readonly csv_zip_reader_enable_read_ahead: {
189
+ readonly args: readonly ["ptr", "u32"];
190
+ readonly returns: "void";
191
+ };
177
192
  readonly csv_zip_reader_read: {
178
193
  readonly args: readonly ["ptr", "buffer", "buffer_length"];
179
194
  readonly returns: "u64";
@@ -190,7 +205,41 @@ export declare const native: Library<{
190
205
  readonly args: readonly ["ptr"];
191
206
  readonly returns: "cstring";
192
207
  };
208
+ readonly csv_parser_prepare: {
209
+ readonly args: readonly ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
210
+ readonly returns: "bool";
211
+ };
212
+ readonly csv_parser_write_prepared_batch: {
213
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
214
+ readonly returns: "ptr";
215
+ };
216
+ readonly csv_parser_write_prepared_count: {
217
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
218
+ readonly returns: "u64";
219
+ };
220
+ readonly csv_parser_create_latin1_rows: {
221
+ readonly args: readonly ["u8"];
222
+ readonly returns: "ptr";
223
+ };
224
+ readonly csv_parser_create_latin1_rows_with_quoted_spans: {
225
+ readonly args: readonly ["u8"];
226
+ readonly returns: "ptr";
227
+ };
228
+ readonly csv_parser_create_latin1_quoted_rows: {
229
+ readonly args: readonly ["u8", "u32"];
230
+ readonly returns: "ptr";
231
+ };
232
+ readonly csv_batch_quoted_rows_ptr: {
233
+ readonly args: readonly ["ptr"];
234
+ readonly returns: "ptr";
235
+ };
236
+ readonly csv_parser_create_latin1_rows_with_fixed_columns: {
237
+ readonly args: readonly ["u8", "u32"];
238
+ readonly returns: "ptr";
239
+ };
193
240
  }>;
241
+ export declare function latin1RowsParser(fixedColumns: number | undefined): (delimiter: number) => NativePointer | null;
242
+ export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
194
243
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
195
244
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
196
245
  export declare function findNativeLibraryPath(candidates: readonly string[]): string | undefined;
package/dist/native.js CHANGED
@@ -19,6 +19,16 @@ export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0);
19
19
  export const EMPTY_U32 = new Uint32Array(1);
20
20
  export const DEFAULT_CHUNK_SIZE = 1048576;
21
21
  const CSV_SYMBOLS = {
22
+ csv_probe_format: {
23
+ args: [
24
+ "buffer",
25
+ "u32",
26
+ "bool",
27
+ "bool",
28
+ "ptr"
29
+ ],
30
+ returns: "u32"
31
+ },
22
32
  csv_runtime_supports_avx2: {
23
33
  args: [],
24
34
  returns: "int"
@@ -201,6 +211,10 @@ const CSV_SYMBOLS = {
201
211
  args: ["ptr"],
202
212
  returns: "void"
203
213
  },
214
+ csv_zip_reader_enable_read_ahead: {
215
+ args: ["ptr", "u32"],
216
+ returns: "void"
217
+ },
204
218
  csv_zip_reader_read: {
205
219
  args: ["ptr", "buffer", "buffer_length"],
206
220
  returns: "u64"
@@ -216,15 +230,40 @@ const CSV_SYMBOLS = {
216
230
  csv_parser_last_error: {
217
231
  args: ["ptr"],
218
232
  returns: "cstring"
233
+ },
234
+ csv_parser_prepare: {
235
+ args: ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"],
236
+ returns: "bool"
237
+ },
238
+ csv_parser_write_prepared_batch: {
239
+ args: ["ptr", "buffer", "buffer_length", "bool"],
240
+ returns: "ptr"
241
+ },
242
+ csv_parser_write_prepared_count: {
243
+ args: ["ptr", "buffer", "buffer_length", "bool"],
244
+ returns: "u64"
245
+ },
246
+ csv_parser_create_latin1_rows: {
247
+ args: ["u8"],
248
+ returns: "ptr"
249
+ },
250
+ csv_parser_create_latin1_rows_with_quoted_spans: { args: ["u8"], returns: "ptr" },
251
+ csv_parser_create_latin1_quoted_rows: { args: ["u8", "u32"], returns: "ptr" },
252
+ csv_batch_quoted_rows_ptr: { args: ["ptr"], returns: "ptr" },
253
+ csv_parser_create_latin1_rows_with_fixed_columns: {
254
+ args: ["u8", "u32"],
255
+ returns: "ptr"
219
256
  }
220
257
  };
221
- export const native = loadNative();
222
- function loadNative() {
258
+ export const native = dlopen(resolveNativeLibraryPath(process.env.CSV_NATIVE_LIBRARY_PATH), CSV_SYMBOLS);
259
+ export function latin1RowsParser(fixedColumns) {
260
+ return (delimiter) => native.symbols.csv_parser_create_latin1_quoted_rows(delimiter, fixedColumns ?? 0);
261
+ }
262
+ export function resolveNativeLibraryPath(configuredPath) {
223
263
  const root = dirname(dirname(fileURLToPath(import.meta.url)));
224
264
  const target = `${process.platform}-${process.arch}`;
225
- const configuredPath = process.env.CSV_NATIVE_LIBRARY_PATH;
226
265
  const libraryPath = configuredPath === void 0 ? requireNativeLibraryPath(nativeLibraryCandidates(root, target, suffix)) : requireConfiguredNativeLibraryPath(configuredPath);
227
- return dlopen(resolve(libraryPath), CSV_SYMBOLS);
266
+ return resolve(libraryPath);
228
267
  }
229
268
  export function requireConfiguredNativeLibraryPath(configuredPath) {
230
269
  if (configuredPath.length === 0)
@@ -1,17 +1,47 @@
1
- import type { CsvColumns, CsvEncoding, CsvEqualsFilter, CsvFieldValue, CsvInFilter, CsvNativeFilter, CsvRegex, CsvStartsWithFilter } from './types.js';
1
+ import type { CsvColumns, CsvEncoding, CsvEqualsFilter, CsvFieldValue, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeProjectionOptions, CsvRegex, CsvStartsWithFilter } from './types.js';
2
+ interface PreparedCsvBufferInput {
3
+ readonly bytes: NodeJS.TypedArray | DataView;
4
+ readonly parserEncoding: 'utf8' | 'latin1';
5
+ }
2
6
  export declare const MAX_COLUMN_INDEX = 2024;
3
7
  export declare const MAX_PROJECTION_LENGTH = 2024;
4
8
  export declare const MAX_FILTER_COUNT = 2024;
5
9
  export declare const MAX_REGEX_FILTER_COUNT = 32;
6
10
  export declare const MAX_FILTER_PROGRAM_LENGTH = 4096;
11
+ /**
12
+ * Boolean operation in a postfix filter program accepted by `NativeCsvParser`.
13
+ *
14
+ * Predicates push results onto a stack. An operator consumes the most recent
15
+ * results and pushes one combined result. Missing columns produce an unknown
16
+ * result, which remains unknown under `not` and does not select a row by itself.
17
+ */
7
18
  export interface CsvNativeFilterOperator {
19
+ /** Number of preceding stack results to consume; positive, and exactly one for `not`. */
8
20
  readonly operandCount: number;
21
+ /** Combine operands with AND, OR, or unary negation. */
9
22
  readonly operator: 'all' | 'any' | 'not';
10
23
  }
24
+ /**
25
+ * Predicate or boolean operator in a low-level postfix filter program.
26
+ *
27
+ * Place predicates before the operators that consume them. A complete program
28
+ * must leave exactly one result on the stack and contain at most 4096 entries.
29
+ * Most applications can use `csv.column()` and its boolean combinators instead.
30
+ */
11
31
  export type CsvNativeFilterProgramEntry = CsvNativeFilter | CsvNativeFilterOperator;
12
- export declare function encodingCode(encoding?: CsvEncoding): number;
32
+ export declare function projectionFilterProgram(options: CsvNativeProjectionOptions): readonly CsvNativeFilterProgramEntry[] | undefined;
33
+ export declare function encodingCode(encoding?: CsvNativeEncoding): number;
34
+ /**
35
+ * Selects the byte encoding used by the native parser or a decoder for the input.
36
+ * The three Latin-1 labels map bytes 0x80–0x9f directly to Unicode control characters.
37
+ */
38
+ export declare function resolveInputEncoding(encoding?: string, delimiter?: string): 'utf8' | 'latin1' | TextDecoder;
39
+ /** Converts a complete buffer to bytes accepted by the native parser. */
40
+ export declare function prepareCsvBufferInput(buffer: NodeJS.TypedArray | DataView, encoding?: CsvEncoding, delimiter?: string): PreparedCsvBufferInput;
13
41
  export declare function normalizeChunk(chunk: NodeJS.TypedArray | DataView): NodeJS.TypedArray | DataView;
14
42
  export declare function normalizeFixedColumnsCount(value: number | undefined, label: string): number | undefined;
43
+ /** Reject stale JavaScript options before a requested projection can silently return all fields. */
44
+ export declare function rejectSelectedColumns(options: object): void;
15
45
  export declare function normalizeColumns(columns: CsvColumns | undefined): Uint32Array;
16
46
  export declare function normalizeColumnIndex(column: number, label: string): number;
17
47
  export declare function normalizeEqualsFilter(filter: CsvEqualsFilter | undefined): {