vite-gc-i18n-plugin 1.1.0 → 1.1.1

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.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2699 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("gc-i18n-plugin-core");function t(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var n=t(require("@babel/core")),r=function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},r.apply(this,arguments)};function o(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,l)}c((r=r.apply(e,t||[])).next())}))}function i(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=l(0),a.throw=l(1),a.return=l(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function l(l){return function(c){return function(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&l[0]?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[2&l[0],o.value]),l[0]){case 0:case 1:o=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,r=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==l[0]&&2!==l[0])){i=0;continue}if(3===l[0]&&(!o||l[1]>o[0]&&l[1]<o[3])){i.label=l[1];break}if(6===l[0]&&i.label<o[1]){i.label=o[1],o=l;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(l);break}o[2]&&i.ops.pop(),i.trys.pop();continue}l=t.call(e,i)}catch(e){l=[6,e],r=0}finally{n=o=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,c])}}}function a(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var l=[".vue",".ts",".js",".tsx",".jsx"];exports.default=function(t){var c,u="vite-gc-i18n-plugin";if(e.initOption(r({deepScan:!0,globalPath:"./lang",namespace:"lang",translateKey:"$t",distPath:"./dist/assets",distKey:"index",targetLangList:["zh-cn","zh-tw"],originLang:"zh-cn",translator:new e.CNToTWTranslator},t)),!e.checkOption())return{name:u};e.fileUtils.initLangFile();var s=e.fileUtils.getLangObjByJSONFileWithLangKey(e.option.originLang);return e.translateUtils.languageConfigCompletion(s),e.translateUtils.initLangObj(s),{name:u,configResolved:function(e){c=e},transform:function(t,r){return o(this,void 0,void 0,(function(){var o,u;return i(this,(function(i){switch(i.label){case 0:return a(a([],l,!0),e.option.insertFileExtensions||[],!0).some((function(e){return r.endsWith(e)}))?e.option.includePath.length&&!e.baseUtils.checkAgainstRegexArray(r,e.option.includePath)||e.option.excludedPath.length&&e.baseUtils.checkAgainstRegexArray(r,e.option.excludedPath)?[2,t]:(e.FunctionFactoryOption.originLang=e.option.originLang,o=void 0,e.option.translateExtends?[4,null===(u=e.option.translateExtends)||void 0===u?void 0:u.handleInitFile(t,r)]:[3,2]):[3,4];case 1:return o=i.sent(),[3,3];case 2:o={source:t},i.label=3;case 3:return[2,n.transformAsync(o.source,{configFile:!1,plugins:[e.filter.default()]}).then((function(t){return"serve"===(null==c?void 0:c.command)&&e.translateUtils.autoTranslate(),null==t?void 0:t.code})).catch((function(e){console.error(e)}))];case 4:return[2]}}))}))},buildEnd:function(){return o(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return console.info("构建阶段批量翻译"),[4,e.translateUtils.autoTranslate()];case 1:return t.sent(),[2]}}))}))},closeBundle:function(){return o(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return c&&"build"===c.command?e.option.uploadEnabled?(console.info("构建阶段:开始上传翻译文件"),[4,e.fileUtils.uploadFile()]):[3,2]:[3,3];case 1:return t.sent(),[3,3];case 2:console.info("构建阶段:上传翻译文件功能已禁用(uploadEnabled: false)"),t.label=3;case 3:return[2]}}))}))}}},Object.keys(e).forEach((function(t){"default"===t||Object.prototype.hasOwnProperty.call(exports,t)||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}})}));
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var googleTranslateApi = require('@vitalets/google-translate-api');
6
+ var tunnel = require('tunnel');
7
+ var axios = require('axios');
8
+ var CryptoJS = require('crypto-js');
9
+ var OpenCC = require('opencc-js');
10
+ var types = require('@babel/types');
11
+ var _ = require('lodash');
12
+ var path = require('node:path');
13
+ var fs = require('node:fs');
14
+ var babel = require('@babel/core');
15
+
16
+ function _interopNamespaceDefault(e) {
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n.default = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var OpenCC__namespace = /*#__PURE__*/_interopNamespaceDefault(OpenCC);
34
+ var types__namespace = /*#__PURE__*/_interopNamespaceDefault(types);
35
+ var babel__namespace = /*#__PURE__*/_interopNamespaceDefault(babel);
36
+
37
+ /******************************************************************************
38
+ Copyright (c) Microsoft Corporation.
39
+
40
+ Permission to use, copy, modify, and/or distribute this software for any
41
+ purpose with or without fee is hereby granted.
42
+
43
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
44
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
45
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
46
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
47
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
48
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
49
+ PERFORMANCE OF THIS SOFTWARE.
50
+ ***************************************************************************** */
51
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
52
+
53
+ var __assign = function () {
54
+ __assign = Object.assign || function __assign(t) {
55
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
56
+ s = arguments[i];
57
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
58
+ }
59
+ return t;
60
+ };
61
+ return __assign.apply(this, arguments);
62
+ };
63
+ function __awaiter(thisArg, _arguments, P, generator) {
64
+ function adopt(value) {
65
+ return value instanceof P ? value : new P(function (resolve) {
66
+ resolve(value);
67
+ });
68
+ }
69
+ return new (P || (P = Promise))(function (resolve, reject) {
70
+ function fulfilled(value) {
71
+ try {
72
+ step(generator.next(value));
73
+ } catch (e) {
74
+ reject(e);
75
+ }
76
+ }
77
+ function rejected(value) {
78
+ try {
79
+ step(generator["throw"](value));
80
+ } catch (e) {
81
+ reject(e);
82
+ }
83
+ }
84
+ function step(result) {
85
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
86
+ }
87
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
88
+ });
89
+ }
90
+ function __generator(thisArg, body) {
91
+ var _ = {
92
+ label: 0,
93
+ sent: function () {
94
+ if (t[0] & 1) throw t[1];
95
+ return t[1];
96
+ },
97
+ trys: [],
98
+ ops: []
99
+ },
100
+ f,
101
+ y,
102
+ t,
103
+ g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
104
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () {
105
+ return this;
106
+ }), g;
107
+ function verb(n) {
108
+ return function (v) {
109
+ return step([n, v]);
110
+ };
111
+ }
112
+ function step(op) {
113
+ if (f) throw new TypeError("Generator is already executing.");
114
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
115
+ 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;
116
+ if (y = 0, t) op = [op[0] & 2, t.value];
117
+ switch (op[0]) {
118
+ case 0:
119
+ case 1:
120
+ t = op;
121
+ break;
122
+ case 4:
123
+ _.label++;
124
+ return {
125
+ value: op[1],
126
+ done: false
127
+ };
128
+ case 5:
129
+ _.label++;
130
+ y = op[1];
131
+ op = [0];
132
+ continue;
133
+ case 7:
134
+ op = _.ops.pop();
135
+ _.trys.pop();
136
+ continue;
137
+ default:
138
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
139
+ _ = 0;
140
+ continue;
141
+ }
142
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
143
+ _.label = op[1];
144
+ break;
145
+ }
146
+ if (op[0] === 6 && _.label < t[1]) {
147
+ _.label = t[1];
148
+ t = op;
149
+ break;
150
+ }
151
+ if (t && _.label < t[2]) {
152
+ _.label = t[2];
153
+ _.ops.push(op);
154
+ break;
155
+ }
156
+ if (t[2]) _.ops.pop();
157
+ _.trys.pop();
158
+ continue;
159
+ }
160
+ op = body.call(thisArg, _);
161
+ } catch (e) {
162
+ op = [6, e];
163
+ y = 0;
164
+ } finally {
165
+ f = t = 0;
166
+ }
167
+ if (op[0] & 5) throw op[1];
168
+ return {
169
+ value: op[0] ? op[1] : void 0,
170
+ done: true
171
+ };
172
+ }
173
+ }
174
+ function __spreadArray(to, from, pack) {
175
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
176
+ if (ar || !(i in from)) {
177
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
178
+ ar[i] = from[i];
179
+ }
180
+ }
181
+ return to.concat(ar || Array.prototype.slice.call(from));
182
+ }
183
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
184
+ var e = new Error(message);
185
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
186
+ };
187
+
188
+ /**
189
+ * 间隔执行队列
190
+ */
191
+ class IntervalQueue {
192
+ /**
193
+ * @param fn 执行函数
194
+ * @param delay 执行间隔
195
+ * @param timeout 超时时间
196
+ */
197
+ constructor(fn, delay, timeout) {
198
+ this.fn = fn;
199
+ this.delay = delay;
200
+ this.timeout = timeout;
201
+ }
202
+ queue = [];
203
+ async wait() {
204
+ let delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.delay;
205
+ await new Promise(resolve => setTimeout(resolve, delay));
206
+ }
207
+ isRunning = false;
208
+ async run() {
209
+ if (this.isRunning) return;
210
+ let item;
211
+ while (item = this.queue.shift()) {
212
+ const {
213
+ args,
214
+ resolve,
215
+ reject
216
+ } = item;
217
+ this.isRunning = true;
218
+ try {
219
+ const result = await this.fn(...args);
220
+ resolve(result);
221
+ } catch (e) {
222
+ reject(e);
223
+ }
224
+ await this.wait();
225
+ }
226
+ this.isRunning = false;
227
+ }
228
+
229
+ /**
230
+ * 执行一次fn
231
+ * @param args fn的入参
232
+ * @returns 返回fn的返回值的Promise
233
+ */
234
+ execute() {
235
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
236
+ args[_key] = arguments[_key];
237
+ }
238
+ return new Promise((resolve, reject) => {
239
+ this.queue.push({
240
+ args,
241
+ resolve,
242
+ reject
243
+ });
244
+ this.run();
245
+ if (this.timeout) {
246
+ setTimeout(() => {
247
+ reject(new Error('IntervalQueue timeout'));
248
+ }, this.timeout);
249
+ }
250
+ });
251
+ }
252
+ }
253
+
254
+ class Translator {
255
+ constructor(option) {
256
+ this.option = this.getResultOption(option);
257
+ }
258
+ defaultErrorHandler = error => {
259
+ const name = this.option.name;
260
+ console.error(`翻译api${name ? `【${name}】` : ''}请求异常:${this.getErrorMessage(error)}`);
261
+ };
262
+ getResultOption(option) {
263
+ const resultOption = {
264
+ version: 1,
265
+ maxChunkSize: 4500,
266
+ // 目前默认是4500
267
+ interval: 0,
268
+ onError: this.defaultErrorHandler,
269
+ ...option
270
+ };
271
+ if (resultOption.interval) {
272
+ const getIntervalFn = (fn, delay) => {
273
+ const queue = new IntervalQueue(fn.bind(null), delay);
274
+ return function () {
275
+ return queue.execute(...arguments);
276
+ };
277
+ };
278
+ resultOption.fetchMethod = getIntervalFn(resultOption.fetchMethod, resultOption.interval);
279
+ }
280
+ return resultOption;
281
+ }
282
+ getErrorMessage(error) {
283
+ if (error instanceof Error) {
284
+ return error.message;
285
+ } else {
286
+ return String(error);
287
+ }
288
+ }
289
+ async translate(text, fromKey, toKey, separator) {
290
+ let result = '';
291
+ try {
292
+ result = await this.option.fetchMethod(text, fromKey, toKey, separator);
293
+ } catch (error) {
294
+ this.option.onError(error, this.defaultErrorHandler);
295
+ }
296
+ return result;
297
+ }
298
+ }
299
+
300
+ /*
301
+ * @Date: 2025-03-11 17:53:11
302
+ * @LastEditors: xiaoshan
303
+ * @LastEditTime: 2025-03-14 14:21:06
304
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/google.ts
305
+ */
306
+ /**
307
+ * 谷歌翻译器
308
+ *
309
+ * 基于@vitalets/google-translate-api,需要翻墙,不稳定,但是免费
310
+ *
311
+ * 使用方式:
312
+ * ```ts
313
+ * vitePluginsAutoI18n({
314
+ ...
315
+ translator: translator: new GoogleTranslator({
316
+ proxyOption: {
317
+ // 如果你本地的代理在127.0.0.0:8899
318
+ host: '127.0.0.1',
319
+ port: 8899,
320
+ headers: {
321
+ 'User-Agent': 'Node'
322
+ }
323
+ }
324
+ })
325
+ })
326
+ * ```
327
+ */
328
+ class GoogleTranslator extends Translator {
329
+ constructor(option) {
330
+ super({
331
+ name: 'Google翻译',
332
+ fetchMethod: async (text, fromKey, toKey) => {
333
+ let data = await googleTranslateApi.translate(text, {
334
+ from: fromKey,
335
+ to: toKey,
336
+ ...(option.proxyOption ? {
337
+ fetchOptions: {
338
+ agent: tunnel.httpsOverHttp({
339
+ proxy: option.proxyOption
340
+ })
341
+ }
342
+ } : {}),
343
+ ...(option.insertOption || {})
344
+ });
345
+ return data['text'] || '';
346
+ },
347
+ onError: (error, cb) => {
348
+ cb(error);
349
+ if (error instanceof Object && 'code' in error && error.code === 'ETIMEDOUT') {
350
+ console.error('❗ 请求超时,请确保你的网络可以访问google ❗');
351
+ }
352
+ },
353
+ interval: option.interval ?? 1000
354
+ });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * 有道翻译器
360
+ *
361
+ * api文档:https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html
362
+ *
363
+ * 使用方式:
364
+ * ```ts
365
+ * vitePluginsAutoI18n({
366
+ ...
367
+ translator: new YoudaoTranslator({
368
+ appId: '你申请的appId',
369
+ appKey: '你申请的appKey'
370
+ })
371
+ })
372
+ * ```
373
+ */
374
+ class YoudaoTranslator extends Translator {
375
+ /** 有道的语言类型映射不标准,需要手动控制 */
376
+ YOUDAO_TRANSLATE_KEY_CONVERT_MAP = {
377
+ 'zh-cn': 'zh-CHS',
378
+ 'zh-tw': 'zh-CHT'
379
+ };
380
+ truncate(q) {
381
+ // 检查输入字符串的长度
382
+ if (q.length <= 20) {
383
+ // 如果长度小于等于20,直接返回原字符串
384
+ return q;
385
+ } else {
386
+ // 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
387
+ const len = q.length;
388
+ return q.substring(0, 10) + len + q.substring(len - 10);
389
+ }
390
+ }
391
+ getTranslateKey(key) {
392
+ return this.YOUDAO_TRANSLATE_KEY_CONVERT_MAP[key] || key;
393
+ }
394
+ constructor(option) {
395
+ super({
396
+ name: '有道翻译',
397
+ fetchMethod: async (text, fromKey, toKey) => {
398
+ let salt = new Date().getTime();
399
+ let curTime = Math.round(new Date().getTime() / 1000);
400
+ let str = option.appId + this.truncate(text) + salt + curTime + option.appKey;
401
+ let sign = CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
402
+ const data = {
403
+ q: text,
404
+ appKey: option.appId,
405
+ salt,
406
+ from: this.getTranslateKey(fromKey),
407
+ to: this.getTranslateKey(toKey),
408
+ sign,
409
+ signType: 'v3',
410
+ curtime: curTime,
411
+ ...(option.insertOption || {})
412
+ };
413
+ const response = await axios.post('https://openapi.youdao.com/api', data, {
414
+ headers: {
415
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
416
+ },
417
+ proxy: option.proxy
418
+ });
419
+ // 请求成功,返回响应数据
420
+ return response.data.translation?.[0] || '';
421
+ },
422
+ onError: (error, cb) => {
423
+ cb(error);
424
+ console.error('请前往有道翻译官方申请翻译key,默认会有50的额度,并请检查额度是否充足。');
425
+ },
426
+ interval: option.interval ?? 1000
427
+ });
428
+ }
429
+ }
430
+
431
+ /*
432
+ * @Date: 2025-03-16 23:39:13
433
+ * @LastEditors: xiaoshan
434
+ * @LastEditTime: 2025-03-17 01:11:37
435
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/baidu.ts
436
+ */
437
+ /**
438
+ * 百度翻译器
439
+ *
440
+ * api文档:https://api.fanyi.baidu.com/product/113
441
+ *
442
+ * 使用方式:
443
+ * ```ts
444
+ * vitePluginsAutoI18n({
445
+ ...
446
+ translator: new BaiduTranslator({
447
+ appId: '你申请的appId',
448
+ appKey: '你申请的appKey'
449
+ })
450
+ })
451
+ * ```
452
+ */
453
+ class BaiduTranslator extends Translator {
454
+ /** 百度的语言类型映射不标准,需要手动控制 */
455
+ BAIDU_TRANSLATE_KEY_CONVERT_MAP = {
456
+ 'zh-cn': 'zh',
457
+ ja: 'jp',
458
+ ko: 'kor'
459
+ };
460
+ getTranslateKey(key) {
461
+ return this.BAIDU_TRANSLATE_KEY_CONVERT_MAP[key] || key;
462
+ }
463
+ constructor(option) {
464
+ super({
465
+ name: '百度翻译',
466
+ fetchMethod: async (text, fromKey, toKey, separator) => {
467
+ let salt = new Date().getTime();
468
+ const data = {
469
+ q: text,
470
+ appid: option.appId,
471
+ from: this.getTranslateKey(fromKey),
472
+ to: this.getTranslateKey(toKey),
473
+ salt,
474
+ sign: CryptoJS.MD5(option.appId + text + salt + option.appKey).toString(),
475
+ ...(option.insertOption || {})
476
+ };
477
+ const response = await axios.post('https://fanyi-api.baidu.com/api/trans/vip/translate', data, {
478
+ headers: {
479
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
480
+ },
481
+ proxy: option.proxy
482
+ });
483
+ const translatedTexts = response.data?.trans_result.map(item => item.dst).filter((_item, index) => index % 2 === 0).join(separator);
484
+
485
+ // 请求成功,返回响应数据
486
+ return translatedTexts || '';
487
+ },
488
+ onError: (error, cb) => {
489
+ cb(error);
490
+ console.error('请前往百度翻译官方申请翻译key,每个月都有免费额度,并请检查额度是否充足。');
491
+ },
492
+ interval: option.interval ?? 1000
493
+ });
494
+ }
495
+ }
496
+
497
+ /*
498
+ * @Date: 2025-03-31 19:05:57
499
+ * @LastEditors: xiaoshan
500
+ * @LastEditTime: 2025-03-31 19:52:10
501
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/translator/scan.ts
502
+ */
503
+
504
+ /**
505
+ * 空翻译器,不翻译文本,用于配合某些特殊的操作
506
+ */
507
+ class EmptyTranslator extends Translator {
508
+ constructor() {
509
+ let option = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
510
+ const resultOption = {
511
+ name: '空翻译器',
512
+ fetchMethod: async (text, _from, _to, separator) => {
513
+ // 相当于把翻译结果统一设置为空串
514
+ const value = text.split(separator).fill('');
515
+ return value.join(separator);
516
+ },
517
+ ...option
518
+ };
519
+ super(resultOption);
520
+ }
521
+ // TODO: 后续可以作为基类,提供更多的配置选项
522
+ }
523
+
524
+ /** @deprecated 别名导出,兼容旧版本 */
525
+ const ScanTranslator = EmptyTranslator;
526
+
527
+ const cn2tw = OpenCC__namespace.Converter({
528
+ from: 'cn',
529
+ to: 'tw'
530
+ });
531
+ class CNToTWTranslator extends Translator {
532
+ constructor() {
533
+ super({
534
+ name: '中翻繁翻译',
535
+ fetchMethod: async (text, fromKey, toKey) => {
536
+ let translatedTexts = text;
537
+ if (fromKey === 'zh-cn' && toKey === 'zh-tw') {
538
+ translatedTexts = cn2tw(text);
539
+ }
540
+
541
+ // 请求成功,返回响应数据
542
+ return translatedTexts;
543
+ },
544
+ onError: (error, cb) => {
545
+ cb(error);
546
+ console.error('翻译失败');
547
+ }
548
+ });
549
+ }
550
+ }
551
+
552
+ /*
553
+ * @Author: xiaoshanwen
554
+ * @Date: 2024-02-29 14:44:18
555
+ * @LastEditTime: 2024-03-01 11:42:34
556
+ * @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/utils/option.ts
557
+ */
558
+
559
+ class FunctionFactoryOption {
560
+ static originLang = '';
561
+ }
562
+
563
+ /*
564
+ * @Author: xiaoshanwen
565
+ * @Date: 2024-03-11 18:59:10
566
+ * @LastEditTime: 2025-03-16 18:15:25
567
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/enums/language.ts
568
+ */
569
+ // 待补充...
570
+ let LanguageEnum = /*#__PURE__*/function (LanguageEnum) {
571
+ return LanguageEnum;
572
+ }({});
573
+ let OriginLangKeyEnum = /*#__PURE__*/function (OriginLangKeyEnum) {
574
+ OriginLangKeyEnum["ZH"] = "zh-cn";
575
+ OriginLangKeyEnum["EN"] = "en";
576
+ OriginLangKeyEnum["JA"] = "ja";
577
+ OriginLangKeyEnum["KO"] = "ko";
578
+ OriginLangKeyEnum["RU"] = "ru";
579
+ return OriginLangKeyEnum;
580
+ }({});
581
+
582
+ /*
583
+ * @Author: xiaoshanwen
584
+ * @Date: 2024-04-06 15:47:14
585
+ * @LastEditTime: 2025-03-16 18:18:28
586
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/constants/translate.ts
587
+ */
588
+ const REGEX_MAP = {
589
+ [OriginLangKeyEnum.ZH]: /[\u4e00-\u9fff]/,
590
+ [OriginLangKeyEnum.EN]: /[a-zA-Z]/,
591
+ [OriginLangKeyEnum.JA]: /[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF]/,
592
+ // 日语假名和汉字
593
+ [OriginLangKeyEnum.KO]: /[\uAC00-\uD7A3]/,
594
+ // 韩语字母
595
+ [OriginLangKeyEnum.RU]: /[йцукенгшщзхъфывапролджэячсмитьбюё .-]{1,}/ // 俄语字母
596
+ };
597
+
598
+ /*
599
+ * @Author: xiaoshanwen
600
+ * @Date: 2023-10-11 10:01:43
601
+ * @LastEditTime: 2025-03-28 19:07:17
602
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/base.ts
603
+ */
604
+ function getOriginRegex() {
605
+ const originLang = FunctionFactoryOption.originLang;
606
+ return REGEX_MAP[originLang];
607
+ }
608
+
609
+ /**
610
+ * @description: 是否包含来源语言字符
611
+ * @param {string} code
612
+ * @return {*}
613
+ */
614
+ function hasOriginSymbols(code) {
615
+ return getOriginRegex().test(code);
616
+ }
617
+
618
+ /**
619
+ * @description: 过滤注释
620
+ * @param {string} code
621
+ * @return {*}
622
+ */
623
+ const removeComments = function (code) {
624
+ // 使用正则表达式匹配并删除单行注释
625
+ code = code.replace(/\/\/.*?\n/g, '');
626
+ // 使用正则表达式匹配并删除多行注释
627
+ code = code.replace(/\/\*[\s\S]*?\*\//g, '');
628
+ // 使用正则表达式匹配并删除HTML注释
629
+ code = code.replace(/<!--[\s\S]*?-->/g, '');
630
+ return code;
631
+ };
632
+
633
+ /**
634
+ * @description: 用于判断提供的值是否符合正则表达式数组中的任一规则,符合则跳过
635
+ * @param {*} value
636
+ * @param {*} regexArray
637
+ * @return {*}
638
+ */
639
+ function checkAgainstRegexArray(value, regexArray) {
640
+ for (let i = 0; i < regexArray.length; i++) {
641
+ const regex = typeof regexArray[i] === 'string' ? new RegExp(regexArray[i]) : regexArray[i];
642
+ if (regex.test(value)) {
643
+ return true; // 如果符合任何一个规则,返回 true
644
+ }
645
+ }
646
+ return false; // 如果所有规则都不符合,返回 false
647
+ }
648
+
649
+ /**
650
+ * @description: 用于解析抽象语法树中的调用表达式,并提取出调用的名称,如a.b.c() 取 c。
651
+ * @param {any} node
652
+ * @return {*}
653
+ */
654
+ function extractFunctionName(node) {
655
+ let callName = '';
656
+ function callObjName(callObj, name) {
657
+ name += '.' + callObj.property.name;
658
+ if (types.isMemberExpression(callObj.object)) {
659
+ // isMemberExpression: 是否是成员表达式
660
+ return callObjName(callObj.object, name);
661
+ }
662
+ name = callObj.object.name + name;
663
+ return name;
664
+ }
665
+ if (types.isCallExpression(node)) {
666
+ // isCallExpression: 是否是调用表达式
667
+ if (types.isMemberExpression(node.callee)) {
668
+ callName = callObjName(node.callee, '');
669
+ } else {
670
+ callName = node.callee.name || '';
671
+ }
672
+ }
673
+ return callName;
674
+ }
675
+
676
+ /**
677
+ * @description: 提取文件的中文部分
678
+ * @param {string} fileContent
679
+ * @return {*}
680
+ */
681
+ const extractCnStrings = fileContent => {
682
+ const regex = /[^\x00-\xff]+/g;
683
+ return extractStrings(fileContent, regex);
684
+ };
685
+
686
+ /**
687
+ * @description: 提取文件指定部分内容
688
+ * @param {string} fileContent
689
+ * @param {any} regex
690
+ * @return {*}
691
+ */
692
+ function extractStrings(fileContent, regex) {
693
+ const matches = fileContent.match(regex);
694
+ return matches ? matches.filter((item, index) => matches.indexOf(item) === index) : [];
695
+ }
696
+
697
+ /**
698
+ * @description: 生成i8n翻译函数
699
+ * @param {string} value
700
+ * @param {boolean} isExpression
701
+ * @param {string} key
702
+ * @return {*}
703
+ */
704
+ function createI18nTranslator(createOption) {
705
+ const {
706
+ value,
707
+ isExpression = false,
708
+ key,
709
+ insertOption
710
+ } = createOption;
711
+
712
+ // 从全局配置对象 option 中获取命名空间
713
+ const nameSpace = exports.option.namespace;
714
+ const {
715
+ trimmedValue,
716
+ valStr
717
+ } = normalizeTranslateValue(value);
718
+ // 若 key 存在则使用 key,否则调用 generateId 函数根据 valStr 生成唯一的键
719
+ const generatedKey = key || generateId(valStr);
720
+ // 提取公共配置对象,避免重复代码
721
+ const config = {
722
+ option: exports.option,
723
+ hash: generatedKey,
724
+ value: trimmedValue,
725
+ uncodeValue: valStr,
726
+ namespace: nameSpace
727
+ };
728
+ if (exports.option.translateExtends) {
729
+ const {
730
+ handleCodeCall,
731
+ handleCodeString
732
+ } = exports.option.translateExtends;
733
+ return isExpression ? handleCodeCall(config, insertOption) : handleCodeString(config, insertOption);
734
+ }
735
+ if (isExpression) {
736
+ const valueExp = types.stringLiteral(trimmedValue);
737
+ valueExp.extra = {
738
+ raw: `'${valStr}'`,
739
+ // 防止转码为unicode
740
+ rawValue: trimmedValue
741
+ };
742
+ return exports.option.useValueAsKey ? types.callExpression(types.identifier(exports.option.translateKey), [valueExp]) : types.callExpression(types.identifier(exports.option.translateKey), [types.stringLiteral(generatedKey), valueExp]);
743
+ } else {
744
+ return `${exports.option.translateKey}('${generatedKey}','${valStr}')`;
745
+ }
746
+ }
747
+ function normalizeTranslateValue(value) {
748
+ const trimmedValue = exports.option.isClearSpace ? value : value.trim();
749
+ const valStr = trimmedValue.replace(/'/g, '"').replace(/(\n)/g, '\\n');
750
+ return {
751
+ trimmedValue,
752
+ valStr
753
+ };
754
+ }
755
+
756
+ /**
757
+ * @description: 生成唯一id
758
+ * @param {string} key
759
+ * @return {*}
760
+ */
761
+ function generateId(key) {
762
+ let hash = 0;
763
+ for (let i = 0; i < key.length; i++) {
764
+ const charCode = key.charCodeAt(i);
765
+ hash = (hash << 5) - hash + charCode;
766
+ hash = hash & hash;
767
+ }
768
+ const id = Math.abs(hash).toString(36) + key.length.toString(36);
769
+ return id;
770
+ }
771
+
772
+ /**
773
+ * @description: unicode转普通字符串
774
+ * @param {string} str
775
+ * @return {*}
776
+ */
777
+ const unicodeToString = str => {
778
+ return str.replace(/\\u[\dA-Fa-f]{4}/g, match => {
779
+ return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
780
+ });
781
+ };
782
+
783
+ /**
784
+ * @description: 有道翻译 标识截取
785
+ * @param {string} q
786
+ * @return {*}
787
+ */
788
+ function truncate(q) {
789
+ // 检查输入字符串的长度
790
+ if (q.length <= 20) {
791
+ // 如果长度小于等于20,直接返回原字符串
792
+ return q;
793
+ } else {
794
+ // 如果长度大于20,截取前10个字符和后10个字符,并在中间插入长度信息
795
+ const len = q.length;
796
+ return q.substring(0, 10) + len + q.substring(len - 10);
797
+ }
798
+ }
799
+
800
+ // 导出一个深拷贝函数,用于克隆对象
801
+ function cloneDeep(value) {
802
+ let cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new WeakMap();
803
+ // 处理基本类型和 null
804
+ if (typeof value !== 'object' || value === null) {
805
+ return value;
806
+ }
807
+
808
+ // 处理循环引用
809
+ if (cache.has(value)) {
810
+ return cache.get(value);
811
+ }
812
+
813
+ // 处理特殊对象类型
814
+ if (value instanceof Date) {
815
+ return new Date(value);
816
+ }
817
+ if (value instanceof RegExp) {
818
+ return new RegExp(value.source, value.flags);
819
+ }
820
+
821
+ // 初始化克隆容器
822
+ const clone = Array.isArray(value) ? [] : {};
823
+
824
+ // 缓存对象防止循环引用
825
+ cache.set(value, clone);
826
+
827
+ // 处理 Symbol 和普通键的枚举
828
+ const keys = [...Object.keys(value), ...Object.getOwnPropertySymbols(value).filter(sym => value.propertyIsEnumerable(sym))];
829
+
830
+ // 递归克隆属性
831
+ for (const key of keys) {
832
+ clone[key] = cloneDeep(value[key], cache);
833
+ }
834
+ return clone;
835
+ }
836
+
837
+ var base = /*#__PURE__*/Object.freeze({
838
+ __proto__: null,
839
+ checkAgainstRegexArray: checkAgainstRegexArray,
840
+ cloneDeep: cloneDeep,
841
+ createI18nTranslator: createI18nTranslator,
842
+ extractCnStrings: extractCnStrings,
843
+ extractFunctionName: extractFunctionName,
844
+ extractStrings: extractStrings,
845
+ generateId: generateId,
846
+ getOriginRegex: getOriginRegex,
847
+ hasOriginSymbols: hasOriginSymbols,
848
+ normalizeTranslateValue: normalizeTranslateValue,
849
+ removeComments: removeComments,
850
+ truncate: truncate,
851
+ unicodeToString: unicodeToString
852
+ });
853
+
854
+ // 代码灵感来自https://github.com/dadidi9900/auto-plugins-json-translate/blob/main/src/services/translationService.ts
855
+ /**
856
+ * 火山引擎翻译器,内置豆包、deepseek等模型
857
+ *
858
+ * 火山引擎大模型介绍:https://www.volcengine.com/docs/82379/1099455
859
+ *
860
+ * api文档:https://www.volcengine.com/docs/82379/1298454
861
+ *
862
+ * 使用方式:
863
+ * ```ts
864
+ * vitePluginsAutoI18n({
865
+ ...
866
+ translator: new VolcengineTranslator({
867
+ apiKey: '你申请的apiKey',
868
+ model: '你要调用的模型,如:`doubao-1-5-pro-32k-250115`,请确保使用前已在控制台开通了对应模型'
869
+ })
870
+ })
871
+ * ```
872
+ */
873
+ class VolcengineTranslator extends Translator {
874
+ constructor(option) {
875
+ super({
876
+ name: '火山引擎ai翻译',
877
+ fetchMethod: async (text, fromKey, toKey, separator) => {
878
+ let salt = new Date().getTime();
879
+ const textArr = text.split(separator);
880
+ const sourceMap = Object.fromEntries(textArr.map(text => [generateId(text), text]));
881
+ const data = {
882
+ model: option.model,
883
+ messages: [{
884
+ role: 'system',
885
+ content: `
886
+ ###
887
+ 假如你是一个无情的翻译接口,你将根据一个文本组成的JSON对象,来解决将数组每个成员从源语言A翻译成目标语言B并返回翻译后的JSON对象的任务。需要注意的是,待翻译的文本均来自一个${option.desc ? option.desc + '的' : ''}web平台,遇到歧义时需要做好处理。根据以下规则一步步执行:
888
+ 1. 明确源语言A和目标语言B。
889
+ 2. 对JSON对象中数组的每个成员进行从源语言A到目标语言B的翻译。
890
+ 3. 将翻译后的内容以JSON对象格式返回,确保返回的内容可以被JSON.parse解析。
891
+
892
+ 参考例子:
893
+ 示例1:
894
+ 输入:zh-cn -> en { "awfgx": "你好", "qwfga": "世界" }
895
+ 输出:{ "awfgx": "Hello", "qwfga": "World" }
896
+
897
+ 示例2:
898
+ 输入:de -> fr { "gweaq": "Hallo", "wtrts": "Welt" }
899
+ 输出:{ "gweaq": "Bonjour", "wtrts": "Monde" }
900
+
901
+ 请回答问题:
902
+ 输入:源语言A -> 目标语言B { "wghhj": "XXX" }
903
+ 输出:
904
+
905
+ 要求:
906
+ 1 以JSON对象格式输出
907
+ 2 JSON对象中每个成员为翻译后的内容
908
+ ###
909
+ `
910
+ }, {
911
+ role: 'user',
912
+ content: `${fromKey} -> ${toKey} ${JSON.stringify(sourceMap)}`
913
+ }],
914
+ ...(option.insertOption || {})
915
+ };
916
+ const response = await axios.post(`https://ark.cn-beijing.volces.com/api/v3/chat/completions?t=${salt}`, data, {
917
+ headers: {
918
+ 'Content-Type': 'application/json',
919
+ Authorization: `Bearer ${option.apiKey}`
920
+ },
921
+ proxy: option.proxy
922
+ });
923
+ let resultTextArr = Array.from(textArr).fill('');
924
+ const content = response.data.choices[0].message.content;
925
+ try {
926
+ let resultMap;
927
+ try {
928
+ resultMap = JSON.parse(content);
929
+ } catch (error) {
930
+ throw new Error('大模型返回文本解析失败');
931
+ }
932
+ if (typeof resultMap !== 'object' || !resultMap) {
933
+ throw new Error('大模型返回文本解析后类型不正确');
934
+ }
935
+ const isMiss = Object.keys(resultMap).some(key => !(key in sourceMap));
936
+ if (isMiss) {
937
+ throw new Error('大模型返回文本内容不完整');
938
+ }
939
+ resultTextArr = textArr.map(text => resultMap[generateId(text)]); // 用textArr遍历,保证顺序
940
+ } catch (error) {
941
+ const message = error instanceof Error ? error.message : '未知错误';
942
+ console.warn('⚠', message);
943
+ console.warn('⚠ 返回的文本内容:', content);
944
+ console.warn('⚠ 原文本内容:', JSON.stringify(sourceMap));
945
+ }
946
+ return resultTextArr.join(separator);
947
+ },
948
+ onError: (error, cb) => {
949
+ cb(error);
950
+ console.error('请确保在火山引擎控制台开通了对应模型,且有足够的token余额。控制台地址:https://console.volcengine.com/ark/');
951
+ },
952
+ maxChunkSize: 1000,
953
+ // 太长可能会导致返回文本不完整
954
+ interval: option.interval ?? 1000
955
+ });
956
+ }
957
+ }
958
+
959
+ /*
960
+ * @Author: xiaoshanwen
961
+ * @Date: 2024-04-03 18:12:45
962
+ * @LastEditTime: 2024-04-03 18:33:53
963
+ * @FilePath: /i18n_translation_vite/autoI18nPluginCore/src/enums/translate.ts
964
+ */
965
+ let TranslateApiEnum = /*#__PURE__*/function (TranslateApiEnum) {
966
+ TranslateApiEnum["google"] = "Google";
967
+ TranslateApiEnum["youdao"] = "Youdao";
968
+ return TranslateApiEnum;
969
+ }({});
970
+
971
+ /*
972
+ * @Date: 2025-03-16 14:12:30
973
+ * @LastEditors: xiaoshan
974
+ * @LastEditTime: 2025-03-16 14:13:42
975
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/enums/option.ts
976
+ */
977
+ /**
978
+ * 翻译类型枚举
979
+ */
980
+ let TranslateTypeEnum = /*#__PURE__*/function (TranslateTypeEnum) {
981
+ TranslateTypeEnum["FULL_AUTO"] = "full-auto";
982
+ TranslateTypeEnum["SEMI_AUTO"] = "semi-auto";
983
+ return TranslateTypeEnum;
984
+ }({});
985
+
986
+ /*
987
+ * @Author: xiaoshanwen
988
+ * @Date: 2023-10-26 17:34:47
989
+ * @LastEditTime: 2025-03-31 19:58:37
990
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/option.ts
991
+ */
992
+
993
+ const EXCLUDED_CALL = ['$deepScan', 'console.info', 'console.warn', 'console.error', '$i8n', 'console.log', '$t', 'require', '$$i8n', '$$t', '_createCommentVNode'];
994
+ /**
995
+ * 默认插件配置选项
996
+ */
997
+ const DEFAULT_OPTION = {
998
+ appCode: '',
999
+ /** 是否启用插件,默认启用 */
1000
+ enabled: true,
1001
+ /** 翻译调用函数,默认为 $t */
1002
+ translateKey: '$t',
1003
+ /** 标记不翻译调用函数列表,避免某些调用被错误翻译 */
1004
+ excludedCall: [],
1005
+ /** 标记不用翻译的字符串模式数组,默认是匹配文件扩展名 */
1006
+ excludedPattern: [/\.\w+$/],
1007
+ /** 排查不需要翻译的目录下的文件路径(黑名单), 默认不处理node_modules */
1008
+ excludedPath: ['node_modules'],
1009
+ /** 指定需要翻译文件的目录路径正则(白名单) */
1010
+ includePath: [/src\//, /src\\/],
1011
+ /** 配置文件生成位置,默认为 './lang' */
1012
+ globalPath: './lang',
1013
+ /** 打包后生成文件的位置,例如 './dist/assets' */
1014
+ distPath: '',
1015
+ /** 打包后生成文件的主文件名称,默认是 'index' */
1016
+ distKey: 'index',
1017
+ /** 来源语言,默认是中文 */
1018
+ originLang: OriginLangKeyEnum.ZH,
1019
+ /** 翻译目标语言列表,默认包含英文 */
1020
+ targetLangList: ['en'],
1021
+ /** 语言key,用于请求谷歌api和生成配置文件下对应语言的内容文件 */
1022
+ langKey: [],
1023
+ /** 命名空间,防止全局命名冲突 */
1024
+ namespace: 'lang',
1025
+ /** 单位代码 */
1026
+ orgCode: 'GREENCLOUD',
1027
+ /** 是否启用源码的值作为key */
1028
+ useValueAsKey: false,
1029
+ /** 是否在构建结束之后将最新的翻译重新打包到主包中,默认不打包 */
1030
+ buildToDist: false,
1031
+ /** 是否启用上传翻译文件到服务器,默认关闭 */
1032
+ uploadEnabled: false,
1033
+ /** 翻译器,决定自动翻译使用的api与调用方式,默认使用 Google 翻译器并使用7890(clash)端口代理 */
1034
+ translator: new GoogleTranslator({
1035
+ proxyOption: {
1036
+ port: 7890,
1037
+ host: '127.0.0.1',
1038
+ headers: {
1039
+ 'User-Agent': 'Node'
1040
+ }
1041
+ }
1042
+ }),
1043
+ /** 翻译器配置选项,优先级低于translator */
1044
+ translatorOption: undefined,
1045
+ /**
1046
+ * 翻译类型,支持全自动和半自动两种模式
1047
+ * 全自动:所有翻译任务自动完成
1048
+ * 半自动:需要人工标识,类似于 $t('key') 的方式
1049
+ * 默认值为全自动
1050
+ */
1051
+ translateType: TranslateTypeEnum.FULL_AUTO,
1052
+ /**
1053
+ * 是否重写配置文件,默认为true
1054
+ */
1055
+ rewriteConfig: true,
1056
+ /**
1057
+ * 通用翻译key,默认使用namespace,如果commonTranslateKey不为空,则使用commonTranslateKey
1058
+ */
1059
+ commonTranslateKey: '',
1060
+ /**
1061
+ * 实验性属性,表示是否进行深层扫描字符串,默认为 false
1062
+ * 当设置为 true 时,会对代码中的字符串进行更深入的扫描
1063
+ */
1064
+ deepScan: false,
1065
+ /**
1066
+ * 自定义文件拓展名数组
1067
+ */
1068
+ insertFileExtensions: [],
1069
+ /**
1070
+ * 自定义拓展类,插件默认翻译函数挂载在window上,如果希望自定义翻译函数挂载在其他对象上,可以使用该属性
1071
+ * 注意:该属性需要继承BaseExtends类,并且需要实现handleInitFile和handleCodeCall和handleCodeString方法
1072
+ */
1073
+ translateExtends: null,
1074
+ isClear: false,
1075
+ // 是否清除已经不在上下文中的内容(清除项目中不再使用到的源语言键值对)
1076
+
1077
+ /**
1078
+ * 是否保留空格
1079
+ */
1080
+ isClearSpace: true
1081
+ };
1082
+
1083
+ /**
1084
+ * 类型定义:插件配置选项类型
1085
+ */
1086
+
1087
+ /**
1088
+ * 全局插件配置实例,复制自默认配置
1089
+ */
1090
+ exports.option = {
1091
+ ...DEFAULT_OPTION
1092
+ };
1093
+
1094
+ /**
1095
+ * 类型定义:用户传入的配置选项
1096
+ */
1097
+
1098
+ /**
1099
+ * 通过深度克隆提供的选项信息生成一个用户选项对象,
1100
+ * 确保原始配置不被修改。它还根据用户的配置初始化翻译器。
1101
+ * @param optionInfo - 包含用户选项和翻译器细节的选项信息。
1102
+ * @returns 一个新的、可能已初始化翻译器的用户选项对象。
1103
+ */
1104
+ function generateUserOption(optionInfo) {
1105
+ // 深拷贝用户传入的配置,防止修改原配置对象
1106
+ const userOption = cloneDeep(optionInfo);
1107
+ userOption.translator = optionInfo?.translator;
1108
+
1109
+ // 如果用户配置了translatorOption则初始化translator,如果都没有则不设置translator
1110
+ userOption.translator ||= userOption.translatorOption ? new Translator(userOption.translatorOption) : undefined;
1111
+ if (!userOption.translator) delete userOption.translator;
1112
+ return userOption;
1113
+ }
1114
+
1115
+ /**
1116
+ * 初始化插件配置选项
1117
+ * @param optionInfo 用户提供的配置选项
1118
+ */
1119
+ function initOption(optionInfo) {
1120
+ // 合并默认配置和用户配置
1121
+ exports.option = {
1122
+ ...DEFAULT_OPTION,
1123
+ ...generateUserOption(optionInfo)
1124
+ };
1125
+
1126
+ // 初始化语言key数组,包含来源语言和目标语言
1127
+ exports.option.langKey = [exports.option.originLang, ...exports.option.targetLangList];
1128
+ // 初始化排除调用函数列表,包含默认排除和调用函数主动排除
1129
+ exports.option.excludedCall = [...exports.option.excludedCall, ...EXCLUDED_CALL, ...[exports.option.translateKey, '$' + exports.option.translateKey]];
1130
+ return exports.option;
1131
+ }
1132
+
1133
+ /**
1134
+ * 校验插件配置选项是否完整有效
1135
+ * @returns {boolean} 校验结果,完整返回 true,否则返回 false
1136
+ */
1137
+ function checkOption() {
1138
+ // 校验翻译调用函数是否配置
1139
+ if (!exports.option.translateKey) {
1140
+ console.error('❌请配置翻译调用函数');
1141
+ return false;
1142
+ }
1143
+
1144
+ // 校验命名空间是否配置
1145
+ if (!exports.option.namespace) {
1146
+ console.error('❌请配置命名空间');
1147
+ return false;
1148
+ }
1149
+
1150
+ // 校验是否配置了打包后生成文件的主文件名称(如果需要打包到主包中)
1151
+ if (exports.option.buildToDist && !exports.option.distKey) {
1152
+ console.log('❌请配置打包后生成文件的主文件名称');
1153
+ return false;
1154
+ }
1155
+
1156
+ // 校验是否配置了打包后生成文件的位置(如果需要打包到主包中)
1157
+ if (exports.option.buildToDist && !exports.option.distPath) {
1158
+ console.log('❌请配置打包后生成文件的位置');
1159
+ return false;
1160
+ }
1161
+
1162
+ // 校验来源语言是否配置
1163
+ if (!exports.option.originLang) {
1164
+ console.error('❌请配置来源语言');
1165
+ return false;
1166
+ }
1167
+
1168
+ // 校验目标翻译语言数组是否配置
1169
+ if (!exports.option.targetLangList || !exports.option.targetLangList.length) {
1170
+ console.error('❌请配置目标翻译语言数组');
1171
+ return false;
1172
+ }
1173
+
1174
+ // 如果所有校验通过,返回 true
1175
+ return true;
1176
+ }
1177
+
1178
+ var allLanguage = [{
1179
+ code: 'zh-CN',
1180
+ name: '简体中文'
1181
+ }, {
1182
+ code: 'zh-TW',
1183
+ name: '繁体中文'
1184
+ }, {
1185
+ code: 'zh-UG',
1186
+ name: '维吾尔语'
1187
+ }, {
1188
+ code: 'en-US',
1189
+ name: '英文'
1190
+ }, {
1191
+ code: 'tr-TR',
1192
+ name: '土耳其语'
1193
+ }, {
1194
+ code: 'es-ES',
1195
+ name: '西班牙语'
1196
+ }, {
1197
+ code: 'ja-JP',
1198
+ name: '日语'
1199
+ }, {
1200
+ code: 'ru-RU',
1201
+ name: '俄语'
1202
+ }, {
1203
+ code: 'fr-FR',
1204
+ name: '法语'
1205
+ }, {
1206
+ code: 'de-DE',
1207
+ name: '德语'
1208
+ }, {
1209
+ code: 'pt-BR',
1210
+ name: '巴西葡萄牙语'
1211
+ }, {
1212
+ code: 'pt-PT',
1213
+ name: '葡萄牙语'
1214
+ }, {
1215
+ code: 'ko-KR',
1216
+ name: '韩语'
1217
+ }, {
1218
+ code: 'vi-VN',
1219
+ name: '越南语'
1220
+ }, {
1221
+ code: 'sv-SE',
1222
+ name: '瑞典语'
1223
+ }, {
1224
+ code: 'id-ID',
1225
+ name: '印尼语'
1226
+ }, {
1227
+ code: 'uk-UA',
1228
+ name: '乌克兰语'
1229
+ }, {
1230
+ code: 'it-IT',
1231
+ name: '意大利语'
1232
+ }, {
1233
+ code: 'th-TH',
1234
+ name: '泰语'
1235
+ }, {
1236
+ code: 'hi-IN',
1237
+ name: '印地语'
1238
+ }, {
1239
+ code: 'fa-IR',
1240
+ name: '波斯语'
1241
+ }, {
1242
+ code: 'ro-RO',
1243
+ name: '罗马尼亚语'
1244
+ }, {
1245
+ code: 'el-GR',
1246
+ name: '希腊语'
1247
+ }, {
1248
+ code: 'nl-NL',
1249
+ name: '荷兰语'
1250
+ }, {
1251
+ code: 'cs-CZ',
1252
+ name: '捷克语'
1253
+ }, {
1254
+ code: 'mn-MN',
1255
+ name: '蒙古语'
1256
+ }, {
1257
+ code: 'mn-TR',
1258
+ name: '传统蒙古语'
1259
+ }, {
1260
+ code: 'fi-FI',
1261
+ name: '芬兰语'
1262
+ }, {
1263
+ code: 'ar-SA',
1264
+ name: '阿拉伯语'
1265
+ }, {
1266
+ code: 'ar-EG',
1267
+ name: '阿拉伯语-埃及'
1268
+ }, {
1269
+ code: 'da-DK',
1270
+ name: '丹麦语'
1271
+ }, {
1272
+ code: 'pl-PL',
1273
+ name: '波兰语'
1274
+ }, {
1275
+ code: 'nb-NO',
1276
+ name: '挪威语'
1277
+ }, {
1278
+ code: 'si-LK',
1279
+ name: '僧伽罗语'
1280
+ }];
1281
+
1282
+ /**
1283
+ * JSON 格式化配置类型
1284
+ */
1285
+
1286
+ // 默认的缩进配置
1287
+ const indentConfig = {
1288
+ tab: {
1289
+ char: '\t',
1290
+ size: 1
1291
+ },
1292
+ space: {
1293
+ char: ' ',
1294
+ size: 4
1295
+ }
1296
+ };
1297
+
1298
+ // 默认格式化配置
1299
+ const configDefault = {
1300
+ type: 'tab'
1301
+ };
1302
+
1303
+ // 临时存储替换字符串的数组
1304
+ let placeholderStorage = [];
1305
+
1306
+ // 临时存储处理函数
1307
+ const pushPlaceholder = match => `\\${placeholderStorage.push(match)}\\`;
1308
+ const popPlaceholder = (_match, index) => placeholderStorage[+index - 1];
1309
+
1310
+ // 生成缩进字符
1311
+ const generateIndentation = (count, indentType) => {
1312
+ return new Array(count + 1).join(indentType);
1313
+ };
1314
+
1315
+ /**
1316
+ * 格式化 JSON 字符串
1317
+ * @param json JSON 字符串
1318
+ * @param indentType 缩进类型
1319
+ * @returns 格式化的 JSON 字符串
1320
+ */
1321
+ function formatJSON(json, indentType) {
1322
+ placeholderStorage = [];
1323
+ let output = '';
1324
+ let indentLevel = 0;
1325
+
1326
+ // 提取反斜杠和字符串
1327
+ json = json.replace(/\\./g, pushPlaceholder) // 处理反斜杠
1328
+ .replace(/(".*?"|'.*?')/g, pushPlaceholder) // 处理字符串
1329
+ .replace(/\s+/g, ''); // 去除多余空格
1330
+
1331
+ // 根据 JSON 内容添加换行和缩进
1332
+ for (let i = 0; i < json.length; i++) {
1333
+ const char = json.charAt(i);
1334
+ switch (char) {
1335
+ case '{':
1336
+ case '[':
1337
+ output += char + '\n' + generateIndentation(++indentLevel, indentType);
1338
+ break;
1339
+ case '}':
1340
+ case ']':
1341
+ output += '\n' + generateIndentation(--indentLevel, indentType) + char;
1342
+ break;
1343
+ case ',':
1344
+ output += ',\n' + generateIndentation(indentLevel, indentType);
1345
+ break;
1346
+ case ':':
1347
+ output += ': ';
1348
+ break;
1349
+ default:
1350
+ output += char;
1351
+ break;
1352
+ }
1353
+ }
1354
+
1355
+ // 去除数字数组的空格,并还原反斜杠和字符串
1356
+ output = output.replace(/\[[\d,\s]+?\]/g, match => match.replace(/\s/g, '')).replace(/\\(\d+)\\/g, popPlaceholder) // 还原填充数据
1357
+ .replace(/\\(\d+)\\/g, popPlaceholder); // 再次还原填充数据
1358
+
1359
+ return output;
1360
+ }
1361
+
1362
+ /**
1363
+ * 格式化 JSON 的主函数
1364
+ * @param json 需要格式化的 JSON 对象或字符串
1365
+ * @param config 配置选项
1366
+ * @returns 格式化后的 JSON 字符串
1367
+ */
1368
+ function jsonFormatter(json) {
1369
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : configDefault;
1370
+ // 确保输入是 JSON 字符串
1371
+ const jsonString = typeof json === 'string' ? json : JSON.stringify(json);
1372
+
1373
+ // 获取缩进配置
1374
+ const indent = indentConfig[config.type];
1375
+ if (!indent) {
1376
+ throw new Error(`Unrecognized indent type: "${config.type}"`);
1377
+ }
1378
+
1379
+ // 生成缩进字符
1380
+ const indentType = generateIndentation(config.size || indent.size, indent.char);
1381
+
1382
+ // 格式化 JSON 字符串
1383
+ return formatJSON(jsonString, indentType);
1384
+ }
1385
+
1386
+ /**
1387
+ * @description: 新建国际化配置文件夹
1388
+ * @return {*}
1389
+ */
1390
+ function initLangFile() {
1391
+ if (!fs.existsSync(exports.option.globalPath)) {
1392
+ fs.mkdirSync(exports.option.globalPath); // 创建lang文件夹
1393
+ }
1394
+ initLangTranslateJSONFile();
1395
+ initTranslateBasicFnFile();
1396
+ }
1397
+ /**
1398
+ * @description: 初始化翻译基础函数文件
1399
+ * @returns {void}
1400
+ */
1401
+ async function initTranslateBasicFnFile() {
1402
+ // 从配置选项中获取必要的配置信息
1403
+ const {
1404
+ targetLangList
1405
+ } = exports.option;
1406
+ // 生成语言映射列表
1407
+ let languages = [];
1408
+ let langList = targetLangList.map(item => {
1409
+ const parts = item.split('-');
1410
+ const lang = parts[0] + '-' + parts[1].toUpperCase();
1411
+ return _.find(allLanguage, {
1412
+ code: lang
1413
+ });
1414
+ });
1415
+ langList
1416
+ // 构建语言映射项
1417
+ .map(item => {
1418
+ languages.push(`{
1419
+ code: "${item.code}",
1420
+ name: "${item.name}"
1421
+ }`);
1422
+ });
1423
+ // 用逗号和换行符连接所有映射项
1424
+ const translateBasicFnText = `
1425
+ import gc_i18n from 'gc_i18n'
1426
+ export const languages = [${languages.toString()}]
1427
+ const gcI18nInstance = new gc_i18n({
1428
+ appCode: 'TEST',
1429
+ env: 'dev', // local 本地部署 dev 多语言测试环境 prod 多语言生产环境
1430
+ orgCode: 'GREENCLOUD',
1431
+ messages: {} // 如果你需要自己引入语言包
1432
+ })
1433
+ export default {
1434
+ install(app, router) {
1435
+ gcI18nInstance.setRouter(router)
1436
+ }
1437
+ }`;
1438
+ // 构建翻译基础函数文件的路径
1439
+ const indexPath = path.join(exports.option.globalPath, 'index.js');
1440
+
1441
+ // 文件已存在 同时 不重写配置,那么这里就结束
1442
+ if (fs.existsSync(indexPath) && !exports.option.rewriteConfig) return;
1443
+
1444
+ // 新增哈希比对逻辑
1445
+
1446
+ // 标记是否需要更新文件
1447
+ let needUpdate = true;
1448
+ if (fs.existsSync(indexPath)) {
1449
+ // 检查文件是否已存在
1450
+ // 读取现有文件内容
1451
+ const existingContent = fs.readFileSync(indexPath, 'utf-8');
1452
+ // 生成现有内容的哈希值
1453
+ const existingHash = generateId(existingContent);
1454
+ // 判断是否需要更新文件
1455
+ // needUpdate = currentHash !== existingHash
1456
+ needUpdate = !existingHash;
1457
+ }
1458
+
1459
+ // 如果需要更新文件,则写入新内容
1460
+ if (needUpdate) {
1461
+ fs.writeFileSync(indexPath, translateBasicFnText);
1462
+ }
1463
+ }
1464
+ /**
1465
+ * @description: 生成国际化JSON文件
1466
+ * @return {*}
1467
+ */
1468
+ function initLangTranslateJSONFile() {
1469
+ const indexPath = path.join(exports.option.globalPath, 'index.json');
1470
+ if (!fs.existsSync(indexPath)) {
1471
+ // 不存在就创建
1472
+ fs.writeFileSync(indexPath, JSON.stringify({})); // 创建
1473
+ }
1474
+ }
1475
+
1476
+ /**
1477
+ * @description: 读取国际化JSON文件
1478
+ * @return {*}
1479
+ */
1480
+ function getLangTranslateJSONFile() {
1481
+ const filePath = path.join(exports.option.globalPath, 'index.json');
1482
+ try {
1483
+ const content = fs.readFileSync(filePath, 'utf-8');
1484
+ return content;
1485
+ } catch (error) {
1486
+ if (error.code === 'ENOENT') {
1487
+ console.log('❌读取JSON配置文件异常,文件不存在');
1488
+ } else {
1489
+ console.log('❌读取JSON配置文件异常,无法读取文件');
1490
+ }
1491
+ return JSON.stringify({});
1492
+ }
1493
+ }
1494
+
1495
+ /**
1496
+ * @description: 基于langKey获取JSON配置文件中对应语言对象
1497
+ * @param {string} key
1498
+ * @return {*}
1499
+ */
1500
+ function getLangObjByJSONFileWithLangKey(key) {
1501
+ let insertJSONObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
1502
+ // 获取翻译配置对象,优先使用传入的配置,否则从本地文件读取
1503
+ const JSONObj = insertJSONObj || JSON.parse(getLangTranslateJSONFile());
1504
+
1505
+ // 初始化语言映射对象,用于存储不同语言的hash: value映射
1506
+ const langObj = {};
1507
+
1508
+ // 遍历hash,提取hash对应语言key的值,并写入到langObj
1509
+ Object.keys(JSONObj).forEach(langCode => {
1510
+ langObj[langCode] = JSONObj[langCode][key];
1511
+ });
1512
+
1513
+ // 返回当前语言的hash: value映射对象
1514
+ // 例如: 'zh-cn' > {'hash1': '你好', 'hash2': '世界'}
1515
+ // 'en' > {'hash1': 'hello', 'hash2': 'world'}
1516
+ return langObj;
1517
+ }
1518
+
1519
+ /**
1520
+ * @description: 设置国际化JSON文件
1521
+ * @return {*}
1522
+ */
1523
+ function setLangTranslateJSONFile(obj) {
1524
+ const filePath = path.join(exports.option.globalPath, 'index.json');
1525
+ const jsonObj = jsonFormatter(obj);
1526
+ if (fs.existsSync(filePath)) {
1527
+ fs.writeFileSync(filePath, jsonObj);
1528
+ } else {
1529
+ console.log('❌JSON配置文件写入异常,文件不存在');
1530
+ }
1531
+ }
1532
+
1533
+ /**
1534
+ * @description: 构建时把lang配置文件设置到打包后到主文件中
1535
+ * @return {*}
1536
+ */
1537
+ function uploadFile() {
1538
+ const JSONObj = JSON.parse(getLangTranslateJSONFile());
1539
+ upload(JSONObj);
1540
+ // if (!option.buildToDist) return
1541
+ // let langObjMap: any = {}
1542
+ // option.langKey.forEach(item => {
1543
+ // langObjMap[item] = getLangObjByJSONFileWithLangKey(item)
1544
+ // })
1545
+ // if (fs.existsSync(option.distPath)) {
1546
+ // fs.readdir(option.distPath, (err, files) => {
1547
+ // if (err) {
1548
+ // console.error('❌构建文件夹为空,翻译配置无法写入')
1549
+ // return
1550
+ // }
1551
+
1552
+ // files.forEach(file => {
1553
+ // if (file.startsWith(option.distKey) && file.endsWith('.js')) {
1554
+ // const filePath = path.join(option.distPath, file)
1555
+ // fs.readFile(filePath, 'utf-8', (err, data) => {
1556
+ // if (err) {
1557
+ // console.log(filePath)
1558
+ // console.error('❌构建主文件不存在,翻译配置无法写入')
1559
+ // return
1560
+ // }
1561
+ // let buildLangConfigString = ''
1562
+ // Object.keys(langObjMap).forEach(item => {
1563
+ // buildLangConfigString =
1564
+ // buildLangConfigString +
1565
+ // `globalThis['${option.namespace}']['${item}']=${JSON.stringify(langObjMap[item])};`
1566
+ // })
1567
+ // try {
1568
+ // // 翻译配置写入主文件
1569
+ // fs.writeFileSync(
1570
+ // filePath,
1571
+ // `globalThis['${option.namespace}']={};${buildLangConfigString}` +
1572
+ // data
1573
+ // )
1574
+ // console.info('恭喜:翻译配置写入构建主文件成功🌟🌟🌟')
1575
+ // } catch (err) {
1576
+ // console.error('翻译配置写入构建主文件失败:', err)
1577
+ // }
1578
+ // })
1579
+ // }
1580
+ // })
1581
+ // })
1582
+ // }
1583
+ }
1584
+
1585
+ var file = /*#__PURE__*/Object.freeze({
1586
+ __proto__: null,
1587
+ getLangObjByJSONFileWithLangKey: getLangObjByJSONFileWithLangKey,
1588
+ getLangTranslateJSONFile: getLangTranslateJSONFile,
1589
+ initLangFile: initLangFile,
1590
+ initLangTranslateJSONFile: initLangTranslateJSONFile,
1591
+ initTranslateBasicFnFile: initTranslateBasicFnFile,
1592
+ setLangTranslateJSONFile: setLangTranslateJSONFile,
1593
+ uploadFile: uploadFile
1594
+ });
1595
+
1596
+ /*
1597
+ * @Author: xiaoshanwen
1598
+ * @Date: 2023-10-30 18:23:03
1599
+ * @LastEditTime: 2025-03-16 19:12:54
1600
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/translate.ts
1601
+ */
1602
+
1603
+ const SEPARATOR = '\n┇┇┇\n';
1604
+ const SPLIT_SEPARATOR_REGEX = /\n┇ *┇ *┇\n/;
1605
+ let langObj = {};
1606
+
1607
+ /**
1608
+ * @description: 设置翻译对象属性
1609
+ * @param {string} key
1610
+ * @param {string} value
1611
+ * @return {*}
1612
+ */
1613
+ function setLangObj(key, value) {
1614
+ if (!langObj[key]) {
1615
+ langObj[key] = value;
1616
+ }
1617
+ }
1618
+
1619
+ /**
1620
+ * @description: 读取翻译对象
1621
+ * @return {*}
1622
+ */
1623
+ function getLangObj() {
1624
+ return langObj;
1625
+ }
1626
+
1627
+ /**
1628
+ * @description: 初始化翻译对象
1629
+ * @param {langObj} obj
1630
+ * @return {*}
1631
+ */
1632
+ function initLangObj(obj) {
1633
+ if (!Object.keys(langObj)) {
1634
+ langObj = obj;
1635
+ }
1636
+ }
1637
+
1638
+ // todo 类型修复
1639
+ /**
1640
+ * 自动生成多语言配置文件的核心方法
1641
+ *
1642
+ * 主要流程:
1643
+ * 1. 加载现有翻译文件
1644
+ * 2. 对比找出新增需要翻译的内容
1645
+ * 3. 分块并行翻译所有目标语言
1646
+ * 4. 合并翻译结果并生成最终配置文件
1647
+ *
1648
+ * 异常处理:
1649
+ * - 翻译结果不完整时中断流程
1650
+ * - 文件读写失败时明确报错
1651
+ */
1652
+ async function autoTranslate() {
1653
+ const enabled = typeof exports.option.enabled === 'function' ? exports.option.enabled() : exports.option.enabled;
1654
+ if (!enabled) return;
1655
+
1656
+ // 初始化现有翻译文件缓存
1657
+ const originLangObjMap = {};
1658
+
1659
+ // 加载所有语言的现有翻译内容
1660
+ // 获取当前待翻译内容(深拷贝避免污染原始数据)
1661
+ const currentLangObj = JSON.parse(JSON.stringify(getLangObj()));
1662
+ exports.option.langKey.forEach(lang => {
1663
+ const keyMap = getLangObjByJSONFileWithLangKey(lang);
1664
+ originLangObjMap[lang] = keyMap;
1665
+ });
1666
+
1667
+ // 筛选需要翻译的新增内容
1668
+ const transLangObj = {};
1669
+ Object.keys(currentLangObj).forEach(key => {
1670
+ if (!originLangObjMap[exports.option.originLang][key]) {
1671
+ transLangObj[key] = currentLangObj[key];
1672
+ }
1673
+ });
1674
+
1675
+ // 无新内容提前退出
1676
+ if (Object.keys(transLangObj).length === 0) {
1677
+ console.info('✅ 当前没有需要翻译的新内容');
1678
+ return;
1679
+ }
1680
+
1681
+ // 初始化翻译结果存储结构
1682
+ const newLangObjMap = {};
1683
+
1684
+ // 遍历所有目标语言进行处理
1685
+ for (let langIndex = 0; langIndex < exports.option.langKey.length; langIndex++) {
1686
+ const currentLang = exports.option.langKey[langIndex];
1687
+
1688
+ // 原始语言直接存储原文,读取扫出来的元素翻译内容
1689
+ if (langIndex === 0) {
1690
+ newLangObjMap[exports.option.originLang] = Object.values(transLangObj);
1691
+ continue;
1692
+ }
1693
+ console.info('开始自动翻译...');
1694
+
1695
+ // ─── 分块翻译流程开始 ───
1696
+ const translatedValues = await translateChunks(transLangObj, exports.option.langKey[langIndex]);
1697
+ // ─── 分块翻译流程结束 ───=
1698
+
1699
+ // ─── 翻译结果校验 ───
1700
+ if (translatedValues.length !== Object.keys(transLangObj).length) {
1701
+ console.error('❌ 使用付费翻译时,请检查翻译API额度是否充足,或是否已申请对应翻译API使用权限');
1702
+ console.error(`❌ 翻译结果不完整
1703
+ 预期数量: ${Object.keys(transLangObj).length}
1704
+ 实际数量: ${translatedValues.length}
1705
+ 样例数据: ${JSON.stringify(translatedValues.slice(0, 3))}`);
1706
+ return;
1707
+ }
1708
+
1709
+ // 存储当前语言翻译结果
1710
+ newLangObjMap[currentLang] = translatedValues;
1711
+ console.info(`✅ ${currentLang} 翻译完成`);
1712
+ }
1713
+
1714
+ // ─── 合并翻译结果到配置 ───
1715
+ Object.keys(transLangObj).forEach((key, index) => {
1716
+ exports.option.langKey.forEach(item => {
1717
+ originLangObjMap[item][key] = newLangObjMap[item][index];
1718
+ });
1719
+ });
1720
+
1721
+ // ─── 生成最终配置文件结构 ───
1722
+ console.log('📄 构建配置文件数据结构...');
1723
+ const configLangObj = {};
1724
+ Object.keys(originLangObjMap[exports.option.originLang]).forEach(key => {
1725
+ configLangObj[key] = {};
1726
+ exports.option.langKey.forEach(lang => {
1727
+ configLangObj[key][lang] = originLangObjMap[lang][key];
1728
+ });
1729
+ });
1730
+
1731
+ // ─── 写入文件系统 ───
1732
+ try {
1733
+ setLangTranslateJSONFile(configLangObj);
1734
+ console.info('🎉 多语言配置文件已成功更新');
1735
+ } catch (error) {
1736
+ console.error('❌ 配置文件写入失败,原因:', error);
1737
+ // todo 可添加重试逻辑或回滚机制
1738
+ }
1739
+ }
1740
+
1741
+ /**
1742
+ * @description: 新增语言类型配置补全
1743
+ * @param {any} obj
1744
+ * @return {*}
1745
+ */
1746
+ function languageConfigCompletion(obj) {
1747
+ if (!Object.keys(obj)) return;
1748
+ const enabled = typeof exports.option.enabled === 'function' ? exports.option.enabled() : exports.option.enabled;
1749
+ if (!enabled) return;
1750
+ let needCompletionList = [];
1751
+ const JSONobj = JSON.parse(getLangTranslateJSONFile());
1752
+ exports.option.targetLangList.forEach(item => {
1753
+ // 获取目标语言 hash:value 对象 和 语言的复合对象,如果当前语言不存在,是langObj的value卡都为空
1754
+ let langObj = getLangObjByJSONFileWithLangKey(item, JSONobj);
1755
+ needCompletionList.push({
1756
+ key: item,
1757
+ curLangObj: langObj
1758
+ });
1759
+ });
1760
+ needCompletionList.forEach(async item => {
1761
+ await completionTranslateAndWriteConfigFile(obj, item.curLangObj, item.key);
1762
+ });
1763
+ }
1764
+
1765
+ /**
1766
+ * @description: 补全新增语言翻译写入函数
1767
+ * @param langObj
1768
+ * @param curLangObj
1769
+ * @param translateKey
1770
+ * @return
1771
+ */
1772
+ async function completionTranslateAndWriteConfigFile(langObj, curLangObj, translateKey) {
1773
+ // 构建需要翻译的语言映射对象
1774
+ // langObj: 源语言的键值对映射,格式为 { hash: sourceText }
1775
+ // curLangObj: 目标语言的键值对映射,格式为 { hash: targetText },未翻译的值为空
1776
+
1777
+ // 创建待翻译内容对象,仅包含未翻译的条目,key是hash,value是源语言的对应hash的文本
1778
+ const transLangObj = {};
1779
+ Object.keys(langObj).forEach(key => {
1780
+ // 如果目标语言中对应的翻译为空,则将 源语言的对应hash的文本 加入待翻译内容对象 中
1781
+ if (curLangObj[key] === undefined) {
1782
+ transLangObj[key] = langObj[key];
1783
+ }
1784
+ });
1785
+ if (!Object.values(transLangObj).length) return;
1786
+
1787
+ // ─── 分块翻译流程开始 ───
1788
+
1789
+ console.info('进入新增语言补全翻译...');
1790
+
1791
+ // 调用抽离的函数
1792
+ const resultValues = await translateChunks(transLangObj, translateKey);
1793
+ // ─── 分块翻译流程结束 ───
1794
+
1795
+ if (resultValues.length !== Object.values(langObj).length) {
1796
+ console.error('翻译异常,翻译结果缺失❌');
1797
+ return;
1798
+ }
1799
+ let newLangObjMap = resultValues;
1800
+ console.info('翻译成功⭐️⭐️⭐️');
1801
+ Object.keys(transLangObj).forEach((key, index) => {
1802
+ curLangObj[key] = newLangObjMap[index];
1803
+ });
1804
+ console.log('开始写入JSON配置文件...');
1805
+ const configLangObj = JSON.parse(getLangTranslateJSONFile());
1806
+ Object.keys(transLangObj).forEach(key => {
1807
+ configLangObj[key][translateKey] = curLangObj[key];
1808
+ });
1809
+ try {
1810
+ setLangTranslateJSONFile(configLangObj);
1811
+ console.info('JSON配置文件写入成功⭐️⭐️⭐️');
1812
+ } catch (error) {
1813
+ console.error('❌JSON配置文件写入失败' + error);
1814
+ }
1815
+ console.info('新增语言翻译补全成功⭐️⭐️⭐️');
1816
+ }
1817
+
1818
+ // 分块翻译流程函数
1819
+ async function translateChunks(transLangObj, translateKey) {
1820
+ const {
1821
+ translator
1822
+ } = exports.option;
1823
+ // 获取分块后的文本列表
1824
+ const translationChunks = createTextSplitter(Object.values(transLangObj), translator.option.maxChunkSize);
1825
+ // 并行执行分块翻译
1826
+ const translatePromises = [];
1827
+ for (let i = 0; i < translationChunks.length; i++) {
1828
+ translatePromises.push(translator.translate(translationChunks[i], exports.option.originLang, translateKey, SEPARATOR));
1829
+ }
1830
+
1831
+ // 等待所有分块完成并合并结果
1832
+ const chunkResults = await Promise.all(translatePromises);
1833
+ return chunkResults.map(item => {
1834
+ // 提取分割逻辑到单独的函数中,提高代码复用性
1835
+ const splitTranslation = (text, separatorRegex) => {
1836
+ return text.split(separatorRegex).map(v => v.trim());
1837
+ };
1838
+
1839
+ // 分割符可能会被翻译,所以这里做了兼容处理
1840
+ if (SPLIT_SEPARATOR_REGEX.test(item)) {
1841
+ return splitTranslation(item, SPLIT_SEPARATOR_REGEX);
1842
+ } else {
1843
+ const lines = item.split('\n');
1844
+ const separator = lines.find(line => line.length === 3);
1845
+ let value = [];
1846
+ if (separator) {
1847
+ value = splitTranslation(item, new RegExp(`\\n${separator}\\n`));
1848
+ }
1849
+ const realList = value.filter(Boolean);
1850
+ if (realList.length > 1) {
1851
+ return realList;
1852
+ }
1853
+ return splitTranslation(item, SPLIT_SEPARATOR_REGEX);
1854
+ }
1855
+ }).flat();
1856
+ }
1857
+ /**
1858
+ * @description: 清理多余的翻译配置JSON文件
1859
+ * @return {void} 无返回值
1860
+ */
1861
+ function cleanupUnusedTranslations() {
1862
+ if (!exports.option.isClear) return;
1863
+ console.log('🧹 进入清理流程');
1864
+ // 获取当前的语言对象,如果不存在则使用空对象
1865
+ const langObj = getLangObj() || {};
1866
+
1867
+ // 创建一个Set用于存储当前语言对象的所有key,便于快速查找
1868
+ let langSet = new Set(Object.keys(langObj));
1869
+
1870
+ // 获取基础对象:优先使用传入的insertObj,否则从翻译文件中读取
1871
+ const baseObj = JSON.parse(getLangTranslateJSONFile());
1872
+
1873
+ // 获取基础对象的所有key
1874
+ const baseObjKeys = Object.keys(baseObj);
1875
+ // 遍历所有key,删除在当前语言对象中不存在的配置
1876
+ baseObjKeys.forEach(key => {
1877
+ if (!langSet.has(key)) {
1878
+ baseObj[key] && delete baseObj[key];
1879
+ }
1880
+ });
1881
+ setLangTranslateJSONFile(baseObj);
1882
+ }
1883
+
1884
+ var translate = /*#__PURE__*/Object.freeze({
1885
+ __proto__: null,
1886
+ SEPARATOR: SEPARATOR,
1887
+ SPLIT_SEPARATOR_REGEX: SPLIT_SEPARATOR_REGEX,
1888
+ autoTranslate: autoTranslate,
1889
+ cleanupUnusedTranslations: cleanupUnusedTranslations,
1890
+ completionTranslateAndWriteConfigFile: completionTranslateAndWriteConfigFile,
1891
+ getLangObj: getLangObj,
1892
+ initLangObj: initLangObj,
1893
+ get langObj () { return langObj; },
1894
+ languageConfigCompletion: languageConfigCompletion,
1895
+ setLangObj: setLangObj
1896
+ });
1897
+
1898
+ /*
1899
+ * @Date: 2025-02-17 17:11:26
1900
+ * @LastEditors: xiaoshan
1901
+ * @LastEditTime: 2025-02-17 18:00:37
1902
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/chunk.ts
1903
+ */
1904
+
1905
+ /**
1906
+ * 智能文本分块处理器
1907
+ * @param values 待分块的原始文本数组
1908
+ * @param maxChunkSize 最大分块长度
1909
+ * @returns 包含分块文本和重组方法的对象
1910
+ *
1911
+ * 功能特性:
1912
+ * 1. 自动合并小文本为最大可能块
1913
+ * 2. 处理超长文本并给出警告
1914
+ * 3. 保证块长度不超过限制
1915
+ * 4. 保留原始顺序和分隔符语义
1916
+ */
1917
+ function createTextSplitter(values, maxChunkSize) {
1918
+ // 分隔符定义(用于合并/拆分时保持语义)
1919
+ const SEP_LENGTH = SEPARATOR.length;
1920
+
1921
+ // 结果存储和缓冲区
1922
+ const result = []; // 最终分块结果
1923
+ let buffer = []; // 当前累积块缓冲区
1924
+ let currentSize = 0; // 当前缓冲区字符数(含分隔符)
1925
+
1926
+ /**
1927
+ * 提交缓冲区内容到结果集
1928
+ * - 将缓冲区内容用分隔符连接
1929
+ * - 重置缓冲区和计数器
1930
+ */
1931
+ const commitBuffer = () => {
1932
+ if (buffer.length > 0) {
1933
+ // 计算实际连接长度用于验证
1934
+ const actualLength = buffer.join(SEPARATOR).length;
1935
+ if (actualLength > maxChunkSize) {
1936
+ console.warn(`缓冲区提交异常:生成块长度 ${actualLength} 超过限制`);
1937
+ }
1938
+ result.push(buffer.join(SEPARATOR));
1939
+ buffer = [];
1940
+ currentSize = 0;
1941
+ }
1942
+ };
1943
+
1944
+ // 主处理循环:遍历所有原始文本项
1945
+ for (const value of values) {
1946
+ // 计算需要新增的空间:文本长度 + 分隔符(非首项)
1947
+ const neededSpace = value.length + (buffer.length > 0 ? SEP_LENGTH : 0);
1948
+
1949
+ // ─── 超长文本处理策略 ───
1950
+ if (value.length > maxChunkSize) {
1951
+ // 优先提交现有缓冲区内容
1952
+ if (buffer.length > 0) commitBuffer();
1953
+
1954
+ /**
1955
+ * 超长文本处理逻辑:
1956
+ * - 长度超过1.5倍限制时发出强警告
1957
+ * - 强制单独成块(即使超过限制)
1958
+ * - 后续需要特殊处理这些异常块
1959
+ */
1960
+ if (value.length > maxChunkSize * 1.5) {
1961
+ console.warn(`超长文本告警:检测到长度 ${value.length} 字符的文本项,可能影响翻译质量`);
1962
+ }
1963
+ // 结果直接新增一个超长文本
1964
+ result.push(value);
1965
+ continue;
1966
+ }
1967
+
1968
+ // ─── 正常分块逻辑 ───
1969
+ // 空间不足时提交当前缓冲区
1970
+ if (currentSize + neededSpace > maxChunkSize) {
1971
+ commitBuffer();
1972
+ }
1973
+
1974
+ // 更新缓冲区状态(累加长度需包含分隔符)
1975
+ currentSize += neededSpace;
1976
+ buffer.push(value);
1977
+ }
1978
+
1979
+ // 提交最终未完成的缓冲区内容
1980
+ commitBuffer();
1981
+
1982
+ // 返回分块结果
1983
+ return result;
1984
+ }
1985
+
1986
+ /*
1987
+ * @Date: 2025-03-26 20:28:21
1988
+ * @LastEditors: xiaoshan
1989
+ * @LastEditTime: 2025-03-31 10:29:49
1990
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/utils/split.ts
1991
+ */
1992
+ // 插件核心文件
1993
+ // 字符串切割与转换函数
1994
+ // import generate from '@babel/generator'
1995
+
1996
+ // todo 这个切割函数可以优化,性能可能很差
1997
+ /**
1998
+ * 根据正则表达式分割字符串,并将符合正则的连续字符拼接起来。
1999
+ * @param str - 要分割的字符串。
2000
+ * @param separatorRegex - 用于分割字符串的正则表达式。
2001
+ * @returns 分割并拼接后的字符串数组。
2002
+ */
2003
+ /**
2004
+ * 这个函数的主要功能是根据给定的正则表达式分割字符串,并对分割结果进行特殊处理。
2005
+ * 处理过程分为三个主要步骤:
2006
+ *
2007
+ * 1. 首先根据分隔符正则和标点符号正则进行初步分割
2008
+ * 2. 然后将连续的标点符号和符合分隔符正则的部分重新连接
2009
+ * 3. 最后将不符合分隔符正则的相邻部分合并
2010
+ *
2011
+ * @param str - 需要分割的源字符串
2012
+ * @param separatorRegex - 用于分割的正则表达式
2013
+ * @returns 处理后的字符串数组
2014
+ */
2015
+ function splitByRegex(str, separatorRegex) {
2016
+ if (str.includes('\n')) console.log(str, separatorRegex);
2017
+
2018
+ // 定义标点符号的正则表达式
2019
+ const punctuationRegex = /[,。?!《》,..:!?""'';'"、0-9\n\r\t\v\f]/;
2020
+ // 创建一个新的正则表达式,用于分割字符串
2021
+ const splitRegex = new RegExp(`(${separatorRegex.source}|${punctuationRegex.source})`, separatorRegex.flags);
2022
+
2023
+ // 使用正则表达式分割字符串,并过滤掉空字符串
2024
+ const splitArr = str.split(splitRegex).filter(Boolean);
2025
+ const result = [];
2026
+ let currentMatch = '';
2027
+
2028
+ // 定义连接标点符号的正则表达式
2029
+ const connectPunctuationRegex = /[,。?!《》,..:!?;'"、0-9]/;
2030
+ // 创建一个新的正则表达式,用于检测是否需要连接
2031
+ const connectRegex = new RegExp(`(${separatorRegex.source}|${connectPunctuationRegex.source})`, separatorRegex.flags);
2032
+
2033
+ // 遍历分割后的数组
2034
+ for (const item of splitArr) {
2035
+ if (connectRegex.test(item)) {
2036
+ // 如果当前项符合连接条件,则将其添加到当前匹配字符串中
2037
+ currentMatch += item;
2038
+ } else {
2039
+ // 如果当前匹配字符串不为空,则将其添加到结果数组中
2040
+ if (currentMatch) {
2041
+ result.push(currentMatch);
2042
+ currentMatch = '';
2043
+ }
2044
+ // 将当前项添加到结果数组中
2045
+ result.push(item);
2046
+ }
2047
+ }
2048
+
2049
+ // 如果最后一个匹配字符串不为空,则将其添加到结果数组中
2050
+ if (currentMatch) {
2051
+ result.push(currentMatch);
2052
+ }
2053
+
2054
+ // 再遍历一次,把不符合separatorRegex 这个正则的拼起来
2055
+ const finalResult = [];
2056
+ let tempStr = '';
2057
+ for (let i = 0; i < result.length; i++) {
2058
+ const item = result[i];
2059
+ if (separatorRegex.test(item)) {
2060
+ if (tempStr) {
2061
+ finalResult.push(tempStr);
2062
+ tempStr = '';
2063
+ }
2064
+ finalResult.push(item);
2065
+ } else {
2066
+ tempStr += item;
2067
+ if (i === result.length - 1 || separatorRegex.test(result[i + 1])) {
2068
+ finalResult.push(tempStr);
2069
+ tempStr = '';
2070
+ }
2071
+ }
2072
+ }
2073
+ if (tempStr) {
2074
+ finalResult.push(tempStr);
2075
+ }
2076
+ return finalResult;
2077
+ }
2078
+
2079
+ /**
2080
+ * 检查字符串是否需要切割。
2081
+ * @param str - 要检查的字符串。
2082
+ * @returns 如果字符串需要切割,则返回 true,否则返回 false。
2083
+ */
2084
+ function checkNeedSplit(str) {
2085
+ // 检查字符串中是否包含需要切割的特殊字符
2086
+ return str.includes('\n') || str.includes('\\') || str.includes('\r') || str.includes('\t') || str.includes('\v') || str.includes('\f') || str.includes('>') || str.includes('<');
2087
+ }
2088
+
2089
+ /**
2090
+ * @description: 将字符串数组转换为babel的模板字符串节点
2091
+ * @param {string[]} strArray - 字符串数组
2092
+ * @return {types.CallExpression} - babel的深度扫描的表达式
2093
+ */
2094
+ function convertToTemplateLiteral(strArray, option) {
2095
+ const quasis = [];
2096
+ const expressions = [];
2097
+ strArray.forEach((str, index) => {
2098
+ if (index === 0) {
2099
+ if (getOriginRegex().test(str)) {
2100
+ quasis.push(types__namespace.templateElement({
2101
+ raw: '',
2102
+ cooked: ''
2103
+ }, false));
2104
+ expressions.push(createI18nTranslator({
2105
+ value: str,
2106
+ isExpression: true,
2107
+ insertOption: option
2108
+ }));
2109
+ } else {
2110
+ quasis.push(types__namespace.templateElement({
2111
+ raw: str,
2112
+ cooked: str
2113
+ }, false));
2114
+ }
2115
+ } else {
2116
+ if (getOriginRegex().test(str)) {
2117
+ expressions.push(createI18nTranslator({
2118
+ value: str,
2119
+ isExpression: true,
2120
+ insertOption: option
2121
+ }));
2122
+ } else {
2123
+ quasis.push(types__namespace.templateElement({
2124
+ raw: str,
2125
+ cooked: str
2126
+ }, false));
2127
+ }
2128
+ }
2129
+ });
2130
+ if (quasis.length === expressions.length) {
2131
+ quasis.push(types__namespace.templateElement({
2132
+ raw: '',
2133
+ cooked: ''
2134
+ }, true));
2135
+ } else if (quasis.length > expressions.length) {
2136
+ quasis[quasis.length - 1].tail = true;
2137
+ }
2138
+ const templateLiteral = types__namespace.templateLiteral(quasis, expressions);
2139
+ const deepScanCall = types__namespace.callExpression(types__namespace.identifier('$deepScan'), [templateLiteral]);
2140
+ // 打印转换结果
2141
+ // console.log('deepScanCall', (generate as any).default(deepScanCall).code)
2142
+ return deepScanCall;
2143
+ }
2144
+
2145
+ // 上传到远程服务器
2146
+ // import { getAppCode, saveConfig, convertToUploadJson } from './config.js'
2147
+ async function upload(json) {
2148
+ const {
2149
+ appCode,
2150
+ targetLangList
2151
+ } = exports.option;
2152
+ let data = [];
2153
+ _.map(json, (value, key) => {
2154
+ _.map(targetLangList, item => {
2155
+ const parts = item.split('-');
2156
+ const lang = parts[0] + '-' + parts[1].toUpperCase();
2157
+ data.push({
2158
+ page: 'common',
2159
+ key,
2160
+ lang,
2161
+ value: _.get(value, item, key)
2162
+ });
2163
+ });
2164
+ });
2165
+ const res = await axios.post('http://192.168.0.104:8108/i18n-web/kv_translate/batch', {
2166
+ appCode,
2167
+ data
2168
+ }, {
2169
+ headers: {
2170
+ 'Content-Type': 'application/json'
2171
+ }
2172
+ });
2173
+ if (res.status === 200 && res.data.result === 0) {
2174
+ console.info('上传翻译服务成功✔');
2175
+ } else {
2176
+ console.error('上传翻译服务失败❌');
2177
+ console.log(`请求数据为:`, JSON.stringify(data));
2178
+ console.log(`返回报错信息为:`, res.data);
2179
+ }
2180
+ }
2181
+
2182
+ var upload$1 = /*#__PURE__*/Object.freeze({
2183
+ __proto__: null,
2184
+ upload: upload
2185
+ });
2186
+
2187
+ class Vue2Extends {
2188
+ constructor() {
2189
+ this.handleInitFile = async (source, path) => {
2190
+ let code = source;
2191
+
2192
+ // 检查是否已经引入了 Vue
2193
+ let importVue = false;
2194
+ let hasVue = false;
2195
+ let importDefaultChar = 'Vue';
2196
+ const result = await babel.transformAsync(code, {
2197
+ configFile: false,
2198
+ plugins: [{
2199
+ visitor: {
2200
+ ImportDeclaration(path) {
2201
+ const {
2202
+ node
2203
+ } = path;
2204
+ if (node.source.value === 'vue') {
2205
+ importVue = true;
2206
+ const specifiers = node.specifiers;
2207
+ specifiers.forEach(specifier => {
2208
+ if (types.isImportDefaultSpecifier(specifier)) {
2209
+ hasVue = true;
2210
+ importDefaultChar = specifier.local.name;
2211
+ }
2212
+ });
2213
+ if (!hasVue) {
2214
+ hasVue = true;
2215
+ specifiers.unshift(types.importDefaultSpecifier(types.identifier('Vue')));
2216
+ }
2217
+ }
2218
+ }
2219
+ }
2220
+ }]
2221
+ });
2222
+ if (importVue && result) code = result.code;
2223
+ if (!importVue) code = `import Vue from 'vue'
2224
+ ${code}`;
2225
+ return {
2226
+ path,
2227
+ importDefaultChar,
2228
+ source: code
2229
+ };
2230
+ };
2231
+ this.handleCodeCall = (config, _initFileResult) => {
2232
+ const {
2233
+ option,
2234
+ hash,
2235
+ value,
2236
+ uncodeValue,
2237
+ namespace
2238
+ } = config;
2239
+ const valueExp = types.stringLiteral(value);
2240
+ valueExp.extra = {
2241
+ raw: `'${uncodeValue}'`,
2242
+ // 防止转码为unicode
2243
+ rawValue: value
2244
+ };
2245
+ return types.callExpression(types.memberExpression(types.memberExpression(types.identifier(_initFileResult.importDefaultChar), types.identifier('prototype')), types.identifier(option.translateKey)), [types.stringLiteral(hash), valueExp, types.stringLiteral(namespace)]);
2246
+ };
2247
+ this.handleCodeString = (config, _initFileResult) => {
2248
+ const {
2249
+ option,
2250
+ hash,
2251
+ uncodeValue,
2252
+ namespace
2253
+ } = config;
2254
+ return `${_initFileResult.importDefaultChar}.prototype.${option.translateKey}('${hash}','${uncodeValue}','${namespace}')`;
2255
+ };
2256
+ }
2257
+ }
2258
+
2259
+ /*
2260
+ * @Author: xiaoshanwen
2261
+ * @Date: 2023-11-01 16:35:38
2262
+ * @LastEditTime: 2025-03-31 02:29:02
2263
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/TemplateElement.ts
2264
+ */
2265
+
2266
+ // 定义一个包含亚洲语言代码的数组
2267
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2268
+ function TemplateLiteral (insertOption) {
2269
+ return function (path) {
2270
+ // 如果是半自动翻译,不做处理
2271
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2272
+ return;
2273
+ }
2274
+ let {
2275
+ node,
2276
+ parent
2277
+ } = path;
2278
+ if (!node.quasis.length) return;
2279
+ if (types.isTaggedTemplateExpression(parent)) {
2280
+ return;
2281
+ }
2282
+
2283
+ // 获取真实调用函数
2284
+ const extractFnName = extractFunctionName(parent);
2285
+
2286
+ // 调用语句判断当前调用语句是否包含需要过滤的调用语句
2287
+ if (types.isCallExpression(parent) && extractFnName && (exports.option.excludedCall.includes(extractFnName) || extractFnName?.split('.')?.pop() && exports.option.excludedCall.includes(extractFnName?.split('.')?.pop() || ''))) return;
2288
+ if (node.expressions.length && handleTemplateLiteralWithExpressions(node, path)) {
2289
+ return;
2290
+ }
2291
+ node.quasis.forEach(item => handleTemplateElement(item, insertOption));
2292
+ };
2293
+ }
2294
+ function handleTemplateLiteralWithExpressions(node, path) {
2295
+ const placeholders = node.expressions.map(expression => getExpressionPlaceholder(expression));
2296
+ if (placeholders.some(placeholder => !placeholder)) {
2297
+ return false;
2298
+ }
2299
+ const fullValue = node.quasis.reduce((result, quasi, index) => {
2300
+ let value = quasi.value.raw || quasi.value.cooked || '';
2301
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2302
+ try {
2303
+ value = unicodeToString(value);
2304
+ } catch (error) {
2305
+ console.log('转换异常');
2306
+ }
2307
+ }
2308
+ return result + value + (index < node.expressions.length ? `\${${placeholders[index]}}` : '');
2309
+ }, '');
2310
+ if (!fullValue || !hasOriginSymbols(fullValue) || !exports.option.excludedPattern.length || checkAgainstRegexArray(fullValue, [...exports.option.excludedPattern])) {
2311
+ return false;
2312
+ }
2313
+ const {
2314
+ trimmedValue,
2315
+ valStr
2316
+ } = normalizeTranslateValue(fullValue);
2317
+ const id = generateId(valStr);
2318
+ const translateNode = types.callExpression(types.identifier(exports.option.translateKey), [types.stringLiteral(id), types.stringLiteral(valStr)]);
2319
+ const valuesName = types.identifier('__values');
2320
+ const keyName = types.identifier('__key');
2321
+ const valueMap = types.objectExpression(node.expressions.map((expression, index) => {
2322
+ const placeholder = placeholders[index];
2323
+ return types.objectProperty(types.stringLiteral(placeholder), expression);
2324
+ }));
2325
+ const interpolationNode = types.callExpression(types.arrowFunctionExpression([types.identifier('__value'), valuesName], types.callExpression(types.memberExpression(types.identifier('__value'), types.identifier('replace')), [types.regExpLiteral('\\\\?\\$\\{([^}]+)\\}', 'g'), types.arrowFunctionExpression([types.identifier('__match'), keyName], types.conditionalExpression(types.binaryExpression('in', keyName, valuesName), types.memberExpression(valuesName, keyName, true), types.identifier('__match')))])), [translateNode, valueMap]);
2326
+ path.replaceWith(interpolationNode);
2327
+ setLangObj(id, trimmedValue);
2328
+ return true;
2329
+ }
2330
+ function getExpressionPlaceholder(expression) {
2331
+ if (types.isIdentifier(expression)) {
2332
+ return expression.name;
2333
+ }
2334
+ if (types.isMemberExpression(expression)) {
2335
+ const objectName = getExpressionPlaceholder(expression.object);
2336
+ const propertyName = expression.computed ? getExpressionPlaceholder(expression.property) : types.isIdentifier(expression.property) ? expression.property.name : '';
2337
+ const value = [objectName, propertyName].filter(Boolean).join('.');
2338
+ return value.replace(/^\$setup\./, '').replace(/^_ctx\./, '');
2339
+ }
2340
+ if (types.isStringLiteral(expression) || types.isNumericLiteral(expression)) {
2341
+ return String(expression.value);
2342
+ }
2343
+ if (types.isTSAsExpression(expression) || types.isTSTypeAssertion(expression)) {
2344
+ return getExpressionPlaceholder(expression.expression);
2345
+ }
2346
+ if (types.isTSNonNullExpression(expression)) {
2347
+ return getExpressionPlaceholder(expression.expression);
2348
+ }
2349
+ return '';
2350
+ }
2351
+
2352
+ // 处理模板元素
2353
+ function handleTemplateElement(node, insertOption) {
2354
+ let value = node.value.raw || node.value.cooked; // 获取模板字符串的值
2355
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2356
+ try {
2357
+ value = unicodeToString(value || '');
2358
+ } catch (error) {
2359
+ console.log('转换异常');
2360
+ }
2361
+ }
2362
+ // 是否存在来源语言字符,是否在默认字符串中,是否包含过滤字段
2363
+ if (value && hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2364
+ // 生成字符类型翻译节点
2365
+ let newNode = createI18nTranslator({
2366
+ insertOption,
2367
+ value
2368
+ });
2369
+
2370
+ // 替换为字符类型翻译节点
2371
+ node.value.raw = node.value.cooked = `\${${newNode}}`;
2372
+ const {
2373
+ valStr
2374
+ } = normalizeTranslateValue(value);
2375
+ let id = generateId(valStr);
2376
+ if (id && value) {
2377
+ setLangObj(id, value);
2378
+ }
2379
+ }
2380
+ }
2381
+
2382
+ /*
2383
+ * @Author: xiaoshanwen
2384
+ * @Date: 2023-10-12 18:18:51
2385
+ * @LastEditTime: 2025-03-16 15:17:30
2386
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/CallExpression.ts
2387
+ */
2388
+
2389
+ // 收集翻译对象
2390
+ function CallExpressionFn (insertOption) {
2391
+ return function (path) {
2392
+ let {
2393
+ node
2394
+ } = path;
2395
+ // 提取公共部分,减少重复访问 node.callee 属性
2396
+ const callee = node.callee;
2397
+ if (callee.name === exports.option.translateKey || callee.property && callee.property.name === exports.option.translateKey // 拓展 半自动模式下的 如 a.b.c() 调用
2398
+ ) {
2399
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2400
+ // 获取当前翻译函数的参数
2401
+ let arg = node.arguments || [];
2402
+ // 如果参数数量不为 1,则直接返回
2403
+ if (arg.length === 1) {
2404
+ const value = arg[0]?.value || '';
2405
+ // 生成真实调用函数
2406
+ const replaceNode = createI18nTranslator({
2407
+ insertOption,
2408
+ value,
2409
+ isExpression: true
2410
+ });
2411
+ path.replaceWith(replaceNode);
2412
+ translateSetLang(replaceNode);
2413
+ }
2414
+ } else if (exports.option.translateType === TranslateTypeEnum.FULL_AUTO) {
2415
+ // 全自动模式下还是只收集 单独 $t 调用
2416
+ if (callee.name === exports.option.translateKey || callee.property && callee.property.name === exports.option.translateKey) translateSetLang(node);
2417
+ }
2418
+ }
2419
+ };
2420
+ }
2421
+
2422
+ /**
2423
+ * @description: 处理翻译并设置语言对象属性
2424
+ * @param node - 调用表达式节点
2425
+ * @return
2426
+ */
2427
+ function translateSetLang(node) {
2428
+ // 获取调用表达式的参数
2429
+ let arg = node.arguments || [];
2430
+ // 提取参数作为值
2431
+ // 检查参数是否为字符串字面量
2432
+ const id = types__namespace.isStringLiteral(arg[0]) ? arg[0].value : '';
2433
+ const value = types__namespace.isStringLiteral(arg[1]) ? arg[1].value : '';
2434
+ // 检查 ID 和值是否存在,并且第二个参数是字符串字面量
2435
+ if (id && value && types__namespace.isStringLiteral(arg[1])) {
2436
+ // 调用翻译工具的 setLangObj 方法设置语言对象属性
2437
+ setLangObj(id, value);
2438
+ }
2439
+ }
2440
+
2441
+ /*
2442
+ * @Author: xiaoshanwen
2443
+ * @Date: 2023-10-12 18:18:51
2444
+ * @LastEditTime: 2025-03-31 02:28:53
2445
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/StringLiteral.ts
2446
+ */
2447
+ function StringLiteralFn (insertOption) {
2448
+ return function (path) {
2449
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2450
+ return;
2451
+ }
2452
+ let {
2453
+ node,
2454
+ parent
2455
+ } = path;
2456
+ let value = node.value;
2457
+
2458
+ // 定义一个包含亚洲语言代码的数组
2459
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2460
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2461
+ try {
2462
+ value = unicodeToString(value);
2463
+ } catch (error) {
2464
+ console.log('转换异常');
2465
+ }
2466
+ }
2467
+ if (hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2468
+ // 获取真实调用函数
2469
+ const extractFnName = extractFunctionName(parent);
2470
+
2471
+ // 防止导入语句,只处理那些当前节点不是键值对的键的字符串字面量,调用语句判断当前调用语句是否包含需要过滤的调用语句
2472
+ if (parent?.callee?.property?.name === exports.option.translateKey || types__namespace.isImportDeclaration(parent) || parent.key === node || types__namespace.isCallExpression(parent) && extractFnName && (exports.option.excludedCall.includes(extractFnName) || extractFnName?.split('.')?.pop() && exports.option.excludedCall.includes(extractFnName?.split('.')?.pop() || ''))) return;
2473
+ let replaceNode;
2474
+ if (exports.option.deepScan && checkNeedSplit(value)) {
2475
+ replaceNode = convertToTemplateLiteral(splitByRegex(value, getOriginRegex()), insertOption);
2476
+ } else if (types__namespace.isJSXAttribute(parent)) {
2477
+ let expression = createI18nTranslator({
2478
+ insertOption,
2479
+ value,
2480
+ isExpression: true
2481
+ });
2482
+ replaceNode = types__namespace.jSXExpressionContainer(expression);
2483
+ } else {
2484
+ replaceNode = createI18nTranslator({
2485
+ insertOption,
2486
+ value,
2487
+ isExpression: true
2488
+ });
2489
+ }
2490
+ path.replaceWith(replaceNode);
2491
+ }
2492
+ };
2493
+ }
2494
+
2495
+ /*
2496
+ * @Author: xiaoshanwen
2497
+ * @Date: 2023-11-01 16:35:38
2498
+ * @LastEditTime: 2025-03-16 18:24:44
2499
+ * @FilePath: /i18n_translation_vite/packages/autoI18nPluginCore/src/filter/visitor/JSXText.ts
2500
+ */
2501
+ function JSXTextFn (insertOption) {
2502
+ return function (path) {
2503
+ console.log('jsx text');
2504
+ if (exports.option.translateType === TranslateTypeEnum.SEMI_AUTO) {
2505
+ return;
2506
+ }
2507
+ let {
2508
+ node
2509
+ } = path;
2510
+ let value = node.value;
2511
+ // 定义一个包含亚洲语言代码的数组
2512
+ const asianLangs = ['zh-cn', 'ja', 'ko'];
2513
+ if (asianLangs.some(lang => exports.option.originLang.includes(lang) || exports.option.originLang === lang)) {
2514
+ try {
2515
+ value = unicodeToString(value);
2516
+ } catch (error) {
2517
+ console.log('转换异常');
2518
+ }
2519
+ }
2520
+ if (hasOriginSymbols(value) && exports.option.excludedPattern.length && !checkAgainstRegexArray(value, [...exports.option.excludedPattern])) {
2521
+ // 生成翻译节点
2522
+ let expression = createI18nTranslator({
2523
+ insertOption,
2524
+ value,
2525
+ isExpression: true
2526
+ });
2527
+ // 生成的翻译节点包装在 types.JSXExpressionContainer 中
2528
+ let newNode = types__namespace.jSXExpressionContainer(expression);
2529
+ // 使用 path.replaceWith 方法将原来的节点替换为新的翻译节点
2530
+ path.replaceWith(newNode);
2531
+ }
2532
+ };
2533
+ }
2534
+
2535
+ /*
2536
+ * @Author: xiaoshanwen
2537
+ * @Date: 2023-10-12 18:00:37
2538
+ * @LastEditTime: 2023-11-02 10:36:02
2539
+ * @FilePath: /i18n_translation_vite/src/plugins/filter/index.ts
2540
+ */
2541
+
2542
+ function index (insertOption) {
2543
+ // 分别调用各个访问器函数并传入插入选项
2544
+ const stringLiteralVisitor = StringLiteralFn(insertOption);
2545
+ const jsxTextVisitor = JSXTextFn(insertOption);
2546
+ const templateLiteralVisitor = TemplateLiteral(insertOption);
2547
+ const callExpressionVisitor = CallExpressionFn(insertOption);
2548
+
2549
+ // 返回一个函数,该函数返回包含访问器的对象
2550
+ return function () {
2551
+ return {
2552
+ // 定义 Babel 访问器对象
2553
+ visitor: {
2554
+ StringLiteral: stringLiteralVisitor,
2555
+ JSXText: jsxTextVisitor,
2556
+ TemplateLiteral: templateLiteralVisitor,
2557
+ CallExpression: callExpressionVisitor
2558
+ }
2559
+ };
2560
+ };
2561
+ }
2562
+
2563
+ var index$1 = /*#__PURE__*/Object.freeze({
2564
+ __proto__: null,
2565
+ default: index
2566
+ });
2567
+
2568
+ var allowedExtensions = ['.vue', '.ts', '.js', '.tsx', '.jsx'];
2569
+ function vitePluginsAutoI18n(optionInfo) {
2570
+ var name = 'vite-gc-i18n-plugin';
2571
+ var config;
2572
+ initOption(__assign({
2573
+ deepScan: true,
2574
+ globalPath: './lang',
2575
+ namespace: 'lang',
2576
+ translateKey: '$t',
2577
+ distPath: './dist/assets',
2578
+ distKey: 'index',
2579
+ targetLangList: ['zh-cn', 'zh-tw'],
2580
+ originLang: 'zh-cn',
2581
+ translator: new CNToTWTranslator()
2582
+ }, optionInfo));
2583
+ if (!checkOption()) return {
2584
+ name: name
2585
+ };
2586
+ initLangFile();
2587
+ var originLangObj = getLangObjByJSONFileWithLangKey(exports.option.originLang);
2588
+ languageConfigCompletion(originLangObj);
2589
+ initLangObj(originLangObj);
2590
+ var plugin = {
2591
+ name: name,
2592
+ configResolved: function (resolvedConfig) {
2593
+ // 存储最终解析的配置
2594
+ config = resolvedConfig;
2595
+ },
2596
+ transform: function (code, path) {
2597
+ return __awaiter(this, void 0, void 0, function () {
2598
+ var sourceObj;
2599
+ var _a;
2600
+ return __generator(this, function (_b) {
2601
+ switch (_b.label) {
2602
+ case 0:
2603
+ if (!__spreadArray(__spreadArray([], allowedExtensions, true), exports.option.insertFileExtensions || [], true).some(function (ext) {
2604
+ return path.endsWith(ext);
2605
+ })) return [3 /*break*/, 4];
2606
+ if (exports.option.includePath.length && !checkAgainstRegexArray(path, exports.option.includePath)) return [2 /*return*/, code];
2607
+ if (exports.option.excludedPath.length && checkAgainstRegexArray(path, exports.option.excludedPath)) return [2 /*return*/, code];
2608
+ FunctionFactoryOption.originLang = exports.option.originLang;
2609
+ sourceObj = void 0;
2610
+ if (!exports.option.translateExtends) return [3 /*break*/, 2];
2611
+ return [4 /*yield*/, (_a = exports.option.translateExtends) === null || _a === void 0 ? void 0 : _a.handleInitFile(code, path)];
2612
+ case 1:
2613
+ sourceObj = _b.sent();
2614
+ return [3 /*break*/, 3];
2615
+ case 2:
2616
+ sourceObj = {
2617
+ source: code
2618
+ };
2619
+ _b.label = 3;
2620
+ case 3:
2621
+ return [2 /*return*/, babel__namespace.transformAsync(sourceObj.source, {
2622
+ configFile: false,
2623
+ plugins: [index()]
2624
+ }).then(function (result) {
2625
+ if ((config === null || config === void 0 ? void 0 : config.command) === 'serve') {
2626
+ autoTranslate(); // 执行前需要确保transformAsync已经完成
2627
+ }
2628
+ return result === null || result === void 0 ? void 0 : result.code;
2629
+ }).catch(function (e) {
2630
+ console.error(e);
2631
+ })];
2632
+ case 4:
2633
+ return [2 /*return*/];
2634
+ }
2635
+ });
2636
+ });
2637
+ },
2638
+ buildEnd: function () {
2639
+ return __awaiter(this, void 0, void 0, function () {
2640
+ return __generator(this, function (_a) {
2641
+ switch (_a.label) {
2642
+ case 0:
2643
+ console.info('构建阶段批量翻译');
2644
+ return [4 /*yield*/, autoTranslate()];
2645
+ case 1:
2646
+ _a.sent();
2647
+ return [2 /*return*/];
2648
+ }
2649
+ });
2650
+ });
2651
+ },
2652
+ closeBundle: function () {
2653
+ return __awaiter(this, void 0, void 0, function () {
2654
+ return __generator(this, function (_a) {
2655
+ switch (_a.label) {
2656
+ case 0:
2657
+ if (!(config && config.command === 'build')) return [3 /*break*/, 3];
2658
+ if (!exports.option.uploadEnabled) return [3 /*break*/, 2];
2659
+ console.info('构建阶段:开始上传翻译文件');
2660
+ return [4 /*yield*/, uploadFile()];
2661
+ case 1:
2662
+ _a.sent();
2663
+ return [3 /*break*/, 3];
2664
+ case 2:
2665
+ console.info('构建阶段:上传翻译文件功能已禁用(uploadEnabled: false)');
2666
+ _a.label = 3;
2667
+ case 3:
2668
+ return [2 /*return*/];
2669
+ }
2670
+ });
2671
+ });
2672
+ }
2673
+ };
2674
+ return plugin;
2675
+ }
2676
+
2677
+ exports.BaiduTranslator = BaiduTranslator;
2678
+ exports.CNToTWTranslator = CNToTWTranslator;
2679
+ exports.EmptyTranslator = EmptyTranslator;
2680
+ exports.FunctionFactoryOption = FunctionFactoryOption;
2681
+ exports.GoogleTranslator = GoogleTranslator;
2682
+ exports.LanguageEnum = LanguageEnum;
2683
+ exports.OriginLangKeyEnum = OriginLangKeyEnum;
2684
+ exports.ScanTranslator = ScanTranslator;
2685
+ exports.TranslateApiEnum = TranslateApiEnum;
2686
+ exports.TranslateTypeEnum = TranslateTypeEnum;
2687
+ exports.Translator = Translator;
2688
+ exports.VolcengineTranslator = VolcengineTranslator;
2689
+ exports.Vue2Extends = Vue2Extends;
2690
+ exports.YoudaoTranslator = YoudaoTranslator;
2691
+ exports.baseUtils = base;
2692
+ exports.checkOption = checkOption;
2693
+ exports.default = vitePluginsAutoI18n;
2694
+ exports.fileUtils = file;
2695
+ exports.filter = index$1;
2696
+ exports.initOption = initOption;
2697
+ exports.translateUtils = translate;
2698
+ exports.uploadUtils = upload$1;
2
2699
  //# sourceMappingURL=index.cjs.map