@konstit/csv 0.4.3 → 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 (63) hide show
  1. package/README.md +42 -26
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +39 -249
  4. package/dist/api.js +40 -304
  5. package/dist/batches.d.ts +5 -53
  6. package/dist/batches.js +66 -43
  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 +241 -36
  14. package/dist/files.d.ts +11 -11
  15. package/dist/files.js +11 -9
  16. package/dist/filter.d.ts +4 -6
  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 +3 -1
  24. package/dist/latin1-rows.js +61 -23
  25. package/dist/materialize-field.d.ts +2 -0
  26. package/dist/materialize-field.js +20 -15
  27. package/dist/native.d.ts +29 -9
  28. package/dist/native.js +27 -29
  29. package/dist/normalize.d.ts +15 -2
  30. package/dist/normalize.js +41 -2
  31. package/dist/options-snapshot.js +3 -2
  32. package/dist/options.d.ts +4 -30
  33. package/dist/options.js +0 -6
  34. package/dist/parser.d.ts +14 -15
  35. package/dist/parser.js +38 -54
  36. package/dist/strict-schema.d.ts +5 -3
  37. package/dist/types.d.ts +88 -222
  38. package/dist/zip-reader.d.ts +11 -1
  39. package/dist/zip-reader.js +12 -3
  40. package/package.json +34 -32
  41. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  42. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  43. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  44. package/prebuilds/manifest.json +9 -8
  45. package/prebuilds/provenance/darwin-arm64.json +1 -1
  46. package/prebuilds/provenance/darwin-x64.json +1 -1
  47. package/prebuilds/provenance/linux-x64.json +1 -1
  48. package/dist/worker-count.d.ts +0 -34
  49. package/dist/worker-count.js +0 -101
  50. package/dist/worker-factory.d.ts +0 -3
  51. package/dist/worker-factory.js +0 -9
  52. package/dist/worker-filter.d.ts +0 -29
  53. package/dist/worker-filter.js +0 -46
  54. package/dist/worker-module.d.ts +0 -1
  55. package/dist/worker-module.js +0 -4
  56. package/dist/worker-pool.d.ts +0 -93
  57. package/dist/worker-pool.js +0 -298
  58. package/dist/worker-rows.d.ts +0 -36
  59. package/dist/worker-rows.js +0 -127
  60. package/dist/workers/count.worker.d.ts +0 -1
  61. package/dist/workers/count.worker.js +0 -36
  62. package/dist/workers/rows.worker.d.ts +0 -1
  63. package/dist/workers/rows.worker.js +0 -56
@@ -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
+ }
@@ -1,3 +1,5 @@
1
+ import { type NativePointer } from './native.js';
1
2
  import type { CsvNativeFilterProgramEntry } from './normalize.js';
2
3
  import type { CsvColumns, CsvDelimiter, CsvRow } from './types.js';
3
- export declare function latin1Rows(chunks: AsyncIterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined): AsyncGenerator<CsvRow[], void>;
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;
@@ -1,46 +1,48 @@
1
- import { decodeMaterializedField } from "./materialize-field.js";
1
+ import {
2
+ copyLatin1Range,
3
+ latin1Pair
4
+ } from "./materialize-field.js";
2
5
  import {
3
6
  EMPTY_BUFFER,
4
7
  native,
5
- optionalLatin1RowsNative,
6
8
  requirePtr,
7
9
  toArrayBuffer,
8
10
  u64ToSafeNumber
9
11
  } from "./native.js";
10
12
  import { normalizeChunk } from "./normalize.js";
11
- import { prepareNativeParser } from "./parser.js";
12
- const latin1RowsParserFinalizer = new FinalizationRegistry((parser) => {
13
- native.symbols.csv_parser_destroy(parser);
14
- });
15
- export async function* latin1Rows(chunks, delimiter, columns, filters) {
13
+ import {
14
+ nativeCsvParserFinalizer,
15
+ prepareNativeParser
16
+ } from "./parser.js";
17
+ export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows) {
16
18
  if (delimiter === "auto")
17
19
  throw Error("automatic delimiter detection is only supported by file APIs");
18
20
  if (delimiter.length !== 1)
19
21
  throw Error("delimiter must be one character");
20
- const parser = optionalLatin1RowsNative()?.symbols.csv_parser_create_latin1_rows(delimiter.charCodeAt(0));
21
- if (parser === null || parser === void 0)
22
+ const parser = createParser(delimiter.charCodeAt(0));
23
+ if (parser === null)
22
24
  throw Error("failed to create native CSV parser");
23
25
  const lifetime = {};
24
- latin1RowsParserFinalizer.register(lifetime, parser, lifetime);
26
+ nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
25
27
  try {
26
28
  const prepared = prepareNativeParser(parser, columns, filters);
27
29
  for await (const chunk of chunks) {
28
30
  const input = normalizeChunk(chunk);
29
31
  const batch = prepared.writeBatch(input, !1);
30
- const rows = consumeLatin1Batch(parser, batch);
32
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
31
33
  if (rows.length > 0)
32
34
  yield rows;
33
35
  }
34
36
  const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
35
- const rows = consumeLatin1Batch(parser, batch);
37
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
36
38
  if (rows.length > 0)
37
39
  yield rows;
38
40
  } finally {
39
- latin1RowsParserFinalizer.unregister(lifetime);
41
+ nativeCsvParserFinalizer.unregister(lifetime);
40
42
  native.symbols.csv_parser_destroy(parser);
41
43
  }
42
44
  }
43
- function consumeLatin1Batch(parser, batch) {
45
+ function consumeLatin1Batch(parser, batch, reusableRows) {
44
46
  if (batch === null)
45
47
  throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(parser) ?? "native parser error unavailable"}`);
46
48
  try {
@@ -51,30 +53,66 @@ function consumeLatin1Batch(parser, batch) {
51
53
  const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
52
54
  const data = dataLength === 0 ? EMPTY_BUFFER : new Uint8Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_data_ptr(batch)), 0, dataLength));
53
55
  const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
56
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
57
  const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
55
58
  const fieldOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch)), 0, (totalFields + 1) * 8));
56
- const rows = [];
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 ?? [];
57
62
  rows.length = rowCount;
63
+ let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
64
+ let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
58
65
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
59
- const fieldStart = checkedOffset(rowOffsets, rowIndex, totalFields);
60
66
  const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
61
- const row = [];
62
- row.length = fieldEnd - fieldStart;
63
- for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
64
- const start = checkedOffset(fieldOffsets, fieldIndex, dataLength);
65
- const end = checkedOffset(fieldOffsets, fieldIndex + 1, dataLength);
66
- row[fieldIndex - fieldStart] = decodeMaterializedField(bytes, start, end, "latin1");
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;
67
99
  }
68
100
  rows[rowIndex] = row;
101
+ fieldStart = fieldEnd;
69
102
  }
70
103
  return rows;
71
104
  } finally {
72
105
  native.symbols.csv_batch_destroy(batch);
73
106
  }
74
107
  }
75
- function checkedOffset(words, index, upperBound) {
108
+ export function checkedOffset(words, index, upperBound) {
76
109
  const low = words[index * 2];
77
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) {
78
116
  if (low === void 0 || high === void 0 || high > 2097151)
79
117
  throw RangeError("CSV batch offset out of range");
80
118
  const offset = low + high * 4294967296;
@@ -1 +1,3 @@
1
+ export declare function latin1Pair(key: number): string;
2
+ export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
1
3
  export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
@@ -1,26 +1,31 @@
1
- const ASCII_SINGLE = Array.from({ length: 128 }, (_, byte) => String.fromCharCode(byte));
2
- const ASCII_PAIRS = Array.from({ length: 16384 });
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
+ }
3
16
  export function decodeMaterializedField(data, start, end, encoding) {
4
17
  const length = end - start;
5
18
  if (length === 0)
6
19
  return "";
7
20
  if (length === 1) {
8
- const first = data[start] ?? 128;
9
- if (first < 128)
10
- return ASCII_SINGLE[first] ?? "";
21
+ const first = data[start];
22
+ return first < 128 || encoding === "latin1" ? LATIN1_SINGLE[first] : "\uFFFD";
11
23
  }
12
24
  if (length === 2) {
13
25
  const first = data[start] ?? 128;
14
26
  const second = data[start + 1] ?? 128;
15
- if (first < 128 && second < 128) {
16
- const key = first << 7 | second;
17
- const cached = ASCII_PAIRS[key];
18
- if (cached !== void 0)
19
- return cached;
20
- const decoded = String.fromCharCode(first, second);
21
- ASCII_PAIRS[key] = decoded;
22
- return decoded;
23
- }
27
+ if (first < 128 && second < 128)
28
+ return latin1Pair(first | second << 8);
24
29
  }
25
- return data.toString(encoding, start, end);
30
+ return encoding === "latin1" ? copyLatin1Range(data, start, end) : data.toString("utf8", start, end);
26
31
  }
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
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
4
  /**
@@ -12,7 +12,11 @@ export type NativePointer = Pointer | bigint;
12
12
  export declare const EMPTY_BUFFER: Uint8Array<ArrayBuffer>;
13
13
  export declare const EMPTY_U32: Uint32Array<ArrayBuffer>;
14
14
  export declare const DEFAULT_CHUNK_SIZE: number;
15
- 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
+ };
16
20
  readonly csv_runtime_supports_avx2: {
17
21
  readonly args: readonly [];
18
22
  readonly returns: "int";
@@ -181,6 +185,10 @@ export declare const native: Library<{
181
185
  readonly args: readonly ["ptr"];
182
186
  readonly returns: "void";
183
187
  };
188
+ readonly csv_zip_reader_enable_read_ahead: {
189
+ readonly args: readonly ["ptr", "u32"];
190
+ readonly returns: "void";
191
+ };
184
192
  readonly csv_zip_reader_read: {
185
193
  readonly args: readonly ["ptr", "buffer", "buffer_length"];
186
194
  readonly returns: "u64";
@@ -197,8 +205,6 @@ export declare const native: Library<{
197
205
  readonly args: readonly ["ptr"];
198
206
  readonly returns: "cstring";
199
207
  };
200
- }>;
201
- declare const PREPARED_PARSER_SYMBOLS: {
202
208
  readonly csv_parser_prepare: {
203
209
  readonly args: readonly ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
204
210
  readonly returns: "bool";
@@ -211,15 +217,29 @@ declare const PREPARED_PARSER_SYMBOLS: {
211
217
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
212
218
  readonly returns: "u64";
213
219
  };
214
- };
215
- export declare function optionalPreparedParserNative(): Library<typeof PREPARED_PARSER_SYMBOLS> | null;
216
- declare const LATIN1_ROWS_SYMBOLS: {
217
220
  readonly csv_parser_create_latin1_rows: {
218
221
  readonly args: readonly ["u8"];
219
222
  readonly returns: "ptr";
220
223
  };
221
- };
222
- export declare function optionalLatin1RowsNative(): Library<typeof LATIN1_ROWS_SYMBOLS> | null;
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
+ };
240
+ }>;
241
+ export declare function latin1RowsParser(fixedColumns: number | undefined): (delimiter: number) => NativePointer | null;
242
+ export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
223
243
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
224
244
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
225
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,11 +230,7 @@ const CSV_SYMBOLS = {
216
230
  csv_parser_last_error: {
217
231
  args: ["ptr"],
218
232
  returns: "cstring"
219
- }
220
- };
221
- const nativeLibraryPath = resolveNativeLibraryPath();
222
- export const native = dlopen(nativeLibraryPath, CSV_SYMBOLS);
223
- const PREPARED_PARSER_SYMBOLS = {
233
+ },
224
234
  csv_parser_prepare: {
225
235
  args: ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"],
226
236
  returns: "bool"
@@ -232,38 +242,26 @@ const PREPARED_PARSER_SYMBOLS = {
232
242
  csv_parser_write_prepared_count: {
233
243
  args: ["ptr", "buffer", "buffer_length", "bool"],
234
244
  returns: "u64"
235
- }
236
- };
237
- let preparedParserNative;
238
- export function optionalPreparedParserNative() {
239
- if (preparedParserNative === void 0)
240
- try {
241
- preparedParserNative = dlopen(nativeLibraryPath, PREPARED_PARSER_SYMBOLS);
242
- } catch {
243
- preparedParserNative = null;
244
- }
245
- return preparedParserNative;
246
- }
247
- const LATIN1_ROWS_SYMBOLS = {
245
+ },
248
246
  csv_parser_create_latin1_rows: {
249
247
  args: ["u8"],
250
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"
251
256
  }
252
257
  };
253
- let latin1RowsNative;
254
- export function optionalLatin1RowsNative() {
255
- if (latin1RowsNative === void 0)
256
- try {
257
- latin1RowsNative = dlopen(nativeLibraryPath, LATIN1_ROWS_SYMBOLS);
258
- } catch {
259
- latin1RowsNative = null;
260
- }
261
- return latin1RowsNative;
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);
262
261
  }
263
- function resolveNativeLibraryPath() {
262
+ export function resolveNativeLibraryPath(configuredPath) {
264
263
  const root = dirname(dirname(fileURLToPath(import.meta.url)));
265
264
  const target = `${process.platform}-${process.arch}`;
266
- const configuredPath = process.env.CSV_NATIVE_LIBRARY_PATH;
267
265
  const libraryPath = configuredPath === void 0 ? requireNativeLibraryPath(nativeLibraryCandidates(root, target, suffix)) : requireConfiguredNativeLibraryPath(configuredPath);
268
266
  return resolve(libraryPath);
269
267
  }
@@ -1,4 +1,8 @@
1
- import type { CsvColumns, CsvEncoding, CsvEqualsFilter, CsvFieldValue, CsvInFilter, CsvNativeFilter, CsvNativeProjectionOptions, 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;
@@ -26,9 +30,18 @@ export interface CsvNativeFilterOperator {
26
30
  */
27
31
  export type CsvNativeFilterProgramEntry = CsvNativeFilter | CsvNativeFilterOperator;
28
32
  export declare function projectionFilterProgram(options: CsvNativeProjectionOptions): readonly CsvNativeFilterProgramEntry[] | undefined;
29
- export declare function encodingCode(encoding?: CsvEncoding): number;
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;
30
41
  export declare function normalizeChunk(chunk: NodeJS.TypedArray | DataView): NodeJS.TypedArray | DataView;
31
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;
32
45
  export declare function normalizeColumns(columns: CsvColumns | undefined): Uint32Array;
33
46
  export declare function normalizeColumnIndex(column: number, label: string): number;
34
47
  export declare function normalizeEqualsFilter(filter: CsvEqualsFilter | undefined): {
package/dist/normalize.js CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  EMPTY_U32,
4
4
  native
5
5
  } from "./native.js";
6
+ const LATIN1_ENCODINGS = new Set(["latin1", "iso88591", "iso-8859-1"]);
6
7
  export const MAX_COLUMN_INDEX = 2024;
7
8
  export const MAX_PROJECTION_LENGTH = 2024;
8
9
  export const MAX_FILTER_COUNT = MAX_PROJECTION_LENGTH;
@@ -31,13 +32,47 @@ export function projectionFilterProgram(options) {
31
32
  return filters.length === 1 ? filters : [...filters, { operator: "all", operandCount: filters.length }];
32
33
  }
33
34
  export function encodingCode(encoding = "utf8") {
34
- const normalized = encoding.toLowerCase();
35
+ const normalized = resolveInputEncoding(encoding);
35
36
  if (normalized === "utf8")
36
37
  return 0;
37
- if (normalized === "latin1" || normalized === "iso88591" || normalized === "iso-8859-1")
38
+ if (normalized === "latin1")
38
39
  return 1;
39
40
  throw Error(`unsupported encoding: ${encoding}`);
40
41
  }
42
+ export function resolveInputEncoding(encoding = "utf8", delimiter) {
43
+ if (encoding === "auto")
44
+ throw Error("automatic encoding detection is only supported by file parsing APIs; specify encoding explicitly");
45
+ if (encoding === "utf8" || encoding === "utf-8")
46
+ return "utf8";
47
+ if (LATIN1_ENCODINGS.has(encoding))
48
+ return "latin1";
49
+ if (typeof encoding !== "string")
50
+ throw TypeError("encoding must be a string");
51
+ let decoder;
52
+ try {
53
+ decoder = new TextDecoder(encoding);
54
+ } catch (cause) {
55
+ if (cause instanceof RangeError)
56
+ throw Error(`unsupported encoding: ${encoding}`, { cause });
57
+ throw cause;
58
+ }
59
+ if (decoder.encoding === "utf-8")
60
+ return "utf8";
61
+ if (decoder.encoding === "windows-1252" && LATIN1_ENCODINGS.has(encoding.trim().toLowerCase()))
62
+ return "latin1";
63
+ if (delimiter !== void 0 && delimiter.charCodeAt(0) > 127)
64
+ throw Error(`encoding ${decoder.encoding} requires an ASCII delimiter`);
65
+ return decoder;
66
+ }
67
+ export function prepareCsvBufferInput(buffer, encoding, delimiter) {
68
+ const resolved = resolveInputEncoding(encoding, delimiter);
69
+ if (typeof resolved === "string")
70
+ return { bytes: buffer, parserEncoding: resolved };
71
+ return {
72
+ bytes: new TextEncoder().encode(resolved.decode(buffer)),
73
+ parserEncoding: "utf8"
74
+ };
75
+ }
41
76
  export function normalizeChunk(chunk) {
42
77
  return chunk.byteLength === 0 ? EMPTY_BUFFER : chunk;
43
78
  }
@@ -48,6 +83,10 @@ export function normalizeFixedColumnsCount(value, label) {
48
83
  throw RangeError(`${label} out of range: ${value}`);
49
84
  return value;
50
85
  }
86
+ export function rejectSelectedColumns(options) {
87
+ if ("selectedColumns" in options)
88
+ throw TypeError("selectedColumns is unsupported; use columns");
89
+ }
51
90
  export function normalizeColumns(columns) {
52
91
  if (columns === void 0)
53
92
  return EMPTY_U32;
@@ -1,18 +1,19 @@
1
1
  import {
2
2
  MAX_FILTER_COUNT,
3
- MAX_PROJECTION_LENGTH
3
+ MAX_PROJECTION_LENGTH,
4
+ rejectSelectedColumns
4
5
  } from "./normalize.js";
5
6
  const snapshots = new WeakSet;
6
7
  export function snapshotCsvOptions(options) {
7
8
  if (snapshots.has(options))
8
9
  return options;
10
+ rejectSelectedColumns(options);
9
11
  const captured = { ...options };
10
12
  if (captured.filters !== void 0 && captured.filters.length > MAX_FILTER_COUNT)
11
13
  throw RangeError(`filter count out of range: ${captured.filters.length}`);
12
14
  const snapshot = Object.freeze({
13
15
  ...captured,
14
16
  columns: snapshotColumns(captured.columns),
15
- selectedColumns: snapshotColumns(captured.selectedColumns),
16
17
  expectedHeaders: captured.expectedHeaders === void 0 ? void 0 : Object.freeze([...captured.expectedHeaders]),
17
18
  compression: typeof captured.compression === "object" && captured.compression !== null ? Object.freeze({ ...captured.compression }) : captured.compression,
18
19
  equalsFilter: captured.equalsFilter === void 0 ? void 0 : Object.freeze({ ...captured.equalsFilter, value: copyFieldValue(captured.equalsFilter.value) }),
package/dist/options.d.ts CHANGED
@@ -1,11 +1,10 @@
1
- import type { CsvColumnarBatchOptions, CsvColumns, CsvCountOptions, CsvRowsOptions, CsvRowViewsOptions } from './types.js';
1
+ import type { CsvColumns, CsvCountOptions, CsvRowsOptions } from './types.js';
2
2
  /**
3
3
  * Preserve literal column inference for `csv.rows()` options.
4
4
  *
5
5
  * This identity helper is useful when options are declared separately from the call site. It
6
- * checks the selected-column/strict/worker union while retaining tuple literals for projected row
7
- * types; it does not clone or freeze the object. Each operation snapshots caller-owned option
8
- * values when invoked.
6
+ * checks projection and strict validation options while retaining tuple literals for projected row
7
+ * types. Each operation snapshots caller-owned option values when invoked.
9
8
  *
10
9
  * @typeParam TColumns - Literal selected column indexes, when supplied.
11
10
  * @typeParam TOptions - The complete rows option object to preserve.
@@ -24,35 +23,10 @@ export declare function defineRowsOptions<const TColumns extends CsvColumns | un
24
23
  /**
25
24
  * Preserve literal inference for `csv.count()` options.
26
25
  *
27
- * The helper validates the count option union, including the restrictions that apply to strict
28
- * and parallel counting, while returning the original object unchanged.
26
+ * The helper checks that strict counts use unfiltered input and returns the original object.
29
27
  *
30
28
  * @typeParam TOptions - The complete count option object to preserve.
31
29
  * @param options - Type-checked count options.
32
30
  * @returns The same options object, with its literal type preserved.
33
31
  */
34
32
  export declare function defineCountOptions<const TOptions extends CsvCountOptions>(options: TOptions): TOptions;
35
- /**
36
- * Preserve literal column inference for `csv.withColumnarBatches()` options.
37
- *
38
- * This identity helper retains projected column tuples for columnar batch callbacks and checks
39
- * the callback API's option restrictions, including its non-strict projected mode.
40
- *
41
- * @typeParam TColumns - Literal selected column indexes, when supplied.
42
- * @typeParam TOptions - The complete columnar batch option object to preserve.
43
- * @param options - Type-checked columnar batch options.
44
- * @returns The same options object, with its literal type preserved.
45
- */
46
- export declare function defineColumnarOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvColumnarBatchOptions<TColumns>>(options: TOptions): TOptions;
47
- /**
48
- * Preserve literal column inference for `csv.withRowViews()` options.
49
- *
50
- * The helper checks the serial row-view option union and keeps a selected-column tuple visible to
51
- * the callback's `CsvRowView` type. It is an identity function at runtime.
52
- *
53
- * @typeParam TColumns - Literal selected column indexes, when supplied.
54
- * @typeParam TOptions - The complete row-view option object to preserve.
55
- * @param options - Type-checked row-view options.
56
- * @returns The same options object, with its literal type preserved.
57
- */
58
- export declare function defineRowViewOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvRowViewsOptions<TColumns>>(options: TOptions): TOptions;
package/dist/options.js CHANGED
@@ -4,9 +4,3 @@ export function defineRowsOptions(options) {
4
4
  export function defineCountOptions(options) {
5
5
  return options;
6
6
  }
7
- export function defineColumnarOptions(options) {
8
- return options;
9
- }
10
- export function defineRowViewOptions(options) {
11
- return options;
12
- }