web-utility-streams 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +470 -2
- package/lib/ConcatStream.d.mts +22 -0
- package/lib/ConcatStream.mjs +67 -0
- package/lib/DebugStream.d.mts +3 -0
- package/lib/DebugStream.mjs +12 -0
- package/lib/DeferredStream.d.mts +16 -0
- package/lib/DeferredStream.mjs +51 -0
- package/lib/EmptyStream.d.mts +3 -0
- package/lib/EmptyStream.mjs +9 -0
- package/lib/EventSourceDecoderStream.d.mts +39 -0
- package/lib/EventSourceDecoderStream.mjs +106 -0
- package/lib/EventSourceEncoderStream.d.mts +34 -0
- package/lib/EventSourceEncoderStream.mjs +57 -0
- package/lib/FilterMapStream.d.mts +8 -0
- package/lib/FilterMapStream.mjs +19 -0
- package/lib/FilterStream.d.mts +4 -0
- package/lib/FilterStream.mjs +9 -0
- package/lib/JsonDecoderStream.d.mts +63 -0
- package/lib/JsonDecoderStream.mjs +121 -0
- package/lib/JsonEncoderStream.d.mts +51 -0
- package/lib/JsonEncoderStream.mjs +96 -0
- package/lib/JsonTokenDecoderStream.d.mts +49 -0
- package/lib/JsonTokenDecoderStream.mjs +62 -0
- package/lib/JsonTokenizer-BtRpnxKn.mjs +299 -0
- package/lib/LazyStream.d.mts +18 -0
- package/lib/LazyStream.mjs +53 -0
- package/lib/LineEndings-CET4b2lJ.d.mts +5 -0
- package/lib/LineSplitter-CPGPZH7w.mjs +64 -0
- package/lib/MapStream.d.mts +7 -0
- package/lib/MapStream.mjs +18 -0
- package/lib/NewlineDelimitedJsonDecoderStream.d.mts +18 -0
- package/lib/NewlineDelimitedJsonDecoderStream.mjs +48 -0
- package/lib/NewlineDelimitedJsonEncoderStream.d.mts +15 -0
- package/lib/NewlineDelimitedJsonEncoderStream.mjs +16 -0
- package/lib/SplitLinesStream.d.mts +8 -0
- package/lib/SplitLinesStream.mjs +24 -0
- package/lib/TransformPipelineStream.d.mts +7 -0
- package/lib/TransformPipelineStream.mjs +17 -0
- package/lib/UnionStream.d.mts +21 -0
- package/lib/UnionStream.mjs +79 -0
- package/lib/consumers.d.mts +26 -0
- package/lib/consumers.mjs +92 -0
- package/lib/isPromiseLike-SjGgF7zP.mjs +9 -0
- package/lib/readableStreamToGenerator.d.mts +8 -0
- package/lib/readableStreamToGenerator.mjs +64 -0
- package/package.json +127 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export interface EventSourceEvent {
|
|
2
|
+
type: string;
|
|
3
|
+
data: string;
|
|
4
|
+
id: string | null;
|
|
5
|
+
/**
|
|
6
|
+
* The reconnection time in milliseconds
|
|
7
|
+
*/
|
|
8
|
+
retryMilliseconds: number | null;
|
|
9
|
+
}
|
|
10
|
+
export interface EventSourceDecoderStreamOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Called whenever a valid `id` field is received, even if no event is
|
|
13
|
+
* dispatched afterwards (e.g. the stream ends or the event has no data).
|
|
14
|
+
*/
|
|
15
|
+
onId?: (id: string) => void;
|
|
16
|
+
/**
|
|
17
|
+
* Called whenever a valid `retry` field is received, even if no event is
|
|
18
|
+
* dispatched afterwards (e.g. the stream ends or the event has no data).
|
|
19
|
+
*/
|
|
20
|
+
onRetry?: (retryMilliseconds: number) => void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Decode a stream of text in the `text/event-stream` format into
|
|
24
|
+
* `EventSourceEvent` objects. The text can be split into chunks at any point.
|
|
25
|
+
*
|
|
26
|
+
* The `id` and `retryMilliseconds` properties of each event reflect any `id`
|
|
27
|
+
* and `retry` fields received since the previous event was emitted, or `null`
|
|
28
|
+
* if there were none. To be notified of every `id` and `retry` field as soon
|
|
29
|
+
* as it is received, use the `onId` and `onRetry` options.
|
|
30
|
+
*
|
|
31
|
+
* If `onId` or `onRetry` throws, the stream is errored.
|
|
32
|
+
*/
|
|
33
|
+
export default class EventSourceDecoderStream extends TransformStream<string, EventSourceEvent> {
|
|
34
|
+
private _latestId;
|
|
35
|
+
private _retryMilliseconds;
|
|
36
|
+
get latestId(): string | null;
|
|
37
|
+
get retryMilliseconds(): number | null;
|
|
38
|
+
constructor({ onId, onRetry }?: EventSourceDecoderStreamOptions);
|
|
39
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { t as LineSplitter } from "./LineSplitter-CPGPZH7w.mjs";
|
|
2
|
+
// src/EventSourceDecoderStream.ts
|
|
3
|
+
const DEFAULT_EVENT_TYPE = "message";
|
|
4
|
+
const SPACE = 32;
|
|
5
|
+
const COLON = 58;
|
|
6
|
+
/**
|
|
7
|
+
* Decode a stream of text in the `text/event-stream` format into
|
|
8
|
+
* `EventSourceEvent` objects. The text can be split into chunks at any point.
|
|
9
|
+
*
|
|
10
|
+
* The `id` and `retryMilliseconds` properties of each event reflect any `id`
|
|
11
|
+
* and `retry` fields received since the previous event was emitted, or `null`
|
|
12
|
+
* if there were none. To be notified of every `id` and `retry` field as soon
|
|
13
|
+
* as it is received, use the `onId` and `onRetry` options.
|
|
14
|
+
*
|
|
15
|
+
* If `onId` or `onRetry` throws, the stream is errored.
|
|
16
|
+
*/
|
|
17
|
+
var EventSourceDecoderStream = class extends TransformStream {
|
|
18
|
+
_latestId = null;
|
|
19
|
+
_retryMilliseconds = null;
|
|
20
|
+
get latestId() {
|
|
21
|
+
return this._latestId;
|
|
22
|
+
}
|
|
23
|
+
get retryMilliseconds() {
|
|
24
|
+
return this._retryMilliseconds;
|
|
25
|
+
}
|
|
26
|
+
constructor({ onId, onRetry } = {}) {
|
|
27
|
+
let id = null;
|
|
28
|
+
let retryMilliseconds = null;
|
|
29
|
+
let eventType = null;
|
|
30
|
+
let eventData = null;
|
|
31
|
+
let splitter;
|
|
32
|
+
super({
|
|
33
|
+
start: (controller) => {
|
|
34
|
+
splitter = new LineSplitter((text, start, end) => {
|
|
35
|
+
if (start === end) {
|
|
36
|
+
if (eventData !== null) {
|
|
37
|
+
controller.enqueue({
|
|
38
|
+
type: eventType || DEFAULT_EVENT_TYPE,
|
|
39
|
+
data: eventData,
|
|
40
|
+
id,
|
|
41
|
+
retryMilliseconds
|
|
42
|
+
});
|
|
43
|
+
id = null;
|
|
44
|
+
retryMilliseconds = null;
|
|
45
|
+
}
|
|
46
|
+
eventType = null;
|
|
47
|
+
eventData = null;
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (text.charCodeAt(start + 4) === COLON && text.startsWith("data", start) && start + 4 < end) {
|
|
51
|
+
const valueStart = text.charCodeAt(start + 5) === SPACE && start + 5 < end ? start + 6 : start + 5;
|
|
52
|
+
const value = text.slice(valueStart, end);
|
|
53
|
+
eventData = eventData === null ? value : `${eventData}\n${value}`;
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let nameEnd = text.indexOf(":", start);
|
|
57
|
+
if (nameEnd === -1 || nameEnd > end) nameEnd = end;
|
|
58
|
+
const field = fieldName(text, start, nameEnd);
|
|
59
|
+
if (field === null) return;
|
|
60
|
+
let valueStart = nameEnd + 1;
|
|
61
|
+
if (valueStart < end && text.charCodeAt(valueStart) === SPACE) valueStart++;
|
|
62
|
+
const value = valueStart < end ? text.slice(valueStart, end) : "";
|
|
63
|
+
switch (field) {
|
|
64
|
+
case "data":
|
|
65
|
+
eventData = eventData === null ? value : `${eventData}\n${value}`;
|
|
66
|
+
break;
|
|
67
|
+
case "event":
|
|
68
|
+
eventType = value;
|
|
69
|
+
break;
|
|
70
|
+
case "id":
|
|
71
|
+
if (!value.includes("\0")) {
|
|
72
|
+
id = value;
|
|
73
|
+
this._latestId = value;
|
|
74
|
+
onId?.(value);
|
|
75
|
+
}
|
|
76
|
+
break;
|
|
77
|
+
case "retry": if (/^\d+$/.test(value)) {
|
|
78
|
+
retryMilliseconds = parseInt(value, 10);
|
|
79
|
+
this._retryMilliseconds = retryMilliseconds;
|
|
80
|
+
onRetry?.(retryMilliseconds);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
},
|
|
85
|
+
transform: (chunk) => {
|
|
86
|
+
splitter.write(chunk);
|
|
87
|
+
},
|
|
88
|
+
flush: () => {
|
|
89
|
+
splitter.end();
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Get the name of the field in `text.slice(start, end)`, if it's one we
|
|
96
|
+
* handle. Other field names (and comments) are ignored.
|
|
97
|
+
*/
|
|
98
|
+
function fieldName(text, start, end) {
|
|
99
|
+
switch (end - start) {
|
|
100
|
+
case 4: return text.startsWith("data", start) ? "data" : null;
|
|
101
|
+
case 5: return text.startsWith("event", start) ? "event" : text.startsWith("retry", start) ? "retry" : null;
|
|
102
|
+
case 2: return text.startsWith("id", start) ? "id" : null;
|
|
103
|
+
default: return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export { EventSourceDecoderStream as default };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { EventSourceEvent } from "./EventSourceDecoderStream.mjs";
|
|
2
|
+
import { t as LineEnding } from "./LineEndings-CET4b2lJ.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* The input to `EventSourceEncoderStream`. Only `data` is required. `type`
|
|
5
|
+
* defaults to `"message"`. Other fields are not sent if not provided.
|
|
6
|
+
*/
|
|
7
|
+
export interface EventSourceEncoderInput {
|
|
8
|
+
type?: EventSourceEvent["type"] | null;
|
|
9
|
+
data: EventSourceEvent["data"];
|
|
10
|
+
id?: EventSourceEvent["id"];
|
|
11
|
+
retryMilliseconds?: EventSourceEvent["retryMilliseconds"];
|
|
12
|
+
}
|
|
13
|
+
export interface EventSourceEncoderStreamOptions {
|
|
14
|
+
/**
|
|
15
|
+
* The line ending used to terminate each line of the output. Defaults to
|
|
16
|
+
* `"\n"`. Line breaks within `data` are also converted to this line ending.
|
|
17
|
+
*/
|
|
18
|
+
lineEnding?: LineEnding;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Encode events in the `text/event-stream` format. Each event is output as
|
|
22
|
+
* a single string chunk, including the trailing blank line that marks the end
|
|
23
|
+
* of the event.
|
|
24
|
+
*
|
|
25
|
+
* The output is suitable for piping through a `TextEncoderStream` and sending
|
|
26
|
+
* as the body of an HTTP response with `Content-Type: text/event-stream`. It
|
|
27
|
+
* can be decoded using `EventSourceDecoderStream`.
|
|
28
|
+
*
|
|
29
|
+
* Events that cannot be represented in the `text/event-stream` format (e.g. an
|
|
30
|
+
* `id` or `type` containing a line break) will error the stream.
|
|
31
|
+
*/
|
|
32
|
+
export default class EventSourceEncoderStream extends TransformStream<EventSourceEncoderInput, string> {
|
|
33
|
+
constructor({ lineEnding }?: EventSourceEncoderStreamOptions);
|
|
34
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// src/EventSourceEncoderStream.ts
|
|
2
|
+
const DEFAULT_EVENT_TYPE = "message";
|
|
3
|
+
const LINE_BREAK = /\r\n|\r|\n/;
|
|
4
|
+
/**
|
|
5
|
+
* Encode events in the `text/event-stream` format. Each event is output as
|
|
6
|
+
* a single string chunk, including the trailing blank line that marks the end
|
|
7
|
+
* of the event.
|
|
8
|
+
*
|
|
9
|
+
* The output is suitable for piping through a `TextEncoderStream` and sending
|
|
10
|
+
* as the body of an HTTP response with `Content-Type: text/event-stream`. It
|
|
11
|
+
* can be decoded using `EventSourceDecoderStream`.
|
|
12
|
+
*
|
|
13
|
+
* Events that cannot be represented in the `text/event-stream` format (e.g. an
|
|
14
|
+
* `id` or `type` containing a line break) will error the stream.
|
|
15
|
+
*/
|
|
16
|
+
var EventSourceEncoderStream = class extends TransformStream {
|
|
17
|
+
constructor({ lineEnding = "\n" } = {}) {
|
|
18
|
+
super({ transform(event, controller) {
|
|
19
|
+
controller.enqueue(encodeEvent(event, lineEnding));
|
|
20
|
+
} });
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function encodeEvent({ type, data, id, retryMilliseconds }, lineEnding) {
|
|
24
|
+
let result = "";
|
|
25
|
+
if (type != null && type !== "" && type !== DEFAULT_EVENT_TYPE) {
|
|
26
|
+
assertSingleLine("type", type);
|
|
27
|
+
result += `event: ${type}${lineEnding}`;
|
|
28
|
+
}
|
|
29
|
+
if (id != null) {
|
|
30
|
+
assertSingleLine("id", id);
|
|
31
|
+
if (id.includes("\0")) throw new TypeError(`EventSourceEncoderStream: "id" cannot contain a null character`);
|
|
32
|
+
result += `id: ${id}${lineEnding}`;
|
|
33
|
+
}
|
|
34
|
+
if (retryMilliseconds != null) {
|
|
35
|
+
if (!Number.isSafeInteger(retryMilliseconds) || retryMilliseconds < 0) throw new TypeError(`EventSourceEncoderStream: "retryMilliseconds" must be a non-negative integer, got ${retryMilliseconds}`);
|
|
36
|
+
result += `retry: ${retryMilliseconds}${lineEnding}`;
|
|
37
|
+
}
|
|
38
|
+
assertString("data", data);
|
|
39
|
+
if (!hasLineBreak(data)) return `${result}data: ${data}${lineEnding}${lineEnding}`;
|
|
40
|
+
for (const line of data.split(LINE_BREAK)) result += `data: ${line}${lineEnding}`;
|
|
41
|
+
return result + lineEnding;
|
|
42
|
+
}
|
|
43
|
+
function assertString(name, value) {
|
|
44
|
+
if (typeof value !== "string") throw new TypeError(`EventSourceEncoderStream: Expected "${name}" to be a string but got ${typeof value}`);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Quicker than testing `LINE_BREAK`, as `includes` doesn't use the regex
|
|
48
|
+
* engine
|
|
49
|
+
*/
|
|
50
|
+
function hasLineBreak(value) {
|
|
51
|
+
return value.includes("\n") || value.includes("\r");
|
|
52
|
+
}
|
|
53
|
+
function assertSingleLine(name, value) {
|
|
54
|
+
assertString(name, value);
|
|
55
|
+
if (hasLineBreak(value)) throw new TypeError(`EventSourceEncoderStream: "${name}" cannot contain line breaks`);
|
|
56
|
+
}
|
|
57
|
+
export { EventSourceEncoderStream as default };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transform each chunk using a (sync or async) function, dropping any chunks
|
|
3
|
+
* for which the function returns `undefined`. Chunks are processed one at a
|
|
4
|
+
* time, in order. If `fn` throws, the stream is errored.
|
|
5
|
+
*/
|
|
6
|
+
export default class FilterMapStream<TInput, TOutput> extends TransformStream<TInput, TOutput> {
|
|
7
|
+
constructor(fn: (data: TInput) => TOutput | undefined | PromiseLike<TOutput | undefined>);
|
|
8
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { t as isPromiseLike } from "./isPromiseLike-SjGgF7zP.mjs";
|
|
2
|
+
// src/FilterMapStream.ts
|
|
3
|
+
/**
|
|
4
|
+
* Transform each chunk using a (sync or async) function, dropping any chunks
|
|
5
|
+
* for which the function returns `undefined`. Chunks are processed one at a
|
|
6
|
+
* time, in order. If `fn` throws, the stream is errored.
|
|
7
|
+
*/
|
|
8
|
+
var FilterMapStream = class extends TransformStream {
|
|
9
|
+
constructor(fn) {
|
|
10
|
+
super({ transform(chunk, controller) {
|
|
11
|
+
const result = fn(chunk);
|
|
12
|
+
if (isPromiseLike(result)) return Promise.resolve(result).then((value) => {
|
|
13
|
+
if (value !== void 0) controller.enqueue(value);
|
|
14
|
+
});
|
|
15
|
+
if (result !== void 0) controller.enqueue(result);
|
|
16
|
+
} });
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
export { FilterMapStream as default };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export interface JsonDecoderStreamOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The keys to get from the root object to the array or object to stream.
|
|
4
|
+
* Defaults to streaming the root of the document.
|
|
5
|
+
*/
|
|
6
|
+
readonly path?: readonly string[];
|
|
7
|
+
/**
|
|
8
|
+
* If supplied, this callback is called with all the data that's not at
|
|
9
|
+
* the supplied `path`, once the whole document has been parsed. This is the
|
|
10
|
+
* document with the value at `path` replaced by `undefined` (the key is
|
|
11
|
+
* still present), so it can be passed back to `JsonEncoderStream` as
|
|
12
|
+
* `extraData`. If `path` is empty, it is called with `undefined`.
|
|
13
|
+
*
|
|
14
|
+
* It is called as soon as the end of the document is reached, which may be
|
|
15
|
+
* before all the emitted elements have been read from the stream. If the
|
|
16
|
+
* document is invalid before then, it is not called. If it throws, the
|
|
17
|
+
* stream is errored.
|
|
18
|
+
*
|
|
19
|
+
* Note that when this is supplied, all the data outside of `path` is kept
|
|
20
|
+
* in memory until the end of the document, rather than being discarded.
|
|
21
|
+
*/
|
|
22
|
+
readonly onExtraData?: (extraData: unknown) => void;
|
|
23
|
+
/**
|
|
24
|
+
* The maximum length, in characters, of any single value in the document
|
|
25
|
+
* (each emitted element, each discarded object/array, and each string or
|
|
26
|
+
* number). If a value is longer than this, the stream is errored, so that
|
|
27
|
+
* an unexpectedly large (or never-ending) value can't use unlimited memory.
|
|
28
|
+
* Defaults to 100 MiB (`100 * 2 ** 20` characters).
|
|
29
|
+
*/
|
|
30
|
+
readonly maxValueLength?: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Decode a JSON array or object from a stream of text, emitting each element
|
|
34
|
+
* as soon as it has been parsed, without waiting for the rest of the document.
|
|
35
|
+
* For an array, each element is emitted. For an object, each property is
|
|
36
|
+
* emitted as a `[key, value]` tuple. The text can be split into chunks at any
|
|
37
|
+
* point.
|
|
38
|
+
*
|
|
39
|
+
* By default, the root of the document is streamed. If the array/object is
|
|
40
|
+
* nested inside other objects, pass the keys to get from the root to it as
|
|
41
|
+
* `path`.
|
|
42
|
+
*
|
|
43
|
+
* The entire document is validated, but only the elements being emitted are
|
|
44
|
+
* kept in memory, so other (potentially large) properties are discarded as
|
|
45
|
+
* they are parsed. To receive those other properties instead, pass an
|
|
46
|
+
* `onExtraData` callback. If the document is not valid JSON, the stream is
|
|
47
|
+
* errored when the problem is found. For speed, each element (and each
|
|
48
|
+
* object/array that is being discarded) is parsed in one go when its end is
|
|
49
|
+
* reached, so a problem inside one is found when its end is reached. A value
|
|
50
|
+
* longer than `maxValueLength` errors the stream as soon as that length is
|
|
51
|
+
* exceeded. If there is no array/object at `path`, the
|
|
52
|
+
* stream is errored once the whole document has been parsed. Because elements
|
|
53
|
+
* are emitted as soon as they are parsed, some elements may be emitted before
|
|
54
|
+
* an error is found later in the document.
|
|
55
|
+
*
|
|
56
|
+
* If the key at any point in `path` appears more than once in an object, the
|
|
57
|
+
* elements from every match are emitted. Similarly, if a streamed object has
|
|
58
|
+
* the same key more than once, a tuple is emitted for each of them (unlike
|
|
59
|
+
* `JSON.parse`, which keeps only the last value).
|
|
60
|
+
*/
|
|
61
|
+
export default class JsonDecoderStream extends TransformStream<string, unknown> {
|
|
62
|
+
constructor({ path, maxValueLength, onExtraData }?: JsonDecoderStreamOptions);
|
|
63
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { t as JsonTokenizer } from "./JsonTokenizer-BtRpnxKn.mjs";
|
|
2
|
+
// src/JsonDecoderStream.ts
|
|
3
|
+
/**
|
|
4
|
+
* Decode a JSON array or object from a stream of text, emitting each element
|
|
5
|
+
* as soon as it has been parsed, without waiting for the rest of the document.
|
|
6
|
+
* For an array, each element is emitted. For an object, each property is
|
|
7
|
+
* emitted as a `[key, value]` tuple. The text can be split into chunks at any
|
|
8
|
+
* point.
|
|
9
|
+
*
|
|
10
|
+
* By default, the root of the document is streamed. If the array/object is
|
|
11
|
+
* nested inside other objects, pass the keys to get from the root to it as
|
|
12
|
+
* `path`.
|
|
13
|
+
*
|
|
14
|
+
* The entire document is validated, but only the elements being emitted are
|
|
15
|
+
* kept in memory, so other (potentially large) properties are discarded as
|
|
16
|
+
* they are parsed. To receive those other properties instead, pass an
|
|
17
|
+
* `onExtraData` callback. If the document is not valid JSON, the stream is
|
|
18
|
+
* errored when the problem is found. For speed, each element (and each
|
|
19
|
+
* object/array that is being discarded) is parsed in one go when its end is
|
|
20
|
+
* reached, so a problem inside one is found when its end is reached. A value
|
|
21
|
+
* longer than `maxValueLength` errors the stream as soon as that length is
|
|
22
|
+
* exceeded. If there is no array/object at `path`, the
|
|
23
|
+
* stream is errored once the whole document has been parsed. Because elements
|
|
24
|
+
* are emitted as soon as they are parsed, some elements may be emitted before
|
|
25
|
+
* an error is found later in the document.
|
|
26
|
+
*
|
|
27
|
+
* If the key at any point in `path` appears more than once in an object, the
|
|
28
|
+
* elements from every match are emitted. Similarly, if a streamed object has
|
|
29
|
+
* the same key more than once, a tuple is emitted for each of them (unlike
|
|
30
|
+
* `JSON.parse`, which keeps only the last value).
|
|
31
|
+
*/
|
|
32
|
+
var JsonDecoderStream = class extends TransformStream {
|
|
33
|
+
constructor({ path = [], maxValueLength = 100 * 2 ** 20, onExtraData } = {}) {
|
|
34
|
+
const stack = [];
|
|
35
|
+
let foundTarget = false;
|
|
36
|
+
let extraData;
|
|
37
|
+
let controller;
|
|
38
|
+
/**
|
|
39
|
+
* Decide how to handle an object/array that is starting
|
|
40
|
+
*/
|
|
41
|
+
const childMode = () => {
|
|
42
|
+
const parent = stack.at(-1);
|
|
43
|
+
if (!parent) {
|
|
44
|
+
if (!path.length) {
|
|
45
|
+
foundTarget = true;
|
|
46
|
+
return "target";
|
|
47
|
+
}
|
|
48
|
+
return "path";
|
|
49
|
+
}
|
|
50
|
+
switch (parent.mode) {
|
|
51
|
+
case "path":
|
|
52
|
+
if (parent.key !== path[stack.length - 1]) return "skip";
|
|
53
|
+
if (stack.length === path.length) {
|
|
54
|
+
foundTarget = true;
|
|
55
|
+
return "target";
|
|
56
|
+
}
|
|
57
|
+
return "path";
|
|
58
|
+
case "target":
|
|
59
|
+
case "build": return "build";
|
|
60
|
+
case "skip": return "skip";
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* A value (scalar, object or array) has been completely parsed.
|
|
65
|
+
* `value` is only meaningful if the parent is being built or emitted.
|
|
66
|
+
*/
|
|
67
|
+
const endValue = (value) => {
|
|
68
|
+
const parent = stack.at(-1);
|
|
69
|
+
if (!parent) {
|
|
70
|
+
extraData = value;
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (parent.mode === "target") controller.enqueue(parent.kind === 123 ? [parent.key, value] : value);
|
|
74
|
+
else if (parent.mode === "build" || onExtraData) {
|
|
75
|
+
if (parent.kind === 91) parent.value.push(value);
|
|
76
|
+
else if (parent.key === "__proto__") Object.defineProperty(parent.value, parent.key, {
|
|
77
|
+
value,
|
|
78
|
+
writable: true,
|
|
79
|
+
enumerable: true,
|
|
80
|
+
configurable: true
|
|
81
|
+
});
|
|
82
|
+
else parent.value[parent.key] = value;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const tokenizer = new JsonTokenizer("JsonDecoderStream", maxValueLength, {
|
|
86
|
+
onKey: (key) => {
|
|
87
|
+
stack[stack.length - 1].key = key;
|
|
88
|
+
},
|
|
89
|
+
onLiteral: endValue,
|
|
90
|
+
onOpen: (kind) => {
|
|
91
|
+
const mode = childMode();
|
|
92
|
+
if (mode === "build" || mode === "skip") return true;
|
|
93
|
+
stack.push({
|
|
94
|
+
kind,
|
|
95
|
+
mode,
|
|
96
|
+
key: void 0,
|
|
97
|
+
value: onExtraData && mode !== "target" ? kind === 123 ? {} : [] : void 0
|
|
98
|
+
});
|
|
99
|
+
return false;
|
|
100
|
+
},
|
|
101
|
+
onClose: () => {
|
|
102
|
+
endValue(stack.pop().value);
|
|
103
|
+
},
|
|
104
|
+
onPunctuation: () => {}
|
|
105
|
+
});
|
|
106
|
+
super({
|
|
107
|
+
start(c) {
|
|
108
|
+
controller = c;
|
|
109
|
+
},
|
|
110
|
+
transform(chunk) {
|
|
111
|
+
tokenizer.write(chunk);
|
|
112
|
+
},
|
|
113
|
+
flush() {
|
|
114
|
+
tokenizer.end();
|
|
115
|
+
if (!foundTarget) throw new TypeError(`JsonDecoderStream: Expected an array or object at ${path.length === 0 ? "the root" : `path ${JSON.stringify(path)}`}`);
|
|
116
|
+
if (onExtraData) onExtraData(extraData);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
export { JsonDecoderStream as default };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export interface JsonEncoderStreamOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The path to the location in the output where the streaming data should appear
|
|
4
|
+
*/
|
|
5
|
+
readonly path?: readonly string[];
|
|
6
|
+
/**
|
|
7
|
+
* Defaults to "array". To stream an object, set this to `"object"` and
|
|
8
|
+
* ensure the input to the stream is tuples of `[string, value]`
|
|
9
|
+
*/
|
|
10
|
+
readonly mode?: "array" | "object";
|
|
11
|
+
/**
|
|
12
|
+
* Other properties to include with the output - must not have any value
|
|
13
|
+
* at the `path`.
|
|
14
|
+
*/
|
|
15
|
+
readonly extraData?: unknown;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Encode a stream of values as a single JSON document, where the values are
|
|
19
|
+
* the elements of an array (or, with `mode: "object"`, the properties of an
|
|
20
|
+
* object). This is the opposite of `JsonDecoderStream`.
|
|
21
|
+
*
|
|
22
|
+
* Values are encoded the same way `JSON.stringify` encodes them inside an
|
|
23
|
+
* array or object: in "array" mode, values that can't be represented in JSON
|
|
24
|
+
* (`undefined`, functions and symbols) are encoded as `null`, and in "object"
|
|
25
|
+
* mode, properties with those values are left out. Values that `JSON.stringify`
|
|
26
|
+
* throws for (e.g. `BigInt` values or circular structures) error the stream.
|
|
27
|
+
*
|
|
28
|
+
* By default, the array/object is the root of the document. To nest it inside
|
|
29
|
+
* other objects, pass the keys that lead to it as `path`, and any other
|
|
30
|
+
* properties to include as `extraData`. The other properties are output
|
|
31
|
+
* before the streamed array/object, so they are available to the reader
|
|
32
|
+
* straight away.
|
|
33
|
+
*
|
|
34
|
+
* The start of the document is output immediately, each value is output as a
|
|
35
|
+
* separate chunk as soon as it is written, and the end of the document is
|
|
36
|
+
* output when the input closes.
|
|
37
|
+
*
|
|
38
|
+
* Example:
|
|
39
|
+
*
|
|
40
|
+
* ReadableStream.from(["a", "b"]).pipeThrough(new JsonEncoderStream())
|
|
41
|
+
* // => `[`, `"a"`, `,"b"`, `]`
|
|
42
|
+
*
|
|
43
|
+
* ReadableStream.from([["a", 1], ["b", 2]]).pipeThrough(new JsonEncoderStream({ mode: "object" }))
|
|
44
|
+
* // => `{`, `"a":1`, `,"b":2`, `}`
|
|
45
|
+
*
|
|
46
|
+
* ReadableStream.from(["a", "b"]).pipeThrough(new JsonEncoderStream({ path: ["results"], extraData: { total: 2 } }))
|
|
47
|
+
* // => `{"total":2,"results":[`, `"a"`, `,"b"`, `]}`
|
|
48
|
+
*/
|
|
49
|
+
export default class JsonEncoderStream extends TransformStream<unknown, string> {
|
|
50
|
+
constructor({ path, mode, extraData }?: JsonEncoderStreamOptions);
|
|
51
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// src/JsonEncoderStream.ts
|
|
2
|
+
/**
|
|
3
|
+
* Encode a stream of values as a single JSON document, where the values are
|
|
4
|
+
* the elements of an array (or, with `mode: "object"`, the properties of an
|
|
5
|
+
* object). This is the opposite of `JsonDecoderStream`.
|
|
6
|
+
*
|
|
7
|
+
* Values are encoded the same way `JSON.stringify` encodes them inside an
|
|
8
|
+
* array or object: in "array" mode, values that can't be represented in JSON
|
|
9
|
+
* (`undefined`, functions and symbols) are encoded as `null`, and in "object"
|
|
10
|
+
* mode, properties with those values are left out. Values that `JSON.stringify`
|
|
11
|
+
* throws for (e.g. `BigInt` values or circular structures) error the stream.
|
|
12
|
+
*
|
|
13
|
+
* By default, the array/object is the root of the document. To nest it inside
|
|
14
|
+
* other objects, pass the keys that lead to it as `path`, and any other
|
|
15
|
+
* properties to include as `extraData`. The other properties are output
|
|
16
|
+
* before the streamed array/object, so they are available to the reader
|
|
17
|
+
* straight away.
|
|
18
|
+
*
|
|
19
|
+
* The start of the document is output immediately, each value is output as a
|
|
20
|
+
* separate chunk as soon as it is written, and the end of the document is
|
|
21
|
+
* output when the input closes.
|
|
22
|
+
*
|
|
23
|
+
* Example:
|
|
24
|
+
*
|
|
25
|
+
* ReadableStream.from(["a", "b"]).pipeThrough(new JsonEncoderStream())
|
|
26
|
+
* // => `[`, `"a"`, `,"b"`, `]`
|
|
27
|
+
*
|
|
28
|
+
* ReadableStream.from([["a", 1], ["b", 2]]).pipeThrough(new JsonEncoderStream({ mode: "object" }))
|
|
29
|
+
* // => `{`, `"a":1`, `,"b":2`, `}`
|
|
30
|
+
*
|
|
31
|
+
* ReadableStream.from(["a", "b"]).pipeThrough(new JsonEncoderStream({ path: ["results"], extraData: { total: 2 } }))
|
|
32
|
+
* // => `{"total":2,"results":[`, `"a"`, `,"b"`, `]}`
|
|
33
|
+
*/
|
|
34
|
+
var JsonEncoderStream = class extends TransformStream {
|
|
35
|
+
constructor({ path = [], mode = "array", extraData = void 0 } = {}) {
|
|
36
|
+
const prefix = encodePath(path, extraData) + (mode === "array" ? "[" : "{");
|
|
37
|
+
const suffix = (mode === "array" ? "]" : "}") + "}".repeat(path.length);
|
|
38
|
+
let isFirst = true;
|
|
39
|
+
const stringifyElement = mode === "object" ? stringifyObjectKey : stringifyArrayElement;
|
|
40
|
+
super({
|
|
41
|
+
start(controller) {
|
|
42
|
+
controller.enqueue(prefix);
|
|
43
|
+
},
|
|
44
|
+
transform(chunk, controller) {
|
|
45
|
+
const json = stringifyElement(chunk);
|
|
46
|
+
if (json === void 0) return;
|
|
47
|
+
controller.enqueue(isFirst ? json : "," + json);
|
|
48
|
+
isFirst = false;
|
|
49
|
+
},
|
|
50
|
+
flush(controller) {
|
|
51
|
+
controller.enqueue(suffix);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
function stringifyArrayElement(chunk) {
|
|
57
|
+
return JSON.stringify(chunk) ?? "null";
|
|
58
|
+
}
|
|
59
|
+
function stringifyObjectKey(chunk) {
|
|
60
|
+
if (!Array.isArray(chunk) || chunk.length !== 2 || typeof chunk[0] !== "string") throw new TypeError(`JsonEncoderStream: In "object" mode, each chunk must be a [key, value] tuple`);
|
|
61
|
+
const value = JSON.stringify(chunk[1]);
|
|
62
|
+
if (value === void 0) return;
|
|
63
|
+
return `${JSON.stringify(chunk[0])}:${value}`;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Encode the start of the document, up to the point where the streamed
|
|
67
|
+
* array/object begins, including any `extraData`.
|
|
68
|
+
*/
|
|
69
|
+
function encodePath(path, extraData) {
|
|
70
|
+
let result = "";
|
|
71
|
+
let level = extraData;
|
|
72
|
+
for (let i = 0; i < path.length; i++) {
|
|
73
|
+
const key = path[i];
|
|
74
|
+
if (level !== void 0 && !isPlainObject(level)) throw new TypeError(`JsonEncoderStream: extraData at ${describePath(path.slice(0, i))} must be a plain object`);
|
|
75
|
+
result += "{";
|
|
76
|
+
for (const [k, v] of Object.entries(level ?? {})) {
|
|
77
|
+
if (k === key) continue;
|
|
78
|
+
const json = JSON.stringify(v);
|
|
79
|
+
if (json === void 0) continue;
|
|
80
|
+
result += `${JSON.stringify(k)}:${json},`;
|
|
81
|
+
}
|
|
82
|
+
result += `${JSON.stringify(key)}:`;
|
|
83
|
+
level = level !== void 0 && Object.hasOwn(level, key) ? level[key] : void 0;
|
|
84
|
+
}
|
|
85
|
+
if (level !== void 0) throw new TypeError(path.length ? `JsonEncoderStream: extraData must not have a value at ${describePath(path)}` : `JsonEncoderStream: extraData can only be used with a path`);
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
function isPlainObject(value) {
|
|
89
|
+
if (typeof value !== "object" || value === null) return false;
|
|
90
|
+
const prototype = Object.getPrototypeOf(value);
|
|
91
|
+
return prototype === Object.prototype || prototype === null;
|
|
92
|
+
}
|
|
93
|
+
function describePath(path) {
|
|
94
|
+
return path.length ? `path ${JSON.stringify(path)}` : "the root";
|
|
95
|
+
}
|
|
96
|
+
export { JsonEncoderStream as default };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface JsonTokenDecoderStreamOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The maximum length, in characters, of any single string, number or
|
|
4
|
+
* literal token. If a token is longer than this, the stream is errored, so
|
|
5
|
+
* that an unexpectedly large (or never-ending) token can't use unlimited
|
|
6
|
+
* memory. Defaults to 100 MiB (`100 * 2 ** 20` characters).
|
|
7
|
+
*/
|
|
8
|
+
readonly maxValueLength?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A token in a JSON document. `position` is the index of the token's first
|
|
12
|
+
* character in the input text.
|
|
13
|
+
*
|
|
14
|
+
* A string is a `KEY` token if it is directly inside an object, immediately
|
|
15
|
+
* after the `{` or a `,`. All other strings are `LITERAL` tokens.
|
|
16
|
+
*/
|
|
17
|
+
export type JsonToken = {
|
|
18
|
+
readonly type: "PUNCTUATION";
|
|
19
|
+
readonly value: "{" | "}" | "[" | "]" | ":" | ",";
|
|
20
|
+
readonly position: number;
|
|
21
|
+
} | {
|
|
22
|
+
readonly type: "KEY";
|
|
23
|
+
readonly value: string;
|
|
24
|
+
readonly position: number;
|
|
25
|
+
} | {
|
|
26
|
+
readonly type: "LITERAL";
|
|
27
|
+
readonly value: string | number | boolean | null;
|
|
28
|
+
readonly position: number;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Split a stream of JSON text into tokens. The text can be split into chunks
|
|
32
|
+
* at any point.
|
|
33
|
+
*
|
|
34
|
+
* The text must be a single JSON value, such as an object or array. Each
|
|
35
|
+
* token is checked to be valid (e.g. strings have valid escape sequences and
|
|
36
|
+
* numbers are correctly formatted), and to be in a valid place in the
|
|
37
|
+
* document (e.g. brackets match, and keys are followed by a `:`). Whitespace
|
|
38
|
+
* is skipped. If there is a problem, the stream is errored with a
|
|
39
|
+
* `SyntaxError` as soon as it is found, after emitting the tokens before it.
|
|
40
|
+
* If the input ends before the value is complete, the stream is errored with
|
|
41
|
+
* a `SyntaxError` when it closes.
|
|
42
|
+
*
|
|
43
|
+
* A number or `true`/`false`/`null` is only emitted once the character after
|
|
44
|
+
* it has been received (or the input ends), as it could continue in the next
|
|
45
|
+
* chunk.
|
|
46
|
+
*/
|
|
47
|
+
export default class JsonTokenDecoderStream extends TransformStream<string, JsonToken> {
|
|
48
|
+
constructor({ maxValueLength }?: JsonTokenDecoderStreamOptions);
|
|
49
|
+
}
|