@terai/dev 0.0.2 → 0.0.4

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,15 +1,999 @@
1
- "use strict";var Ie=Object.create;var F=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var De=(e,t)=>{for(var r in t)F(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ne(t))!Le.call(e,o)&&o!==r&&F(e,o,{get:()=>t[o],enumerable:!(n=ke(t,o))||n.enumerable});return e};var k=(e,t,r)=>(r=e!=null?Ie(Pe(e)):{},oe(t||!e||!e.__esModule?F(r,"default",{value:e,enumerable:!0}):r,e)),Se=e=>oe(F({},"__esModule",{value:!0}),e);var yt={};De(yt,{createExtractCommand:()=>pt,createInitCommand:()=>ht,createTranslateCommand:()=>vt,extractCmd:()=>Te,initCmd:()=>we,translateCmd:()=>Ee});module.exports=Se(yt);var B=require("@terai/runtime"),D=require("@inquirer/prompts");var Z=k(require("process"),1),Y=k(require("process"),1),he=k(require("os"),1),K=k(require("tty"),1),ie=(e=0)=>t=>`\x1B[${t+e}m`,ae=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,se=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,l={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]}},Ct=Object.keys(l.modifier),Fe=Object.keys(l.color),We=Object.keys(l.bgColor),Ot=[...Fe,...We];function _e(){let e=new Map;for(let[t,r]of Object.entries(l)){for(let[n,o]of Object.entries(r))l[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=l[n],e.set(o[0],o[1]);Object.defineProperty(l,t,{value:r,enumerable:!1})}return Object.defineProperty(l,"codes",{value:e,enumerable:!1}),l.color.close="\x1B[39m",l.bgColor.close="\x1B[49m",l.color.ansi=ie(),l.color.ansi256=ae(),l.color.ansi16m=se(),l.bgColor.ansi=ie(10),l.bgColor.ansi256=ae(10),l.bgColor.ansi16m=se(10),Object.defineProperties(l,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.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:t=>l.rgbToAnsi256(...l.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,o;if(t>=232)r=((t-232)*10+8)/255,n=r,o=r;else{t-=16;let s=t%36;r=Math.floor(t/36)/5,n=Math.floor(s/6)/5,o=s%6/5}let i=Math.max(r,n,o)*2;if(i===0)return 30;let a=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>l.ansi256ToAnsi(l.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>l.ansi256ToAnsi(l.hexToAnsi256(t)),enumerable:!1}}),l}var Ye=_e(),w=Ye;function y(e,t=globalThis.Deno?globalThis.Deno.args:Y.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(r+e),o=t.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:c}=Y.default,W;y("no-color")||y("no-colors")||y("color=false")||y("color=never")?W=0:(y("color")||y("colors")||y("color=true")||y("color=always"))&&(W=1);function Ge(){if("FORCE_COLOR"in c)return c.FORCE_COLOR==="true"?1:c.FORCE_COLOR==="false"?0:c.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(c.FORCE_COLOR,10),3)}function Ve(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ue(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let n=Ge();n!==void 0&&(W=n);let o=r?W:n;if(o===0)return 0;if(r){if(y("color=16m")||y("color=full")||y("color=truecolor"))return 3;if(y("color=256"))return 2}if("TF_BUILD"in c&&"AGENT_NAME"in c)return 1;if(e&&!t&&o===void 0)return 0;let i=o||0;if(c.TERM==="dumb")return i;if(Y.default.platform==="win32"){let a=he.default.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in c)return"GITHUB_ACTIONS"in c||"GITEA_ACTIONS"in c?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in c)||c.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in c)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(c.TEAMCITY_VERSION)?1:0;if(c.COLORTERM==="truecolor"||c.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in c){let a=Number.parseInt((c.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(c.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(c.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(c.TERM)||"COLORTERM"in c?1:i}function le(e,t={}){let r=Ue(e,{streamIsTTY:e&&e.isTTY,...t});return Ve(r)}var ze={stdout:le({isTTY:K.default.isatty(1)}),stderr:le({isTTY:K.default.isatty(2)})},Je=ze;function He(e,t,r){let n=e.indexOf(t);if(n===-1)return e;let o=t.length,i=0,a="";do a+=e.slice(i,n)+t+r,i=n+o,n=e.indexOf(t,i);while(n!==-1);return a+=e.slice(i),a}function Ke(e,t,r,n){let o=0,i="";do{let a=e[n-1]==="\r";i+=e.slice(o,a?n-1:n)+t+(a?`\r
2
- `:`
3
- `)+r,o=n+1,n=e.indexOf(`
4
- `,o)}while(n!==-1);return i+=e.slice(o),i}var{stdout:ce,stderr:ue}=Je,q=Symbol("GENERATOR"),E=Symbol("STYLER"),N=Symbol("IS_EMPTY"),fe=["ansi","ansi","ansi256","ansi16m"],R=Object.create(null),qe=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=ce?ce.level:0;e.level=t.level===void 0?r:t.level},Qe=e=>{let t=(...r)=>r.join(" ");return qe(t,e),Object.setPrototypeOf(t,P.prototype),t};function P(e){return Qe(e)}Object.setPrototypeOf(P.prototype,Function.prototype);for(let[e,t]of Object.entries(w))R[e]={get(){let r=_(this,X(t.open,t.close,this[E]),this[N]);return Object.defineProperty(this,e,{value:r}),r}};R.visible={get(){let e=_(this,this[E],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var Q=(e,t,r,...n)=>e==="rgb"?t==="ansi16m"?w[r].ansi16m(...n):t==="ansi256"?w[r].ansi256(w.rgbToAnsi256(...n)):w[r].ansi(w.rgbToAnsi(...n)):e==="hex"?Q("rgb",t,r,...w.hexToRgb(...n)):w[r][e](...n),Xe=["rgb","hex","ansi256"];for(let e of Xe){R[e]={get(){let{level:r}=this;return function(...n){let o=X(Q(e,fe[r],"color",...n),w.color.close,this[E]);return _(this,o,this[N])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);R[t]={get(){let{level:r}=this;return function(...n){let o=X(Q(e,fe[r],"bgColor",...n),w.bgColor.close,this[E]);return _(this,o,this[N])}}}}var Ze=Object.defineProperties(()=>{},{...R,level:{enumerable:!0,get(){return this[q].level},set(e){this[q].level=e}}}),X=(e,t,r)=>{let n,o;return r===void 0?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},_=(e,t,r)=>{let n=(...o)=>et(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Ze),n[q]=e,n[E]=t,n[N]=r,n},et=(e,t)=>{if(e.level<=0||!t)return e[N]?"":t;let r=e[E];if(r===void 0)return t;let{openAll:n,closeAll:o}=r;if(t.includes("\x1B"))for(;r!==void 0;)t=He(t,r.close,r.open),r=r.parent;let i=t.indexOf(`
5
- `);return i!==-1&&(t=Ke(t,o,n,i)),n+t+o};Object.defineProperties(P.prototype,R);var tt=P(),Tt=P({level:ue?ue.level:0}),p=tt;function T(e){return Z.default.stdout.write(e+`
6
- `)}function rt(e){return Z.default.stderr.write(e+`
7
- `)}function L(e,t,r,n,o,i){let a=(Array.isArray(i)?i:[i||""].filter(Boolean)).map(s=>r(s)).join("");e(`${" ".repeat(3)} ${t(n)} ${t(o)} ${a}`)}function nt(e,t){L(T,p.yellow,p.yellow,"\u25CF",e,t)}function me(e,t){L(T,p.yellow,p.dim,"\u25CF",e,t)}function ge(e,t){L(T,p.cyan,p.dim,"\u25FC",e,t)}function de(e){L(T,p.green,p.dim,"\u2714",e)}function ot(e,t){T(""),L(rt,p.red,p.red,"\u25B2",e,t)}function it(e,t){return T(`
8
- ${p.bgWhite(` ${p.whiteBright(e)} `)} ${p.bold(t)}
9
- `)}var H=e=>()=>{let t=performance.now();return r=>{let n=performance.now()-t;e(`${r} ${p.gray(`(${n.toFixed(2)}ms)`)}`)}},u={colors:p,log:T,heading:it,debug:me,info:ge,warn:nt,success:de,error:ot,time:{success:H(de),info:H(ge),debug:H(me)}};function G(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t]}function pe(){return typeof WeakMap<"u"?new WeakMap:at()}function at(){return{add:G,delete:G,get:G,set:G,has:function(e){return!1}}}var st=Object.prototype.hasOwnProperty,te=function(e,t){return st.call(e,t)};function ee(e,t){for(var r in t)te(t,r)&&(e[r]=t[r]);return e}var lt=/^[ \t]*(?:\r\n|\r|\n)/,ct=/(?:\r\n|\r|\n)[ \t]*$/,ut=/^(?:[\r\n]|$)/,ft=/(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/,mt=/^[ \t]*[\r\n][ \t\r\n]*$/;function ve(e,t,r){var n=0,o=e[0].match(ft);o&&(n=o[1].length);var i="(\\r\\n|\\r|\\n).{0,"+n+"}",a=new RegExp(i,"g");t&&(e=e.slice(1));var s=r.newline,g=r.trimLeadingNewline,h=r.trimTrailingNewline,m=typeof s=="string",f=e.length,x=e.map(function(v,M){return v=v.replace(a,"$1"),M===0&&g&&(v=v.replace(lt,"")),M===f-1&&h&&(v=v.replace(ct,"")),m&&(v=v.replace(/\r\n|\n|\r/g,function(Re){return s})),v});return x}function gt(e,t){for(var r="",n=0,o=e.length;n<o;n++)r+=e[n],n<o-1&&(r+=t[n]);return r}function dt(e){return te(e,"raw")&&te(e,"length")}function ye(e){var t=pe(),r=pe();function n(i){for(var a=[],s=1;s<arguments.length;s++)a[s-1]=arguments[s];if(dt(i)){var g=i,h=(a[0]===n||a[0]===C)&&mt.test(g[0])&&ut.test(g[1]),m=h?r:t,f=m.get(g);if(f||(f=ve(g,h,e),m.set(g,f)),a.length===0)return f[0];var x=gt(f,h?a.slice(1):a);return x}else return ye(ee(ee({},e),i||{}))}var o=ee(n,{string:function(i){return ve([i],!1,e)[0]}});return o}var C=ye({trimLeadingNewline:!0,trimTrailingNewline:!0});if(typeof module<"u")try{module.exports=C,Object.defineProperty(C,"__esModule",{value:!0}),C.default=C,C.outdent=C}catch{}var be=k(require("preferred-pm"));function ht(e,t){return e.command("init","Initialize config file").option("-f, --force","Force overwrite existing config files").option("--cwd <cwd>","Current working directory",{default:t}).action(we)}async function we({cwd:e,force:t}){u.heading("init","Initialize config file");let r=(0,B.findConfig)({cwd:e}),o=(await(0,be.default)(e))?.name??"npm",i=o==="npm"?"npm run":o;if(r&&!t)return u.log(C`
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/index.ts
31
+ var commands_exports = {};
32
+ __export(commands_exports, {
33
+ createExtractCommand: () => createExtractCommand,
34
+ createInitCommand: () => createInitCommand,
35
+ createTranslateCommand: () => createTranslateCommand,
36
+ extractCmd: () => extractCmd,
37
+ initCmd: () => initCmd,
38
+ translateCmd: () => translateCmd
39
+ });
40
+ module.exports = __toCommonJS(commands_exports);
41
+
42
+ // src/commands/init.ts
43
+ var import_runtime = require("@terai/runtime");
44
+ var import_prompts = require("@inquirer/prompts");
45
+
46
+ // ../logger/dist/index.mjs
47
+ var import_node_process = __toESM(require("process"), 1);
48
+ var import_node_process2 = __toESM(require("process"), 1);
49
+ var import_node_os = __toESM(require("os"), 1);
50
+ var import_node_tty = __toESM(require("tty"), 1);
51
+ var ANSI_BACKGROUND_OFFSET = 10;
52
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
53
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
54
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
55
+ var styles = {
56
+ modifier: {
57
+ reset: [0, 0],
58
+ // 21 isn't widely supported and 22 does the same thing
59
+ bold: [1, 22],
60
+ dim: [2, 22],
61
+ italic: [3, 23],
62
+ underline: [4, 24],
63
+ overline: [53, 55],
64
+ inverse: [7, 27],
65
+ hidden: [8, 28],
66
+ strikethrough: [9, 29]
67
+ },
68
+ color: {
69
+ black: [30, 39],
70
+ red: [31, 39],
71
+ green: [32, 39],
72
+ yellow: [33, 39],
73
+ blue: [34, 39],
74
+ magenta: [35, 39],
75
+ cyan: [36, 39],
76
+ white: [37, 39],
77
+ // Bright color
78
+ blackBright: [90, 39],
79
+ gray: [90, 39],
80
+ // Alias of `blackBright`
81
+ grey: [90, 39],
82
+ // Alias of `blackBright`
83
+ redBright: [91, 39],
84
+ greenBright: [92, 39],
85
+ yellowBright: [93, 39],
86
+ blueBright: [94, 39],
87
+ magentaBright: [95, 39],
88
+ cyanBright: [96, 39],
89
+ whiteBright: [97, 39]
90
+ },
91
+ bgColor: {
92
+ bgBlack: [40, 49],
93
+ bgRed: [41, 49],
94
+ bgGreen: [42, 49],
95
+ bgYellow: [43, 49],
96
+ bgBlue: [44, 49],
97
+ bgMagenta: [45, 49],
98
+ bgCyan: [46, 49],
99
+ bgWhite: [47, 49],
100
+ // Bright color
101
+ bgBlackBright: [100, 49],
102
+ bgGray: [100, 49],
103
+ // Alias of `bgBlackBright`
104
+ bgGrey: [100, 49],
105
+ // Alias of `bgBlackBright`
106
+ bgRedBright: [101, 49],
107
+ bgGreenBright: [102, 49],
108
+ bgYellowBright: [103, 49],
109
+ bgBlueBright: [104, 49],
110
+ bgMagentaBright: [105, 49],
111
+ bgCyanBright: [106, 49],
112
+ bgWhiteBright: [107, 49]
113
+ }
114
+ };
115
+ var modifierNames = Object.keys(styles.modifier);
116
+ var foregroundColorNames = Object.keys(styles.color);
117
+ var backgroundColorNames = Object.keys(styles.bgColor);
118
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
119
+ function assembleStyles() {
120
+ const codes = /* @__PURE__ */ new Map();
121
+ for (const [groupName, group] of Object.entries(styles)) {
122
+ for (const [styleName, style] of Object.entries(group)) {
123
+ styles[styleName] = {
124
+ open: `\x1B[${style[0]}m`,
125
+ close: `\x1B[${style[1]}m`
126
+ };
127
+ group[styleName] = styles[styleName];
128
+ codes.set(style[0], style[1]);
129
+ }
130
+ Object.defineProperty(styles, groupName, {
131
+ value: group,
132
+ enumerable: false
133
+ });
134
+ }
135
+ Object.defineProperty(styles, "codes", {
136
+ value: codes,
137
+ enumerable: false
138
+ });
139
+ styles.color.close = "\x1B[39m";
140
+ styles.bgColor.close = "\x1B[49m";
141
+ styles.color.ansi = wrapAnsi16();
142
+ styles.color.ansi256 = wrapAnsi256();
143
+ styles.color.ansi16m = wrapAnsi16m();
144
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
145
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
146
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
147
+ Object.defineProperties(styles, {
148
+ rgbToAnsi256: {
149
+ value(red, green, blue) {
150
+ if (red === green && green === blue) {
151
+ if (red < 8) {
152
+ return 16;
153
+ }
154
+ if (red > 248) {
155
+ return 231;
156
+ }
157
+ return Math.round((red - 8) / 247 * 24) + 232;
158
+ }
159
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
160
+ },
161
+ enumerable: false
162
+ },
163
+ hexToRgb: {
164
+ value(hex) {
165
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
166
+ if (!matches) {
167
+ return [0, 0, 0];
168
+ }
169
+ let [colorString] = matches;
170
+ if (colorString.length === 3) {
171
+ colorString = [...colorString].map((character) => character + character).join("");
172
+ }
173
+ const integer = Number.parseInt(colorString, 16);
174
+ return [
175
+ /* eslint-disable no-bitwise */
176
+ integer >> 16 & 255,
177
+ integer >> 8 & 255,
178
+ integer & 255
179
+ /* eslint-enable no-bitwise */
180
+ ];
181
+ },
182
+ enumerable: false
183
+ },
184
+ hexToAnsi256: {
185
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
186
+ enumerable: false
187
+ },
188
+ ansi256ToAnsi: {
189
+ value(code) {
190
+ if (code < 8) {
191
+ return 30 + code;
192
+ }
193
+ if (code < 16) {
194
+ return 90 + (code - 8);
195
+ }
196
+ let red;
197
+ let green;
198
+ let blue;
199
+ if (code >= 232) {
200
+ red = ((code - 232) * 10 + 8) / 255;
201
+ green = red;
202
+ blue = red;
203
+ } else {
204
+ code -= 16;
205
+ const remainder = code % 36;
206
+ red = Math.floor(code / 36) / 5;
207
+ green = Math.floor(remainder / 6) / 5;
208
+ blue = remainder % 6 / 5;
209
+ }
210
+ const value = Math.max(red, green, blue) * 2;
211
+ if (value === 0) {
212
+ return 30;
213
+ }
214
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
215
+ if (value === 2) {
216
+ result += 60;
217
+ }
218
+ return result;
219
+ },
220
+ enumerable: false
221
+ },
222
+ rgbToAnsi: {
223
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
224
+ enumerable: false
225
+ },
226
+ hexToAnsi: {
227
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
228
+ enumerable: false
229
+ }
230
+ });
231
+ return styles;
232
+ }
233
+ var ansiStyles = assembleStyles();
234
+ var ansi_styles_default = ansiStyles;
235
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process2.default.argv) {
236
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
237
+ const position = argv.indexOf(prefix + flag);
238
+ const terminatorPosition = argv.indexOf("--");
239
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
240
+ }
241
+ var { env } = import_node_process2.default;
242
+ var flagForceColor;
243
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
244
+ flagForceColor = 0;
245
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
246
+ flagForceColor = 1;
247
+ }
248
+ function envForceColor() {
249
+ if ("FORCE_COLOR" in env) {
250
+ if (env.FORCE_COLOR === "true") {
251
+ return 1;
252
+ }
253
+ if (env.FORCE_COLOR === "false") {
254
+ return 0;
255
+ }
256
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
257
+ }
258
+ }
259
+ function translateLevel(level) {
260
+ if (level === 0) {
261
+ return false;
262
+ }
263
+ return {
264
+ level,
265
+ hasBasic: true,
266
+ has256: level >= 2,
267
+ has16m: level >= 3
268
+ };
269
+ }
270
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
271
+ const noFlagForceColor = envForceColor();
272
+ if (noFlagForceColor !== void 0) {
273
+ flagForceColor = noFlagForceColor;
274
+ }
275
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
276
+ if (forceColor === 0) {
277
+ return 0;
278
+ }
279
+ if (sniffFlags) {
280
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
281
+ return 3;
282
+ }
283
+ if (hasFlag("color=256")) {
284
+ return 2;
285
+ }
286
+ }
287
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
288
+ return 1;
289
+ }
290
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
291
+ return 0;
292
+ }
293
+ const min = forceColor || 0;
294
+ if (env.TERM === "dumb") {
295
+ return min;
296
+ }
297
+ if (import_node_process2.default.platform === "win32") {
298
+ const osRelease = import_node_os.default.release().split(".");
299
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
300
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
301
+ }
302
+ return 1;
303
+ }
304
+ if ("CI" in env) {
305
+ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
306
+ return 3;
307
+ }
308
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
309
+ return 1;
310
+ }
311
+ return min;
312
+ }
313
+ if ("TEAMCITY_VERSION" in env) {
314
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
315
+ }
316
+ if (env.COLORTERM === "truecolor") {
317
+ return 3;
318
+ }
319
+ if (env.TERM === "xterm-kitty") {
320
+ return 3;
321
+ }
322
+ if ("TERM_PROGRAM" in env) {
323
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
324
+ switch (env.TERM_PROGRAM) {
325
+ case "iTerm.app": {
326
+ return version >= 3 ? 3 : 2;
327
+ }
328
+ case "Apple_Terminal": {
329
+ return 2;
330
+ }
331
+ }
332
+ }
333
+ if (/-256(color)?$/i.test(env.TERM)) {
334
+ return 2;
335
+ }
336
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
337
+ return 1;
338
+ }
339
+ if ("COLORTERM" in env) {
340
+ return 1;
341
+ }
342
+ return min;
343
+ }
344
+ function createSupportsColor(stream, options = {}) {
345
+ const level = _supportsColor(stream, {
346
+ streamIsTTY: stream && stream.isTTY,
347
+ ...options
348
+ });
349
+ return translateLevel(level);
350
+ }
351
+ var supportsColor = {
352
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
353
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
354
+ };
355
+ var supports_color_default = supportsColor;
356
+ function stringReplaceAll(string, substring, replacer) {
357
+ let index = string.indexOf(substring);
358
+ if (index === -1) {
359
+ return string;
360
+ }
361
+ const substringLength = substring.length;
362
+ let endIndex = 0;
363
+ let returnValue = "";
364
+ do {
365
+ returnValue += string.slice(endIndex, index) + substring + replacer;
366
+ endIndex = index + substringLength;
367
+ index = string.indexOf(substring, endIndex);
368
+ } while (index !== -1);
369
+ returnValue += string.slice(endIndex);
370
+ return returnValue;
371
+ }
372
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
373
+ let endIndex = 0;
374
+ let returnValue = "";
375
+ do {
376
+ const gotCR = string[index - 1] === "\r";
377
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
378
+ endIndex = index + 1;
379
+ index = string.indexOf("\n", endIndex);
380
+ } while (index !== -1);
381
+ returnValue += string.slice(endIndex);
382
+ return returnValue;
383
+ }
384
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
385
+ var GENERATOR = Symbol("GENERATOR");
386
+ var STYLER = Symbol("STYLER");
387
+ var IS_EMPTY = Symbol("IS_EMPTY");
388
+ var levelMapping = [
389
+ "ansi",
390
+ "ansi",
391
+ "ansi256",
392
+ "ansi16m"
393
+ ];
394
+ var styles2 = /* @__PURE__ */ Object.create(null);
395
+ var applyOptions = (object, options = {}) => {
396
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
397
+ throw new Error("The `level` option should be an integer from 0 to 3");
398
+ }
399
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
400
+ object.level = options.level === void 0 ? colorLevel : options.level;
401
+ };
402
+ var chalkFactory = (options) => {
403
+ const chalk2 = (...strings) => strings.join(" ");
404
+ applyOptions(chalk2, options);
405
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
406
+ return chalk2;
407
+ };
408
+ function createChalk(options) {
409
+ return chalkFactory(options);
410
+ }
411
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
412
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
413
+ styles2[styleName] = {
414
+ get() {
415
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
416
+ Object.defineProperty(this, styleName, { value: builder });
417
+ return builder;
418
+ }
419
+ };
420
+ }
421
+ styles2.visible = {
422
+ get() {
423
+ const builder = createBuilder(this, this[STYLER], true);
424
+ Object.defineProperty(this, "visible", { value: builder });
425
+ return builder;
426
+ }
427
+ };
428
+ var getModelAnsi = (model, level, type, ...arguments_) => {
429
+ if (model === "rgb") {
430
+ if (level === "ansi16m") {
431
+ return ansi_styles_default[type].ansi16m(...arguments_);
432
+ }
433
+ if (level === "ansi256") {
434
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
435
+ }
436
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
437
+ }
438
+ if (model === "hex") {
439
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
440
+ }
441
+ return ansi_styles_default[type][model](...arguments_);
442
+ };
443
+ var usedModels = ["rgb", "hex", "ansi256"];
444
+ for (const model of usedModels) {
445
+ styles2[model] = {
446
+ get() {
447
+ const { level } = this;
448
+ return function(...arguments_) {
449
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
450
+ return createBuilder(this, styler, this[IS_EMPTY]);
451
+ };
452
+ }
453
+ };
454
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
455
+ styles2[bgModel] = {
456
+ get() {
457
+ const { level } = this;
458
+ return function(...arguments_) {
459
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
460
+ return createBuilder(this, styler, this[IS_EMPTY]);
461
+ };
462
+ }
463
+ };
464
+ }
465
+ var proto = Object.defineProperties(() => {
466
+ }, {
467
+ ...styles2,
468
+ level: {
469
+ enumerable: true,
470
+ get() {
471
+ return this[GENERATOR].level;
472
+ },
473
+ set(level) {
474
+ this[GENERATOR].level = level;
475
+ }
476
+ }
477
+ });
478
+ var createStyler = (open, close, parent) => {
479
+ let openAll;
480
+ let closeAll;
481
+ if (parent === void 0) {
482
+ openAll = open;
483
+ closeAll = close;
484
+ } else {
485
+ openAll = parent.openAll + open;
486
+ closeAll = close + parent.closeAll;
487
+ }
488
+ return {
489
+ open,
490
+ close,
491
+ openAll,
492
+ closeAll,
493
+ parent
494
+ };
495
+ };
496
+ var createBuilder = (self, _styler, _isEmpty) => {
497
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
498
+ Object.setPrototypeOf(builder, proto);
499
+ builder[GENERATOR] = self;
500
+ builder[STYLER] = _styler;
501
+ builder[IS_EMPTY] = _isEmpty;
502
+ return builder;
503
+ };
504
+ var applyStyle = (self, string) => {
505
+ if (self.level <= 0 || !string) {
506
+ return self[IS_EMPTY] ? "" : string;
507
+ }
508
+ let styler = self[STYLER];
509
+ if (styler === void 0) {
510
+ return string;
511
+ }
512
+ const { openAll, closeAll } = styler;
513
+ if (string.includes("\x1B")) {
514
+ while (styler !== void 0) {
515
+ string = stringReplaceAll(string, styler.close, styler.open);
516
+ styler = styler.parent;
517
+ }
518
+ }
519
+ const lfIndex = string.indexOf("\n");
520
+ if (lfIndex !== -1) {
521
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
522
+ }
523
+ return openAll + string + closeAll;
524
+ };
525
+ Object.defineProperties(createChalk.prototype, styles2);
526
+ var chalk = createChalk();
527
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
528
+ var source_default = chalk;
529
+ function log(message) {
530
+ return import_node_process.default.stdout.write(`${message}
531
+ `);
532
+ }
533
+ function logError(message) {
534
+ return import_node_process.default.stderr.write(`${message}
535
+ `);
536
+ }
537
+ function logBullet(logger2, colorizePrefix, colorizeText, symbol, prefix, text) {
538
+ const textParts = Array.isArray(text) ? text : [text || ""].filter(Boolean);
539
+ const formattedText = textParts.map((textPart) => colorizeText(textPart)).join("");
540
+ logger2(
541
+ `${" ".repeat(3)} ${colorizePrefix(symbol)} ${colorizePrefix(
542
+ prefix
543
+ )} ${formattedText}`
544
+ );
545
+ }
546
+ function warn(prefix, text) {
547
+ logBullet(log, source_default.yellow, source_default.yellow, "\u25CF", prefix, text);
548
+ }
549
+ function debug(prefix, text) {
550
+ logBullet(log, source_default.yellow, source_default.dim, "\u25CF", prefix, text);
551
+ }
552
+ function info(prefix, text) {
553
+ logBullet(log, source_default.cyan, source_default.dim, "\u25FC", prefix, text);
554
+ }
555
+ function success(text) {
556
+ logBullet(log, source_default.green, source_default.dim, "\u2714", text);
557
+ }
558
+ function error(prefix, text) {
559
+ log("");
560
+ logBullet(logError, source_default.red, source_default.red, "\u25B2", prefix, text);
561
+ }
562
+ function heading(heading2, description) {
563
+ return log(
564
+ `
565
+ ${source_default.bgWhite(` ${source_default.whiteBright(heading2)} `)} ${source_default.bold(
566
+ description
567
+ )}
568
+ `
569
+ );
570
+ }
571
+ var timing = (fn) => () => {
572
+ const start = performance.now();
573
+ return (msg) => {
574
+ const end = performance.now();
575
+ const ms = end - start;
576
+ fn(`${msg} ${source_default.gray(`(${ms.toFixed(2)}ms)`)}`);
577
+ };
578
+ };
579
+ var logger = {
580
+ colors: source_default,
581
+ log,
582
+ heading,
583
+ debug,
584
+ info,
585
+ warn,
586
+ success,
587
+ error,
588
+ time: {
589
+ success: timing(success),
590
+ info: timing(info),
591
+ debug: timing(debug)
592
+ }
593
+ };
594
+
595
+ // ../../node_modules/.pnpm/outdent@0.8.0/node_modules/outdent/lib-module/index.js
596
+ function noop() {
597
+ var args = [];
598
+ for (var _i = 0; _i < arguments.length; _i++) {
599
+ args[_i] = arguments[_i];
600
+ }
601
+ }
602
+ function createWeakMap() {
603
+ if (typeof WeakMap !== "undefined") {
604
+ return /* @__PURE__ */ new WeakMap();
605
+ } else {
606
+ return fakeSetOrMap();
607
+ }
608
+ }
609
+ function fakeSetOrMap() {
610
+ return {
611
+ add: noop,
612
+ delete: noop,
613
+ get: noop,
614
+ set: noop,
615
+ has: function(k) {
616
+ return false;
617
+ }
618
+ };
619
+ }
620
+ var hop = Object.prototype.hasOwnProperty;
621
+ var has = function(obj, prop) {
622
+ return hop.call(obj, prop);
623
+ };
624
+ function extend(target, source) {
625
+ for (var prop in source) {
626
+ if (has(source, prop)) {
627
+ target[prop] = source[prop];
628
+ }
629
+ }
630
+ return target;
631
+ }
632
+ var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
633
+ var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
634
+ var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
635
+ var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
636
+ var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
637
+ function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
638
+ var indentationLevel = 0;
639
+ var match = strings[0].match(reDetectIndentation);
640
+ if (match) {
641
+ indentationLevel = match[1].length;
642
+ }
643
+ var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
644
+ var reMatchIndent = new RegExp(reSource, "g");
645
+ if (firstInterpolatedValueSetsIndentationLevel) {
646
+ strings = strings.slice(1);
647
+ }
648
+ var newline = options.newline, trimLeadingNewline = options.trimLeadingNewline, trimTrailingNewline = options.trimTrailingNewline;
649
+ var normalizeNewlines = typeof newline === "string";
650
+ var l = strings.length;
651
+ var outdentedStrings = strings.map(function(v, i) {
652
+ v = v.replace(reMatchIndent, "$1");
653
+ if (i === 0 && trimLeadingNewline) {
654
+ v = v.replace(reLeadingNewline, "");
655
+ }
656
+ if (i === l - 1 && trimTrailingNewline) {
657
+ v = v.replace(reTrailingNewline, "");
658
+ }
659
+ if (normalizeNewlines) {
660
+ v = v.replace(/\r\n|\n|\r/g, function(_) {
661
+ return newline;
662
+ });
663
+ }
664
+ return v;
665
+ });
666
+ return outdentedStrings;
667
+ }
668
+ function concatStringsAndValues(strings, values) {
669
+ var ret = "";
670
+ for (var i = 0, l = strings.length; i < l; i++) {
671
+ ret += strings[i];
672
+ if (i < l - 1) {
673
+ ret += values[i];
674
+ }
675
+ }
676
+ return ret;
677
+ }
678
+ function isTemplateStringsArray(v) {
679
+ return has(v, "raw") && has(v, "length");
680
+ }
681
+ function createInstance(options) {
682
+ var arrayAutoIndentCache = createWeakMap();
683
+ var arrayFirstInterpSetsIndentCache = createWeakMap();
684
+ function outdent(stringsOrOptions) {
685
+ var values = [];
686
+ for (var _i = 1; _i < arguments.length; _i++) {
687
+ values[_i - 1] = arguments[_i];
688
+ }
689
+ if (isTemplateStringsArray(stringsOrOptions)) {
690
+ var strings = stringsOrOptions;
691
+ var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]);
692
+ var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
693
+ var renderedArray = cache.get(strings);
694
+ if (!renderedArray) {
695
+ renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
696
+ cache.set(strings, renderedArray);
697
+ }
698
+ if (values.length === 0) {
699
+ return renderedArray[0];
700
+ }
701
+ var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
702
+ return rendered;
703
+ } else {
704
+ return createInstance(extend(extend({}, options), stringsOrOptions || {}));
705
+ }
706
+ }
707
+ var fullOutdent = extend(outdent, {
708
+ string: function(str) {
709
+ return _outdentArray([str], false, options)[0];
710
+ }
711
+ });
712
+ return fullOutdent;
713
+ }
714
+ var defaultOutdent = createInstance({
715
+ trimLeadingNewline: true,
716
+ trimTrailingNewline: true
717
+ });
718
+ if (typeof module !== "undefined") {
719
+ try {
720
+ module.exports = defaultOutdent;
721
+ Object.defineProperty(defaultOutdent, "__esModule", { value: true });
722
+ defaultOutdent.default = defaultOutdent;
723
+ defaultOutdent.outdent = defaultOutdent;
724
+ } catch (e) {
725
+ }
726
+ }
727
+
728
+ // src/commands/init.ts
729
+ var import_preferred_pm = __toESM(require("preferred-pm"));
730
+ function createInitCommand(cli, cwd) {
731
+ return cli.command("init", "Initialize config file").option("-f, --force", "Force overwrite existing config files").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(initCmd);
732
+ }
733
+ async function initCmd({ cwd, force }) {
734
+ logger.heading("init", "Initialize config file");
735
+ const configFile = (0, import_runtime.findConfig)({ cwd });
736
+ const pmResult = await (0, import_preferred_pm.default)(cwd);
737
+ const pm = pmResult?.name ?? "npm";
738
+ const cmd = pm === "npm" ? "npm run" : pm;
739
+ if (configFile && !force) {
740
+ return logger.log(
741
+ defaultOutdent`
10
742
  It looks like you already have terai created.
11
- You can now run ${u.colors.cyan(`'${i} terai extract --watch'`)}
12
- `);let a=await(0,D.input)({message:"What locale do you use for development?",default:"en"}),s=await(0,D.input)({message:"Where do you want to place your generated files?",default:"./locale-system"}),g=await(0,D.select)({message:"Would you like to use any of these templates? (recommended)",choices:[{name:"No",value:null},{name:"Next",value:"next"},{name:"Vite",value:"vite"}]}),h=u.time.success();await(0,B.setupConfig)({cwd:e,projectLocale:a,outDir:s}),g&&await(0,B.setupTemplate)({cwd:e,outDir:s,framework:g}),h("Config file created"),u.log("\u{1F680} You are set up to start using terai! Thanks for choosing it.")}var Ce=require("perfect-debounce"),Oe=require("@terai/extractor");var V=require("@terai/runtime"),xe=require("@terai/utils");async function U({dictionaries:e,locale:t,cwd:r,outDir:n}){let o=V.runtime.path.resolve(r,n,t),i=[];for(let a in e){let s=V.runtime.path.resolve(o,a+".json"),g=e[a],h=(0,xe.stringify)(g);V.runtime.fs.write(s,h),i.push(h)}return i}var b=require("@terai/runtime");var j=require("@terai/utils");function pt(e,t){return e.command("extract","Statically extract messages from your project").option("-w, --watch","Watch files and rebuild").option("--cwd <cwd>","Current working directory",{default:t}).action(Te)}async function Te(e){u.heading("extract","Statically extract messages from your project");let t=u.time.success(),r=await(0,b.loadConfig)(e),n=b.runtime.fs.glob({...r,cwd:e.cwd}),o=b.runtime.path.resolve(e.cwd,r.outDir),i=b.runtime.path.resolve(o,r.projectLocale),a=b.runtime.path.resolve(o,".terai","locale-manifest.json");u.info("Scan:","Processing files...");async function s(h=n){let m=await(0,Oe.extract)({...r,filesPaths:h,cwd:e.cwd}),f=(0,j.convertExtractedMessagesToDictionary)(m),x={messages:m},v=(0,j.groupDictionaryByChunks)(f,x,r.projectLocale);return b.runtime.fs.remove(b.runtime.path.resolve(i)),await U({...r,dictionaries:v,locale:r.projectLocale,cwd:e.cwd}),b.runtime.fs.write(a,(0,j.stringify)(x)),Object.keys(f).length}u.info("Extraction:","Extracting messages...");let g=await s();t(`Extracted ${g} messages`),e.watch&&(u.log(""),u.info("Watch:",`Watching files for changes...
13
- `),b.runtime.fs.watch({...r,...e}).on("change",(0,Ce.debounce)(async()=>{let m=u.time.success();u.info("Extraction:","Files changed, processing messages...");let f=await s();m(`Extracted ${f} messages`),u.log("")})))}var d=require("@terai/runtime");var Me=require("@terai/translator"),$=require("@terai/utils");function vt(e,t){return e.command("translate","Translate messages from your project").option("--cwd <cwd>","Current working directory",{default:t}).action(Ee)}async function Ee({cwd:e}){u.heading("translate","Translate messages from your project");let t=u.time.success(),r=await(0,d.loadConfig)({cwd:e}),n=d.runtime.path.resolve(e,r.outDir),o=d.runtime.path.resolve(e,r.outDir,".terai"),i=d.runtime.path.resolve(o,"locale-manifest.json");if(!d.runtime.fs.exists(i))return u.error("translate",`No locale-manifest.json found in ${o}. Please run "extract" first.`);let s=JSON.parse(d.runtime.fs.readFile(i)),g=0,h=0;if(await Promise.all(r.outLocales.map(async m=>{try{let f={},x={},v=d.runtime.path.resolve(n,m),M=d.runtime.path.resolve(o,"cache",`${m}.cache.json`),I=d.runtime.fs.exists(M)?JSON.parse(d.runtime.fs.readFile(M)):{},z=0,S=0;for(let O in s.messages){let{value:Be,chunksIds:re}=s.messages[O],je=re.length?re:[m];for(let $e of je){let ne=d.runtime.path.resolve(v,`${$e}.json`),J=(d.runtime.fs.exists(ne)?JSON.parse(d.runtime.fs.readFile(ne)):{})[O]??I[O];J?(f[O]=J,I[O]=J,z++):(x[O]=Be,S++)}}if(S>0){let O=await(0,Me.translate)({...r,dictionary:x,locale:m});f=(0,$.merge)(O,f)}I={...I,...f},d.runtime.fs.remove(v);let Ae=(0,$.groupDictionaryByChunks)(f,s,m);await U({...r,dictionaries:Ae,locale:m,cwd:e}),d.runtime.fs.write(M,(0,$.stringify)(I)),g+=S,h+=z,u.info(`Locale ${m.toUpperCase()}:`,`${S} new messages translated, ${z} recovered from cache`)}catch(f){f instanceof Error&&u.error(`${m} translation:`,`Error translating to ${m}: ${f.message}
14
- `)}})),!g)return t("Everything up-to-date");t(`Translated ${g} messages, ${h} read from cache`)}0&&(module.exports={createExtractCommand,createInitCommand,createTranslateCommand,extractCmd,initCmd,translateCmd});
743
+ You can now run ${logger.colors.cyan(`'${cmd} terai extract --watch'`)}
744
+ `
745
+ );
746
+ }
747
+ const projectLocale = await (0, import_prompts.input)({
748
+ message: "What locale do you use for development?",
749
+ default: "en"
750
+ });
751
+ const outDir = await (0, import_prompts.input)({
752
+ message: "Where do you want to place your generated files?",
753
+ default: "./locale-system"
754
+ });
755
+ const framework = await (0, import_prompts.select)({
756
+ message: "Would you like to use any of these templates? (recommended)",
757
+ choices: [
758
+ {
759
+ name: "No",
760
+ value: null
761
+ },
762
+ {
763
+ name: "Next",
764
+ value: "next"
765
+ },
766
+ {
767
+ name: "Vite",
768
+ value: "vite"
769
+ }
770
+ ]
771
+ });
772
+ const done = logger.time.success();
773
+ await (0, import_runtime.setupConfig)({ cwd, projectLocale, outDir });
774
+ if (framework) {
775
+ await (0, import_runtime.setupTemplate)({ cwd, outDir, framework });
776
+ }
777
+ done("Config file created");
778
+ logger.log("\u{1F680} You are set up to start using Terai! Thanks for choosing it.");
779
+ }
780
+
781
+ // src/commands/extract.ts
782
+ var import_perfect_debounce = require("perfect-debounce");
783
+ var import_extractor = require("@terai/extractor");
784
+
785
+ // ../generator/dist/index.mjs
786
+ var import_runtime2 = require("@terai/runtime");
787
+ var import_utils = require("@terai/utils");
788
+ async function generate({
789
+ dictionaries,
790
+ locale,
791
+ cwd,
792
+ outDir
793
+ }) {
794
+ const folderPath = import_runtime2.runtime.path.resolve(cwd, outDir, locale);
795
+ const output = [];
796
+ for (const id in dictionaries) {
797
+ const fileDir = import_runtime2.runtime.path.resolve(folderPath, `${id}.json`);
798
+ const fileContent = dictionaries[id];
799
+ const idOutput = (0, import_utils.stringify)(fileContent);
800
+ import_runtime2.runtime.fs.write(fileDir, idOutput);
801
+ output.push(idOutput);
802
+ }
803
+ return output;
804
+ }
805
+
806
+ // src/commands/extract.ts
807
+ var import_runtime3 = require("@terai/runtime");
808
+ var import_utils2 = require("@terai/utils");
809
+ function createExtractCommand(cli, cwd) {
810
+ return cli.command("extract", "Statically extract messages from your project").option("-w, --watch", "Watch files and rebuild").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(extractCmd);
811
+ }
812
+ async function extractCmd(options) {
813
+ logger.heading("extract", "Statically extract messages from your project");
814
+ const done = logger.time.success();
815
+ const config = await (0, import_runtime3.loadConfig)(options);
816
+ const filesPaths = import_runtime3.runtime.fs.glob({
817
+ ...config,
818
+ cwd: options.cwd
819
+ });
820
+ const outDirPath = import_runtime3.runtime.path.resolve(options.cwd, config.outDir);
821
+ const projectLocalePath = import_runtime3.runtime.path.resolve(
822
+ outDirPath,
823
+ config.projectLocale
824
+ );
825
+ const manifestPath = import_runtime3.runtime.path.resolve(
826
+ outDirPath,
827
+ ".terai",
828
+ "locale-manifest.json"
829
+ );
830
+ logger.info("Scan:", "Processing files...");
831
+ async function extractor(files = filesPaths) {
832
+ const extractedMessages = await (0, import_extractor.extract)({
833
+ ...config,
834
+ filesPaths: files,
835
+ cwd: options.cwd
836
+ });
837
+ const dictionary = (0, import_utils2.convertExtractedMessagesToDictionary)(extractedMessages);
838
+ const manifest = {
839
+ messages: extractedMessages
840
+ };
841
+ const dictionaries = (0, import_utils2.groupDictionaryByChunks)(
842
+ dictionary,
843
+ manifest,
844
+ config.projectLocale
845
+ );
846
+ import_runtime3.runtime.fs.remove(import_runtime3.runtime.path.resolve(projectLocalePath));
847
+ await generate({
848
+ ...config,
849
+ dictionaries,
850
+ locale: config.projectLocale,
851
+ cwd: options.cwd
852
+ });
853
+ import_runtime3.runtime.fs.write(manifestPath, (0, import_utils2.stringify)(manifest));
854
+ return Object.keys(dictionary).length;
855
+ }
856
+ logger.info("Extraction:", "Extracting messages...");
857
+ const msgCount = await extractor();
858
+ done(`Extracted ${msgCount} messages`);
859
+ if (options.watch) {
860
+ logger.log("");
861
+ logger.info("Watch:", "Watching files for changes...\n");
862
+ const configWatcher = import_runtime3.runtime.fs.watch({
863
+ ...config,
864
+ ...options
865
+ });
866
+ configWatcher.on(
867
+ "change",
868
+ (0, import_perfect_debounce.debounce)(async () => {
869
+ const done2 = logger.time.success();
870
+ logger.info("Extraction:", "Files changed, processing messages...");
871
+ const msgCount2 = await extractor();
872
+ done2(`Extracted ${msgCount2} messages`);
873
+ logger.log("");
874
+ })
875
+ );
876
+ }
877
+ }
878
+
879
+ // src/commands/translate.ts
880
+ var import_runtime4 = require("@terai/runtime");
881
+ var import_translator = require("@terai/translator");
882
+ var import_utils3 = require("@terai/utils");
883
+ function createTranslateCommand(cli, cwd) {
884
+ return cli.command("translate", "Translate messages from your project").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(translateCmd);
885
+ }
886
+ async function translateCmd({ cwd }) {
887
+ logger.heading("translate", "Translate messages from your project");
888
+ const done = logger.time.success();
889
+ const config = await (0, import_runtime4.loadConfig)({ cwd });
890
+ const outDirPath = import_runtime4.runtime.path.resolve(cwd, config.outDir);
891
+ const tmuDirPath = import_runtime4.runtime.path.resolve(cwd, config.outDir, ".terai");
892
+ const manifestPath = import_runtime4.runtime.path.resolve(tmuDirPath, "locale-manifest.json");
893
+ const existsManifest = import_runtime4.runtime.fs.exists(manifestPath);
894
+ if (!existsManifest) {
895
+ return logger.error(
896
+ "translate",
897
+ `No locale-manifest.json found in ${tmuDirPath}. Please run "extract" first.`
898
+ );
899
+ }
900
+ const buildManifest = JSON.parse(
901
+ import_runtime4.runtime.fs.readFile(manifestPath)
902
+ );
903
+ let totalTranslatedMsgs = 0;
904
+ let totalCachedMsgs = 0;
905
+ await Promise.all(
906
+ config.outLocales.map(async (locale) => {
907
+ try {
908
+ let translatedDictionary = {};
909
+ const untranslatedDictionary = {};
910
+ const localeDirPath = import_runtime4.runtime.path.resolve(outDirPath, locale);
911
+ const localeCachePath = import_runtime4.runtime.path.resolve(
912
+ tmuDirPath,
913
+ "cache",
914
+ `${locale}.cache.json`
915
+ );
916
+ const cacheExists = import_runtime4.runtime.fs.exists(localeCachePath);
917
+ let cache = cacheExists ? JSON.parse(import_runtime4.runtime.fs.readFile(localeCachePath)) : {};
918
+ let localeCachedMsgs = 0;
919
+ let localeTranslatedMsgs = 0;
920
+ for (const id in buildManifest.messages) {
921
+ const { value, chunksIds } = buildManifest.messages[id];
922
+ const chnks = chunksIds.length ? chunksIds : [locale];
923
+ for (const chunkId of chnks) {
924
+ const chunkPath = import_runtime4.runtime.path.resolve(
925
+ localeDirPath,
926
+ `${chunkId}.json`
927
+ );
928
+ const existsChunk = import_runtime4.runtime.fs.exists(chunkPath);
929
+ const chunk = existsChunk ? JSON.parse(import_runtime4.runtime.fs.readFile(chunkPath)) : {};
930
+ const localeValue = chunk[id] ?? cache[id];
931
+ if (!localeValue) {
932
+ untranslatedDictionary[id] = value;
933
+ localeTranslatedMsgs++;
934
+ } else {
935
+ translatedDictionary[id] = localeValue;
936
+ cache[id] = localeValue;
937
+ localeCachedMsgs++;
938
+ }
939
+ }
940
+ }
941
+ if (localeTranslatedMsgs > 0) {
942
+ const translation = await (0, import_translator.translate)({
943
+ ...config,
944
+ dictionary: untranslatedDictionary,
945
+ locale
946
+ });
947
+ translatedDictionary = (0, import_utils3.merge)(translation, translatedDictionary);
948
+ }
949
+ cache = {
950
+ ...cache,
951
+ ...translatedDictionary
952
+ };
953
+ import_runtime4.runtime.fs.remove(localeDirPath);
954
+ const dictionaries = (0, import_utils3.groupDictionaryByChunks)(
955
+ translatedDictionary,
956
+ buildManifest,
957
+ locale
958
+ );
959
+ await generate({
960
+ ...config,
961
+ dictionaries,
962
+ locale,
963
+ cwd
964
+ });
965
+ import_runtime4.runtime.fs.write(localeCachePath, (0, import_utils3.stringify)(cache));
966
+ totalTranslatedMsgs += localeTranslatedMsgs;
967
+ totalCachedMsgs += localeCachedMsgs;
968
+ logger.info(
969
+ `Locale ${locale.toUpperCase()}:`,
970
+ `${localeTranslatedMsgs} new messages translated, ${localeCachedMsgs} recovered from cache`
971
+ );
972
+ } catch (err) {
973
+ if (err instanceof Error) {
974
+ logger.error(
975
+ `${locale} translation:`,
976
+ `Error translating to ${locale}: ${err.message}
977
+ `
978
+ );
979
+ }
980
+ }
981
+ })
982
+ );
983
+ if (!totalTranslatedMsgs) {
984
+ return done("Everything up-to-date");
985
+ }
986
+ done(
987
+ `Translated ${totalTranslatedMsgs} messages, ${totalCachedMsgs} read from cache`
988
+ );
989
+ }
990
+ // Annotate the CommonJS export names for ESM import in node:
991
+ 0 && (module.exports = {
992
+ createExtractCommand,
993
+ createInitCommand,
994
+ createTranslateCommand,
995
+ extractCmd,
996
+ initCmd,
997
+ translateCmd
998
+ });
15
999
  //# sourceMappingURL=index.js.map