@konstit/csv 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,10 @@ import {
7
7
  positional
8
8
  } from "@konstit/cli";
9
9
  import packageInfo from "../package.json";
10
- import { resolveInputEncoding } from "./normalize.js";
10
+ import {
11
+ normalizeColumns,
12
+ resolveInputEncoding
13
+ } from "./normalize.js";
11
14
  const encodings = parsers.enum([
12
15
  "auto",
13
16
  { value: "utf8", aliases: ["utf-8"] },
@@ -64,6 +67,7 @@ const encodingParser = {
64
67
  };
65
68
  const compressionFormats = ["auto", "none", "gzip", "deflate", "deflate-raw", "brotli", "zstd", "zip"];
66
69
  const positiveUint32 = parsers.range(1, 4294967295, { integer: !0 });
70
+ const rowCount = parsers.range(0, Number.MAX_SAFE_INTEGER, { integer: !0 });
67
71
  const byteSize = parsers.custom(parsers.byteSize.label, (input) => {
68
72
  const bare = Number(input);
69
73
  return parsers.byteSize.parse(Number.isNaN(bare) ? input : `${bare}B`);
@@ -72,18 +76,26 @@ const positiveByteSize = parsers.refine(byteSize, (bytes) => bytes > 0, "expecte
72
76
  const chunkSize = parsers.refine(positiveByteSize, (bytes) => bytes <= 67108864, "expected at most 64 MiB");
73
77
  const inputDelimiter = parsers.regex(/^(?:auto|[\p{ASCII}--["\r\n]])$/v);
74
78
  const outputDelimiter = parsers.regex(/^[\p{ASCII}--["\r\n]]$/v);
79
+ const columns = parsers.custom("INDEXES", (value) => {
80
+ const indexes = value.length === 0 ? [] : value.split(",").map((column) => parseColumnIndex(column, "columns"));
81
+ normalizeColumns(indexes);
82
+ return indexes;
83
+ });
75
84
  const path = positional("path", parsers.string, { required: !0, valueHint: "file", describe: "Input file path" });
76
85
  const zipEntry = option("zip-entry", parsers.refine(parsers.string, (value) => value.length > 0, "expected a non-empty ZIP entry name"), {
77
86
  valueName: "PATH",
78
87
  describe: "Select an entry inside a ZIP archive"
79
88
  });
80
- const fileArgs = [
81
- path,
89
+ const formatArgs = [
82
90
  option("delimiter", inputDelimiter, { valueName: "CHAR|auto", describe: "One safe ASCII character or auto (default: auto)" }),
83
91
  option("encoding", encodingParser, {
84
92
  valueName: "ENCODING",
85
93
  describe: "Input encoding or decoder alias (default: auto)"
86
- }),
94
+ })
95
+ ];
96
+ const fileArgs = [
97
+ path,
98
+ ...formatArgs,
87
99
  option("compression", parsers.enum(compressionFormats), {
88
100
  valueName: "FORMAT",
89
101
  describe: `Input compression (default: auto). Choices: ${compressionFormats.join(", ")}`
@@ -91,6 +103,7 @@ const fileArgs = [
91
103
  option("chunk-size", chunkSize, {
92
104
  describe: "Read 1 B through 64 MiB per chunk (default: 1MiB). Example: 256KiB"
93
105
  }),
106
+ option("skip-rows", rowCount, { valueName: "N", describe: "Skip the first N input records before filtering, including any header" }),
94
107
  zipEntry,
95
108
  option("max-compression-ratio", positiveUint32, {
96
109
  valueName: "RATIO",
@@ -99,13 +112,12 @@ const fileArgs = [
99
112
  option("max-decompressed-bytes", positiveByteSize, { describe: "Maximum decompressed ZIP size (default: 64GiB)" }),
100
113
  flag("strict", { describe: "Enable strict RFC 4180 validation" }),
101
114
  option("fixed-columns", positiveUint32, { valueName: "COUNT", describe: "Require this positive field count in strict mode" }),
102
- option("columns", parsers.string, {
103
- valueName: "INDEXES",
115
+ option("columns", columns, {
104
116
  describe: "Zero-based column indexes in output order. The count command validates the indexes only"
105
117
  }),
106
118
  option("expected-header", parsers.string, { repeatable: !0, describe: "Expected header value. Repeat once per column in strict mode" }),
107
119
  flag("require-header", { describe: "Require a header row in strict mode" }),
108
- option("min-data-rows", parsers.range(0, Number.MAX_SAFE_INTEGER, { integer: !0 }), {
120
+ option("min-data-rows", rowCount, {
109
121
  valueName: "COUNT",
110
122
  describe: "Require at least this many data rows in strict mode"
111
123
  }),
@@ -160,7 +172,6 @@ const count = command("count", {
160
172
  ...fileRelations,
161
173
  about: "Count CSV records, including the header row",
162
174
  args: fileArgs,
163
- argsOverrideSelf: !0,
164
175
  afterHelp: `${fileHelp}
165
176
 
166
177
  Examples:
@@ -170,7 +181,7 @@ Examples:
170
181
  });
171
182
  const lines = command("lines", {
172
183
  ...fileRelations,
173
- conflicts: [["json", "output-delimiter"], ["limit", "min-data-rows"]],
184
+ conflicts: [["json", "output-delimiter"]],
174
185
  about: "Stream matching records as normalized UTF-8 CSV or NDJSON",
175
186
  args: [
176
187
  ...fileArgs,
@@ -180,22 +191,25 @@ const lines = command("lines", {
180
191
  default: ",",
181
192
  describe: "One safe ASCII output delimiter (default: comma). Incompatible with --json"
182
193
  }),
183
- option("limit", parsers.range(1, Number.MAX_SAFE_INTEGER, { integer: !0 }), {
194
+ option("limit", rowCount, {
184
195
  valueName: "N",
185
- describe: "Stop after matching output record N, numbered from 1. Incompatible with --min-data-rows"
196
+ describe: "Emit at most N matching records (0 emits none)"
186
197
  })
187
198
  ],
188
- argsOverrideSelf: !0,
189
199
  afterHelp: `${fileHelp}
190
200
 
191
- With --strict and --limit, validation stops at the selected record. Set a fixed
192
- delimiter and encoding (defaults: comma and UTF-8). Input must be uncompressed
193
- and the chunk size must be 1 byte. Earlier records can be written before a later error.
201
+ Strict validation includes skipped records and stops when the output limit is reached.
202
+ Header and minimum data row checks apply to the consumed input prefix.
194
203
 
195
204
  Examples:
196
- csv lines data.csv --json --limit 10
205
+ csv lines data.csv --json --skip-rows 1 --limit 10
197
206
  csv lines data.csv --columns 0,2 --where-eq 3=active`
198
207
  });
208
+ const probe = command("probe", {
209
+ about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
210
+ args: [path, ...formatArgs, zipEntry, flag("json", { describe: "Emit the inspection as one JSON object" })],
211
+ afterHelp: "Samples up to 64 KiB of decompressed CSV. For a ZIP archive with multiple data files, select one with --zip-entry."
212
+ });
199
213
  export const csvCommand = command("csv", {
200
214
  about: "Inspect, count, and stream CSV records",
201
215
  version: packageInfo.version,
@@ -204,12 +218,7 @@ export const csvCommand = command("csv", {
204
218
  subcommands: [
205
219
  count,
206
220
  lines,
207
- command("probe", {
208
- about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
209
- args: [path, zipEntry],
210
- argsOverrideSelf: !0,
211
- afterHelp: "Samples up to 64 KiB of CSV. For a ZIP archive with multiple data files, select one with --zip-entry."
212
- }),
221
+ probe,
213
222
  command("completion", {
214
223
  about: "Print a shell completion script for csv",
215
224
  args: [positional("shell", parsers.enum(completionShells), { required: !0, describe: completionShells.join(", ") })]
@@ -217,3 +226,9 @@ export const csvCommand = command("csv", {
217
226
  ],
218
227
  afterHelp: "Run without installing: bunx @konstit/csv <command> <path>"
219
228
  });
229
+ export function parseColumnIndex(value, label) {
230
+ const number = Number(value);
231
+ if (!Number.isSafeInteger(number) || number < 0)
232
+ throw Error(`${label} must be an integer greater than or equal to 0: ${value}`);
233
+ return number;
234
+ }
@@ -27,7 +27,7 @@ interface CompressionExtensionHint {
27
27
  format: Bun.CompressionFormat;
28
28
  signatureRequired: boolean;
29
29
  }
30
- interface CsvFileInput extends AsyncDisposable {
30
+ export interface CsvFileInput extends AsyncDisposable {
31
31
  readonly delimiter: CsvDelimiter;
32
32
  /** Encoding expected by the native parser after any stream transcoding. */
33
33
  readonly parserEncoding: 'utf8' | 'latin1';
@@ -54,11 +54,15 @@ interface CsvFormatSample {
54
54
  }
55
55
  /** When scoring delimiters, structural bytes exclude the BOM and use UTF-8 for UTF-16 input. */
56
56
  export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean): CsvFormatSample;
57
- export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): {
57
+ type DelimiterChoice = {
58
58
  delimiter: CsvDelimiter;
59
59
  } | {
60
- error: string;
60
+ reason: 'no-records' | 'no-stable-separator';
61
+ } | {
62
+ reason: 'ambiguous';
63
+ candidates: readonly CsvDelimiter[];
61
64
  };
65
+ export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): DelimiterChoice;
62
66
  export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
63
67
  export declare function isZipSignature(prefix: Uint8Array): boolean;
64
68
  export declare function compressionFromPrefix(path: string, prefix: Uint8Array): Bun.CompressionFormat | undefined;
@@ -271,15 +271,20 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
271
271
  }
272
272
  function requireDelimiter(path, rows) {
273
273
  const result = selectDelimiter(path, rows);
274
- if ("error" in result)
275
- throw Error(result.error);
276
- return result.delimiter;
274
+ if ("delimiter" in result)
275
+ return result.delimiter;
276
+ switch (result.reason) {
277
+ case "no-records":
278
+ throw Error(`delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
279
+ case "no-stable-separator":
280
+ throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
281
+ case "ambiguous":
282
+ throw Error(`delimiter auto-detection is ambiguous between ${result.candidates.map((c) => JSON.stringify(c)).join(", ")}; specify delimiter explicitly`);
283
+ }
277
284
  }
278
285
  export function selectDelimiter(path, rows) {
279
286
  if (rows.length === 0)
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
- };
287
+ return { reason: "no-records" };
283
288
  const stableCandidates = [];
284
289
  for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
285
290
  const separatorCount = rows[0]?.[candidateIndex] ?? 0;
@@ -292,9 +297,7 @@ export function selectDelimiter(path, rows) {
292
297
  }
293
298
  }
294
299
  if (stableCandidates.length === 0)
295
- return {
296
- error: "delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly"
297
- };
300
+ return { reason: "no-stable-separator" };
298
301
  const extensionHint = delimiterFromExtension(path);
299
302
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
300
303
  if (confirmedHint !== void 0)
@@ -303,9 +306,7 @@ export function selectDelimiter(path, rows) {
303
306
  const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
304
307
  if (strongestCandidates.length === 1)
305
308
  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
- };
309
+ return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
309
310
  }
310
311
  export function scanDelimiterCounts(probe, sourceEnded) {
311
312
  const rows = [];
package/dist/files.js CHANGED
@@ -10,26 +10,22 @@ import {
10
10
  import {
11
11
  normalizeChunk,
12
12
  prepareCsvBufferInput,
13
- projectionFilterProgram
13
+ rejectSelectedColumns
14
14
  } from "./normalize.js";
15
15
  import { snapshotCsvOptions } from "./options-snapshot.js";
16
16
  import {
17
+ countFileChunks,
17
18
  createPreparedParser,
18
- NativeCsvParser
19
+ NativeCsvParser,
20
+ parseFileChunks
19
21
  } from "./parser.js";
20
- import {
21
- rejectStrictSchemaUnsupported,
22
- strictSchemaValidator
23
- } from "./strict-schema.js";
22
+ import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
24
23
  export function parseCsvBuffer(buffer, suppliedOptions = {}) {
25
24
  const options = snapshotCsvOptions(suppliedOptions);
26
25
  const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
27
- using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding });
28
- const validator = strictSchemaValidator(options);
26
+ using parser = createPreparedParser({ ...options, encoding: input.parserEncoding });
29
27
  const batch = parser.writeBatch(input.bytes, !0);
30
28
  try {
31
- validator?.validateBatch(batch);
32
- validator?.finish();
33
29
  return batch.rowsInto([], options.columns);
34
30
  } finally {
35
31
  batch.close();
@@ -78,81 +74,42 @@ export function parseCsvFile(path, options = {}) {
78
74
  }
79
75
  async function* iterateCsvFile(path, options) {
80
76
  await using input = await prepareCsvFileInput(path, options);
81
- using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
82
- const validator = strictSchemaValidator(options);
83
- for await (const chunk of input.chunks()) {
84
- const batch = parser.writeBatch(chunk);
85
- try {
86
- validator?.validateBatch(batch);
87
- const rows = batch.rowsInto([], options.columns);
88
- if (rows.length > 0)
89
- yield rows;
90
- } finally {
91
- batch.close();
92
- }
93
- }
94
- const batch = parser.endBatch();
95
- try {
96
- validator?.validateBatch(batch);
97
- validator?.finish();
98
- const rows = batch.rowsInto([], options.columns);
99
- if (rows.length > 0)
100
- yield rows;
101
- } finally {
102
- batch.close();
103
- }
77
+ using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
78
+ for await (using batch of parseFileChunks(input, parser, options.limit))
79
+ yield batch.rowsInto([], options.columns);
104
80
  }
105
81
  export function parseCsvFileProjected(path, options = {}) {
106
- return iterateCsvFileProjected(path, snapshotCsvOptions(options));
82
+ rejectSelectedColumns(options);
83
+ return iterateCsvFileProjected(path, snapshotCsvOptions({
84
+ encoding: options.encoding,
85
+ delimiter: options.delimiter,
86
+ compression: options.compression,
87
+ chunkSize: options.chunkSize,
88
+ columns: options.columns,
89
+ equalsFilter: options.equalsFilter,
90
+ filters: options.filters,
91
+ fixedColumns: options.fixedColumns,
92
+ skipRows: options.skipRows,
93
+ limit: options.limit,
94
+ strict: options.strict,
95
+ expectedHeaders: options.expectedHeaders,
96
+ requireHeader: options.requireHeader,
97
+ minDataRows: options.minDataRows
98
+ }));
107
99
  }
108
100
  async function* iterateCsvFileProjected(path, options) {
109
101
  rejectStrictSchemaUnsupported(options, "projected file parsing");
110
102
  await using input = await prepareCsvFileInput(path, options);
111
- using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter }, options.columns, projectionFilterProgram(options), !0);
112
- for await (const chunk of input.chunks()) {
113
- const batch = parser.writeBatch(chunk);
114
- try {
115
- const rows = batch.rows();
116
- if (rows.length > 0)
117
- yield rows;
118
- } finally {
119
- batch.close();
120
- }
121
- }
122
- const batch = parser.endBatch();
123
- try {
124
- const rows = batch.rows();
125
- if (rows.length > 0)
126
- yield rows;
127
- } finally {
128
- batch.close();
129
- }
103
+ if (options.strict === !0)
104
+ throw Error("strict CSV validation is not supported for projected batches");
105
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
106
+ for await (using batch of parseFileChunks(input, parser, options.limit))
107
+ yield batch.rows();
130
108
  }
131
109
  export async function countCsvFile(path, suppliedOptions = {}) {
132
110
  const options = snapshotCsvOptions(suppliedOptions);
133
111
  rejectStrictSchemaUnsupported(options, "count");
134
112
  await using input = await prepareCsvFileInput(path, options, "count");
135
- using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
136
- let rows = 0;
137
- if (options.strict === !0) {
138
- for await (const chunk of input.chunks()) {
139
- const batch = parser.writeBatch(chunk);
140
- try {
141
- rows += batch.rowCount;
142
- } finally {
143
- batch.close();
144
- }
145
- }
146
- const batch = parser.endBatch();
147
- try {
148
- rows += batch.rowCount;
149
- } finally {
150
- batch.close();
151
- }
152
- return rows;
153
- }
154
- for await (const chunk of input.chunks())
155
- rows += parser.writeCount(chunk);
156
- rows += parser.endCount();
157
- return rows;
113
+ using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
114
+ return await countFileChunks(input, parser, options);
158
115
  }
package/dist/filter.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import type { CsvNativeFilterProgramEntry } from './normalize.js';
2
- import type { CsvFilter, CsvFilterColumn, CsvRegex } from './types.js';
1
+ import type { CsvFilter, CsvFilterColumn, CsvNativeFilterProgramEntry, CsvRegex } from './types.js';
3
2
  /**
4
3
  * Select a reusable zero-based physical CSV column for building native filters.
5
4
  *
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
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';
1
+ export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterOperator, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
2
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';
@@ -1,12 +1,22 @@
1
- import type { CsvFileProbe } from './file-stream.js';
1
+ interface InspectionOptions {
2
+ readonly zipEntry?: string;
3
+ readonly delimiter?: string;
4
+ readonly encoding?: string;
5
+ }
2
6
  interface FileInspection {
3
- size: number;
7
+ fileSizeBytes: number;
8
+ sampleBytes: number;
9
+ sampleReachedEof: boolean;
4
10
  compression: Bun.CompressionFormat | 'zip' | 'none';
5
- encoding: ReturnType<CsvFileProbe>['encoding'];
6
- delimiter: string | undefined;
11
+ zipEntry: string | null;
12
+ encoding: string;
13
+ encodingSource: 'explicit' | 'inferred';
14
+ delimiter: string | null;
15
+ delimiterSource: 'explicit' | 'inferred' | null;
16
+ delimiterReason: string | null;
7
17
  lineEnding: string;
8
- firstRecordColumns: number | undefined;
18
+ firstRecordColumns: number | null;
9
19
  }
10
20
  /** 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>;
21
+ export declare function inspectCsvFile(path: string, options?: InspectionOptions): Promise<FileInspection>;
12
22
  export {};
@@ -7,42 +7,50 @@ import {
7
7
  isZipSignature,
8
8
  readCsvFileChunks,
9
9
  scanCsvFileFormat,
10
+ scanDelimiterCounts,
10
11
  selectDelimiter
11
12
  } from "./file-stream.js";
12
- export async function inspectCsvFile(path, zipEntry) {
13
+ import { resolveInputEncoding } from "./normalize.js";
14
+ import { NativeZipReader } from "./zip-reader.js";
15
+ export async function inspectCsvFile(path, options = {}) {
13
16
  const info = await stat(path);
14
17
  if (!info.isFile())
15
18
  throw Error("probe requires a regular file");
16
19
  const raw = await Bun.file(path).slice(0, FILE_PROBE_SIZE + 1).bytes();
17
20
  const zip = isZipSignature(raw);
18
- if (zipEntry !== void 0 && !zip)
21
+ if (options.zipEntry !== void 0 && !zip)
19
22
  throw Error("--zip-entry requires a ZIP archive");
20
- let compression = zip ? { format: "zip", entry: zipEntry ?? "*" } : compressionFromPrefix(path, raw);
23
+ let compression = zip ? "zip" : compressionFromPrefix(path, raw) ?? "none";
24
+ let zipEntry = null;
21
25
  let sample = raw;
22
- if (compression !== void 0)
26
+ if (compression === "zip") {
27
+ using reader = new NativeZipReader(path, { format: "zip", entry: options.zipEntry ?? "*" });
28
+ zipEntry = reader.entryName;
29
+ sample = await readCompressedSample(reader.chunks(FILE_PROBE_SIZE + 1));
30
+ } else if (compression !== "none")
23
31
  try {
24
- sample = await readCompressedSample(path, compression);
32
+ sample = await readCompressedSample(readCsvFileChunks(path, { compression, chunkSize: FILE_PROBE_SIZE + 1 }));
25
33
  } catch (error) {
26
34
  if (compression !== "deflate" || compressionFromExtension(path) !== void 0 || !(error instanceof TypeError) || raw.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
27
35
  throw error;
28
- compression = void 0;
36
+ compression = "none";
29
37
  }
30
38
  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;
39
+ const prefix = sample.subarray(0, FILE_PROBE_SIZE);
40
+ const format = inspectFormat(zipEntry ?? path, prefix, eof, options.encoding ?? "auto", options.delimiter ?? "auto");
34
41
  return {
35
- size: info.size,
36
- compression: typeof compression === "object" ? "zip" : compression ?? "none",
37
- encoding,
38
- delimiter,
39
- ...inspectRecords(bytes, eof, delimiter)
42
+ fileSizeBytes: info.size,
43
+ sampleBytes: prefix.byteLength,
44
+ sampleReachedEof: eof,
45
+ compression,
46
+ zipEntry,
47
+ ...format
40
48
  };
41
49
  }
42
- async function readCompressedSample(path, compression) {
50
+ async function readCompressedSample(chunks) {
43
51
  const sample = new Uint8Array(FILE_PROBE_SIZE + 1);
44
52
  let length = 0;
45
- for await (const chunk of readCsvFileChunks(path, { compression, chunkSize: sample.length })) {
53
+ for await (const chunk of chunks) {
46
54
  const take = Math.min(chunk.length, sample.length - length);
47
55
  sample.set(chunk.subarray(0, take), length);
48
56
  length += take;
@@ -51,6 +59,48 @@ async function readCompressedSample(path, compression) {
51
59
  }
52
60
  return sample.subarray(0, length);
53
61
  }
62
+ function inspectFormat(path, prefix, eof, encoding, delimiter) {
63
+ let bytes = prefix;
64
+ let counts;
65
+ const encodingSource = encoding === "auto" ? "inferred" : "explicit";
66
+ if (encoding === "auto") {
67
+ const sample = scanCsvFileFormat(prefix, eof, !0);
68
+ bytes = sample.bytes;
69
+ counts = sample.counts;
70
+ encoding = sample.encoding;
71
+ } else {
72
+ const decoder = resolveInputEncoding(encoding, delimiter);
73
+ if (typeof decoder === "string")
74
+ encoding = decoder;
75
+ else {
76
+ bytes = new TextEncoder().encode(decoder.decode(prefix, { stream: !eof }));
77
+ encoding = decoder.encoding;
78
+ }
79
+ }
80
+ const choice = delimiter === "auto" ? inspectDelimiter(path, bytes, eof, counts, prefix.length) : { delimiter, delimiterSource: "explicit", delimiterReason: null };
81
+ return { encoding, encodingSource, ...choice, ...inspectRecords(bytes, eof, choice.delimiter) };
82
+ }
83
+ function inspectDelimiter(path, bytes, eof, counts, sampleBytes) {
84
+ const rows = counts ?? scanDelimiterCounts(bytes, eof);
85
+ const choice = selectDelimiter(path, rows);
86
+ if ("delimiter" in choice)
87
+ return { delimiter: choice.delimiter, delimiterSource: "inferred", delimiterReason: null };
88
+ let reason;
89
+ switch (choice.reason) {
90
+ case "no-records":
91
+ reason = sampleBytes === 0 ? "Empty payload" : eof ? "No complete non-empty record in the payload" : "No complete non-empty record in the 64 KiB sample";
92
+ break;
93
+ case "no-stable-separator": {
94
+ const perRecord = counts === void 0 ? rows : scanDelimiterCounts(bytes, eof);
95
+ reason = perRecord.some((row) => row.some((count) => count > 0)) ? "Separator counts vary across sampled records" : "No supported separator found in sampled records";
96
+ break;
97
+ }
98
+ case "ambiguous":
99
+ reason = `Ambiguous between ${choice.candidates.map((c) => JSON.stringify(c)).join(" and ")}`;
100
+ break;
101
+ }
102
+ return { delimiter: null, delimiterSource: null, delimiterReason: reason };
103
+ }
54
104
  function inspectRecords(bytes, eof, delimiter) {
55
105
  const separator = delimiter?.charCodeAt(0);
56
106
  const endings = new Set;
@@ -82,7 +132,7 @@ function inspectRecords(bytes, eof, delimiter) {
82
132
  }
83
133
  const firstComplete = !firstRecord || eof && !quoted;
84
134
  return {
85
- firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns : void 0,
135
+ firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns : null,
86
136
  lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown")
87
137
  };
88
138
  }
@@ -1,5 +1,4 @@
1
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>;
2
+ import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow } from './types.js';
3
+ export declare function latin1Rows(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[], options?: CsvParserOptions): AsyncGenerator<CsvRow[], void>;
5
4
  export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
@@ -12,9 +12,10 @@ import {
12
12
  import { normalizeChunk } from "./normalize.js";
13
13
  import {
14
14
  nativeCsvParserFinalizer,
15
- prepareNativeParser
15
+ prepareNativeParser,
16
+ setRowSelection
16
17
  } from "./parser.js";
17
- export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows) {
18
+ export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
18
19
  if (delimiter === "auto")
19
20
  throw Error("automatic delimiter detection is only supported by file APIs");
20
21
  if (delimiter.length !== 1)
@@ -25,13 +26,22 @@ export async function* latin1Rows(chunks, delimiter, columns, filters, createPar
25
26
  const lifetime = {};
26
27
  nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
27
28
  try {
29
+ setRowSelection(parser, options);
28
30
  const prepared = prepareNativeParser(parser, columns, filters);
31
+ let remaining = options.limit;
32
+ if (remaining === 0)
33
+ return;
29
34
  for await (const chunk of chunks) {
30
35
  const input = normalizeChunk(chunk);
31
36
  const batch = prepared.writeBatch(input, !1);
32
37
  const rows = consumeLatin1Batch(parser, batch, reusableRows);
33
- if (rows.length > 0)
38
+ if (rows.length > 0) {
39
+ if (remaining !== void 0)
40
+ remaining -= rows.length;
34
41
  yield rows;
42
+ if (remaining === 0)
43
+ return;
44
+ }
35
45
  }
36
46
  const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
37
47
  const rows = consumeLatin1Batch(parser, batch, reusableRows);