@loaders.gl/core
Version:
The core API for working with loaders.gl loaders and writers
51 lines (50 loc) • 1.73 kB
JavaScript
// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
/**
* Builds a DOM stream from an iterator
* This stream is currently used in browsers only,
* but note that Web stream support is present in Node from Node 16
* https://nodejs.org/api/webstreams.html#webstreams_web_streams_api
*/
export function makeStream(source, options) {
if (globalThis.loaders.makeNodeStream) {
return globalThis.loaders.makeNodeStream(source, options);
}
// TODO - add AsyncGenerator to parameter types?
const iterator = source[Symbol.asyncIterator]
? source[Symbol.asyncIterator]()
: source[Symbol.iterator]();
return new ReadableStream({
// Create a byte stream (enables `Response(stream).arrayBuffer()`)
// Only supported on Chrome
// See: https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController
// @ts-ignore
type: 'bytes',
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
controller.close();
}
else {
// TODO - ignores controller.desiredSize
// @ts-expect-error Unclear why value is not correctly typed
controller.enqueue(new Uint8Array(value));
}
}
catch (error) {
controller.error(error);
}
},
async cancel() {
await iterator?.return?.();
}
},
// options: QueingStrategy<Uint8Array>
{
// This is bytes, not chunks
highWaterMark: 2 ** 24,
...options
});
}