@sefinek/google-tts-api 2.1.4 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +2 -2
  2. package/dist/assertInputTypes.js +1 -2
  3. package/dist/getAudioBase64.d.ts +0 -28
  4. package/dist/getAudioBase64.d.ts.map +1 -1
  5. package/dist/getAudioBase64.js +54 -150
  6. package/dist/getAudioUrl.d.ts +0 -28
  7. package/dist/getAudioUrl.d.ts.map +1 -1
  8. package/dist/getAudioUrl.js +10 -39
  9. package/dist/index.js +2 -3
  10. package/dist/splitLongText.d.ts +0 -10
  11. package/dist/splitLongText.d.ts.map +1 -1
  12. package/dist/splitLongText.js +15 -33
  13. package/eslint.config.mjs +56 -0
  14. package/example/british.js +3 -3
  15. package/example/chinese.js +3 -3
  16. package/example/download-by-audio-url.js +4 -4
  17. package/example/english.js +3 -3
  18. package/example/long-chinese-text.js +4 -5
  19. package/example/long-english-text.js +4 -4
  20. package/package.json +9 -6
  21. package/test/basic.test.js +2 -2
  22. package/test/param.test.js +2 -2
  23. package/test/split-long-text.test.js +2 -2
  24. package/coverage/assertInputTypes.ts.html +0 -142
  25. package/coverage/base.css +0 -224
  26. package/coverage/block-navigation.js +0 -87
  27. package/coverage/favicon.png +0 -0
  28. package/coverage/getAudioBase64.ts.html +0 -481
  29. package/coverage/getAudioUrl.ts.html +0 -361
  30. package/coverage/index.html +0 -176
  31. package/coverage/index.ts.html +0 -97
  32. package/coverage/lcov-report/assertInputTypes.ts.html +0 -142
  33. package/coverage/lcov-report/base.css +0 -224
  34. package/coverage/lcov-report/block-navigation.js +0 -87
  35. package/coverage/lcov-report/favicon.png +0 -0
  36. package/coverage/lcov-report/getAudioBase64.ts.html +0 -481
  37. package/coverage/lcov-report/getAudioUrl.ts.html +0 -361
  38. package/coverage/lcov-report/index.html +0 -176
  39. package/coverage/lcov-report/index.ts.html +0 -97
  40. package/coverage/lcov-report/prettify.css +0 -1
  41. package/coverage/lcov-report/prettify.js +0 -2
  42. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  43. package/coverage/lcov-report/sorter.js +0 -196
  44. package/coverage/lcov-report/splitLongText.ts.html +0 -319
  45. package/coverage/lcov.info +0 -257
  46. package/coverage/prettify.css +0 -1
  47. package/coverage/prettify.js +0 -2
  48. package/coverage/sort-arrow-sprite.png +0 -0
  49. package/coverage/sorter.js +0 -196
  50. package/coverage/splitLongText.ts.html +0 -319
  51. package/dist/assertInputTypes.js.map +0 -1
  52. package/dist/getAudioBase64.js.map +0 -1
  53. package/dist/getAudioUrl.js.map +0 -1
  54. package/dist/index.js.map +0 -1
  55. package/dist/splitLongText.js.map +0 -1
  56. package/tsconfig.json +0 -73
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
- # 📢 @sefinek/google-tts-api
2
- Google TTS (Text-To-Speech) for [Node.js](https://nodejs.org) without any vulnerabilities.
1
+ # 📢 Google TTS API
2
+ Google TTS (Text-To-Speech) for [Node.js](https://nodejs.org) without any vulnerabilities. For free without any API keys!
3
3
 
4
4
  ![@sefinek/google-tts-api.png](https://img.shields.io/npm/dt/@sefinek/google-tts-api?maxAge=3600)
5
5
  ![@sefinek/google-tts-api.png](https://img.shields.io/github/last-commit/sefinek24/google-tts-api)
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var assertInputTypes = function (text, lang, slow, host) {
3
+ const assertInputTypes = (text, lang, slow, host) => {
4
4
  if (typeof text !== 'string' || text.length === 0) {
5
5
  throw new TypeError('text should be a string');
6
6
  }
@@ -15,4 +15,3 @@ var assertInputTypes = function (text, lang, slow, host) {
15
15
  }
16
16
  };
17
17
  exports.default = assertInputTypes;
18
- //# sourceMappingURL=assertInputTypes.js.map
@@ -4,38 +4,10 @@ interface Option {
4
4
  host?: string;
5
5
  timeout?: number;
6
6
  }
7
- /**
8
- * Get "Google TTS" audio base64 text
9
- *
10
- * @param {string} text length should be less than 200 characters
11
- * @param {object?} option
12
- * @param {string?} option.lang default is "en"
13
- * @param {boolean?} option.slow default is false
14
- * @param {string?} option.host default is "https://translate.google.com"
15
- * @param {number?} option.timeout default is 10000 (ms)
16
- * @returns {Promise<string>} url
17
- */
18
7
  export declare const getAudioBase64: (text: string, { lang, slow, host, timeout }?: Option) => Promise<string>;
19
8
  interface LongTextOption extends Option {
20
9
  splitPunct?: string;
21
10
  }
22
- /**
23
- * @typedef {object} Result
24
- * @property {string} shortText
25
- * @property {string} base64
26
- */
27
- /**
28
- * Split the long text into multiple short text and generate audio base64 list
29
- *
30
- * @param {string} text
31
- * @param {object?} option
32
- * @param {string?} option.lang default is "en"
33
- * @param {boolean?} option.slow default is false
34
- * @param {string?} option.host default is "https://translate.google.com"
35
- * @param {string?} option.splitPunct split punctuation
36
- * @param {number?} option.timeout default is 10000 (ms)
37
- * @return {Result[]} the list with short text and audio base64
38
- */
39
11
  export declare const getAllAudioBase64: (text: string, { lang, slow, host, splitPunct, timeout, }?: LongTextOption) => Promise<{
40
12
  shortText: string;
41
13
  base64: string;
@@ -1 +1 @@
1
- {"version":3,"file":"getAudioBase64.d.ts","sourceRoot":"","sources":["../src/getAudioBase64.ts"],"names":[],"mappings":"AAIA,UAAU,MAAM;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,cAAc,SACjB,MAAM,kCAC2E,MAAM,KAC9F,QAAQ,MAAM,CAgDhB,CAAC;AAEF,UAAU,cAAe,SAAQ,MAAM;IACrC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,SACpB,MAAM,+CAOT,cAAc,KAClB,QAAQ;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,CAyBjD,CAAC"}
1
+ {"version":3,"file":"getAudioBase64.d.ts","sourceRoot":"","sources":["../src/getAudioBase64.ts"],"names":[],"mappings":"AAIA,UAAU,MAAM;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAaD,eAAO,MAAM,cAAc,SACjB,MAAM,kCAC2E,MAAM,KAC9F,OAAO,CAAC,MAAM,CAgDhB,CAAC;AAEF,UAAU,cAAe,SAAQ,MAAM;IACrC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAoBD,eAAO,MAAM,iBAAiB,SACpB,MAAM,+CAOT,cAAc,KAClB,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,CAyBjD,CAAC"}
@@ -8,163 +8,67 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
39
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
40
- if (ar || !(i in from)) {
41
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
42
- ar[i] = from[i];
43
- }
44
- }
45
- return to.concat(ar || Array.prototype.slice.call(from));
46
- };
47
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
48
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
49
13
  };
50
14
  Object.defineProperty(exports, "__esModule", { value: true });
51
15
  exports.getAllAudioBase64 = exports.getAudioBase64 = void 0;
52
- var assertInputTypes_1 = __importDefault(require("./assertInputTypes"));
53
- var axios_1 = __importDefault(require("axios"));
54
- var splitLongText_1 = __importDefault(require("./splitLongText"));
55
- /**
56
- * Get "Google TTS" audio base64 text
57
- *
58
- * @param {string} text length should be less than 200 characters
59
- * @param {object?} option
60
- * @param {string?} option.lang default is "en"
61
- * @param {boolean?} option.slow default is false
62
- * @param {string?} option.host default is "https://translate.google.com"
63
- * @param {number?} option.timeout default is 10000 (ms)
64
- * @returns {Promise<string>} url
65
- */
66
- var getAudioBase64 = function (text_1) {
67
- var args_1 = [];
68
- for (var _i = 1; _i < arguments.length; _i++) {
69
- args_1[_i - 1] = arguments[_i];
16
+ const assertInputTypes_1 = __importDefault(require("./assertInputTypes"));
17
+ const axios_1 = __importDefault(require("axios"));
18
+ const splitLongText_1 = __importDefault(require("./splitLongText"));
19
+ const getAudioBase64 = (text_1, ...args_1) => __awaiter(void 0, [text_1, ...args_1], void 0, function* (text, { lang = 'en', slow = false, host = 'https://translate.google.com', timeout = 10000 } = {}) {
20
+ (0, assertInputTypes_1.default)(text, lang, slow, host);
21
+ if (typeof timeout !== 'number' || timeout <= 0) {
22
+ throw new TypeError('timeout should be a positive number');
70
23
  }
71
- return __awaiter(void 0, __spreadArray([text_1], args_1, true), void 0, function (text, _a) {
72
- var res, result;
73
- var _b = _a === void 0 ? {} : _a, _c = _b.lang, lang = _c === void 0 ? 'en' : _c, _d = _b.slow, slow = _d === void 0 ? false : _d, _e = _b.host, host = _e === void 0 ? 'https://translate.google.com' : _e, _f = _b.timeout, timeout = _f === void 0 ? 10000 : _f;
74
- return __generator(this, function (_g) {
75
- switch (_g.label) {
76
- case 0:
77
- (0, assertInputTypes_1.default)(text, lang, slow, host);
78
- if (typeof timeout !== 'number' || timeout <= 0) {
79
- throw new TypeError('timeout should be a positive number');
80
- }
81
- if (text.length > 200) {
82
- throw new RangeError("text length (".concat(text.length, ") should be less than 200 characters. Try \"getAllAudioBase64(text, [option])\" for long text."));
83
- }
84
- return [4 /*yield*/, (0, axios_1.default)({
85
- method: 'post',
86
- baseURL: host,
87
- url: '/_/TranslateWebserverUi/data/batchexecute',
88
- timeout: timeout,
89
- data: 'f.req=' +
90
- encodeURIComponent(JSON.stringify([
91
- [['jQ1olc', JSON.stringify([text, lang, slow ? true : null, 'null']), null, 'generic']],
92
- ])),
93
- })];
94
- case 1:
95
- res = _g.sent();
96
- try {
97
- result = eval(res.data.slice(5))[0][2];
98
- }
99
- catch (e) {
100
- throw new Error("parse response failed:\n".concat(res.data));
101
- }
102
- // Check the result. The result will be null if given the lang doesn't exist
103
- if (!result) {
104
- throw new Error("lang \"".concat(lang, "\" might not exist"));
105
- }
106
- // 2. continue to parse audio base64 string
107
- try {
108
- result = eval(result)[0];
109
- }
110
- catch (e) {
111
- throw new Error("parse response failed:\n".concat(res.data));
112
- }
113
- return [2 /*return*/, result];
114
- }
115
- });
24
+ if (text.length > 200) {
25
+ throw new RangeError(`text length (${text.length}) should be less than 200 characters. Try "getAllAudioBase64(text, [option])" for long text.`);
26
+ }
27
+ const res = yield (0, axios_1.default)({
28
+ method: 'post',
29
+ baseURL: host,
30
+ url: '/_/TranslateWebserverUi/data/batchexecute',
31
+ timeout,
32
+ data: 'f.req=' +
33
+ encodeURIComponent(JSON.stringify([
34
+ [['jQ1olc', JSON.stringify([text, lang, slow ? true : null, 'null']), null, 'generic']],
35
+ ])),
116
36
  });
117
- };
37
+ let result;
38
+ try {
39
+ result = eval(res.data.slice(5))[0][2];
40
+ }
41
+ catch (e) {
42
+ throw new Error(`parse response failed:\n${res.data}`);
43
+ }
44
+ if (!result) {
45
+ throw new Error(`lang "${lang}" might not exist`);
46
+ }
47
+ try {
48
+ result = eval(result)[0];
49
+ }
50
+ catch (e) {
51
+ throw new Error(`parse response failed:\n${res.data}`);
52
+ }
53
+ return result;
54
+ });
118
55
  exports.getAudioBase64 = getAudioBase64;
119
- /**
120
- * @typedef {object} Result
121
- * @property {string} shortText
122
- * @property {string} base64
123
- */
124
- /**
125
- * Split the long text into multiple short text and generate audio base64 list
126
- *
127
- * @param {string} text
128
- * @param {object?} option
129
- * @param {string?} option.lang default is "en"
130
- * @param {boolean?} option.slow default is false
131
- * @param {string?} option.host default is "https://translate.google.com"
132
- * @param {string?} option.splitPunct split punctuation
133
- * @param {number?} option.timeout default is 10000 (ms)
134
- * @return {Result[]} the list with short text and audio base64
135
- */
136
- var getAllAudioBase64 = function (text_1) {
137
- var args_1 = [];
138
- for (var _i = 1; _i < arguments.length; _i++) {
139
- args_1[_i - 1] = arguments[_i];
56
+ const getAllAudioBase64 = (text_1, ...args_1) => __awaiter(void 0, [text_1, ...args_1], void 0, function* (text, { lang = 'en', slow = false, host = 'https://translate.google.com', splitPunct = '', timeout = 10000, } = {}) {
57
+ (0, assertInputTypes_1.default)(text, lang, slow, host);
58
+ if (typeof splitPunct !== 'string') {
59
+ throw new TypeError('splitPunct should be a string');
140
60
  }
141
- return __awaiter(void 0, __spreadArray([text_1], args_1, true), void 0, function (text, _a) {
142
- var shortTextList, base64List, result, i, shortText, base64;
143
- var _b = _a === void 0 ? {} : _a, _c = _b.lang, lang = _c === void 0 ? 'en' : _c, _d = _b.slow, slow = _d === void 0 ? false : _d, _e = _b.host, host = _e === void 0 ? 'https://translate.google.com' : _e, _f = _b.splitPunct, splitPunct = _f === void 0 ? '' : _f, _g = _b.timeout, timeout = _g === void 0 ? 10000 : _g;
144
- return __generator(this, function (_h) {
145
- switch (_h.label) {
146
- case 0:
147
- (0, assertInputTypes_1.default)(text, lang, slow, host);
148
- if (typeof splitPunct !== 'string') {
149
- throw new TypeError('splitPunct should be a string');
150
- }
151
- if (typeof timeout !== 'number' || timeout <= 0) {
152
- throw new TypeError('timeout should be a positive number');
153
- }
154
- shortTextList = (0, splitLongText_1.default)(text, { splitPunct: splitPunct });
155
- return [4 /*yield*/, Promise.all(shortTextList.map(function (shortText) { return (0, exports.getAudioBase64)(shortText, { lang: lang, slow: slow, host: host, timeout: timeout }); }))];
156
- case 1:
157
- base64List = _h.sent();
158
- result = [];
159
- for (i = 0; i < shortTextList.length; i++) {
160
- shortText = shortTextList[i];
161
- base64 = base64List[i];
162
- result.push({ shortText: shortText, base64: base64 });
163
- }
164
- return [2 /*return*/, result];
165
- }
166
- });
167
- });
168
- };
61
+ if (typeof timeout !== 'number' || timeout <= 0) {
62
+ throw new TypeError('timeout should be a positive number');
63
+ }
64
+ const shortTextList = (0, splitLongText_1.default)(text, { splitPunct });
65
+ const base64List = yield Promise.all(shortTextList.map((shortText) => (0, exports.getAudioBase64)(shortText, { lang, slow, host, timeout })));
66
+ const result = [];
67
+ for (let i = 0; i < shortTextList.length; i++) {
68
+ const shortText = shortTextList[i];
69
+ const base64 = base64List[i];
70
+ result.push({ shortText, base64 });
71
+ }
72
+ return result;
73
+ });
169
74
  exports.getAllAudioBase64 = getAllAudioBase64;
170
- //# sourceMappingURL=getAudioBase64.js.map
@@ -1,40 +1,12 @@
1
- /// <reference types="node" />
2
- import url from 'url';
3
1
  interface Option {
4
2
  lang?: string;
5
3
  slow?: boolean;
6
4
  host?: string;
7
5
  }
8
- /**
9
- * Generate "Google TTS" audio URL
10
- *
11
- * @param {string} text length should be less than 200 characters
12
- * @param {object?} option
13
- * @param {string?} option.lang default is "en"
14
- * @param {boolean?} option.slow default is false
15
- * @param {string?} option.host default is "https://translate.google.com"
16
- * @return {string} url
17
- */
18
6
  export declare const getAudioUrl: (text: string, { lang, slow, host }?: Option) => string;
19
7
  interface LongTextOption extends Option {
20
8
  splitPunct?: string;
21
9
  }
22
- /**
23
- * @typedef {object} Result
24
- * @property {string} shortText
25
- * @property {string} url
26
- */
27
- /**
28
- * Split the long text into multiple short text and generate audio URL list
29
- *
30
- * @param {string} text
31
- * @param {object?} option
32
- * @param {string?} option.lang default is "en"
33
- * @param {boolean?} option.slow default is false
34
- * @param {string?} option.host default is "https://translate.google.com"
35
- * @param {string?} option.splitPunct split punctuation
36
- * @return {Result[]} the list with short text and audio url
37
- */
38
10
  export declare const getAllAudioUrls: (text: string, { lang, slow, host, splitPunct, }?: LongTextOption) => {
39
11
  shortText: string;
40
12
  url: string;
@@ -1 +1 @@
1
- {"version":3,"file":"getAudioUrl.d.ts","sourceRoot":"","sources":["../src/getAudioUrl.ts"],"names":[],"mappings":";AAEA,OAAO,GAAG,MAAM,KAAK,CAAC;AAEtB,UAAU,MAAM;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,WAAW,SACd,MAAM,yBAC0D,MAAM,KAC7E,MA0BF,CAAC;AAEF,UAAU,cAAe,SAAQ,MAAM;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AAEH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,SAClB,MAAM,sCAMT,cAAc,KAClB;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,MAAM,CAAA;CAAE,EAWpC,CAAC"}
1
+ {"version":3,"file":"getAudioUrl.d.ts","sourceRoot":"","sources":["../src/getAudioUrl.ts"],"names":[],"mappings":"AAIA,UAAU,MAAM;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAYD,eAAO,MAAM,WAAW,SACd,MAAM,yBAC0D,MAAM,KAC7E,MA0BF,CAAC;AAEF,UAAU,cAAe,SAAQ,MAAM;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAmBD,eAAO,MAAM,eAAe,SAClB,MAAM,sCAMT,cAAc,KAClB;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EAWpC,CAAC"}
@@ -4,24 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getAllAudioUrls = exports.getAudioUrl = void 0;
7
- var assertInputTypes_1 = __importDefault(require("./assertInputTypes"));
8
- var splitLongText_1 = __importDefault(require("./splitLongText"));
9
- var url_1 = __importDefault(require("url"));
10
- /**
11
- * Generate "Google TTS" audio URL
12
- *
13
- * @param {string} text length should be less than 200 characters
14
- * @param {object?} option
15
- * @param {string?} option.lang default is "en"
16
- * @param {boolean?} option.slow default is false
17
- * @param {string?} option.host default is "https://translate.google.com"
18
- * @return {string} url
19
- */
20
- var getAudioUrl = function (text, _a) {
21
- var _b = _a === void 0 ? {} : _a, _c = _b.lang, lang = _c === void 0 ? 'en' : _c, _d = _b.slow, slow = _d === void 0 ? false : _d, _e = _b.host, host = _e === void 0 ? 'https://translate.google.com' : _e;
7
+ const assertInputTypes_1 = __importDefault(require("./assertInputTypes"));
8
+ const splitLongText_1 = __importDefault(require("./splitLongText"));
9
+ const url_1 = __importDefault(require("url"));
10
+ const getAudioUrl = (text, { lang = 'en', slow = false, host = 'https://translate.google.com' } = {}) => {
22
11
  (0, assertInputTypes_1.default)(text, lang, slow, host);
23
12
  if (text.length > 200) {
24
- throw new RangeError("text length (".concat(text.length, ") should be less than 200 characters. Try \"getAllAudioUrls(text, [option])\" for long text."));
13
+ throw new RangeError(`text length (${text.length}) should be less than 200 characters. Try "getAllAudioUrls(text, [option])" for long text.`);
25
14
  }
26
15
  return (host +
27
16
  '/translate_tts' +
@@ -40,32 +29,14 @@ var getAudioUrl = function (text, _a) {
40
29
  }));
41
30
  };
42
31
  exports.getAudioUrl = getAudioUrl;
43
- /**
44
- * @typedef {object} Result
45
- * @property {string} shortText
46
- * @property {string} url
47
- */
48
- /**
49
- * Split the long text into multiple short text and generate audio URL list
50
- *
51
- * @param {string} text
52
- * @param {object?} option
53
- * @param {string?} option.lang default is "en"
54
- * @param {boolean?} option.slow default is false
55
- * @param {string?} option.host default is "https://translate.google.com"
56
- * @param {string?} option.splitPunct split punctuation
57
- * @return {Result[]} the list with short text and audio url
58
- */
59
- var getAllAudioUrls = function (text, _a) {
60
- var _b = _a === void 0 ? {} : _a, _c = _b.lang, lang = _c === void 0 ? 'en' : _c, _d = _b.slow, slow = _d === void 0 ? false : _d, _e = _b.host, host = _e === void 0 ? 'https://translate.google.com' : _e, _f = _b.splitPunct, splitPunct = _f === void 0 ? '' : _f;
32
+ const getAllAudioUrls = (text, { lang = 'en', slow = false, host = 'https://translate.google.com', splitPunct = '', } = {}) => {
61
33
  (0, assertInputTypes_1.default)(text, lang, slow, host);
62
34
  if (typeof splitPunct !== 'string') {
63
35
  throw new TypeError('splitPunct should be a string');
64
36
  }
65
- return (0, splitLongText_1.default)(text, { splitPunct: splitPunct }).map(function (shortText) { return ({
66
- shortText: shortText,
67
- url: (0, exports.getAudioUrl)(shortText, { lang: lang, slow: slow, host: host }),
68
- }); });
37
+ return (0, splitLongText_1.default)(text, { splitPunct }).map((shortText) => ({
38
+ shortText,
39
+ url: (0, exports.getAudioUrl)(shortText, { lang, slow, host }),
40
+ }));
69
41
  };
70
42
  exports.getAllAudioUrls = getAllAudioUrls;
71
- //# sourceMappingURL=getAudioUrl.js.map
package/dist/index.js CHANGED
@@ -1,10 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAllAudioBase64 = exports.getAudioBase64 = exports.getAllAudioUrls = exports.getAudioUrl = void 0;
4
- var getAudioUrl_1 = require("./getAudioUrl");
4
+ const getAudioUrl_1 = require("./getAudioUrl");
5
5
  Object.defineProperty(exports, "getAudioUrl", { enumerable: true, get: function () { return getAudioUrl_1.getAudioUrl; } });
6
6
  Object.defineProperty(exports, "getAllAudioUrls", { enumerable: true, get: function () { return getAudioUrl_1.getAllAudioUrls; } });
7
- var getAudioBase64_1 = require("./getAudioBase64");
7
+ const getAudioBase64_1 = require("./getAudioBase64");
8
8
  Object.defineProperty(exports, "getAudioBase64", { enumerable: true, get: function () { return getAudioBase64_1.getAudioBase64; } });
9
9
  Object.defineProperty(exports, "getAllAudioBase64", { enumerable: true, get: function () { return getAudioBase64_1.getAllAudioBase64; } });
10
- //# sourceMappingURL=index.js.map
@@ -2,16 +2,6 @@ interface Option {
2
2
  maxLength?: number;
3
3
  splitPunct?: string;
4
4
  }
5
- /**
6
- * split the long text to short texts
7
- * Time Complexity: O(n)
8
- *
9
- * @param {string} text
10
- * @param {object?} option
11
- * @param {number?} option.maxLength default is 200
12
- * @param {string?} option.splitPunct default is ''
13
- * @returns {string[]} short text list
14
- */
15
5
  declare const splitLongText: (text: string, { maxLength, splitPunct }?: Option) => string[];
16
6
  export default splitLongText;
17
7
  //# sourceMappingURL=splitLongText.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"splitLongText.d.ts","sourceRoot":"","sources":["../src/splitLongText.ts"],"names":[],"mappings":"AAMA,UAAU,MAAM;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;GASG;AACH,QAAA,MAAM,aAAa,SACT,MAAM,8BAC0B,MAAM,KAC7C,MAAM,EAmDR,CAAC;AAEF,eAAe,aAAa,CAAC"}
1
+ {"version":3,"file":"splitLongText.d.ts","sourceRoot":"","sources":["../src/splitLongText.ts"],"names":[],"mappings":"AAMA,UAAU,MAAM;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAYD,QAAA,MAAM,aAAa,SACT,MAAM,8BAC0B,MAAM,KAC7C,MAAM,EAmDR,CAAC;AAEF,eAAe,aAAa,CAAC"}
@@ -1,63 +1,45 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
4
- var SPACE_REGEX = '\\s\\uFEFF\\xA0';
5
- // https://remarkablemark.org/blog/2019/09/28/javascript-remove-punctuation
6
- var DEFAULT_PUNCTUATION_REGEX = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
7
- /**
8
- * split the long text to short texts
9
- * Time Complexity: O(n)
10
- *
11
- * @param {string} text
12
- * @param {object?} option
13
- * @param {number?} option.maxLength default is 200
14
- * @param {string?} option.splitPunct default is ''
15
- * @returns {string[]} short text list
16
- */
17
- var splitLongText = function (text, _a) {
18
- var _b = _a === void 0 ? {} : _a, _c = _b.maxLength, maxLength = _c === void 0 ? 200 : _c, _d = _b.splitPunct, splitPunct = _d === void 0 ? '' : _d;
19
- var isSpaceOrPunct = function (s, i) {
20
- var regex = new RegExp('[' + SPACE_REGEX + DEFAULT_PUNCTUATION_REGEX + splitPunct + ']');
3
+ const SPACE_REGEX = '\\s\\uFEFF\\xA0';
4
+ const DEFAULT_PUNCTUATION_REGEX = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
5
+ const splitLongText = (text, { maxLength = 200, splitPunct = '' } = {}) => {
6
+ const isSpaceOrPunct = (s, i) => {
7
+ const regex = new RegExp('[' + SPACE_REGEX + DEFAULT_PUNCTUATION_REGEX + splitPunct + ']');
21
8
  return regex.test(s.charAt(i));
22
9
  };
23
- var lastIndexOfSpaceOrPunct = function (s, left, right) {
24
- for (var i = right; i >= left; i--) {
10
+ const lastIndexOfSpaceOrPunct = (s, left, right) => {
11
+ for (let i = right; i >= left; i--) {
25
12
  if (isSpaceOrPunct(s, i))
26
13
  return i;
27
14
  }
28
- return -1; // not found
15
+ return -1;
29
16
  };
30
- var result = [];
31
- var addResult = function (text, start, end) {
17
+ const result = [];
18
+ const addResult = (text, start, end) => {
32
19
  result.push(text.slice(start, end + 1));
33
20
  };
34
- var start = 0;
21
+ let start = 0;
35
22
  for (;;) {
36
- // check text's length
37
23
  if (text.length - start <= maxLength) {
38
24
  addResult(text, start, text.length - 1);
39
- break; // end of text
25
+ break;
40
26
  }
41
- // check whether the word is cut in the middle.
42
- var end = start + maxLength - 1;
27
+ let end = start + maxLength - 1;
43
28
  if (isSpaceOrPunct(text, end) || isSpaceOrPunct(text, end + 1)) {
44
29
  addResult(text, start, end);
45
30
  start = end + 1;
46
31
  continue;
47
32
  }
48
- // find last index of space
49
33
  end = lastIndexOfSpaceOrPunct(text, start, end);
50
34
  if (end === -1) {
51
- var str = text.slice(start, start + maxLength);
35
+ const str = text.slice(start, start + maxLength);
52
36
  throw new Error('The word is too long to split into a short text:' +
53
- "\n".concat(str, " ...") +
37
+ `\n${str} ...` +
54
38
  '\n\nTry the option "splitPunct" to split the text by punctuation.');
55
39
  }
56
- // add result
57
40
  addResult(text, start, end);
58
41
  start = end + 1;
59
42
  }
60
43
  return result;
61
44
  };
62
45
  exports.default = splitLongText;
63
- //# sourceMappingURL=splitLongText.js.map
@@ -0,0 +1,56 @@
1
+ import js from '@eslint/js';
2
+ import globals from 'globals';
3
+
4
+ // noinspection JSUnusedGlobalSymbols
5
+ export default [
6
+ js.configs.recommended,
7
+ {
8
+ languageOptions: {
9
+ ecmaVersion: 2024,
10
+ globals: {
11
+ ...globals.node,
12
+ ...globals.es2024
13
+ }
14
+ },
15
+ rules: {
16
+ 'arrow-spacing': ['warn', { before: true, after: true }],
17
+ 'comma-dangle': ['error'],
18
+ 'comma-spacing': 'error',
19
+ 'comma-style': 'error',
20
+ 'curly': ['error', 'multi-line', 'consistent'],
21
+ 'dot-location': ['error', 'property'],
22
+ 'handle-callback-err': 'off',
23
+ 'indent': ['warn', 'tab'],
24
+ 'keyword-spacing': 'warn',
25
+ 'max-nested-callbacks': ['error', { max: 4 }],
26
+ 'max-statements-per-line': ['error', { max: 2 }],
27
+ 'no-console': 'off',
28
+ 'no-empty': 'warn',
29
+ 'no-empty-function': 'error',
30
+ 'no-floating-decimal': 'error',
31
+ 'no-lonely-if': 'error',
32
+ 'no-multi-spaces': 'warn',
33
+ 'no-multiple-empty-lines': ['warn', { max: 4, maxEOF: 1, maxBOF: 0 }],
34
+ 'no-shadow': ['error', { allow: ['err', 'resolve', 'reject'] }],
35
+ 'no-trailing-spaces': ['warn'],
36
+ 'no-unreachable': 'warn',
37
+ 'no-unused-vars': 'warn',
38
+ 'no-use-before-define': ['error', { functions: false, classes: true }],
39
+ 'no-var': 'error',
40
+ 'object-curly-spacing': ['error', 'always'],
41
+ 'prefer-const': 'error',
42
+ 'quotes': ['warn', 'single'],
43
+ 'semi': ['warn', 'always'],
44
+ 'sort-vars': 'warn',
45
+ 'space-before-blocks': 'error',
46
+ 'space-before-function-paren': ['error', { anonymous: 'never', named: 'never', asyncArrow: 'always' }],
47
+ 'space-in-parens': 'error',
48
+ 'space-infix-ops': 'error',
49
+ 'space-unary-ops': 'error',
50
+ 'spaced-comment': 'warn',
51
+ 'wrap-regex': 'error',
52
+ 'yoda': 'error'
53
+ },
54
+ ignores: ['node_modules']
55
+ }
56
+ ];
@@ -1,17 +1,17 @@
1
1
  const fs = require('fs');
2
2
  const googleTTS = require('../dist/index');
3
3
 
4
- // 1. get audio URL
4
+ // 1. Get audio URL
5
5
  const url = googleTTS.getAudioUrl('Hello World', { lang: 'en-GB' });
6
6
  console.log({ url }); // https://translate.google.com/translate_tts?...
7
7
 
8
- // 2. get base64 text
8
+ // 2. Get base64 text
9
9
  googleTTS
10
10
  .getAudioBase64('Hello World', { lang: 'en-GB' })
11
11
  .then((base64) => {
12
12
  console.log({ base64 });
13
13
 
14
- // save the audio file
14
+ // Save the audio file
15
15
  const buffer = Buffer.from(base64, 'base64');
16
16
  fs.writeFileSync('hello-world-british.mp3', buffer, { encoding: 'base64' });
17
17
  })
@@ -1,17 +1,17 @@
1
1
  const fs = require('fs');
2
2
  const googleTTS = require('../dist/index');
3
3
 
4
- // 1. get audio URL
4
+ // 1. Get audio URL
5
5
  const url = googleTTS.getAudioUrl('你好世界', { lang: 'zh-TW' });
6
6
  console.log({ url }); // https://translate.google.com/translate_tts?...
7
7
 
8
- // 2. get base64 text
8
+ // 2. Get base64 text
9
9
  googleTTS
10
10
  .getAudioBase64('你好世界', { lang: 'zh-TW' })
11
11
  .then((base64) => {
12
12
  console.log({ base64 });
13
13
 
14
- // save the audio file
14
+ // Save the audio file
15
15
  const buffer = Buffer.from(base64, 'base64');
16
16
  fs.writeFileSync('hello-world-chinese.mp3', buffer, { encoding: 'base64' });
17
17
  })
@@ -13,13 +13,13 @@ function downloadFile(url, dest) {
13
13
  host: info.host,
14
14
  path: info.path,
15
15
  headers: {
16
- 'user-agent': 'WHAT_EVER',
17
- },
16
+ 'user-agent': 'WHAT_EVER'
17
+ }
18
18
  };
19
19
 
20
20
  httpClient
21
21
  .get(options, (res) => {
22
- // check status code
22
+ // Check status code
23
23
  if (res.statusCode !== 200) {
24
24
  const msg = `request to ${url} failed, status code = ${res.statusCode} (${res.statusMessage})`;
25
25
  reject(new Error(msg));
@@ -48,7 +48,7 @@ function downloadFile(url, dest) {
48
48
  const url = googleTTS.getAudioUrl('hello');
49
49
  console.log(url); // https://translate.google.com/translate_tts?...
50
50
 
51
- const dest = path.resolve(__dirname, 'hello.mp3'); // file destination
51
+ const dest = path.resolve(__dirname, 'hello.mp3'); // File destination
52
52
  console.log('Download to ' + dest + ' ...');
53
53
  downloadFile(url, dest);
54
54
  console.log('Download success');