json-autotranslate
Version:
Translate a folder of JSON files containing translations into multiple languages.
40 lines (39 loc) • 1.45 kB
JavaScript
;
exports.__esModule = true;
exports.matchIcu = void 0;
var messageformat_parser_1 = require("messageformat-parser");
exports.matchIcu = function (input, replacer) {
var writeTokens = function (part) {
var _a;
if (typeof part !== 'string' && ((_a = part === null || part === void 0 ? void 0 : part.cases) === null || _a === void 0 ? void 0 : _a.length)) {
return part.cases
.map(function (partCase) {
return partCase.tokens.length
? "(.*)" + nestedIcuMatcher(partCase.tokens) + "(.*)"
: '';
})
.join('');
}
else {
return '(.*)';
}
};
var nestedIcuMatcher = function (parts) {
return (parts
.map(function (part) {
return typeof part === 'string'
? part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
: writeTokens(part);
})
.join('')
// reduce replacement noise between replacements from nested tokens i.e. back to back (.*)(.*)
.replace(/(\(\.\*\)){2,}/g, '(.*)'));
};
var parts = messageformat_parser_1.parse(input);
var regex = new RegExp(nestedIcuMatcher(parts));
var matches = input.match(regex);
return (matches || []).slice(1).map(function (match, index) { return ({
from: match,
to: replacer(index)
}); });
};