source: imaps-frontend/node_modules/@discoveryjs/json-ext/src/web-streams.js@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 4 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 1.6 KB
Line 
1/* eslint-env browser */
2import { parseChunked } from './parse-chunked.js';
3import { stringifyChunked } from './stringify-chunked.js';
4import { isIterable } from './utils.js';
5
6export 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
29export 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};
Note: See TracBrowser for help on using the repository browser.