@konstit/csv 0.5.1 → 0.6.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.
Files changed (41) hide show
  1. package/README.md +34 -1
  2. package/THIRD_PARTY_NOTICES.md +99 -0
  3. package/dist/api.d.ts +16 -9
  4. package/dist/api.js +40 -20
  5. package/dist/batches.d.ts +21 -0
  6. package/dist/batches.js +154 -20
  7. package/dist/cli-command.js +107 -2
  8. package/dist/cli-schema.d.ts +4 -0
  9. package/dist/cli-schema.js +11 -1
  10. package/dist/file-stream.d.ts +10 -6
  11. package/dist/file-stream.js +97 -47
  12. package/dist/files.js +3 -2
  13. package/dist/filter.d.ts +2 -2
  14. package/dist/filter.js +2 -0
  15. package/dist/gzip-reader.d.ts +2 -0
  16. package/dist/gzip-reader.js +37 -0
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +1 -1
  19. package/dist/latin1-rows.d.ts +3 -2
  20. package/dist/latin1-rows.js +52 -12
  21. package/dist/materialize-field.d.ts +1 -0
  22. package/dist/materialize-field.js +10 -1
  23. package/dist/native.d.ts +55 -3
  24. package/dist/native.js +27 -3
  25. package/dist/normalize.d.ts +2 -1
  26. package/dist/normalize.js +7 -0
  27. package/dist/options-snapshot.d.ts +2 -2
  28. package/dist/options-snapshot.js +2 -0
  29. package/dist/parser.d.ts +9 -6
  30. package/dist/parser.js +64 -11
  31. package/dist/transforms.d.ts +11 -0
  32. package/dist/transforms.js +192 -0
  33. package/dist/types.d.ts +64 -9
  34. package/package.json +1 -1
  35. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  36. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  37. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  38. package/prebuilds/manifest.json +17 -8
  39. package/prebuilds/provenance/darwin-arm64.json +1 -1
  40. package/prebuilds/provenance/darwin-x64.json +1 -1
  41. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -5,7 +5,11 @@ import {
5
5
  } from "./cli-schema.js";
6
6
  import { formatBytes } from "./format-bytes.js";
7
7
  import { inspectCsvFile } from "./inspect-file.js";
8
- import { normalizeFilterColumn } from "./normalize.js";
8
+ import {
9
+ normalizeFilterColumn,
10
+ validateRegex
11
+ } from "./normalize.js";
12
+ import { snapshotTransforms } from "./transforms.js";
9
13
  const MAX_FILTER_NESTING = 128;
10
14
  const OUTPUT_BUFFER_SIZE = 65536;
11
15
  export async function runCli(arguments_, customOutput) {
@@ -82,7 +86,7 @@ async function runCount(args, output) {
82
86
  async function runLines(args, output) {
83
87
  let options;
84
88
  try {
85
- options = { ...parseCommonOptions(args), limit: args.limit };
89
+ options = { ...parseCommonOptions(args), limit: args.limit, transform: parseTransformOptions(args) };
86
90
  } catch (error) {
87
91
  return usageError(output, error instanceof Error ? error.message : String(error), "csv lines --help");
88
92
  }
@@ -166,6 +170,104 @@ function serializeCsvField(field, delimiter) {
166
170
  function isBrokenPipe(error) {
167
171
  return isObject(error) && error.code === "EPIPE";
168
172
  }
173
+ function parseTransformOptions(args) {
174
+ const transforms = [];
175
+ for (const [index, { key, value }] of args.transform.entries()) {
176
+ const label = `--transform[${index}]`;
177
+ const columns = key.split(",").map((column) => {
178
+ if (!/^[0-9]+$/.test(column))
179
+ throw Error(`${label} must start with comma-separated decimal column indexes`);
180
+ return parseColumnIndex(column, `${label} column`);
181
+ });
182
+ const steps = value.split(",").map((op) => {
183
+ if (!isCleanupTransform(op))
184
+ throw Error(`${label} expected trim, upper, lower, or unaccent, got ${JSON.stringify(op)}`);
185
+ return { op };
186
+ });
187
+ transforms.push(parseTransformChain({ columns, steps }, label));
188
+ }
189
+ const json = args["transform-json"];
190
+ if (json !== void 0) {
191
+ if (!Array.isArray(json))
192
+ throw Error("--transform-json must be a JSON array of chains");
193
+ for (const [index, chain] of json.entries())
194
+ transforms.push(parseTransformChain(chain, `--transform-json[${index}]`));
195
+ }
196
+ return transforms.length === 0 ? void 0 : snapshotTransforms(transforms);
197
+ }
198
+ function parseTransformChain(value, label) {
199
+ if (!isObject(value))
200
+ throw Error(`${label} must be an object with columns and steps`);
201
+ requireExactKeys(value, ["columns", "steps"], label);
202
+ const { columns, steps } = value;
203
+ if (!Array.isArray(columns))
204
+ throw Error(`${label}.columns must be a non-empty array of column indexes`);
205
+ const [first, ...rest] = columns.map((column, index) => {
206
+ if (typeof column !== "number")
207
+ throw Error(`${label}.columns[${index}] must be a number`);
208
+ return column;
209
+ });
210
+ if (first === void 0)
211
+ throw Error(`${label}.columns must be a non-empty array of column indexes`);
212
+ if (!Array.isArray(steps) || steps.length === 0)
213
+ throw Error(`${label}.steps must be a non-empty array`);
214
+ let chain = parseTransformStep(csv.transform(), steps[0], `${label}.steps[0]`);
215
+ for (let index = 1;index < steps.length; ++index)
216
+ chain = parseTransformStep(chain, steps[index], `${label}.steps[${index}]`);
217
+ return chain.on(first, ...rest);
218
+ }
219
+ function isCleanupTransform(op) {
220
+ return op === "trim" || op === "upper" || op === "lower" || op === "unaccent";
221
+ }
222
+ function parseTransformStep(chain, step, label) {
223
+ if (!isObject(step))
224
+ throw Error(`${label} must be an object with an op property`);
225
+ const op = requireString(step.op, `${label}.op`);
226
+ if (isCleanupTransform(op)) {
227
+ requireExactKeys(step, ["op"], label);
228
+ return chain[op]();
229
+ }
230
+ switch (op) {
231
+ case "replace": {
232
+ requireExactKeys(step, ["op", "search", "replacement"], label);
233
+ const search = step.search;
234
+ const replacement = requireString(step.replacement, `${label}.replacement`);
235
+ if (!isObject(search))
236
+ return chain.replace(requireString(search, `${label}.search`), replacement);
237
+ const searchLabel = `${label}.search`;
238
+ requireExactKeys(search, ["source", "flags"], searchLabel, !0);
239
+ const source = requireString(search.source, `${searchLabel}.source`);
240
+ const flags = optionalString(search.flags, `${searchLabel}.flags`);
241
+ let regex;
242
+ try {
243
+ regex = new RegExp(source, flags);
244
+ validateRegex({ source: regex.source, flags: regex.flags.replace("g", "") });
245
+ } catch (error) {
246
+ throw Error(`${searchLabel}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
247
+ }
248
+ return chain.replace(regex, replacement);
249
+ }
250
+ case "map": {
251
+ requireExactKeys(step, ["op", "values", "defaultValue"], label, !0);
252
+ const values = step.values;
253
+ if (!isObject(values))
254
+ throw Error(`${label}.values must be an object of strings`);
255
+ const mapping = new Map;
256
+ for (const [key, value] of Object.entries(values))
257
+ mapping.set(key, requireString(value, `${label}.values[${JSON.stringify(key)}]`));
258
+ return chain.map(mapping, optionalString(step.defaultValue, `${label}.defaultValue`));
259
+ }
260
+ case "date": {
261
+ requireExactKeys(step, ["op", "format", "defaultValue"], label, !0);
262
+ const format = step.format;
263
+ if (format !== "YYYY-MM-DD" && format !== "DD-MM-YYYY" && format !== "DD/MM/YYYY")
264
+ throw Error(`${label}.format must be YYYY-MM-DD, DD-MM-YYYY, or DD/MM/YYYY`);
265
+ return chain.date(format, optionalString(step.defaultValue, `${label}.defaultValue`));
266
+ }
267
+ default:
268
+ throw Error(`${label}.op is an unknown transform: ${JSON.stringify(op)}`);
269
+ }
270
+ }
169
271
  function parseWhereOptions(values) {
170
272
  const filters = [];
171
273
  if (values.where !== void 0)
@@ -297,6 +399,9 @@ function requireString(value, label) {
297
399
  throw Error(`${label} must be a string`);
298
400
  return value;
299
401
  }
402
+ function optionalString(value, label) {
403
+ return value === void 0 ? void 0 : requireString(value, label);
404
+ }
300
405
  function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
301
406
  const keys = Object.keys(value);
302
407
  const unknownKey = keys.find((key) => !allowedKeys.includes(key));
@@ -49,6 +49,8 @@ declare const lines: import("@konstit/cli").HandledCommand<"lines", {
49
49
  json: boolean;
50
50
  "output-delimiter": string;
51
51
  limit: number | undefined;
52
+ transform: readonly import("@konstit/cli").KeyValuePair[];
53
+ "transform-json": unknown;
52
54
  }, {}, false, "filters" | "zip-limits" | "schema">;
53
55
  export type CountArguments = Infer<typeof count>;
54
56
  export type LinesArguments = Infer<typeof lines>;
@@ -111,6 +113,8 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
111
113
  json: boolean;
112
114
  "output-delimiter": string;
113
115
  limit: number | undefined;
116
+ transform: readonly import("@konstit/cli").KeyValuePair[];
117
+ "transform-json": unknown;
114
118
  }, {}, false, "filters" | "zip-limits" | "schema">;
115
119
  probe: import("@konstit/cli").HandledCommand<"probe", {
116
120
  path: string;
@@ -194,6 +194,15 @@ const lines = command("lines", {
194
194
  option("limit", rowCount, {
195
195
  valueName: "N",
196
196
  describe: "Emit at most N matching records (0 emits none)"
197
+ }),
198
+ option("transform", parsers.keyValue, {
199
+ repeatable: !0,
200
+ valueName: "COLUMNS=STEPS",
201
+ describe: "Apply comma-separated trim, upper, lower, or unaccent steps to zero-based input columns"
202
+ }),
203
+ option("transform-json", parsers.json(), {
204
+ valueName: "JSON",
205
+ describe: "Apply an array of column transform chains, including replace, map, and date"
197
206
  })
198
207
  ],
199
208
  afterHelp: `${fileHelp}
@@ -203,7 +212,8 @@ Header and minimum data row checks apply to the consumed input prefix.
203
212
 
204
213
  Examples:
205
214
  csv lines data.csv --json --skip-rows 1 --limit 10
206
- csv lines data.csv --columns 0,2 --where-eq 3=active`
215
+ csv lines data.csv --columns 0,2 --where-eq 3=active
216
+ csv lines data.csv --skip-rows 1 --transform '1,2=trim,upper'`
207
217
  });
208
218
  const probe = command("probe", {
209
219
  about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
@@ -21,6 +21,9 @@ export declare const DELIMITER_CANDIDATES: readonly [{
21
21
  }, {
22
22
  readonly byte: 126;
23
23
  readonly delimiter: "~";
24
+ }, {
25
+ readonly byte: 64;
26
+ readonly delimiter: "@";
24
27
  }];
25
28
  interface CompressionExtensionHint {
26
29
  extension: string;
@@ -33,27 +36,28 @@ export interface CsvFileInput extends AsyncDisposable {
33
36
  readonly parserEncoding: 'utf8' | 'latin1';
34
37
  chunks(): AsyncIterable<Uint8Array>;
35
38
  }
36
- export type CsvFileProbe = (path: string, prefix: Uint8Array, sourceEnded: boolean, delimiter: CsvDelimiter) => {
39
+ type ProbeDialect = Pick<CsvFileOptions, 'quote' | 'recordDelimiter'>;
40
+ export type CsvFileProbe = (path: string, prefix: Uint8Array, sourceEnded: boolean, delimiter: CsvDelimiter, dialect?: ProbeDialect) => {
37
41
  delimiter: CsvDelimiter;
38
42
  encoding: 'utf8' | 'latin1' | 'windows-1252' | 'utf-16le' | 'utf-16be';
39
43
  skipBytes: number;
40
44
  };
41
45
  type FileReadMode = 'stream' | 'parse' | 'read-ahead' | 'count';
42
- export declare function prepareCsvFileInput(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter' | 'encoding'>, readMode?: FileReadMode, probeFormat?: CsvFileProbe): Promise<CsvFileInput>;
46
+ export declare function prepareCsvFileInput(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter' | 'encoding'> & ProbeDialect, readMode?: FileReadMode, probeFormat?: CsvFileProbe): Promise<CsvFileInput>;
43
47
  export declare function readCsvFileChunks(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression'>, readMode?: FileReadMode): AsyncIterable<Uint8Array>;
44
48
  export declare function rejectCompressedSharding(options: Pick<CsvFileOptions, 'compression'>, operation: string): void;
45
49
  export declare function rejectAutoDelimiterSharding(options: Pick<CsvFileOptions, 'delimiter'>, operation: string): void;
46
- export declare function detectDelimiter(path: string, probe: Uint8Array, sourceEnded: boolean): CsvDelimiter;
50
+ export declare function detectDelimiter(path: string, probe: Uint8Array, sourceEnded: boolean, dialect?: ProbeDialect): CsvDelimiter;
47
51
  /** Detect the encoding and, when requested, score delimiters on the same prefix. */
48
52
  export declare const probeCsvFileFormat: CsvFileProbe;
49
53
  interface CsvFormatSample {
50
54
  bytes: Uint8Array;
51
55
  encoding: ReturnType<CsvFileProbe>['encoding'];
52
56
  skipBytes: number;
53
- counts: readonly Uint32Array[];
57
+ counts: readonly (Uint32Array | number[])[];
54
58
  }
55
59
  /** When scoring delimiters, structural bytes exclude the BOM and use UTF-8 for UTF-16 input. */
56
- export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean): CsvFormatSample;
60
+ export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean, dialect?: ProbeDialect): CsvFormatSample;
57
61
  type DelimiterChoice = {
58
62
  delimiter: CsvDelimiter;
59
63
  } | {
@@ -63,7 +67,7 @@ type DelimiterChoice = {
63
67
  candidates: readonly CsvDelimiter[];
64
68
  };
65
69
  export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): DelimiterChoice;
66
- export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
70
+ export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean, { quote, recordDelimiter }?: ProbeDialect): number[][];
67
71
  export declare function isZipSignature(prefix: Uint8Array): boolean;
68
72
  export declare function compressionFromPrefix(path: string, prefix: Uint8Array): Bun.CompressionFormat | undefined;
69
73
  export declare function compressionFromExtension(path: string): CompressionExtensionHint | undefined;
@@ -10,12 +10,16 @@ import {
10
10
  constants,
11
11
  inflateSync
12
12
  } from "node:zlib";
13
+ import { readGzipFileChunks } from "./gzip-reader.js";
13
14
  import {
14
15
  DEFAULT_CHUNK_SIZE,
15
16
  EMPTY_BUFFER,
16
17
  native
17
18
  } from "./native.js";
18
- import { resolveInputEncoding } from "./normalize.js";
19
+ import {
20
+ resolveInputEncoding,
21
+ validateCsvDialect
22
+ } from "./normalize.js";
19
23
  import { snapshotCsvOptions } from "./options-snapshot.js";
20
24
  import { readZipEntryChunks } from "./zip-reader.js";
21
25
  export const FILE_PROBE_SIZE = 65536;
@@ -28,7 +32,8 @@ export const DELIMITER_CANDIDATES = [
28
32
  { byte: 124, delimiter: "|" },
29
33
  { byte: 58, delimiter: ":" },
30
34
  { byte: 94, delimiter: "^" },
31
- { byte: 126, delimiter: "~" }
35
+ { byte: 126, delimiter: "~" },
36
+ { byte: 64, delimiter: "@" }
32
37
  ];
33
38
  const COMPRESSION_EXTENSIONS = [
34
39
  ".deflate-raw",
@@ -43,6 +48,7 @@ const COMPRESSION_EXTENSIONS = [
43
48
  ];
44
49
  export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
45
50
  const options = snapshotCsvOptions(suppliedOptions);
51
+ validateCsvDialect(options);
46
52
  const autoEncoding = options.encoding === void 0 || options.encoding === "auto";
47
53
  const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, options.delimiter);
48
54
  const parserEncoding = typeof inputEncoding === "string" ? inputEncoding : "utf8";
@@ -69,7 +75,7 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
69
75
  }
70
76
  const iterator = source()[Symbol.asyncIterator]();
71
77
  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));
78
+ const reusesReadBuffer = typeof inputEncoding === "string" && (readMode !== "stream" && (compression === "auto" || compression === "gzip") || readMode === "read-ahead" && compression === "none" || isZipCompression(compression) && useZipReadAhead(readMode, options.chunkSize ?? DEFAULT_CHUNK_SIZE));
73
79
  const bufferedChunks = [];
74
80
  let bufferedByteLength = 0;
75
81
  let sourceEnded = !1;
@@ -90,8 +96,8 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
90
96
  }
91
97
  const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
92
98
  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);
99
+ const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter, options) : void 0;
100
+ const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded, options);
95
101
  const replayEncoding = format === void 0 ? parserEncoding : resolveInputEncoding(format.encoding, delimiter);
96
102
  let skip = format?.skipBytes ?? 0;
97
103
  if (skip > 0)
@@ -123,10 +129,16 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
123
129
  }
124
130
  }
125
131
  async function* readAheadFileChunks(path, chunkSize) {
132
+ validateReadAheadChunkSize(chunkSize);
133
+ await using file = await open(path, "r");
134
+ yield* readAheadOpenFileChunks(file, chunkSize, (await file.stat()).isFile());
135
+ }
136
+ function validateReadAheadChunkSize(chunkSize) {
126
137
  if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
127
138
  throw RangeError("chunkSize must be a positive safe integer");
128
- await using file = await open(path, "r");
129
- if (!(await file.stat()).isFile()) {
139
+ }
140
+ async function* readAheadOpenFileChunks(file, chunkSize, regularFile) {
141
+ if (!regularFile) {
130
142
  const buffer = Buffer.allocUnsafe(chunkSize);
131
143
  let { bytesRead } = await file.read(buffer);
132
144
  while (bytesRead > 0) {
@@ -153,11 +165,12 @@ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
153
165
  const zipReadAhead = useZipReadAhead(readMode, chunkSize);
154
166
  if (isZipCompression(compression))
155
167
  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
- }
168
+ if (compression === "auto")
169
+ return readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead);
170
+ if (compression === "none")
171
+ return readMode === "read-ahead" ? readAheadFileChunks(path, chunkSize) : createReadStream(path, { highWaterMark: chunkSize });
172
+ if (compression === "gzip")
173
+ return readGzipPathChunks(path, chunkSize, readMode !== "stream");
161
174
  return decompressedCsvFileChunks(path, compression, chunkSize);
162
175
  }
163
176
  function isZipCompression(compression) {
@@ -233,14 +246,14 @@ function copyProbePrefix(chunks, totalByteLength) {
233
246
  }
234
247
  return probe;
235
248
  }
236
- export function detectDelimiter(path, probe, sourceEnded) {
237
- return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded));
249
+ export function detectDelimiter(path, probe, sourceEnded, dialect) {
250
+ return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded, dialect));
238
251
  }
239
- export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter) => {
240
- const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto");
252
+ export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter, dialect) => {
253
+ const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto", dialect);
241
254
  return { encoding, delimiter: delimiter === "auto" ? requireDelimiter(path, counts) : delimiter, skipBytes };
242
255
  };
243
- export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
256
+ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters, dialect) {
244
257
  let bytes = prefix;
245
258
  let bomEncoding;
246
259
  let skipBytes = 0;
@@ -262,12 +275,15 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
262
275
  bytes = new TextEncoder().encode(text);
263
276
  }
264
277
  }
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));
278
+ const customDialect = scoreDelimiters && (dialect?.quote === !1 || dialect?.recordDelimiter !== void 0);
279
+ const counts = scoreDelimiters && !customDialect ? new Uint32Array(DELIMITER_CANDIDATES.length + 1) : void 0;
280
+ const encodingCode = native.symbols.csv_probe_format_v2(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
267
281
  const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
268
282
  if (encoding === void 0)
269
283
  throw Error("NUL in encoding probe: specify the encoding explicitly");
270
- return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[7] === 0 ? [] : [counts] };
284
+ if (customDialect)
285
+ return { bytes, encoding, skipBytes, counts: scanDelimiterCounts(bytes, sourceEnded, dialect) };
286
+ return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[DELIMITER_CANDIDATES.length] === 0 ? [] : [counts] };
271
287
  }
272
288
  function requireDelimiter(path, rows) {
273
289
  const result = selectDelimiter(path, rows);
@@ -286,18 +302,21 @@ export function selectDelimiter(path, rows) {
286
302
  if (rows.length === 0)
287
303
  return { reason: "no-records" };
288
304
  const stableCandidates = [];
305
+ let hasStableAtSign = !1;
289
306
  for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
290
307
  const separatorCount = rows[0]?.[candidateIndex] ?? 0;
291
308
  if (separatorCount === 0)
292
309
  continue;
293
310
  if (rows.every((row) => row[candidateIndex] === separatorCount)) {
294
311
  const candidate = DELIMITER_CANDIDATES[candidateIndex];
295
- if (candidate !== void 0)
312
+ if (candidate?.delimiter === "@")
313
+ hasStableAtSign = !0;
314
+ else if (candidate !== void 0)
296
315
  stableCandidates.push({ delimiter: candidate.delimiter, separatorCount });
297
316
  }
298
317
  }
299
318
  if (stableCandidates.length === 0)
300
- return { reason: "no-stable-separator" };
319
+ return hasStableAtSign ? { delimiter: "@" } : { reason: "no-stable-separator" };
301
320
  const extensionHint = delimiterFromExtension(path);
302
321
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
303
322
  if (confirmedHint !== void 0)
@@ -308,14 +327,14 @@ export function selectDelimiter(path, rows) {
308
327
  return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
309
328
  return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
310
329
  }
311
- export function scanDelimiterCounts(probe, sourceEnded) {
330
+ export function scanDelimiterCounts(probe, sourceEnded, { quote = !0, recordDelimiter } = {}) {
312
331
  const rows = [];
313
332
  let counts = Array.from({ length: DELIMITER_CANDIDATES.length }, () => 0);
314
333
  let inQuotes = !1;
315
334
  let rowHasContent = !1;
316
335
  for (let index = 0;index < probe.byteLength; ++index) {
317
336
  const byte = probe[index];
318
- if (byte === 34) {
337
+ if (quote && byte === 34) {
319
338
  rowHasContent = !0;
320
339
  if (inQuotes && probe[index + 1] === 34) {
321
340
  ++index;
@@ -324,7 +343,7 @@ export function scanDelimiterCounts(probe, sourceEnded) {
324
343
  inQuotes = !inQuotes;
325
344
  continue;
326
345
  }
327
- if (!inQuotes && (byte === 10 || byte === 13)) {
346
+ if (!inQuotes && (byte === 10 || recordDelimiter === void 0 && byte === 13)) {
328
347
  if (rowHasContent) {
329
348
  rows.push(counts);
330
349
  if (rows.length === MAX_DELIMITER_PROBE_ROWS)
@@ -367,46 +386,77 @@ function stripCompressionExtension(path) {
367
386
  return path.slice(0, -extension.length);
368
387
  return path;
369
388
  }
370
- async function* readAutoDetectedCsvFileChunks(path, raw, chunkSize, reusesBuffer, zipReadAhead) {
371
- const iterator = raw[Symbol.asyncIterator]();
389
+ async function* readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead) {
390
+ const reusesBuffer = readMode === "read-ahead";
391
+ if (reusesBuffer)
392
+ validateReadAheadChunkSize(chunkSize);
393
+ await using file = await open(path, "r");
394
+ const regularFile = (await file.stat()).isFile();
395
+ const raw = () => reusesBuffer ? readAheadOpenFileChunks(file, chunkSize, regularFile) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 });
396
+ const iterator = regularFile ? void 0 : raw()[Symbol.asyncIterator]();
372
397
  const buffered = [];
373
398
  const prefix = new Uint8Array(64);
374
399
  let length = 0;
375
- let needed = 4;
376
400
  try {
377
- while (length < needed) {
378
- const next = await iterator.next();
379
- if (next.done === !0)
380
- break;
381
- const chunk = next.value;
382
- const take = Math.min(prefix.length - length, chunk.length);
383
- prefix.set(chunk.subarray(0, take), length);
384
- length += take;
385
- if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
386
- needed = prefix.length;
387
- buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
401
+ if (iterator === void 0)
402
+ while (length < prefix.length) {
403
+ const { bytesRead } = await file.read(prefix, length, prefix.length - length, length);
404
+ if (bytesRead === 0)
405
+ break;
406
+ length += bytesRead;
407
+ }
408
+ else {
409
+ let needed = 4;
410
+ while (length < needed) {
411
+ const next = await iterator.next();
412
+ if (next.done === !0)
413
+ break;
414
+ const chunk = next.value;
415
+ const take = Math.min(prefix.length - length, chunk.length);
416
+ prefix.set(chunk.subarray(0, take), length);
417
+ length += take;
418
+ if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
419
+ needed = prefix.length;
420
+ buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
421
+ }
388
422
  }
389
423
  const sample = prefix.subarray(0, length);
390
424
  if (isZipSignature(sample)) {
391
- if (!(await stat(path)).isFile())
425
+ if (!regularFile || !(await stat(path)).isFile())
392
426
  throw Error("ZIP input requires a regular file; save the archive before reading it");
393
- await closeCsvFileIterator(iterator);
427
+ await file.close();
394
428
  yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
395
429
  return;
396
430
  }
397
431
  const compression = compressionFromPrefix(path, sample);
398
- const replay = replayCsvFileChunks(buffered, iterator);
432
+ if (compression === "gzip" && regularFile) {
433
+ yield* readGzipFileChunks(file.fd, chunkSize, readMode !== "stream");
434
+ return;
435
+ }
436
+ if (compression === void 0 && !isPlainCsvFile(path))
437
+ throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
438
+ const source = iterator === void 0 ? raw() : replayCsvFileChunks(buffered, iterator);
399
439
  if (compression === void 0) {
400
- if (!isPlainCsvFile(path))
401
- throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
402
- yield* replay;
440
+ yield* source;
403
441
  return;
404
442
  }
405
- yield* WebReadableStream.from(reusesBuffer ? copyFileChunks(replay) : replay).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
443
+ yield* decompressFileStream(reusesBuffer ? copyFileChunks(source) : source, compression, chunkSize);
406
444
  } finally {
407
- await closeCsvFileIterator(iterator);
445
+ if (iterator !== void 0)
446
+ await closeCsvFileIterator(iterator);
408
447
  }
409
448
  }
449
+ async function* readGzipPathChunks(path, chunkSize, reuseBuffer) {
450
+ await using file = await open(path, "r");
451
+ if ((await file.stat()).isFile()) {
452
+ yield* readGzipFileChunks(file.fd, chunkSize, reuseBuffer);
453
+ return;
454
+ }
455
+ yield* decompressFileStream(file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 }), "gzip", chunkSize);
456
+ }
457
+ function decompressFileStream(source, compression, chunkSize) {
458
+ return WebReadableStream.from(source).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
459
+ }
410
460
  async function* copyFileChunks(chunks) {
411
461
  for await (const chunk of chunks)
412
462
  yield new Uint8Array(chunk);
package/dist/files.js CHANGED
@@ -83,6 +83,8 @@ export function parseCsvFileProjected(path, options = {}) {
83
83
  return iterateCsvFileProjected(path, snapshotCsvOptions({
84
84
  encoding: options.encoding,
85
85
  delimiter: options.delimiter,
86
+ quote: options.quote,
87
+ recordDelimiter: options.recordDelimiter,
86
88
  compression: options.compression,
87
89
  chunkSize: options.chunkSize,
88
90
  columns: options.columns,
@@ -110,6 +112,5 @@ export async function countCsvFile(path, suppliedOptions = {}) {
110
112
  const options = snapshotCsvOptions(suppliedOptions);
111
113
  rejectStrictSchemaUnsupported(options, "count");
112
114
  await using input = await prepareCsvFileInput(path, options, "count");
113
- using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
114
- return await countFileChunks(input, parser, options);
115
+ return await countFileChunks(input, { ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
115
116
  }
package/dist/filter.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CsvFilter, CsvFilterColumn, CsvNativeFilterProgramEntry, CsvRegex } from './types.js';
1
+ import type { CsvColumn, CsvFilter, CsvNativeFilterProgramEntry, CsvRegex } from './types.js';
2
2
  /**
3
3
  * Select a reusable zero-based physical CSV column for building native filters.
4
4
  *
@@ -17,7 +17,7 @@ import type { CsvFilter, CsvFilterColumn, CsvNativeFilterProgramEntry, CsvRegex
17
17
  * const filter = state.isOneOf(['SP', 'RJ']);
18
18
  * ```
19
19
  */
20
- export declare function column(columnIndex: number): CsvFilterColumn;
20
+ export declare function column(columnIndex: number): CsvColumn;
21
21
  /**
22
22
  * Match rows for which every supplied filter matches.
23
23
  *
package/dist/filter.js CHANGED
@@ -3,10 +3,12 @@ import {
3
3
  normalizeNativeFilterProgram,
4
4
  validateRegex
5
5
  } from "./normalize.js";
6
+ import { transformMethods } from "./transforms.js";
6
7
  const nativeProgramByFilter = new WeakMap;
7
8
  export function column(columnIndex) {
8
9
  const selectedColumn = normalizeFilterColumn(columnIndex);
9
10
  return Object.freeze({
11
+ ...transformMethods(selectedColumn),
10
12
  equals: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, value: copyFieldValue(value, "equals value") })),
11
13
  doesNotEqual: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, notEquals: copyFieldValue(value, "doesNotEqual value") })),
12
14
  isOneOf: (values) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, values: copyFieldValues(values, "isOneOf values") })),
@@ -0,0 +1,2 @@
1
+ /** Read a regular file from offset zero. The native reader owns a duplicate descriptor. */
2
+ export declare function readGzipFileChunks(fd: number, chunkSize: number, reuseBuffer: boolean, readAhead?: boolean): Generator<Uint8Array, void>;
@@ -0,0 +1,37 @@
1
+ import {
2
+ native
3
+ } from "./native.js";
4
+ const gzipReaderFinalizer = new FinalizationRegistry(native.symbols.csv_gzip_reader_destroy);
5
+ export function* readGzipFileChunks(fd, chunkSize, reuseBuffer, readAhead = !0) {
6
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0 || chunkSize > 4294967295)
7
+ throw RangeError("gzip chunkSize must be a positive integer no larger than 4294967295");
8
+ const handle = native.symbols.csv_gzip_reader_create(fd);
9
+ if (handle === null)
10
+ throw Error("failed to create native gzip reader");
11
+ const lifetime = {};
12
+ gzipReaderFinalizer.register(lifetime, handle, lifetime);
13
+ try {
14
+ const reusableBuffer = reuseBuffer ? new Uint8Array(chunkSize) : void 0;
15
+ let startProducer = readAhead;
16
+ while (!0) {
17
+ const buffer = reusableBuffer ?? new Uint8Array(chunkSize);
18
+ const size = Number(native.symbols.csv_gzip_reader_read(handle, buffer, buffer));
19
+ if (size < 0) {
20
+ const message = native.symbols.csv_gzip_reader_last_error(handle)?.toString() ?? "gzip read failed";
21
+ throw TypeError(message);
22
+ }
23
+ if (size === 0)
24
+ return;
25
+ if (size > buffer.length)
26
+ throw Error("native gzip reader returned an invalid output length");
27
+ yield size === buffer.length ? buffer : buffer.subarray(0, size);
28
+ if (startProducer) {
29
+ native.symbols.csv_gzip_reader_enable_read_ahead(handle, chunkSize);
30
+ startProducer = !1;
31
+ }
32
+ }
33
+ } finally {
34
+ gzipReaderFinalizer.unregister(lifetime);
35
+ native.symbols.csv_gzip_reader_destroy(handle);
36
+ }
37
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
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';
1
+ export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumn, 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, CsvRawRecordBatchesOptions, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvTransform, CsvTransformChain, CsvTransformMethods, CsvTransformOptions, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
2
2
  export { csv } from './api.js';
3
- export { NativeCsvBatch, NativeCsvRowView } from './batches.js';
3
+ export { NativeCsvBatch, NativeCsvRawRecordBatch, NativeCsvRowView } from './batches.js';
4
4
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
5
5
  export { defineCountOptions, defineRowsOptions } from './options.js';
6
6
  export { NativeCsvParser } from './parser.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { requireBunRuntime } from "./runtime.js";
2
2
  requireBunRuntime();
3
3
  export { csv } from "./api.js";
4
- export { NativeCsvBatch, NativeCsvRowView } from "./batches.js";
4
+ export { NativeCsvBatch, NativeCsvRawRecordBatch, NativeCsvRowView } from "./batches.js";
5
5
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from "./files.js";
6
6
  export { defineCountOptions, defineRowsOptions } from "./options.js";
7
7
  export { NativeCsvParser } from "./parser.js";
@@ -1,4 +1,5 @@
1
1
  import { type NativePointer } from './native.js';
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>;
2
+ import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, CsvTransformOptions } from './types.js';
3
+ export declare function canUseFilteredLatin1Cleanup(columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, transforms: readonly CsvTransform[]): boolean;
4
+ 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?: Pick<CsvParserOptions, 'limit' | 'skipRows'> & CsvTransformOptions): AsyncGenerator<CsvRow[], void>;
4
5
  export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;