@vtex/api
Version:
VTEX I/O API client
43 lines (42 loc) • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleSingleString = exports.formatTranslatableStringV2 = exports.parseTranslatableStringV2 = exports.CONTENT_REGEX = exports.FROM_REGEX = exports.CONTEXT_REGEX = void 0;
exports.CONTEXT_REGEX = /\(\(\((?<context>(.)*)\)\)\)/;
exports.FROM_REGEX = /\<\<\<(?<from>(.)*)\>\>\>/;
exports.CONTENT_REGEX = /\(\(\((?<context>(.)*)\)\)\)|\<\<\<(?<from>(.)*)\>\>\>/g;
const parseTranslatableStringV2 = (rawMessage) => {
var _a, _b, _c, _d;
const context = (_b = (_a = rawMessage.match(exports.CONTEXT_REGEX)) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.context;
const from = (_d = (_c = rawMessage.match(exports.FROM_REGEX)) === null || _c === void 0 ? void 0 : _c.groups) === null || _d === void 0 ? void 0 : _d.from;
const content = rawMessage.replace(exports.CONTENT_REGEX, '');
return {
content: content === null || content === void 0 ? void 0 : content.trim(),
context: context === null || context === void 0 ? void 0 : context.trim(),
from: from === null || from === void 0 ? void 0 : from.trim(),
};
};
exports.parseTranslatableStringV2 = parseTranslatableStringV2;
const formatTranslatableStringV2 = ({ from, content, context }) => `${content} ${context ? `(((${context})))` : ''} ${from ? `<<<${from}>>>` : ''}`;
exports.formatTranslatableStringV2 = formatTranslatableStringV2;
const handleSingleString = (ctx, loader, behavior, directiveName) => async (rawMessage) => {
// Messages only know how to process non empty strings.
if (rawMessage == null) {
return rawMessage;
}
const { content, context, from: maybeFrom } = (0, exports.parseTranslatableStringV2)(rawMessage);
const { binding, tenant } = ctx;
if (content == null) {
throw new Error(`@${directiveName} directive needs a content to translate, but received ${JSON.stringify(rawMessage)}`);
}
const from = maybeFrom || (binding === null || binding === void 0 ? void 0 : binding.locale) || (tenant === null || tenant === void 0 ? void 0 : tenant.locale);
if (from == null) {
throw new Error(`@${directiveName} directive needs a source language to translate from. You can do this by either setting ${'`ctx.vtex.tenant`'} variable, call this app with the header ${'`x-vtex-tenant`'} or format the string with the ${'`formatTranslatableStringV2`'} function with the ${'`from`'} option set`);
}
return loader.load({
behavior,
content,
context,
from,
});
};
exports.handleSingleString = handleSingleString;