From 5ee147588c37db7df9feb2f7ef7ca6e7b393c9a0 Mon Sep 17 00:00:00 2001 From: cm-ayf Date: Mon, 27 May 2024 13:36:50 +0900 Subject: [PATCH] implement Readable by passing option --- lib/index.js | 85 +++++++++++++++++++--------------------------------- 1 file changed, 31 insertions(+), 54 deletions(-) diff --git a/lib/index.js b/lib/index.js index 3797245..fdefaae 100644 --- a/lib/index.js +++ b/lib/index.js @@ -21,59 +21,6 @@ exports.OM_SYRINX_VERSION = OM_SYRINX_VERSION; const { setTimeout } = require("node:timers/promises"); -class SyrinxStream extends Readable { - /** - * @param {import("./native").Syrinx} syrinx - * @param {boolean} objectMode - * @param {string} inputText - * @param {import("./native").SynthesisOption} option - */ - constructor(syrinx, objectMode, inputText, option) { - super({ objectMode }); - /** - * @type {import("./native").Syrinx} - * @private - */ - this._syrinx = syrinx; - /** - * @type {string} - * @private - */ - this._inputText = inputText; - /** - * @type {import("./native").SynthesisOption} - * @private - */ - this._option = option; - } - - /** - * @param {(error?: Error | null) => void} callback - */ - async _construct(callback) { - /** @type {[import("./native").PreparedSynthesizer, null] | [null, Error]} */ - const [synthesizer, error] = await this._syrinx - .prepare(this._inputText, this._option) - .then( - (s) => [s, null], - (e) => [null, e], - ); - callback(error); - - await synthesizer?.synthesize((err, result) => { - if (err) this.emit("error", err); - else this.push(result); - }); - - // The last push sometimes occurs after the Promise resolution, - // so we need to make sure that the last push occurs before the stream ends. - await setTimeout(); - this.push(null); - } - - _read() {} -} - class Syrinx { /** * @param {import("./native").SyrinxConfig} config @@ -117,7 +64,37 @@ class Syrinx { * @returns {Readable} */ synthesize(inputText, option) { - return new SyrinxStream(this._inner, this._objectMode, inputText, option); + const { _inner } = this; + + return new Readable({ + objectMode: this._objectMode, + + /** + * @param {(error?: Error | null) => void} callback + */ + async construct(callback) { + /** @type {[import("./native").PreparedSynthesizer, null] | [null, Error]} */ + const [synthesizer, error] = await _inner + .prepare(inputText, option) + .then( + (s) => [s, null], + (e) => [null, e], + ); + callback(error); + + await synthesizer?.synthesize((err, result) => { + if (err) this.emit("error", err); + else this.push(result); + }); + + // The last push sometimes occurs after the Promise resolution, + // so we need to make sure that the last push occurs before the stream ends. + await setTimeout(); + this.push(null); + }, + + read() {}, + }); } }