web-utility-streams 1.0.0 → 1.1.0-canary-3

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 CHANGED
@@ -7,6 +7,10 @@ Various utility streams that are very useful for working with web streams.
7
7
  **Transform streams**
8
8
 
9
9
  - [`AddPrefixStream`](#addprefixstream) - Emit some chunks before the rest of the stream.
10
+ - [`CsvDecoderStream`](#csvdecoderstream) - Decode CSV text into rows.
11
+ - [`CsvEncoderStream`](#csvencoderstream) - Encode rows as CSV text.
12
+ - [`CsvObjectDecoderStream`](#csvobjectdecoderstream) - Decode CSV text with a header row into objects.
13
+ - [`CsvObjectEncoderStream`](#csvobjectencoderstream) - Encode objects as CSV text with a header row.
10
14
  - [`DebounceStream`](#debouncestream) - Emit at most one chunk per period, dropping the rest.
11
15
  - [`DebugStream`](#debugstream) - Call a function with each chunk as it passes through.
12
16
  - [`EventSourceDecoderStream`](#eventsourcedecoderstream) - Decode `text/event-stream` (Server-Sent Events) text into events.
@@ -20,6 +24,8 @@ Various utility streams that are very useful for working with web streams.
20
24
  - [`NewlineDelimitedJsonDecoderStream`](#newlinedelimitedjsondecoderstream) - Parse each line of NDJSON text into a value.
21
25
  - [`NewlineDelimitedJsonEncoderStream`](#newlinedelimitedjsonencoderstream) - Encode each value as a line of NDJSON.
22
26
  - [`SplitLinesStream`](#splitlinesstream) - Split text into lines.
27
+ - [`TableDecoderStream`](#tabledecoderstream) - Turn rows (with a header row) into objects.
28
+ - [`TableEncoderStream`](#tableencoderstream) - Turn objects into rows, with a header row.
23
29
  - [`TimeoutStream`](#timeoutstream) - Error the stream if no chunk arrives for too long.
24
30
  - [`TransformPipelineStream`](#transformpipelinestream) - Combine several transform streams into one.
25
31
  - [`TransformStreamWithCancel`](#transformstreamwithcancel) - A `TransformStream` that calls the transformer's `cancel` method, in any runtime.
@@ -71,6 +77,152 @@ const events = updates.pipeThrough(
71
77
 
72
78
  The prefix is only read as the output is read, and written chunks wait until it's done. If the prefix errors, the stream errors. If the stream is cancelled or errors first, the prefix is closed, so a generator's `finally` blocks run and a `ReadableStream` is cancelled.
73
79
 
80
+ ### CsvDecoderStream
81
+
82
+ Decode a stream of CSV text into rows, where each row is an array of strings. The text can be split into chunks at any point, and each row is emitted as soon as it is complete.
83
+
84
+ ```ts
85
+ import CsvDecoderStream from "web-utility-streams/CsvDecoderStream";
86
+
87
+ const response = await fetch("https://example.com/users.csv");
88
+ const rows = response
89
+ .body!.pipeThrough(new TextDecoderStream())
90
+ .pipeThrough(new CsvDecoderStream());
91
+
92
+ for await (const [id, name, email] of rows) {
93
+ console.log(id, name, email);
94
+ }
95
+ ```
96
+
97
+ Fields can be quoted, so they can contain delimiters, quotes and line breaks. A quote within a quoted field is escaped by doubling it (`""`). Spaces and tabs around a quoted field are ignored, but spaces in unquoted fields are kept. Rows can end with `"\r\n"`, `"\n"` or `"\r"`, a final line break doesn't produce an extra row, and a byte order mark at the start of the text is removed. Invalid CSV (text after a closing quote, or a quoted field with no closing quote) errors the stream with a `SyntaxError`. These options can be passed to the constructor:
98
+
99
+ | Option | Description | Default |
100
+ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
101
+ | `delimiter` | The character that separates fields, e.g. `","`, `";"` or `"\t"`. | Guessed from the first line (see below) |
102
+ | `maxCharsToGuessDelimiter` | If `delimiter` isn't passed, the most characters to read before guessing it, if the first line is longer than this (see below). | `10000` |
103
+ | `quote` | The character used to quote fields, or `false` to treat quotes like any other character. | `'"'` |
104
+ | `escape` | The character that escapes a quote in a quoted field. If it isn't the quote character (e.g. `"\\"`), it also escapes itself, and is kept as it is before any other character. | The quote character |
105
+ | `ignoreEmpty` | Skip blank lines (lines that are empty or only contain spaces and tabs), rather than emitting them as a row with one field. | `false` |
106
+
107
+ If you don't pass a `delimiter`, it's guessed from the first line of the text: whichever of `","`, `";"` and `"\t"` appears most often, not counting any in quoted fields. If there's a tie, or none of them appear, `","` is preferred, then `";"`. No rows are emitted until the end of the first line has been read, or `maxCharsToGuessDelimiter` characters (10,000 by default), if that comes first. That limit is checked after each chunk, so all of the chunk that reaches it is used to guess. If you know which delimiter your data uses, it's best to pass it, as a file with a single column could contain one of these characters in its first line. You must pass a `delimiter` if `quote` or `escape` is one of these characters.
108
+
109
+ If your CSV has a header row, and you want each row as an object, use [`CsvObjectDecoderStream`](#csvobjectdecoderstream) instead.
110
+
111
+ The parser is also exported as `CsvDecoder`, if you want to parse CSV text without using streams.
112
+
113
+ ### CsvEncoderStream
114
+
115
+ Encode a stream of rows (arrays of strings) as CSV text. By default, fields are quoted if they contain the delimiter, a quote or a line break, and quotes within them are escaped.
116
+
117
+ ```ts
118
+ import CsvEncoderStream from "web-utility-streams/CsvEncoderStream";
119
+
120
+ return new Response(
121
+ users
122
+ .pipeThrough(
123
+ new MapStream((user) => [String(user.id), user.name, user.email]),
124
+ )
125
+ .pipeThrough(new CsvEncoderStream({ includeEndRowDelimiter: true }))
126
+ .pipeThrough(new TextEncoderStream()),
127
+ { headers: { "Content-Type": "text/csv" } },
128
+ );
129
+ ```
130
+
131
+ Every field must be a string, so convert other values (e.g. numbers, or `null` to `""`) before encoding them. These options can be passed to the constructor:
132
+
133
+ | Option | Description | Default |
134
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
135
+ | `delimiter` | The text between fields. | `","` |
136
+ | `rowDelimiter` | The text between rows. | `"\n"` |
137
+ | `includeEndRowDelimiter` | Also write `rowDelimiter` after the last row. Without this, each row's chunk starts with `rowDelimiter` (except the first), rather than ending with it. | `false` |
138
+ | `quote` | The character used to quote fields. | `'"'` |
139
+ | `escape` | The character used to escape quotes in quoted fields. If it isn't the quote character, it is also used to escape itself. | The quote character |
140
+ | `quoteMode` | `"AUTO"` quotes fields that need it (those containing the delimiter, a quote or a line break), `"ALWAYS"` quotes every field, and `"NEVER"` never quotes fields. | `"AUTO"` |
141
+ | `writeBOM` | Write a byte order mark at the start of the output, which helps some programs (e.g. Excel) detect that the text is UTF-8. | `false` |
142
+
143
+ If you're encoding objects, and want a header row, use [`CsvObjectEncoderStream`](#csvobjectencoderstream) instead.
144
+
145
+ The encoder is also exported as `CsvEncoder`, if you want to encode CSV text without using streams.
146
+
147
+ ### CsvObjectDecoderStream
148
+
149
+ Decode a stream of CSV text, whose first row is a header row, into objects. Pass a function that builds the object for each row, by looking its fields up by column name:
150
+
151
+ ```ts
152
+ import CsvObjectDecoderStream from "web-utility-streams/CsvObjectDecoderStream";
153
+
154
+ const response = await fetch("https://example.com/users.csv");
155
+ const users = response.body!.pipeThrough(new TextDecoderStream()).pipeThrough(
156
+ new CsvObjectDecoderStream((row) => ({
157
+ id: row.parse("id", parseInteger),
158
+ name: row.get("name"),
159
+ email: row.getOptional("email") ?? null,
160
+ })),
161
+ );
162
+
163
+ for await (const user of users) {
164
+ console.log(user.id, user.name, user.email);
165
+ }
166
+
167
+ function parseInteger(value: string): number {
168
+ if (!/^-?\d+$/.test(value)) throw new Error(`Expected an integer`);
169
+ return Number(value);
170
+ }
171
+ ```
172
+
173
+ The function is passed a row, which has these properties and methods (call them on the row, rather than destructuring them):
174
+
175
+ | Property or method | Description |
176
+ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
177
+ | `index` | The 0-based index of the row, not counting the header row. This isn't the line number, as quoted fields can contain line breaks. |
178
+ | `get(columnName)` | The value of a column. Throws a "missing column" error if there's no column with that name. |
179
+ | `getOptional(columnName)` | The value of a column, or `undefined` if there's no column with that name. |
180
+ | `parse(columnName, parser)` | The value of a column (as with `get`), passed through `parser`, which is a function or an object with a `parse` method (such as a [Funtypes](https://funtypes.dev) schema). If it throws, the cell is invalid. |
181
+ | `parseOptional(columnName, parser)` | The same as `parse`, but returns `undefined` (without calling `parser`) if there's no column with that name. |
182
+ | `toObject()` | The whole row, as an object whose keys are the column names, and whose values are strings. |
183
+
184
+ A header row can contain the same column name more than once, but reading that column (or calling `toObject()`) throws a "duplicate column" error.
185
+
186
+ By default, any of these errors, or any error thrown by your function, errors the stream with `Error decoding row <index>: <message>`, whose `cause` is the original error. To skip rows with errors instead, or replace them, pass these options. Each is passed the stream's controller, so it can enqueue a replacement value with `controller.enqueue(value)`, or end the stream with `controller.error(err)`. If it does neither, the row is skipped.
187
+
188
+ | Option | Called with | Called when |
189
+ | ------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
190
+ | `onHeaders` | `(headers)` | The header row has been read, before any objects are emitted. |
191
+ | `onMissingColumn` | `(columnName, controller)` | `get` or `parse` is called with a column name that isn't in the header row. |
192
+ | `onDuplicateColumn` | `(columnName, controller)` | A column that appears more than once in the header row is read. |
193
+ | `onInvalidCell` | `(index, columnName, error, controller)` | A parser throws. `error` is the error it threw. |
194
+ | `onInvalidRow` | `(index, error, controller)` | A row has too many fields, your function throws, or one of the errors above happens and its option isn't passed. |
195
+
196
+ All of [`CsvDecoderStream`](#csvdecoderstream)'s options can also be passed. It gives the same results as piping [`CsvDecoderStream`](#csvdecoderstream) into [`TableDecoderStream`](#tabledecoderstream), but is about 10–15% faster, as each row doesn't have to go through a second stream (see [benchmarks/results/decode-csv-objects.md](benchmarks/results/decode-csv-objects.md)).
197
+
198
+ ### CsvObjectEncoderStream
199
+
200
+ Encode a stream of objects as CSV text, with a header row. Pass an array of columns, where each column is a header and a function that gets that column's field from an object (and its 0-based index):
201
+
202
+ ```ts
203
+ import CsvObjectEncoderStream from "web-utility-streams/CsvObjectEncoderStream";
204
+
205
+ return new Response(
206
+ users
207
+ .pipeThrough(
208
+ new CsvObjectEncoderStream<User>(
209
+ [
210
+ ["id", (user) => String(user.id)],
211
+ ["name", (user) => user.name],
212
+ ["email", (user) => user.email ?? ""],
213
+ ],
214
+ { includeEndRowDelimiter: true },
215
+ ),
216
+ )
217
+ .pipeThrough(new TextEncoderStream()),
218
+ { headers: { "Content-Type": "text/csv" } },
219
+ );
220
+ ```
221
+
222
+ The columns are written in the order of the array, and the same header can be used more than once. Each function must return a string, so convert other values (e.g. numbers, or `null` to `""`) yourself. If a function throws, the stream is errored. The header row is written even if there are no objects. Pass `skipHeaders: true` to leave it out (e.g. when appending to an existing file). All of [`CsvEncoderStream`](#csvencoderstream)'s options can also be passed.
223
+
224
+ It gives the same output as piping [`TableEncoderStream`](#tableencoderstream) into [`CsvEncoderStream`](#csvencoderstream), but is about 15% faster (see [benchmarks/results/encode-csv-objects.md](benchmarks/results/encode-csv-objects.md)).
225
+
74
226
  ### DebounceStream
75
227
 
76
228
  Emit at most one chunk every `debounceMs` milliseconds, dropping the rest. This is useful for things like progress updates, where only the latest value matters.
@@ -354,6 +506,37 @@ for await (const line of lines) {
354
506
  }
355
507
  ```
356
508
 
509
+ ### TableDecoderStream
510
+
511
+ Turn a stream of rows (arrays of strings), whose first row is a header row, into objects. It works in the same way as [`CsvObjectDecoderStream`](#csvobjectdecoderstream), with the same function and options (apart from the CSV options), but takes rows rather than text. This is useful for rows that come from somewhere other than CSV, or when you need to do something to the rows first. For CSV text, `CsvObjectDecoderStream` is faster.
512
+
513
+ ```ts
514
+ import TableDecoderStream from "web-utility-streams/TableDecoderStream";
515
+
516
+ const users = rows.pipeThrough(
517
+ new TableDecoderStream((row) => ({
518
+ id: Number(row.get("id")),
519
+ name: row.get("name"),
520
+ })),
521
+ );
522
+ ```
523
+
524
+ ### TableEncoderStream
525
+
526
+ Turn a stream of objects into rows (arrays of strings), with a header row first. It takes the same columns and `skipHeaders` option as [`CsvObjectEncoderStream`](#csvobjectencoderstream), but emits rows rather than CSV text. For CSV, `CsvObjectEncoderStream` is faster.
527
+
528
+ ```ts
529
+ import TableEncoderStream from "web-utility-streams/TableEncoderStream";
530
+
531
+ const rows = users.pipeThrough(
532
+ new TableEncoderStream<User>([
533
+ ["id", (user) => String(user.id)],
534
+ ["name", (user) => user.name],
535
+ ]),
536
+ );
537
+ // ["id", "name"], ["1", "Ada"], ["2", "Grace"], ...
538
+ ```
539
+
357
540
  ### TimeoutStream
358
541
 
359
542
  Pass chunks through unchanged, but error the stream if no chunk is written for `timeoutMs` milliseconds. This is useful for detecting a connection that has stalled, such as a streaming API response that stops sending data without closing. When the timeout is reached, the stream is errored with a `TimeoutStreamError` (which has `code: "TIMEOUT_STREAM_TIMEOUT"`), so in a pipeline the source is cancelled and the error is thrown from `pipeTo`.
@@ -0,0 +1,122 @@
1
+ export interface CsvDecoderOptions {
2
+ /**
3
+ * The character that separates fields. By default, it is guessed from the
4
+ * first line: whichever of `","`, `";"` and `"\t"` appears most often
5
+ * (outside of quoted fields), or `","` if none of them do.
6
+ * It must be passed if `quote` or `escape` is one of these characters.
7
+ */
8
+ readonly delimiter?: string;
9
+ /**
10
+ * If `delimiter` isn't passed, the maximum number of characters to read
11
+ * before guessing it, if the first line is longer than this. This limits
12
+ * how much text is held, and how long rows are delayed, while guessing. The
13
+ * limit is checked after each chunk, so all of the chunk that reaches it is
14
+ * used. Defaults to 10,000.
15
+ */
16
+ readonly maxCharsToGuessDelimiter?: number;
17
+ /**
18
+ * The character used to quote fields. Defaults to `'"'`. Pass `false` to
19
+ * disable quoting, so quotes are treated like any other character.
20
+ */
21
+ readonly quote?: string | boolean;
22
+ /**
23
+ * The character used to escape a quote within a quoted field. Defaults to
24
+ * the quote character, so a quote is escaped by doubling it (`""`). If it is
25
+ * a different character (e.g. `"\\"`), it also escapes itself, and is kept
26
+ * as it is if it is followed by any other character.
27
+ */
28
+ readonly escape?: string;
29
+ /**
30
+ * Skip blank lines (lines that are empty, or only contain spaces and tabs),
31
+ * rather than emitting them as a row with a single field.
32
+ */
33
+ readonly ignoreEmpty?: boolean;
34
+ }
35
+ /**
36
+ * The CSV parser used by `CsvDecoderStream`. You can use it directly if you
37
+ * want to parse CSV text without using streams.
38
+ */
39
+ export declare class CsvDecoder {
40
+ private readonly _onRow;
41
+ private _delimiter;
42
+ private _delimiterCode;
43
+ private readonly _maxCharsToDetectDelimiter;
44
+ private readonly _quote;
45
+ private readonly _quoteCode;
46
+ private readonly _escape;
47
+ private readonly _escapeCode;
48
+ private readonly _ignoreEmpty;
49
+ /**
50
+ * The text so far, while we are reading the first line to guess the
51
+ * delimiter. Once the delimiter is known, all text is parsed as it arrives.
52
+ */
53
+ private _buffer;
54
+ /** Set until we have guessed the delimiter, if it wasn't passed */
55
+ private _detector;
56
+ private _state;
57
+ /** The fields of the current row that have been parsed so far */
58
+ private _row;
59
+ /** The start of the current field, if it continues in the next chunk */
60
+ private _field;
61
+ /** Whether we have not yet seen any text (so we need to skip a BOM) */
62
+ private _atStart;
63
+ /**
64
+ * Whether the previous chunk ended with a "\r" that ended a row, so a "\n"
65
+ * at the start of the next chunk is part of the same line break.
66
+ */
67
+ private _skipLineFeed;
68
+ /** The number of rows that have ended so far, for error messages */
69
+ private _rowCount;
70
+ constructor(onRow: (row: string[]) => void, opts?: CsvDecoderOptions);
71
+ /**
72
+ * Parse the next chunk of text, calling `onRow` for each row that is
73
+ * completed. The text can be split into chunks at any point. Pass
74
+ * `isFinal: true` with the last chunk (which can be empty) to emit the
75
+ * final row, if the text doesn't end with a line break.
76
+ *
77
+ * Once the delimiter is known, each chunk is parsed all the way to its end.
78
+ * The decoder keeps track of the parts of an unfinished row that it has
79
+ * already parsed (including a quote or escape character at the end of a
80
+ * chunk, whose meaning depends on the next chunk), so it never needs to
81
+ * keep the text itself.
82
+ */
83
+ parse(chunk: string, isFinal: boolean): void;
84
+ /**
85
+ * Emit the final row, once there is no more input
86
+ */
87
+ private _finish;
88
+ private _endRow;
89
+ private _error;
90
+ /**
91
+ * Returns the length of the line break at `pos`, or 0 if there isn't one.
92
+ * `pos` must be less than `end`.
93
+ */
94
+ private _lineBreakAt;
95
+ /**
96
+ * Parse `text` from `pos` to `end`, updating the parser's state so it can
97
+ * carry on from where it got to with the next chunk.
98
+ */
99
+ private _parse;
100
+ private _quotedValue;
101
+ /**
102
+ * Parse a quoted field where quotes are escaped by doubling them, starting
103
+ * after the opening quote (or where the previous chunk ended). Returns the
104
+ * position after the closing quote, `QUOTED_CONTINUES` if the field
105
+ * continues in the next chunk, or `QUOTED_PENDING` if the text ends with a
106
+ * quote that could be the closing quote or the start of an escaped quote.
107
+ * The value so far is set in `_quotedValue`.
108
+ */
109
+ private _parseQuotedDoubled;
110
+ /**
111
+ * Parse a quoted field where quotes (and the escape character itself) are
112
+ * escaped by a different escape character. See `_parseQuotedDoubled`.
113
+ */
114
+ private _parseQuotedEscaped;
115
+ }
116
+ /**
117
+ * Decode a stream of CSV text into rows, where each row is an array of
118
+ * strings. The text can be split into chunks at any point.
119
+ */
120
+ export default class CsvDecoderStream extends TransformStream<string, string[]> {
121
+ constructor(options?: CsvDecoderOptions);
122
+ }