web-utility-streams 0.0.0-stage → 0.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +470 -2
  3. package/lib/ConcatStream.d.mts +22 -0
  4. package/lib/ConcatStream.mjs +67 -0
  5. package/lib/DebugStream.d.mts +3 -0
  6. package/lib/DebugStream.mjs +12 -0
  7. package/lib/DeferredStream.d.mts +16 -0
  8. package/lib/DeferredStream.mjs +51 -0
  9. package/lib/EmptyStream.d.mts +3 -0
  10. package/lib/EmptyStream.mjs +9 -0
  11. package/lib/EventSourceDecoderStream.d.mts +39 -0
  12. package/lib/EventSourceDecoderStream.mjs +106 -0
  13. package/lib/EventSourceEncoderStream.d.mts +34 -0
  14. package/lib/EventSourceEncoderStream.mjs +57 -0
  15. package/lib/FilterMapStream.d.mts +8 -0
  16. package/lib/FilterMapStream.mjs +19 -0
  17. package/lib/FilterStream.d.mts +4 -0
  18. package/lib/FilterStream.mjs +9 -0
  19. package/lib/JsonDecoderStream.d.mts +55 -0
  20. package/lib/JsonDecoderStream.mjs +120 -0
  21. package/lib/JsonEncoderStream.d.mts +51 -0
  22. package/lib/JsonEncoderStream.mjs +96 -0
  23. package/lib/JsonTokenDecoderStream.d.mts +43 -0
  24. package/lib/JsonTokenDecoderStream.mjs +62 -0
  25. package/lib/JsonTokenizer-BFV5P0dO.mjs +298 -0
  26. package/lib/LazyStream.d.mts +18 -0
  27. package/lib/LazyStream.mjs +53 -0
  28. package/lib/LineEndings-CET4b2lJ.d.mts +5 -0
  29. package/lib/LineSplitter-CPGPZH7w.mjs +64 -0
  30. package/lib/MapStream.d.mts +7 -0
  31. package/lib/MapStream.mjs +18 -0
  32. package/lib/NewlineDelimitedJsonDecoderStream.d.mts +18 -0
  33. package/lib/NewlineDelimitedJsonDecoderStream.mjs +48 -0
  34. package/lib/NewlineDelimitedJsonEncoderStream.d.mts +15 -0
  35. package/lib/NewlineDelimitedJsonEncoderStream.mjs +16 -0
  36. package/lib/SplitLinesStream.d.mts +8 -0
  37. package/lib/SplitLinesStream.mjs +24 -0
  38. package/lib/TransformPipelineStream.d.mts +7 -0
  39. package/lib/TransformPipelineStream.mjs +17 -0
  40. package/lib/UnionStream.d.mts +21 -0
  41. package/lib/UnionStream.mjs +79 -0
  42. package/lib/consumers.d.mts +25 -0
  43. package/lib/consumers.mjs +82 -0
  44. package/lib/isPromiseLike-SjGgF7zP.mjs +9 -0
  45. package/lib/readableStreamToGenerator.d.mts +8 -0
  46. package/lib/readableStreamToGenerator.mjs +64 -0
  47. package/package.json +127 -4
@@ -0,0 +1,62 @@
1
+ import { t as JsonTokenizer } from "./JsonTokenizer-BFV5P0dO.mjs";
2
+ // src/JsonTokenDecoderStream.ts
3
+ /**
4
+ * Split a stream of JSON text into tokens. The text can be split into chunks
5
+ * at any point.
6
+ *
7
+ * The text must be a single JSON value, such as an object or array. Each
8
+ * token is checked to be valid (e.g. strings have valid escape sequences and
9
+ * numbers are correctly formatted), and to be in a valid place in the
10
+ * document (e.g. brackets match, and keys are followed by a `:`). Whitespace
11
+ * is skipped. If there is a problem, the stream is errored with a
12
+ * `SyntaxError` as soon as it is found, after emitting the tokens before it.
13
+ * If the input ends before the value is complete, the stream is errored with
14
+ * a `SyntaxError` when it closes.
15
+ *
16
+ * A number or `true`/`false`/`null` is only emitted once the character after
17
+ * it has been received (or the input ends), as it could continue in the next
18
+ * chunk.
19
+ */
20
+ var JsonTokenDecoderStream = class extends TransformStream {
21
+ constructor({ maxValueLength = 100 * 2 ** 20 } = {}) {
22
+ let tokenizer;
23
+ super({
24
+ start(controller) {
25
+ const onPunctuation = (code, position) => {
26
+ controller.enqueue({
27
+ type: "PUNCTUATION",
28
+ value: String.fromCharCode(code),
29
+ position
30
+ });
31
+ return false;
32
+ };
33
+ tokenizer = new JsonTokenizer("JsonTokenDecoderStream", maxValueLength, {
34
+ onLiteral(value, position) {
35
+ controller.enqueue({
36
+ type: "LITERAL",
37
+ value,
38
+ position
39
+ });
40
+ },
41
+ onKey(value, position) {
42
+ controller.enqueue({
43
+ type: "KEY",
44
+ value,
45
+ position
46
+ });
47
+ },
48
+ onOpen: onPunctuation,
49
+ onClose: onPunctuation,
50
+ onPunctuation
51
+ });
52
+ },
53
+ transform(chunk) {
54
+ tokenizer.write(chunk);
55
+ },
56
+ flush() {
57
+ tokenizer.end();
58
+ }
59
+ });
60
+ }
61
+ };
62
+ export { JsonTokenDecoderStream as default };
@@ -0,0 +1,298 @@
1
+ /** `}` or `]`: after a value or an open `{` or `[` */
2
+ const STATE_CLOSE = 1;
3
+ /** A value: at the start of the document, after a `:`, or after a `,` in an array */
4
+ const STATE_VALUE = 2;
5
+ /** A key: after a `{` or a `,` in an object */
6
+ const STATE_KEY = 4;
7
+ /** A `:`: after a key */
8
+ const STATE_COLON = 8;
9
+ /** A `,` or the end of the object/array: after a value */
10
+ const STATE_COMMA = 16;
11
+ /** Nothing (other than whitespace): after the document's root value */
12
+ const STATE_DONE = 32;
13
+ const STATE_STRING = 64;
14
+ const STATE_NUMBER = 128;
15
+ const STATE_LITERAL = 256;
16
+ const STATE_CAPTURE_REQUESTED = 512;
17
+ const STATE_ESCAPED = 1024;
18
+ const STATE_NEEDS_PARSING = 2048;
19
+ const isNumberChar = (code) => code >= 48 && code <= 57 || code === 46 || code === 43 || code === 45 || code === 101 || code === 69;
20
+ const isLetter = (code) => code >= 97 && code <= 122 || code >= 65 && code <= 90;
21
+ const IGNORE_ALL_TOKENS_HANDLERS = {
22
+ onLiteral() {},
23
+ onKey() {},
24
+ onOpen: () => false,
25
+ onClose() {},
26
+ onPunctuation() {}
27
+ };
28
+ /**
29
+ * Split JSON text, which can be split into chunks at any point, into tokens.
30
+ * The text must be a single JSON value (with optional whitespace around it).
31
+ * Throws a `SyntaxError`, with a message starting with `name`, for an invalid
32
+ * token, or a token in the wrong place, as soon as it is found.
33
+ */
34
+ var JsonTokenizer = class {
35
+ _name;
36
+ _maxValueLength;
37
+ _handlers;
38
+ _tokenText = "";
39
+ _tokenPosition = 0;
40
+ _offset = 0;
41
+ _openBrackets = [];
42
+ _state = STATE_VALUE;
43
+ _capturePosition = 0;
44
+ _captureText = "";
45
+ _captureDepth = 0;
46
+ constructor(name, maxValueLength, handlers) {
47
+ this._name = name;
48
+ this._maxValueLength = maxValueLength;
49
+ this._handlers = handlers;
50
+ }
51
+ _unexpected(description, position) {
52
+ throw new SyntaxError(`${this._name}: Unexpected ${description} at position ${position}`);
53
+ }
54
+ /**
55
+ * A value (of any type) has ended
56
+ */
57
+ _endValue() {
58
+ this._state = this._openBrackets.length === 0 ? STATE_DONE : 17;
59
+ }
60
+ _endLiteral() {
61
+ const text = this._tokenText;
62
+ this._tokenText = "";
63
+ if ((this._state & STATE_VALUE) !== STATE_VALUE) return this._unexpected(`token ${text}`, this._tokenPosition);
64
+ let value;
65
+ switch (text) {
66
+ case "true":
67
+ value = true;
68
+ break;
69
+ case "false":
70
+ value = false;
71
+ break;
72
+ case "null":
73
+ value = null;
74
+ break;
75
+ default: return this._unexpected(`token ${text}`, this._tokenPosition);
76
+ }
77
+ this._handlers.onLiteral(value, this._tokenPosition);
78
+ this._endValue();
79
+ }
80
+ _endNumber() {
81
+ const text = this._tokenText;
82
+ this._tokenText = "";
83
+ if ((this._state & STATE_VALUE) !== STATE_VALUE) return this._unexpected(`number ${text}`, this._tokenPosition);
84
+ let value;
85
+ try {
86
+ value = JSON.parse(text);
87
+ } catch {
88
+ return this._unexpected(`number ${text}`, this._tokenPosition);
89
+ }
90
+ this._handlers.onLiteral(value, this._tokenPosition);
91
+ this._endValue();
92
+ }
93
+ _endString() {
94
+ let value = this._tokenText;
95
+ this._tokenText = "";
96
+ if ((this._state & STATE_NEEDS_PARSING) !== STATE_NEEDS_PARSING) value = value.slice(1, -1);
97
+ else try {
98
+ value = JSON.parse(value);
99
+ } catch {
100
+ return this._unexpected(`string`, this._tokenPosition);
101
+ }
102
+ if ((this._state & STATE_KEY) === STATE_KEY) {
103
+ this._handlers.onKey(value, this._tokenPosition);
104
+ this._state = STATE_COLON;
105
+ } else if ((this._state & STATE_VALUE) === STATE_VALUE) {
106
+ this._handlers.onLiteral(value, this._tokenPosition);
107
+ this._endValue();
108
+ } else this._unexpected(`string`, this._tokenPosition);
109
+ }
110
+ /**
111
+ * Stop capturing, and process `text` as tokens instead. `text` must start
112
+ * at the beginning of the captured value (`_capturePosition`), and can
113
+ * include the rest of the current chunk after it.
114
+ */
115
+ _evaluateCapturedAsTokens(text) {
116
+ this._state = STATE_VALUE;
117
+ this._captureText = "";
118
+ this._handlers = IGNORE_ALL_TOKENS_HANDLERS;
119
+ this._offset = this._capturePosition;
120
+ this.write(text);
121
+ }
122
+ /**
123
+ * Scan for the end of the value being captured, starting at `start`.
124
+ * Returns the index after the end of the value, or -1 if it continues in
125
+ * the next chunk.
126
+ */
127
+ _scanCapture(chunk, start) {
128
+ let depth = this._captureDepth;
129
+ let inString = (this._state & STATE_STRING) === STATE_STRING;
130
+ let j = start;
131
+ if ((this._state & STATE_ESCAPED) === STATE_ESCAPED && j < chunk.length) {
132
+ this._state = this._state & -1025;
133
+ j++;
134
+ }
135
+ while (j < chunk.length) {
136
+ if (inString) {
137
+ const quote = chunk.indexOf("\"", j);
138
+ const stop = quote === -1 ? chunk.length : quote;
139
+ let backslashes = 0;
140
+ while (stop - backslashes > j && chunk.charCodeAt(stop - backslashes - 1) === 92) backslashes++;
141
+ if (quote === -1) {
142
+ this._state = backslashes % 2 === 1 ? this._state | STATE_ESCAPED : this._state & -1025;
143
+ break;
144
+ }
145
+ if (backslashes % 2 === 0) inString = false;
146
+ j = quote + 1;
147
+ continue;
148
+ }
149
+ const code = chunk.charCodeAt(j);
150
+ if (code === 34) inString = true;
151
+ else if (code === 123 || code === 91) depth++;
152
+ else if (code === 125 || code === 93) {
153
+ if (--depth === 0) {
154
+ this._captureDepth = 0;
155
+ return j + 1;
156
+ }
157
+ }
158
+ j++;
159
+ }
160
+ this._captureDepth = depth;
161
+ this._state = inString ? this._state | STATE_STRING : this._state & -65;
162
+ return -1;
163
+ }
164
+ _valueExceedsMaxLength(position) {
165
+ throw new Error(`${this._name}: Value at position ${position} exceeds the configured maximum value length of ${this._maxValueLength.toLocaleString()}`);
166
+ }
167
+ /**
168
+ * Process the next chunk of text, calling `onToken` for each complete token
169
+ */
170
+ write(chunk) {
171
+ let i = 0;
172
+ while (i < chunk.length) {
173
+ if ((this._state & STATE_CAPTURE_REQUESTED) === STATE_CAPTURE_REQUESTED) {
174
+ const end = this._scanCapture(chunk, i);
175
+ if (end === -1) {
176
+ this._captureText += chunk.slice(i);
177
+ if (this._captureText.length > this._maxValueLength) this._valueExceedsMaxLength(this._capturePosition);
178
+ break;
179
+ }
180
+ const text = this._captureText + chunk.slice(i, end);
181
+ let captured;
182
+ try {
183
+ captured = JSON.parse(text);
184
+ } catch {
185
+ this._evaluateCapturedAsTokens(this._captureText + chunk.slice(i));
186
+ return;
187
+ }
188
+ this._captureText = "";
189
+ this._handlers.onLiteral(captured, this._capturePosition);
190
+ this._endValue();
191
+ i = end;
192
+ continue;
193
+ }
194
+ if ((this._state & STATE_STRING) === STATE_STRING) {
195
+ let end = i;
196
+ let isEscaped = (this._state & STATE_ESCAPED) === STATE_ESCAPED;
197
+ for (; end < chunk.length; end++) {
198
+ const code = chunk.charCodeAt(end);
199
+ if (isEscaped) isEscaped = false;
200
+ else if (code === 92) {
201
+ isEscaped = true;
202
+ this._state = this._state | STATE_NEEDS_PARSING;
203
+ } else if (code === 34) break;
204
+ else if (code < 32) this._state = this._state | STATE_NEEDS_PARSING;
205
+ }
206
+ this._state = isEscaped ? this._state | STATE_ESCAPED : this._state & -1025;
207
+ if (end === chunk.length) {
208
+ this._tokenText += chunk.slice(i);
209
+ i = end;
210
+ } else {
211
+ this._tokenText += chunk.slice(i, end + 1);
212
+ i = end + 1;
213
+ this._endString();
214
+ }
215
+ continue;
216
+ }
217
+ const isLiteral = (this._state & STATE_LITERAL) === STATE_LITERAL;
218
+ const isNumber = (this._state & STATE_NUMBER) === STATE_NUMBER;
219
+ if (isLiteral || isNumber) {
220
+ const isPart = isNumber ? isNumberChar : isLetter;
221
+ let end = i;
222
+ while (end < chunk.length && isPart(chunk.charCodeAt(end))) end++;
223
+ this._tokenText += chunk.slice(i, end);
224
+ i = end;
225
+ if (end < chunk.length) {
226
+ if (isNumber) this._endNumber();
227
+ else this._endLiteral();
228
+ }
229
+ continue;
230
+ }
231
+ const code = chunk.charCodeAt(i);
232
+ const position = this._offset + i;
233
+ switch (code) {
234
+ case 32:
235
+ case 10:
236
+ case 13:
237
+ case 9:
238
+ i++;
239
+ break;
240
+ case 123:
241
+ case 91:
242
+ if ((this._state & STATE_VALUE) !== STATE_VALUE) this._unexpected(`token ${chunk[i]}`, position);
243
+ if (this._handlers.onOpen(code, position)) {
244
+ this._state = STATE_CAPTURE_REQUESTED;
245
+ this._capturePosition = position;
246
+ this._captureDepth = 0;
247
+ } else {
248
+ this._openBrackets.push(code);
249
+ this._state = (code === 123 ? STATE_KEY : STATE_VALUE) | STATE_CLOSE;
250
+ i++;
251
+ }
252
+ break;
253
+ case 58:
254
+ if (this._state !== STATE_COLON) this._unexpected("token :", position);
255
+ this._state = STATE_VALUE;
256
+ this._handlers.onPunctuation?.(code, position);
257
+ i++;
258
+ break;
259
+ case 44:
260
+ if ((this._state & STATE_COMMA) !== STATE_COMMA) this._unexpected("token ,", position);
261
+ this._state = this._openBrackets[this._openBrackets.length - 1] === 123 ? STATE_KEY : STATE_VALUE;
262
+ this._handlers.onPunctuation?.(code, position);
263
+ i++;
264
+ break;
265
+ case 125:
266
+ case 93:
267
+ if (this._openBrackets[this._openBrackets.length - 1] !== code - 2 || (this._state & STATE_CLOSE) !== STATE_CLOSE) this._unexpected(`token ${chunk[i]}`, position);
268
+ this._openBrackets.pop();
269
+ this._endValue();
270
+ this._handlers.onClose(code, position);
271
+ i++;
272
+ break;
273
+ case 34:
274
+ this._state = STATE_STRING | this._state;
275
+ this._tokenText = "\"";
276
+ this._tokenPosition = position;
277
+ i++;
278
+ break;
279
+ default:
280
+ if (code === 45 || code >= 48 && code <= 57) this._state = STATE_NUMBER | this._state;
281
+ else if (isLetter(code)) this._state = STATE_LITERAL | this._state;
282
+ else this._unexpected(`character ${JSON.stringify(chunk[i])}`, position);
283
+ this._tokenPosition = position;
284
+ }
285
+ }
286
+ this._offset += chunk.length;
287
+ }
288
+ /**
289
+ * Call once there is no more text, to emit any final token
290
+ */
291
+ end() {
292
+ if ((this._state & STATE_CAPTURE_REQUESTED) === STATE_CAPTURE_REQUESTED) this._evaluateCapturedAsTokens(this._captureText);
293
+ if ((this._state & STATE_NUMBER) === STATE_NUMBER) this._endNumber();
294
+ if ((this._state & STATE_LITERAL) === STATE_LITERAL) this._endLiteral();
295
+ if (this._state !== STATE_DONE) throw new SyntaxError(`${this._name}: Unexpected end of JSON input`);
296
+ }
297
+ };
298
+ export { JsonTokenizer as t };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * A `ReadableStream` that only calls `getStream` to create its underlying
3
+ * stream when it is first read. `getStream` can return a `ReadableStream`, or
4
+ * a promise for one.
5
+ *
6
+ * - If `getStream` throws, or its promise rejects (or does not resolve to an
7
+ * unlocked `ReadableStream`), the stream errors with that error.
8
+ * - Errors from the underlying stream are forwarded.
9
+ * - Cancelling this stream before it is read does not call `getStream`.
10
+ * Cancelling it later cancels the underlying stream, waiting for the promise
11
+ * to resolve first if necessary.
12
+ *
13
+ * Nothing is read from the underlying stream until this stream is read, so
14
+ * backpressure is preserved.
15
+ */
16
+ export default class LazyStream<T> extends ReadableStream<T> {
17
+ constructor(getStream: () => ReadableStream<T> | PromiseLike<ReadableStream<T>>);
18
+ }
@@ -0,0 +1,53 @@
1
+ // src/LazyStream.ts
2
+ /**
3
+ * A `ReadableStream` that only calls `getStream` to create its underlying
4
+ * stream when it is first read. `getStream` can return a `ReadableStream`, or
5
+ * a promise for one.
6
+ *
7
+ * - If `getStream` throws, or its promise rejects (or does not resolve to an
8
+ * unlocked `ReadableStream`), the stream errors with that error.
9
+ * - Errors from the underlying stream are forwarded.
10
+ * - Cancelling this stream before it is read does not call `getStream`.
11
+ * Cancelling it later cancels the underlying stream, waiting for the promise
12
+ * to resolve first if necessary.
13
+ *
14
+ * Nothing is read from the underlying stream until this stream is read, so
15
+ * backpressure is preserved.
16
+ */
17
+ var LazyStream = class extends ReadableStream {
18
+ constructor(getStream) {
19
+ let isCancelled = false;
20
+ let controller;
21
+ let readerPromise;
22
+ let reader;
23
+ const onResult = (result) => {
24
+ if (isCancelled) return;
25
+ if (result.done) controller.close();
26
+ else controller.enqueue(result.value);
27
+ };
28
+ super({
29
+ start(c) {
30
+ controller = c;
31
+ },
32
+ pull() {
33
+ if (reader) return reader.read().then(onResult);
34
+ readerPromise ??= Promise.resolve(getStream()).then((stream) => reader = stream.getReader());
35
+ return readerPromise.then((reader) => {
36
+ if (isCancelled) return;
37
+ return reader.read().then(onResult);
38
+ });
39
+ },
40
+ async cancel(reason) {
41
+ isCancelled = true;
42
+ let reader;
43
+ try {
44
+ reader = await readerPromise;
45
+ } catch {
46
+ return;
47
+ }
48
+ await reader?.cancel(reason);
49
+ }
50
+ }, { highWaterMark: 0 });
51
+ }
52
+ };
53
+ export { LazyStream as default };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The line endings supported by our encoders
3
+ */
4
+ type LineEnding = "\n" | "\r\n" | "\r";
5
+ export { LineEnding as t };
@@ -0,0 +1,64 @@
1
+ // src/internal/LineSplitter.ts
2
+ const LINE_BREAK = /\r\n|\r|\n/g;
3
+ const LINE_FEED = 10;
4
+ const CARRIAGE_RETURN = 13;
5
+ /**
6
+ * Split text, which can be split into chunks at any point, into lines. Lines
7
+ * may be terminated by `\n`, `\r\n` or `\r`. The line terminators are not
8
+ * included in the output.
9
+ */
10
+ var LineSplitter = class {
11
+ _partialLine = "";
12
+ _skipLeadingLineFeed = false;
13
+ _onLine;
14
+ constructor(onLine) {
15
+ this._onLine = onLine;
16
+ }
17
+ /**
18
+ * Emit a line that ends in this chunk, including the part of it from
19
+ * previous chunks
20
+ */
21
+ _emitLine(chunk, start, end) {
22
+ if (this._partialLine) {
23
+ const line = this._partialLine + chunk.slice(start, end);
24
+ this._partialLine = "";
25
+ this._onLine(line, 0, line.length);
26
+ } else this._onLine(chunk, start, end);
27
+ }
28
+ /**
29
+ * Process the next chunk of text, calling `onLine` for each complete line
30
+ */
31
+ write(chunk) {
32
+ let lineStart = 0;
33
+ if (this._skipLeadingLineFeed && chunk.charCodeAt(0) === LINE_FEED) lineStart = 1;
34
+ if (chunk.length > 0) this._skipLeadingLineFeed = false;
35
+ if (!chunk.includes("\r")) {
36
+ let lineEnd;
37
+ while ((lineEnd = chunk.indexOf("\n", lineStart)) !== -1) {
38
+ this._emitLine(chunk, lineStart, lineEnd);
39
+ lineStart = lineEnd + 1;
40
+ }
41
+ } else {
42
+ LINE_BREAK.lastIndex = lineStart;
43
+ let match;
44
+ while ((match = LINE_BREAK.exec(chunk)) !== null) {
45
+ this._emitLine(chunk, lineStart, match.index);
46
+ lineStart = LINE_BREAK.lastIndex;
47
+ }
48
+ this._skipLeadingLineFeed = chunk.charCodeAt(chunk.length - 1) === CARRIAGE_RETURN;
49
+ }
50
+ this._partialLine += chunk.slice(lineStart);
51
+ }
52
+ /**
53
+ * Call once there is no more text, to emit the final line (if it wasn't
54
+ * terminated by a line break)
55
+ */
56
+ end() {
57
+ if (this._partialLine.length) {
58
+ const line = this._partialLine;
59
+ this._partialLine = "";
60
+ this._onLine(line, 0, line.length);
61
+ }
62
+ }
63
+ };
64
+ export { LineSplitter as t };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Transform each chunk using a (sync or async) function. Chunks are processed
3
+ * one at a time, in order. If `fn` throws, the stream is errored.
4
+ */
5
+ export default class MapStream<TInput, TOutput> extends TransformStream<TInput, TOutput> {
6
+ constructor(fn: (data: TInput) => TOutput | PromiseLike<TOutput>);
7
+ }
@@ -0,0 +1,18 @@
1
+ import { t as isPromiseLike } from "./isPromiseLike-SjGgF7zP.mjs";
2
+ // src/MapStream.ts
3
+ /**
4
+ * Transform each chunk using a (sync or async) function. Chunks are processed
5
+ * one at a time, in order. If `fn` throws, the stream is errored.
6
+ */
7
+ var MapStream = class extends TransformStream {
8
+ constructor(fn) {
9
+ super({ transform(chunk, controller) {
10
+ const result = fn(chunk);
11
+ if (isPromiseLike(result)) return Promise.resolve(result).then((value) => {
12
+ controller.enqueue(value);
13
+ });
14
+ controller.enqueue(result);
15
+ } });
16
+ }
17
+ };
18
+ export { MapStream as default };
@@ -0,0 +1,18 @@
1
+ export interface NewlineDelimitedJsonDecoderStreamOptions {
2
+ /**
3
+ * Called for each line that is not valid JSON. You can skip the line (by
4
+ * doing nothing), enqueue a replacement value, or error the stream. If
5
+ * `onError` throws, the stream is errored.
6
+ *
7
+ * Defaults to erroring the stream with the JSON parse error.
8
+ */
9
+ onError?: (invalidLine: string, error: Error, controller: TransformStreamDefaultController<unknown>) => void;
10
+ }
11
+ /**
12
+ * Decode a stream of text in the newline delimited JSON format. The text can
13
+ * be split into chunks at any point, any line ending is supported, and blank
14
+ * lines are ignored.
15
+ */
16
+ export default class NewlineDelimitedJsonDecoderStream extends TransformStream<string, unknown> {
17
+ constructor({ onError }?: NewlineDelimitedJsonDecoderStreamOptions);
18
+ }
@@ -0,0 +1,48 @@
1
+ import { t as LineSplitter } from "./LineSplitter-CPGPZH7w.mjs";
2
+ import "./SplitLinesStream.mjs";
3
+ import "./TransformPipelineStream.mjs";
4
+ // src/NewlineDelimitedJsonDecoderStream.ts
5
+ let lastError;
6
+ function tryParse(chunk) {
7
+ try {
8
+ return JSON.parse(chunk);
9
+ } catch (ex) {
10
+ lastError = ex;
11
+ return;
12
+ }
13
+ }
14
+ function handleError(onError, line, controller) {
15
+ const err = lastError;
16
+ lastError = void 0;
17
+ if (line.trim()) {
18
+ if (onError) onError(line, err, controller);
19
+ else controller.error(err);
20
+ }
21
+ }
22
+ /**
23
+ * Decode a stream of text in the newline delimited JSON format. The text can
24
+ * be split into chunks at any point, any line ending is supported, and blank
25
+ * lines are ignored.
26
+ */
27
+ var NewlineDelimitedJsonDecoderStream = class extends TransformStream {
28
+ constructor({ onError } = {}) {
29
+ let splitter;
30
+ super({
31
+ start(controller) {
32
+ splitter = new LineSplitter((text, start, end) => {
33
+ const line = text.slice(start, end);
34
+ const value = tryParse(line);
35
+ if (lastError) handleError(onError, line, controller);
36
+ else controller.enqueue(value);
37
+ });
38
+ },
39
+ transform(chunk) {
40
+ splitter.write(chunk);
41
+ },
42
+ flush() {
43
+ splitter.end();
44
+ }
45
+ });
46
+ }
47
+ };
48
+ export { NewlineDelimitedJsonDecoderStream as default };
@@ -0,0 +1,15 @@
1
+ import { t as LineEnding } from "./LineEndings-CET4b2lJ.mjs";
2
+ export interface NewlineDelimitedJsonEncoderStreamOptions {
3
+ /**
4
+ * The line ending written after each JSON value. Defaults to `"\n"`.
5
+ */
6
+ lineEnding?: LineEnding;
7
+ }
8
+ /**
9
+ * Encode each chunk as JSON, followed by a line ending. Chunks that cannot be
10
+ * represented as JSON (e.g. `undefined`, functions, symbols, `BigInt` values or
11
+ * circular structures) will error the stream.
12
+ */
13
+ export default class NewlineDelimitedJsonEncoderStream extends TransformStream<unknown, string> {
14
+ constructor({ lineEnding }?: NewlineDelimitedJsonEncoderStreamOptions);
15
+ }
@@ -0,0 +1,16 @@
1
+ // src/NewlineDelimitedJsonEncoderStream.ts
2
+ /**
3
+ * Encode each chunk as JSON, followed by a line ending. Chunks that cannot be
4
+ * represented as JSON (e.g. `undefined`, functions, symbols, `BigInt` values or
5
+ * circular structures) will error the stream.
6
+ */
7
+ var NewlineDelimitedJsonEncoderStream = class extends TransformStream {
8
+ constructor({ lineEnding = "\n" } = {}) {
9
+ super({ transform(chunk, controller) {
10
+ const json = JSON.stringify(chunk);
11
+ if (json === void 0) throw new TypeError(`Cannot encode a value of type ${typeof chunk} as newline delimited JSON`);
12
+ controller.enqueue(json + lineEnding);
13
+ } });
14
+ }
15
+ };
16
+ export { NewlineDelimitedJsonEncoderStream as default };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Split a stream of text into lines. Lines may be terminated by `\n`, `\r\n`
3
+ * or `\r`. The line terminators are not included in the output. A final line
4
+ * without a trailing line terminator is emitted when the input ends.
5
+ */
6
+ export default class SplitLinesStream extends TransformStream<string, string> {
7
+ constructor();
8
+ }
@@ -0,0 +1,24 @@
1
+ import { t as LineSplitter } from "./LineSplitter-CPGPZH7w.mjs";
2
+ // src/SplitLinesStream.ts
3
+ /**
4
+ * Split a stream of text into lines. Lines may be terminated by `\n`, `\r\n`
5
+ * or `\r`. The line terminators are not included in the output. A final line
6
+ * without a trailing line terminator is emitted when the input ends.
7
+ */
8
+ var SplitLinesStream = class extends TransformStream {
9
+ constructor() {
10
+ let splitter;
11
+ super({
12
+ start(controller) {
13
+ splitter = new LineSplitter((text, start, end) => controller.enqueue(text.slice(start, end)));
14
+ },
15
+ transform(chunk, controller) {
16
+ splitter.write(chunk);
17
+ },
18
+ flush(controller) {
19
+ splitter.end();
20
+ }
21
+ });
22
+ }
23
+ };
24
+ export { SplitLinesStream as default };
@@ -0,0 +1,7 @@
1
+ export default class TransformPipelineStream<In, Out> implements TransformStream<In, Out> {
2
+ readonly writable: WritableStream<In>;
3
+ readonly readable: ReadableStream<Out>;
4
+ constructor(buildPipeline: (input: {
5
+ pipeThrough: <T>(transform: ReadableWritablePair<T, In>) => ReadableStream<T>;
6
+ }) => ReadableStream<Out>);
7
+ }