@devgrid/netron
Version:
Event bus, streams and remote object invocation.
52 lines • 1.55 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WritableStream = void 0;
const uid_1 = require("./uid");
const uid = new uid_1.Uid();
class WritableStream {
constructor(peer, source, isLive = false) {
this.peer = peer;
this.isLive = isLive;
this.closed = false;
this.index = 0;
this.expectedIndex = 0;
this.id = uid.next();
if (source) {
this.pipeFrom(source);
}
}
async pipeFrom(source) {
for await (const chunk of source) {
if (this.closed)
break;
await this.write(chunk);
}
if (!this.isLive) {
this.end();
}
}
async write(data) {
if (this.closed)
throw new Error('Stream is closed');
return this.peer.sendStreamChunk(this.id, data, this.index++, false, this.isLive);
}
async end(force = false) {
if (this.closed)
return;
if (!this.isLive || force) {
await this.peer.sendStreamChunk(this.id, null, this.index, true, this.isLive);
this.close();
}
}
close() {
this.closed = true;
this.peer.writableStreams.delete(this.id);
}
static create(peer, source, isLive = false) {
const stream = new WritableStream(peer, source, isLive);
peer.writableStreams.set(stream.id, stream);
return stream;
}
}
exports.WritableStream = WritableStream;
//# sourceMappingURL=writable-stream.js.map