@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
@@ -1,10 +1,27 @@
1
+ import { ptr } from "bun:ffi";
1
2
  import { createReadStream } from "node:fs";
3
+ import {
4
+ open,
5
+ stat
6
+ } from "node:fs/promises";
2
7
  import { extname } from "node:path";
3
- import { DEFAULT_CHUNK_SIZE } from "./native.js";
8
+ import { ReadableStream as WebReadableStream } from "node:stream/web";
9
+ import {
10
+ constants,
11
+ inflateSync
12
+ } from "node:zlib";
13
+ import {
14
+ DEFAULT_CHUNK_SIZE,
15
+ EMPTY_BUFFER,
16
+ native
17
+ } from "./native.js";
18
+ import { resolveInputEncoding } from "./normalize.js";
19
+ import { snapshotCsvOptions } from "./options-snapshot.js";
4
20
  import { readZipEntryChunks } from "./zip-reader.js";
5
- const DELIMITER_PROBE_SIZE = 65536;
21
+ export const FILE_PROBE_SIZE = 65536;
22
+ const PROBED_BYTE_ENCODINGS = ["utf8", "latin1", "windows-1252"];
6
23
  const MAX_DELIMITER_PROBE_ROWS = 128;
7
- const DELIMITER_CANDIDATES = [
24
+ export const DELIMITER_CANDIDATES = [
8
25
  { byte: 44, delimiter: "," },
9
26
  { byte: 9, delimiter: "\t" },
10
27
  { byte: 59, delimiter: ";" },
@@ -24,29 +41,41 @@ const COMPRESSION_EXTENSIONS = [
24
41
  ".gz",
25
42
  ".zz"
26
43
  ];
27
- export async function prepareCsvFileInput(path, options) {
44
+ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
45
+ const options = snapshotCsvOptions(suppliedOptions);
46
+ const autoEncoding = options.encoding === void 0 || options.encoding === "auto";
47
+ const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, options.delimiter);
48
+ const parserEncoding = typeof inputEncoding === "string" ? inputEncoding : "utf8";
49
+ const source = () => {
50
+ const chunks = readCsvFileChunks(path, options, readMode);
51
+ return typeof inputEncoding === "string" ? chunks : transcodeCsvChunks(chunks, inputEncoding);
52
+ };
28
53
  const configuredDelimiter = options.delimiter ?? ",";
29
- if (configuredDelimiter !== "auto") {
54
+ if (!autoEncoding && configuredDelimiter !== "auto") {
30
55
  let opened = !1;
31
56
  return {
32
57
  delimiter: configuredDelimiter,
58
+ parserEncoding,
33
59
  chunks() {
34
60
  if (opened)
35
61
  throw Error("CSV file input can only be read once");
36
62
  opened = !0;
37
- return readCsvFileChunks(path, options);
63
+ return source();
38
64
  },
39
65
  [Symbol.asyncDispose]() {
40
66
  return Promise.resolve();
41
67
  }
42
68
  };
43
69
  }
44
- const iterator = readCsvFileChunks(path, options)[Symbol.asyncIterator]();
70
+ const iterator = source()[Symbol.asyncIterator]();
71
+ const compression = options.compression ?? "auto";
72
+ const reusesReadBuffer = typeof inputEncoding === "string" && (readMode === "read-ahead" && (compression === "auto" || compression === "none") || (compression === "auto" || isZipCompression(compression)) && useZipReadAhead(readMode, options.chunkSize ?? DEFAULT_CHUNK_SIZE));
45
73
  const bufferedChunks = [];
46
74
  let bufferedByteLength = 0;
47
75
  let sourceEnded = !1;
76
+ let bytesNeeded = FILE_PROBE_SIZE;
48
77
  try {
49
- while (bufferedByteLength < DELIMITER_PROBE_SIZE) {
78
+ while (bufferedByteLength < bytesNeeded) {
50
79
  const result = await iterator.next();
51
80
  if (result.done === !0) {
52
81
  sourceEnded = !0;
@@ -54,19 +83,35 @@ export async function prepareCsvFileInput(path, options) {
54
83
  }
55
84
  if (result.value.byteLength === 0)
56
85
  continue;
57
- bufferedChunks.push(result.value);
58
86
  bufferedByteLength += result.value.byteLength;
87
+ if (bufferedByteLength === FILE_PROBE_SIZE && (configuredDelimiter === "auto" || autoEncoding && mayEndInPartialUtf8(result.value)))
88
+ ++bytesNeeded;
89
+ bufferedChunks.push(reusesReadBuffer && bufferedByteLength < bytesNeeded ? new Uint8Array(result.value) : result.value);
59
90
  }
60
91
  const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
61
- const delimiter = detectDelimiter(delimiterHintPath(path, options.compression), probe, sourceEnded);
92
+ const hint = delimiterHintPath(path, options.compression);
93
+ const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter) : void 0;
94
+ const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded);
95
+ const replayEncoding = format === void 0 ? parserEncoding : resolveInputEncoding(format.encoding, delimiter);
96
+ let skip = format?.skipBytes ?? 0;
97
+ if (skip > 0)
98
+ for (const [i, chunk] of bufferedChunks.entries()) {
99
+ const length = Math.min(skip, chunk.length);
100
+ bufferedChunks[i] = chunk.subarray(length);
101
+ skip -= length;
102
+ if (skip === 0)
103
+ break;
104
+ }
62
105
  let opened = !1;
63
106
  return {
64
107
  delimiter,
108
+ parserEncoding: typeof replayEncoding === "string" ? replayEncoding : "utf8",
65
109
  chunks() {
66
110
  if (opened)
67
111
  throw Error("CSV file input can only be read once");
68
112
  opened = !0;
69
- return replayCsvFileChunks(bufferedChunks, iterator);
113
+ const replay = replayCsvFileChunks(bufferedChunks, iterator);
114
+ return typeof replayEncoding === "string" ? replay : transcodeCsvChunks(replay, replayEncoding);
70
115
  },
71
116
  [Symbol.asyncDispose]() {
72
117
  return closeCsvFileIterator(iterator);
@@ -77,19 +122,50 @@ export async function prepareCsvFileInput(path, options) {
77
122
  throw error;
78
123
  }
79
124
  }
80
- export function readCsvFileChunks(path, options) {
125
+ async function* readAheadFileChunks(path, chunkSize) {
126
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
127
+ throw RangeError("chunkSize must be a positive safe integer");
128
+ await using file = await open(path, "r");
129
+ if (!(await file.stat()).isFile()) {
130
+ const buffer = Buffer.allocUnsafe(chunkSize);
131
+ let { bytesRead } = await file.read(buffer);
132
+ while (bytesRead > 0) {
133
+ yield buffer.subarray(0, bytesRead);
134
+ bytesRead = (await file.read(buffer)).bytesRead;
135
+ }
136
+ return;
137
+ }
138
+ let current = Buffer.allocUnsafe(chunkSize);
139
+ let spare = Buffer.allocUnsafe(chunkSize);
140
+ let { bytesRead } = await file.read(current);
141
+ while (bytesRead > 0) {
142
+ const pending = file.read(spare);
143
+ void pending.catch(() => {});
144
+ yield bytesRead === current.length ? current : current.subarray(0, bytesRead);
145
+ bytesRead = (await pending).bytesRead;
146
+ [current, spare] = [spare, current];
147
+ }
148
+ }
149
+ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
150
+ const options = snapshotCsvOptions(suppliedOptions);
81
151
  const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
82
- if (options.compression === void 0)
83
- return createReadStream(path, { highWaterMark: chunkSize });
84
- if (isZipCompression(options.compression))
85
- return readZipEntryChunks(path, options.compression, chunkSize);
86
- if (options.compression === "auto")
87
- return readAutoDetectedCsvFileChunks(path, chunkSize);
88
- return decompressedCsvFileChunks(path, options.compression, chunkSize);
152
+ const compression = options.compression ?? "auto";
153
+ const zipReadAhead = useZipReadAhead(readMode, chunkSize);
154
+ if (isZipCompression(compression))
155
+ return readZipEntryChunks(path, compression, chunkSize, zipReadAhead);
156
+ if (compression === "auto" || compression === "none") {
157
+ const readAhead = readMode === "read-ahead";
158
+ const raw = readAhead ? readAheadFileChunks(path, chunkSize) : createReadStream(path, { highWaterMark: chunkSize });
159
+ return compression === "none" ? raw : readAutoDetectedCsvFileChunks(path, raw, chunkSize, readAhead, zipReadAhead);
160
+ }
161
+ return decompressedCsvFileChunks(path, compression, chunkSize);
89
162
  }
90
163
  function isZipCompression(compression) {
91
164
  return typeof compression === "object" && compression.format === "zip";
92
165
  }
166
+ function useZipReadAhead(mode, chunkSize) {
167
+ return mode === "count" || mode !== "stream" && chunkSize >= 65536;
168
+ }
93
169
  function delimiterHintPath(path, compression) {
94
170
  return compression !== void 0 && isZipCompression(compression) ? compression.entry : path;
95
171
  }
@@ -114,13 +190,38 @@ async function* replayCsvFileChunks(bufferedChunks, iterator) {
114
190
  await closeCsvFileIterator(iterator);
115
191
  }
116
192
  }
193
+ async function* transcodeCsvChunks(source, decoder) {
194
+ const encoder = new TextEncoder;
195
+ for await (const chunk of source) {
196
+ const text = decoder.decode(chunk, { stream: !0 });
197
+ if (text.length > 0)
198
+ yield encoder.encode(text);
199
+ }
200
+ const text = decoder.decode();
201
+ if (text.length > 0)
202
+ yield encoder.encode(text);
203
+ }
117
204
  async function closeCsvFileIterator(iterator) {
118
205
  try {
119
206
  await iterator.return?.();
120
207
  } catch {}
121
208
  }
209
+ function mayEndInPartialUtf8(chunk) {
210
+ let index = chunk.length - 1;
211
+ while (index >= 0 && chunk.length - index < 4 && ((chunk[index] ?? 0) & 192) === 128)
212
+ --index;
213
+ const length = chunk.length - index;
214
+ if (length >= 4)
215
+ return !1;
216
+ if (index < 0)
217
+ return !0;
218
+ const lead = chunk[index] ?? 0;
219
+ if (lead < 194 || lead > 244)
220
+ return !1;
221
+ return length < (lead < 224 ? 2 : lead < 240 ? 3 : 4);
222
+ }
122
223
  function copyProbePrefix(chunks, totalByteLength) {
123
- const probe = new Uint8Array(Math.min(totalByteLength, DELIMITER_PROBE_SIZE));
224
+ const probe = new Uint8Array(Math.min(totalByteLength, FILE_PROBE_SIZE));
124
225
  let offset = 0;
125
226
  for (const chunk of chunks) {
126
227
  if (offset === probe.byteLength)
@@ -132,10 +233,53 @@ function copyProbePrefix(chunks, totalByteLength) {
132
233
  }
133
234
  return probe;
134
235
  }
135
- function detectDelimiter(path, probe, sourceEnded) {
136
- const rows = scanDelimiterCounts(probe, sourceEnded);
236
+ export function detectDelimiter(path, probe, sourceEnded) {
237
+ return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded));
238
+ }
239
+ export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter) => {
240
+ const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto");
241
+ return { encoding, delimiter: delimiter === "auto" ? requireDelimiter(path, counts) : delimiter, skipBytes };
242
+ };
243
+ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
244
+ let bytes = prefix;
245
+ let bomEncoding;
246
+ let skipBytes = 0;
247
+ if (bytes[0] === 255 && bytes[1] === 254 && bytes[2] === 0 && bytes[3] === 0 || bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 254 && bytes[3] === 255)
248
+ throw Error("automatic encoding detection does not support UTF-32; transcode the input to UTF-8");
249
+ if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
250
+ bomEncoding = "utf8";
251
+ skipBytes = 3;
252
+ bytes = bytes.subarray(skipBytes);
253
+ } else if (bytes[0] === 255 && bytes[1] === 254)
254
+ bomEncoding = "utf-16le";
255
+ else if (bytes[0] === 254 && bytes[1] === 255)
256
+ bomEncoding = "utf-16be";
257
+ if (bomEncoding !== void 0) {
258
+ if (!scoreDelimiters)
259
+ return { bytes, encoding: bomEncoding, skipBytes, counts: [] };
260
+ if (bomEncoding !== "utf8") {
261
+ const text = new TextDecoder(bomEncoding).decode(bytes, { stream: !sourceEnded });
262
+ bytes = new TextEncoder().encode(text);
263
+ }
264
+ }
265
+ const counts = scoreDelimiters ? new Uint32Array(8) : void 0;
266
+ const encodingCode = native.symbols.csv_probe_format(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
267
+ const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
268
+ if (encoding === void 0)
269
+ throw Error("NUL in encoding probe: specify the encoding explicitly");
270
+ return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[7] === 0 ? [] : [counts] };
271
+ }
272
+ function requireDelimiter(path, rows) {
273
+ const result = selectDelimiter(path, rows);
274
+ if ("error" in result)
275
+ throw Error(result.error);
276
+ return result.delimiter;
277
+ }
278
+ export function selectDelimiter(path, rows) {
137
279
  if (rows.length === 0)
138
- throw Error(`delimiter auto-detection failed: the ${String(DELIMITER_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
280
+ return {
281
+ error: `delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`
282
+ };
139
283
  const stableCandidates = [];
140
284
  for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
141
285
  const separatorCount = rows[0]?.[candidateIndex] ?? 0;
@@ -148,16 +292,20 @@ function detectDelimiter(path, probe, sourceEnded) {
148
292
  }
149
293
  }
150
294
  if (stableCandidates.length === 0)
151
- throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
295
+ return {
296
+ error: "delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly"
297
+ };
152
298
  const extensionHint = delimiterFromExtension(path);
153
299
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
154
300
  if (confirmedHint !== void 0)
155
- return confirmedHint.delimiter;
301
+ return { delimiter: confirmedHint.delimiter };
156
302
  const maximumSeparatorCount = Math.max(...stableCandidates.map((candidate) => candidate.separatorCount));
157
303
  const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
158
304
  if (strongestCandidates.length === 1)
159
- return strongestCandidates[0]?.delimiter ?? ",";
160
- throw Error(`delimiter auto-detection is ambiguous between ${strongestCandidates.map((candidate) => JSON.stringify(candidate.delimiter)).join(", ")}; specify delimiter explicitly`);
305
+ return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
306
+ return {
307
+ error: `delimiter auto-detection is ambiguous between ${strongestCandidates.map((candidate) => JSON.stringify(candidate.delimiter)).join(", ")}; specify delimiter explicitly`
308
+ };
161
309
  }
162
310
  export function scanDelimiterCounts(probe, sourceEnded) {
163
311
  const rows = [];
@@ -218,16 +366,66 @@ function stripCompressionExtension(path) {
218
366
  return path.slice(0, -extension.length);
219
367
  return path;
220
368
  }
221
- async function* readAutoDetectedCsvFileChunks(path, chunkSize) {
222
- const compression = await detectCompression(path);
223
- for await (const chunk of decompressedCsvFileChunks(path, compression, chunkSize))
224
- yield chunk;
369
+ async function* readAutoDetectedCsvFileChunks(path, raw, chunkSize, reusesBuffer, zipReadAhead) {
370
+ const iterator = raw[Symbol.asyncIterator]();
371
+ const buffered = [];
372
+ const prefix = new Uint8Array(64);
373
+ let length = 0;
374
+ let needed = 4;
375
+ try {
376
+ while (length < needed) {
377
+ const next = await iterator.next();
378
+ if (next.done === !0)
379
+ break;
380
+ const chunk = next.value;
381
+ const take = Math.min(prefix.length - length, chunk.length);
382
+ prefix.set(chunk.subarray(0, take), length);
383
+ length += take;
384
+ if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
385
+ needed = prefix.length;
386
+ buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
387
+ }
388
+ const sample = prefix.subarray(0, length);
389
+ if (isZipSignature(sample)) {
390
+ if (!(await stat(path)).isFile())
391
+ throw Error("ZIP input requires a regular file; save the archive before reading it");
392
+ await closeCsvFileIterator(iterator);
393
+ yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
394
+ return;
395
+ }
396
+ const compression = compressionFromPrefix(path, sample);
397
+ const replay = replayCsvFileChunks(buffered, iterator);
398
+ if (compression === void 0) {
399
+ if (!isPlainCsvFile(path))
400
+ throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
401
+ yield* replay;
402
+ return;
403
+ }
404
+ yield* WebReadableStream.from(reusesBuffer ? copyFileChunks(replay) : replay).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
405
+ } finally {
406
+ await closeCsvFileIterator(iterator);
407
+ }
408
+ }
409
+ async function* copyFileChunks(chunks) {
410
+ for await (const chunk of chunks)
411
+ yield new Uint8Array(chunk);
412
+ }
413
+ function isPlainCsvFile(path) {
414
+ const mime = Bun.file(path).type.split(";", 1)[0];
415
+ return mime === "text/csv" || mime === "text/tab-separated-values" || mime === "text/plain" || mime === "application/octet-stream" && /\.(?:psv|ssv|tab)$/i.test(path);
416
+ }
417
+ export function isZipSignature(prefix) {
418
+ return prefix[0] === 80 && prefix[1] === 75 && (prefix[2] === 3 && prefix[3] === 4 || prefix[2] === 5 && prefix[3] === 6);
419
+ }
420
+ function isPrintableZlibHeader(prefix) {
421
+ const first = prefix[0] ?? 0;
422
+ const second = prefix[1] ?? 0;
423
+ return first >= 32 && first < 127 && second >= 32 && second < 127;
225
424
  }
226
425
  function decompressedCsvFileChunks(path, compression, chunkSize) {
227
426
  return Bun.file(path).stream().pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
228
427
  }
229
- async function detectCompression(path) {
230
- const prefix = await Bun.file(path).slice(0, 4).bytes();
428
+ export function compressionFromPrefix(path, prefix) {
231
429
  const extensionHint = compressionFromExtension(path);
232
430
  const strongSignature = compressionFromStrongSignature(prefix);
233
431
  if (strongSignature !== void 0) {
@@ -246,11 +444,21 @@ async function detectCompression(path) {
246
444
  }
247
445
  return extensionHint.format;
248
446
  }
249
- if (hasZlibHeader)
447
+ if (hasZlibHeader) {
448
+ const sample = prefix.subarray(0, 64);
449
+ if (isPrintableZlibHeader(sample) && isPlainCsvFile(path) && !sample.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
450
+ try {
451
+ inflateSync(sample, { finishFlush: sample.length < 64 ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
452
+ } catch (error) {
453
+ if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
454
+ return;
455
+ throw error;
456
+ }
250
457
  return "deflate";
251
- throw Error("compression auto-detection failed: no supported signature or extension; specify compression as 'brotli' or 'deflate-raw' when applicable");
458
+ }
459
+ return;
252
460
  }
253
- function compressionFromExtension(path) {
461
+ export function compressionFromExtension(path) {
254
462
  const lowerPath = path.toLowerCase();
255
463
  if (lowerPath.endsWith(".deflate-raw"))
256
464
  return { extension: ".deflate-raw", format: "deflate-raw", signatureRequired: !1 };
package/dist/files.d.ts CHANGED
@@ -1,8 +1,154 @@
1
- import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
2
- export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, options?: CsvParserOptions): CsvRow[];
1
+ import type { CsvEncoding, CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
2
+ /**
3
+ * Parse one complete in-memory CSV buffer into materialized rows.
4
+ *
5
+ * The buffer is treated as the complete input, so quoted records may span the
6
+ * buffer but parser state is not retained after this call. `columns`
7
+ * projects zero-based physical columns in the returned rows. The supplied
8
+ * options are captured when the function is called; changing an options array
9
+ * while parsing cannot change the operation.
10
+ *
11
+ * Automatic delimiter and encoding detection and compression are file-only features.
12
+ * Use an explicit one-character delimiter for in-memory input.
13
+ *
14
+ * @param buffer Complete CSV bytes to parse.
15
+ * @param suppliedOptions Parser, projection, and strict-schema options.
16
+ * @returns Materialized rows. Each row is a newly allocated array of strings.
17
+ * @throws If the buffer, delimiter, projection, or strict-schema options are invalid, or if CSV parsing fails.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { parseCsvBuffer } from '@konstit/csv';
22
+ *
23
+ * const rows = parseCsvBuffer(Buffer.from('id,name\n1,Ada\n'));
24
+ * // rows[0] is ['id', 'name']
25
+ * ```
26
+ */
27
+ export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions<CsvEncoding>): CsvRow[];
28
+ /**
29
+ * Count rows in bytes known to contain one record per physical line.
30
+ *
31
+ * This is a structural newline counter rather than a CSV parser: newlines in
32
+ * quoted fields are counted as row boundaries. The native counter counts each
33
+ * LF byte; a final byte other than LF or CR adds one unterminated row. Thus a
34
+ * CRLF ending counts once through its LF, while a standalone CR is not a row
35
+ * separator. Use it only for trusted newline-delimited data.
36
+ *
37
+ * @param buffer Newline-delimited bytes. Typed-array views are counted from their visible byte range.
38
+ * @returns The number of physical lines, represented as a safe JavaScript number.
39
+ * @throws If the count cannot be represented safely as a JavaScript number.
40
+ */
3
41
  export declare function countTrustedNewlineRows(buffer: NodeJS.TypedArray | DataView): number;
42
+ /**
43
+ * Find byte offsets at which a CSV file can be split without breaking a record.
44
+ *
45
+ * Returned offsets include `0` and the file byte length. Intermediate offsets
46
+ * are chosen at record boundaries, including records containing quoted
47
+ * newlines, and approximate the requested number of shards. The file is read
48
+ * as raw bytes, so this low-level helper accepts only an explicit
49
+ * one-character delimiter.
50
+ *
51
+ * @param path Path to the uncompressed CSV file.
52
+ * @param shardCount Desired number of shards. It must be a positive integer.
53
+ * @param delimiter One-byte CSV delimiter; defaults to `,`.
54
+ * @returns Nondecreasing byte offsets suitable as half-open shard starts and ends.
55
+ * @throws {RangeError} If `shardCount` is not a positive integer.
56
+ * @throws If `delimiter` is not exactly one character or the native scan fails.
57
+ */
4
58
  export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string): number[];
59
+ /**
60
+ * Return inclusive byte ranges that can each be read as complete CSV records.
61
+ *
62
+ * The ranges are derived from {@link findCsvSafeSplitOffsets}. Empty ranges
63
+ * are omitted, so a small file can produce fewer ranges than `shardCount`.
64
+ * `start` and `end` are byte offsets in the uncompressed file and both ends
65
+ * are inclusive.
66
+ *
67
+ * @param path Path to the uncompressed CSV file.
68
+ * @param shardCount Desired number of shards. It must be a positive integer.
69
+ * @param delimiter One-byte CSV delimiter; defaults to `,`.
70
+ * @returns Non-empty, record-safe ranges in file order.
71
+ * @throws {RangeError} If `shardCount` is not a positive integer.
72
+ * @throws If `delimiter` is not exactly one character or the native scan fails.
73
+ */
5
74
  export declare function findCsvSafeShards(path: string, shardCount: number, delimiter?: string): CsvShard[];
75
+ /**
76
+ * Stream materialized row arrays from a CSV file.
77
+ *
78
+ * Each yielded value contains the rows parsed from one input chunk. Rows are
79
+ * ordinary strings and remain usable after the next batch is yielded. File
80
+ * compression and automatic delimiter and encoding detection are supported by
81
+ * `CsvFileOptions`.
82
+ *
83
+ * Options are snapshotted when this function is called, before iteration
84
+ * begins. Do not rely on mutating an options object while consuming the
85
+ * generator to reconfigure the stream.
86
+ *
87
+ * @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
88
+ * @param options File and parser options. `columns` selects physical columns for each row.
89
+ * @returns An async generator of non-empty row batches.
90
+ * @throws When iteration encounters an I/O, decompression, parsing, or strict-schema error.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * import { parseCsvFile } from '@konstit/csv';
95
+ *
96
+ * for await (const rows of parseCsvFile('data.csv', { columns: [0, 2] })) {
97
+ * for (const row of rows) console.log(row);
98
+ * }
99
+ * ```
100
+ */
6
101
  export declare function parseCsvFile(path: string, options?: CsvFileOptions): AsyncGenerator<CsvRow[], void>;
102
+ /**
103
+ * Stream rows using native projection and native filter evaluation.
104
+ *
105
+ * This lower-level file API is useful when the selected columns or native
106
+ * filter descriptors are already prepared. `columns` is the returned
107
+ * projection, while `equalsFilter` and `filters` are evaluated against
108
+ * physical columns before materialization. Options are snapshotted at call
109
+ * time, including nested filter values.
110
+ *
111
+ * Strict mode is not supported for projected batches, including strict CSV
112
+ * quote parsing and strict schema metadata. Use `parseCsvFile` when strict
113
+ * validation is required.
114
+ *
115
+ * @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
116
+ * @param options Native projection/filter and file parser options.
117
+ * @returns An async generator of non-empty projected row batches.
118
+ * @throws When strict mode is enabled, or when I/O, decompression, filter, or parsing errors occur during iteration.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * import { parseCsvFileProjected } from '@konstit/csv';
123
+ *
124
+ * for await (const rows of parseCsvFileProjected('data.csv', {
125
+ * columns: [2, 0],
126
+ * equalsFilter: { column: 1, value: 'active' },
127
+ * })) {
128
+ * console.log(rows);
129
+ * }
130
+ * ```
131
+ */
7
132
  export declare function parseCsvFileProjected(path: string, options?: CsvFileOptions & CsvNativeProjectionOptions): AsyncGenerator<CsvRow[], void>;
8
- export declare function countCsvFile(path: string, options?: CsvFileOptions): Promise<number>;
133
+ /**
134
+ * Count logical CSV records in a file without materializing row strings.
135
+ *
136
+ * The parser honors quoted newlines and supports the same compression and
137
+ * delimiter options as file parsing. With `strict: true`, quote syntax
138
+ * is validated while counting. Strict schema metadata is intentionally not
139
+ * supported by this counting path; use row parsing when headers or minimum
140
+ * data-row constraints must be checked.
141
+ *
142
+ * @param path Path to the CSV file (or compressed/ZIP input selected by `suppliedOptions.compression`).
143
+ * @param suppliedOptions File and parser options.
144
+ * @returns A promise for the logical CSV record count.
145
+ * @throws When strict schema metadata is requested, the file cannot be read or decompressed, parsing fails, or the count exceeds safe integer range.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * import { countCsvFile } from '@konstit/csv';
150
+ *
151
+ * const rows = await countCsvFile('data.csv', { delimiter: ';' });
152
+ * ```
153
+ */
154
+ export declare function countCsvFile(path: string, suppliedOptions?: CsvFileOptions): Promise<number>;
package/dist/files.js CHANGED
@@ -7,26 +7,32 @@ import {
7
7
  requirePtr,
8
8
  toArrayBuffer
9
9
  } from "./native.js";
10
- import { normalizeChunk } from "./normalize.js";
11
- import { NativeCsvParser } from "./parser.js";
10
+ import {
11
+ normalizeChunk,
12
+ prepareCsvBufferInput,
13
+ projectionFilterProgram
14
+ } from "./normalize.js";
15
+ import { snapshotCsvOptions } from "./options-snapshot.js";
16
+ import {
17
+ createPreparedParser,
18
+ NativeCsvParser
19
+ } from "./parser.js";
12
20
  import {
13
21
  rejectStrictSchemaUnsupported,
14
22
  strictSchemaValidator
15
23
  } from "./strict-schema.js";
16
- export function parseCsvBuffer(buffer, options = {}) {
17
- const parser = new NativeCsvParser(options);
24
+ export function parseCsvBuffer(buffer, suppliedOptions = {}) {
25
+ const options = snapshotCsvOptions(suppliedOptions);
26
+ const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
27
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding });
18
28
  const validator = strictSchemaValidator(options);
29
+ const batch = parser.writeBatch(input.bytes, !0);
19
30
  try {
20
- const batch = parser.writeBatch(buffer, !0);
21
- try {
22
- validator?.validateBatch(batch);
23
- validator?.finish();
24
- return batch.rowsInto([], options.selectedColumns);
25
- } finally {
26
- batch.close();
27
- }
31
+ validator?.validateBatch(batch);
32
+ validator?.finish();
33
+ return batch.rowsInto([], options.columns);
28
34
  } finally {
29
- parser.close();
35
+ batch.close();
30
36
  }
31
37
  }
32
38
  export function countTrustedNewlineRows(buffer) {
@@ -67,15 +73,18 @@ export function findCsvSafeShards(path, shardCount, delimiter = ",") {
67
73
  }
68
74
  return shards;
69
75
  }
70
- export async function* parseCsvFile(path, options = {}) {
76
+ export function parseCsvFile(path, options = {}) {
77
+ return iterateCsvFile(path, snapshotCsvOptions(options));
78
+ }
79
+ async function* iterateCsvFile(path, options) {
71
80
  await using input = await prepareCsvFileInput(path, options);
72
- using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
81
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
73
82
  const validator = strictSchemaValidator(options);
74
83
  for await (const chunk of input.chunks()) {
75
84
  const batch = parser.writeBatch(chunk);
76
85
  try {
77
86
  validator?.validateBatch(batch);
78
- const rows = batch.rowsInto([], options.selectedColumns);
87
+ const rows = batch.rowsInto([], options.columns);
79
88
  if (rows.length > 0)
80
89
  yield rows;
81
90
  } finally {
@@ -86,24 +95,22 @@ export async function* parseCsvFile(path, options = {}) {
86
95
  try {
87
96
  validator?.validateBatch(batch);
88
97
  validator?.finish();
89
- const rows = batch.rowsInto([], options.selectedColumns);
98
+ const rows = batch.rowsInto([], options.columns);
90
99
  if (rows.length > 0)
91
100
  yield rows;
92
101
  } finally {
93
102
  batch.close();
94
103
  }
95
104
  }
96
- export async function* parseCsvFileProjected(path, options = {}) {
105
+ export function parseCsvFileProjected(path, options = {}) {
106
+ return iterateCsvFileProjected(path, snapshotCsvOptions(options));
107
+ }
108
+ async function* iterateCsvFileProjected(path, options) {
97
109
  rejectStrictSchemaUnsupported(options, "projected file parsing");
98
110
  await using input = await prepareCsvFileInput(path, options);
99
- using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
100
- const projectionOptions = {
101
- selectedColumns: options.selectedColumns,
102
- equalsFilter: options.equalsFilter,
103
- filters: options.filters
104
- };
111
+ using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter }, options.columns, projectionFilterProgram(options), !0);
105
112
  for await (const chunk of input.chunks()) {
106
- const batch = parser.writeProjectedBatch(chunk, projectionOptions);
113
+ const batch = parser.writeBatch(chunk);
107
114
  try {
108
115
  const rows = batch.rows();
109
116
  if (rows.length > 0)
@@ -112,7 +119,7 @@ export async function* parseCsvFileProjected(path, options = {}) {
112
119
  batch.close();
113
120
  }
114
121
  }
115
- const batch = parser.endProjectedBatch(projectionOptions);
122
+ const batch = parser.endBatch();
116
123
  try {
117
124
  const rows = batch.rows();
118
125
  if (rows.length > 0)
@@ -121,10 +128,11 @@ export async function* parseCsvFileProjected(path, options = {}) {
121
128
  batch.close();
122
129
  }
123
130
  }
124
- export async function countCsvFile(path, options = {}) {
131
+ export async function countCsvFile(path, suppliedOptions = {}) {
132
+ const options = snapshotCsvOptions(suppliedOptions);
125
133
  rejectStrictSchemaUnsupported(options, "count");
126
- await using input = await prepareCsvFileInput(path, options);
127
- using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
134
+ await using input = await prepareCsvFileInput(path, options, "count");
135
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
128
136
  let rows = 0;
129
137
  if (options.strict === !0) {
130
138
  for await (const chunk of input.chunks()) {