@konstit/csv 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +113 -101
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +84 -57
  4. package/dist/api.js +211 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +36 -1
  8. package/dist/batches.js +241 -5
  9. package/dist/cli-command.d.ts +7 -7
  10. package/dist/cli-command.js +325 -164
  11. package/dist/cli-schema.d.ts +51 -21
  12. package/dist/cli-schema.js +126 -65
  13. package/dist/cli.js +1 -1
  14. package/dist/file-stream.d.ts +66 -18
  15. package/dist/file-stream.js +534 -199
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +50 -21
  18. package/dist/gzip-reader.d.ts +2 -0
  19. package/dist/gzip-reader.js +37 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +2 -2
  22. package/dist/inspect-file.d.ts +26 -3
  23. package/dist/inspect-file.js +169 -74
  24. package/dist/inspect-zip.d.ts +26 -0
  25. package/dist/inspect-zip.js +59 -0
  26. package/dist/latin1-rows.d.ts +11 -3
  27. package/dist/latin1-rows.js +276 -75
  28. package/dist/materialize-field.d.ts +6 -0
  29. package/dist/materialize-field.js +9 -0
  30. package/dist/native.d.ts +118 -20
  31. package/dist/native.js +53 -23
  32. package/dist/normalize.d.ts +7 -1
  33. package/dist/normalize.js +49 -9
  34. package/dist/options.d.ts +27 -12
  35. package/dist/parser.d.ts +34 -14
  36. package/dist/parser.js +296 -102
  37. package/dist/strict-schema.d.ts +7 -8
  38. package/dist/strict-schema.js +45 -83
  39. package/dist/transforms.d.ts +1 -3
  40. package/dist/transforms.js +17 -16
  41. package/dist/types.d.ts +192 -75
  42. package/dist/zip-entry.d.ts +14 -0
  43. package/dist/zip-entry.js +155 -0
  44. package/dist/zip-reader.d.ts +14 -3
  45. package/dist/zip-reader.js +65 -23
  46. package/package.json +34 -23
  47. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  48. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  49. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  50. package/prebuilds/manifest.json +18 -8
  51. package/prebuilds/provenance/darwin-arm64.json +1 -1
  52. package/prebuilds/provenance/darwin-x64.json +1 -1
  53. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -1,5 +1,7 @@
1
1
  import { ptr } from "bun:ffi";
2
- import { createReadStream } from "node:fs";
2
+ import {
3
+ createReadStream
4
+ } from "node:fs";
3
5
  import {
4
6
  open,
5
7
  stat
@@ -10,15 +12,27 @@ import {
10
12
  constants,
11
13
  inflateSync
12
14
  } from "node:zlib";
15
+ import { readGzipFileChunks } from "./gzip-reader.js";
13
16
  import {
14
17
  DEFAULT_CHUNK_SIZE,
15
18
  EMPTY_BUFFER,
16
19
  native
17
20
  } from "./native.js";
18
- import { resolveInputEncoding } from "./normalize.js";
21
+ import {
22
+ delimiterByte,
23
+ hasUtf8Bom,
24
+ resolveInputEncoding,
25
+ UTF8_BOM,
26
+ validateChunkSize,
27
+ validateCsvDialect
28
+ } from "./normalize.js";
19
29
  import { snapshotCsvOptions } from "./options-snapshot.js";
20
- import { readZipEntryChunks } from "./zip-reader.js";
30
+ import { readZipEntryChunks } from "./zip-entry.js";
21
31
  export const FILE_PROBE_SIZE = 65536;
32
+ export const COMPRESSION_PROBE_SIZE = 64;
33
+ const SMALL_PLAIN_FILE_MAX_BYTES = 65536;
34
+ const MIN_PARSE_AHEAD_FILE_BYTES = 33554432;
35
+ const MIN_PARSE_AHEAD_CHUNK_BYTES = 262144;
22
36
  const PROBED_BYTE_ENCODINGS = ["utf8", "latin1", "windows-1252"];
23
37
  const MAX_DELIMITER_PROBE_ROWS = 128;
24
38
  export const DELIMITER_CANDIDATES = [
@@ -42,35 +56,39 @@ const COMPRESSION_EXTENSIONS = [
42
56
  ".gz",
43
57
  ".zz"
44
58
  ];
59
+ function usesPlainFileReadAhead(mode) {
60
+ return mode === "read-ahead" || mode === "count";
61
+ }
62
+ function usesSmallPlainFileRead(mode) {
63
+ return mode === "read-ahead" || mode === "batches";
64
+ }
45
65
  export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
46
66
  const options = snapshotCsvOptions(suppliedOptions);
67
+ validateCsvDialect(options);
68
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
69
+ validateChunkSize(chunkSize);
70
+ const configuredDelimiter = options.delimiter ?? "auto";
47
71
  const autoEncoding = options.encoding === void 0 || options.encoding === "auto";
48
- const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, options.delimiter);
72
+ const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, configuredDelimiter);
49
73
  const parserEncoding = typeof inputEncoding === "string" ? inputEncoding : "utf8";
74
+ const readAhead = readMode === "read-ahead" && typeof path === "string" && typeof inputEncoding === "string" && chunkSize >= MIN_PARSE_AHEAD_CHUNK_BYTES ? { minimumParseAheadBytes: Math.max(MIN_PARSE_AHEAD_FILE_BYTES, 2 * chunkSize), canParseAhead: !1 } : void 0;
75
+ let hint = typeof path === "string" ? path : "";
76
+ const onZipEntryName = configuredDelimiter === "auto" && isZipCompression(options.compression ?? "auto") ? (entry) => {
77
+ hint = entry;
78
+ } : void 0;
50
79
  const source = () => {
51
- const chunks = readCsvFileChunks(path, options, readMode);
80
+ const chunks = typeof path === "string" ? readCsvFileChunks(path, options, readMode, onZipEntryName, readAhead) : readCsvByteStream(path, options, chunkSize);
81
+ if (!autoEncoding && inputEncoding === "utf8" && readMode !== "raw-records")
82
+ return stripUtf8StreamBom(chunks);
52
83
  return typeof inputEncoding === "string" ? chunks : transcodeCsvChunks(chunks, inputEncoding);
53
84
  };
54
- const configuredDelimiter = options.delimiter ?? ",";
55
85
  if (!autoEncoding && configuredDelimiter !== "auto") {
56
- let opened = !1;
57
- return {
58
- delimiter: configuredDelimiter,
59
- parserEncoding,
60
- chunks() {
61
- if (opened)
62
- throw Error("CSV file input can only be read once");
63
- opened = !0;
64
- return source();
65
- },
66
- [Symbol.asyncDispose]() {
67
- return Promise.resolve();
68
- }
69
- };
86
+ delimiterByte(configuredDelimiter, parserEncoding);
87
+ return new PreparedCsvFileInput(configuredDelimiter, parserEncoding, () => source()[Symbol.asyncIterator](), readAhead);
70
88
  }
71
89
  const iterator = source()[Symbol.asyncIterator]();
72
90
  const compression = options.compression ?? "auto";
73
- const reusesReadBuffer = typeof inputEncoding === "string" && (readMode === "read-ahead" && (compression === "auto" || compression === "none") || (compression === "auto" || isZipCompression(compression)) && useZipReadAhead(readMode, options.chunkSize ?? DEFAULT_CHUNK_SIZE));
91
+ const reusesReadBuffer = typeof inputEncoding === "string" && (typeof path !== "string" || readMode !== "stream" && (compression === "auto" || compression === "gzip") || usesPlainFileReadAhead(readMode) && compression === "none" || isZipCompression(compression) && useZipReadAhead(readMode, chunkSize));
74
92
  const bufferedChunks = [];
75
93
  let bufferedByteLength = 0;
76
94
  let sourceEnded = !1;
@@ -90,10 +108,10 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
90
108
  bufferedChunks.push(reusesReadBuffer && bufferedByteLength < bytesNeeded ? new Uint8Array(result.value) : result.value);
91
109
  }
92
110
  const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
93
- const hint = delimiterHintPath(path, options.compression);
94
- const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter) : void 0;
95
- const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded);
111
+ const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter, options) : void 0;
112
+ const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded, options);
96
113
  const replayEncoding = format === void 0 ? parserEncoding : resolveInputEncoding(format.encoding, delimiter);
114
+ delimiterByte(delimiter, typeof replayEncoding === "string" ? replayEncoding : "utf8");
97
115
  let skip = format?.skipBytes ?? 0;
98
116
  if (skip > 0)
99
117
  for (const [i, chunk] of bufferedChunks.entries()) {
@@ -103,31 +121,126 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
103
121
  if (skip === 0)
104
122
  break;
105
123
  }
106
- let opened = !1;
124
+ const replay = replayCsvFileChunks(bufferedChunks, iterator);
125
+ return typeof replayEncoding === "string" ? new PreparedCsvFileInput(delimiter, replayEncoding, replay, readAhead, iterator) : new PreparedCsvFileInput(delimiter, "utf8", transcodeCsvChunks(replay, replayEncoding), void 0, iterator);
126
+ } catch (error) {
127
+ await closeCsvFileIterator(iterator);
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ class PreparedCsvFileInput {
133
+ delimiter;
134
+ parserEncoding;
135
+ #state;
136
+ #readAhead;
137
+ constructor(delimiter, parserEncoding, source, readAhead, probedSource) {
138
+ this.delimiter = delimiter;
139
+ this.parserEncoding = parserEncoding;
140
+ this.#state = { phase: "ready", source, probedSource, replay: void 0 };
141
+ this.#readAhead = readAhead;
142
+ }
143
+ get canParseAhead() {
144
+ return this.#readAhead?.canParseAhead;
145
+ }
146
+ async readPrefix(inspect) {
147
+ const state = this.#ready();
148
+ if (state.replay !== void 0)
149
+ throw Error("CSV input prefix has already been read");
150
+ state.phase = "reading-prefix";
151
+ try {
152
+ const { value, replay } = await inspect(() => this.#nextChunk());
153
+ if (this.#state.phase === "closed")
154
+ throw Error("CSV file input is closed");
155
+ state.replay = replay;
156
+ state.phase = "ready";
157
+ return value;
158
+ } catch (error) {
159
+ await this[Symbol.asyncDispose]();
160
+ throw error;
161
+ }
162
+ }
163
+ chunks() {
164
+ this.#ready().phase = "reading";
107
165
  return {
108
- delimiter,
109
- parserEncoding: typeof replayEncoding === "string" ? replayEncoding : "utf8",
110
- chunks() {
111
- if (opened)
112
- throw Error("CSV file input can only be read once");
113
- opened = !0;
114
- const replay = replayCsvFileChunks(bufferedChunks, iterator);
115
- return typeof replayEncoding === "string" ? replay : transcodeCsvChunks(replay, replayEncoding);
166
+ [Symbol.asyncIterator]() {
167
+ return this;
168
+ },
169
+ next: async () => {
170
+ try {
171
+ const result = await this.#nextChunk();
172
+ if (result.done !== !0 && this.#state.phase !== "closed")
173
+ return result;
174
+ } catch (error) {
175
+ await this[Symbol.asyncDispose]();
176
+ throw error;
177
+ }
178
+ await this[Symbol.asyncDispose]();
179
+ return { done: !0, value: void 0 };
116
180
  },
117
- [Symbol.asyncDispose]() {
118
- return closeCsvFileIterator(iterator);
181
+ return: async () => {
182
+ await this.#close();
183
+ return { done: !0, value: void 0 };
119
184
  }
120
185
  };
121
- } catch (error) {
122
- await closeCsvFileIterator(iterator);
123
- throw error;
186
+ }
187
+ async[Symbol.asyncDispose]() {
188
+ try {
189
+ await this.#close();
190
+ } catch {}
191
+ }
192
+ #ready() {
193
+ const state = this.#state;
194
+ if (state.phase !== "ready")
195
+ throw Error("CSV file input can only be read once");
196
+ return state;
197
+ }
198
+ #nextChunk() {
199
+ const state = this.#state;
200
+ if (state.phase === "closed")
201
+ return Promise.resolve({ done: !0, value: void 0 });
202
+ if (state.replay !== void 0) {
203
+ const result = state.replay.next();
204
+ if (result.done !== !0)
205
+ return Promise.resolve(result);
206
+ state.replay = void 0;
207
+ }
208
+ if (typeof state.source === "function")
209
+ state.source = state.source();
210
+ return state.source.next();
211
+ }
212
+ #close() {
213
+ if (this.#state.phase === "closed")
214
+ return this.#state.closing;
215
+ const { source, probedSource } = this.#state;
216
+ const closing = Promise.resolve().then(async () => {
217
+ try {
218
+ if (typeof source !== "function")
219
+ await source.return?.();
220
+ } finally {
221
+ if (probedSource !== void 0)
222
+ await closeCsvFileIterator(probedSource);
223
+ }
224
+ });
225
+ this.#state = { phase: "closed", closing };
226
+ return closing;
124
227
  }
125
228
  }
126
- async function* readAheadFileChunks(path, chunkSize) {
127
- if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
128
- throw RangeError("chunkSize must be a positive safe integer");
229
+ async function* readPlainFileChunks(path, chunkSize, mode, readAhead) {
129
230
  await using file = await open(path, "r");
130
- if (!(await file.stat()).isFile()) {
231
+ const stats = await file.stat();
232
+ const smallRead = usesSmallPlainFileRead(mode) ? readSmallRegularFile(file, stats, chunkSize) : void 0;
233
+ if (smallRead !== void 0) {
234
+ const bytes = await smallRead;
235
+ if (bytes.length <= stats.size) {
236
+ yield* closeWhileYielding(file, bytes);
237
+ return;
238
+ }
239
+ }
240
+ yield* smallRead === void 0 && usesPlainFileReadAhead(mode) ? readAheadOpenFileChunks(file, chunkSize, stats, readAhead) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1, start: smallRead === void 0 ? void 0 : 0 });
241
+ }
242
+ async function* readAheadOpenFileChunks(file, chunkSize, stats, readAhead) {
243
+ if (!stats.isFile()) {
131
244
  const buffer = Buffer.allocUnsafe(chunkSize);
132
245
  let { bytesRead } = await file.read(buffer);
133
246
  while (bytesRead > 0) {
@@ -136,6 +249,8 @@ async function* readAheadFileChunks(path, chunkSize) {
136
249
  }
137
250
  return;
138
251
  }
252
+ if (readAhead !== void 0)
253
+ readAhead.canParseAhead = stats.size >= readAhead.minimumParseAheadBytes;
139
254
  let current = Buffer.allocUnsafe(chunkSize);
140
255
  let spare = Buffer.allocUnsafe(chunkSize);
141
256
  let { bytesRead } = await file.read(current);
@@ -147,48 +262,114 @@ async function* readAheadFileChunks(path, chunkSize) {
147
262
  [current, spare] = [spare, current];
148
263
  }
149
264
  }
150
- export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
265
+ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream", onZipEntryName, readAhead) {
151
266
  const options = snapshotCsvOptions(suppliedOptions);
152
267
  const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
268
+ validateChunkSize(chunkSize);
153
269
  const compression = options.compression ?? "auto";
154
270
  const zipReadAhead = useZipReadAhead(readMode, chunkSize);
155
271
  if (isZipCompression(compression))
156
- return readZipEntryChunks(path, compression, chunkSize, zipReadAhead);
157
- if (compression === "auto" || compression === "none") {
158
- const readAhead = readMode === "read-ahead";
159
- const raw = readAhead ? readAheadFileChunks(path, chunkSize) : createReadStream(path, { highWaterMark: chunkSize });
160
- return compression === "none" ? raw : readAutoDetectedCsvFileChunks(path, raw, chunkSize, readAhead, zipReadAhead);
161
- }
272
+ return readZipFileChunks(path, compression, chunkSize, zipReadAhead, readAhead, onZipEntryName);
273
+ if (compression === "auto")
274
+ return readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead, readAhead);
275
+ if (compression === "none")
276
+ return usesPlainFileReadAhead(readMode) || usesSmallPlainFileRead(readMode) ? readPlainFileChunks(path, chunkSize, readMode, readAhead) : createReadStream(path, { highWaterMark: chunkSize });
277
+ if (compression === "gzip")
278
+ return readGzipPathChunks(path, chunkSize, readMode !== "stream");
162
279
  return decompressedCsvFileChunks(path, compression, chunkSize);
163
280
  }
164
281
  function isZipCompression(compression) {
165
282
  return typeof compression === "object" && compression.format === "zip";
166
283
  }
284
+ async function* readCsvByteStream(input, options, chunkSize) {
285
+ const compression = options.compression ?? "auto";
286
+ if (isZipCompression(compression))
287
+ throw Error("ZIP input requires a regular file");
288
+ async function* bytes() {
289
+ const iterator = input[Symbol.asyncIterator]();
290
+ try {
291
+ while (!0) {
292
+ const next = await iterator.next();
293
+ if (next.done)
294
+ return;
295
+ if (!(next.value instanceof Uint8Array))
296
+ throw TypeError("CSV stream chunks must be Uint8Array values");
297
+ yield next.value;
298
+ }
299
+ } finally {
300
+ await closeCsvFileIterator(iterator);
301
+ }
302
+ }
303
+ if (compression !== "auto") {
304
+ yield* compression === "none" ? bytes() : decompressByteStream(bytes(), compression, chunkSize);
305
+ return;
306
+ }
307
+ const iterator = bytes();
308
+ try {
309
+ const buffered = [];
310
+ const detected = await probeStreamCompression(iterator, buffered, !0, { kind: "stream" });
311
+ if (detected === "zip")
312
+ throw Error("ZIP input requires a regular file");
313
+ const replay = replayCsvFileChunks(buffered, iterator);
314
+ yield* detected === "none" ? replay : decompressByteStream(replay, detected, chunkSize);
315
+ } finally {
316
+ await closeCsvFileIterator(iterator);
317
+ }
318
+ }
319
+ function decompressByteStream(input, format, chunkSize) {
320
+ return decompressChunks(copyChunks(input), format, Math.max(64, Math.min(chunkSize, DEFAULT_CHUNK_SIZE)));
321
+ }
322
+ async function probeStreamCompression(iterator, buffered, reusesBuffer, source) {
323
+ const prefix = new Uint8Array(COMPRESSION_PROBE_SIZE);
324
+ let length = 0;
325
+ while (!0) {
326
+ const next = await iterator.next();
327
+ if (next.done === !0)
328
+ return probeCompression(prefix.subarray(0, length), !0, source);
329
+ const chunk = next.value;
330
+ if (chunk.length === 0)
331
+ continue;
332
+ const take = Math.min(prefix.length - length, chunk.length);
333
+ prefix.set(chunk.subarray(0, take), length);
334
+ length += take;
335
+ const result = probeCompression(prefix.subarray(0, length), !1, source);
336
+ const needsMore = result === "need-more";
337
+ buffered.push(reusesBuffer && needsMore ? new Uint8Array(chunk) : chunk);
338
+ if (!needsMore)
339
+ return result;
340
+ }
341
+ }
167
342
  function useZipReadAhead(mode, chunkSize) {
168
343
  return mode === "count" || mode !== "stream" && chunkSize >= 65536;
169
344
  }
170
- function delimiterHintPath(path, compression) {
171
- return compression !== void 0 && isZipCompression(compression) ? compression.entry : path;
345
+ async function* readZipFileChunks(path, compression, chunkSize, zipReadAhead, readAhead, onZipEntryName) {
346
+ const chunks = readZipEntryChunks(path, compression, chunkSize, zipReadAhead, onZipEntryName, readAhead !== void 0);
347
+ if (readAhead === void 0) {
348
+ yield* chunks;
349
+ return;
350
+ }
351
+ let bytesUntilParseAhead = readAhead.minimumParseAheadBytes;
352
+ for await (const chunk of chunks) {
353
+ if (bytesUntilParseAhead > 0) {
354
+ bytesUntilParseAhead -= chunk.byteLength;
355
+ if (bytesUntilParseAhead <= 0)
356
+ readAhead.canParseAhead = !0;
357
+ }
358
+ yield chunk;
359
+ }
172
360
  }
173
361
  export function rejectCompressedSharding(options, operation) {
174
362
  if (options.compression !== void 0)
175
363
  throw Error(`${operation} does not support compressed input because compressed byte offsets cannot be sharded`);
176
364
  }
177
- export function rejectAutoDelimiterSharding(options, operation) {
178
- if (options.delimiter === "auto")
179
- throw Error(`${operation} does not support automatic delimiter detection because byte offsets are resolved first`);
180
- }
181
365
  async function* replayCsvFileChunks(bufferedChunks, iterator) {
182
- try {
183
- yield* bufferedChunks;
184
- while (!0) {
185
- const result = await iterator.next();
186
- if (result.done === !0)
187
- return;
188
- yield result.value;
189
- }
190
- } finally {
191
- await closeCsvFileIterator(iterator);
366
+ yield* bufferedChunks;
367
+ bufferedChunks.length = 0;
368
+ while (!0) {
369
+ const result = await iterator.next();
370
+ if (result.done === !0)
371
+ return;
372
+ yield result.value;
192
373
  }
193
374
  }
194
375
  async function* transcodeCsvChunks(source, decoder) {
@@ -202,6 +383,34 @@ async function* transcodeCsvChunks(source, decoder) {
202
383
  if (text.length > 0)
203
384
  yield encoder.encode(text);
204
385
  }
386
+ async function* stripUtf8StreamBom(chunks) {
387
+ let checked = !1;
388
+ let matched = 0;
389
+ for await (const chunk of chunks) {
390
+ if (checked) {
391
+ yield chunk;
392
+ continue;
393
+ }
394
+ let offset = 0;
395
+ while (offset < chunk.length && matched < UTF8_BOM.length && chunk[offset] === UTF8_BOM[matched]) {
396
+ ++offset;
397
+ ++matched;
398
+ }
399
+ if (matched === UTF8_BOM.length) {
400
+ checked = !0;
401
+ if (offset < chunk.length)
402
+ yield chunk.subarray(offset);
403
+ } else if (offset < chunk.length) {
404
+ checked = !0;
405
+ const preceding = matched - offset;
406
+ if (preceding > 0)
407
+ yield Uint8Array.from(UTF8_BOM.slice(0, preceding));
408
+ yield chunk;
409
+ }
410
+ }
411
+ if (!checked && matched > 0)
412
+ yield Uint8Array.from(UTF8_BOM.slice(0, matched));
413
+ }
205
414
  async function closeCsvFileIterator(iterator) {
206
415
  try {
207
416
  await iterator.return?.();
@@ -234,22 +443,27 @@ function copyProbePrefix(chunks, totalByteLength) {
234
443
  }
235
444
  return probe;
236
445
  }
237
- export function detectDelimiter(path, probe, sourceEnded) {
238
- return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded));
446
+ export function detectDelimiter(path, probe, sourceEnded, dialect) {
447
+ return requireDelimiter(path, scanDelimiterScores(probe, sourceEnded, dialect), probe, sourceEnded, dialect);
239
448
  }
240
- export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter) => {
241
- const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto");
242
- return { encoding, delimiter: delimiter === "auto" ? requireDelimiter(path, counts) : delimiter, skipBytes };
449
+ export function detectBufferDelimiter(input, path, final, dialect, stripBom = !1) {
450
+ const prefix = new Uint8Array(input.buffer, input.byteOffset, Math.min(input.byteLength, FILE_PROBE_SIZE));
451
+ const probe = stripBom && hasUtf8Bom(prefix) ? prefix.subarray(UTF8_BOM.length) : prefix;
452
+ return detectDelimiter(path, probe, final && input.byteLength <= FILE_PROBE_SIZE, dialect);
453
+ }
454
+ export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter, dialect) => {
455
+ const { bytes, encoding, skipBytes, scores } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto", dialect);
456
+ return { encoding, delimiter: scores === void 0 ? delimiter : requireDelimiter(path, scores, bytes, sourceEnded, dialect), skipBytes };
243
457
  };
244
- export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
458
+ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters, dialect) {
245
459
  let bytes = prefix;
246
460
  let bomEncoding;
247
461
  let skipBytes = 0;
248
462
  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)
249
463
  throw Error("automatic encoding detection does not support UTF-32; transcode the input to UTF-8");
250
- if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
464
+ if (hasUtf8Bom(bytes)) {
251
465
  bomEncoding = "utf8";
252
- skipBytes = 3;
466
+ skipBytes = UTF8_BOM.length;
253
467
  bytes = bytes.subarray(skipBytes);
254
468
  } else if (bytes[0] === 255 && bytes[1] === 254)
255
469
  bomEncoding = "utf-16le";
@@ -257,102 +471,157 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
257
471
  bomEncoding = "utf-16be";
258
472
  if (bomEncoding !== void 0) {
259
473
  if (!scoreDelimiters)
260
- return { bytes, encoding: bomEncoding, skipBytes, counts: [] };
474
+ return { bytes, encoding: bomEncoding, hasBom: !0, skipBytes };
261
475
  if (bomEncoding !== "utf8") {
262
476
  const text = new TextDecoder(bomEncoding).decode(bytes, { stream: !sourceEnded });
263
477
  bytes = new TextEncoder().encode(text);
264
478
  }
265
479
  }
266
- const counts = scoreDelimiters ? new Uint32Array(DELIMITER_CANDIDATES.length + 1) : void 0;
267
- 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));
480
+ const customDialect = scoreDelimiters && (dialect?.quote === !1 || dialect?.recordDelimiter !== void 0);
481
+ const candidateCount = DELIMITER_CANDIDATES.length;
482
+ const counts = scoreDelimiters && !customDialect ? new Uint32Array(2 * candidateCount + 2) : void 0;
483
+ const encodingCode = native.symbols.csv_probe_format_v3(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
268
484
  const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
269
485
  if (encoding === void 0)
270
486
  throw Error("NUL in encoding probe: specify the encoding explicitly");
271
- return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[DELIMITER_CANDIDATES.length] === 0 ? [] : [counts] };
487
+ const hasBom = bomEncoding !== void 0;
488
+ if (customDialect)
489
+ return { bytes, encoding, hasBom, skipBytes, scores: scanDelimiterScores(bytes, sourceEnded, dialect) };
490
+ const scores = counts === void 0 ? void 0 : {
491
+ stableCounts: counts.subarray(0, candidateCount),
492
+ quotedFields: counts.subarray(candidateCount, 2 * candidateCount),
493
+ hasCompleteRecords: (counts[2 * candidateCount] ?? 0) > 0,
494
+ hasSeparator: counts[2 * candidateCount + 1] === 1
495
+ };
496
+ return { bytes, encoding, hasBom, skipBytes, scores };
272
497
  }
273
- function requireDelimiter(path, rows) {
274
- const result = selectDelimiter(path, rows);
498
+ function requireDelimiter(path, scores, sample, sourceEnded, dialect) {
499
+ const result = selectDelimiter(path, scores);
275
500
  if ("delimiter" in result)
276
501
  return result.delimiter;
502
+ if (sourceEnded && !scores.hasSeparator) {
503
+ if (sample.every((byte) => byte === 10 || byte === 13))
504
+ return ",";
505
+ const fullScores = scanDelimiterScores(sample, !0, dialect, 1 / 0);
506
+ if (fullScores.hasCompleteRecords && !fullScores.hasSeparator)
507
+ return ",";
508
+ }
277
509
  switch (result.reason) {
278
510
  case "no-records":
279
511
  throw Error(`delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
280
512
  case "no-stable-separator":
281
513
  throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
282
514
  case "ambiguous":
283
- throw Error(`delimiter auto-detection is ambiguous between ${result.candidates.map((c) => JSON.stringify(c)).join(", ")}; specify delimiter explicitly`);
515
+ throw delimiterAmbiguityError(result.candidates);
516
+ case "weak-separator":
517
+ throw Error(`delimiter auto-detection could not confirm ${JSON.stringify(result.candidate)}; specify delimiter explicitly`);
284
518
  }
285
519
  }
286
- export function selectDelimiter(path, rows) {
287
- if (rows.length === 0)
520
+ export function delimiterAmbiguityError(candidates) {
521
+ return Error(`delimiter auto-detection is ambiguous between ${candidates.map((candidate) => JSON.stringify(candidate)).join(", ")}; specify delimiter explicitly`);
522
+ }
523
+ export function selectDelimiter(path, scores) {
524
+ if (!scores.hasCompleteRecords)
288
525
  return { reason: "no-records" };
289
526
  const stableCandidates = [];
290
- let hasStableAtSign = !1;
291
- for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
292
- const separatorCount = rows[0]?.[candidateIndex] ?? 0;
527
+ for (const [candidateIndex, candidate] of DELIMITER_CANDIDATES.entries()) {
528
+ const separatorCount = scores.stableCounts[candidateIndex] ?? 0;
293
529
  if (separatorCount === 0)
294
530
  continue;
295
- if (rows.every((row) => row[candidateIndex] === separatorCount)) {
296
- const candidate = DELIMITER_CANDIDATES[candidateIndex];
297
- if (candidate?.delimiter === "@")
298
- hasStableAtSign = !0;
299
- else if (candidate !== void 0)
300
- stableCandidates.push({ delimiter: candidate.delimiter, separatorCount });
301
- }
531
+ stableCandidates.push({ delimiter: candidate.delimiter, separatorCount, quotedFields: scores.quotedFields[candidateIndex] ?? 0 });
302
532
  }
303
533
  if (stableCandidates.length === 0)
304
- return hasStableAtSign ? { delimiter: "@" } : { reason: "no-stable-separator" };
305
- const extensionHint = delimiterFromExtension(path);
534
+ return { reason: "no-stable-separator" };
535
+ const bestQuoteCount = Math.max(...stableCandidates.map((candidate) => candidate.quotedFields));
536
+ const bestQuotedCandidates = stableCandidates.filter((candidate) => candidate.quotedFields === bestQuoteCount);
537
+ const extension = extname(stripCompressionExtension(path.toLowerCase()));
538
+ const extensionHint = delimiterFromExtension(extension);
306
539
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
307
- if (confirmedHint !== void 0)
308
- return { delimiter: confirmedHint.delimiter };
309
- const maximumSeparatorCount = Math.max(...stableCandidates.map((candidate) => candidate.separatorCount));
310
- const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
311
- if (strongestCandidates.length === 1)
312
- return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
540
+ if (confirmedHint !== void 0) {
541
+ if (confirmedHint.quotedFields === bestQuoteCount)
542
+ return {
543
+ delimiter: confirmedHint.delimiter,
544
+ extensionHint: extension,
545
+ ...bestQuotedCandidates.length > 1 ? { extensionBrokeTie: !0 } : {}
546
+ };
547
+ return {
548
+ reason: "ambiguous",
549
+ candidates: [confirmedHint.delimiter, ...bestQuotedCandidates.map((candidate) => candidate.delimiter)],
550
+ conflictingHint: !0
551
+ };
552
+ }
553
+ const preferredCandidates = bestQuotedCandidates.filter((candidate) => candidate.delimiter !== "@");
554
+ const candidates = preferredCandidates.length === 0 ? bestQuotedCandidates : preferredCandidates;
555
+ const maximumSeparatorCount = Math.max(...candidates.map((candidate) => candidate.separatorCount));
556
+ const strongestCandidates = candidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
557
+ const [strongest] = strongestCandidates;
558
+ if (strongest !== void 0 && strongestCandidates.length === 1) {
559
+ const { delimiter, quotedFields, separatorCount } = strongest;
560
+ if (separatorCount === 1 && (delimiter === "@" || delimiter === ":" || delimiter === "^" || delimiter === "~") && DELIMITER_CANDIDATES.some((candidate, index) => candidate.delimiter !== delimiter && (scores.quotedFields[index] ?? 0) >= quotedFields))
561
+ return { reason: "weak-separator", candidate: delimiter };
562
+ return { delimiter };
563
+ }
313
564
  return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
314
565
  }
315
- export function scanDelimiterCounts(probe, sourceEnded) {
316
- const rows = [];
317
- let counts = Array.from({ length: DELIMITER_CANDIDATES.length }, () => 0);
318
- let inQuotes = !1;
319
- let rowHasContent = !1;
320
- for (let index = 0;index < probe.byteLength; ++index) {
321
- const byte = probe[index];
322
- if (byte === 34) {
323
- rowHasContent = !0;
324
- if (inQuotes && probe[index + 1] === 34) {
325
- ++index;
326
- continue;
327
- }
328
- inQuotes = !inQuotes;
329
- continue;
330
- }
331
- if (!inQuotes && (byte === 10 || byte === 13)) {
332
- if (rowHasContent) {
333
- rows.push(counts);
334
- if (rows.length === MAX_DELIMITER_PROBE_ROWS)
335
- return rows;
566
+ export function scanDelimiterScores(probe, sourceEnded, { quote = !0, recordDelimiter } = {}, maxRows = MAX_DELIMITER_PROBE_ROWS) {
567
+ const stableCounts = new Uint32Array(DELIMITER_CANDIDATES.length);
568
+ const quotedFields = new Uint32Array(DELIMITER_CANDIDATES.length);
569
+ let hasCompleteRecords = !1;
570
+ let hasSeparator = !1;
571
+ for (const [candidateIndex, { byte: delimiter }] of DELIMITER_CANDIDATES.entries()) {
572
+ let finishRecord = function() {
573
+ if (rows === 0)
574
+ stableCounts[candidateIndex] = separators;
575
+ else if (stableCounts[candidateIndex] !== separators)
576
+ stableCounts[candidateIndex] = 0;
577
+ ++rows;
578
+ hasCompleteRecords = !0;
579
+ hasSeparator ||= separators > 0;
580
+ quotedFields[candidateIndex] = (quotedFields[candidateIndex] ?? 0) + completeQuotes;
581
+ separators = 0;
582
+ completeQuotes = 0;
583
+ };
584
+ let rows = 0;
585
+ let rowStart = 0;
586
+ let separators = 0;
587
+ let completeQuotes = 0;
588
+ let quoted = !1;
589
+ for (let index = 0;index < probe.byteLength; ++index) {
590
+ const byte = probe[index];
591
+ if (quote && byte === 34) {
592
+ if (quoted) {
593
+ const next = probe[index + 1];
594
+ if (next === 34)
595
+ ++index;
596
+ else {
597
+ quoted = !1;
598
+ if (next === delimiter || next === 10 || recordDelimiter === void 0 && next === 13 || next === void 0 && sourceEnded)
599
+ ++completeQuotes;
600
+ }
601
+ } else if (index === rowStart || probe[index - 1] === delimiter)
602
+ quoted = !0;
603
+ } else if (!quoted) {
604
+ if (byte === delimiter)
605
+ ++separators;
606
+ else if (byte === 10 || recordDelimiter === void 0 && byte === 13) {
607
+ if (index > rowStart) {
608
+ finishRecord();
609
+ if (rows === maxRows)
610
+ break;
611
+ }
612
+ rowStart = index + 1;
613
+ }
336
614
  }
337
- counts = Array.from({ length: DELIMITER_CANDIDATES.length }, () => 0);
338
- rowHasContent = !1;
339
- if (byte === 13 && probe[index + 1] === 10)
340
- ++index;
341
- continue;
342
- }
343
- rowHasContent = !0;
344
- if (!inQuotes) {
345
- for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex)
346
- if (byte === DELIMITER_CANDIDATES[candidateIndex]?.byte)
347
- counts[candidateIndex] = (counts[candidateIndex] ?? 0) + 1;
348
615
  }
616
+ if (sourceEnded && !quoted && rowStart < probe.byteLength && rows < maxRows)
617
+ finishRecord();
349
618
  }
350
- if (sourceEnded && !inQuotes && rowHasContent && rows.length < MAX_DELIMITER_PROBE_ROWS)
351
- rows.push(counts);
352
- return rows;
619
+ return { stableCounts, quotedFields, hasCompleteRecords, hasSeparator };
353
620
  }
354
- function delimiterFromExtension(path) {
355
- const extension = extname(stripCompressionExtension(path.toLowerCase()));
621
+ export function isDelimiterCandidate(byte) {
622
+ return DELIMITER_CANDIDATES.some((candidate) => candidate.byte === byte);
623
+ }
624
+ function delimiterFromExtension(extension) {
356
625
  switch (extension) {
357
626
  case ".csv":
358
627
  return ",";
@@ -371,47 +640,90 @@ function stripCompressionExtension(path) {
371
640
  return path.slice(0, -extension.length);
372
641
  return path;
373
642
  }
374
- async function* readAutoDetectedCsvFileChunks(path, raw, chunkSize, reusesBuffer, zipReadAhead) {
375
- const iterator = raw[Symbol.asyncIterator]();
643
+ async function* readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead, readAhead) {
644
+ const reusesBuffer = readMode === "read-ahead";
645
+ await using file = await open(path, "r");
646
+ const stats = await file.stat();
647
+ const regularFile = stats.isFile();
648
+ const smallRead = usesSmallPlainFileRead(readMode) ? readSmallRegularFile(file, stats, chunkSize) : void 0;
649
+ const raw = (plainReadAhead) => reusesBuffer && smallRead === void 0 ? readAheadOpenFileChunks(file, chunkSize, stats, plainReadAhead) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1, start: smallRead === void 0 ? void 0 : 0 });
650
+ const iterator = regularFile ? void 0 : raw()[Symbol.asyncIterator]();
376
651
  const buffered = [];
377
- const prefix = new Uint8Array(64);
378
- let length = 0;
379
- let needed = 4;
380
652
  try {
381
- while (length < needed) {
382
- const next = await iterator.next();
383
- if (next.done === !0)
384
- break;
385
- const chunk = next.value;
386
- const take = Math.min(prefix.length - length, chunk.length);
387
- prefix.set(chunk.subarray(0, take), length);
388
- length += take;
389
- if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
390
- needed = prefix.length;
391
- buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
392
- }
393
- const sample = prefix.subarray(0, length);
394
- if (isZipSignature(sample)) {
395
- if (!(await stat(path)).isFile())
653
+ const bytes = smallRead === void 0 ? void 0 : await smallRead;
654
+ const smallFile = bytes !== void 0 && bytes.length <= stats.size ? bytes : void 0;
655
+ const probeSource = { kind: "file", path };
656
+ const compression = iterator === void 0 ? probeCompression(smallFile ?? await readRegularFilePrefix(file, COMPRESSION_PROBE_SIZE), !0, probeSource) : await probeStreamCompression(iterator, buffered, reusesBuffer, probeSource);
657
+ if (compression === "zip") {
658
+ if (!regularFile || !(await stat(path)).isFile())
396
659
  throw Error("ZIP input requires a regular file; save the archive before reading it");
397
- await closeCsvFileIterator(iterator);
398
- yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
660
+ await file.close();
661
+ yield* readZipFileChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead, readAhead);
399
662
  return;
400
663
  }
401
- const compression = compressionFromPrefix(path, sample);
402
- const replay = replayCsvFileChunks(buffered, iterator);
403
- if (compression === void 0) {
404
- if (!isPlainCsvFile(path))
405
- throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
406
- yield* replay;
664
+ if (compression === "gzip" && regularFile) {
665
+ yield* readGzipFileChunks(file.fd, chunkSize, readMode !== "stream");
666
+ return;
667
+ }
668
+ if (compression === "none" && !isPlainCsvFile(path))
669
+ throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
670
+ if (compression === "none" && regularFile && readMode === "count") {
671
+ yield* readAheadOpenFileChunks(file, chunkSize, stats);
672
+ return;
673
+ }
674
+ if (compression === "none" && smallFile !== void 0) {
675
+ yield* closeWhileYielding(file, smallFile);
676
+ return;
677
+ }
678
+ const source = iterator === void 0 ? raw(compression === "none" ? readAhead : void 0) : replayCsvFileChunks(buffered, iterator);
679
+ if (compression === "none") {
680
+ yield* source;
407
681
  return;
408
682
  }
409
- yield* WebReadableStream.from(reusesBuffer ? copyFileChunks(replay) : replay).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
683
+ yield* decompressChunks(reusesBuffer ? copyChunks(source) : source, compression, chunkSize);
410
684
  } finally {
411
- await closeCsvFileIterator(iterator);
685
+ if (iterator !== void 0)
686
+ await closeCsvFileIterator(iterator);
687
+ }
688
+ }
689
+ function readSmallRegularFile(file, stats, chunkSize) {
690
+ if (!stats.isFile() || stats.size === 0 || stats.size > Math.min(SMALL_PLAIN_FILE_MAX_BYTES, chunkSize))
691
+ return;
692
+ return Bun.file(file.fd).slice(0, stats.size + 1).bytes();
693
+ }
694
+ async function* closeWhileYielding(file, bytes) {
695
+ const closing = file.close();
696
+ void closing.catch(() => {});
697
+ try {
698
+ if (bytes.length > 0)
699
+ yield bytes;
700
+ } finally {
701
+ await closing;
702
+ }
703
+ }
704
+ async function readRegularFilePrefix(file, capacity) {
705
+ const bytes = new Uint8Array(capacity);
706
+ let length = 0;
707
+ while (length < capacity) {
708
+ const { bytesRead } = await file.read(bytes, length, capacity - length, length);
709
+ if (bytesRead === 0)
710
+ break;
711
+ length += bytesRead;
412
712
  }
713
+ return bytes.subarray(0, length);
413
714
  }
414
- async function* copyFileChunks(chunks) {
715
+ async function* readGzipPathChunks(path, chunkSize, reuseBuffer) {
716
+ await using file = await open(path, "r");
717
+ if ((await file.stat()).isFile()) {
718
+ yield* readGzipFileChunks(file.fd, chunkSize, reuseBuffer);
719
+ return;
720
+ }
721
+ yield* decompressChunks(file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 }), "gzip", chunkSize);
722
+ }
723
+ function decompressChunks(source, compression, chunkSize) {
724
+ return WebReadableStream.from(source).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
725
+ }
726
+ async function* copyChunks(chunks) {
415
727
  for await (const chunk of chunks)
416
728
  yield new Uint8Array(chunk);
417
729
  }
@@ -420,7 +732,7 @@ function isPlainCsvFile(path) {
420
732
  return mime === "text/csv" || mime === "text/tab-separated-values" || mime === "text/plain" || mime === "application/octet-stream" && /\.(?:psv|ssv|tab)$/i.test(path);
421
733
  }
422
734
  export function isZipSignature(prefix) {
423
- return prefix[0] === 80 && prefix[1] === 75 && (prefix[2] === 3 && prefix[3] === 4 || prefix[2] === 5 && prefix[3] === 6);
735
+ return compressionSignature(prefix) === "zip";
424
736
  }
425
737
  function isPrintableZlibHeader(prefix) {
426
738
  const first = prefix[0] ?? 0;
@@ -430,15 +742,22 @@ function isPrintableZlibHeader(prefix) {
430
742
  function decompressedCsvFileChunks(path, compression, chunkSize) {
431
743
  return Bun.file(path).stream().pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
432
744
  }
433
- export function compressionFromPrefix(path, prefix) {
434
- const extensionHint = compressionFromExtension(path);
435
- const strongSignature = compressionFromStrongSignature(prefix);
436
- if (strongSignature !== void 0) {
437
- if (extensionHint !== void 0 && extensionHint.format !== strongSignature)
438
- throw Error(`compression auto-detection mismatch: extension ${extensionHint.extension} indicates ${extensionHint.format}, but the file signature indicates ${strongSignature}`);
439
- return strongSignature;
745
+ export function probeCompression(prefix, sourceEnded, source) {
746
+ const sample = prefix.length > COMPRESSION_PROBE_SIZE ? prefix.subarray(0, COMPRESSION_PROBE_SIZE) : prefix;
747
+ const signature = compressionSignature(sample);
748
+ const hasZlibHeader = isZlibHeader(sample);
749
+ const printableZlib = hasZlibHeader && isPrintableZlibHeader(sample);
750
+ if (!sourceEnded && (sample.length === 0 || signature === "partial" || sample.length === 1 && isZlibMethod(sample[0]) || sample.length < COMPRESSION_PROBE_SIZE && printableZlib))
751
+ return "need-more";
752
+ if (signature === "zip")
753
+ return "zip";
754
+ const path = source.kind === "stream" ? void 0 : source.path;
755
+ const extensionHint = path === void 0 ? void 0 : compressionFromExtension(path);
756
+ if (signature === "gzip" || signature === "zstd") {
757
+ if (extensionHint !== void 0 && extensionHint.format !== signature)
758
+ throw Error(`compression auto-detection mismatch: extension ${extensionHint.extension} indicates ${extensionHint.format}, but the file signature indicates ${signature}`);
759
+ return signature;
440
760
  }
441
- const hasZlibHeader = isZlibHeader(prefix);
442
761
  if (extensionHint !== void 0) {
443
762
  if (extensionHint.signatureRequired) {
444
763
  if (extensionHint.format === "deflate" && hasZlibHeader)
@@ -449,21 +768,19 @@ export function compressionFromPrefix(path, prefix) {
449
768
  }
450
769
  return extensionHint.format;
451
770
  }
452
- if (hasZlibHeader) {
453
- const sample = prefix.subarray(0, 64);
454
- if (isPrintableZlibHeader(sample) && isPlainCsvFile(path) && !sample.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
455
- try {
456
- inflateSync(sample, { finishFlush: sample.length < 64 ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
457
- } catch (error) {
458
- if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
459
- return;
460
- throw error;
461
- }
462
- return "deflate";
463
- }
464
- return;
771
+ if (!hasZlibHeader)
772
+ return "none";
773
+ if (printableZlib && (path === void 0 || isPlainCsvFile(path)) || source.kind === "inspection" && !sample.some((byte) => byte < 32 && byte !== 9 && byte !== 10 && byte !== 13))
774
+ try {
775
+ inflateSync(sample, { finishFlush: sample.length < COMPRESSION_PROBE_SIZE ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
776
+ } catch (error) {
777
+ if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
778
+ return "none";
779
+ throw error;
780
+ }
781
+ return "deflate";
465
782
  }
466
- export function compressionFromExtension(path) {
783
+ function compressionFromExtension(path) {
467
784
  const lowerPath = path.toLowerCase();
468
785
  if (lowerPath.endsWith(".deflate-raw"))
469
786
  return { extension: ".deflate-raw", format: "deflate-raw", signatureRequired: !1 };
@@ -485,19 +802,37 @@ export function compressionFromExtension(path) {
485
802
  return;
486
803
  }
487
804
  }
488
- function compressionFromStrongSignature(prefix) {
489
- if (prefix[0] === 31 && prefix[1] === 139)
490
- return "gzip";
491
- if (prefix[0] === 40 && prefix[1] === 181 && prefix[2] === 47 && prefix[3] === 253)
492
- return "zstd";
493
- if (prefix[0] !== void 0 && prefix[0] >= 80 && prefix[0] <= 95 && prefix[1] === 42 && prefix[2] === 77 && prefix[3] === 24)
494
- return "zstd";
805
+ const COMPRESSION_SIGNATURES = [
806
+ { format: "gzip", bytes: [31, 139], firstByteMask: 255 },
807
+ { format: "zstd", bytes: [40, 181, 47, 253], firstByteMask: 255 },
808
+ { format: "zstd", bytes: [80, 42, 77, 24], firstByteMask: 240 },
809
+ { format: "zip", bytes: [80, 75, 3, 4], firstByteMask: 255 },
810
+ { format: "zip", bytes: [80, 75, 5, 6], firstByteMask: 255 }
811
+ ];
812
+ function compressionSignature(prefix) {
813
+ const first = prefix[0];
814
+ if (first === void 0)
815
+ return;
816
+ for (const { format, bytes, firstByteMask } of COMPRESSION_SIGNATURES) {
817
+ if ((first & firstByteMask) !== bytes[0])
818
+ continue;
819
+ let matched = 1;
820
+ while (matched < bytes.length && prefix[matched] === bytes[matched])
821
+ ++matched;
822
+ if (matched === bytes.length)
823
+ return format;
824
+ if (matched === prefix.length)
825
+ return "partial";
826
+ }
495
827
  return;
496
828
  }
829
+ function isZlibMethod(byte = 0) {
830
+ return (byte & 15) === 8 && byte >> 4 <= 7;
831
+ }
497
832
  function isZlibHeader(prefix) {
498
833
  const compressionMethodAndFlags = prefix[0];
499
834
  const flags = prefix[1];
500
835
  if (compressionMethodAndFlags === void 0 || flags === void 0)
501
836
  return !1;
502
- return (compressionMethodAndFlags & 15) === 8 && compressionMethodAndFlags >> 4 <= 7 && (compressionMethodAndFlags << 8 | flags) % 31 === 0;
837
+ return isZlibMethod(compressionMethodAndFlags) && (compressionMethodAndFlags << 8 | flags) % 31 === 0;
503
838
  }