UNPKG

@anchor-solutions-nl/translator-as

Version:
452 lines (451 loc) 22.1 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TranslatorClientService = void 0; var axios_1 = __importDefault(require("axios")); var browser_or_node_1 = require("browser-or-node"); var models_1 = require("./models"); var lodash_1 = require("lodash"); var date_fns_1 = require("date-fns"); var helpers = __importStar(require("./helper")); var queue_1 = require("./queue"); /** * This translator service class */ var TranslatorClientService = /** @class */ (function (_super) { __extends(TranslatorClientService, _super); function TranslatorClientService(options) { var _this = _super.call(this, options) || this; _this.clientDomain = browser_or_node_1.isBrowser ? location.hostname : ''; _this.appLanguages = []; _this.customLabels = {}; return _this; } TranslatorClientService.prototype.setCustomLabels = function (lbs) { var _this = this; if (lbs) { (0, lodash_1.keys)(lbs).forEach(function (key) { return __awaiter(_this, void 0, void 0, function () { var v, label; var _a; return __generator(this, function (_b) { v = lbs[key]; label = ((_a = this.labelsResponse.starredLabels) === null || _a === void 0 ? void 0 : _a.find(function (l) { return l.id === v; })) || this.addNewLabel('global-labels', v); this.customLabels[key] = label; return [2 /*return*/]; }); }); }); } }; // @TODO make this an interval that runs every one hour TranslatorClientService.prototype.init = function (customLabels) { var _this = this; var addStarredLabels = (0, lodash_1.isEmpty)(this.inMemoryStore); return new Promise(function (resolve, reject) { axios_1.default.get(models_1.translationsBaseUrl + "/" + _this.options.appId + "?starred=" + addStarredLabels + "&syncAuth=" + browser_or_node_1.isBrowser) .then(function (res) { return __awaiter(_this, void 0, void 0, function () { var data; return __generator(this, function (_a) { switch (_a.label) { case 0: data = res.data; return [4 /*yield*/, this.setup(data)]; case 1: _a.sent(); this.setCustomLabels(customLabels); resolve(null); return [2 /*return*/]; } }); }); }) .catch(function (e) { console.log(e); reject(e); }); }); }; TranslatorClientService.prototype.setup = function (data) { return __awaiter(this, void 0, void 0, function () { var outDatedSegmentIds_1, segments_1, labels; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: this.appLanguages = data.appLanguages; this.app = data.app; this.syncAuth = data.syncAuth; this.labelsResponse = data; if (browser_or_node_1.isBrowser && !this.options.defaultLanguage) { this.options.defaultLanguage = window.navigator.language.split('-')[0]; } if (browser_or_node_1.isNode && !this.options.defaultLanguage) { this.options.defaultLanguage = this.appLanguages[0].symbol; } if (!(0, lodash_1.isEmpty)(this.inMemoryStore)) return [3 /*break*/, 1]; this.groupLabelsAndSave((0, lodash_1.values)(data.app.segments).filter(function (segment) { return segment.starred; }), data.starredLabels); return [3 /*break*/, 3]; case 1: // Here we prune non used segments first this.pruneUnUsedlabels(); outDatedSegmentIds_1 = []; segments_1 = []; (0, lodash_1.keys)(this.inMemoryStore).forEach(function (segmentId) { if ((0, date_fns_1.isBefore)(_this.inMemoryStore[segmentId].segment.lastUpdated, data.app.segments[segmentId].lastUpdated)) { segments_1.push(data.app.segments[segmentId]); outDatedSegmentIds_1.push(segmentId); } }); if (!(outDatedSegmentIds_1.length > 0)) return [3 /*break*/, 3]; return [4 /*yield*/, this.getLabelsForSegments(outDatedSegmentIds_1)]; case 2: labels = _a.sent(); this.groupLabelsAndSave(segments_1, labels); _a.label = 3; case 3: return [2 /*return*/, Promise.resolve()]; } }); }); }; TranslatorClientService.prototype.getAppLanguages = function () { return this.appLanguages; }; TranslatorClientService.prototype.getActiveLanguages = function () { return this.appLanguages.filter(function (l) { return l.active; }); }; TranslatorClientService.prototype.setDefaultLanguage = function (languageSymbol) { // if the language is among the supported languages, we use that // else we ignore var language = this.appLanguages.find(function (lang) { return lang.symbol === languageSymbol; }); if (language) { this.options.defaultLanguage = language.symbol; } }; TranslatorClientService.prototype.getlabels = function (segmentId) { return __awaiter(this, void 0, void 0, function () { var labelsProvider; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: labelsProvider = { _translate: function (label, variableMap) { if (label) { return _this.translate(segmentId, label, variableMap); } return label; } }; if (!!this.inMemoryStore[segmentId]) return [3 /*break*/, 2]; return [4 /*yield*/, this.addNewSegment(segmentId)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/, Promise.resolve({ data: new Proxy(labelsProvider, { get: function (target, key) { // return labelsProvider._translate(key); if (key === '_translate') { return target[key]; } else { return labelsProvider._translate(key); } } }) })]; } }); }); }; TranslatorClientService.prototype.addNewSegment = function (segmentId) { return __awaiter(this, void 0, void 0, function () { var labels, segment, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.app.segments[segmentId]) return [3 /*break*/, 2]; return [4 /*yield*/, this.getLabelsForSegments([segmentId])]; case 1: labels = _a.sent(); this.groupLabelsAndSave([this.app.segments[segmentId]], labels); return [3 /*break*/, 6]; case 2: if (!this.canSync()) return [3 /*break*/, 6]; segment = { id: segmentId, totalLabels: 0, completed: 0, dateAdded: new Date(), lastUpdated: new Date(), starred: false }; _a.label = 3; case 3: _a.trys.push([3, 5, , 6]); this.app.segments[segmentId] = segment; // save to the database return [4 /*yield*/, this.saveTranslatorApp(this.app)]; case 4: // save to the database _a.sent(); // here we sync this.groupLabelsAndSave([segment], []); return [3 /*break*/, 6]; case 5: e_1 = _a.sent(); console.log(e_1); return [3 /*break*/, 6]; case 6: return [2 /*return*/, Promise.resolve()]; } }); }); }; TranslatorClientService.prototype.translate = function (segmentId, labelId, variableMap) { var result; if (this.inMemoryStore[segmentId]) { var label_1; // here we first check if it is in the global name space var globalHaslabel = this.inMemoryStore['global-labels'].labels[labelId]; var segmentHaslabel = this.inMemoryStore[segmentId].labels[labelId]; if (globalHaslabel || segmentHaslabel) { label_1 = globalHaslabel || segmentHaslabel; if (variableMap) { // @TODO we could remove this line but do a data migration to make sure // @TODO that the all labels in the db has a variables field label_1.variables = label_1.variables || {}; var _a = helpers.eliminateSimilarities((0, lodash_1.keys)(variableMap), (0, lodash_1.keys)(label_1.variables)), added = _a[0], removed = _a[1]; if (added.length > 0) { added.forEach(function (key) { label_1.variables[key] = { id: key, description: '' }; }); } if (removed.length > 0) { removed.forEach(function (key) { return delete label_1.variables[key]; }); } if (added.length > 0 || removed.length > 0) { this.updateLabel(label_1); } } else { // If no variable map, we clear what was already there if ((0, lodash_1.keys)(label_1.variables).length > 0) { label_1.variables = {}; this.updateLabel(label_1); } } } else { this.addNewLabel(segmentId, labelId, variableMap); } if (label_1) { result = label_1.values[models_1.LanguageTypes[this.options.defaultLanguage]]; } } // If the label has variables we interpolate else we just return the values if (((result === null || result === void 0 ? void 0 : result.includes('{{')) && (result === null || result === void 0 ? void 0 : result.includes('}}'))) && (variableMap || this.customLabels)) { return this.interpolate(result, variableMap); } else { return result || labelId; } }; TranslatorClientService.prototype.updateLabel = function (label) { return __awaiter(this, void 0, void 0, function () { var e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log('Update: ', label); // we add the label optimistically to memory this.inMemoryStore[label.segmentId].labels[label.id] = label; if (!this.canSync()) return [3 /*break*/, 4]; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.updateLabelToServer(label)]; case 2: _a.sent(); this.options.labelStore.setItem('translations', JSON.stringify(this.inMemoryStore)); return [3 /*break*/, 4]; case 3: e_2 = _a.sent(); console.log(e_2); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; TranslatorClientService.prototype.addNewLabel = function (segmentId, labelId, variableMap) { var variables = {}; if (variableMap) { (0, lodash_1.keys)(variableMap).forEach(function (key) { variables[key] = { id: key, description: '' }; }); } var label = { id: labelId, label: labelId, segmentId: segmentId, done: false, values: {}, variables: variables }; this.appLanguages.forEach(function (languge) { label.values[languge.id] = ''; }); // we add the label optimistically to memory this.inMemoryStore[segmentId].labels[label.id] = label; if (this.canSync()) { // here we add the label save operation to queue this.addToQueue(label); } return label; }; // This method removes all segments store on the client side // that no longer exists on the main app TranslatorClientService.prototype.pruneUnUsedlabels = function () { var _this = this; (0, lodash_1.values)(this.inMemoryStore).forEach(function (segment) { if (!(_this.app.segments[segment.segment.id])) { delete _this.inMemoryStore[segment.segment.id]; } }); this.options.labelStore.setItem('translations', JSON.stringify(this.inMemoryStore)); }; TranslatorClientService.prototype.getLabelsForSegments = function (segmentIds) { var _this = this; return new Promise(function (resolve, reject) { axios_1.default.post(models_1.translationsBaseUrl + "/" + _this.options.appId + "/labels", { segmentIds: segmentIds, appId: _this.app.id }) .then(function (res) { resolve(res.data); }) .catch(function (e) { reject(e); }); }); }; TranslatorClientService.prototype.groupLabelsAndSave = function (segments, labels) { var _this = this; segments.forEach(function (segment) { _this.inMemoryStore[segment.id] = { segment: segment, labels: {} }; }); labels.forEach(function (label) { _this.inMemoryStore[label.segmentId].labels[label.id] = label; }); this.options.labelStore.setItem('translations', JSON.stringify(this.inMemoryStore)); }; TranslatorClientService.prototype.canSync = function () { if (this.options.sync) { return (browser_or_node_1.isBrowser && this.syncAuth.allowedDomains.indexOf(this.clientDomain) >= 0) || (browser_or_node_1.isNode && !!this.options.secret); } return false; }; TranslatorClientService.prototype.interpolate = function (templateStr, vMap) { var variableMap = vMap || {}; try { // use custom delimiter {{ }} as used in the the labels lodash_1.templateSettings.interpolate = /{{([\s\S]+?)}}/g; if (this.customLabels) { for (var _i = 0, _a = (0, lodash_1.keys)(this.customLabels); _i < _a.length; _i++) { var key = _a[_i]; var v = this.customLabels[key]; var prop = v.values[models_1.LanguageTypes[this.options.defaultLanguage]]; variableMap[key] = prop || variableMap[key] || v.id; } } // interpolate var compile = (0, lodash_1.template)(templateStr); return compile(variableMap); } catch (e) { console.log(templateStr); console.log(variableMap); console.log(e); return templateStr; } }; return TranslatorClientService; }(queue_1.LabelSaverQueue)); exports.TranslatorClientService = TranslatorClientService;