Skip to main content
Module

x/i18next_locize_backend/i18nextLocizeBackend.min.js

A simple i18next backend for locize.com which can be used in Node.js, in the browser and for Deno.
Go to Latest
File
!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).i18nextLocizeBackend=e()}(function(){return function n(i,r,s){function a(t,e){if(!r[t]){if(!i[t]){var o="function"==typeof require&&require;if(!e&&o)return o(t,!0);if(c)return c(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}o=r[t]={exports:{}},i[t][0].call(o.exports,function(e){return a(i[t][1][e]||e)},o,o.exports,n,i,r,s)}return r[t].exports}for(var c="function"==typeof require&&require,e=0;e<s.length;e++)a(s[e]);return a}({1:[function(o,n,i){!function(t){!function(){var e;"function"==typeof fetch&&(e=void 0!==t&&t.fetch?t.fetch:"undefined"!=typeof window&&window.fetch?window.fetch:fetch),void 0!==o&&"undefined"==typeof window&&((e=e||o("cross-fetch")).default&&(e=e.default),i.default=e,n.exports=i.default)}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"cross-fetch":5}],2:[function(e,t,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.default=void 0;var f=e("./utils.js"),d=(e=e("./request.js"))&&e.__esModule?e:{default:e};function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function n(e,t){for(var o=0;o<t.length;o++){var n=t[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==i(e)||null===e)return e;var o=e[Symbol.toPrimitive];if(void 0===o)return("string"===t?String:Number)(e);o=o.call(e,t||"default");if("object"!==i(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"===i(e)?e:String(e)}(n.key),n)}}try{var c="undefined"!=typeof window&&null!==window.localStorage,r="notExistingLocizeProject";window.localStorage.setItem(r,"foo"),window.localStorage.removeItem(r)}catch(e){c=!1}function p(e,t,o){var n={};return t.authorize&&t.apiKey&&(n.Authorization=t.apiKey),(o||t.setContentTypeJSON)&&(n["Content-Type"]="application/json"),{method:o?"POST":"GET",url:e,headers:n,body:o}}function h(e,t,o){if(1===e.request.length)try{var n=e.request(t);n&&"function"==typeof n.then?n.then(function(e){return o(null,e)}).catch(o):o(null,n)}catch(e){o(e)}else e.request(t,o)}e=a,(r=[{key:"init",value:function(e){var o,n=this,i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},t=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},r=3<arguments.length?arguments[3]:void 0,s=(!i.referenceLng&&t.fallbackLng&&Array.isArray(t.fallbackLng)&&"dev"!==t.fallbackLng[0]&&(i.referenceLng=t.fallbackLng[0]),this.services=e,{loadPath:"https://api.locize.app/{{projectId}}/{{version}}/{{lng}}/{{ns}}",privatePath:"https://api.locize.app/private/{{projectId}}/{{version}}/{{lng}}/{{ns}}",getLanguagesPath:"https://api.locize.app/languages/{{projectId}}",addPath:"https://api.locize.app/missing/{{projectId}}/{{version}}/{{lng}}/{{ns}}",updatePath:"https://api.locize.app/update/{{projectId}}/{{version}}/{{lng}}/{{ns}}",referenceLng:"en",crossDomain:!0,setContentTypeJSON:!1,version:"latest",private:!1,translatedPercentageThreshold:.9,failLoadingOnEmptyJSON:!1,allowedAddOrUpdateHosts:["localhost"],onSaved:!1,reloadInterval:"undefined"==typeof window&&36e5,checkForProjectTimeout:3e3,storageExpiration:36e5,writeDebounce:5e3}),a=(0,f.defaults)(i,this.options||{}),a=(a.reloadInterval&&a.reloadInterval<3e5&&(console.warn("Your configured reloadInterval option is to low."),a.reloadInterval=s.reloadInterval),this.options=(0,f.defaults)(i,this.options||{},s),this.allOptions=t,this.somethingLoaded=!1,this.isProjectNotExisting=!1,this.storage=(o=this.options.storageExpiration,a=function(){},s=function(){},c?(a=function(e){window.localStorage.setItem("notExistingLocizeProject_".concat(e),Date.now())},s=function(e){var t=window.localStorage.getItem("notExistingLocizeProject_".concat(e));return!(!t||Date.now()-t>o&&(window.localStorage.removeItem("notExistingLocizeProject_".concat(e)),1))}):"undefined"!=typeof document&&(a=function(e){var t=new Date,t=(t.setTime(t.getTime()+o),"; expires=".concat(t.toGMTString())),e="notExistingLocizeProject_".concat(e);try{document.cookie="".concat(e,"=").concat(Date.now()).concat(t,";path=/")}catch(e){}},s=function(e){var e="notExistingLocizeProject_".concat(e),t="".concat(e,"=");try{for(var o=document.cookie.split(";"),n=0;n<o.length;n++){for(var i=o[n];" "===i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return!0}}catch(e){}return!1}),{setProjectNotExisting:a,isProjectNotExisting:s}),this.options.pull&&console.warn('The pull API was removed use "private: true" option instead: https://docs.locize.com/integration/api#fetch-private-namespace-resources'),"undefined"!=typeof window&&window.location&&window.location.hostname);a?(this.isAddOrUpdateAllowed="function"==typeof this.options.allowedAddOrUpdateHosts?this.options.allowedAddOrUpdateHosts(a):-1<this.options.allowedAddOrUpdateHosts.indexOf(a),e&&e.logger&&(t.saveMissing||t.updateMissing)&&(this.isAddOrUpdateAllowed?"localhost"!==a&&e.logger.warn('locize-backend: you are using the save or update missings feature from this host "'.concat(a,'".\nMake sure you will not use it in production!\nhttps://docs.locize.com/guides-tips-and-tricks/going-production')):e.logger.warn("function"==typeof this.options.allowedAddOrUpdateHosts?'locize-backend: will not save or update missings because allowedAddOrUpdateHosts returned false for the host "'.concat(a,'".'):'locize-backend: will not save or update missings because the host "'.concat(a,'" was not in the list of allowedAddOrUpdateHosts: ').concat(this.options.allowedAddOrUpdateHosts.join(", ")," (matches need to be exact).")))):this.isAddOrUpdateAllowed=!0,"function"==typeof r&&this.getOptions(function(e,t,o){if(e)return r(e);n.options.referenceLng=i.referenceLng||t.referenceLng||n.options.referenceLng,r(null,t,o)}),this.queuedWrites={pending:{}},this.debouncedProcess=(0,f.debounce)(this.process,this.options.writeDebounce),this.interval&&clearInterval(this.interval),this.options.reloadInterval&&this.options.projectId&&(this.interval=setInterval(function(){return n.reload()},this.options.reloadInterval))}},{key:"reload",value:function(){var t,e,o=this,n=this.services||{logger:console},i=n.backendConnector,r=n.languageUtils,s=n.logger;!i||(n=i.language)&&"cimode"===n.toLowerCase()||(t=[],(e=function(e){r.toResolveHierarchy(e).forEach(function(e){t.indexOf(e)<0&&t.push(e)})})(n),this.allOptions.preload&&this.allOptions.preload.forEach(e),t.forEach(function(n){o.allOptions.ns.forEach(function(o){i.read(n,o,"read",null,null,function(e,t){e&&s.warn("loading namespace ".concat(o," for language ").concat(n," failed"),e),!e&&t&&s.log("loaded namespace ".concat(o," for language ").concat(n),t),i.loaded("".concat(n,"|").concat(o),e,t)})})}))}},{key:"getLanguages",value:function(e){var o,i=this,t=(e||(o=(0,f.defer)(),e=function(e,t){if(e)return o.reject(e);o.resolve(t)}),(0,f.isMissingOption)(this.options,["projectId"]));return t?e(new Error(t)):(t=(0,f.interpolate)(this.options.getLanguagesPath,{projectId:this.options.projectId}),!this.isProjectNotExisting&&this.storage.isProjectNotExisting(this.options.projectId)&&(this.isProjectNotExisting=!0),this.isProjectNotExisting?e(new Error("locize project ".concat(this.options.projectId," does not exist!"))):(this.getLanguagesCalls=this.getLanguagesCalls||[],this.getLanguagesCalls.push(e),1<this.getLanguagesCalls.length?void 0:(this.loadUrl({},t,function(t,o,e){var n;if(!i.somethingLoaded&&e&&e.resourceNotExisting)return i.isProjectNotExisting=!0,i.storage.setProjectNotExisting(i.options.projectId),n=new Error("locize project ".concat(i.options.projectId," does not exist!")),e=i.getLanguagesCalls,i.getLanguagesCalls=[],e.forEach(function(e){return e(n)});o&&(e=Object.keys(o).reduce(function(e,t){return e=o[t].isReferenceLanguage?t:e},""))&&i.options.referenceLng!==e&&(i.options.referenceLng=e),i.somethingLoaded=!0;e=i.getLanguagesCalls;i.getLanguagesCalls=[],e.forEach(function(e){return e(t,o)})}),o)))}},{key:"getOptions",value:function(o){var n,i=this;return o||(n=(0,f.defer)(),o=function(e,t){if(e)return n.reject(e);n.resolve(t)}),this.getLanguages(function(e,n){var t;return e?o(e):(e=Object.keys(n)).length?(t=e.reduce(function(e,t){var o=n[t];return o.translated[i.options.version]&&o.translated[i.options.version]>=i.options.translatedPercentageThreshold&&e.push(t),e},[]),e=e.reduce(function(e,t){return-1<t.indexOf("-")||e},!1),void o(null,{fallbackLng:i.options.referenceLng,referenceLng:i.options.referenceLng,supportedLngs:t,load:e?"all":"languageOnly"},n)):o(new Error("was unable to load languages via API"))}),n}},{key:"checkIfProjectExists",value:function(t){var e=this,o=(this.services||{logger:console}).logger;this.somethingLoaded?t&&t(null):this.alreadyRequestedCheckIfProjectExists?setTimeout(function(){return e.checkIfProjectExists(t)},this.options.checkForProjectTimeout):(this.alreadyRequestedCheckIfProjectExists=!0,this.getLanguages(function(e){e&&e.message&&0<e.message.indexOf("does not exist")&&o&&o.error(e.message),t&&t(e)}))}},{key:"read",value:function(e,t,n){var i=this,o=(this.services||{logger:console}).logger,r={};if(this.options.private){var s=(0,f.isMissingOption)(this.options,["projectId","version","apiKey"]);if(s)return n(new Error(s),!1);s=(0,f.interpolate)(this.options.privatePath,{lng:e,ns:t,projectId:this.options.projectId,version:this.options.version}),r={authorize:!0}}else{var a=(0,f.isMissingOption)(this.options,["projectId","version"]);if(a)return n(new Error(a),!1);s=(0,f.interpolate)(this.options.loadPath,{lng:e,ns:t,projectId:this.options.projectId,version:this.options.version})}!this.isProjectNotExisting&&this.storage.isProjectNotExisting(this.options.projectId)&&(this.isProjectNotExisting=!0),this.isProjectNotExisting?(a=new Error("locize project ".concat(this.options.projectId," does not exist!")),o&&o.error(a.message),n&&n(a)):this.loadUrl(r,s,function(e,t,o){i.somethingLoaded||(o&&o.resourceNotExisting?setTimeout(function(){return i.checkIfProjectExists()},i.options.checkForProjectTimeout):i.somethingLoaded=!0),n(e,t)})}},{key:"loadUrl",value:function(e,r,t,s){function o(e,t){var o,n,i=t&&t.resourceNotExisting;if(t&&(408===t.status||400===t.status))return s("failed loading "+r,!0,{resourceNotExisting:i});if(t&&(500<=t.status&&t.status<600||!t.status))return s("failed loading "+r,!0,{resourceNotExisting:i});if(t&&400<=t.status&&t.status<500)return s("failed loading "+r,!1,{resourceNotExisting:i});if(!t&&e&&e.message&&-1<e.message.indexOf("Failed to fetch"))return s("failed loading "+r,!0,{resourceNotExisting:i});if(e)return s(e,!1);try{o="string"==typeof t.data?JSON.parse(t.data):t.data}catch(e){n="failed parsing "+r+" to json"}return n?s(n,!1):a.options.failLoadingOnEmptyJSON&&!Object.keys(o).length?s("loaded result empty for "+r,!1,{resourceNotExisting:i}):void s(null,o,{resourceNotExisting:i})}var a=this;e=(0,f.defaults)(e,this.options),"function"==typeof t&&(s=t,t=void 0),s=s||function(){};if(!this.options.request||0<r.indexOf("/languages/".concat(e.projectId)))return(0,d.default)(e,r,t,o);e=p(r,e,t);h(this.options,e,o)}},{key:"create",value:function(t,o,n,i,r,s){var a=this;"function"!=typeof r&&(r=function(){}),this.checkIfProjectExists(function(e){return e?r(e):(e=(0,f.isMissingOption)(a.options,["projectId","version","apiKey","referenceLng"]))?r(new Error(e)):a.isAddOrUpdateAllowed?((t="string"==typeof t?[t]:t).filter(function(e){return e===a.options.referenceLng}).length<1&&a.services&&a.services.logger&&a.services.logger.warn('locize-backend: will not save missings because the reference language "'.concat(a.options.referenceLng,'" was not in the list of to save languages: ').concat(t.join(", ")," (open your site in the reference language to save missings).")),void t.forEach(function(e){e===a.options.referenceLng&&a.queue.call(a,a.options.referenceLng,o,n,i,r,s)})):r("host is not allowed to create key.")})}},{key:"update",value:function(t,o,n,i,r,s){var a=this;"function"!=typeof r&&(r=function(){}),this.checkIfProjectExists(function(e){return e?r(e):(e=(0,f.isMissingOption)(a.options,["projectId","version","apiKey","referenceLng"]))?r(new Error(e)):a.isAddOrUpdateAllowed?("string"==typeof t&&(t=[t]),(s=s||{}).isUpdate=!0,void t.forEach(function(e){e===a.options.referenceLng&&a.queue.call(a,a.options.referenceLng,o,n,i,r,s)})):r("host is not allowed to update key.")})}},{key:"writePage",value:function(e,t,o,n){function i(e){--l||n(e)}var r=(0,f.interpolate)(this.options.addPath,{lng:e,ns:t,projectId:this.options.projectId,version:this.options.version}),e=(0,f.interpolate)(this.options.updatePath,{lng:e,ns:t,projectId:this.options.projectId,version:this.options.version}),s=!1,a=!1,c={},u={},l=(o.forEach(function(e){var t=e.options&&e.options.tDescription?{value:e.fallbackValue||"",context:{text:e.options.tDescription}}:e.fallbackValue||"";e.options&&e.options.isUpdate?(a=a||!0,u[e.key]=t):(s=s||!0,c[e.key]=t)}),0);s&&l++,a&&l++;l||i(),s&&(this.options.request?(t=p(r,(0,f.defaults)({authorize:!0},this.options),c),h(this.options,t,i)):(0,d.default)((0,f.defaults)({authorize:!0},this.options),r,c,i)),a&&(this.options.request?(o=p(e,(0,f.defaults)({authorize:!0},this.options),u),h(this.options,o,i)):(0,d.default)((0,f.defaults)({authorize:!0},this.options),e,u,i))}},{key:"write",value:function(e,t){var o=this,n=(0,f.getPath)(this.queuedWrites,["locks",e,t]);if(!n){var i=(0,f.getPath)(this.queuedWrites,[e,t]),r=((0,f.setPath)(this.queuedWrites,[e,t],[]),i.filter(function(e){return e.callback}).map(function(e){return e.callback}));if(i.length){(0,f.setPath)(this.queuedWrites,["locks",e,t],!0);var s=function(){(0,f.setPath)(o.queuedWrites,["locks",e,t],!1),r.forEach(function(e){return e()}),o.options.onSaved&&o.options.onSaved(e,t),o.debouncedProcess(e,t)},a=i.length/1e3,c=0,u=i.splice(0,1e3);for(this.writePage(e,t,u,function(){a<=++c&&s()});1e3===u.length;)(u=i.splice(0,1e3)).length&&this.writePage(e,t,u,function(){a<=++c&&s()})}}}},{key:"process",value:function(){var o=this;Object.keys(this.queuedWrites).forEach(function(t){"locks"!==t&&Object.keys(o.queuedWrites[t]).forEach(function(e){o.queuedWrites[t][e].length&&o.write(t,e)})})}},{key:"queue",value:function(e,t,o,n,i,r){(0,f.pushPath)(this.queuedWrites,[e,t],{key:o,fallbackValue:n||"",callback:i,options:r}),this.debouncedProcess()}}])&&n(e.prototype,r),s&&n(e,s),Object.defineProperty(e,"prototype",{writable:!1});var s=a;function a(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},n=3<arguments.length?arguments[3]:void 0,i=this,r=a;if(!(i instanceof r))throw new TypeError("Cannot call a class as a function");this.services=e,this.options=t,this.allOptions=o,this.type="backend",e&&e.projectId?this.init(null,e,o,t):this.init(e,t,o,n)}s.type="backend";o.default=s;t.exports=o.default},{"./request.js":3,"./utils.js":4}],3:[function(t,o,n){!function(d){!function(){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var s,a,c,e=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=l(e)&&"function"!=typeof e)return{default:e};t=u(t);if(t&&t.has(e))return t.get(e);var o,n={__proto__:null},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(o in e){var r;"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&((r=i?Object.getOwnPropertyDescriptor(e,o):null)&&(r.get||r.set)?Object.defineProperty(n,o,r):n[o]=e[o])}return n.default=e,t&&t.set(e,n),n}(t("./getFetch.js"));function u(e){var t,o;return"function"!=typeof WeakMap?null:(t=new WeakMap,o=new WeakMap,(u=function(e){return e?o:t})(e))}function l(e){return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}"function"==typeof fetch&&(s=void 0!==d&&d.fetch?d.fetch:"undefined"!=typeof window&&window.fetch?window.fetch:fetch),"function"!=typeof XMLHttpRequest&&"object"!==("undefined"==typeof XMLHttpRequest?"undefined":l(XMLHttpRequest))||(void 0!==d&&d.XMLHttpRequest?a=d.XMLHttpRequest:"undefined"!=typeof window&&window.XMLHttpRequest&&(a=window.XMLHttpRequest)),"function"==typeof ActiveXObject&&(void 0!==d&&d.ActiveXObject?c=d.ActiveXObject:"undefined"!=typeof window&&window.ActiveXObject&&(c=window.ActiveXObject)),"function"!=typeof(s=s||!e||a||c?s:e.default||e)&&(s=void 0);function f(e,t,o,n){function i(t){var o=t.headers&&"Error from cloudfront"===t.headers.get("x-cache");if(!t.ok)return n(t.statusText||"Error",{status:t.status,resourceNotExisting:o});t.text().then(function(e){n(null,{status:t.status,data:e,resourceNotExisting:o})}).catch(n)}var r={};"undefined"==typeof window&&void 0!==d&&void 0!==d.process&&d.process.versions&&d.process.versions.node&&(r["User-Agent"]="i18next-locize-backend (node/".concat(d.process.version,"; ").concat(d.process.platform," ").concat(d.process.arch,")")),e.authorize&&e.apiKey&&(r.Authorization=e.apiKey),(o||e.setContentTypeJSON)&&(r["Content-Type"]="application/json"),("function"==typeof fetch?fetch:s)(t,{method:o?"POST":"GET",body:o?JSON.stringify(o):void 0,headers:r}).then(i).catch(n)}n.default=function(e,t,o,n){if("function"==typeof o&&(n=o,o=void 0),n=n||function(){},s)return f(e,t,o,n);if("function"==typeof XMLHttpRequest||"object"===("undefined"==typeof XMLHttpRequest?"undefined":l(XMLHttpRequest))||"function"==typeof ActiveXObject){var i=n;try{var r=a?new a:new c("MSXML2.XMLHTTP.3.0");r.open(o?"POST":"GET",t,1),e.crossDomain||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.authorize&&e.apiKey&&r.setRequestHeader("Authorization",e.apiKey),(o||e.setContentTypeJSON)&&r.setRequestHeader("Content-Type","application/json"),r.onreadystatechange=function(){var e="Error from cloudfront"===r.getResponseHeader("x-cache");3<r.readyState&&i(400<=r.status?r.statusText:null,{status:r.status,data:r.responseText,resourceNotExisting:e})},r.send(JSON.stringify(o))}catch(e){console&&console.log(e)}}else n(new Error("No fetch and no xhr implementation found!"))};o.exports=n.default}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./getFetch.js":1}],4:[function(e,t,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.debounce=function(n,i,r){var s;return function(){var e=this,t=arguments,o=r&&!s;clearTimeout(s),s=setTimeout(function(){s=null,r||n.apply(e,t)},i),o&&n.apply(e,t)}},o.defaults=function(o){return n.call(i.call(arguments,1),function(e){if(e)for(var t in e)void 0===o[t]&&(o[t]=e[t])}),o},o.defer=function(){var o,n,e=new Promise(function(e,t){o=e,n=t});return e.resolve=o,e.reject=n,e},o.getPath=function(e,t){e=r(e,t),t=e.obj,e=e.k;if(t)return t[e]},o.interpolate=function(e,t,o){var n,i;for(;n=s.exec(e);)i=(i=(i="string"!=typeof(i=n[1].trim())?function(e){return null==e?"":""+e}(i):i)||"").replace(/\$/g,"$$$$"),e=e.replace(n[0],t[i]||i),s.lastIndex=0;return e},o.isMissingOption=a,o.optionExist=function(e,t){return!a(e,t)},o.pushPath=function(e,t,o,n){e=r(e,t,Object),t=e.obj,e=e.k;t[e]=t[e]||[],n&&(t[e]=t[e].concat(o));n||t[e].push(o)},o.setPath=function(e,t,o){e=r(e,t,Object),t=e.obj,e=e.k;t[e]=o};var o=[],n=o.forEach,i=o.slice;function r(e,t,o){function n(e){return e&&-1<e.indexOf("###")?e.replace(/###/g,"."):e}for(var i="string"!=typeof t?[].concat(t):t.split(".");1<i.length;){if(!e)return{};var r=n(i.shift());!e[r]&&o&&(e[r]=new o),e=e[r]}return e?{obj:e,k:n(i.shift())}:{}}var s=new RegExp("{{(.+?)}}","g");function a(o,e){return e.reduce(function(e,t){return e||(!o||!o[t]||"string"!=typeof o[t]||!o[t].toLowerCase()===t.toLowerCase())&&(e='i18next-locize-backend :: got "'.concat(o[t],'" in options for ').concat(t," which is invalid."),console.warn(e),e)},!1)}},{}],5:[function(e,t,o){},{}]},{},[2])(2)});