@konstit/csv 0.4.3 → 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.
- package/README.md +50 -28
- package/THIRD_PARTY_NOTICES.md +7 -1
- package/dist/api.d.ts +39 -249
- package/dist/api.js +56 -394
- package/dist/batches.d.ts +8 -57
- package/dist/batches.js +77 -52
- package/dist/cli-command.d.ts +7 -0
- package/dist/cli-command.js +315 -0
- package/dist/cli-schema.d.ts +127 -0
- package/dist/cli-schema.js +234 -0
- package/dist/cli.js +2 -604
- package/dist/file-stream.d.ts +62 -3
- package/dist/file-stream.js +242 -36
- package/dist/files.d.ts +11 -11
- package/dist/files.js +38 -79
- package/dist/filter.d.ts +5 -8
- package/dist/format-bytes.d.ts +1 -0
- package/dist/format-bytes.js +11 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -14
- package/dist/inspect-file.d.ts +22 -0
- package/dist/inspect-file.js +138 -0
- package/dist/latin1-rows.d.ts +4 -3
- package/dist/latin1-rows.js +72 -24
- package/dist/materialize-field.d.ts +2 -0
- package/dist/materialize-field.js +20 -15
- package/dist/native.d.ts +50 -78
- package/dist/native.js +36 -112
- package/dist/normalize.d.ts +14 -40
- package/dist/normalize.js +66 -64
- package/dist/options-snapshot.js +3 -2
- package/dist/options.d.ts +4 -30
- package/dist/options.js +0 -6
- package/dist/parser.d.ts +23 -209
- package/dist/parser.js +146 -261
- package/dist/strict-schema.d.ts +6 -4
- package/dist/strict-schema.js +4 -3
- package/dist/types.d.ts +119 -221
- package/dist/zip-reader.d.ts +13 -1
- package/dist/zip-reader.js +36 -17
- package/package.json +36 -33
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +9 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
- package/dist/worker-count.d.ts +0 -34
- package/dist/worker-count.js +0 -101
- package/dist/worker-factory.d.ts +0 -3
- package/dist/worker-factory.js +0 -9
- package/dist/worker-filter.d.ts +0 -29
- package/dist/worker-filter.js +0 -46
- package/dist/worker-module.d.ts +0 -1
- package/dist/worker-module.js +0 -4
- package/dist/worker-pool.d.ts +0 -93
- package/dist/worker-pool.js +0 -298
- package/dist/worker-rows.d.ts +0 -36
- package/dist/worker-rows.js +0 -127
- package/dist/workers/count.worker.d.ts +0 -1
- package/dist/workers/count.worker.js +0 -36
- package/dist/workers/rows.worker.d.ts +0 -1
- package/dist/workers/rows.worker.js +0 -56
package/dist/file-stream.js
CHANGED
|
@@ -1,11 +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 {
|
|
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";
|
|
4
19
|
import { snapshotCsvOptions } from "./options-snapshot.js";
|
|
5
20
|
import { readZipEntryChunks } from "./zip-reader.js";
|
|
6
|
-
const
|
|
21
|
+
export const FILE_PROBE_SIZE = 65536;
|
|
22
|
+
const PROBED_BYTE_ENCODINGS = ["utf8", "latin1", "windows-1252"];
|
|
7
23
|
const MAX_DELIMITER_PROBE_ROWS = 128;
|
|
8
|
-
const DELIMITER_CANDIDATES = [
|
|
24
|
+
export const DELIMITER_CANDIDATES = [
|
|
9
25
|
{ byte: 44, delimiter: "," },
|
|
10
26
|
{ byte: 9, delimiter: "\t" },
|
|
11
27
|
{ byte: 59, delimiter: ";" },
|
|
@@ -25,30 +41,41 @@ const COMPRESSION_EXTENSIONS = [
|
|
|
25
41
|
".gz",
|
|
26
42
|
".zz"
|
|
27
43
|
];
|
|
28
|
-
export async function prepareCsvFileInput(path, suppliedOptions) {
|
|
44
|
+
export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
|
|
29
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
|
+
};
|
|
30
53
|
const configuredDelimiter = options.delimiter ?? ",";
|
|
31
|
-
if (configuredDelimiter !== "auto") {
|
|
54
|
+
if (!autoEncoding && configuredDelimiter !== "auto") {
|
|
32
55
|
let opened = !1;
|
|
33
56
|
return {
|
|
34
57
|
delimiter: configuredDelimiter,
|
|
58
|
+
parserEncoding,
|
|
35
59
|
chunks() {
|
|
36
60
|
if (opened)
|
|
37
61
|
throw Error("CSV file input can only be read once");
|
|
38
62
|
opened = !0;
|
|
39
|
-
return
|
|
63
|
+
return source();
|
|
40
64
|
},
|
|
41
65
|
[Symbol.asyncDispose]() {
|
|
42
66
|
return Promise.resolve();
|
|
43
67
|
}
|
|
44
68
|
};
|
|
45
69
|
}
|
|
46
|
-
const iterator =
|
|
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));
|
|
47
73
|
const bufferedChunks = [];
|
|
48
74
|
let bufferedByteLength = 0;
|
|
49
75
|
let sourceEnded = !1;
|
|
76
|
+
let bytesNeeded = FILE_PROBE_SIZE;
|
|
50
77
|
try {
|
|
51
|
-
while (bufferedByteLength <
|
|
78
|
+
while (bufferedByteLength < bytesNeeded) {
|
|
52
79
|
const result = await iterator.next();
|
|
53
80
|
if (result.done === !0) {
|
|
54
81
|
sourceEnded = !0;
|
|
@@ -56,19 +83,35 @@ export async function prepareCsvFileInput(path, suppliedOptions) {
|
|
|
56
83
|
}
|
|
57
84
|
if (result.value.byteLength === 0)
|
|
58
85
|
continue;
|
|
59
|
-
bufferedChunks.push(result.value);
|
|
60
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);
|
|
61
90
|
}
|
|
62
91
|
const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
|
|
63
|
-
const
|
|
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
|
+
}
|
|
64
105
|
let opened = !1;
|
|
65
106
|
return {
|
|
66
107
|
delimiter,
|
|
108
|
+
parserEncoding: typeof replayEncoding === "string" ? replayEncoding : "utf8",
|
|
67
109
|
chunks() {
|
|
68
110
|
if (opened)
|
|
69
111
|
throw Error("CSV file input can only be read once");
|
|
70
112
|
opened = !0;
|
|
71
|
-
|
|
113
|
+
const replay = replayCsvFileChunks(bufferedChunks, iterator);
|
|
114
|
+
return typeof replayEncoding === "string" ? replay : transcodeCsvChunks(replay, replayEncoding);
|
|
72
115
|
},
|
|
73
116
|
[Symbol.asyncDispose]() {
|
|
74
117
|
return closeCsvFileIterator(iterator);
|
|
@@ -79,20 +122,50 @@ export async function prepareCsvFileInput(path, suppliedOptions) {
|
|
|
79
122
|
throw error;
|
|
80
123
|
}
|
|
81
124
|
}
|
|
82
|
-
|
|
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") {
|
|
83
150
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
84
151
|
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
if (isZipCompression(
|
|
88
|
-
return readZipEntryChunks(path,
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
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);
|
|
92
162
|
}
|
|
93
163
|
function isZipCompression(compression) {
|
|
94
164
|
return typeof compression === "object" && compression.format === "zip";
|
|
95
165
|
}
|
|
166
|
+
function useZipReadAhead(mode, chunkSize) {
|
|
167
|
+
return mode === "count" || mode !== "stream" && chunkSize >= 65536;
|
|
168
|
+
}
|
|
96
169
|
function delimiterHintPath(path, compression) {
|
|
97
170
|
return compression !== void 0 && isZipCompression(compression) ? compression.entry : path;
|
|
98
171
|
}
|
|
@@ -117,13 +190,38 @@ async function* replayCsvFileChunks(bufferedChunks, iterator) {
|
|
|
117
190
|
await closeCsvFileIterator(iterator);
|
|
118
191
|
}
|
|
119
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
|
+
}
|
|
120
204
|
async function closeCsvFileIterator(iterator) {
|
|
121
205
|
try {
|
|
122
206
|
await iterator.return?.();
|
|
123
207
|
} catch {}
|
|
124
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
|
+
}
|
|
125
223
|
function copyProbePrefix(chunks, totalByteLength) {
|
|
126
|
-
const probe = new Uint8Array(Math.min(totalByteLength,
|
|
224
|
+
const probe = new Uint8Array(Math.min(totalByteLength, FILE_PROBE_SIZE));
|
|
127
225
|
let offset = 0;
|
|
128
226
|
for (const chunk of chunks) {
|
|
129
227
|
if (offset === probe.byteLength)
|
|
@@ -135,10 +233,58 @@ function copyProbePrefix(chunks, totalByteLength) {
|
|
|
135
233
|
}
|
|
136
234
|
return probe;
|
|
137
235
|
}
|
|
138
|
-
function detectDelimiter(path, probe, sourceEnded) {
|
|
139
|
-
|
|
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 ("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
|
+
}
|
|
284
|
+
}
|
|
285
|
+
export function selectDelimiter(path, rows) {
|
|
140
286
|
if (rows.length === 0)
|
|
141
|
-
|
|
287
|
+
return { reason: "no-records" };
|
|
142
288
|
const stableCandidates = [];
|
|
143
289
|
for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
|
|
144
290
|
const separatorCount = rows[0]?.[candidateIndex] ?? 0;
|
|
@@ -151,16 +297,16 @@ function detectDelimiter(path, probe, sourceEnded) {
|
|
|
151
297
|
}
|
|
152
298
|
}
|
|
153
299
|
if (stableCandidates.length === 0)
|
|
154
|
-
|
|
300
|
+
return { reason: "no-stable-separator" };
|
|
155
301
|
const extensionHint = delimiterFromExtension(path);
|
|
156
302
|
const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
|
|
157
303
|
if (confirmedHint !== void 0)
|
|
158
|
-
return confirmedHint.delimiter;
|
|
304
|
+
return { delimiter: confirmedHint.delimiter };
|
|
159
305
|
const maximumSeparatorCount = Math.max(...stableCandidates.map((candidate) => candidate.separatorCount));
|
|
160
306
|
const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
|
|
161
307
|
if (strongestCandidates.length === 1)
|
|
162
|
-
return strongestCandidates[0]?.delimiter ?? ",";
|
|
163
|
-
|
|
308
|
+
return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
|
|
309
|
+
return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
|
|
164
310
|
}
|
|
165
311
|
export function scanDelimiterCounts(probe, sourceEnded) {
|
|
166
312
|
const rows = [];
|
|
@@ -221,16 +367,66 @@ function stripCompressionExtension(path) {
|
|
|
221
367
|
return path.slice(0, -extension.length);
|
|
222
368
|
return path;
|
|
223
369
|
}
|
|
224
|
-
async function* readAutoDetectedCsvFileChunks(path, chunkSize) {
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
370
|
+
async function* readAutoDetectedCsvFileChunks(path, raw, chunkSize, reusesBuffer, zipReadAhead) {
|
|
371
|
+
const iterator = raw[Symbol.asyncIterator]();
|
|
372
|
+
const buffered = [];
|
|
373
|
+
const prefix = new Uint8Array(64);
|
|
374
|
+
let length = 0;
|
|
375
|
+
let needed = 4;
|
|
376
|
+
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);
|
|
388
|
+
}
|
|
389
|
+
const sample = prefix.subarray(0, length);
|
|
390
|
+
if (isZipSignature(sample)) {
|
|
391
|
+
if (!(await stat(path)).isFile())
|
|
392
|
+
throw Error("ZIP input requires a regular file; save the archive before reading it");
|
|
393
|
+
await closeCsvFileIterator(iterator);
|
|
394
|
+
yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const compression = compressionFromPrefix(path, sample);
|
|
398
|
+
const replay = replayCsvFileChunks(buffered, iterator);
|
|
399
|
+
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;
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
yield* WebReadableStream.from(reusesBuffer ? copyFileChunks(replay) : replay).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
|
|
406
|
+
} finally {
|
|
407
|
+
await closeCsvFileIterator(iterator);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
async function* copyFileChunks(chunks) {
|
|
411
|
+
for await (const chunk of chunks)
|
|
412
|
+
yield new Uint8Array(chunk);
|
|
413
|
+
}
|
|
414
|
+
function isPlainCsvFile(path) {
|
|
415
|
+
const mime = Bun.file(path).type.split(";", 1)[0];
|
|
416
|
+
return mime === "text/csv" || mime === "text/tab-separated-values" || mime === "text/plain" || mime === "application/octet-stream" && /\.(?:psv|ssv|tab)$/i.test(path);
|
|
417
|
+
}
|
|
418
|
+
export function isZipSignature(prefix) {
|
|
419
|
+
return prefix[0] === 80 && prefix[1] === 75 && (prefix[2] === 3 && prefix[3] === 4 || prefix[2] === 5 && prefix[3] === 6);
|
|
420
|
+
}
|
|
421
|
+
function isPrintableZlibHeader(prefix) {
|
|
422
|
+
const first = prefix[0] ?? 0;
|
|
423
|
+
const second = prefix[1] ?? 0;
|
|
424
|
+
return first >= 32 && first < 127 && second >= 32 && second < 127;
|
|
228
425
|
}
|
|
229
426
|
function decompressedCsvFileChunks(path, compression, chunkSize) {
|
|
230
427
|
return Bun.file(path).stream().pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
|
|
231
428
|
}
|
|
232
|
-
|
|
233
|
-
const prefix = await Bun.file(path).slice(0, 4).bytes();
|
|
429
|
+
export function compressionFromPrefix(path, prefix) {
|
|
234
430
|
const extensionHint = compressionFromExtension(path);
|
|
235
431
|
const strongSignature = compressionFromStrongSignature(prefix);
|
|
236
432
|
if (strongSignature !== void 0) {
|
|
@@ -249,11 +445,21 @@ async function detectCompression(path) {
|
|
|
249
445
|
}
|
|
250
446
|
return extensionHint.format;
|
|
251
447
|
}
|
|
252
|
-
if (hasZlibHeader)
|
|
448
|
+
if (hasZlibHeader) {
|
|
449
|
+
const sample = prefix.subarray(0, 64);
|
|
450
|
+
if (isPrintableZlibHeader(sample) && isPlainCsvFile(path) && !sample.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
|
|
451
|
+
try {
|
|
452
|
+
inflateSync(sample, { finishFlush: sample.length < 64 ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
|
|
455
|
+
return;
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
253
458
|
return "deflate";
|
|
254
|
-
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
255
461
|
}
|
|
256
|
-
function compressionFromExtension(path) {
|
|
462
|
+
export function compressionFromExtension(path) {
|
|
257
463
|
const lowerPath = path.toLowerCase();
|
|
258
464
|
if (lowerPath.endsWith(".deflate-raw"))
|
|
259
465
|
return { extension: ".deflate-raw", format: "deflate-raw", signatureRequired: !1 };
|
package/dist/files.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
|
|
1
|
+
import type { CsvEncoding, CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Parse one complete in-memory CSV buffer into materialized rows.
|
|
4
4
|
*
|
|
5
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. `
|
|
6
|
+
* buffer but parser state is not retained after this call. `columns`
|
|
7
7
|
* projects zero-based physical columns in the returned rows. The supplied
|
|
8
8
|
* options are captured when the function is called; changing an options array
|
|
9
9
|
* while parsing cannot change the operation.
|
|
10
10
|
*
|
|
11
|
-
* Automatic delimiter detection and
|
|
11
|
+
* Automatic delimiter and encoding detection and compression are file-only features.
|
|
12
12
|
* Use an explicit one-character delimiter for in-memory input.
|
|
13
13
|
*
|
|
14
14
|
* @param buffer Complete CSV bytes to parse.
|
|
@@ -24,7 +24,7 @@ import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvR
|
|
|
24
24
|
* // rows[0] is ['id', 'name']
|
|
25
25
|
* ```
|
|
26
26
|
*/
|
|
27
|
-
export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions): CsvRow[];
|
|
27
|
+
export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions<CsvEncoding>): CsvRow[];
|
|
28
28
|
/**
|
|
29
29
|
* Count rows in bytes known to contain one record per physical line.
|
|
30
30
|
*
|
|
@@ -57,7 +57,7 @@ export declare function countTrustedNewlineRows(buffer: NodeJS.TypedArray | Data
|
|
|
57
57
|
*/
|
|
58
58
|
export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string): number[];
|
|
59
59
|
/**
|
|
60
|
-
* Return inclusive
|
|
60
|
+
* Return inclusive byte ranges that can each be read as complete CSV records.
|
|
61
61
|
*
|
|
62
62
|
* The ranges are derived from {@link findCsvSafeSplitOffsets}. Empty ranges
|
|
63
63
|
* are omitted, so a small file can produce fewer ranges than `shardCount`.
|
|
@@ -77,7 +77,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
|
|
|
77
77
|
*
|
|
78
78
|
* Each yielded value contains the rows parsed from one input chunk. Rows are
|
|
79
79
|
* ordinary strings and remain usable after the next batch is yielded. File
|
|
80
|
-
* compression and automatic delimiter detection are supported by
|
|
80
|
+
* compression and automatic delimiter and encoding detection are supported by
|
|
81
81
|
* `CsvFileOptions`.
|
|
82
82
|
*
|
|
83
83
|
* Options are snapshotted when this function is called, before iteration
|
|
@@ -85,7 +85,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
|
|
|
85
85
|
* generator to reconfigure the stream.
|
|
86
86
|
*
|
|
87
87
|
* @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
|
|
88
|
-
* @param options File and parser options. `
|
|
88
|
+
* @param options File and parser options. `columns` selects physical columns for each row.
|
|
89
89
|
* @returns An async generator of non-empty row batches.
|
|
90
90
|
* @throws When iteration encounters an I/O, decompression, parsing, or strict-schema error.
|
|
91
91
|
*
|
|
@@ -93,7 +93,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
|
|
|
93
93
|
* ```ts
|
|
94
94
|
* import { parseCsvFile } from '@konstit/csv';
|
|
95
95
|
*
|
|
96
|
-
* for await (const rows of parseCsvFile('data.csv', {
|
|
96
|
+
* for await (const rows of parseCsvFile('data.csv', { columns: [0, 2] })) {
|
|
97
97
|
* for (const row of rows) console.log(row);
|
|
98
98
|
* }
|
|
99
99
|
* ```
|
|
@@ -103,7 +103,7 @@ export declare function parseCsvFile(path: string, options?: CsvFileOptions): As
|
|
|
103
103
|
* Stream rows using native projection and native filter evaluation.
|
|
104
104
|
*
|
|
105
105
|
* This lower-level file API is useful when the selected columns or native
|
|
106
|
-
* filter descriptors are already prepared. `
|
|
106
|
+
* filter descriptors are already prepared. `columns` is the returned
|
|
107
107
|
* projection, while `equalsFilter` and `filters` are evaluated against
|
|
108
108
|
* physical columns before materialization. Options are snapshotted at call
|
|
109
109
|
* time, including nested filter values.
|
|
@@ -122,7 +122,7 @@ export declare function parseCsvFile(path: string, options?: CsvFileOptions): As
|
|
|
122
122
|
* import { parseCsvFileProjected } from '@konstit/csv';
|
|
123
123
|
*
|
|
124
124
|
* for await (const rows of parseCsvFileProjected('data.csv', {
|
|
125
|
-
*
|
|
125
|
+
* columns: [2, 0],
|
|
126
126
|
* equalsFilter: { column: 1, value: 'active' },
|
|
127
127
|
* })) {
|
|
128
128
|
* console.log(rows);
|
|
@@ -134,7 +134,7 @@ export declare function parseCsvFileProjected(path: string, options?: CsvFileOpt
|
|
|
134
134
|
* Count logical CSV records in a file without materializing row strings.
|
|
135
135
|
*
|
|
136
136
|
* The parser honors quoted newlines and supports the same compression and
|
|
137
|
-
* delimiter options as
|
|
137
|
+
* delimiter options as file parsing. With `strict: true`, quote syntax
|
|
138
138
|
* is validated while counting. Strict schema metadata is intentionally not
|
|
139
139
|
* supported by this counting path; use row parsing when headers or minimum
|
|
140
140
|
* data-row constraints must be checked.
|
package/dist/files.js
CHANGED
|
@@ -9,26 +9,24 @@ import {
|
|
|
9
9
|
} from "./native.js";
|
|
10
10
|
import {
|
|
11
11
|
normalizeChunk,
|
|
12
|
-
|
|
12
|
+
prepareCsvBufferInput,
|
|
13
|
+
rejectSelectedColumns
|
|
13
14
|
} from "./normalize.js";
|
|
14
15
|
import { snapshotCsvOptions } from "./options-snapshot.js";
|
|
15
16
|
import {
|
|
17
|
+
countFileChunks,
|
|
16
18
|
createPreparedParser,
|
|
17
|
-
NativeCsvParser
|
|
19
|
+
NativeCsvParser,
|
|
20
|
+
parseFileChunks
|
|
18
21
|
} from "./parser.js";
|
|
19
|
-
import {
|
|
20
|
-
rejectStrictSchemaUnsupported,
|
|
21
|
-
strictSchemaValidator
|
|
22
|
-
} from "./strict-schema.js";
|
|
22
|
+
import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
|
|
23
23
|
export function parseCsvBuffer(buffer, suppliedOptions = {}) {
|
|
24
24
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const batch = parser.writeBatch(
|
|
25
|
+
const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
|
|
26
|
+
using parser = createPreparedParser({ ...options, encoding: input.parserEncoding });
|
|
27
|
+
const batch = parser.writeBatch(input.bytes, !0);
|
|
28
28
|
try {
|
|
29
|
-
|
|
30
|
-
validator?.finish();
|
|
31
|
-
return batch.rowsInto([], options.selectedColumns);
|
|
29
|
+
return batch.rowsInto([], options.columns);
|
|
32
30
|
} finally {
|
|
33
31
|
batch.close();
|
|
34
32
|
}
|
|
@@ -76,81 +74,42 @@ export function parseCsvFile(path, options = {}) {
|
|
|
76
74
|
}
|
|
77
75
|
async function* iterateCsvFile(path, options) {
|
|
78
76
|
await using input = await prepareCsvFileInput(path, options);
|
|
79
|
-
using parser =
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const batch = parser.writeBatch(chunk);
|
|
83
|
-
try {
|
|
84
|
-
validator?.validateBatch(batch);
|
|
85
|
-
const rows = batch.rowsInto([], options.selectedColumns);
|
|
86
|
-
if (rows.length > 0)
|
|
87
|
-
yield rows;
|
|
88
|
-
} finally {
|
|
89
|
-
batch.close();
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
const batch = parser.endBatch();
|
|
93
|
-
try {
|
|
94
|
-
validator?.validateBatch(batch);
|
|
95
|
-
validator?.finish();
|
|
96
|
-
const rows = batch.rowsInto([], options.selectedColumns);
|
|
97
|
-
if (rows.length > 0)
|
|
98
|
-
yield rows;
|
|
99
|
-
} finally {
|
|
100
|
-
batch.close();
|
|
101
|
-
}
|
|
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);
|
|
102
80
|
}
|
|
103
81
|
export function parseCsvFileProjected(path, options = {}) {
|
|
104
|
-
|
|
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
|
+
}));
|
|
105
99
|
}
|
|
106
100
|
async function* iterateCsvFileProjected(path, options) {
|
|
107
101
|
rejectStrictSchemaUnsupported(options, "projected file parsing");
|
|
108
102
|
await using input = await prepareCsvFileInput(path, options);
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
if (rows.length > 0)
|
|
115
|
-
yield rows;
|
|
116
|
-
} finally {
|
|
117
|
-
batch.close();
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
const batch = parser.endBatch();
|
|
121
|
-
try {
|
|
122
|
-
const rows = batch.rows();
|
|
123
|
-
if (rows.length > 0)
|
|
124
|
-
yield rows;
|
|
125
|
-
} finally {
|
|
126
|
-
batch.close();
|
|
127
|
-
}
|
|
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();
|
|
128
108
|
}
|
|
129
109
|
export async function countCsvFile(path, suppliedOptions = {}) {
|
|
130
110
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
131
111
|
rejectStrictSchemaUnsupported(options, "count");
|
|
132
|
-
await using input = await prepareCsvFileInput(path, options);
|
|
133
|
-
using parser =
|
|
134
|
-
|
|
135
|
-
if (options.strict === !0) {
|
|
136
|
-
for await (const chunk of input.chunks()) {
|
|
137
|
-
const batch = parser.writeBatch(chunk);
|
|
138
|
-
try {
|
|
139
|
-
rows += batch.rowCount;
|
|
140
|
-
} finally {
|
|
141
|
-
batch.close();
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
const batch = parser.endBatch();
|
|
145
|
-
try {
|
|
146
|
-
rows += batch.rowCount;
|
|
147
|
-
} finally {
|
|
148
|
-
batch.close();
|
|
149
|
-
}
|
|
150
|
-
return rows;
|
|
151
|
-
}
|
|
152
|
-
for await (const chunk of input.chunks())
|
|
153
|
-
rows += parser.writeCount(chunk);
|
|
154
|
-
rows += parser.endCount();
|
|
155
|
-
return rows;
|
|
112
|
+
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);
|
|
156
115
|
}
|
package/dist/filter.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { CsvNativeFilterProgramEntry } from './
|
|
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
|
*
|
|
@@ -22,9 +21,8 @@ export declare function column(columnIndex: number): CsvFilterColumn;
|
|
|
22
21
|
/**
|
|
23
22
|
* Match rows for which every supplied filter matches.
|
|
24
23
|
*
|
|
25
|
-
* Groups can be nested, and the resulting filter can be reused
|
|
26
|
-
*
|
|
27
|
-
* negation; the native evaluator applies the CSV filter's three-valued semantics.
|
|
24
|
+
* Groups can be nested, and the resulting filter can be reused for both rows and counts.
|
|
25
|
+
* A missing physical column remains unknown under negation.
|
|
28
26
|
*
|
|
29
27
|
* @param first - First filter in the group.
|
|
30
28
|
* @param rest - Additional filters that must also match.
|
|
@@ -36,9 +34,8 @@ export declare function all(first: CsvFilter, ...rest: readonly CsvFilter[]): Cs
|
|
|
36
34
|
/**
|
|
37
35
|
* Match rows for which at least one supplied filter matches.
|
|
38
36
|
*
|
|
39
|
-
* Groups can be nested, and the resulting filter can be reused
|
|
40
|
-
*
|
|
41
|
-
* the group match.
|
|
37
|
+
* Groups can be nested, and the resulting filter can be reused for both rows and counts.
|
|
38
|
+
* Another matching child can satisfy the group when one child's column is missing.
|
|
42
39
|
*
|
|
43
40
|
* @param first - First filter in the group.
|
|
44
41
|
* @param rest - Additional filters, any one of which may match.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function formatBytes(bytes: number): string;
|