[79a0317] | 1 | /* eslint-env browser */
|
---|
| 2 | import { parseChunked } from './parse-chunked.js';
|
---|
| 3 | import { stringifyChunked } from './stringify-chunked.js';
|
---|
| 4 | import { isIterable } from './utils.js';
|
---|
| 5 |
|
---|
| 6 | export function parseFromWebStream(stream) {
|
---|
| 7 | // 2024/6/17: currently, an @@asyncIterator on a ReadableStream is not widely supported,
|
---|
| 8 | // therefore use a fallback using a reader
|
---|
| 9 | // https://caniuse.com/mdn-api_readablestream_--asynciterator
|
---|
| 10 | return parseChunked(isIterable(stream) ? stream : async function*() {
|
---|
| 11 | const reader = stream.getReader();
|
---|
| 12 |
|
---|
| 13 | try {
|
---|
| 14 | while (true) {
|
---|
| 15 | const { value, done } = await reader.read();
|
---|
| 16 |
|
---|
| 17 | if (done) {
|
---|
| 18 | break;
|
---|
| 19 | }
|
---|
| 20 |
|
---|
| 21 | yield value;
|
---|
| 22 | }
|
---|
| 23 | } finally {
|
---|
| 24 | reader.releaseLock();
|
---|
| 25 | }
|
---|
| 26 | });
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | export function createStringifyWebStream(value, replacer, space) {
|
---|
| 30 | // 2024/6/17: the ReadableStream.from() static method is supported
|
---|
| 31 | // in Node.js 20.6+ and Firefox only
|
---|
| 32 | if (typeof ReadableStream.from === 'function') {
|
---|
| 33 | return ReadableStream.from(stringifyChunked(value, replacer, space));
|
---|
| 34 | }
|
---|
| 35 |
|
---|
| 36 | // emulate ReadableStream.from()
|
---|
| 37 | return new ReadableStream({
|
---|
| 38 | start() {
|
---|
| 39 | this.generator = stringifyChunked(value, replacer, space);
|
---|
| 40 | },
|
---|
| 41 | pull(controller) {
|
---|
| 42 | const { value, done } = this.generator.next();
|
---|
| 43 |
|
---|
| 44 | if (done) {
|
---|
| 45 | controller.close();
|
---|
| 46 | } else {
|
---|
| 47 | controller.enqueue(value);
|
---|
| 48 | }
|
---|
| 49 | },
|
---|
| 50 | cancel() {
|
---|
| 51 | this.generator = null;
|
---|
| 52 | }
|
---|
| 53 | });
|
---|
| 54 | };
|
---|