update modules

This commit is contained in:
s2
2020-06-08 08:50:28 +02:00
parent ae4aaf2668
commit 27635904a6
477 changed files with 20385 additions and 35036 deletions

View File

@@ -1,3 +1,30 @@
### 4.2.0
- Add config option checkForSimilarInWhitelist [211](https://github.com/i18next/i18next-browser-languageDetector/pull/211)
### 4.1.1
- fix: pass cookieOptions with the cacheUserLang [205](https://github.com/i18next/i18next-browser-languageDetector/pull/205)
### 4.1.0
- feat: add cookieOptions for setting cookies [203](https://github.com/i18next/i18next-browser-languageDetector/pull/203)
### 4.0.2
- update index file to reflect build changes done in 4.0.0
### 4.0.1
- typescript: Use updated ts export default from i18next [194](https://github.com/i18next/i18next-browser-languageDetector/pull/194)
### 4.0.0
- removes deprecated jsnext:main from package.json
- Bundle all entry points with rollup bringing it up to same standard as [xhr-backend](https://github.com/i18next/i18next-xhr-backend/pull/314)
- **note:** dist/es -> dist/esm, dist/commonjs -> dist/cjs (individual files -> one bundled file)
- removes bower finally
### v3.1.1
- add default checkWhitelist: true

View File

@@ -67,7 +67,17 @@ As with all modules you can either pass the constructor function (class) to the
htmlTag: document.documentElement,
// only detect languages that are in the whitelist
checkWhitelist: true
checkWhitelist: true,
// fallback to a similar whitelist language
// Example 1: Browser language is 'es'
// if 'es' is not found in whitelist, first fallback to any whitelist language that starts with 'es-', then fallback to fallbackLng ('es' -> 'es-*' -> fallbackLng)
// Example 2: Browser language is 'es-MX'
// if 'es-MX' is not found in whitelist, first fallback to 'es', then fallback to 'es-*', then fallback to fallbackLng ('es-MX' -> 'es' -> 'es-*' -> fallbackLng)
checkForSimilarInWhitelist: false,
// optional set cookie options, reference:[MDN Set-Cookie docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)
cookieOptions: {path:'/'}
}
```

View File

@@ -0,0 +1,363 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _classCallCheck = _interopDefault(require('@babel/runtime/helpers/classCallCheck'));
var _createClass = _interopDefault(require('@babel/runtime/helpers/createClass'));
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
var cookie = {
create: function create(name, value, minutes, domain) {
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/'
};
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toUTCString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
cookieOptions = Object.keys(cookieOptions).reduce(function (acc, key) {
return acc + ';' + key.replace(/([A-Z])/g, function ($1) {
return '-' + $1.toLowerCase();
}) + '=' + cookieOptions[key];
}, '');
document.cookie = name + '=' + encodeURIComponent(value) + expires + ';' + domain + cookieOptions;
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};
var path = {
name: 'path',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
} else {
found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
}
}
}
return found;
}
};
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true,
checkForSimilarInWhitelist: false
};
}
var Browser =
/*#__PURE__*/
function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults()); // if checking for similar, user needs to check whitelist
if (this.options.checkForSimilarInWhitelist) this.options.checkWhitelist = true; // backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(navigator$1);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
}, {
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
if (!found && _this.options.checkForSimilarInWhitelist) {
found = _this.getSimilarInWhitelist(cleanedLng);
}
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks["default"] && fallbacks["default"][0];
}
}
return found;
}
}, {
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}, {
key: "getSimilarInWhitelist",
value: function getSimilarInWhitelist(cleanedLng) {
var _this3 = this;
if (!this.i18nOptions.whitelist) return;
if (cleanedLng.includes('-')) {
// i.e. es-MX should check if es is in whitelist
var prefix = cleanedLng.split('-')[0];
var cleanedPrefix = this.services.languageUtils.formatLanguageCode(prefix);
if (this.services.languageUtils.isWhitelisted(cleanedPrefix)) return cleanedPrefix; // if reached here, nothing found. continue to search for similar using only prefix
cleanedLng = cleanedPrefix;
} // i.e. 'pt' should return 'pt-BR'. If multiple in whitelist with 'pt-', then use first one in whitelist
var similar = this.i18nOptions.whitelist.find(function (whitelistLng) {
var cleanedWhitelistLng = _this3.services.languageUtils.formatLanguageCode(whitelistLng);
if (cleanedWhitelistLng.startsWith(cleanedLng)) return cleanedWhitelistLng;
});
if (similar) return similar;
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
module.exports = Browser;

View File

@@ -1,53 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var cookie = {
create: function create(name, value, minutes, domain) {
var expires = void 0;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toGMTString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
exports.default = {
name: 'cookie',
lookup: function lookup(options) {
var found = void 0;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain);
}
}
};

View File

@@ -1,19 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'htmlTag',
lookup: function lookup(options) {
var found = void 0;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};

View File

@@ -1,34 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var hasLocalStorageSupport = void 0;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
exports.default = {
name: 'localStorage',
lookup: function lookup(options) {
var found = void 0;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};

View File

@@ -1,29 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};

View File

@@ -1,26 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'path',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};

View File

@@ -1,28 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'querystring',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};

View File

@@ -1,23 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'subdomain',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
} else {
found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
}
}
}
return found;
}
};

View File

@@ -1,158 +0,0 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _utils = require('./utils.js');
var utils = _interopRequireWildcard(_utils);
var _cookie = require('./browserLookups/cookie.js');
var _cookie2 = _interopRequireDefault(_cookie);
var _querystring = require('./browserLookups/querystring.js');
var _querystring2 = _interopRequireDefault(_querystring);
var _localStorage = require('./browserLookups/localStorage.js');
var _localStorage2 = _interopRequireDefault(_localStorage);
var _navigator = require('./browserLookups/navigator.js');
var _navigator2 = _interopRequireDefault(_navigator);
var _htmlTag = require('./browserLookups/htmlTag.js');
var _htmlTag2 = _interopRequireDefault(_htmlTag);
var _path = require('./browserLookups/path.js');
var _path2 = _interopRequireDefault(_path);
var _subdomain = require('./browserLookups/subdomain.js');
var _subdomain2 = _interopRequireDefault(_subdomain);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true
};
}
var Browser = function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: 'init',
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = utils.defaults(options, this.options || {}, getDefaults());
// backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(_cookie2.default);
this.addDetector(_querystring2.default);
this.addDetector(_localStorage2.default);
this.addDetector(_navigator2.default);
this.addDetector(_htmlTag2.default);
this.addDetector(_path2.default);
this.addDetector(_subdomain2.default);
}
}, {
key: 'addDetector',
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: 'detect',
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found = void 0;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks.default && fallbacks.default[0];
}
}
return found;
}
}, {
key: 'cacheUserLanguage',
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
exports.default = Browser;

View File

@@ -1,32 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defaults = defaults;
exports.extend = extend;
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
function extend(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
}

View File

@@ -1,48 +0,0 @@
var cookie = {
create: function create(name, value, minutes, domain) {
var expires = void 0;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toGMTString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
export default {
name: 'cookie',
lookup: function lookup(options) {
var found = void 0;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain);
}
}
};

View File

@@ -1,14 +0,0 @@
export default {
name: 'htmlTag',
lookup: function lookup(options) {
var found = void 0;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};

View File

@@ -1,29 +0,0 @@
var hasLocalStorageSupport = void 0;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
export default {
name: 'localStorage',
lookup: function lookup(options) {
var found = void 0;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};

View File

@@ -1,24 +0,0 @@
export default {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};

View File

@@ -1,21 +0,0 @@
export default {
name: 'path',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};

View File

@@ -1,23 +0,0 @@
export default {
name: 'querystring',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};

View File

@@ -1,18 +0,0 @@
export default {
name: 'subdomain',
lookup: function lookup(options) {
var found = void 0;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
} else {
found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
}
}
}
return found;
}
};

View File

@@ -1,125 +0,0 @@
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
import * as utils from './utils.js';
import cookie from './browserLookups/cookie.js';
import querystring from './browserLookups/querystring.js';
import localStorage from './browserLookups/localStorage.js';
import navigator from './browserLookups/navigator.js';
import htmlTag from './browserLookups/htmlTag.js';
import path from './browserLookups/path.js';
import subdomain from './browserLookups/subdomain.js';
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true
};
}
var Browser = function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: 'init',
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = utils.defaults(options, this.options || {}, getDefaults());
// backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(navigator);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
}, {
key: 'addDetector',
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: 'detect',
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found = void 0;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks.default && fallbacks.default[0];
}
}
return found;
}
}, {
key: 'cacheUserLanguage',
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
export default Browser;

View File

@@ -1,25 +0,0 @@
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
export function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
export function extend(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
}

View File

@@ -0,0 +1,359 @@
import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
import _createClass from '@babel/runtime/helpers/esm/createClass';
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
var cookie = {
create: function create(name, value, minutes, domain) {
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/'
};
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toUTCString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
cookieOptions = Object.keys(cookieOptions).reduce(function (acc, key) {
return acc + ';' + key.replace(/([A-Z])/g, function ($1) {
return '-' + $1.toLowerCase();
}) + '=' + cookieOptions[key];
}, '');
document.cookie = name + '=' + encodeURIComponent(value) + expires + ';' + domain + cookieOptions;
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && hasLocalStorageSupport) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};
var path = {
name: 'path',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
} else {
found = language[0].replace('http://', '').replace('https://', '').replace('.', '');
}
}
}
return found;
}
};
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true,
checkForSimilarInWhitelist: false
};
}
var Browser =
/*#__PURE__*/
function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults()); // if checking for similar, user needs to check whitelist
if (this.options.checkForSimilarInWhitelist) this.options.checkWhitelist = true; // backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(navigator$1);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
}, {
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
if (!found && _this.options.checkForSimilarInWhitelist) {
found = _this.getSimilarInWhitelist(cleanedLng);
}
});
if (!found) {
var fallbacks = this.i18nOptions.fallbackLng;
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (!fallbacks) fallbacks = [];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks["default"] && fallbacks["default"][0];
}
}
return found;
}
}, {
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}, {
key: "getSimilarInWhitelist",
value: function getSimilarInWhitelist(cleanedLng) {
var _this3 = this;
if (!this.i18nOptions.whitelist) return;
if (cleanedLng.includes('-')) {
// i.e. es-MX should check if es is in whitelist
var prefix = cleanedLng.split('-')[0];
var cleanedPrefix = this.services.languageUtils.formatLanguageCode(prefix);
if (this.services.languageUtils.isWhitelisted(cleanedPrefix)) return cleanedPrefix; // if reached here, nothing found. continue to search for similar using only prefix
cleanedLng = cleanedPrefix;
} // i.e. 'pt' should return 'pt-BR'. If multiple in whitelist with 'pt-', then use first one in whitelist
var similar = this.i18nOptions.whitelist.find(function (whitelistLng) {
var cleanedWhitelistLng = _this3.services.languageUtils.formatLanguageCode(whitelistLng);
if (cleanedWhitelistLng.startsWith(cleanedLng)) return cleanedWhitelistLng;
});
if (similar) return similar;
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
export default Browser;

View File

@@ -1,13 +1,34 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.i18nextBrowserLanguageDetector = factory());
}(this, function () { 'use strict';
(global = global || self, global.i18nextBrowserLanguageDetector = factory());
}(this, (function () { 'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
@@ -21,38 +42,49 @@
var cookie = {
create: function create(name, value, minutes, domain) {
var expires = void 0;
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/'
};
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toGMTString();
expires = '; expires=' + date.toUTCString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
},
domain = domain ? 'domain=' + domain + ';' : '';
cookieOptions = Object.keys(cookieOptions).reduce(function (acc, key) {
return acc + ';' + key.replace(/([A-Z])/g, function ($1) {
return '-' + $1.toLowerCase();
}) + '=' + cookieOptions[key];
}, '');
document.cookie = name + '=' + encodeURIComponent(value) + expires + ';' + domain + cookieOptions;
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found = void 0;
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
@@ -63,24 +95,26 @@
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain);
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
@@ -92,7 +126,8 @@
}
};
var hasLocalStorageSupport = void 0;
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
@@ -104,9 +139,8 @@
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found = void 0;
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
@@ -124,7 +158,6 @@
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
@@ -135,9 +168,11 @@
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
@@ -149,9 +184,8 @@
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found = void 0;
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
@@ -164,33 +198,37 @@
var path = {
name: 'path',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
@@ -199,31 +237,30 @@
}
}
}
return found;
}
};
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true
checkWhitelist: true,
checkForSimilarInWhitelist: false
};
}
var Browser = function () {
var Browser =
/*#__PURE__*/
function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -231,24 +268,21 @@
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: 'init',
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults());
this.options = defaults(options, this.options || {}, getDefaults()); // if checking for similar, user needs to check whitelist
if (this.options.checkForSimilarInWhitelist) this.options.checkWhitelist = true; // backwards compatibility
// backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
@@ -258,31 +292,36 @@
this.addDetector(subdomain);
}
}, {
key: 'addDetector',
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: 'detect',
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found = void 0;
var found;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
if (!found && _this.options.checkForSimilarInWhitelist) {
found = _this.getSimilarInWhitelist(cleanedLng);
}
});
if (!found) {
@@ -293,14 +332,14 @@
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks.default && fallbacks.default[0];
found = fallbacks[0] || fallbacks["default"] && fallbacks["default"][0];
}
}
return found;
}
}, {
key: 'cacheUserLanguage',
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
@@ -311,6 +350,30 @@
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}, {
key: "getSimilarInWhitelist",
value: function getSimilarInWhitelist(cleanedLng) {
var _this3 = this;
if (!this.i18nOptions.whitelist) return;
if (cleanedLng.includes('-')) {
// i.e. es-MX should check if es is in whitelist
var prefix = cleanedLng.split('-')[0];
var cleanedPrefix = this.services.languageUtils.formatLanguageCode(prefix);
if (this.services.languageUtils.isWhitelisted(cleanedPrefix)) return cleanedPrefix; // if reached here, nothing found. continue to search for similar using only prefix
cleanedLng = cleanedPrefix;
} // i.e. 'pt' should return 'pt-BR'. If multiple in whitelist with 'pt-', then use first one in whitelist
var similar = this.i18nOptions.whitelist.find(function (whitelistLng) {
var cleanedWhitelistLng = _this3.services.languageUtils.formatLanguageCode(whitelistLng);
if (cleanedWhitelistLng.startsWith(cleanedLng)) return cleanedWhitelistLng;
});
if (similar) return similar;
}
}]);
return Browser;
@@ -320,4 +383,4 @@
return Browser;
}));
})));

File diff suppressed because one or more lines are too long

View File

@@ -1,13 +1,34 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.i18nextBrowserLanguageDetector = factory());
}(this, function () { 'use strict';
(global = global || self, global.i18nextBrowserLanguageDetector = factory());
}(this, (function () { 'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
@@ -21,38 +42,49 @@
var cookie = {
create: function create(name, value, minutes, domain) {
var expires = void 0;
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/'
};
var expires;
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + minutes * 60 * 1000);
expires = '; expires=' + date.toGMTString();
expires = '; expires=' + date.toUTCString();
} else expires = '';
domain = domain ? 'domain=' + domain + ';' : '';
document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
},
domain = domain ? 'domain=' + domain + ';' : '';
cookieOptions = Object.keys(cookieOptions).reduce(function (acc, key) {
return acc + ';' + key.replace(/([A-Z])/g, function ($1) {
return '-' + $1.toLowerCase();
}) + '=' + cookieOptions[key];
}, '');
document.cookie = name + '=' + encodeURIComponent(value) + expires + ';' + domain + cookieOptions;
},
read: function read(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found = void 0;
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
@@ -63,24 +95,26 @@
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain);
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
@@ -92,7 +126,8 @@
}
};
var hasLocalStorageSupport = void 0;
var hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
@@ -104,9 +139,8 @@
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found = void 0;
var found;
if (options.lookupLocalStorage && hasLocalStorageSupport) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
@@ -124,7 +158,6 @@
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
@@ -135,9 +168,11 @@
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
@@ -149,9 +184,8 @@
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found = void 0;
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
@@ -164,33 +198,37 @@
var path = {
name: 'path',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
var found = void 0;
var found;
if (typeof window !== 'undefined') {
var language = window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);
if (language instanceof Array) {
if (typeof options.lookupFromSubdomainIndex === 'number') {
found = language[options.lookupFromSubdomainIndex].replace('http://', '').replace('https://', '').replace('.', '');
@@ -199,31 +237,30 @@
}
}
}
return found;
}
};
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'],
//cookieMinutes: 10,
//cookieDomain: 'myDomain'
checkWhitelist: true
checkWhitelist: true,
checkForSimilarInWhitelist: false
};
}
var Browser = function () {
var Browser =
/*#__PURE__*/
function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -231,24 +268,21 @@
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass(Browser, [{
key: 'init',
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults());
this.options = defaults(options, this.options || {}, getDefaults()); // if checking for similar, user needs to check whitelist
if (this.options.checkForSimilarInWhitelist) this.options.checkWhitelist = true; // backwards compatibility
// backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
@@ -258,31 +292,36 @@
this.addDetector(subdomain);
}
}, {
key: 'addDetector',
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: 'detect',
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
var found = void 0;
var found;
detected.forEach(function (lng) {
if (found) return;
var cleanedLng = _this.services.languageUtils.formatLanguageCode(lng);
if (!_this.options.checkWhitelist || _this.services.languageUtils.isWhitelisted(cleanedLng)) found = cleanedLng;
if (!found && _this.options.checkForSimilarInWhitelist) {
found = _this.getSimilarInWhitelist(cleanedLng);
}
});
if (!found) {
@@ -293,14 +332,14 @@
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0];
} else {
found = fallbacks[0] || fallbacks.default && fallbacks.default[0];
found = fallbacks[0] || fallbacks["default"] && fallbacks["default"][0];
}
}
return found;
}
}, {
key: 'cacheUserLanguage',
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
@@ -311,6 +350,30 @@
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}, {
key: "getSimilarInWhitelist",
value: function getSimilarInWhitelist(cleanedLng) {
var _this3 = this;
if (!this.i18nOptions.whitelist) return;
if (cleanedLng.includes('-')) {
// i.e. es-MX should check if es is in whitelist
var prefix = cleanedLng.split('-')[0];
var cleanedPrefix = this.services.languageUtils.formatLanguageCode(prefix);
if (this.services.languageUtils.isWhitelisted(cleanedPrefix)) return cleanedPrefix; // if reached here, nothing found. continue to search for similar using only prefix
cleanedLng = cleanedPrefix;
} // i.e. 'pt' should return 'pt-BR'. If multiple in whitelist with 'pt-', then use first one in whitelist
var similar = this.i18nOptions.whitelist.find(function (whitelistLng) {
var cleanedWhitelistLng = _this3.services.languageUtils.formatLanguageCode(whitelistLng);
if (cleanedWhitelistLng.startsWith(cleanedLng)) return cleanedWhitelistLng;
});
if (similar) return similar;
}
}]);
return Browser;
@@ -320,4 +383,4 @@
return Browser;
}));
})));

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
/* eslint no-var: 0 */
var main = require('./dist/commonjs/index.js').default;
var main = require('./dist/cjs/i18nextBrowserLanguageDetector.js');
module.exports = main;
module.exports.default = main;
module.exports.default = main;

View File

@@ -1,32 +1,27 @@
{
"_args": [
[
"i18next-browser-languagedetector@3.1.1",
"D:\\Projects\\siag\\vanillajs-seed"
]
],
"_from": "i18next-browser-languagedetector@3.1.1",
"_id": "i18next-browser-languagedetector@3.1.1",
"_from": "i18next-browser-languagedetector@^4.2.0",
"_id": "i18next-browser-languagedetector@4.2.0",
"_inBundle": false,
"_integrity": "sha512-JBgFWijjI1t6as4WgGvDdX4GLJPZwC/SMHzLQQ3ef7XaJsEkomlXFqXifKvOVJg09Hj2BVWe6strDdIF4J/0ng==",
"_integrity": "sha512-qRSCBWgDUSqVQb3sTxkDC+ImYLhF+wB387Y1RpOcJvyex+V3abi+W83n4Awy+dx719AOBbKTy97FjrUGrAhbyw==",
"_location": "/i18next-browser-languagedetector",
"_phantomChildren": {},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "i18next-browser-languagedetector@3.1.1",
"raw": "i18next-browser-languagedetector@^4.2.0",
"name": "i18next-browser-languagedetector",
"escapedName": "i18next-browser-languagedetector",
"rawSpec": "3.1.1",
"rawSpec": "^4.2.0",
"saveSpec": null,
"fetchSpec": "3.1.1"
"fetchSpec": "^4.2.0"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-3.1.1.tgz",
"_spec": "3.1.1",
"_where": "D:\\Projects\\siag\\vanillajs-seed",
"_resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-4.2.0.tgz",
"_shasum": "82e35d31f88a1d7c2b6d5913bf8c8481cd40aafb",
"_spec": "i18next-browser-languagedetector@^4.2.0",
"_where": "D:\\Projects\\vanillajs-seed",
"author": {
"name": "Jan Mühlemann",
"email": "jan.muehlemann@gmail.com",
@@ -35,59 +30,62 @@
"bugs": {
"url": "https://github.com/i18next/i18next-browser-languageDetector/issues"
},
"dependencies": {},
"bundleDependencies": false,
"dependencies": {
"@babel/runtime": "^7.5.5"
},
"deprecated": false,
"description": "language detector used in browser environment for i18next",
"devDependencies": {
"babel-cli": "6.26.0",
"babel-core": "6.26.3",
"babel-eslint": "10.0.2",
"babel-plugin-external-helpers": "6.22.0",
"babel-plugin-transform-es2015-classes": "6.24.1",
"babel-preset-es2015": "6.24.1",
"babel-preset-stage-0": "6.24.1",
"@babel/core": "^7.5.5",
"@babel/plugin-transform-runtime": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"babel-eslint": "^10.0.2",
"babel-polyfill": "^6.26.0",
"babelify": "^10.0.0",
"browserify": "16.3.0",
"browserify-istanbul": "3.0.1",
"chai": "4.2.0",
"coveralls": "3.0.5",
"cpy-cli": "^2.0.0",
"dtslint": "^0.9.1",
"eslint": "6.1.0",
"eslint-config-airbnb": "17.1.1",
"i18next": "^17.0.9",
"expect.js": "0.3.1",
"i18next": "^19.0.0",
"mkdirp": "0.5.1",
"mocha": "7.1.2",
"rimraf": "2.6.3",
"rollup": "1.19.4",
"rollup-plugin-babel": "4.3.3",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-uglify": "6.0.2",
"rollup": "^1.18.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "^5.1.1",
"tslint": "^5.18.0",
"typescript": "^3.5.3",
"yargs": "13.3.0"
},
"homepage": "https://github.com/i18next/i18next-browser-languageDetector",
"jsnext:main": "dist/es/index.js",
"keywords": [
"i18next",
"i18next-languageDetector"
],
"license": "MIT",
"main": "./index.js",
"main": "./dist/cjs/i18nextBrowserLanguageDetector.js",
"module": "./dist/esm/i18nextBrowserLanguageDetector.js",
"name": "i18next-browser-languagedetector",
"repository": {
"type": "git",
"url": "git+https://github.com/i18next/i18next-browser-languageDetector.git"
},
"scripts": {
"build": "npm run clean && npm run build:cjs && npm run build:es && npm run build:umd && npm run copy",
"build:amd": "rollup -c rollup.config.js --format amd && rollup -c rollup.config.js --format umd --uglify",
"build:cjs": "babel src --out-dir dist/commonjs",
"build:es": "BABEL_ENV=jsnext babel src --out-dir dist/es",
"build:iife": "rollup -c rollup.config.js --format iife && rollup -c rollup.config.js --format iife --uglify",
"build:umd": "rollup -c rollup.config.js --format umd && rollup -c rollup.config.js --format umd --uglify",
"clean": "rimraf dist && mkdirp dist",
"copy": "cp ./dist/umd/i18nextBrowserLanguageDetector.min.js ./i18nextBrowserLanguageDetector.min.js && cp ./dist/umd/i18nextBrowserLanguageDetector.js ./i18nextBrowserLanguageDetector.js",
"build": "rimraf dist && rollup -c && cpy \"./dist/umd/*.js\" ./",
"postversion": "git push && git push --tags",
"pretest": "npm run test:typescript && npm run test:typescript:noninterop",
"preversion": "npm run build && git push",
"test": "echo 'TODO'",
"test": "npm run build && mocha test -R spec --exit",
"test:typescript": "tslint --project tsconfig.json",
"test:typescript:noninterop": "tslint --project tsconfig.nonEsModuleInterop.json"
},
"types": "./index.d.ts",
"version": "3.1.1"
"version": "4.2.0"
}

View File

@@ -4,7 +4,5 @@
// typescript defaults to these
"esModuleInterop": false,
"allowSyntheticDefaultImports": false
},
"include": ["./test/typescript/nonEsModuleInterop/**/*.ts"],
"exclude": []
}
}