@terai/dev 0.0.0-dev-20240302092932 → 0.0.0-dev-20240302165901

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.
@@ -1,11 +1,726 @@
1
- "use strict";var de=Object.create;var $=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty;var Te=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0})},K=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of be(e))!ye.call(t,o)&&o!==r&&$(t,o,{get:()=>e[o],enumerable:!(n=pe(e,o))||n.enumerable});return t};var w=(t,e,r)=>(r=t!=null?de(ve(t)):{},K(e||!t||!t.__esModule?$(r,"default",{value:t,enumerable:!0}):r,t)),Oe=t=>K($({},"__esModule",{value:!0}),t);var Ue={};Te(Ue,{createTranslateCommand:()=>Ve,translateCmd:()=>ue});module.exports=Oe(Ue);var j=require("@terai/runtime"),z=require("@terai/utils");async function Q({dictionaries:t,locale:e,cwd:r,outDir:n}){let o=j.runtime.path.resolve(r,n,e),i=[];for(let l in t){let g=j.runtime.path.resolve(o,`${l}.json`),C=t[l],x=(0,z.stringify)(C);j.runtime.fs.write(g,x),i.push(x)}return i}var c=require("@terai/runtime");var V=w(require("process"),1),N=w(require("process"),1),ae=w(require("os"),1),S=w(require("tty"),1),X=(t=0)=>e=>`\x1B[${e+t}m`,Z=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,ee=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,s={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Qe=Object.keys(s.modifier),Ce=Object.keys(s.color),xe=Object.keys(s.bgColor),Xe=[...Ce,...xe];function Re(){let t=new Map;for(let[e,r]of Object.entries(s)){for(let[n,o]of Object.entries(r))s[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=s[n],t.set(o[0],o[1]);Object.defineProperty(s,e,{value:r,enumerable:!1})}return Object.defineProperty(s,"codes",{value:t,enumerable:!1}),s.color.close="\x1B[39m",s.bgColor.close="\x1B[49m",s.color.ansi=X(),s.color.ansi256=Z(),s.color.ansi16m=ee(),s.bgColor.ansi=X(10),s.bgColor.ansi256=Z(10),s.bgColor.ansi16m=ee(10),Object.defineProperties(s,{rgbToAnsi256:{value(e,r,n){return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(i=>i+i).join(""));let o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>s.rgbToAnsi256(...s.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,o;if(e>=232)r=((e-232)*10+8)/255,n=r,o=r;else{e-=16;let g=e%36;r=Math.floor(e/36)/5,n=Math.floor(g/6)/5,o=g%6/5}let i=Math.max(r,n,o)*2;if(i===0)return 30;let l=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return i===2&&(l+=60),l},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>s.ansi256ToAnsi(s.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>s.ansi256ToAnsi(s.hexToAnsi256(e)),enumerable:!1}}),s}var Me=Re(),h=Me;function f(t,e=globalThis.Deno?globalThis.Deno.args:N.default.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:a}=N.default,I;f("no-color")||f("no-colors")||f("color=false")||f("color=never")?I=0:(f("color")||f("colors")||f("color=true")||f("color=always"))&&(I=1);function Ae(){if("FORCE_COLOR"in a)return a.FORCE_COLOR==="true"?1:a.FORCE_COLOR==="false"?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function Be(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ee(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=Ae();n!==void 0&&(I=n);let o=r?I:n;if(o===0)return 0;if(r){if(f("color=16m")||f("color=full")||f("color=truecolor"))return 3;if(f("color=256"))return 2}if("TF_BUILD"in a&&"AGENT_NAME"in a)return 1;if(t&&!e&&o===void 0)return 0;let i=o||0;if(a.TERM==="dumb")return i;if(N.default.platform==="win32"){let l=ae.default.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in a)return"GITHUB_ACTIONS"in a||"GITEA_ACTIONS"in a?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(l=>l in a)||a.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM==="truecolor"||a.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in a){let l=Number.parseInt((a.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(a.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||"COLORTERM"in a?1:i}function te(t,e={}){let r=Ee(t,{streamIsTTY:t&&t.isTTY,...e});return Be(r)}var $e={stdout:te({isTTY:S.default.isatty(1)}),stderr:te({isTTY:S.default.isatty(2)})},we=$e;function je(t,e,r){let n=t.indexOf(e);if(n===-1)return t;let o=e.length,i=0,l="";do l+=t.slice(i,n)+e+r,i=n+o,n=t.indexOf(e,i);while(n!==-1);return l+=t.slice(i),l}function Ie(t,e,r,n){let o=0,i="";do{let l=t[n-1]==="\r";i+=t.slice(o,l?n-1:n)+e+(l?`\r
2
- `:`
3
- `)+r,o=n+1,n=t.indexOf(`
4
- `,o)}while(n!==-1);return i+=t.slice(o),i}var{stdout:re,stderr:ne}=we,L=Symbol("GENERATOR"),v=Symbol("STYLER"),M=Symbol("IS_EMPTY"),oe=["ansi","ansi","ansi256","ansi16m"],y=Object.create(null),Pe=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=re?re.level:0;t.level=e.level===void 0?r:e.level},Ne=t=>{let e=(...r)=>r.join(" ");return Pe(e,t),Object.setPrototypeOf(e,A.prototype),e};function A(t){return Ne(t)}Object.setPrototypeOf(A.prototype,Function.prototype);for(let[t,e]of Object.entries(h))y[t]={get(){let r=P(this,Y(e.open,e.close,this[v]),this[M]);return Object.defineProperty(this,t,{value:r}),r}};y.visible={get(){let t=P(this,this[v],!0);return Object.defineProperty(this,"visible",{value:t}),t}};var G=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?h[r].ansi16m(...n):e==="ansi256"?h[r].ansi256(h.rgbToAnsi256(...n)):h[r].ansi(h.rgbToAnsi(...n)):t==="hex"?G("rgb",e,r,...h.hexToRgb(...n)):h[r][t](...n),ke=["rgb","hex","ansi256"];for(let t of ke){y[t]={get(){let{level:r}=this;return function(...n){let o=Y(G(t,oe[r],"color",...n),h.color.close,this[v]);return P(this,o,this[M])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);y[e]={get(){let{level:r}=this;return function(...n){let o=Y(G(t,oe[r],"bgColor",...n),h.bgColor.close,this[v]);return P(this,o,this[M])}}}}var De=Object.defineProperties(()=>{},{...y,level:{enumerable:!0,get(){return this[L].level},set(t){this[L].level=t}}}),Y=(t,e,r)=>{let n,o;return r===void 0?(n=t,o=e):(n=r.openAll+t,o=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:o,parent:r}},P=(t,e,r)=>{let n=(...o)=>_e(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,De),n[L]=t,n[v]=e,n[M]=r,n},_e=(t,e)=>{if(t.level<=0||!e)return t[M]?"":e;let r=t[v];if(r===void 0)return e;let{openAll:n,closeAll:o}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=je(e,r.close,r.open),r=r.parent;let i=e.indexOf(`
5
- `);return i!==-1&&(e=Ie(e,o,n,i)),n+e+o};Object.defineProperties(A.prototype,y);var Fe=A(),Ze=A({level:ne?ne.level:0}),u=Fe;function b(t){return V.default.stdout.write(`${t}
6
- `)}function Se(t){return V.default.stderr.write(`${t}
7
- `)}function B(t,e,r,n,o,i){let l=(Array.isArray(i)?i:[i||""].filter(Boolean)).map(g=>r(g)).join("");t(`${" ".repeat(3)} ${e(n)} ${e(o)} ${l}`)}function Le(t,e){B(b,u.yellow,u.yellow,"\u25CF",t,e)}function ie(t,e){B(b,u.yellow,u.dim,"\u25CF",t,e)}function se(t,e){B(b,u.cyan,u.dim,"\u25FC",t,e)}function le(t){B(b,u.green,u.dim,"\u2714",t)}function Ge(t,e){b(""),B(Se,u.red,u.red,"\u25B2",t,e)}function Ye(t,e){return b(`
8
- ${u.bgWhite(` ${u.whiteBright(t)} `)} ${u.bold(e)}
9
- `)}var F=t=>()=>{let e=performance.now();return r=>{let n=performance.now()-e;t(`${r} ${u.gray(`(${n.toFixed(2)}ms)`)}`)}},T={colors:u,log:b,heading:Ye,debug:ie,info:se,warn:Le,success:le,error:Ge,time:{success:F(le),info:F(se),debug:F(ie)}};var ce=require("@terai/translator"),O=require("@terai/utils");function Ve(t,e){return t.command("translate","Translate messages from your project").option("--cwd <cwd>","Current working directory",{default:e}).action(ue)}async function ue({cwd:t}){T.heading("translate","Translate messages from your project");let e=T.time.success(),r=await(0,c.loadConfig)({cwd:t}),n=c.runtime.path.resolve(t,r.outDir),o=c.runtime.path.resolve(t,r.outDir,".terai"),i=c.runtime.path.resolve(o,"locale-manifest.json");if(!c.runtime.fs.exists(i))return T.error("translate",`No locale-manifest.json found in ${o}. Please run "extract" first.`);let g=JSON.parse(c.runtime.fs.readFile(i)),C=0,x=0;if(await Promise.all(r.outLocales.map(async m=>{try{let d={},U={},W=c.runtime.path.resolve(n,m),k=c.runtime.path.resolve(o,"cache",`${m}.cache.json`),R=c.runtime.fs.exists(k)?JSON.parse(c.runtime.fs.readFile(k)):{},D=0,E=0;for(let p in g.messages){let{value:ge,chunksIds:J}=g.messages[p],he=J.length?J:[m];for(let me of he){let H=c.runtime.path.resolve(W,`${me}.json`),_=(c.runtime.fs.exists(H)?JSON.parse(c.runtime.fs.readFile(H)):{})[p]??R[p];_?(d[p]=_,R[p]=_,D++):(U[p]=ge,E++)}}if(E>0){let p=await(0,ce.translate)({...r,dictionary:U,locale:m});d=(0,O.merge)(p,d)}R={...R,...d},c.runtime.fs.remove(W);let fe=(0,O.groupDictionaryByChunks)(d,g,m);await Q({...r,dictionaries:fe,locale:m,cwd:t}),c.runtime.fs.write(k,(0,O.stringify)(R)),C+=E,x+=D,T.info(`Locale ${m.toUpperCase()}:`,`${E} new messages translated, ${D} recovered from cache`)}catch(d){d instanceof Error&&T.error(`${m} translation:`,`Error translating to ${m}: ${d.message}
10
- `)}})),!C)return e("Everything up-to-date");e(`Translated ${C} messages, ${x} read from cache`)}0&&(module.exports={createTranslateCommand,translateCmd});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/commands/translate.ts
31
+ var translate_exports = {};
32
+ __export(translate_exports, {
33
+ createTranslateCommand: () => createTranslateCommand,
34
+ translateCmd: () => translateCmd
35
+ });
36
+ module.exports = __toCommonJS(translate_exports);
37
+
38
+ // ../generator/dist/index.mjs
39
+ var import_runtime = require("@terai/runtime");
40
+ var import_utils = require("@terai/utils");
41
+ async function generate({
42
+ dictionaries,
43
+ locale,
44
+ cwd,
45
+ outDir
46
+ }) {
47
+ const folderPath = import_runtime.runtime.path.resolve(cwd, outDir, locale);
48
+ const output = [];
49
+ for (const id in dictionaries) {
50
+ const fileDir = import_runtime.runtime.path.resolve(folderPath, `${id}.json`);
51
+ const fileContent = dictionaries[id];
52
+ const idOutput = (0, import_utils.stringify)(fileContent);
53
+ import_runtime.runtime.fs.write(fileDir, idOutput);
54
+ output.push(idOutput);
55
+ }
56
+ return output;
57
+ }
58
+
59
+ // src/commands/translate.ts
60
+ var import_runtime2 = require("@terai/runtime");
61
+
62
+ // ../logger/dist/index.mjs
63
+ var import_node_process = __toESM(require("process"), 1);
64
+ var import_node_process2 = __toESM(require("process"), 1);
65
+ var import_node_os = __toESM(require("os"), 1);
66
+ var import_node_tty = __toESM(require("tty"), 1);
67
+ var ANSI_BACKGROUND_OFFSET = 10;
68
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
69
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
70
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
71
+ var styles = {
72
+ modifier: {
73
+ reset: [0, 0],
74
+ // 21 isn't widely supported and 22 does the same thing
75
+ bold: [1, 22],
76
+ dim: [2, 22],
77
+ italic: [3, 23],
78
+ underline: [4, 24],
79
+ overline: [53, 55],
80
+ inverse: [7, 27],
81
+ hidden: [8, 28],
82
+ strikethrough: [9, 29]
83
+ },
84
+ color: {
85
+ black: [30, 39],
86
+ red: [31, 39],
87
+ green: [32, 39],
88
+ yellow: [33, 39],
89
+ blue: [34, 39],
90
+ magenta: [35, 39],
91
+ cyan: [36, 39],
92
+ white: [37, 39],
93
+ // Bright color
94
+ blackBright: [90, 39],
95
+ gray: [90, 39],
96
+ // Alias of `blackBright`
97
+ grey: [90, 39],
98
+ // Alias of `blackBright`
99
+ redBright: [91, 39],
100
+ greenBright: [92, 39],
101
+ yellowBright: [93, 39],
102
+ blueBright: [94, 39],
103
+ magentaBright: [95, 39],
104
+ cyanBright: [96, 39],
105
+ whiteBright: [97, 39]
106
+ },
107
+ bgColor: {
108
+ bgBlack: [40, 49],
109
+ bgRed: [41, 49],
110
+ bgGreen: [42, 49],
111
+ bgYellow: [43, 49],
112
+ bgBlue: [44, 49],
113
+ bgMagenta: [45, 49],
114
+ bgCyan: [46, 49],
115
+ bgWhite: [47, 49],
116
+ // Bright color
117
+ bgBlackBright: [100, 49],
118
+ bgGray: [100, 49],
119
+ // Alias of `bgBlackBright`
120
+ bgGrey: [100, 49],
121
+ // Alias of `bgBlackBright`
122
+ bgRedBright: [101, 49],
123
+ bgGreenBright: [102, 49],
124
+ bgYellowBright: [103, 49],
125
+ bgBlueBright: [104, 49],
126
+ bgMagentaBright: [105, 49],
127
+ bgCyanBright: [106, 49],
128
+ bgWhiteBright: [107, 49]
129
+ }
130
+ };
131
+ var modifierNames = Object.keys(styles.modifier);
132
+ var foregroundColorNames = Object.keys(styles.color);
133
+ var backgroundColorNames = Object.keys(styles.bgColor);
134
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
135
+ function assembleStyles() {
136
+ const codes = /* @__PURE__ */ new Map();
137
+ for (const [groupName, group] of Object.entries(styles)) {
138
+ for (const [styleName, style] of Object.entries(group)) {
139
+ styles[styleName] = {
140
+ open: `\x1B[${style[0]}m`,
141
+ close: `\x1B[${style[1]}m`
142
+ };
143
+ group[styleName] = styles[styleName];
144
+ codes.set(style[0], style[1]);
145
+ }
146
+ Object.defineProperty(styles, groupName, {
147
+ value: group,
148
+ enumerable: false
149
+ });
150
+ }
151
+ Object.defineProperty(styles, "codes", {
152
+ value: codes,
153
+ enumerable: false
154
+ });
155
+ styles.color.close = "\x1B[39m";
156
+ styles.bgColor.close = "\x1B[49m";
157
+ styles.color.ansi = wrapAnsi16();
158
+ styles.color.ansi256 = wrapAnsi256();
159
+ styles.color.ansi16m = wrapAnsi16m();
160
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
161
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
162
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
163
+ Object.defineProperties(styles, {
164
+ rgbToAnsi256: {
165
+ value(red, green, blue) {
166
+ if (red === green && green === blue) {
167
+ if (red < 8) {
168
+ return 16;
169
+ }
170
+ if (red > 248) {
171
+ return 231;
172
+ }
173
+ return Math.round((red - 8) / 247 * 24) + 232;
174
+ }
175
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
176
+ },
177
+ enumerable: false
178
+ },
179
+ hexToRgb: {
180
+ value(hex) {
181
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
182
+ if (!matches) {
183
+ return [0, 0, 0];
184
+ }
185
+ let [colorString] = matches;
186
+ if (colorString.length === 3) {
187
+ colorString = [...colorString].map((character) => character + character).join("");
188
+ }
189
+ const integer = Number.parseInt(colorString, 16);
190
+ return [
191
+ /* eslint-disable no-bitwise */
192
+ integer >> 16 & 255,
193
+ integer >> 8 & 255,
194
+ integer & 255
195
+ /* eslint-enable no-bitwise */
196
+ ];
197
+ },
198
+ enumerable: false
199
+ },
200
+ hexToAnsi256: {
201
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
202
+ enumerable: false
203
+ },
204
+ ansi256ToAnsi: {
205
+ value(code) {
206
+ if (code < 8) {
207
+ return 30 + code;
208
+ }
209
+ if (code < 16) {
210
+ return 90 + (code - 8);
211
+ }
212
+ let red;
213
+ let green;
214
+ let blue;
215
+ if (code >= 232) {
216
+ red = ((code - 232) * 10 + 8) / 255;
217
+ green = red;
218
+ blue = red;
219
+ } else {
220
+ code -= 16;
221
+ const remainder = code % 36;
222
+ red = Math.floor(code / 36) / 5;
223
+ green = Math.floor(remainder / 6) / 5;
224
+ blue = remainder % 6 / 5;
225
+ }
226
+ const value = Math.max(red, green, blue) * 2;
227
+ if (value === 0) {
228
+ return 30;
229
+ }
230
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
231
+ if (value === 2) {
232
+ result += 60;
233
+ }
234
+ return result;
235
+ },
236
+ enumerable: false
237
+ },
238
+ rgbToAnsi: {
239
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
240
+ enumerable: false
241
+ },
242
+ hexToAnsi: {
243
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
244
+ enumerable: false
245
+ }
246
+ });
247
+ return styles;
248
+ }
249
+ var ansiStyles = assembleStyles();
250
+ var ansi_styles_default = ansiStyles;
251
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process2.default.argv) {
252
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
253
+ const position = argv.indexOf(prefix + flag);
254
+ const terminatorPosition = argv.indexOf("--");
255
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
256
+ }
257
+ var { env } = import_node_process2.default;
258
+ var flagForceColor;
259
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
260
+ flagForceColor = 0;
261
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
262
+ flagForceColor = 1;
263
+ }
264
+ function envForceColor() {
265
+ if ("FORCE_COLOR" in env) {
266
+ if (env.FORCE_COLOR === "true") {
267
+ return 1;
268
+ }
269
+ if (env.FORCE_COLOR === "false") {
270
+ return 0;
271
+ }
272
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
273
+ }
274
+ }
275
+ function translateLevel(level) {
276
+ if (level === 0) {
277
+ return false;
278
+ }
279
+ return {
280
+ level,
281
+ hasBasic: true,
282
+ has256: level >= 2,
283
+ has16m: level >= 3
284
+ };
285
+ }
286
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
287
+ const noFlagForceColor = envForceColor();
288
+ if (noFlagForceColor !== void 0) {
289
+ flagForceColor = noFlagForceColor;
290
+ }
291
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
292
+ if (forceColor === 0) {
293
+ return 0;
294
+ }
295
+ if (sniffFlags) {
296
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
297
+ return 3;
298
+ }
299
+ if (hasFlag("color=256")) {
300
+ return 2;
301
+ }
302
+ }
303
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
304
+ return 1;
305
+ }
306
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
307
+ return 0;
308
+ }
309
+ const min = forceColor || 0;
310
+ if (env.TERM === "dumb") {
311
+ return min;
312
+ }
313
+ if (import_node_process2.default.platform === "win32") {
314
+ const osRelease = import_node_os.default.release().split(".");
315
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
316
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
317
+ }
318
+ return 1;
319
+ }
320
+ if ("CI" in env) {
321
+ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
322
+ return 3;
323
+ }
324
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
325
+ return 1;
326
+ }
327
+ return min;
328
+ }
329
+ if ("TEAMCITY_VERSION" in env) {
330
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
331
+ }
332
+ if (env.COLORTERM === "truecolor") {
333
+ return 3;
334
+ }
335
+ if (env.TERM === "xterm-kitty") {
336
+ return 3;
337
+ }
338
+ if ("TERM_PROGRAM" in env) {
339
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
340
+ switch (env.TERM_PROGRAM) {
341
+ case "iTerm.app": {
342
+ return version >= 3 ? 3 : 2;
343
+ }
344
+ case "Apple_Terminal": {
345
+ return 2;
346
+ }
347
+ }
348
+ }
349
+ if (/-256(color)?$/i.test(env.TERM)) {
350
+ return 2;
351
+ }
352
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
353
+ return 1;
354
+ }
355
+ if ("COLORTERM" in env) {
356
+ return 1;
357
+ }
358
+ return min;
359
+ }
360
+ function createSupportsColor(stream, options = {}) {
361
+ const level = _supportsColor(stream, {
362
+ streamIsTTY: stream && stream.isTTY,
363
+ ...options
364
+ });
365
+ return translateLevel(level);
366
+ }
367
+ var supportsColor = {
368
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
369
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
370
+ };
371
+ var supports_color_default = supportsColor;
372
+ function stringReplaceAll(string, substring, replacer) {
373
+ let index = string.indexOf(substring);
374
+ if (index === -1) {
375
+ return string;
376
+ }
377
+ const substringLength = substring.length;
378
+ let endIndex = 0;
379
+ let returnValue = "";
380
+ do {
381
+ returnValue += string.slice(endIndex, index) + substring + replacer;
382
+ endIndex = index + substringLength;
383
+ index = string.indexOf(substring, endIndex);
384
+ } while (index !== -1);
385
+ returnValue += string.slice(endIndex);
386
+ return returnValue;
387
+ }
388
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
389
+ let endIndex = 0;
390
+ let returnValue = "";
391
+ do {
392
+ const gotCR = string[index - 1] === "\r";
393
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
394
+ endIndex = index + 1;
395
+ index = string.indexOf("\n", endIndex);
396
+ } while (index !== -1);
397
+ returnValue += string.slice(endIndex);
398
+ return returnValue;
399
+ }
400
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
401
+ var GENERATOR = Symbol("GENERATOR");
402
+ var STYLER = Symbol("STYLER");
403
+ var IS_EMPTY = Symbol("IS_EMPTY");
404
+ var levelMapping = [
405
+ "ansi",
406
+ "ansi",
407
+ "ansi256",
408
+ "ansi16m"
409
+ ];
410
+ var styles2 = /* @__PURE__ */ Object.create(null);
411
+ var applyOptions = (object, options = {}) => {
412
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
413
+ throw new Error("The `level` option should be an integer from 0 to 3");
414
+ }
415
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
416
+ object.level = options.level === void 0 ? colorLevel : options.level;
417
+ };
418
+ var chalkFactory = (options) => {
419
+ const chalk2 = (...strings) => strings.join(" ");
420
+ applyOptions(chalk2, options);
421
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
422
+ return chalk2;
423
+ };
424
+ function createChalk(options) {
425
+ return chalkFactory(options);
426
+ }
427
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
428
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
429
+ styles2[styleName] = {
430
+ get() {
431
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
432
+ Object.defineProperty(this, styleName, { value: builder });
433
+ return builder;
434
+ }
435
+ };
436
+ }
437
+ styles2.visible = {
438
+ get() {
439
+ const builder = createBuilder(this, this[STYLER], true);
440
+ Object.defineProperty(this, "visible", { value: builder });
441
+ return builder;
442
+ }
443
+ };
444
+ var getModelAnsi = (model, level, type, ...arguments_) => {
445
+ if (model === "rgb") {
446
+ if (level === "ansi16m") {
447
+ return ansi_styles_default[type].ansi16m(...arguments_);
448
+ }
449
+ if (level === "ansi256") {
450
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
451
+ }
452
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
453
+ }
454
+ if (model === "hex") {
455
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
456
+ }
457
+ return ansi_styles_default[type][model](...arguments_);
458
+ };
459
+ var usedModels = ["rgb", "hex", "ansi256"];
460
+ for (const model of usedModels) {
461
+ styles2[model] = {
462
+ get() {
463
+ const { level } = this;
464
+ return function(...arguments_) {
465
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
466
+ return createBuilder(this, styler, this[IS_EMPTY]);
467
+ };
468
+ }
469
+ };
470
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
471
+ styles2[bgModel] = {
472
+ get() {
473
+ const { level } = this;
474
+ return function(...arguments_) {
475
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
476
+ return createBuilder(this, styler, this[IS_EMPTY]);
477
+ };
478
+ }
479
+ };
480
+ }
481
+ var proto = Object.defineProperties(() => {
482
+ }, {
483
+ ...styles2,
484
+ level: {
485
+ enumerable: true,
486
+ get() {
487
+ return this[GENERATOR].level;
488
+ },
489
+ set(level) {
490
+ this[GENERATOR].level = level;
491
+ }
492
+ }
493
+ });
494
+ var createStyler = (open, close, parent) => {
495
+ let openAll;
496
+ let closeAll;
497
+ if (parent === void 0) {
498
+ openAll = open;
499
+ closeAll = close;
500
+ } else {
501
+ openAll = parent.openAll + open;
502
+ closeAll = close + parent.closeAll;
503
+ }
504
+ return {
505
+ open,
506
+ close,
507
+ openAll,
508
+ closeAll,
509
+ parent
510
+ };
511
+ };
512
+ var createBuilder = (self, _styler, _isEmpty) => {
513
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
514
+ Object.setPrototypeOf(builder, proto);
515
+ builder[GENERATOR] = self;
516
+ builder[STYLER] = _styler;
517
+ builder[IS_EMPTY] = _isEmpty;
518
+ return builder;
519
+ };
520
+ var applyStyle = (self, string) => {
521
+ if (self.level <= 0 || !string) {
522
+ return self[IS_EMPTY] ? "" : string;
523
+ }
524
+ let styler = self[STYLER];
525
+ if (styler === void 0) {
526
+ return string;
527
+ }
528
+ const { openAll, closeAll } = styler;
529
+ if (string.includes("\x1B")) {
530
+ while (styler !== void 0) {
531
+ string = stringReplaceAll(string, styler.close, styler.open);
532
+ styler = styler.parent;
533
+ }
534
+ }
535
+ const lfIndex = string.indexOf("\n");
536
+ if (lfIndex !== -1) {
537
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
538
+ }
539
+ return openAll + string + closeAll;
540
+ };
541
+ Object.defineProperties(createChalk.prototype, styles2);
542
+ var chalk = createChalk();
543
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
544
+ var source_default = chalk;
545
+ function log(message) {
546
+ return import_node_process.default.stdout.write(`${message}
547
+ `);
548
+ }
549
+ function logError(message) {
550
+ return import_node_process.default.stderr.write(`${message}
551
+ `);
552
+ }
553
+ function logBullet(logger2, colorizePrefix, colorizeText, symbol, prefix, text) {
554
+ const textParts = Array.isArray(text) ? text : [text || ""].filter(Boolean);
555
+ const formattedText = textParts.map((textPart) => colorizeText(textPart)).join("");
556
+ logger2(
557
+ `${" ".repeat(3)} ${colorizePrefix(symbol)} ${colorizePrefix(
558
+ prefix
559
+ )} ${formattedText}`
560
+ );
561
+ }
562
+ function warn(prefix, text) {
563
+ logBullet(log, source_default.yellow, source_default.yellow, "\u25CF", prefix, text);
564
+ }
565
+ function debug(prefix, text) {
566
+ logBullet(log, source_default.yellow, source_default.dim, "\u25CF", prefix, text);
567
+ }
568
+ function info(prefix, text) {
569
+ logBullet(log, source_default.cyan, source_default.dim, "\u25FC", prefix, text);
570
+ }
571
+ function success(text) {
572
+ logBullet(log, source_default.green, source_default.dim, "\u2714", text);
573
+ }
574
+ function error(prefix, text) {
575
+ log("");
576
+ logBullet(logError, source_default.red, source_default.red, "\u25B2", prefix, text);
577
+ }
578
+ function heading(heading2, description) {
579
+ return log(
580
+ `
581
+ ${source_default.bgWhite(` ${source_default.whiteBright(heading2)} `)} ${source_default.bold(
582
+ description
583
+ )}
584
+ `
585
+ );
586
+ }
587
+ var timing = (fn) => () => {
588
+ const start = performance.now();
589
+ return (msg) => {
590
+ const end = performance.now();
591
+ const ms = end - start;
592
+ fn(`${msg} ${source_default.gray(`(${ms.toFixed(2)}ms)`)}`);
593
+ };
594
+ };
595
+ var logger = {
596
+ colors: source_default,
597
+ log,
598
+ heading,
599
+ debug,
600
+ info,
601
+ warn,
602
+ success,
603
+ error,
604
+ time: {
605
+ success: timing(success),
606
+ info: timing(info),
607
+ debug: timing(debug)
608
+ }
609
+ };
610
+
611
+ // src/commands/translate.ts
612
+ var import_translator = require("@terai/translator");
613
+ var import_utils2 = require("@terai/utils");
614
+ function createTranslateCommand(cli, cwd) {
615
+ return cli.command("translate", "Translate messages from your project").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(translateCmd);
616
+ }
617
+ async function translateCmd({ cwd }) {
618
+ logger.heading("translate", "Translate messages from your project");
619
+ const done = logger.time.success();
620
+ const config = await (0, import_runtime2.loadConfig)({ cwd });
621
+ const outDirPath = import_runtime2.runtime.path.resolve(cwd, config.outDir);
622
+ const tmuDirPath = import_runtime2.runtime.path.resolve(cwd, config.outDir, ".terai");
623
+ const manifestPath = import_runtime2.runtime.path.resolve(tmuDirPath, "locale-manifest.json");
624
+ const existsManifest = import_runtime2.runtime.fs.exists(manifestPath);
625
+ if (!existsManifest) {
626
+ return logger.error(
627
+ "translate",
628
+ `No locale-manifest.json found in ${tmuDirPath}. Please run "extract" first.`
629
+ );
630
+ }
631
+ const buildManifest = JSON.parse(
632
+ import_runtime2.runtime.fs.readFile(manifestPath)
633
+ );
634
+ let totalTranslatedMsgs = 0;
635
+ let totalCachedMsgs = 0;
636
+ await Promise.all(
637
+ config.outLocales.map(async (locale) => {
638
+ try {
639
+ let translatedDictionary = {};
640
+ const untranslatedDictionary = {};
641
+ const localeDirPath = import_runtime2.runtime.path.resolve(outDirPath, locale);
642
+ const localeCachePath = import_runtime2.runtime.path.resolve(
643
+ tmuDirPath,
644
+ "cache",
645
+ `${locale}.cache.json`
646
+ );
647
+ const cacheExists = import_runtime2.runtime.fs.exists(localeCachePath);
648
+ let cache = cacheExists ? JSON.parse(import_runtime2.runtime.fs.readFile(localeCachePath)) : {};
649
+ let localeCachedMsgs = 0;
650
+ let localeTranslatedMsgs = 0;
651
+ for (const id in buildManifest.messages) {
652
+ const { value, chunksIds } = buildManifest.messages[id];
653
+ const chnks = chunksIds.length ? chunksIds : [locale];
654
+ for (const chunkId of chnks) {
655
+ const chunkPath = import_runtime2.runtime.path.resolve(
656
+ localeDirPath,
657
+ `${chunkId}.json`
658
+ );
659
+ const existsChunk = import_runtime2.runtime.fs.exists(chunkPath);
660
+ const chunk = existsChunk ? JSON.parse(import_runtime2.runtime.fs.readFile(chunkPath)) : {};
661
+ const localeValue = chunk[id] ?? cache[id];
662
+ if (!localeValue) {
663
+ untranslatedDictionary[id] = value;
664
+ localeTranslatedMsgs++;
665
+ } else {
666
+ translatedDictionary[id] = localeValue;
667
+ cache[id] = localeValue;
668
+ localeCachedMsgs++;
669
+ }
670
+ }
671
+ }
672
+ if (localeTranslatedMsgs > 0) {
673
+ const translation = await (0, import_translator.translate)({
674
+ ...config,
675
+ dictionary: untranslatedDictionary,
676
+ locale
677
+ });
678
+ translatedDictionary = (0, import_utils2.merge)(translation, translatedDictionary);
679
+ }
680
+ cache = {
681
+ ...cache,
682
+ ...translatedDictionary
683
+ };
684
+ import_runtime2.runtime.fs.remove(localeDirPath);
685
+ const dictionaries = (0, import_utils2.groupDictionaryByChunks)(
686
+ translatedDictionary,
687
+ buildManifest,
688
+ locale
689
+ );
690
+ await generate({
691
+ ...config,
692
+ dictionaries,
693
+ locale,
694
+ cwd
695
+ });
696
+ import_runtime2.runtime.fs.write(localeCachePath, (0, import_utils2.stringify)(cache));
697
+ totalTranslatedMsgs += localeTranslatedMsgs;
698
+ totalCachedMsgs += localeCachedMsgs;
699
+ logger.info(
700
+ `Locale ${locale.toUpperCase()}:`,
701
+ `${localeTranslatedMsgs} new messages translated, ${localeCachedMsgs} recovered from cache`
702
+ );
703
+ } catch (err) {
704
+ if (err instanceof Error) {
705
+ logger.error(
706
+ `${locale} translation:`,
707
+ `Error translating to ${locale}: ${err.message}
708
+ `
709
+ );
710
+ }
711
+ }
712
+ })
713
+ );
714
+ if (!totalTranslatedMsgs) {
715
+ return done("Everything up-to-date");
716
+ }
717
+ done(
718
+ `Translated ${totalTranslatedMsgs} messages, ${totalCachedMsgs} read from cache`
719
+ );
720
+ }
721
+ // Annotate the CommonJS export names for ESM import in node:
722
+ 0 && (module.exports = {
723
+ createTranslateCommand,
724
+ translateCmd
725
+ });
11
726
  //# sourceMappingURL=translate.js.map