@voerkai18n/utils
Version:
829 lines (806 loc) • 24.9 kB
JavaScript
import path8 from 'node:path';
import t2 from 'node:fs';
import axios from 'axios';
/***
* ---=== VoerkaI18n Utils ===---
* https://zhangfisher.github.io/voerka-i18n/
*/
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
get: (a3, b2) => (typeof require !== "undefined" ? require : a3)[b2]
}) : x2)(function(x2) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x2 + '" is not supported');
});
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-OTHYD4AD.mjs
var _a;
var e = (_a = class extends Error {
}, __name(_a, "e"), _a);
function t(o3 = "./", e3 = false) {
path8.isAbsolute(o3) || (o3 = path8.join(process.cwd(), o3 || "./"));
try {
let i3 = e3 ? path8.join(o3, "..", "package.json") : path8.join(o3, "package.json");
if (t2.existsSync(i3)) return path8.dirname(i3);
let n2 = path8.dirname(o3);
return n2 === o3 ? null : t(n2, false);
} catch {
throw new e();
}
}
__name(t, "t");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-R42SWOGE.mjs
var o = ((a3) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(a3, { get: /* @__PURE__ */ __name((b2, c4) => (typeof __require < "u" ? __require : b2)[c4], "get") }) : a3)(function(a3) {
if (typeof __require < "u") return __require.apply(this, arguments);
throw Error('Dynamic require of "' + a3 + '" is not supported');
});
function g(e3, a$2 = true) {
let r4 = a$2 ? t(e3) : e3 || process.cwd();
try {
return o(path8.join(r4, "package.json"));
} catch {
return;
}
}
__name(g, "g");
// src/getSettingsFromPackageJson.ts
function getSettingsFromPackageJson(entry) {
const pkg = g(entry, false);
const settings = {
entry: void 0
};
if (typeof pkg == "object" && "voerkai18n" in pkg) {
Object.assign(settings, pkg.voerkai18n);
}
return settings;
}
__name(getSettingsFromPackageJson, "getSettingsFromPackageJson");
function getDefaultLanguageDir() {
const cwd = process.env.INIT_CWD || process.cwd();
const srcPath = path8.join(cwd, "src");
if (t2.existsSync(srcPath)) {
return path8.join(srcPath, "languages");
} else {
return path8.join(cwd, "languages");
}
}
__name(getDefaultLanguageDir, "getDefaultLanguageDir");
// src/getLanguageDir.ts
function getLanguageDir(options) {
const { location, autoCreate, absolute } = Object.assign({
autoCreate: true,
absolute: true
}, options);
const cwd = process.env.INIT_CWD || process.cwd();
try {
const { entry } = getSettingsFromPackageJson(location);
let langDir = entry || getDefaultLanguageDir();
langDir = path8.isAbsolute(langDir) ? langDir : path8.join(cwd, langDir);
if (autoCreate && !t2.existsSync(langDir)) {
t2.mkdirSync(langDir, {
recursive: true
});
}
return absolute ? langDir : path8.relative(cwd, langDir);
} catch (e3) {
console.error("\u83B7\u53D6\u8BED\u8A00\u6587\u4EF6\u5939\u5931\u8D25", e3);
return "src/languages";
}
}
__name(getLanguageDir, "getLanguageDir");
// src/getIdMap.ts
function getIdMap(idMapFile) {
if (!idMapFile) {
const langDir = getLanguageDir({
autoCreate: false,
absolute: true
});
idMapFile = path8.join(langDir, "idMap.json");
}
try {
if (t2.existsSync(idMapFile)) {
return JSON.parse(t2.readFileSync(idMapFile, {
encoding: "utf-8"
}));
}
} catch {
}
}
__name(getIdMap, "getIdMap");
function isVoerkaI18nInstalled() {
const langDir = getLanguageDir({
autoCreate: false
});
const settingsFile = path8.join(langDir, "settings.json");
return t2.existsSync(settingsFile);
}
__name(isVoerkaI18nInstalled, "isVoerkaI18nInstalled");
// src/escapeRegex.ts
function escapeRegex(input) {
return input.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
__name(escapeRegex, "escapeRegex");
// src/applyIdMap.ts
var getMessageRegex = /* @__PURE__ */ __name((names = [
"t"
]) => {
return new RegExp(`([ \\t\\^;\\{\\(\\,=\\'\\"\\.\\[\\|\\+\\>])(${names.map((name) => escapeRegex(name)).join("|")})\\(\\s*(["']{1})(.*?)(\\3)`, "gm");
}, "getMessageRegex");
var getComponentRegex = /* @__PURE__ */ __name((tags = [
"Translate"
]) => {
return new RegExp(`<(${tags.map((tag) => escapeRegex(tag)).join("|")})(\\s+[^>]*)(?<![:@#%&*])message\\s*=\\s*(?:"([^"]+)"|{["'\`](.+?)["'\`]}|{\`([^\`]+)\`})`, "gm");
}, "getComponentRegex");
function applyIdMap(code, idMap, options) {
const { tFuncNames, tComponentNames } = Object.assign({
tFuncNames: [
"t",
"$t"
],
tComponentNames: [
"Translate",
"v-translate"
]
}, options);
return code.replace(getMessageRegex(tFuncNames), (matched, pre, tName, _, message, n2) => {
return `${pre}${tName}('${idMap[message] || message}'`;
}).replace(getComponentRegex(tComponentNames), (_, tagName, attrs, message) => {
return `<${tagName}${attrs}message="${idMap[message] || message}"`;
});
}
__name(applyIdMap, "applyIdMap");
function getVoerkaI18nSettings() {
const packageJsonSettings = getSettingsFromPackageJson();
const langDir = getLanguageDir({
autoCreate: false
});
const settings = Object.assign({
namespaces: {}
}, packageJsonSettings);
const settingFile = path8.join(langDir, "settings.json");
if (t2.existsSync(settingFile)) {
Object.assign(settings, __require(settingFile));
}
settings.defaultLanguage = (settings.languages || []).find((lang) => lang.default)?.name;
settings.activeLanguage = (settings.languages || []).find((lang) => lang.active)?.name;
return settings;
}
__name(getVoerkaI18nSettings, "getVoerkaI18nSettings");
// src/getBcp47LanguageApi.ts
function getBcp47LanguageApi(osLocale = "en-US") {
try {
return __require(`bcp47-language-tags/${osLocale.split("-")[0]}`);
} catch (e3) {
return __require("bcp47-language-tags/en");
}
}
__name(getBcp47LanguageApi, "getBcp47LanguageApi");
function inNamespace(filePath, nsPath) {
return !path8.relative(nsPath, filePath).startsWith("..");
}
__name(inNamespace, "inNamespace");
function getFileNamespace(file, namespaces) {
if (!namespaces) return "default";
if (!file) return "default";
const cwd = process.env.INIT_CWD || process.cwd();
file = path8.isAbsolute(file) ? file : path8.join(cwd, file);
for (let [name, value] of Object.entries(namespaces)) {
if (typeof value === "function") {
if (value(file) === true) return name;
} else {
const paths = Array.isArray(value) ? value : [
value
];
for (let nsPath of paths) {
nsPath = path8.isAbsolute(nsPath) ? nsPath : path8.join(cwd, nsPath);
if (inNamespace(file, nsPath)) {
return name;
}
}
}
}
return "default";
}
__name(getFileNamespace, "getFileNamespace");
function getApi(name, defaultValue) {
const langDir = getLanguageDir();
const apikeyFile = path8.join(langDir, "./api.json");
if (t2.existsSync(apikeyFile)) {
const apikeys = JSON.parse(t2.readFileSync(apikeyFile, "utf-8"));
return apikeys[name] || defaultValue;
}
return defaultValue;
}
__name(getApi, "getApi");
function removeCodeBlock(text) {
return text.replace(/^```\w?.*?[\n\r]+/gm, "").replace(/```\s*$/gm, "");
}
__name(removeCodeBlock, "removeCodeBlock");
async function aiQuestion(prompt, options) {
const { apiUrl, apiKey, temperature, model, roles } = Object.assign({
temperature: 1,
roles: []
}, options);
const request = {
messages: [
{
role: "user",
content: prompt
},
...roles
],
model,
temperature
};
let data;
try {
const res = await axios.post(apiUrl, request, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"Cache-Control": "no-cache"
}
});
if (res.status !== 200) {
throw new Error(`API request failed with status ${res.status}: ${res.statusText}`);
}
data = res.data;
const result = removeCodeBlock(data.choices[0].message.content.trim());
return result;
} catch (err) {
throw new Error(`Error when calling AI api: ${err.message}`);
}
}
__name(aiQuestion, "aiQuestion");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-NVXIWUQI.mjs
function c2(o3) {
try {
let e3 = g(o3);
if (e3) return e3.type == "module" ? "esm" : "cjs";
} catch {
}
}
__name(c2, "c");
function e2(t3) {
try {
return t2.statSync(t3), true;
} catch {
return false;
}
}
__name(e2, "e");
function a(e3) {
let o3 = t(e3);
return o3 ? e2(path8.join(o3, "tsconfig.json")) || e2(path8.join(o3, "src", "tsconfig.json")) : false;
}
__name(a, "a");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-IDRPOXQ6.mjs
var u = /* @__PURE__ */ __name((n2, e3) => [...n2, e3], "u");
var l = /* @__PURE__ */ __name((n2) => {
if (n2.length !== 0) {
if (n2.length > 0 && n2[0]) throw n2[0];
return n2.length == 2 ? n2[1] : n2.slice(1);
}
}, "l");
function p(n2, e3) {
let { buildArgs: s2, parseCallback: t3 } = Object.assign({ buildArgs: u, parseCallback: l }, e3);
return function(...c4) {
return new Promise((o3, i3) => {
let y2 = s2(c4, (...r4) => {
try {
let a3 = t3(r4);
o3(a3);
} catch (a3) {
i3(a3);
}
});
try {
n2(...y2);
} catch (r4) {
i3(r4);
}
});
};
}
__name(p, "p");
var c3 = p(t2.readFile);
p(t2.copyFile);
p(t2.mkdir);
p(t2.readdir);
p(t2.readlink);
p(t2.realpath);
p(t2.rename);
p(t2.rmdir);
p(t2.stat);
p(t2.symlink);
p(t2.unlink);
p(t2.writeFile);
p(t2.access);
p(t2.appendFile);
p(t2.chmod);
p(t2.chown);
p(t2.close);
p(t2.fchmod);
p(t2.fchown);
p(t2.rm);
p(t2.truncate);
p(t2.opendir);
p(t2.open);
p(t2.read);
p(t2.write);
p(t2.mkdtemp);
p(t2.cp);
p(t2.exists, { parseCallback: /* @__PURE__ */ __name((e3) => e3[0], "parseCallback") });
async function getPromptTemplate(name, defaultPrompt) {
const { promptDir } = this;
if (!name) return defaultPrompt;
const promptFile = path8.isAbsolute(name) ? name : path8.join(promptDir, name.endsWith(".md") ? name : name + ".md");
if (t2.existsSync(promptFile)) {
return await c3(promptFile, {
encoding: "utf-8"
});
}
return defaultPrompt;
}
__name(getPromptTemplate, "getPromptTemplate");
function getDefaultPatterns(options) {
const patterns = [
"!coverage",
"!.pnpm",
"!**/*.test.*",
"!**/*.spec.*",
"!.vscode",
"!dist",
"!.git",
"!.turbo",
"!**/*.d.ts",
"!*.config.{js,ts}",
"!node_modules",
"!" + this.langRelDir
];
if (Array.isArray(this.patterns)) {
patterns.push(...this.patterns);
}
if (Array.isArray(options?.patterns)) {
patterns.push(...options.patterns);
delete options.patterns;
} else if (typeof options?.patterns === "string") {
patterns.push(options.patterns);
delete options.patterns;
}
if (patterns.every((p3) => p3.startsWith("!"))) {
patterns.push("**/*.{js,jsx,ts,tsx,vue,astro,svelte,mdx}");
}
return patterns;
}
__name(getDefaultPatterns, "getDefaultPatterns");
function getApi2(name, defaultValue) {
const { langDir } = this;
const apiFile = path8.join(langDir, "api.json");
let apis = {};
try {
if (t2.existsSync(apiFile)) {
apis = JSON.parse(t2.readFileSync(apiFile, "utf-8"));
}
} catch {
}
return apis[name] || defaultValue;
}
__name(getApi2, "getApi");
function getApiParams(options) {
if (typeof options === "object") {
let api;
if (typeof options.api === "string") {
api = getApi2.call(this, options.api, {});
}
Object.entries(options).forEach(([key, value]) => {
if (key.startsWith("api") && key.length > 3) {
const name = key.substring(3);
if (!api) api = {};
api[name[0].toLowerCase() + name.substring(1)] = value;
}
});
return api;
}
}
__name(getApiParams, "getApiParams");
function getDir(location) {
return (autoCreate = true) => {
const dir = path8.join(this.langDir, location);
if (autoCreate && !t2.existsSync(dir)) {
t2.mkdirSync(dir, {
recursive: true
});
}
return dir;
};
}
__name(getDir, "getDir");
async function getProjectContext(options) {
const ctx = await getVoerkaI18nSettings();
ctx.rootDir = process.env.INIT_CWD || process.cwd();
ctx.langDir = getLanguageDir();
ctx.langRelDir = path8.relative(process.cwd(), ctx.langDir).replaceAll(path8.sep, "/");
ctx.settingFile = path8.join(ctx.langDir, "settings.json");
ctx.settingRelFile = path8.relative(process.cwd(), ctx.settingFile).replace(/\\/g, "/");
ctx.promptDir = path8.join(ctx.langDir, "prompts");
ctx.getPrompt = getPromptTemplate.bind(ctx);
ctx.patterns = getDefaultPatterns.call(ctx, options);
ctx.getApi = getApi2.bind(ctx);
ctx.getTranslateMessagesDir = getDir.call(ctx, "translates/messages").bind(ctx);
ctx.getTranslateParagraphsDir = getDir.call(ctx, "translates/paragraphs").bind(ctx);
ctx.getMessagesDir = getDir.call(ctx, "messages").bind(ctx);
ctx.getParagraphsDir = getDir.call(ctx, "paragraphs").bind(ctx);
if (!ctx.typescript) ctx.typescript = a();
if (!ctx.moduleType) ctx.moduleType = c2();
Object.assign(ctx, options);
ctx.api = getApiParams.call(ctx, options);
return ctx;
}
__name(getProjectContext, "getProjectContext");
function getBackupFile(file) {
let i3 = 0;
const extName = path8.extname(file);
while (true) {
const bakFile = file.replace(extName, `.bak.${i3++}${extName}`);
if (!t2.existsSync(bakFile)) {
return bakFile;
}
}
}
__name(getBackupFile, "getBackupFile");
function addToGitIgnore(files) {
const projectRoot = t() || process.cwd();
const gitignoreFile = path8.resolve(projectRoot, ".gitignore");
if (!t2.existsSync(gitignoreFile)) {
t2.writeFileSync(gitignoreFile, "");
}
const content = t2.readFileSync(gitignoreFile).toString();
const lines = content.split("\n");
const newLines = Array.isArray(files) ? files : [
files
];
newLines.forEach((file) => {
if (lines.includes(file)) {
return;
}
lines.push(file);
});
t2.writeFileSync(gitignoreFile, lines.join("\n"));
}
__name(addToGitIgnore, "addToGitIgnore");
// src/trimChars.ts
function trimChars(str, chars = [
'"',
"'"
]) {
let start = 0;
let end = str.length;
while (start < end && chars.includes(str[start])) {
start++;
}
while (end > start && chars.includes(str[end - 1])) {
end--;
}
return str.substring(start, end);
}
__name(trimChars, "trimChars");
// src/hasImport.ts
var RequireRegex = /(let|const|var)\s*((\{[^}]*\})|(\w+))\s+=\s*require\(['"]\S+['"]\)/gm;
function hasImport(code, importName, options) {
let { moduleType } = Object.assign({
moduleType: "auto"
}, options);
if (moduleType === "auto") {
moduleType = RequireRegex.test(code) ? "cjs" : "ts";
}
let reg;
if (moduleType === "ts" || moduleType === "esm") {
reg = new RegExp(`import\\s+\\{[^}]*${importName}[^}]*\\}\\s+from\\s+['"]([^'"]+)['"]`);
} else {
reg = new RegExp(`(let|const|var){1}\\s+\\{[^}]*${importName}[^}]*\\}\\s*=\\s*require\\(['"]([^'"]+)['"]\\)`);
}
return reg.test(code);
}
__name(hasImport, "hasImport");
// src/addImport.ts
var RequireRegex2 = /(let|const|var)\s*((\{[^}]*\})|(\w+))\s+=\s*require\(['"]\S+['"]\)/gm;
function addImport(code, fromModule, importName, options) {
let { moduleType, scriptSection } = Object.assign({
moduleType: "auto",
scriptSection: /(<script[^>]*>)([\s\S]*?)(<\/script>)/gm
}, options);
if (moduleType === "auto") {
moduleType = RequireRegex2.test(code) ? "cjs" : "ts";
}
if (hasImport(code, importName, options)) {
return code;
} else {
const importCode = moduleType == "cjs" ? `const { ${importName} } from "${fromModule}"` : `import { ${importName} } from "${fromModule}"`;
let hasScript = false;
code = code.replace(scriptSection, (matched, scriptBegin, scriptContent, scriptEnd) => {
hasScript = true;
return matched.replace(scriptContent, scriptBegin + "\n" + importCode + "\n" + scriptContent + "\n" + scriptEnd);
});
if (!hasScript) {
code = importCode + "\n" + code;
}
}
return code;
}
__name(addImport, "addImport");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-XULHPTIO.mjs
function r3(t3, n2 = false) {
if (typeof t3 == "number") return true;
if (typeof t3 != "string" || n2) return false;
try {
if (t3.includes(".")) {
let e3 = parseFloat(t3);
return t3.endsWith(".") ? !isNaN(e3) && String(e3).length === t3.length - 1 : !isNaN(e3) && String(e3).length === t3.length;
} else {
let e3 = parseInt(t3);
return !isNaN(e3) && String(e3).length === t3.length;
}
} catch {
return false;
}
}
__name(r3, "r");
// src/isMessageId.ts
function isMessageId(content) {
return r3(content);
}
__name(isMessageId, "isMessageId");
function getDir2(spath) {
spath = path8.isAbsolute(spath) ? spath : path8.join(process.cwd(), spath);
if (!t2.existsSync(spath)) {
t2.mkdirSync(spath, {
recursive: true
});
}
return spath;
}
__name(getDir2, "getDir");
// src/indentString.ts
function indentString(str, indent = 0) {
const indentChars = " ".repeat(indent);
const lines = str.split("\n").map((line) => {
if (line.startsWith(indentChars)) {
line = line.substring(indentChars.length);
}
return line;
});
return lines.join("\n");
}
__name(indentString, "indentString");
async function fetchJson(urls, defaultValue) {
if (typeof urls === "string") {
urls = [
urls
];
}
for (const url of urls) {
try {
const response = await axios.get(url);
if (response.status === 200) {
return JSON.parse(response.data);
}
} catch (error) {
}
}
return defaultValue;
}
__name(fetchJson, "fetchJson");
// src/encodeRegExp.ts
function encodeRegExp(regex, vars) {
let r4 = regex.toString().replace(/^\/|\/$/g, "");
if (vars && typeof vars === "object") {
Object.entries(vars).forEach(([k2, v2]) => {
r4 = r4.replaceAll(k2, v2);
});
}
return r4;
}
__name(encodeRegExp, "encodeRegExp");
// src/extractMessages.ts
var commentRegexs = {
"js,vue,jsx,ts,tsx": [
/(^[^\n\r\w\W]*\/\/.*$)|(\/\/.*$)/gm,
/\/\*\s*[\W\w|\r|\n|*]*\s*\*\//gm
],
"html,vue,svelte": [
/\<\!--[\s\r\n-]*?[\w\r\n-\W]*?[\s\r\n-]*?--\>/gm
]
};
function removeComments(code, language = "js") {
Object.entries(commentRegexs).forEach(([filetype, regexps]) => {
if (filetype.split(",").includes(filetype)) {
regexps.forEach((regex) => {
code = code.replaceAll(regex, "");
});
}
});
return code;
}
__name(removeComments, "removeComments");
var messageExtractors = [
/[ \t\^;\{\(,='"\.\[\|\+\>](__T_FUNC__)\(\s*(["'])(?<text>.*?)(?=(\2\s*\))|(\2\s*\,))/,
/<(__T_COMPONENT__)[^:#@\>]*?message\s*=\s*(["'])(?<text>.*?)\2[\s\/\>]/
];
function getMessageExtractors(options) {
const { tFuncNames = [
"t",
"$t"
], tComponentNames = [
"Translate",
"v-translate"
] } = options;
return messageExtractors.map((regex) => {
return new RegExp(encodeRegExp(regex, {
"__T_FUNC__": tFuncNames.map((n2) => escapeRegex(n2)).join("|"),
"__T_COMPONENT__": tComponentNames.map((n2) => escapeRegex(n2)).join("|")
}), "gm");
});
}
__name(getMessageExtractors, "getMessageExtractors");
function parseTranslateMessagesByRegex(code, options) {
const { tFuncNames, tComponentNames } = Object.assign({
tFuncNames: [
"t",
"$t"
],
tComponentNames: [
"Translate",
"v-translate"
]
}, options);
let result;
let messages = [];
const messageExtractors2 = getMessageExtractors({
tFuncNames,
tComponentNames
});
for (let regex of messageExtractors2) {
while ((result = regex.exec(code)) !== null) {
if (result.index === regex.lastIndex) {
regex.lastIndex++;
}
const text = result.groups?.text;
if (text) {
messages.push({
message: text,
rang: {
start: result.index,
end: result.index + result[0].length
}
});
}
}
}
return messages;
}
__name(parseTranslateMessagesByRegex, "parseTranslateMessagesByRegex");
function extractMessagesUseRegex(code, options) {
const { file, namespaces, language } = options;
const namespace = file ? getFileNamespace(file, namespaces) : "default";
code = removeComments(code, language);
const messages = parseTranslateMessagesByRegex(code, options);
return messages.map((message) => ({
vars: void 0,
options: void 0,
namespace,
file,
...message
}));
}
__name(extractMessagesUseRegex, "extractMessagesUseRegex");
function extractMessages(code, options) {
const opts = Object.assign({
language: "ts",
namespaces: {}
}, options);
return extractMessagesUseRegex(code, opts);
}
__name(extractMessages, "extractMessages");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-ZDPYQ6B2.mjs
function o2(e3) {
if (typeof e3 != "object" || e3 === null) return false;
var r4 = Object.getPrototypeOf(e3);
if (r4 === null) return true;
for (var t3 = r4; Object.getPrototypeOf(t3) !== null; ) t3 = Object.getPrototypeOf(t3);
return r4 === t3;
}
__name(o2, "o");
// ../../node_modules/.pnpm/flex-tools@1.5.9/node_modules/flex-tools/dist/chunk-EQYIKS3N.mjs
function f2(t3, i3, a$1) {
let r4 = o2(a$1) ? Object.assign({}, a$1) : {};
return typeof i3 == "function" ? Object.entries(t3).forEach(([e3, n2]) => {
i3.call(t3, e3, n2) && (r4[e3] = n2);
}) : (Array.isArray(i3) ? i3 : [i3]).forEach((n2) => {
n2 in t3 && t3[n2] !== void 0 && (r4[n2] = t3[n2]);
}), r4;
}
__name(f2, "f");
// src/extractParagraphs.ts
var attrsRegex = /(?<name>\w+)\s*=\s*(["'])(?<value>.*?)\2/gm;
function parseTranslateAttrs(attrs) {
let result;
let attrsMap = {};
while ((result = attrsRegex.exec(attrs)) !== null) {
const { name, value } = result.groups || {};
if (name && value) {
attrsMap[name] = value;
}
}
return attrsMap;
}
__name(parseTranslateAttrs, "parseTranslateAttrs");
var paragraphExtractors = [
/<(__T_COMPONENT__)\s*(?<attrs>[^>]*)(?<![\/])>(?<text>[\s\S]*?)<\/\1>/
];
function getParagraphExtractors(options) {
const { tComponentNames = [
"Translate",
"v-translate"
] } = options;
return paragraphExtractors.map((regex) => {
return new RegExp(encodeRegExp(regex, {
"__T_COMPONENT__": tComponentNames.map((n2) => escapeRegex(n2)).join("|")
}), "gm");
});
}
__name(getParagraphExtractors, "getParagraphExtractors");
function parseParagraphsByRegex(code, options) {
const { file } = options;
const { tComponentNames } = Object.assign({
tComponentNames: [
"Translate",
"v-translate"
]
}, options);
const paragraphExtractors2 = getParagraphExtractors({
tComponentNames
});
let result;
let paragraphs = [];
for (let regex of paragraphExtractors2) {
while ((result = regex.exec(code)) !== null) {
if (result.index === regex.lastIndex) {
regex.lastIndex++;
}
const text = result.groups?.text;
const attrs = parseTranslateAttrs(result.groups?.attrs || "");
if (text) {
paragraphs.push({
message: text,
rang: {
start: result.index,
end: result.index + result[0].length
},
file,
...f2(attrs, [
"id",
"vars",
"scope",
"options",
"tag",
"style",
"class",
"className"
])
});
}
}
}
return paragraphs;
}
__name(parseParagraphsByRegex, "parseParagraphsByRegex");
function extractParagraphs(code, options) {
const opts = Object.assign({}, options);
const paragraphs = parseParagraphsByRegex(code, opts);
return paragraphs;
}
__name(extractParagraphs, "extractParagraphs");
export { addImport, addToGitIgnore, aiQuestion, applyIdMap, encodeRegExp, escapeRegex, extractMessages, extractMessagesUseRegex, extractParagraphs, fetchJson, getApi, getBackupFile, getBcp47LanguageApi, getDefaultLanguageDir, getDir2 as getDir, getFileNamespace, getIdMap, getLanguageDir, getProjectContext, getSettingsFromPackageJson, getVoerkaI18nSettings, hasImport, indentString, isMessageId, isVoerkaI18nInstalled, parseParagraphsByRegex, parseTranslateMessagesByRegex, trimChars };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map