Socket
Socket
Sign inDemoInstall

@lingui/cli

Package Overview
Dependencies
Maintainers
3
Versions
149
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lingui/cli - npm Package Compare versions

Comparing version 4.0.0-next.1 to 4.0.0-next.2

build/api/formats/api/formatterWrapper.js

2

./build/lingui.js

@@ -6,2 +6,2 @@ #!/usr/bin/env node

var _package = require("../package.json");
_commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);
_commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-experimental", "Extracts messages from source files traversing dependency tree").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);

@@ -8,4 +8,3 @@ "use strict";

exports.order = order;
exports.orderByMessageId = orderByMessageId;
exports.orderByOrigin = orderByOrigin;
exports.orderByMessage = orderByMessage;
var _fs = _interopRequireDefault(require("fs"));

@@ -39,4 +38,4 @@ var _path = _interopRequireDefault(require("path"));

this.exclude = [this.localeDir, ...exclude.map(_utils.normalizeRelativePath)];
this.format = (0, _formats.getFormat)(config.format);
this.templateFile = templatePath || getTemplatePath(this.format, this.path);
this.format = (0, _formats.getFormat)(config.format, config.formatOptions);
this.templateFile = templatePath || getTemplatePath(this.format.getTemplateExtension(), this.path);
}

@@ -48,3 +47,3 @@ async make(options) {

if (!nextCatalog) return false;
const prevCatalogs = this.readAll();
const prevCatalogs = await this.readAll();
const catalogs = this.merge(prevCatalogs, nextCatalog, {

@@ -62,7 +61,4 @@ overwrite: options.overwrite,

const sortedCatalogs = cleanAndSort(catalogs);
if (options.locale) {
this.write(options.locale, sortedCatalogs[options.locale]);
} else {
this.writeAll(sortedCatalogs);
}
const locales = options.locale ? [options.locale] : this.locales;
await Promise.all(locales.map(locale => this.write(locale, sortedCatalogs[locale])));
return sortedCatalogs;

@@ -76,3 +72,3 @@ }

const sorted = order(options.orderBy)(catalog);
this.writeTemplate(sorted);
await this.writeTemplate(sorted);
return sorted;

@@ -119,29 +115,18 @@ }

}
getTranslations(locale, options) {
return (0, _getTranslationsForCatalog.getTranslationsForCatalog)(this, locale, options);
async getTranslations(locale, options) {
return await (0, _getTranslationsForCatalog.getTranslationsForCatalog)(this, locale, options);
}
write(locale, messages) {
async write(locale, messages) {
const filename = (0, _utils.replacePlaceholders)(this.path, {
locale
}) + this.format.catalogExtension;
}) + this.format.getCatalogExtension();
const created = !_fs.default.existsSync(filename);
const options = {
...this.config.formatOptions,
locale
};
this.format.write(filename, messages, options);
await this.format.write(filename, messages, locale);
return [created, filename];
}
writeAll(catalogs) {
this.locales.forEach(locale => this.write(locale, catalogs[locale]));
}
writeTemplate(messages) {
async writeTemplate(messages) {
const filename = this.templateFile;
const options = {
...this.config.formatOptions,
locale: undefined
};
this.format.write(filename, messages, options);
await this.format.write(filename, messages, undefined);
}
writeCompiled(locale, compiledCatalog, namespace) {
async writeCompiled(locale, compiledCatalog, namespace) {
let ext;

@@ -158,19 +143,25 @@ if (namespace === "es") {

})}.${ext}`;
(0, _utils.writeFile)(filename, compiledCatalog);
await (0, _utils.writeFile)(filename, compiledCatalog);
return filename;
}
read(locale) {
async read(locale) {
const filename = (0, _utils.replacePlaceholders)(this.path, {
locale
}) + this.format.catalogExtension;
return this.format.read(filename);
}) + this.format.getCatalogExtension();
return await this.format.read(filename, locale);
}
readAll() {
return R.mergeAll(this.locales.map(locale => ({
[locale]: this.read(locale)
})));
async readAll() {
const res = {};
await Promise.all(this.locales.map(async locale => res[locale] = await this.read(locale)));
// statement above will save locales in object in undetermined order
// resort here to have keys order the same as in locales definition
return this.locales.reduce((acc, locale) => {
acc[locale] = res[locale];
return acc;
}, {});
}
readTemplate() {
async readTemplate() {
const filename = this.templateFile;
return this.format.read(filename);
return await this.format.read(filename, undefined);
}

@@ -204,4 +195,3 @@ get sourcePaths() {

exports.Catalog = Catalog;
function getTemplatePath(format, path) {
const ext = format.templateExtension || format.catalogExtension;
function getTemplatePath(ext, path) {
return path.replace(LOCALE_SUFFIX_RE, "messages" + ext);

@@ -214,2 +204,3 @@ }

messageId: orderByMessageId,
message: orderByMessage,
origin: orderByOrigin

@@ -252,2 +243,13 @@ }[by];

}, {});
}
function orderByMessage(messages) {
return Object.keys(messages).sort((a, b) => {
const aMsg = messages[a].message || "";
const bMsg = messages[b].message || "";
return aMsg.localeCompare(bMsg);
}).reduce((acc, key) => {
;
acc[key] = messages[key];
return acc;
}, {});
}

@@ -15,2 +15,3 @@ "use strict";

var _formats = require("../formats");
var _getExperimentalCatalogs = require("../../extract-experimental/getExperimentalCatalogs");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -24,2 +25,3 @@ const NAME_PH = "{name}";

function getCatalogs(config) {
var _config$experimental, _config$experimental$;
const catalogsConfig = config.catalogs;

@@ -70,2 +72,5 @@ const catalogs = [];

});
if ((_config$experimental = config.experimental) !== null && _config$experimental !== void 0 && (_config$experimental$ = _config$experimental.extractor) !== null && _config$experimental$ !== void 0 && _config$experimental$.entries.length) {
catalogs.push(...(0, _getExperimentalCatalogs.getExperimentalCatalogs)(config));
}
return catalogs;

@@ -96,3 +101,3 @@ }

for (const catalog of catalogs) {
const catalogFile = `${catalog.path}${catalog.format.catalogExtension}`;
const catalogFile = `${catalog.path}${catalog.format.getCatalogExtension()}`;
const catalogGlob = (0, _utils.replacePlaceholders)(catalogFile, {

@@ -119,3 +124,3 @@ locale: "*"

}
const extension = (0, _formats.getFormat)(config.format).catalogExtension;
const extension = (0, _formats.getFormat)(config.format, config.formatOptions).getCatalogExtension();
const correctPath = path.slice(0, -1);

@@ -122,0 +127,0 @@ const examplePath = (0, _utils.replacePlaceholders)(correctPath, {

@@ -7,5 +7,5 @@ "use strict";

exports.getTranslationsForCatalog = getTranslationsForCatalog;
function getTranslationsForCatalog(catalog, locale, options) {
const catalogs = catalog.readAll();
const template = catalog.readTemplate() || {};
async function getTranslationsForCatalog(catalog, locale, options) {
const catalogs = await catalog.readAll();
const template = (await catalog.readTemplate()) || {};
const sourceLocaleCatalog = catalogs[options.sourceLocale] || {};

@@ -12,0 +12,0 @@ const input = {

@@ -29,2 +29,7 @@ "use strict";

}, {});
if (namespace === "json") {
return JSON.stringify({
messages: compiledMessages
});
}
const ast = buildExportStatement(

@@ -31,0 +36,0 @@ //build JSON.parse(<compiledMessages>) statement

@@ -21,11 +21,17 @@ "use strict";

const parserOptions = ctx.linguiConfig.extractorParserOptions;
const parserPlugins = [
// https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
["decorators", {
decoratorsBeforeExport: (parserOptions === null || parserOptions === void 0 ? void 0 : parserOptions.decoratorsBeforeExport) || true
}]];
const parserPlugins = [];
if ([/\.ts$/, /\.mts$/, /\.cts$/, /\.tsx$/].some(r => filename.match(r))) {
parserPlugins.push("typescript");
} else if (parserOptions !== null && parserOptions !== void 0 && parserOptions.flow) {
parserPlugins.push("flow");
if (parserOptions.tsExperimentalDecorators) {
parserPlugins.push("decorators-legacy");
} else {
parserPlugins.push("decorators");
}
} else {
parserPlugins.push("decorators");
if (parserOptions !== null && parserOptions !== void 0 && parserOptions.flow) {
parserPlugins.push("flow");
}
}

@@ -32,0 +38,0 @@ if ([/\.jsx$/, /\.tsx$/].some(r => filename.match(r))) {

@@ -6,5 +6,4 @@ "use strict";

});
exports.default = void 0;
exports.default = _default;
var _papaparse = _interopRequireDefault(require("papaparse"));
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -31,24 +30,12 @@ const serialize = catalog => {

};
const csv = {
catalogExtension: ".csv",
write(filename, catalog) {
const messages = serialize(catalog);
(0, _utils.writeFileIfChanged)(filename, messages);
},
read(filename) {
const raw = (0, _utils.readFile)(filename);
if (!raw) {
return null;
function _default() {
return {
catalogExtension: ".csv",
parse(content) {
return deserialize(content);
},
serialize(catalog) {
return serialize(catalog);
}
try {
return deserialize(raw);
} catch (e) {
throw new Error(`Cannot read ${filename}: ${e.message}`);
}
},
parse(content) {
return deserialize(content);
}
};
var _default = csv;
exports.default = _default;
};
}

@@ -6,27 +6,26 @@ "use strict";

});
Object.defineProperty(exports, "FormatterWrapper", {
enumerable: true,
get: function () {
return _formatterWrapper.FormatterWrapper;
}
});
exports.getFormat = getFormat;
var _csv = _interopRequireDefault(require("./csv"));
var _lingui = _interopRequireDefault(require("./lingui"));
var _minimal = _interopRequireDefault(require("./minimal"));
var _po = _interopRequireDefault(require("./po"));
var _poGettext = _interopRequireDefault(require("./po-gettext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _formatterWrapper = require("./api/formatterWrapper");
const formats = {
lingui: _lingui.default,
minimal: _minimal.default,
po: _po.default,
csv: _csv.default,
"po-gettext": _poGettext.default
lingui: () => require("./lingui").default,
minimal: () => require("./minimal").default,
po: () => require("./po").default,
csv: () => require("./csv").default,
"po-gettext": () => require("./po-gettext").default
};
/**
* @internal
*/
function getFormat(name) {
const format = formats[name];
function getFormat(_format, options) {
if (typeof _format !== "string") {
return new _formatterWrapper.FormatterWrapper(_format);
}
const format = formats[_format];
if (!format) {
throw new Error(`Unknown format "${name}". Use one of following: ${Object.keys(formats).join(", ")}`);
throw new Error(`Unknown format "${_format}". Use one of following: ${Object.keys(formats).join(", ")}`);
}
return format;
return new _formatterWrapper.FormatterWrapper(format()(options));
}

@@ -6,5 +6,4 @@ "use strict";

});
exports.default = void 0;
exports.default = _default;
var R = _interopRequireWildcard(require("ramda"));
var _utils = require("../utils");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

@@ -18,37 +17,32 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

if (message.origin) {
message.origin.map(originValue => {
originValue.pop();
return originValue;
});
message.origin = message.origin.map(([file]) => [file]);
}
return message;
});
const lingui = {
catalogExtension: ".json",
write(filename, catalog, options) {
let outputCatalog = catalog;
if (options.origins === false) {
outputCatalog = removeOrigins(catalog);
function _default(options = {}) {
options = {
origins: true,
lineNumbers: true,
...options
};
return {
catalogExtension: ".json",
serialize(catalog, {
existing
}) {
let outputCatalog = catalog;
if (options.origins === false) {
outputCatalog = removeOrigins(outputCatalog);
}
if (options.origins !== false && options.lineNumbers === false) {
outputCatalog = removeLineNumbers(outputCatalog);
}
const shouldUseTrailingNewline = existing === null || (existing === null || existing === void 0 ? void 0 : existing.endsWith("\n"));
const trailingNewLine = shouldUseTrailingNewline ? "\n" : "";
return JSON.stringify(outputCatalog, null, 2) + trailingNewLine;
},
parse(content) {
return JSON.parse(content);
}
if (options.origins !== false && options.lineNumbers === false) {
outputCatalog = removeLineNumbers(outputCatalog);
}
(0, _utils.writeFileIfChanged)(filename, JSON.stringify(outputCatalog, null, 2));
},
read(filename) {
const raw = (0, _utils.readFile)(filename);
if (!raw) {
return null;
}
try {
return JSON.parse(raw);
} catch (e) {
throw new Error(`Cannot read ${filename}: ${e.message}`);
}
},
parse(content) {
return content;
}
};
var _default = lingui;
exports.default = _default;
};
}

@@ -6,5 +6,4 @@ "use strict";

});
exports.default = void 0;
exports.default = _default;
var R = _interopRequireWildcard(require("ramda"));
var _utils = require("../utils");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

@@ -19,28 +18,16 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

}));
const minimal = {
catalogExtension: ".json",
write(filename, catalog) {
const messages = serialize(catalog);
let file = (0, _utils.readFile)(filename);
const shouldUseTrailingNewline = file === null || (file === null || file === void 0 ? void 0 : file.endsWith("\n"));
const trailingNewLine = shouldUseTrailingNewline ? "\n" : "";
(0, _utils.writeFile)(filename, `${JSON.stringify(messages, null, 2)}${trailingNewLine}`);
},
read(filename) {
const raw = (0, _utils.readFile)(filename);
if (!raw) {
return null;
function _default() {
return {
catalogExtension: ".json",
serialize(catalog, {
existing
}) {
const shouldUseTrailingNewline = existing === null || (existing === null || existing === void 0 ? void 0 : existing.endsWith("\n"));
const trailingNewLine = shouldUseTrailingNewline ? "\n" : "";
return JSON.stringify(serialize(catalog), null, 2) + trailingNewLine;
},
parse(content) {
return deserialize(JSON.parse(content));
}
try {
const rawCatalog = JSON.parse(raw);
return deserialize(rawCatalog);
} catch (e) {
throw new Error(`Cannot read ${filename}: ${e.message}`);
}
},
parse(content) {
return deserialize(content);
}
};
var _default = minimal;
exports.default = _default;
};
}

@@ -6,3 +6,5 @@ "use strict";

});
exports.serialize = exports.default = void 0;
exports.default = _default;
exports.parse = parse;
exports.serialize = void 0;
var _dateFns = require("date-fns");

@@ -13,3 +15,2 @@ var _parser = require("@messageformat/parser");

var _plurals = _interopRequireDefault(require("node-gettext/lib/plurals"));
var _utils = require("../utils");
var _po = require("./po");

@@ -19,3 +20,3 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function getCreateHeaders(language = "no") {
function getCreateHeaders(language) {
return {

@@ -27,3 +28,5 @@ "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),

"X-Generator": "@lingui/cli",
Language: language
...(language ? {
Language: language
} : {})
};

@@ -188,43 +191,40 @@ }

};
const poGettext = {
catalogExtension: ".po",
templateExtension: ".pot",
write(filename, catalog, options) {
let po;
const raw = (0, _utils.readFile)(filename);
if (raw) {
po = _pofile.default.parse(raw);
} else {
po = new _pofile.default();
po.headers = getCreateHeaders(options.locale);
if (options.locale === undefined) {
delete po.headers.Language;
function parse(raw) {
const po = _pofile.default.parse(raw);
// .po plurals are numbered 0-N and need to be mapped to ICU plural classes ("one", "few", "many"...). Different
// languages can have different plural classes (some start with "zero", some with "one"), so read that data from CLDR.
// `pluralForms` may be `null` if lang is not found. As long as no plural is used, don't report an error.
let pluralForms = getPluralCases(po.headers.Language);
return (0, _po.deserialize)(po.items, item => {
convertPluralsToICU(item, pluralForms, po.headers.Language);
});
}
function _default(options = {}) {
options = {
origins: true,
lineNumbers: true,
...options
};
return {
catalogExtension: ".po",
templateExtension: ".pot",
parse(content) {
return parse(content);
},
serialize(catalog, ctx) {
let po;
if (ctx.existing) {
po = _pofile.default.parse(ctx.existing);
} else {
po = new _pofile.default();
po.headers = getCreateHeaders(ctx.locale)
// accessing private property
;
po.headerOrder = Object.keys(po.headers);
}
// accessing private property
;
po.headerOrder = Object.keys(po.headers);
po.items = serialize(catalog, options);
return po.toString();
}
po.items = serialize(catalog, options);
(0, _utils.writeFileIfChanged)(filename, po.toString());
},
read(filename) {
const raw = (0, _utils.readFile)(filename);
if (!raw) {
return null;
}
return this.parse(raw);
},
parse(raw) {
const po = _pofile.default.parse(raw);
// .po plurals are numbered 0-N and need to be mapped to ICU plural classes ("one", "few", "many"...). Different
// languages can have different plural classes (some start with "zero", some with "one"), so read that data from CLDR.
// `pluralForms` may be `null` if lang is not found. As long as no plural is used, don't report an error.
let pluralForms = getPluralCases(po.headers.Language);
return (0, _po.deserialize)(po.items, item => {
convertPluralsToICU(item, pluralForms, po.headers.Language);
});
}
};
var _default = poGettext;
exports.default = _default;
};
}

@@ -6,3 +6,3 @@ "use strict";

});
exports.default = void 0;
exports.default = _default;
exports.deserialize = deserialize;

@@ -18,3 +18,3 @@ exports.serialize = void 0;

}
function getCreateHeaders(language = "no") {
function getCreateHeaders(language) {
return {

@@ -26,3 +26,5 @@ "POT-Creation-Date": (0, _dateFns.format)(new Date(), "yyyy-MM-dd HH:mmxxxx"),

"X-Generator": "@lingui/cli",
Language: language
...(language ? {
Language: language
} : {})
};

@@ -98,36 +100,30 @@ }

}
const po = {
catalogExtension: ".po",
templateExtension: ".pot",
write(filename, catalog, options) {
let po;
const raw = (0, _utils.readFile)(filename);
if (raw) {
po = _pofile.default.parse(raw);
} else {
po = new _pofile.default();
po.headers = getCreateHeaders(options.locale);
if (options.locale === undefined) {
delete po.headers.Language;
function _default(options = {}) {
options = {
origins: true,
lineNumbers: true,
...options
};
return {
catalogExtension: ".po",
templateExtension: ".pot",
parse(content) {
const po = _pofile.default.parse(content);
return deserialize(po.items, validateItem);
},
serialize(catalog, ctx) {
let po;
if (ctx.existing) {
po = _pofile.default.parse(ctx.existing);
} else {
po = new _pofile.default();
po.headers = getCreateHeaders(ctx.locale)
// accessing private property
;
po.headerOrder = Object.keys(po.headers);
}
// accessing private property
;
po.headerOrder = Object.keys(po.headers);
po.items = serialize(catalog, options);
return po.toString();
}
po.items = serialize(catalog, options);
(0, _utils.writeFileIfChanged)(filename, po.toString());
},
read(filename) {
const raw = (0, _utils.readFile)(filename);
if (!raw) {
return null;
}
return this.parse(raw);
},
parse(raw) {
const po = _pofile.default.parse(raw);
return deserialize(po.items, validateItem);
}
};
var _default = po;
exports.default = _default;
};
}

@@ -34,3 +34,3 @@ "use strict";

return input.replace(/\{([^}]+)}/g, (m, placeholder) => {
return values[placeholder] || m;
return values[placeholder] ?? m;
});

@@ -45,5 +45,5 @@ }

exports.joinOrigin = joinOrigin;
function readFile(fileName) {
async function readFile(fileName) {
try {
return _fs.default.readFileSync(fileName).toString();
return (await _fs.default.promises.readFile(fileName)).toString();
} catch (err) {

@@ -55,5 +55,5 @@ if (err.code != "ENOENT") {

}
function mkdirp(dir) {
async function mkdirp(dir) {
try {
_fs.default.mkdirSync(dir, {
await _fs.default.promises.mkdir(dir, {
recursive: true

@@ -76,14 +76,14 @@ });

}
function writeFile(fileName, content) {
mkdirp(_path.default.dirname(fileName));
_fs.default.writeFileSync(fileName, content);
async function writeFile(fileName, content) {
await mkdirp(_path.default.dirname(fileName));
await _fs.default.promises.writeFile(fileName, content);
}
function writeFileIfChanged(filename, newContent) {
const raw = readFile(filename);
async function writeFileIfChanged(filename, newContent) {
const raw = await readFile(filename);
if (raw) {
if (newContent !== raw) {
writeFile(filename, newContent);
await writeFile(filename, newContent);
}
} else {
writeFile(filename, newContent);
await writeFile(filename, newContent);
}

@@ -117,4 +117,6 @@ }

}
// https://github.com/lingui/js-lingui/issues/809
const isDir = isDirectory(sourcePath);
return (0, _normalizePath.default)(_path.default.relative(process.cwd(), sourcePath), false) + (isDir ? "/" : "");
}

@@ -16,4 +16,6 @@ "use strict";

var _getCatalogs = require("./api/catalog/getCatalogs");
var _utils = require("./api/utils");
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function command(config, options) {
async function command(config, options) {
const catalogs = (0, _api.getCatalogs)(config);

@@ -28,3 +30,3 @@

const missingMessages = [];
const messages = catalog.getTranslations(locale, {
const messages = await catalog.getTranslations(locale, {
fallbackLocales: config.fallbackLocales,

@@ -63,3 +65,3 @@ sourceLocale: config.sourceLocale,

});
const compiledPath = catalog.writeCompiled(locale, compiledCatalog, namespace);
let compiledPath = await catalog.writeCompiled(locale, compiledCatalog, namespace);
if (options.typescript) {

@@ -72,2 +74,3 @@ const typescriptPath = compiledPath.replace(/\.ts?$/, "") + ".d.ts";

}
compiledPath = (0, _utils.normalizeSlashes)(_path.default.relative(config.rootDir, compiledPath));
options.verbose && console.error(_chalk.default.green(`${locale} ⇒ ${compiledPath}`));

@@ -85,3 +88,4 @@ }

});
const compiledPath = compileCatalog.writeCompiled(locale, compiledCatalog, namespace);
let compiledPath = await compileCatalog.writeCompiled(locale, compiledCatalog, namespace);
compiledPath = (0, _utils.normalizeSlashes)(_path.default.relative(config.rootDir, compiledPath));
options.verbose && console.log(_chalk.default.green(`${locale} ⇒ ${compiledPath}`));

@@ -107,13 +111,17 @@ }

});
const compile = () => command(config, {
verbose: options.watch || options.verbose || false,
allowEmpty: !options.strict,
typescript: options.typescript || config.compileNamespace === "ts" || false,
namespace: options.namespace // we want this to be undefined if user does not specify so default can be used
});
let previousRun = Promise.resolve(true);
const compile = () => {
previousRun = previousRun.then(() => command(config, {
verbose: options.watch || options.verbose || false,
allowEmpty: !options.strict,
typescript: options.typescript || config.compileNamespace === "ts" || false,
namespace: options.namespace // we want this to be undefined if user does not specify so default can be used
}));
return previousRun;
};
let debounceTimer;
const dispatchCompile = () => {
// Skip debouncing if not enabled
if (!options.debounce) return compile();
if (!options.debounce) compile();

@@ -130,3 +138,3 @@ // CLear the previous timer if there is any, and schedule the next

let paths = [];
const catalogExtension = (0, _api.getFormat)(config.format).catalogExtension;
const catalogExtension = (0, _api.getFormat)(config.format, config.formatOptions).getCatalogExtension();
config.locales.forEach(locale => {

@@ -146,8 +154,9 @@ catalogs.forEach(catalog => {

} else {
const results = compile();
if (!results) {
process.exit(1);
}
console.log("Done!");
compile().then(results => {
if (!results) {
process.exit(1);
}
console.log("Done!");
});
}
}

@@ -52,3 +52,3 @@ "use strict";

const moduleName = config.service.name.charAt(0).toLowerCase() + config.service.name.slice(1);
(specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`./services/${moduleName}`).then(module => module.default(config, options)).catch(err => console.error(`Can't load service module ${moduleName}`, err));
await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`./services/${moduleName}`).then(module => module.default(config, options)).catch(err => console.error(`Can't load service module ${moduleName}`, err));
}

@@ -55,0 +55,0 @@ return commandSuccess;

@@ -6,2 +6,2 @@ #!/usr/bin/env node

var _package = require("../package.json");
_commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);
_commander.program.version(_package.version).command("extract [files...]", "Extracts messages from source files").command("extract-experimental", "Extracts messages from source files traversing dependency tree").command("extract-template", "Extracts messages from source files to a .pot template").command("compile", "Compile message catalogs").parse(process.argv);

@@ -55,3 +55,3 @@ "use strict";

const paths = poPathsPerLocale(config);
let segments = {};
const segments = {};
targetLocales.forEach(targetLocale => {

@@ -63,7 +63,7 @@ segments[targetLocale] = [];

paths[sourceLocale].forEach(path => {
let raw = _fs.default.readFileSync(path).toString();
let po = _pofile.default.parse(raw);
const raw = _fs.default.readFileSync(path).toString();
const po = _pofile.default.parse(raw);
po.items.filter(item => !item["obsolete"]).forEach(item => {
targetLocales.forEach(targetLocale => {
let newSegment = createSegmentFromPoItem(item);
const newSegment = createSegmentFromPoItem(item);
segments[targetLocale].push(newSegment);

@@ -77,4 +77,4 @@ });

paths[targetLocale].forEach(path => {
let raw = _fs.default.readFileSync(path).toString();
let po = _pofile.default.parse(raw);
const raw = _fs.default.readFileSync(path).toString();
const po = _pofile.default.parse(raw);
po.items.filter(item => !item["obsolete"]).forEach((item, index) => {

@@ -85,3 +85,3 @@ segments[targetLocale][index].target = item.msgstr[0];

});
let request = {
const request = {
client: "lingui",

@@ -111,14 +111,14 @@ version: require("@lingui/core/package.json").version,

const paths = poPathsPerLocale(config);
let segments = [];
const segments = [];
// Create segments with correct source
paths[sourceLocale].forEach(path => {
let raw = _fs.default.readFileSync(path).toString();
let po = _pofile.default.parse(raw);
const raw = _fs.default.readFileSync(path).toString();
const po = _pofile.default.parse(raw);
po.items.filter(item => !item["obsolete"]).forEach(item => {
let newSegment = createSegmentFromPoItem(item);
const newSegment = createSegmentFromPoItem(item);
segments.push(newSegment);
});
});
let request = {
const request = {
client: "lingui",

@@ -128,9 +128,6 @@ version: require("@lingui/core/package.json").version,

target_languages: targetLocales,
segments: segments
segments: segments,
// Sync and then remove unused segments (not present in the local application) from Translation.io
purge: Boolean(options.clean)
};
// Sync and then remove unused segments (not present in the local application) from Translation.io
if (options.clean) {
request["purge"] = true;
}
postTio("sync", request, config.service.apiKey, response => {

@@ -148,4 +145,4 @@ if (response.errors) {

function createSegmentFromPoItem(item) {
let itemHasId = item.msgid != item.msgstr[0] && item.msgstr[0].length;
let segment = {
const itemHasId = item.msgid != item.msgstr[0] && item.msgstr[0].length;
const segment = {
type: "source",

@@ -171,3 +168,3 @@ // No way to edit text for source language (inside code), so not using "key" here

function createPoItemFromSegment(segment) {
let item = new _pofile.default.Item();
const item = new _pofile.default.Item();
item.msgid = segment.context ? segment.context : segment.source;

@@ -201,7 +198,7 @@ item.msgstr = [segment.target];

const segments = segmentsPerLocale[targetLocale];
let po = new _pofile.default();
const po = new _pofile.default();
po.headers = getCreateHeaders(targetLocale);
let items = [];
const items = [];
segments.forEach(segment => {
let item = createPoItemFromSegment(segment);
const item = createPoItemFromSegment(segment);
items.push(item);

@@ -236,3 +233,3 @@ });

function poPathsPerLocale(config) {
const paths = [];
const paths = {};
config.locales.forEach(locale => {

@@ -254,6 +251,6 @@ paths[locale] = [];

function postTio(action, request, apiKey, successCallback, failCallback) {
let jsonRequest = JSON.stringify(request);
let options = {
const jsonRequest = JSON.stringify(request);
const options = {
hostname: "translation.io",
path: "/api/v1/segments/" + action + ".json?api_key=" + apiKey,
path: `/api/v1/segments/${action}.json?api_key=${apiKey}`,
method: "POST",

@@ -264,3 +261,3 @@ headers: {

};
let req = _https.default.request(options, res => {
const req = _https.default.request(options, res => {
res.setEncoding("utf8");

@@ -272,3 +269,3 @@ let body = "";

res.on("end", () => {
let response = JSON.parse(body);
const response = JSON.parse(body);
successCallback(response);

@@ -275,0 +272,0 @@ });

@@ -7,2 +7,3 @@ "use strict";

exports.copyFixture = copyFixture;
exports.createFixtures = createFixtures;
exports.defaultMergeOptions = exports.defaultMakeTemplateOptions = exports.defaultMakeOptions = void 0;

@@ -97,2 +98,22 @@ exports.listingToHumanReadable = listingToHumanReadable;

}
/**
* Create fixtures from provided listing in temp folder
* Alternative for mock-fs which is also mocking nodejs require calls
* @param listing
*/
async function createFixtures(listing) {
const tmpDir = await _fs.default.promises.mkdtemp(_path.default.join(_os.default.tmpdir(), `lingui-test-${process.pid}`));
async function create(listing) {
for (const [filename, value] of Object.entries(listing)) {
if (typeof value === "string") {
await _fs.default.promises.writeFile(_path.default.join(tmpDir, filename), value);
} else {
await create(value);
}
}
}
await create(listing);
return tmpDir;
}
function readFsToJson(directory, filter) {

@@ -99,0 +120,0 @@ const out = {};

{
"name": "@lingui/cli",
"version": "4.0.0-next.1",
"version": "4.0.0-next.2",
"description": "CLI for working wit message catalogs",

@@ -48,11 +48,10 @@ "keywords": [

"dependencies": {
"@babel/core": "^7.20.12",
"@babel/generator": "^7.20.14",
"@babel/parser": "^7.20.15",
"@babel/plugin-syntax-jsx": "^7.18.6",
"@babel/runtime": "^7.20.13",
"@babel/types": "^7.20.7",
"@lingui/babel-plugin-extract-messages": "^4.0.0-next.1",
"@lingui/conf": "^4.0.0-next.1",
"@lingui/core": "^4.0.0-next.1",
"@babel/core": "^7.21.0",
"@babel/generator": "^7.21.1",
"@babel/parser": "^7.21.2",
"@babel/runtime": "^7.21.0",
"@babel/types": "^7.21.2",
"@lingui/babel-plugin-extract-messages": "^4.0.0-next.2",
"@lingui/conf": "^4.0.0-next.2",
"@lingui/core": "^4.0.0-next.2",
"@messageformat/parser": "^5.0.0",

@@ -66,2 +65,3 @@ "babel-plugin-macros": "^3.0.1",

"date-fns": "^2.16.1",
"esbuild": "^0.17.10",
"glob": "^7.1.4",

@@ -75,2 +75,3 @@ "inquirer": "^7.3.3",

"papaparse": "^5.3.0",
"pkg-up": "^3.1.0",
"plurals-cldr": "^1.0.4",

@@ -92,3 +93,3 @@ "pofile": "^1.1.4",

},
"gitHead": "27ee8e213ff6d0c7a0cd2b21c573d7f6da43fd85"
"gitHead": "556ab57e20c2ac9d384a22424c6a90c2ba0dd133"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc