web-utility-streams 1.0.0 → 1.1.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.
@@ -0,0 +1,502 @@
1
+ import { t as getCsvChar } from "./CsvOptions-BAnaU_B9.mjs";
2
+ // src/CsvDecoderStream.ts
3
+ const LF = 10;
4
+ const CR = 13;
5
+ const SPACE = 32;
6
+ const TAB = 9;
7
+ const BOM = 65279;
8
+ const FIELD_START = 0;
9
+ const UNQUOTED = 1;
10
+ const QUOTED = 2;
11
+ const AFTER_QUOTE = 3;
12
+ /**
13
+ * Spaces (or tabs) at the start of a field, which are dropped if they are
14
+ * followed by a quote, or are part of the field if they aren't. The spaces
15
+ * from previous chunks are kept in `_field`.
16
+ */
17
+ const LEADING_SPACE = 4;
18
+ /**
19
+ * A quote in a quoted field (where quotes are escaped by doubling them) at the
20
+ * end of a chunk. It's an escaped quote if the next chunk starts with a quote,
21
+ * otherwise it's the closing quote.
22
+ */
23
+ const QUOTE_PENDING = 5;
24
+ /**
25
+ * An escape character in a quoted field (where quotes are escaped by a
26
+ * different character) at the end of a chunk. What it escapes depends on the
27
+ * start of the next chunk.
28
+ */
29
+ const ESCAPE_PENDING = 6;
30
+ /** The rest of the text is part of the quoted field */
31
+ const QUOTED_CONTINUES = -1;
32
+ /** The text ends with a quote or escape character that depends on the next chunk */
33
+ const QUOTED_PENDING = -2;
34
+ function getChar(name, value) {
35
+ return getCsvChar("CsvDecoder", name, value);
36
+ }
37
+ /**
38
+ * Find `char` in `text`, starting at `from`. Returns `end` if it is not found
39
+ * before `end`, so that the result can be compared with other positions
40
+ * without checking for -1.
41
+ */
42
+ function find(text, char, from, end) {
43
+ const index = text.indexOf(char, from);
44
+ return index === -1 || index > end ? end : index;
45
+ }
46
+ /**
47
+ * The delimiters we choose between when guessing, in order of preference
48
+ */
49
+ const DELIMITER_CANDIDATES = [
50
+ ",",
51
+ ";",
52
+ " "
53
+ ].map((c) => c.charCodeAt(0));
54
+ /**
55
+ * Guesses the delimiter by counting the candidate delimiters in the first
56
+ * line, ignoring any that are in quoted fields. The text can be passed in
57
+ * chunks, and each character is only looked at once.
58
+ */
59
+ var DelimiterDetector = class {
60
+ _counts;
61
+ _quoteCode;
62
+ _escapeCode;
63
+ _inQuotes = false;
64
+ /** Whether the previous character was an escape character in quotes */
65
+ _escaping = false;
66
+ /** Whether we have not yet seen any text (so we need to skip a BOM) */
67
+ _atStart = true;
68
+ /**
69
+ * Whether we are at the start of a field (after the start of the line or
70
+ * a candidate delimiter, and any spaces), where a quote starts a quoted
71
+ * field. Elsewhere, the decoder treats quotes as normal characters.
72
+ */
73
+ _atFieldStart = true;
74
+ /** Whether the previous character closed a quoted field */
75
+ _quoteClosed = false;
76
+ constructor(quote, escape) {
77
+ this._counts = DELIMITER_CANDIDATES.map(() => 0);
78
+ this._quoteCode = quote ? quote.charCodeAt(0) : -1;
79
+ this._escapeCode = escape && escape !== quote ? escape.charCodeAt(0) : -1;
80
+ }
81
+ /**
82
+ * Count the delimiters in the next chunk of text. Returns true once the
83
+ * end of the first line has been reached.
84
+ */
85
+ write(chunk) {
86
+ const quoteCode = this._quoteCode;
87
+ let i = 0;
88
+ if (this._atStart && chunk.length !== 0) {
89
+ this._atStart = false;
90
+ if (chunk.charCodeAt(0) === BOM) i = 1;
91
+ }
92
+ for (; i < chunk.length; i++) {
93
+ const code = chunk.charCodeAt(i);
94
+ if (this._inQuotes) {
95
+ if (this._escaping) this._escaping = false;
96
+ else if (code === this._escapeCode) this._escaping = true;
97
+ else if (code === quoteCode) {
98
+ this._inQuotes = false;
99
+ this._quoteClosed = true;
100
+ }
101
+ continue;
102
+ }
103
+ if (code === quoteCode && (this._atFieldStart || this._quoteClosed)) {
104
+ this._inQuotes = true;
105
+ this._atFieldStart = false;
106
+ this._quoteClosed = false;
107
+ continue;
108
+ }
109
+ this._quoteClosed = false;
110
+ if (code === LF || code === CR) return true;
111
+ const index = DELIMITER_CANDIDATES.indexOf(code);
112
+ if (index !== -1) {
113
+ this._counts[index]++;
114
+ this._atFieldStart = true;
115
+ } else if (code !== SPACE) this._atFieldStart = false;
116
+ }
117
+ return false;
118
+ }
119
+ /**
120
+ * The most common delimiter, preferring earlier candidates if there's a tie
121
+ */
122
+ result() {
123
+ let best = 0;
124
+ for (let i = 1; i < this._counts.length; i++) if (this._counts[i] > this._counts[best]) best = i;
125
+ return String.fromCharCode(DELIMITER_CANDIDATES[best]);
126
+ }
127
+ };
128
+ /**
129
+ * The CSV parser used by `CsvDecoderStream`. You can use it directly if you
130
+ * want to parse CSV text without using streams.
131
+ */
132
+ var CsvDecoder = class {
133
+ _onRow;
134
+ _delimiter = "";
135
+ _delimiterCode = -1;
136
+ _maxCharsToDetectDelimiter;
137
+ _quote;
138
+ _quoteCode;
139
+ _escape;
140
+ _escapeCode;
141
+ _ignoreEmpty;
142
+ /**
143
+ * The text so far, while we are reading the first line to guess the
144
+ * delimiter. Once the delimiter is known, all text is parsed as it arrives.
145
+ */
146
+ _buffer = "";
147
+ /** Set until we have guessed the delimiter, if it wasn't passed */
148
+ _detector;
149
+ _state = FIELD_START;
150
+ /** The fields of the current row that have been parsed so far */
151
+ _row = [];
152
+ /** The start of the current field, if it continues in the next chunk */
153
+ _field = "";
154
+ /** Whether we have not yet seen any text (so we need to skip a BOM) */
155
+ _atStart = true;
156
+ /**
157
+ * Whether the previous chunk ended with a "\r" that ended a row, so a "\n"
158
+ * at the start of the next chunk is part of the same line break.
159
+ */
160
+ _skipLineFeed = false;
161
+ /** The number of rows that have ended so far, for error messages */
162
+ _rowCount = 0;
163
+ constructor(onRow, opts) {
164
+ this._onRow = onRow;
165
+ const quote = opts?.quote ?? true;
166
+ this._quote = quote === true ? "\"" : quote === false ? "" : getChar("quote", quote);
167
+ this._quoteCode = this._quote ? this._quote.charCodeAt(0) : -1;
168
+ this._escape = this._quote ? getChar("escape", opts?.escape ?? this._quote) : "";
169
+ this._escapeCode = this._escape ? this._escape.charCodeAt(0) : -1;
170
+ this._maxCharsToDetectDelimiter = opts?.maxCharsToGuessDelimiter ?? 1e4;
171
+ if (opts?.delimiter === void 0) {
172
+ for (const [name, value] of [["quote", this._quote], ["escape", this._escape]]) if (value && DELIMITER_CANDIDATES.includes(value.charCodeAt(0))) throw new TypeError(`CsvDecoder: delimiter must be passed if ${name} is ${JSON.stringify(value)}, as the delimiter could be guessed to be the same character`);
173
+ this._detector = new DelimiterDetector(this._quote, this._escape);
174
+ } else {
175
+ this._delimiter = getChar("delimiter", opts.delimiter);
176
+ this._delimiterCode = this._delimiter.charCodeAt(0);
177
+ if (this._quote && this._delimiter === this._quote) throw new TypeError("CsvDecoder: delimiter and quote must be different");
178
+ }
179
+ this._ignoreEmpty = opts?.ignoreEmpty ?? false;
180
+ }
181
+ /**
182
+ * Parse the next chunk of text, calling `onRow` for each row that is
183
+ * completed. The text can be split into chunks at any point. Pass
184
+ * `isFinal: true` with the last chunk (which can be empty) to emit the
185
+ * final row, if the text doesn't end with a line break.
186
+ *
187
+ * Once the delimiter is known, each chunk is parsed all the way to its end.
188
+ * The decoder keeps track of the parts of an unfinished row that it has
189
+ * already parsed (including a quote or escape character at the end of a
190
+ * chunk, whose meaning depends on the next chunk), so it never needs to
191
+ * keep the text itself.
192
+ */
193
+ parse(chunk, isFinal) {
194
+ let text = chunk;
195
+ if (this._detector) {
196
+ const buffer = this._buffer + chunk;
197
+ if (!this._detector.write(chunk) && !isFinal && buffer.length < this._maxCharsToDetectDelimiter) {
198
+ this._buffer = buffer;
199
+ return;
200
+ }
201
+ this._delimiter = this._detector.result();
202
+ this._delimiterCode = this._delimiter.charCodeAt(0);
203
+ this._detector = void 0;
204
+ this._buffer = "";
205
+ text = buffer;
206
+ }
207
+ let pos = 0;
208
+ if (text.length === 0) {
209
+ if (isFinal) this._finish();
210
+ return;
211
+ }
212
+ if (this._atStart) {
213
+ this._atStart = false;
214
+ if (text.charCodeAt(0) === BOM) pos = 1;
215
+ }
216
+ if (this._skipLineFeed) {
217
+ this._skipLineFeed = false;
218
+ if (text.charCodeAt(pos) === LF) pos++;
219
+ }
220
+ const end = text.length;
221
+ this._parse(text, pos, end, isFinal);
222
+ if (isFinal) {
223
+ this._finish();
224
+ return;
225
+ }
226
+ if (this._state === FIELD_START && this._row.length === 0 && text.charCodeAt(end - 1) === CR) this._skipLineFeed = true;
227
+ }
228
+ /**
229
+ * Emit the final row, once there is no more input
230
+ */
231
+ _finish() {
232
+ const state = this._state;
233
+ if (state === QUOTED || state === ESCAPE_PENDING) {
234
+ if (state === ESCAPE_PENDING) this._field += this._escape;
235
+ this._state = QUOTED;
236
+ throw this._error("missing closing quote");
237
+ }
238
+ if (state === FIELD_START && this._row.length === 0) return;
239
+ const row = this._row;
240
+ row.push(this._field);
241
+ this._row = [];
242
+ this._field = "";
243
+ this._state = FIELD_START;
244
+ this._endRow(row, state === UNQUOTED || state === LEADING_SPACE);
245
+ }
246
+ _endRow(row, lastFieldUnquoted) {
247
+ this._rowCount++;
248
+ if (this._ignoreEmpty && lastFieldUnquoted && row.length === 1 && isBlank(row[0])) return;
249
+ this._onRow(row);
250
+ }
251
+ _error(message) {
252
+ return /* @__PURE__ */ new SyntaxError(`CsvDecoder: Invalid CSV on row ${this._rowCount + 1}: ${message}`);
253
+ }
254
+ /**
255
+ * Returns the length of the line break at `pos`, or 0 if there isn't one.
256
+ * `pos` must be less than `end`.
257
+ */
258
+ _lineBreakAt(text, pos, end) {
259
+ const code = text.charCodeAt(pos);
260
+ if (code === LF) return 1;
261
+ if (code === CR) return pos + 1 < end && text.charCodeAt(pos + 1) === LF ? 2 : 1;
262
+ return 0;
263
+ }
264
+ /**
265
+ * Parse `text` from `pos` to `end`, updating the parser's state so it can
266
+ * carry on from where it got to with the next chunk.
267
+ */
268
+ _parse(text, pos, end, isFinal) {
269
+ const delimiter = this._delimiter;
270
+ const delimiterCode = this._delimiterCode;
271
+ const quoteCode = this._quoteCode;
272
+ let state = this._state;
273
+ let row = this._row;
274
+ let field = this._field;
275
+ let nextDelimiter = -1;
276
+ let nextLF = -1;
277
+ let nextCR = -1;
278
+ while (pos < end) {
279
+ if (state === QUOTE_PENDING) {
280
+ if (text.charCodeAt(pos) === quoteCode) {
281
+ field += this._quote;
282
+ pos++;
283
+ state = QUOTED;
284
+ } else state = AFTER_QUOTE;
285
+ } else if (state === ESCAPE_PENDING) {
286
+ const code = text.charCodeAt(pos);
287
+ if (code === quoteCode || code === this._escapeCode) {
288
+ field += text[pos];
289
+ pos++;
290
+ } else field += this._escape;
291
+ state = QUOTED;
292
+ }
293
+ if (state === FIELD_START) {
294
+ const code = text.charCodeAt(pos);
295
+ if (code === quoteCode) {
296
+ pos++;
297
+ state = QUOTED;
298
+ } else if ((code === SPACE || code === TAB) && code !== delimiterCode && quoteCode !== -1) state = LEADING_SPACE;
299
+ else state = UNQUOTED;
300
+ }
301
+ if (state === LEADING_SPACE) {
302
+ let p = pos;
303
+ while (p < end) {
304
+ const c = text.charCodeAt(p);
305
+ if (c !== SPACE && c !== TAB || c === delimiterCode) break;
306
+ p++;
307
+ }
308
+ if (p === end && !isFinal) {
309
+ field += text.slice(pos, end);
310
+ pos = end;
311
+ break;
312
+ }
313
+ if (p < end && text.charCodeAt(p) === quoteCode) {
314
+ field = "";
315
+ pos = p + 1;
316
+ state = QUOTED;
317
+ } else state = UNQUOTED;
318
+ }
319
+ if (state === UNQUOTED) {
320
+ if (nextDelimiter < pos) nextDelimiter = find(text, delimiter, pos, end);
321
+ if (nextLF < pos) nextLF = find(text, "\n", pos, end);
322
+ if (nextCR < pos) nextCR = find(text, "\r", pos, end);
323
+ const lineBreak = nextLF < nextCR ? nextLF : nextCR;
324
+ const lineBreakLength = lineBreak < nextDelimiter ? this._lineBreakAt(text, lineBreak, end) : 0;
325
+ if (nextDelimiter < lineBreak) {
326
+ const value = field === "" ? text.slice(pos, nextDelimiter) : field + text.slice(pos, nextDelimiter);
327
+ field = "";
328
+ row.push(value);
329
+ pos = nextDelimiter + 1;
330
+ state = FIELD_START;
331
+ } else if (lineBreak < end) {
332
+ const value = field === "" ? text.slice(pos, lineBreak) : field + text.slice(pos, lineBreak);
333
+ field = "";
334
+ row.push(value);
335
+ pos = lineBreak + lineBreakLength;
336
+ state = FIELD_START;
337
+ const completed = row;
338
+ row = [];
339
+ this._endRow(completed, true);
340
+ } else {
341
+ field += text.slice(pos, end);
342
+ pos = end;
343
+ }
344
+ continue;
345
+ }
346
+ if (state === QUOTED) {
347
+ const result = this._escapeCode === quoteCode ? this._parseQuotedDoubled(text, pos, end, isFinal, field) : this._parseQuotedEscaped(text, pos, end, isFinal, field);
348
+ field = this._quotedValue;
349
+ if (result === QUOTED_CONTINUES) {
350
+ pos = end;
351
+ break;
352
+ }
353
+ if (result === QUOTED_PENDING) {
354
+ pos = end;
355
+ state = this._escapeCode === quoteCode ? QUOTE_PENDING : ESCAPE_PENDING;
356
+ break;
357
+ }
358
+ pos = result;
359
+ state = AFTER_QUOTE;
360
+ }
361
+ while (pos < end) {
362
+ const code = text.charCodeAt(pos);
363
+ if (code === delimiterCode) {
364
+ row.push(field);
365
+ field = "";
366
+ pos++;
367
+ state = FIELD_START;
368
+ break;
369
+ }
370
+ const lineBreakLength = this._lineBreakAt(text, pos, end);
371
+ if (lineBreakLength !== 0) {
372
+ row.push(field);
373
+ field = "";
374
+ pos += lineBreakLength;
375
+ state = FIELD_START;
376
+ const completed = row;
377
+ row = [];
378
+ this._endRow(completed, false);
379
+ break;
380
+ }
381
+ if (code === SPACE || code === TAB) {
382
+ pos++;
383
+ continue;
384
+ }
385
+ this._state = state;
386
+ this._row = row;
387
+ this._field = field;
388
+ throw this._error(`expected ${JSON.stringify(delimiter)} or a line break after the closing quote, but got ${JSON.stringify(text[pos])}`);
389
+ }
390
+ }
391
+ this._state = state;
392
+ this._row = row;
393
+ this._field = field;
394
+ }
395
+ _quotedValue = "";
396
+ /**
397
+ * Parse a quoted field where quotes are escaped by doubling them, starting
398
+ * after the opening quote (or where the previous chunk ended). Returns the
399
+ * position after the closing quote, `QUOTED_CONTINUES` if the field
400
+ * continues in the next chunk, or `QUOTED_PENDING` if the text ends with a
401
+ * quote that could be the closing quote or the start of an escaped quote.
402
+ * The value so far is set in `_quotedValue`.
403
+ */
404
+ _parseQuotedDoubled(text, pos, end, isFinal, field) {
405
+ const quote = this._quote;
406
+ const quoteCode = this._quoteCode;
407
+ for (;;) {
408
+ const q = find(text, quote, pos, end);
409
+ if (q === end) {
410
+ this._quotedValue = field + text.slice(pos, end);
411
+ if (isFinal) {
412
+ this._field = this._quotedValue;
413
+ this._state = QUOTED;
414
+ throw this._error("missing closing quote");
415
+ }
416
+ return QUOTED_CONTINUES;
417
+ }
418
+ if (q + 1 < end) {
419
+ if (text.charCodeAt(q + 1) === quoteCode) {
420
+ field += text.slice(pos, q + 1);
421
+ pos = q + 2;
422
+ continue;
423
+ }
424
+ } else if (!isFinal) {
425
+ this._quotedValue = field + text.slice(pos, q);
426
+ return QUOTED_PENDING;
427
+ }
428
+ this._quotedValue = field === "" ? text.slice(pos, q) : field + text.slice(pos, q);
429
+ return q + 1;
430
+ }
431
+ }
432
+ /**
433
+ * Parse a quoted field where quotes (and the escape character itself) are
434
+ * escaped by a different escape character. See `_parseQuotedDoubled`.
435
+ */
436
+ _parseQuotedEscaped(text, pos, end, isFinal, field) {
437
+ const quote = this._quote;
438
+ const quoteCode = this._quoteCode;
439
+ const escape = this._escape;
440
+ const escapeCode = this._escapeCode;
441
+ let nextEscape = -1;
442
+ for (;;) {
443
+ const q = find(text, quote, pos, end);
444
+ if (nextEscape < pos) nextEscape = find(text, escape, pos, end);
445
+ if (nextEscape < q) {
446
+ const e = nextEscape;
447
+ if (e + 1 === end && !isFinal) {
448
+ this._quotedValue = field + text.slice(pos, e);
449
+ return QUOTED_PENDING;
450
+ }
451
+ const next = e + 1 < end ? text.charCodeAt(e + 1) : -1;
452
+ if (next === quoteCode || next === escapeCode) {
453
+ field += text.slice(pos, e) + text[e + 1];
454
+ pos = e + 2;
455
+ } else {
456
+ field += text.slice(pos, e + 1);
457
+ pos = e + 1;
458
+ }
459
+ continue;
460
+ }
461
+ if (q === end) {
462
+ this._quotedValue = field + text.slice(pos, end);
463
+ if (isFinal) {
464
+ this._field = this._quotedValue;
465
+ this._state = QUOTED;
466
+ throw this._error("missing closing quote");
467
+ }
468
+ return QUOTED_CONTINUES;
469
+ }
470
+ this._quotedValue = field + text.slice(pos, q);
471
+ return q + 1;
472
+ }
473
+ }
474
+ };
475
+ function isBlank(value) {
476
+ for (let i = 0; i < value.length; i++) {
477
+ const code = value.charCodeAt(i);
478
+ if (code !== SPACE && code !== TAB) return false;
479
+ }
480
+ return true;
481
+ }
482
+ /**
483
+ * Decode a stream of CSV text into rows, where each row is an array of
484
+ * strings. The text can be split into chunks at any point.
485
+ */
486
+ var CsvDecoderStream = class extends TransformStream {
487
+ constructor(options) {
488
+ let decoder;
489
+ super({
490
+ start(controller) {
491
+ decoder = new CsvDecoder((row) => controller.enqueue(row), options);
492
+ },
493
+ transform(chunk) {
494
+ decoder.parse(chunk, false);
495
+ },
496
+ flush() {
497
+ decoder.parse("", true);
498
+ }
499
+ });
500
+ }
501
+ };
502
+ export { CsvDecoder, CsvDecoderStream as default };
@@ -0,0 +1,63 @@
1
+ import { t as LineEnding } from "./LineEndings-CET4b2lJ.mjs";
2
+ export interface CsvEncoderOptions {
3
+ /** The text between fields. Defaults to `","`. */
4
+ readonly delimiter?: string;
5
+ /** The text between rows. Defaults to `"\n"`. */
6
+ readonly rowDelimiter?: LineEnding;
7
+ /**
8
+ * The character used to quote fields. Defaults to `'"'`.
9
+ */
10
+ readonly quote?: string;
11
+ /**
12
+ * The character used to escape quotes in quoted fields. Defaults to the
13
+ * quote character. If it is a different character, it is also used to
14
+ * escape itself.
15
+ */
16
+ readonly escape?: string;
17
+ /**
18
+ * Defaults to "AUTO", which quotes fields if they need to (i.e. if they
19
+ * contain any special characters). Set this to `"ALWAYS"` to add quotes
20
+ * even if they are not needed, and set it to `"NEVER"` to never add quotes.
21
+ */
22
+ readonly quoteMode?: "ALWAYS" | "AUTO" | "NEVER";
23
+ /**
24
+ * Write `rowDelimiter` after the last row. Defaults to `false`, in which
25
+ * case each row except the first starts with `rowDelimiter`.
26
+ */
27
+ readonly includeEndRowDelimiter?: boolean;
28
+ /** Write a byte order mark at the start of the output. Defaults to `false`. */
29
+ readonly writeBOM?: boolean;
30
+ }
31
+ /**
32
+ * The CSV encoder used by `CsvEncoderStream`. You can use it directly if you
33
+ * want to encode CSV without using streams.
34
+ */
35
+ export declare class CsvEncoder {
36
+ private readonly _delimiter;
37
+ private readonly _rowDelimiter;
38
+ private readonly _quote;
39
+ private readonly _escape;
40
+ private readonly _alwaysQuote;
41
+ private readonly _neverQuote;
42
+ private readonly _includeEndRowDelimiter;
43
+ private readonly _writeBOM;
44
+ private readonly _specialRegexp;
45
+ private readonly _escapeRegexp;
46
+ private readonly _escapeReplacement;
47
+ private _isFirstRow;
48
+ constructor(opts?: CsvEncoderOptions);
49
+ /**
50
+ * Format one field. `quoteIfBlank` is set for a row with only one field, as
51
+ * that row would otherwise be a blank line, which is lost if it's the last
52
+ * row (and skipped by decoders that ignore blank lines).
53
+ */
54
+ private _formatField;
55
+ formatRow(columns: readonly string[]): string;
56
+ }
57
+ /**
58
+ * Encode a stream of rows, where each row is an array of strings, as CSV
59
+ * text. Each row is emitted as a separate chunk.
60
+ */
61
+ export default class CsvEncoderStream extends TransformStream<readonly string[], string> {
62
+ constructor(options?: CsvEncoderOptions);
63
+ }
@@ -0,0 +1,95 @@
1
+ import { t as getCsvChar } from "./CsvOptions-BAnaU_B9.mjs";
2
+ // src/CsvEncoderStream.ts
3
+ const BOM = "";
4
+ /**
5
+ * The CSV encoder used by `CsvEncoderStream`. You can use it directly if you
6
+ * want to encode CSV without using streams.
7
+ */
8
+ var CsvEncoder = class {
9
+ _delimiter;
10
+ _rowDelimiter;
11
+ _quote;
12
+ _escape;
13
+ _alwaysQuote;
14
+ _neverQuote;
15
+ _includeEndRowDelimiter;
16
+ _writeBOM;
17
+ _specialRegexp;
18
+ _escapeRegexp;
19
+ _escapeReplacement;
20
+ _isFirstRow = true;
21
+ constructor(opts) {
22
+ this._delimiter = getCsvChar("CsvEncoder", "delimiter", opts?.delimiter ?? ",");
23
+ this._rowDelimiter = opts?.rowDelimiter ?? "\n";
24
+ this._quote = getCsvChar("CsvEncoder", "quote", opts?.quote ?? `"`);
25
+ this._escape = getCsvChar("CsvEncoder", "escape", opts?.escape ?? this._quote);
26
+ const quoteMode = opts?.quoteMode ?? "AUTO";
27
+ if (quoteMode !== "ALWAYS" && quoteMode !== "AUTO" && quoteMode !== "NEVER") throw new TypeError(`CsvEncoder: quoteMode must be "ALWAYS", "AUTO" or "NEVER", got ${JSON.stringify(quoteMode)}`);
28
+ this._alwaysQuote = quoteMode === "ALWAYS";
29
+ this._neverQuote = quoteMode === "NEVER";
30
+ if (!this._neverQuote && this._delimiter === this._quote) throw new TypeError("CsvEncoder: delimiter and quote must be different");
31
+ this._includeEndRowDelimiter = opts?.includeEndRowDelimiter ?? false;
32
+ this._writeBOM = opts?.writeBOM ?? false;
33
+ this._specialRegexp = new RegExp(`[${charClass(this._delimiter + this._quote + this._rowDelimiter + "\r\n\0")}]`);
34
+ this._escapeRegexp = new RegExp(`[${charClass(this._quote + this._escape)}]`, "g");
35
+ this._escapeReplacement = this._escape.replace(/\$/g, "$$$$") + "$&";
36
+ }
37
+ /**
38
+ * Format one field. `quoteIfBlank` is set for a row with only one field, as
39
+ * that row would otherwise be a blank line, which is lost if it's the last
40
+ * row (and skipped by decoders that ignore blank lines).
41
+ */
42
+ _formatField(value, quoteIfBlank) {
43
+ let special = this._specialRegexp.test(value);
44
+ if (special && value.includes("\0")) {
45
+ value = value.replace(/\0/g, "");
46
+ special = this._specialRegexp.test(value);
47
+ }
48
+ if (!this._neverQuote && (special || this._alwaysQuote || quoteIfBlank && isBlank(value))) return this._quote + value.replace(this._escapeRegexp, this._escapeReplacement) + this._quote;
49
+ return value;
50
+ }
51
+ formatRow(columns) {
52
+ const isFirst = this._isFirstRow;
53
+ this._isFirstRow = false;
54
+ let formattedCols = isFirst ? this._writeBOM ? BOM : "" : !this._includeEndRowDelimiter ? this._rowDelimiter : "";
55
+ if (columns.length === 1) formattedCols += this._formatField(columns[0], true);
56
+ else for (let i = 0; i < columns.length; i++) {
57
+ if (i !== 0) formattedCols += this._delimiter;
58
+ formattedCols += this._formatField(columns[i], false);
59
+ }
60
+ if (this._includeEndRowDelimiter) return formattedCols + this._rowDelimiter;
61
+ else return formattedCols;
62
+ }
63
+ };
64
+ /**
65
+ * Whether `value` is empty, or only contains spaces and tabs
66
+ */
67
+ function isBlank(value) {
68
+ for (let i = 0; i < value.length; i++) {
69
+ const code = value.charCodeAt(i);
70
+ if (code !== 32 && code !== 9) return false;
71
+ }
72
+ return true;
73
+ }
74
+ /**
75
+ * The characters in `chars`, escaped so they can be used in a regex
76
+ * character class
77
+ */
78
+ function charClass(chars) {
79
+ let result = "";
80
+ for (let i = 0; i < chars.length; i++) result += `\\u${chars.charCodeAt(i).toString(16).padStart(4, "0")}`;
81
+ return result;
82
+ }
83
+ /**
84
+ * Encode a stream of rows, where each row is an array of strings, as CSV
85
+ * text. Each row is emitted as a separate chunk.
86
+ */
87
+ var CsvEncoderStream = class extends TransformStream {
88
+ constructor(options) {
89
+ const encoder = new CsvEncoder(options);
90
+ super({ transform(chunk, controller) {
91
+ controller.enqueue(encoder.formatRow(chunk));
92
+ } });
93
+ }
94
+ };
95
+ export { CsvEncoder, CsvEncoderStream as default };
@@ -0,0 +1,7 @@
1
+ import { CsvDecoderOptions } from "./CsvDecoderStream.mjs";
2
+ import { n as TableDecoderOptions, r as TableRow, t as TableCellParser } from "./TableDecoder-VilUaURR.mjs";
3
+ export interface CsvObjectDecoderStreamOptions<TObject> extends CsvDecoderOptions, TableDecoderOptions<TObject> {}
4
+ export default class CsvObjectDecoderStream<TObject> extends TransformStream<string, TObject> {
5
+ constructor(getObject: (row: TableRow) => TObject, options?: CsvObjectDecoderStreamOptions<TObject>);
6
+ }
7
+ export type { TableCellParser, TableRow };
@@ -0,0 +1,21 @@
1
+ import { CsvDecoder } from "./CsvDecoderStream.mjs";
2
+ import { t as TableDecoder } from "./TableDecoder-CUD0If2r.mjs";
3
+ // src/CsvObjectDecoderStream.ts
4
+ var CsvObjectDecoderStream = class extends TransformStream {
5
+ constructor(getObject, options = {}) {
6
+ let decoder;
7
+ super({
8
+ start(controller) {
9
+ const tableDecoder = new TableDecoder(getObject, options);
10
+ decoder = new CsvDecoder((chunk) => tableDecoder.transform(chunk, controller), options);
11
+ },
12
+ transform(chunk) {
13
+ decoder.parse(chunk, false);
14
+ },
15
+ flush() {
16
+ decoder.parse("", true);
17
+ }
18
+ });
19
+ }
20
+ };
21
+ export { CsvObjectDecoderStream as default };
@@ -0,0 +1,7 @@
1
+ import { CsvEncoderOptions } from "./CsvEncoderStream.mjs";
2
+ import { n as TableEncoderOptions, t as TableColumn } from "./TableEncoder-DCH6bFmO.mjs";
3
+ export interface CsvObjectEncoderStreamOptions extends CsvEncoderOptions, TableEncoderOptions {}
4
+ export default class CsvObjectEncoderStream<TObject> extends TransformStream<TObject, string> {
5
+ constructor(columns: readonly TableColumn<TObject>[], options?: CsvObjectEncoderStreamOptions);
6
+ }
7
+ export type { TableColumn };