flecks/packages/core/build/stream.js

71 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-03-01 01:52:56 -06:00
// eslint-disable-next-line max-classes-per-file
2024-02-09 01:11:27 -06:00
const {dump: dumpYml, load: loadYml} = require('js-yaml');
2024-01-16 00:28:20 -06:00
const JsonParse = require('jsonparse');
const {Transform} = require('stream');
2022-03-01 01:52:56 -06:00
2024-01-16 00:28:20 -06:00
exports.JsonStream = class JsonStream extends Transform {
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
constructor(decorator) {
2022-03-01 01:52:56 -06:00
super();
this.parser = new JsonParse();
2024-02-09 01:11:27 -06:00
const self = this;
2022-03-01 01:52:56 -06:00
this.parser.onValue = function onValue(O) {
if (0 === this.stack.length) {
2024-02-09 01:11:27 -06:00
self.transformed = JSON.stringify(decorator(O));
2022-03-01 01:52:56 -06:00
}
};
2024-02-09 01:11:27 -06:00
this.transformed = undefined;
}
// eslint-disable-next-line no-underscore-dangle
_flush(done) {
this.push(this.transformed);
done();
2022-03-01 01:52:56 -06:00
}
// eslint-disable-next-line no-underscore-dangle
_transform(chunk, encoding, done) {
this.parser.write(chunk);
2024-02-09 01:11:27 -06:00
done();
2022-03-01 01:52:56 -06:00
}
2024-01-16 00:28:20 -06:00
};
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
exports.JsonStream.PrettyPrint = class extends exports.JsonStream {
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
constructor(decorator, indent = 2) {
super(decorator);
const self = this;
this.parser.onValue = function onValue(O) {
if (0 === this.stack.length) {
self.transformed = JSON.stringify(O, null, indent);
}
};
2022-03-01 01:52:56 -06:00
}
};
2024-02-09 01:11:27 -06:00
exports.YamlStream = class YamlStream extends Transform {
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
constructor(decorator, options = {dump: {}, load: {}}) {
super();
this.buffers = [];
this.decorator = decorator;
this.options = options;
}
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
// eslint-disable-next-line no-underscore-dangle
_flush(done) {
const yml = loadYml(Buffer.concat(this.buffers).toString(), this.options.load);
this.push(dumpYml(this.decorator(yml), this.options.dump));
done();
}
2022-03-01 01:52:56 -06:00
2024-02-09 01:11:27 -06:00
// eslint-disable-next-line no-underscore-dangle
_transform(chunk, encoding, done) {
this.buffers.push(chunk);
done();
2022-03-01 01:52:56 -06:00
}
2024-02-09 01:11:27 -06:00
2022-03-01 01:52:56 -06:00
};