UNPKG

@audc/salute-tts

Version:
471 lines (444 loc) 24.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SmartSpeechClient = void 0; var _googleGax = _interopRequireWildcard(require("google-gax")); var gax = _googleGax; var _stream = require("stream"); var _path = _interopRequireDefault(require("path")); var _url = require("url"); var _jsonHelper = require("../json-helper.cjs"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } // Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** /* global window */ // @ts-ignore // @ts-ignore var dirname = __dirname; /** * Client JSON configuration object, loaded from * `src/v1/smart_speech_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ var gapicConfig = (0, _jsonHelper.getJSON)(_path["default"].join(dirname, 'smart_speech_client_config.json')); var jsonProtos = (0, _jsonHelper.getJSON)(_path["default"].join(dirname, '..', '..', '..', 'protos/protos.json')); var version = (0, _jsonHelper.getJSON)(_path["default"].join(dirname, '..', '..', '..', '..', 'package.json')).version; /** * @class * @memberof v1 */ var SmartSpeechClient = exports.SmartSpeechClient = /*#__PURE__*/function () { /** * Construct an instance of SmartSpeechClient. * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] * @param {string} [options.credentials.private_key] * @param {string} [options.email] - Account email address. Required when * using a .pem or .p12 keyFilename. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or * .p12 key downloaded from the Google Developers Console. If you provide * a path to a JSON file, the projectId option below is not necessary. * NOTE: .pem and .p12 require you to specify options.email as well. * @param {number} [options.port] - The port on which to connect to * the remote host. * @param {string} [options.projectId] - The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. * @param {boolean | "rest"} [options.fallback] - Use HTTP fallback mode. * Pass "rest" to use HTTP/1.1 REST API instead of gRPC. * For more information, please check the * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you * need to avoid loading the default gRPC version and want to use the fallback * HTTP implementation. Load only fallback version and pass it to the constructor: * ``` * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC * const client = new SmartSpeechClient({fallback: 'rest'}, gax); * ``` */ function SmartSpeechClient(opts, gaxInstance) { var _opts, _opts2, _opts3, _opts4, _ref, _ref2, _opts$universeDomain, _opts5, _opts6, _opts7, _opts8, _opts9, _opts10, _opts11, _opts$clientConfig, _opts12, _opts$fallback, _opts13, _window; _classCallCheck(this, SmartSpeechClient); _defineProperty(this, "_terminated", false); _defineProperty(this, "_opts", void 0); _defineProperty(this, "_providedCustomServicePath", void 0); _defineProperty(this, "_gaxModule", void 0); _defineProperty(this, "_gaxGrpc", void 0); _defineProperty(this, "_protos", void 0); _defineProperty(this, "_defaults", void 0); _defineProperty(this, "_universeDomain", void 0); _defineProperty(this, "_servicePath", void 0); _defineProperty(this, "_log", _googleGax.loggingUtils.log('synthesis')); _defineProperty(this, "auth", void 0); _defineProperty(this, "descriptors", { page: {}, stream: {}, longrunning: {}, batching: {} }); _defineProperty(this, "warn", void 0); _defineProperty(this, "innerApiCalls", void 0); _defineProperty(this, "smartSpeechStub", void 0); // Ensure that options include all the required fields. var staticMembers = this.constructor; if ((_opts = opts) !== null && _opts !== void 0 && _opts.universe_domain && (_opts2 = opts) !== null && _opts2 !== void 0 && _opts2.universeDomain && ((_opts3 = opts) === null || _opts3 === void 0 ? void 0 : _opts3.universe_domain) !== ((_opts4 = opts) === null || _opts4 === void 0 ? void 0 : _opts4.universeDomain)) { throw new Error('Please set either universe_domain or universeDomain, but not both.'); } var universeDomainEnvVar = (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && _typeof(process.env) === 'object' ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; this._universeDomain = (_ref = (_ref2 = (_opts$universeDomain = (_opts5 = opts) === null || _opts5 === void 0 ? void 0 : _opts5.universeDomain) !== null && _opts$universeDomain !== void 0 ? _opts$universeDomain : (_opts6 = opts) === null || _opts6 === void 0 ? void 0 : _opts6.universe_domain) !== null && _ref2 !== void 0 ? _ref2 : universeDomainEnvVar) !== null && _ref !== void 0 ? _ref : 'googleapis.com'; this._servicePath = 'sber.ru'; var servicePath = ((_opts7 = opts) === null || _opts7 === void 0 ? void 0 : _opts7.servicePath) || ((_opts8 = opts) === null || _opts8 === void 0 ? void 0 : _opts8.apiEndpoint) || this._servicePath; this._providedCustomServicePath = !!((_opts9 = opts) !== null && _opts9 !== void 0 && _opts9.servicePath || (_opts10 = opts) !== null && _opts10 !== void 0 && _opts10.apiEndpoint); var port = ((_opts11 = opts) === null || _opts11 === void 0 ? void 0 : _opts11.port) || staticMembers.port; var clientConfig = (_opts$clientConfig = (_opts12 = opts) === null || _opts12 === void 0 ? void 0 : _opts12.clientConfig) !== null && _opts$clientConfig !== void 0 ? _opts$clientConfig : {}; var fallback = (_opts$fallback = (_opts13 = opts) === null || _opts13 === void 0 ? void 0 : _opts13.fallback) !== null && _opts$fallback !== void 0 ? _opts$fallback : typeof window !== 'undefined' && typeof ((_window = window) === null || _window === void 0 ? void 0 : _window.fetch) === 'function'; opts = Object.assign({ servicePath: servicePath, port: port, clientConfig: clientConfig, fallback: fallback }, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; } // Load google-gax module synchronously if needed if (!gaxInstance) { gaxInstance = gax; } // Choose either gRPC or proto-over-HTTP implementation of google-gax. this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. this._gaxGrpc = new this._gaxModule.GrpcClient(opts); // Save options to use in initialize() method. this._opts = opts; // Save the auth object to the client, for use by other methods. this.auth = this._gaxGrpc.auth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = this._servicePath; // Set the default scopes in auth client if needed. if (servicePath === this._servicePath) { this.auth.defaultScopes = staticMembers.scopes; } // Add ESM headers var isEsm = false; var isEsmString = isEsm ? '-esm' : '-cjs'; // Determine the client header string. var clientHeader = ["gax/".concat(this._gaxModule.version), "gapic/".concat(version)]; if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && 'versions' in process) { clientHeader.push("gl-node/{process.versions.node}".concat(isEsmString)); } else { clientHeader.push("gl-web/".concat(this._gaxModule.version)); } if (!opts.fallback) { clientHeader.push("grpc/".concat(this._gaxGrpc.grpcVersion)); } else if (opts.fallback === 'rest') { clientHeader.push("rest/".concat(this._gaxGrpc.grpcVersion)); } if (opts.libName && opts.libVersion) { clientHeader.push("".concat(opts.libName, "/").concat(opts.libVersion)); } // Load the applicable protos. this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { synthesize: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings('smartspeech.synthesis.v1.SmartSpeech', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') }); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this.innerApiCalls = {}; // Add a warn function to the client constructor so it can be easily tested. this.warn = this._gaxModule.warn; } /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. * This function will be called automatically when any class method is called for the * first time, but if you need to initialize it before calling an actual method, * feel free to call initialize() directly. * * You can await on this method if you want to make sure the client is initialized. * * @returns {Promise} A promise that resolves to an authenticated service stub. */ return _createClass(SmartSpeechClient, [{ key: "initialize", value: function initialize() { var _this = this; // If the client stub promise is already initialized, return immediately. if (this.smartSpeechStub) { return this.smartSpeechStub; } // Put together the "service stub" for // smartspeech.synthesis.v1.SmartSpeech. this.smartSpeechStub = this._gaxGrpc.createStub(this._opts.fallback ? this._protos.lookupService('smartspeech.synthesis.v1.SmartSpeech') : // eslint-disable-next-line @typescript-eslint/no-explicit-any this._protos.smartspeech.synthesis.v1.SmartSpeech, this._opts, this._providedCustomServicePath); // Iterate over each of the methods that the service provides // and create an API call method for each. var smartSpeechStubMethods = ['synthesize', 'asyncSynthesize']; var _loop = function _loop() { var methodName = _smartSpeechStubMetho[_i]; var callPromise = _this.smartSpeechStub.then(function (stub) { return function () { if (_this._terminated) { if (methodName in _this.descriptors.stream) { var stream = new _stream.PassThrough({ objectMode: true }); setImmediate(function () { stream.emit('error', new _this._gaxModule.GoogleError('The client has already been closed.')); }); return stream; } return Promise.reject('The client has already been closed.'); } var func = stub[methodName]; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return func.apply(stub, args); }; }, function (err) { return function () { throw err; }; }); var descriptor = _this.descriptors.stream[methodName] || undefined; var apiCall = _this._gaxModule.createApiCall(callPromise, _this._defaults[methodName], descriptor, _this._opts.fallback); _this.innerApiCalls[methodName] = apiCall; }; for (var _i = 0, _smartSpeechStubMetho = smartSpeechStubMethods; _i < _smartSpeechStubMetho.length; _i++) { _loop(); } return this.smartSpeechStub; } /** * The DNS address for this API service. * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ }, { key: "apiEndpoint", get: /** * The DNS address for this API service. * @returns {string} The DNS address for this service. */ function get() { return this._servicePath; } }, { key: "universeDomain", get: function get() { return this._universeDomain; } /** * The port for this API service. * @returns {number} The default port for this service. */ }, { key: "getProjectId", value: /** * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ function getProjectId(callback) { if (callback) { this.auth.getProjectId(callback); return; } return this.auth.getProjectId(); } // ------------------- // -- Service calls -- // ------------------- /** * * @param {Object} request * The request object that will be sent. * @param {string} request.requestFileId * @param {smartspeech.synthesis.v1.SynthesisRequest.AudioEncoding} request.audioEncoding * @param {string} request.voice * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing {@link protos.smartspeech.task.v1.Task|Task}. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example <caption>include:samples/generated/v1/smart_speech.async_synthesize.js</caption> * region_tag:sber_v1_generated_SmartSpeech_AsyncSynthesize_async */ }, { key: "asyncSynthesize", value: function asyncSynthesize(request, optionsOrCallback, callback) { var _this2 = this, _this$innerApiCalls$a; request = request || {}; var options; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize()["catch"](function (err) { throw err; }); this._log.info('asyncSynthesize request %j', request); var wrappedCallback = callback ? function (error, response, options, rawResponse) { _this2._log.info('asyncSynthesize response %j', response); callback(error, response, options, rawResponse); } : undefined; return (_this$innerApiCalls$a = this.innerApiCalls.asyncSynthesize(request, options, wrappedCallback)) === null || _this$innerApiCalls$a === void 0 ? void 0 : _this$innerApiCalls$a.then(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 3), response = _ref4[0], options = _ref4[1], rawResponse = _ref4[2]; _this2._log.info('asyncSynthesize response %j', response); return [response, options, rawResponse]; }); } /** * * @param {Object} request * The request object that will be sent. * @param {string} request.text * @param {smartspeech.synthesis.v1.SynthesisRequest.AudioEncoding} request.audioEncoding * @param {string} request.language * @param {smartspeech.synthesis.v1.SynthesisRequest.ContentType} request.contentType * @param {string} request.voice * @param {boolean} request.rebuildCache * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits {@link protos.smartspeech.synthesis.v1.SynthesisResponse|SynthesisResponse} on 'data' event. * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } * for more details and examples. * @example <caption>include:samples/generated/v1/smart_speech.synthesize.js</caption> * region_tag:sber_v1_generated_SmartSpeech_Synthesize_async */ }, { key: "synthesize", value: function synthesize(request, options) { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; this.initialize()["catch"](function (err) { throw err; }); this._log.info('synthesize stream %j', options); return this.innerApiCalls.synthesize(request, options); } /** * Terminate the gRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. * @returns {Promise} A promise that resolves when the client is closed. */ }, { key: "close", value: function close() { var _this3 = this; if (this.smartSpeechStub && !this._terminated) { return this.smartSpeechStub.then(function (stub) { _this3._log.info('ending gRPC channel'); _this3._terminated = true; stub.close(); }); } return Promise.resolve(); } }], [{ key: "servicePath", get: function get() { if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && typeof process.emitWarning === 'function') { process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'sber.ru'; } /** * The DNS address for this API service - same as servicePath, * exists for compatibility reasons. * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ }, { key: "apiEndpoint", get: function get() { if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && typeof process.emitWarning === 'function') { process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'sber.ru'; } }, { key: "port", get: function get() { return 443; } /** * The scopes needed to make gRPC calls for every method defined * in this service. * @returns {string[]} List of default scopes. */ }, { key: "scopes", get: function get() { return []; } }]); }();