Socket
Socket
Sign inDemoInstall

i18next-scanner

Package Overview
Dependencies
Maintainers
1
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

i18next-scanner - npm Package Compare versions

Comparing version 2.10.2 to 2.10.3

90

lib/acorn-jsx-walk.js

@@ -1,59 +0,61 @@

'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = void 0;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _acornWalk = require("acorn-walk");
var _acornWalk = require('acorn-walk');
var _acornDynamicImport = require("acorn-dynamic-import");
var _acornDynamicImport = require('acorn-dynamic-import');
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // Originally from: https://github.com/sderosiaux/acorn-jsx-walk
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
Object.assign(_acornWalk.base, _defineProperty({
FieldDefinition: function FieldDefinition(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
FieldDefinition: function FieldDefinition(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
}, _acornDynamicImport.DynamicImportKey, function () {}));
}
}, _acornDynamicImport.DynamicImportKey, function () {})); // Extends acorn walk with JSX elements
// https://github.com/RReverser/acorn-jsx/issues/23#issuecomment-403753801
// Extends acorn walk with JSX elements
// https://github.com/RReverser/acorn-jsx/issues/23#issuecomment-403753801
Object.assign(_acornWalk.base, {
JSXAttribute: function JSXAttribute(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
},
JSXElement: function JSXElement(node, state, callback) {
node.openingElement.attributes.forEach(function (attribute) {
callback(attribute, state);
});
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXEmptyExpression: function JSXEmptyExpression(node, state, callback) {
// Comments. Just ignore.
},
JSXExpressionContainer: function JSXExpressionContainer(node, state, callback) {
callback(node.expression, state);
},
JSXFragment: function JSXFragment(node, state, callback) {
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXSpreadAttribute: function JSXSpreadAttribute(node, state, callback) {
callback(node.argument, state);
},
JSXText: function JSXText() {}
JSXAttribute: function JSXAttribute(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
},
JSXElement: function JSXElement(node, state, callback) {
node.openingElement.attributes.forEach(function (attribute) {
callback(attribute, state);
});
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXEmptyExpression: function JSXEmptyExpression(node, state, callback) {// Comments. Just ignore.
},
JSXExpressionContainer: function JSXExpressionContainer(node, state, callback) {
callback(node.expression, state);
},
JSXFragment: function JSXFragment(node, state, callback) {
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXSpreadAttribute: function JSXSpreadAttribute(node, state, callback) {
callback(node.argument, state);
},
JSXText: function JSXText() {}
});
exports.default = function (ast, options) {
(0, _acornWalk.simple)(ast, _extends({}, options));
};
var _default = function _default(ast, options) {
(0, _acornWalk.simple)(ast, _objectSpread({}, options));
};
exports["default"] = _default;

@@ -1,13 +0,12 @@

'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = void 0;
var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// flattenObjectKeys({

@@ -31,10 +30,10 @@ // a: {

var flattenObjectKeys = function flattenObjectKeys(obj) {
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return Object.keys(obj).reduce(function (acc, key) {
var o = (0, _isPlainObject2.default)(obj[key]) && Object.keys(obj[key]).length > 0 || Array.isArray(obj[key]) && obj[key].length > 0 ? flattenObjectKeys(obj[key], keys.concat(key)) : [keys.concat(key)];
return acc.concat(o);
}, []);
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return Object.keys(obj).reduce(function (acc, key) {
var o = (0, _isPlainObject["default"])(obj[key]) && Object.keys(obj[key]).length > 0 || Array.isArray(obj[key]) && obj[key].length > 0 ? flattenObjectKeys(obj[key], keys.concat(key)) : [keys.concat(key)];
return acc.concat(o);
}, []);
};
exports.default = flattenObjectKeys;
var _default = flattenObjectKeys;
exports["default"] = _default;

@@ -1,165 +0,147 @@

'use strict';
"use strict";
var _fs = require('fs');
var _fs = _interopRequireDefault(require("fs"));
var _fs2 = _interopRequireDefault(_fs);
var _path = _interopRequireDefault(require("path"));
var _path = require('path');
var _eol = _interopRequireDefault(require("eol"));
var _path2 = _interopRequireDefault(_path);
var _get = _interopRequireDefault(require("lodash/get"));
var _eol = require('eol');
var _includes = _interopRequireDefault(require("lodash/includes"));
var _eol2 = _interopRequireDefault(_eol);
var _vinyl = _interopRequireDefault(require("vinyl"));
var _get = require('lodash/get');
var _through = _interopRequireDefault(require("through2"));
var _get2 = _interopRequireDefault(_get);
var _parser = _interopRequireDefault(require("./parser"));
var _includes = require('lodash/includes');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _includes2 = _interopRequireDefault(_includes);
var _vinyl = require('vinyl');
var _vinyl2 = _interopRequireDefault(_vinyl);
var _through = require('through2');
var _through2 = _interopRequireDefault(_through);
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-buffer-constructor */
var transform = function transform(parser, customTransform) {
return function _transform(file, enc, done) {
var options = parser.options;
return function _transform(file, enc, done) {
var options = parser.options;
var content = _fs2.default.readFileSync(file.path, enc);
var extname = _path2.default.extname(file.path);
var content = _fs["default"].readFileSync(file.path, enc);
if ((0, _includes2.default)((0, _get2.default)(options, 'attr.extensions'), extname)) {
// Parse attribute (e.g. data-i18n="key")
parser.parseAttrFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
var extname = _path["default"].extname(file.path);
if ((0, _includes2.default)((0, _get2.default)(options, 'func.extensions'), extname)) {
// Parse translation function (e.g. i18next.t('key'))
parser.parseFuncFromString(content, {
transformOptions: {
filepath: file.path
}
});
if ((0, _includes["default"])((0, _get["default"])(options, 'attr.extensions'), extname)) {
// Parse attribute (e.g. data-i18n="key")
parser.parseAttrFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
if ((0, _includes2.default)((0, _get2.default)(options, 'trans.extensions'), extname)) {
// Look for Trans components in JSX
parser.parseTransFromString(content, {
transformOptions: {
filepath: file.path
}
});
if ((0, _includes["default"])((0, _get["default"])(options, 'func.extensions'), extname)) {
// Parse translation function (e.g. i18next.t('key'))
parser.parseFuncFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
if (typeof customTransform === 'function') {
this.parser = parser;
customTransform.call(this, file, enc, done);
return;
if ((0, _includes["default"])((0, _get["default"])(options, 'trans.extensions'), extname)) {
// Look for Trans components in JSX
parser.parseTransFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
done();
};
if (typeof customTransform === 'function') {
this.parser = parser;
customTransform.call(this, file, enc, done);
return;
}
done();
};
};
var flush = function flush(parser, customFlush) {
return function _flush(done) {
var _this = this;
return function _flush(done) {
var _this = this;
var options = parser.options;
var options = parser.options;
if (typeof customFlush === 'function') {
this.parser = parser;
customFlush.call(this, done);
return;
} // Flush to resource store
if (typeof customFlush === 'function') {
this.parser = parser;
customFlush.call(this, done);
return;
}
// Flush to resource store
var resStore = parser.get({ sort: options.sort });
var jsonIndent = options.resource.jsonIndent;
var resStore = parser.get({
sort: options.sort
});
var jsonIndent = options.resource.jsonIndent;
var lineEnding = String(options.resource.lineEnding).toLowerCase();
Object.keys(resStore).forEach(function (lng) {
var namespaces = resStore[lng];
Object.keys(namespaces).forEach(function (ns) {
var obj = namespaces[ns];
var resPath = parser.formatResourceSavePath(lng, ns);
var text = JSON.stringify(obj, null, jsonIndent) + '\n';
var lineEnding = String(options.resource.lineEnding).toLowerCase();
if (lineEnding === 'auto') {
text = _eol["default"].auto(text);
} else if (lineEnding === '\r\n' || lineEnding === 'crlf') {
text = _eol["default"].crlf(text);
} else if (lineEnding === '\n' || lineEnding === 'lf') {
text = _eol["default"].lf(text);
} else if (lineEnding === '\r' || lineEnding === 'cr') {
text = _eol["default"].cr(text);
} else {
// Defaults to LF
text = _eol["default"].lf(text);
}
Object.keys(resStore).forEach(function (lng) {
var namespaces = resStore[lng];
var contents = null;
Object.keys(namespaces).forEach(function (ns) {
var obj = namespaces[ns];
var resPath = parser.formatResourceSavePath(lng, ns);
var text = JSON.stringify(obj, null, jsonIndent) + '\n';
try {
// "Buffer.from(string[, encoding])" is added in Node.js v5.10.0
contents = Buffer.from(text);
} catch (e) {
// Fallback to "new Buffer(string[, encoding])" which is deprecated since Node.js v6.0.0
contents = new Buffer(text);
}
if (lineEnding === 'auto') {
text = _eol2.default.auto(text);
} else if (lineEnding === '\r\n' || lineEnding === 'crlf') {
text = _eol2.default.crlf(text);
} else if (lineEnding === '\n' || lineEnding === 'lf') {
text = _eol2.default.lf(text);
} else if (lineEnding === '\r' || lineEnding === 'cr') {
text = _eol2.default.cr(text);
} else {
// Defaults to LF
text = _eol2.default.lf(text);
}
_this.push(new _vinyl["default"]({
path: resPath,
contents: contents
}));
});
});
done();
};
}; // @param {object} options The options object.
// @param {function} [customTransform]
// @param {function} [customFlush]
// @return {object} Returns a through2.obj().
var contents = null;
try {
// "Buffer.from(string[, encoding])" is added in Node.js v5.10.0
contents = Buffer.from(text);
} catch (e) {
// Fallback to "new Buffer(string[, encoding])" which is deprecated since Node.js v6.0.0
contents = new Buffer(text);
}
var createStream = function createStream(options, customTransform, customFlush) {
var parser = new _parser["default"](options);
_this.push(new _vinyl2.default({
path: resPath,
contents: contents
}));
});
});
var stream = _through["default"].obj(transform(parser, customTransform), flush(parser, customFlush));
done();
};
};
return stream;
}; // Convenience API
// @param {object} options The options object.
// @param {function} [customTransform]
// @param {function} [customFlush]
// @return {object} Returns a through2.obj().
var createStream = function createStream(options, customTransform, customFlush) {
var parser = new _parser2.default(options);
var stream = _through2.default.obj(transform(parser, customTransform), flush(parser, customFlush));
return stream;
};
// Convenience API
module.exports = function () {
var _module$exports;
var _module$exports;
return (_module$exports = module.exports).createStream.apply(_module$exports, arguments);
};
return (_module$exports = module.exports).createStream.apply(_module$exports, arguments);
}; // Basic API
// Basic API
module.exports.createStream = createStream;
// Parser
module.exports.Parser = _parser2.default;
module.exports.createStream = createStream; // Parser
module.exports.Parser = _parser["default"];

@@ -1,84 +0,85 @@

'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = void 0;
var _get2 = require('lodash/get');
var _get2 = _interopRequireDefault(require("lodash/get"));
var _get3 = _interopRequireDefault(_get2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isJSXText = function isJSXText(node) {
if (!node) {
return false;
}
if (!node) {
return false;
}
return node.type === 'JSXText';
return node.type === 'JSXText';
};
var isNumericLiteral = function isNumericLiteral(node) {
if (!node) {
return false;
}
if (!node) {
return false;
}
return node.type === 'Literal' && typeof node.value === 'number';
return node.type === 'Literal' && typeof node.value === 'number';
};
var isStringLiteral = function isStringLiteral(node) {
if (!node) {
return false;
}
if (!node) {
return false;
}
return node.type === 'Literal' && typeof node.value === 'string';
return node.type === 'Literal' && typeof node.value === 'string';
};
var isObjectExpression = function isObjectExpression(node) {
if (!node) {
return false;
}
if (!node) {
return false;
}
return node.type === 'ObjectExpression';
return node.type === 'ObjectExpression';
};
var nodesToString = function nodesToString(nodes) {
var memo = '';
var nodeIndex = 0;
nodes.forEach(function (node, i) {
if (isJSXText(node) || isStringLiteral(node)) {
var value = node.value.replace(/^[\r\n]+\s*/g, '') // remove leading spaces containing a leading newline character
.replace(/[\r\n]+\s*$/g, '') // remove trailing spaces containing a leading newline character
.replace(/[\r\n]+\s*/g, ' '); // replace spaces containing a leading newline character with a single space character
var memo = '';
var nodeIndex = 0;
nodes.forEach(function (node, i) {
if (isJSXText(node) || isStringLiteral(node)) {
var value = node.value.replace(/^[\r\n]+\s*/g, '') // remove leading spaces containing a leading newline character
.replace(/[\r\n]+\s*$/g, '') // remove trailing spaces containing a leading newline character
.replace(/[\r\n]+\s*/g, ' '); // replace spaces containing a leading newline character with a single space character
if (!value) {
return;
}
memo += value;
} else if (node.type === 'JSXExpressionContainer') {
var _node$expression = node.expression,
expression = _node$expression === undefined ? {} : _node$expression;
if (!value) {
return;
}
memo += value;
} else if (node.type === 'JSXExpressionContainer') {
var _node$expression = node.expression,
expression = _node$expression === void 0 ? {} : _node$expression;
if (isNumericLiteral(expression)) {
// Numeric literal is ignored in react-i18next
memo += '';
}if (isStringLiteral(expression)) {
memo += expression.value;
} else if (isObjectExpression(expression) && (0, _get3.default)(expression, 'properties[0].type') === 'Property') {
memo += '<' + nodeIndex + '>{{' + expression.properties[0].key.name + '}}</' + nodeIndex + '>';
} else {
console.error('Unsupported JSX expression. Only static values or {{interpolation}} blocks are supported. Got ' + expression.type + ':');
console.error(node.expression);
}
} else if (node.children) {
memo += '<' + nodeIndex + '>' + nodesToString(node.children) + '</' + nodeIndex + '>';
}
if (isNumericLiteral(expression)) {
// Numeric literal is ignored in react-i18next
memo += '';
}
++nodeIndex;
});
if (isStringLiteral(expression)) {
memo += expression.value;
} else if (isObjectExpression(expression) && (0, _get2["default"])(expression, 'properties[0].type') === 'Property') {
memo += "<".concat(nodeIndex, ">{{").concat(expression.properties[0].key.name, "}}</").concat(nodeIndex, ">");
} else {
console.error("Unsupported JSX expression. Only static values or {{interpolation}} blocks are supported. Got ".concat(expression.type, ":"));
console.error(node.expression);
}
} else if (node.children) {
memo += "<".concat(nodeIndex, ">").concat(nodesToString(node.children), "</").concat(nodeIndex, ">");
}
return memo;
++nodeIndex;
});
return memo;
};
exports.default = nodesToString;
var _default = nodesToString;
exports["default"] = _default;

@@ -1,17 +0,14 @@

'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = void 0;
var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _cloneDeep = _interopRequireDefault(require("clone-deep"));
var _cloneDeep = require('clone-deep');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// omitEmptyObject({

@@ -32,21 +29,22 @@ // a: {

var unsetEmptyObject = function unsetEmptyObject(obj) {
Object.keys(obj).forEach(function (key) {
if (!(0, _isPlainObject2.default)(obj[key])) {
return;
}
Object.keys(obj).forEach(function (key) {
if (!(0, _isPlainObject["default"])(obj[key])) {
return;
}
unsetEmptyObject(obj[key]);
if ((0, _isPlainObject2.default)(obj[key]) && Object.keys(obj[key]).length === 0) {
obj[key] = undefined;
delete obj[key];
}
});
unsetEmptyObject(obj[key]);
return obj;
if ((0, _isPlainObject["default"])(obj[key]) && Object.keys(obj[key]).length === 0) {
obj[key] = undefined;
delete obj[key];
}
});
return obj;
};
var omitEmptyObject = function omitEmptyObject(obj) {
return unsetEmptyObject((0, _cloneDeep2.default)(obj));
return unsetEmptyObject((0, _cloneDeep["default"])(obj));
};
exports.default = omitEmptyObject;
var _default = omitEmptyObject;
exports["default"] = _default;

@@ -1,308 +0,302 @@

'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = void 0;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _fs = _interopRequireDefault(require("fs"));
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; }; }(); /* eslint no-console: 0 */
/* eslint no-eval: 0 */
var acorn = _interopRequireWildcard(require("acorn"));
var _acornJsx = _interopRequireDefault(require("acorn-jsx"));
var _fs = require('fs');
var _acornStage = _interopRequireDefault(require("acorn-stage3"));
var _fs2 = _interopRequireDefault(_fs);
var _chalk = _interopRequireDefault(require("chalk"));
var _acorn = require('acorn');
var _cloneDeep = _interopRequireDefault(require("clone-deep"));
var acorn = _interopRequireWildcard(_acorn);
var _deepmerge = _interopRequireDefault(require("deepmerge"));
var _acornJsx = require('acorn-jsx');
var _ensureArray = _interopRequireDefault(require("ensure-array"));
var _acornJsx2 = _interopRequireDefault(_acornJsx);
var _esprima = require("esprima");
var _acornStage = require('acorn-stage3');
var _lodash = _interopRequireDefault(require("lodash"));
var _acornStage2 = _interopRequireDefault(_acornStage);
var _parse = _interopRequireDefault(require("parse5"));
var _chalk = require('chalk');
var _sortobject = _interopRequireDefault(require("sortobject"));
var _chalk2 = _interopRequireDefault(_chalk);
var _i18next = _interopRequireDefault(require("i18next"));
var _cloneDeep = require('clone-deep');
var _acornJsxWalk = _interopRequireDefault(require("./acorn-jsx-walk"));
var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
var _flattenObjectKeys = _interopRequireDefault(require("./flatten-object-keys"));
var _deepmerge = require('deepmerge');
var _omitEmptyObject = _interopRequireDefault(require("./omit-empty-object"));
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _nodesToString = _interopRequireDefault(require("./nodes-to-string"));
var _ensureArray = require('ensure-array');
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
var _ensureArray2 = _interopRequireDefault(_ensureArray);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _esprima = require('esprima');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _lodash = require('lodash');
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
var _lodash2 = _interopRequireDefault(_lodash);
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var _parse = require('parse5');
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
var _parse2 = _interopRequireDefault(_parse);
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var _sortobject = require('sortobject');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _sortobject2 = _interopRequireDefault(_sortobject);
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); } }
var _i18next = require('i18next');
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var _i18next2 = _interopRequireDefault(_i18next);
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _acornJsxWalk = require('./acorn-jsx-walk');
var defaults = {
debug: false,
// verbose logging
sort: false,
// sort keys in alphabetical order
attr: {
// HTML attributes to parse
list: ['data-i18n'],
extensions: ['.html', '.htm']
},
func: {
// function names to parse
list: ['i18next.t', 'i18n.t'],
extensions: ['.js', '.jsx']
},
trans: {
// Trans component (https://github.com/i18next/react-i18next)
component: 'Trans',
i18nKey: 'i18nKey',
defaultsKey: 'defaults',
extensions: ['.js', '.jsx'],
fallbackKey: false,
acorn: {
ecmaVersion: 10,
// defaults to 10
sourceType: 'module' // defaults to 'module'
// Check out https://github.com/acornjs/acorn/tree/master/acorn#interface for additional options
var _acornJsxWalk2 = _interopRequireDefault(_acornJsxWalk);
}
},
lngs: ['en'],
// array of supported languages
fallbackLng: 'en',
// language to lookup key if not found while calling `parser.get(key, { lng: '' })`
ns: [],
// string or array of namespaces
defaultLng: 'en',
// default language used for checking default values
defaultNs: 'translation',
// default namespace used if not passed to translation function
defaultValue: '',
// default value used if not passed to `parser.set`
// resource
resource: {
// The path where resources get loaded from. Relative to current working directory.
loadPath: 'i18n/{{lng}}/{{ns}}.json',
// The path to store resources. Relative to the path specified by `gulp.dest(path)`.
savePath: 'i18n/{{lng}}/{{ns}}.json',
// Specify the number of space characters to use as white space to insert into the output JSON string for readability purpose.
jsonIndent: 2,
// Normalize line endings to '\r\n', '\r', '\n', or 'auto' for the current operating system. Defaults to '\n'.
// Aliases: 'CRLF', 'CR', 'LF', 'crlf', 'cr', 'lf'
lineEnding: '\n'
},
keySeparator: '.',
// char to separate keys
nsSeparator: ':',
// char to split namespace from key
// Context Form
context: true,
// whether to add context form key
contextFallback: true,
// whether to add a fallback key as well as the context form key
contextSeparator: '_',
// char to split context from key
// Plural Form
plural: true,
// whether to add plural form key
pluralFallback: true,
// whether to add a fallback key as well as the plural form key
pluralSeparator: '_',
// char to split plural from key
// interpolation options
interpolation: {
prefix: '{{',
// prefix for interpolation
suffix: '}}' // suffix for interpolation
var _flattenObjectKeys = require('./flatten-object-keys');
}
}; // http://codereview.stackexchange.com/questions/45991/balanced-parentheses
var _flattenObjectKeys2 = _interopRequireDefault(_flattenObjectKeys);
var matchBalancedParentheses = function matchBalancedParentheses() {
var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var parentheses = '[]{}()';
var stack = [];
var bracePosition;
var start = -1;
var i = 0;
str = '' + str; // ensure string
var _omitEmptyObject = require('./omit-empty-object');
for (i = 0; i < str.length; ++i) {
if (start >= 0 && stack.length === 0) {
return str.substring(start, i);
}
var _omitEmptyObject2 = _interopRequireDefault(_omitEmptyObject);
bracePosition = parentheses.indexOf(str[i]);
var _nodesToString = require('./nodes-to-string');
if (bracePosition < 0) {
continue;
}
var _nodesToString2 = _interopRequireDefault(_nodesToString);
if (bracePosition % 2 === 0) {
if (start < 0) {
start = i; // remember the start position
}
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; } }
stack.push(bracePosition + 1); // push next expected brace position
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
continue;
}
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
if (stack.pop() !== bracePosition) {
return str.substring(start, i);
}
}
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
return str.substring(start, i);
};
var defaults = {
debug: false, // verbose logging
var normalizeOptions = function normalizeOptions(options) {
// Attribute
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'attr.list'))) {
_lodash["default"].set(options, 'attr.list', defaults.attr.list);
}
sort: false, // sort keys in alphabetical order
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'attr.extensions'))) {
_lodash["default"].set(options, 'attr.extensions', defaults.attr.extensions);
} // Function
attr: { // HTML attributes to parse
list: ['data-i18n'],
extensions: ['.html', '.htm']
},
func: { // function names to parse
list: ['i18next.t', 'i18n.t'],
extensions: ['.js', '.jsx']
},
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'func.list'))) {
_lodash["default"].set(options, 'func.list', defaults.func.list);
}
trans: { // Trans component (https://github.com/i18next/react-i18next)
component: 'Trans',
i18nKey: 'i18nKey',
defaultsKey: 'defaults',
extensions: ['.js', '.jsx'],
fallbackKey: false,
acorn: {
ecmaVersion: 10, // defaults to 10
sourceType: 'module' // defaults to 'module'
// Check out https://github.com/acornjs/acorn/tree/master/acorn#interface for additional options
}
},
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'func.extensions'))) {
_lodash["default"].set(options, 'func.extensions', defaults.func.extensions);
} // Trans
lngs: ['en'], // array of supported languages
fallbackLng: 'en', // language to lookup key if not found while calling `parser.get(key, { lng: '' })`
ns: [], // string or array of namespaces
if (_lodash["default"].get(options, 'trans')) {
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.component'))) {
_lodash["default"].set(options, 'trans.component', defaults.trans.component);
}
defaultLng: 'en', // default language used for checking default values
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.i18nKey'))) {
_lodash["default"].set(options, 'trans.i18nKey', defaults.trans.i18nKey);
}
defaultNs: 'translation', // default namespace used if not passed to translation function
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.defaultsKey'))) {
_lodash["default"].set(options, 'trans.defaultsKey', defaults.trans.defaultsKey);
}
defaultValue: '', // default value used if not passed to `parser.set`
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.extensions'))) {
_lodash["default"].set(options, 'trans.extensions', defaults.trans.extensions);
}
// resource
resource: {
// The path where resources get loaded from. Relative to current working directory.
loadPath: 'i18n/{{lng}}/{{ns}}.json',
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.fallbackKey'))) {
_lodash["default"].set(options, 'trans.fallbackKey', defaults.trans.fallbackKey);
}
// The path to store resources. Relative to the path specified by `gulp.dest(path)`.
savePath: 'i18n/{{lng}}/{{ns}}.json',
// Specify the number of space characters to use as white space to insert into the output JSON string for readability purpose.
jsonIndent: 2,
// Normalize line endings to '\r\n', '\r', '\n', or 'auto' for the current operating system. Defaults to '\n'.
// Aliases: 'CRLF', 'CR', 'LF', 'crlf', 'cr', 'lf'
lineEnding: '\n'
},
keySeparator: '.', // char to separate keys
nsSeparator: ':', // char to split namespace from key
// Context Form
context: true, // whether to add context form key
contextFallback: true, // whether to add a fallback key as well as the context form key
contextSeparator: '_', // char to split context from key
// Plural Form
plural: true, // whether to add plural form key
pluralFallback: true, // whether to add a fallback key as well as the plural form key
pluralSeparator: '_', // char to split plural from key
// interpolation options
interpolation: {
prefix: '{{', // prefix for interpolation
suffix: '}}' // suffix for interpolation
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'trans.acorn'))) {
_lodash["default"].set(options, 'trans.acorn', defaults.trans.acorn);
}
};
} // Resource
// http://codereview.stackexchange.com/questions/45991/balanced-parentheses
var matchBalancedParentheses = function matchBalancedParentheses() {
var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var parentheses = '[]{}()';
var stack = [];
var bracePosition = void 0;
var start = -1;
var i = 0;
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'resource.loadPath'))) {
_lodash["default"].set(options, 'resource.loadPath', defaults.resource.loadPath);
}
str = '' + str; // ensure string
for (i = 0; i < str.length; ++i) {
if (start >= 0 && stack.length === 0) {
return str.substring(start, i);
}
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'resource.savePath'))) {
_lodash["default"].set(options, 'resource.savePath', defaults.resource.savePath);
}
bracePosition = parentheses.indexOf(str[i]);
if (bracePosition < 0) {
continue;
}
if (bracePosition % 2 === 0) {
if (start < 0) {
start = i; // remember the start position
}
stack.push(bracePosition + 1); // push next expected brace position
continue;
}
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'resource.jsonIndent'))) {
_lodash["default"].set(options, 'resource.jsonIndent', defaults.resource.jsonIndent);
}
if (stack.pop() !== bracePosition) {
return str.substring(start, i);
}
}
if (_lodash["default"].isUndefined(_lodash["default"].get(options, 'resource.lineEnding'))) {
_lodash["default"].set(options, 'resource.lineEnding', defaults.resource.lineEnding);
} // Accept both nsseparator or nsSeparator
return str.substring(start, i);
};
var normalizeOptions = function normalizeOptions(options) {
// Attribute
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'attr.list'))) {
_lodash2.default.set(options, 'attr.list', defaults.attr.list);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'attr.extensions'))) {
_lodash2.default.set(options, 'attr.extensions', defaults.attr.extensions);
}
if (!_lodash["default"].isUndefined(options.nsseparator)) {
options.nsSeparator = options.nsseparator;
delete options.nsseparator;
} // Allowed only string or false
// Function
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'func.list'))) {
_lodash2.default.set(options, 'func.list', defaults.func.list);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'func.extensions'))) {
_lodash2.default.set(options, 'func.extensions', defaults.func.extensions);
}
// Trans
if (_lodash2.default.get(options, 'trans')) {
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.component'))) {
_lodash2.default.set(options, 'trans.component', defaults.trans.component);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.i18nKey'))) {
_lodash2.default.set(options, 'trans.i18nKey', defaults.trans.i18nKey);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.defaultsKey'))) {
_lodash2.default.set(options, 'trans.defaultsKey', defaults.trans.defaultsKey);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.extensions'))) {
_lodash2.default.set(options, 'trans.extensions', defaults.trans.extensions);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.fallbackKey'))) {
_lodash2.default.set(options, 'trans.fallbackKey', defaults.trans.fallbackKey);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'trans.acorn'))) {
_lodash2.default.set(options, 'trans.acorn', defaults.trans.acorn);
}
}
if (!_lodash["default"].isString(options.nsSeparator)) {
options.nsSeparator = false;
} // Accept both keyseparator or keySeparator
// Resource
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'resource.loadPath'))) {
_lodash2.default.set(options, 'resource.loadPath', defaults.resource.loadPath);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'resource.savePath'))) {
_lodash2.default.set(options, 'resource.savePath', defaults.resource.savePath);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'resource.jsonIndent'))) {
_lodash2.default.set(options, 'resource.jsonIndent', defaults.resource.jsonIndent);
}
if (_lodash2.default.isUndefined(_lodash2.default.get(options, 'resource.lineEnding'))) {
_lodash2.default.set(options, 'resource.lineEnding', defaults.resource.lineEnding);
}
// Accept both nsseparator or nsSeparator
if (!_lodash2.default.isUndefined(options.nsseparator)) {
options.nsSeparator = options.nsseparator;
delete options.nsseparator;
}
// Allowed only string or false
if (!_lodash2.default.isString(options.nsSeparator)) {
options.nsSeparator = false;
}
if (!_lodash["default"].isUndefined(options.keyseparator)) {
options.keySeparator = options.keyseparator;
delete options.keyseparator;
} // Allowed only string or false
// Accept both keyseparator or keySeparator
if (!_lodash2.default.isUndefined(options.keyseparator)) {
options.keySeparator = options.keyseparator;
delete options.keyseparator;
}
// Allowed only string or false
if (!_lodash2.default.isString(options.keySeparator)) {
options.keySeparator = false;
}
if (!_lodash2.default.isArray(options.ns)) {
options.ns = [options.ns];
}
if (!_lodash["default"].isString(options.keySeparator)) {
options.keySeparator = false;
}
options.ns = _lodash2.default.union(_lodash2.default.flatten(options.ns.concat(options.defaultNs)));
if (!_lodash["default"].isArray(options.ns)) {
options.ns = [options.ns];
}
return options;
};
// Get an array of plural suffixes for a given language.
options.ns = _lodash["default"].union(_lodash["default"].flatten(options.ns.concat(options.defaultNs)));
return options;
}; // Get an array of plural suffixes for a given language.
// @param {string} lng The language.
// @param {string} pluralSeparator pluralSeparator, default '_'.
// @return {array} An array of plural suffixes.
var getPluralSuffixes = function getPluralSuffixes(lng) {
var pluralSeparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_';
var pluralSeparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_';
var rule = _i18next2.default.services.pluralResolver.getRule(lng);
var rule = _i18next["default"].services.pluralResolver.getRule(lng);
if (!(rule && rule.numbers)) {
return []; // Return an empty array if lng is not supported
}
if (!(rule && rule.numbers)) {
return []; // Return an empty array if lng is not supported
}
if (rule.numbers.length === 1) {
return [pluralSeparator + '0'];
}
if (rule.numbers.length === 1) {
return ["".concat(pluralSeparator, "0")];
}
if (rule.numbers.length === 2) {
return ['', pluralSeparator + 'plural'];
}
if (rule.numbers.length === 2) {
return ['', "".concat(pluralSeparator, "plural")];
}
var suffixes = rule.numbers.reduce(function (acc, n, i) {
return acc.concat('' + pluralSeparator + i);
}, []);
return suffixes;
var suffixes = rule.numbers.reduce(function (acc, n, i) {
return acc.concat("".concat(pluralSeparator).concat(i));
}, []);
return suffixes;
};
/**

@@ -313,801 +307,781 @@ * Creates a new parser

var Parser = function () {
// The resScan only stores translation keys parsed from code
function Parser(options) {
var _this = this;
var Parser =
/*#__PURE__*/
function () {
// The resStore stores all translation keys including unused ones
// The resScan only stores translation keys parsed from code
// The all plurals suffixes for each of target languages.
function Parser(options) {
var _this = this;
_classCallCheck(this, Parser);
_classCallCheck(this, Parser);
this.options = _extends({}, defaults);
this.resStore = {};
this.resScan = {};
this.pluralSuffixes = {};
_defineProperty(this, "options", _objectSpread({}, defaults));
this.options = normalizeOptions(_extends({}, this.options, options));
_defineProperty(this, "resStore", {});
var lngs = this.options.lngs;
var namespaces = this.options.ns;
_defineProperty(this, "resScan", {});
lngs.forEach(function (lng) {
_this.resStore[lng] = _this.resStore[lng] || {};
_this.resScan[lng] = _this.resScan[lng] || {};
_defineProperty(this, "pluralSuffixes", {});
_this.pluralSuffixes[lng] = (0, _ensureArray2.default)(getPluralSuffixes(lng, _this.options.pluralSeparator));
if (_this.pluralSuffixes[lng].length === 0) {
_this.log('No plural rule found for: ' + lng);
}
this.options = normalizeOptions(_objectSpread({}, this.options, {}, options));
var lngs = this.options.lngs;
var namespaces = this.options.ns;
lngs.forEach(function (lng) {
_this.resStore[lng] = _this.resStore[lng] || {};
_this.resScan[lng] = _this.resScan[lng] || {};
_this.pluralSuffixes[lng] = (0, _ensureArray["default"])(getPluralSuffixes(lng, _this.options.pluralSeparator));
namespaces.forEach(function (ns) {
var resPath = _this.formatResourceLoadPath(lng, ns);
if (_this.pluralSuffixes[lng].length === 0) {
_this.log("No plural rule found for: ".concat(lng));
}
_this.resStore[lng][ns] = {};
_this.resScan[lng][ns] = {};
namespaces.forEach(function (ns) {
var resPath = _this.formatResourceLoadPath(lng, ns);
try {
if (_fs2.default.existsSync(resPath)) {
_this.resStore[lng][ns] = JSON.parse(_fs2.default.readFileSync(resPath, 'utf-8'));
}
} catch (err) {
_this.error('Unable to load resource file ' + _chalk2.default.yellow(JSON.stringify(resPath)) + ': lng=' + lng + ', ns=' + ns);
_this.error(err);
}
});
});
_this.resStore[lng][ns] = {};
_this.resScan[lng][ns] = {};
this.log('options=' + JSON.stringify(this.options, null, 2));
}
try {
if (_fs["default"].existsSync(resPath)) {
_this.resStore[lng][ns] = JSON.parse(_fs["default"].readFileSync(resPath, 'utf-8'));
}
} catch (err) {
_this.error("Unable to load resource file ".concat(_chalk["default"].yellow(JSON.stringify(resPath)), ": lng=").concat(lng, ", ns=").concat(ns));
// The all plurals suffixes for each of target languages.
_this.error(err);
}
});
});
this.log("options=".concat(JSON.stringify(this.options, null, 2)));
}
_createClass(Parser, [{
key: "log",
value: function log() {
var debug = this.options.debug;
// The resStore stores all translation keys including unused ones
if (debug) {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
console.log.apply(this, [_chalk["default"].cyan('i18next-scanner:')].concat(args));
}
}
}, {
key: "error",
value: function error() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_createClass(Parser, [{
key: 'log',
value: function log() {
var debug = this.options.debug;
console.error.apply(this, [_chalk["default"].red('i18next-scanner:')].concat(args));
}
}, {
key: "formatResourceLoadPath",
value: function formatResourceLoadPath(lng, ns) {
var options = this.options;
var regex = {
lng: new RegExp(_lodash["default"].escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'),
ns: new RegExp(_lodash["default"].escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g')
};
return options.resource.loadPath.replace(regex.lng, lng).replace(regex.ns, ns);
}
}, {
key: "formatResourceSavePath",
value: function formatResourceSavePath(lng, ns) {
var options = this.options;
var regex = {
lng: new RegExp(_lodash["default"].escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'),
ns: new RegExp(_lodash["default"].escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g')
};
return options.resource.savePath.replace(regex.lng, lng).replace(regex.ns, ns);
}
}, {
key: "fixStringAfterRegExp",
value: function fixStringAfterRegExp(strToFix) {
var fixedString = _lodash["default"].trim(strToFix); // Remove leading and trailing whitespace
if (debug) {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
console.log.apply(this, [_chalk2.default.cyan('i18next-scanner:')].concat(args));
}
}
}, {
key: 'error',
value: function error() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var firstChar = fixedString[0]; // Ignore key with embedded expressions in string literals
console.error.apply(this, [_chalk2.default.red('i18next-scanner:')].concat(args));
}
}, {
key: 'formatResourceLoadPath',
value: function formatResourceLoadPath(lng, ns) {
var options = this.options;
if (firstChar === '`' && fixedString.match(/\${.*?}/)) {
return null;
}
var regex = {
lng: new RegExp(_lodash2.default.escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'),
ns: new RegExp(_lodash2.default.escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g')
};
if (_lodash["default"].includes(['\'', '"', '`'], firstChar)) {
// Remove first and last character
fixedString = fixedString.slice(1, -1);
} // restore multiline strings
return options.resource.loadPath.replace(regex.lng, lng).replace(regex.ns, ns);
}
}, {
key: 'formatResourceSavePath',
value: function formatResourceSavePath(lng, ns) {
var options = this.options;
var regex = {
lng: new RegExp(_lodash2.default.escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'),
ns: new RegExp(_lodash2.default.escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g')
};
return options.resource.savePath.replace(regex.lng, lng).replace(regex.ns, ns);
}
}, {
key: 'fixStringAfterRegExp',
value: function fixStringAfterRegExp(strToFix) {
var fixedString = _lodash2.default.trim(strToFix); // Remove leading and trailing whitespace
var firstChar = fixedString[0];
fixedString = fixedString.replace(/(\\\n|\\\r\n)/g, ''); // JavaScript character escape sequences
// https://mathiasbynens.be/notes/javascript-escapes
// Single character escape sequences
// Note: IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.
// Another thing to note is that the \v and \0 escapes are not allowed in JSON strings.
// Ignore key with embedded expressions in string literals
if (firstChar === '`' && fixedString.match(/\${.*?}/)) {
return null;
}
fixedString = fixedString.replace(/(\\b|\\f|\\n|\\r|\\t|\\v|\\0|\\\\|\\"|\\')/g, function (match) {
return eval("\"".concat(match, "\""));
}); // * Octal escapes have been deprecated in ES5.
// * Hexadecimal escape sequences: \\x[a-fA-F0-9]{2}
// * Unicode escape sequences: \\u[a-fA-F0-9]{4}
if (_lodash2.default.includes(['\'', '"', '`'], firstChar)) {
// Remove first and last character
fixedString = fixedString.slice(1, -1);
}
fixedString = fixedString.replace(/(\\x[a-fA-F0-9]{2}|\\u[a-fA-F0-9]{4})/g, function (match) {
return eval("\"".concat(match, "\""));
});
return fixedString;
} // i18next.t('ns:foo.bar') // matched
// i18next.t("ns:foo.bar") // matched
// i18next.t('ns:foo.bar') // matched
// i18next.t("ns:foo.bar", { count: 1 }); // matched
// i18next.t("ns:foo.bar" + str); // not matched
// restore multiline strings
fixedString = fixedString.replace(/(\\\n|\\\r\n)/g, '');
}, {
key: "parseFuncFromString",
value: function parseFuncFromString(content) {
var _this2 = this;
// JavaScript character escape sequences
// https://mathiasbynens.be/notes/javascript-escapes
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
// Single character escape sequences
// Note: IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.
// Another thing to note is that the \v and \0 escapes are not allowed in JSON strings.
fixedString = fixedString.replace(/(\\b|\\f|\\n|\\r|\\t|\\v|\\0|\\\\|\\"|\\')/g, function (match) {
return eval('"' + match + '"');
});
if (_lodash["default"].isFunction(opts)) {
customHandler = opts;
opts = {};
}
// * Octal escapes have been deprecated in ES5.
// * Hexadecimal escape sequences: \\x[a-fA-F0-9]{2}
// * Unicode escape sequences: \\u[a-fA-F0-9]{4}
fixedString = fixedString.replace(/(\\x[a-fA-F0-9]{2}|\\u[a-fA-F0-9]{4})/g, function (match) {
return eval('"' + match + '"');
});
return fixedString;
}
var funcs = opts.list !== undefined ? (0, _ensureArray["default"])(opts.list) : (0, _ensureArray["default"])(this.options.func.list);
// i18next.t('ns:foo.bar') // matched
// i18next.t("ns:foo.bar") // matched
// i18next.t('ns:foo.bar') // matched
// i18next.t("ns:foo.bar", { count: 1 }); // matched
// i18next.t("ns:foo.bar" + str); // not matched
if (funcs.length === 0) {
return this;
}
}, {
key: 'parseFuncFromString',
value: function parseFuncFromString(content) {
var _this2 = this;
var matchFuncs = funcs.map(function (func) {
return '(?:' + func + ')';
}).join('|').replace(/\./g, '\\.'); // `\s` matches a single whitespace character, which includes spaces, tabs, form feeds, line feeds and other unicode spaces.
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var matchSpecialCharacters = '[\\r\\n\\s]*';
var stringGroup = matchSpecialCharacters + '(' + // backtick (``)
'`(?:[^`\\\\]|\\\\(?:.|$))*`' + '|' + // double quotes ("")
'"(?:[^"\\\\]|\\\\(?:.|$))*"' + '|' + // single quote ('')
'\'(?:[^\'\\\\]|\\\\(?:.|$))*\'' + ')' + matchSpecialCharacters;
var pattern = '(?:(?:^\\s*)|[^a-zA-Z0-9_])' + '(?:' + matchFuncs + ')' + '\\(' + stringGroup + '(?:[\\,]' + stringGroup + ')?' + '[\\,\\)]';
var re = new RegExp(pattern, 'gim');
var r;
if (_lodash2.default.isFunction(opts)) {
customHandler = opts;
opts = {};
}
var _loop = function _loop() {
var options = {};
var full = r[0];
var funcs = opts.list !== undefined ? (0, _ensureArray2.default)(opts.list) : (0, _ensureArray2.default)(this.options.func.list);
var key = _this2.fixStringAfterRegExp(r[1], true);
if (funcs.length === 0) {
return this;
}
if (!key) {
return "continue";
}
var matchFuncs = funcs.map(function (func) {
return '(?:' + func + ')';
}).join('|').replace(/\./g, '\\.');
// `\s` matches a single whitespace character, which includes spaces, tabs, form feeds, line feeds and other unicode spaces.
var matchSpecialCharacters = '[\\r\\n\\s]*';
var stringGroup = matchSpecialCharacters + '(' +
// backtick (``)
'`(?:[^`\\\\]|\\\\(?:.|$))*`' + '|' +
// double quotes ("")
'"(?:[^"\\\\]|\\\\(?:.|$))*"' + '|' +
// single quote ('')
'\'(?:[^\'\\\\]|\\\\(?:.|$))*\'' + ')' + matchSpecialCharacters;
var pattern = '(?:(?:^\\s*)|[^a-zA-Z0-9_])' + '(?:' + matchFuncs + ')' + '\\(' + stringGroup + '(?:[\\,]' + stringGroup + ')?' + '[\\,\\)]';
var re = new RegExp(pattern, 'gim');
if (r[2] !== undefined) {
var defaultValue = _this2.fixStringAfterRegExp(r[2], false);
var r = void 0;
if (!defaultValue) {
return "continue";
}
var _loop = function _loop() {
var options = {};
var full = r[0];
options.defaultValue = defaultValue;
}
var key = _this2.fixStringAfterRegExp(r[1], true);
if (!key) {
return 'continue';
}
var endsWithComma = full[full.length - 1] === ',';
if (r[2] !== undefined) {
var defaultValue = _this2.fixStringAfterRegExp(r[2], false);
if (!defaultValue) {
return 'continue';
}
options.defaultValue = defaultValue;
}
if (endsWithComma) {
var _opts = _objectSpread({}, opts),
propsFilter = _opts.propsFilter;
var endsWithComma = full[full.length - 1] === ',';
if (endsWithComma) {
var _opts = _extends({}, opts),
propsFilter = _opts.propsFilter;
var code = matchBalancedParentheses(content.substr(re.lastIndex));
var code = matchBalancedParentheses(content.substr(re.lastIndex));
if (typeof propsFilter === 'function') {
code = propsFilter(code);
}
if (typeof propsFilter === 'function') {
code = propsFilter(code);
}
try {
var syntax = code.trim() !== '' ? (0, _esprima.parse)('(' + code + ')') : {};
var props = _lodash["default"].get(syntax, 'body[0].expression.properties') || []; // http://i18next.com/docs/options/
try {
var syntax = code.trim() !== '' ? (0, _esprima.parse)('(' + code + ')') : {};
var props = _lodash2.default.get(syntax, 'body[0].expression.properties') || [];
// http://i18next.com/docs/options/
var supportedOptions = ['defaultValue', 'defaultValue_plural', 'count', 'context', 'ns', 'keySeparator', 'nsSeparator'];
props.forEach(function (prop) {
if (_lodash2.default.includes(supportedOptions, prop.key.name)) {
if (prop.value.type === 'Literal') {
options[prop.key.name] = prop.value.value;
} else if (prop.value.type === 'TemplateLiteral') {
options[prop.key.name] = prop.value.quasis.map(function (element) {
return element.value.cooked;
}).join('');
} else {
// Unable to get value of the property
options[prop.key.name] = '';
}
}
});
} catch (err) {
_this2.error('Unable to parse code "' + code + '"');
_this2.error(err);
}
var supportedOptions = ['defaultValue', 'defaultValue_plural', 'count', 'context', 'ns', 'keySeparator', 'nsSeparator'];
props.forEach(function (prop) {
if (_lodash["default"].includes(supportedOptions, prop.key.name)) {
if (prop.value.type === 'Literal') {
options[prop.key.name] = prop.value.value;
} else if (prop.value.type === 'TemplateLiteral') {
options[prop.key.name] = prop.value.quasis.map(function (element) {
return element.value.cooked;
}).join('');
} else {
// Unable to get value of the property
options[prop.key.name] = '';
}
}
});
} catch (err) {
_this2.error("Unable to parse code \"".concat(code, "\""));
if (customHandler) {
customHandler(key, options);
return 'continue';
}
_this2.error(err);
}
}
_this2.set(key, options);
};
if (customHandler) {
customHandler(key, options);
return "continue";
}
while (r = re.exec(content)) {
var _ret = _loop();
_this2.set(key, options);
};
if (_ret === 'continue') continue;
}
while (r = re.exec(content)) {
var _ret = _loop();
return this;
}
if (_ret === "continue") continue;
}
// Parses translation keys from `Trans` components in JSX
// <Trans i18nKey="some.key">Default text</Trans>
return this;
} // Parses translation keys from `Trans` components in JSX
// <Trans i18nKey="some.key">Default text</Trans>
}, {
key: 'parseTransFromString',
value: function parseTransFromString(content) {
var _this3 = this;
}, {
key: "parseTransFromString",
value: function parseTransFromString(content) {
var _this3 = this;
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (_lodash2.default.isFunction(opts)) {
customHandler = opts;
opts = {};
}
if (_lodash["default"].isFunction(opts)) {
customHandler = opts;
opts = {};
}
var _opts2 = _extends({}, opts),
_opts2$transformOptio = _opts2.transformOptions,
transformOptions = _opts2$transformOptio === undefined ? {} : _opts2$transformOptio,
_opts2$component = _opts2.component,
component = _opts2$component === undefined ? this.options.trans.component : _opts2$component,
_opts2$i18nKey = _opts2.i18nKey,
i18nKey = _opts2$i18nKey === undefined ? this.options.trans.i18nKey : _opts2$i18nKey,
_opts2$defaultsKey = _opts2.defaultsKey,
defaultsKey = _opts2$defaultsKey === undefined ? this.options.trans.defaultsKey : _opts2$defaultsKey,
fallbackKey = _opts2.fallbackKey,
_opts2$acorn = _opts2.acorn,
acornOptions = _opts2$acorn === undefined ? this.options.trans.acorn : _opts2$acorn;
var _opts2 = _objectSpread({}, opts),
_opts2$transformOptio = _opts2.transformOptions,
transformOptions = _opts2$transformOptio === void 0 ? {} : _opts2$transformOptio,
_opts2$component = _opts2.component,
component = _opts2$component === void 0 ? this.options.trans.component : _opts2$component,
_opts2$i18nKey = _opts2.i18nKey,
i18nKey = _opts2$i18nKey === void 0 ? this.options.trans.i18nKey : _opts2$i18nKey,
_opts2$defaultsKey = _opts2.defaultsKey,
defaultsKey = _opts2$defaultsKey === void 0 ? this.options.trans.defaultsKey : _opts2$defaultsKey,
fallbackKey = _opts2.fallbackKey,
_opts2$acorn = _opts2.acorn,
acornOptions = _opts2$acorn === void 0 ? this.options.trans.acorn : _opts2$acorn;
var parseJSXElement = function parseJSXElement(node) {
if (!node) {
return;
}
var parseJSXElement = function parseJSXElement(node) {
if (!node) {
return;
}
(0, _ensureArray2.default)(node.openingElement.attributes).forEach(function (attribute) {
var value = attribute.value;
(0, _ensureArray["default"])(node.openingElement.attributes).forEach(function (attribute) {
var value = attribute.value;
if (!(value && value.type === 'JSXExpressionContainer')) {
return;
}
if (!(value && value.type === 'JSXExpressionContainer')) {
return;
}
var expression = value.expression;
if (!(expression && expression.type === 'JSXElement')) {
return;
}
var expression = value.expression;
parseJSXElement(expression);
});
if (!(expression && expression.type === 'JSXElement')) {
return;
}
(0, _ensureArray2.default)(node.children).forEach(function (childNode) {
if (childNode.type === 'JSXElement') {
parseJSXElement(childNode);
}
});
parseJSXElement(expression);
});
(0, _ensureArray["default"])(node.children).forEach(function (childNode) {
if (childNode.type === 'JSXElement') {
parseJSXElement(childNode);
}
});
if (node.openingElement.name.name !== component) {
return;
}
if (node.openingElement.name.name !== component) {
return;
}
var attr = (0, _ensureArray2.default)(node.openingElement.attributes).reduce(function (acc, attribute) {
if (attribute.type !== 'JSXAttribute' || attribute.name.type !== 'JSXIdentifier') {
return acc;
}
var attr = (0, _ensureArray["default"])(node.openingElement.attributes).reduce(function (acc, attribute) {
if (attribute.type !== 'JSXAttribute' || attribute.name.type !== 'JSXIdentifier') {
return acc;
}
var name = attribute.name.name;
var name = attribute.name.name;
if (attribute.value.type === 'Literal') {
acc[name] = attribute.value.value;
} else if (attribute.value.type === 'JSXExpressionContainer') {
var expression = attribute.value.expression; // Identifier
if (attribute.value.type === 'Literal') {
acc[name] = attribute.value.value;
} else if (attribute.value.type === 'JSXExpressionContainer') {
var expression = attribute.value.expression;
if (expression.type === 'Identifier') {
acc[name] = expression.name;
} // Literal
// Identifier
if (expression.type === 'Identifier') {
acc[name] = expression.name;
}
// Literal
if (expression.type === 'Literal') {
acc[name] = expression.value;
}
if (expression.type === 'Literal') {
acc[name] = expression.value;
} // Object Expression
// Object Expression
if (expression.type === 'ObjectExpression') {
var properties = (0, _ensureArray2.default)(expression.properties);
acc[name] = properties.reduce(function (obj, property) {
if (property.value.type === 'Literal') {
obj[property.key.name] = property.value.value;
} else if (property.value.type === 'TemplateLiteral') {
obj[property.key.name] = property.value.quasis.map(function (element) {
return element.value.cooked;
}).join('');
} else {
// Unable to get value of the property
obj[property.key.name] = '';
}
return obj;
}, {});
}
if (expression.type === 'ObjectExpression') {
var properties = (0, _ensureArray["default"])(expression.properties);
acc[name] = properties.reduce(function (obj, property) {
if (property.value.type === 'Literal') {
obj[property.key.name] = property.value.value;
} else if (property.value.type === 'TemplateLiteral') {
obj[property.key.name] = property.value.quasis.map(function (element) {
return element.value.cooked;
}).join('');
} else {
// Unable to get value of the property
obj[property.key.name] = '';
}
// Template Literal
if (expression.type === 'TemplateLiteral') {
acc[name] = expression.quasis.map(function (element) {
return element.value.cooked;
}).join('');
}
}
return obj;
}, {});
} // Template Literal
return acc;
}, {});
var transKey = _lodash2.default.trim(attr[i18nKey]);
if (expression.type === 'TemplateLiteral') {
acc[name] = expression.quasis.map(function (element) {
return element.value.cooked;
}).join('');
}
}
var defaultsString = attr[defaultsKey] || '';
if (typeof defaultsString !== 'string') {
_this3.log('defaults value must be a static string, saw ' + _chalk2.default.yellow(defaultsString));
}
return acc;
}, {});
// https://www.i18next.com/translation-function/essentials#overview-options
var tOptions = attr.tOptions;
var options = _extends({}, tOptions, {
defaultValue: defaultsString || (0, _nodesToString2.default)(node.children),
fallbackKey: fallbackKey || _this3.options.trans.fallbackKey
});
var transKey = _lodash["default"].trim(attr[i18nKey]);
if (Object.prototype.hasOwnProperty.call(attr, 'count')) {
options.count = Number(attr.count) || 0;
}
var defaultsString = attr[defaultsKey] || '';
if (Object.prototype.hasOwnProperty.call(attr, 'ns')) {
if (typeof options.ns !== 'string') {
_this3.log('The ns attribute must be a string, saw ' + _chalk2.default.yellow(attr.ns));
}
if (typeof defaultsString !== 'string') {
_this3.log("defaults value must be a static string, saw ".concat(_chalk["default"].yellow(defaultsString)));
} // https://www.i18next.com/translation-function/essentials#overview-options
options.ns = attr.ns;
}
if (customHandler) {
customHandler(transKey, options);
return;
}
var tOptions = attr.tOptions;
_this3.set(transKey, options);
};
var options = _objectSpread({}, tOptions, {
defaultValue: defaultsString || (0, _nodesToString["default"])(node.children),
fallbackKey: fallbackKey || _this3.options.trans.fallbackKey
});
try {
var ast = acorn.Parser.extend(_acornStage2.default, (0, _acornJsx2.default)()).parse(content, _extends({}, defaults.trans.acorn, acornOptions));
if (Object.prototype.hasOwnProperty.call(attr, 'count')) {
options.count = Number(attr.count) || 0;
}
(0, _acornJsxWalk2.default)(ast, {
JSXElement: parseJSXElement
});
} catch (err) {
if (transformOptions.filepath) {
this.error('Unable to parse ' + _chalk2.default.blue(component) + ' component from ' + _chalk2.default.yellow(JSON.stringify(transformOptions.filepath)));
console.error(' ' + err);
} else {
this.error('Unable to parse ' + _chalk2.default.blue(component) + ' component:');
console.error(content);
console.error(' ' + err);
}
}
if (Object.prototype.hasOwnProperty.call(attr, 'ns')) {
if (typeof options.ns !== 'string') {
_this3.log("The ns attribute must be a string, saw ".concat(_chalk["default"].yellow(attr.ns)));
}
return this;
options.ns = attr.ns;
}
// Parses translation keys from `data-i18n` attribute in HTML
// <div data-i18n="[attr]ns:foo.bar;[attr]ns:foo.baz">
// </div>
if (customHandler) {
customHandler(transKey, options);
return;
}
}, {
key: 'parseAttrFromString',
value: function parseAttrFromString(content) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_this3.set(transKey, options);
};
var setter = this.set.bind(this);
try {
var ast = acorn.Parser.extend(_acornStage["default"], (0, _acornJsx["default"])()).parse(content, _objectSpread({}, defaults.trans.acorn, {}, acornOptions));
(0, _acornJsxWalk["default"])(ast, {
JSXElement: parseJSXElement
});
} catch (err) {
if (transformOptions.filepath) {
this.error("Unable to parse ".concat(_chalk["default"].blue(component), " component from ").concat(_chalk["default"].yellow(JSON.stringify(transformOptions.filepath))));
console.error(' ' + err);
} else {
this.error("Unable to parse ".concat(_chalk["default"].blue(component), " component:"));
console.error(content);
console.error(' ' + err);
}
}
if (_lodash2.default.isFunction(opts)) {
setter = opts;
opts = {};
} else if (_lodash2.default.isFunction(customHandler)) {
setter = customHandler;
}
return this;
} // Parses translation keys from `data-i18n` attribute in HTML
// <div data-i18n="[attr]ns:foo.bar;[attr]ns:foo.baz">
// </div>
var attrs = opts.list !== undefined ? (0, _ensureArray2.default)(opts.list) : (0, _ensureArray2.default)(this.options.attr.list);
}, {
key: "parseAttrFromString",
value: function parseAttrFromString(content) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var customHandler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var setter = this.set.bind(this);
if (attrs.length === 0) {
return this;
}
if (_lodash["default"].isFunction(opts)) {
setter = opts;
opts = {};
} else if (_lodash["default"].isFunction(customHandler)) {
setter = customHandler;
}
var ast = _parse2.default.parse(content);
var attrs = opts.list !== undefined ? (0, _ensureArray["default"])(opts.list) : (0, _ensureArray["default"])(this.options.attr.list);
var parseAttributeValue = function parseAttributeValue(key) {
key = _lodash2.default.trim(key);
if (key.length === 0) {
return;
}
if (key.indexOf('[') === 0) {
var parts = key.split(']');
key = parts[1];
}
if (key.indexOf(';') === key.length - 1) {
key = key.substr(0, key.length - 2);
}
if (attrs.length === 0) {
return this;
}
setter(key);
};
var ast = _parse["default"].parse(content);
var walk = function walk(nodes) {
nodes.forEach(function (node) {
if (node.attrs) {
node.attrs.forEach(function (attr) {
if (attrs.indexOf(attr.name) !== -1) {
var values = attr.value.split(';');
values.forEach(parseAttributeValue);
}
});
}
if (node.childNodes) {
walk(node.childNodes);
}
if (node.content && node.content.childNodes) {
walk(node.content.childNodes);
}
});
};
var parseAttributeValue = function parseAttributeValue(key) {
key = _lodash["default"].trim(key);
walk(ast.childNodes);
if (key.length === 0) {
return;
}
return this;
if (key.indexOf('[') === 0) {
var parts = key.split(']');
key = parts[1];
}
// Get the value of a translation key or the whole resource store containing translation information
// @param {string} [key] The translation key
// @param {object} [opts] The opts object
// @param {boolean} [opts.sort] True to sort object by key
// @param {boolean} [opts.lng] The language to use
// @return {object}
if (key.indexOf(';') === key.length - 1) {
key = key.substr(0, key.length - 2);
}
}, {
key: 'get',
value: function get(key) {
var _this4 = this;
setter(key);
};
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var walk = function walk(nodes) {
nodes.forEach(function (node) {
if (node.attrs) {
node.attrs.forEach(function (attr) {
if (attrs.indexOf(attr.name) !== -1) {
var values = attr.value.split(';');
values.forEach(parseAttributeValue);
}
});
}
if (_lodash2.default.isPlainObject(key)) {
opts = key;
key = undefined;
}
if (node.childNodes) {
walk(node.childNodes);
}
var resStore = {};
if (this.options.removeUnusedKeys) {
// Merge two objects `resStore` and `resScan` deeply, returning a new merged object with the elements from both `resStore` and `resScan`.
var resMerged = (0, _deepmerge2.default)(this.resStore, this.resScan);
if (node.content && node.content.childNodes) {
walk(node.content.childNodes);
}
});
};
Object.keys(this.resStore).forEach(function (lng) {
Object.keys(_this4.resStore[lng]).forEach(function (ns) {
var resStoreKeys = (0, _flattenObjectKeys2.default)(_lodash2.default.get(_this4.resStore, [lng, ns], {}));
var resScanKeys = (0, _flattenObjectKeys2.default)(_lodash2.default.get(_this4.resScan, [lng, ns], {}));
var unusedKeys = _lodash2.default.differenceWith(resStoreKeys, resScanKeys, _lodash2.default.isEqual);
walk(ast.childNodes);
return this;
} // Get the value of a translation key or the whole resource store containing translation information
// @param {string} [key] The translation key
// @param {object} [opts] The opts object
// @param {boolean} [opts.sort] True to sort object by key
// @param {boolean} [opts.lng] The language to use
// @return {object}
for (var i = 0; i < unusedKeys.length; ++i) {
_lodash2.default.unset(resMerged[lng][ns], unusedKeys[i]);
}
}, {
key: "get",
value: function get(key) {
var _this4 = this;
// Omit empty object
resMerged[lng][ns] = (0, _omitEmptyObject2.default)(resMerged[lng][ns]);
});
});
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
resStore = resMerged;
} else {
resStore = (0, _cloneDeep2.default)(this.resStore);
}
if (_lodash["default"].isPlainObject(key)) {
opts = key;
key = undefined;
}
if (opts.sort) {
Object.keys(resStore).forEach(function (lng) {
var namespaces = resStore[lng];
Object.keys(namespaces).forEach(function (ns) {
// Deeply sort an object by its keys without mangling any arrays inside of it
resStore[lng][ns] = (0, _sortobject2.default)(namespaces[ns]);
});
});
}
var resStore = {};
if (!_lodash2.default.isUndefined(key)) {
var ns = this.options.defaultNs;
if (this.options.removeUnusedKeys) {
// Merge two objects `resStore` and `resScan` deeply, returning a new merged object with the elements from both `resStore` and `resScan`.
var resMerged = (0, _deepmerge["default"])(this.resStore, this.resScan);
Object.keys(this.resStore).forEach(function (lng) {
Object.keys(_this4.resStore[lng]).forEach(function (ns) {
var resStoreKeys = (0, _flattenObjectKeys["default"])(_lodash["default"].get(_this4.resStore, [lng, ns], {}));
var resScanKeys = (0, _flattenObjectKeys["default"])(_lodash["default"].get(_this4.resScan, [lng, ns], {}));
// http://i18next.com/translate/keyBasedFallback/
// Set nsSeparator and keySeparator to false if you prefer
// having keys as the fallback for translation.
// i18next.init({
// nsSeparator: false,
// keySeparator: false
// })
var unusedKeys = _lodash["default"].differenceWith(resStoreKeys, resScanKeys, _lodash["default"].isEqual);
if (_lodash2.default.isString(this.options.nsSeparator) && key.indexOf(this.options.nsSeparator) > -1) {
var parts = key.split(this.options.nsSeparator);
for (var i = 0; i < unusedKeys.length; ++i) {
_lodash["default"].unset(resMerged[lng][ns], unusedKeys[i]);
ns = parts[0];
key = parts[1];
}
_this4.log("Removed an unused translation key { ".concat(_chalk["default"].red(JSON.stringify(unusedKeys[i])), " from ").concat(_chalk["default"].red(JSON.stringify(_this4.formatResourceLoadPath(lng, ns)))));
} // Omit empty object
var keys = _lodash2.default.isString(this.options.keySeparator) ? key.split(this.options.keySeparator) : [key];
var lng = opts.lng ? opts.lng : this.options.fallbackLng;
var namespaces = resStore[lng] || {};
var value = namespaces[ns];
var x = 0;
resMerged[lng][ns] = (0, _omitEmptyObject["default"])(resMerged[lng][ns]);
});
});
resStore = resMerged;
} else {
resStore = (0, _cloneDeep["default"])(this.resStore);
}
while (keys[x]) {
value = value && value[keys[x]];
x++;
}
if (opts.sort) {
Object.keys(resStore).forEach(function (lng) {
var namespaces = resStore[lng];
Object.keys(namespaces).forEach(function (ns) {
// Deeply sort an object by its keys without mangling any arrays inside of it
resStore[lng][ns] = (0, _sortobject["default"])(namespaces[ns]);
});
});
}
return value;
}
if (!_lodash["default"].isUndefined(key)) {
var ns = this.options.defaultNs; // http://i18next.com/translate/keyBasedFallback/
// Set nsSeparator and keySeparator to false if you prefer
// having keys as the fallback for translation.
// i18next.init({
// nsSeparator: false,
// keySeparator: false
// })
return resStore;
if (_lodash["default"].isString(this.options.nsSeparator) && key.indexOf(this.options.nsSeparator) > -1) {
var parts = key.split(this.options.nsSeparator);
ns = parts[0];
key = parts[1];
}
// Set translation key with an optional defaultValue to i18n resource store
// @param {string} key The translation key
// @param {object} [options] The options object
// @param {boolean|function} [options.fallbackKey] When the key is missing, pass `true` to return `options.defaultValue` as key, or pass a function to return user-defined key.
// @param {string} [options.defaultValue] defaultValue to return if translation not found
// @param {number} [options.count] count value used for plurals
// @param {string} [options.context] used for contexts (eg. male)
// @param {string} [options.ns] namespace for the translation
// @param {string|boolean} [options.nsSeparator] The value used to override this.options.nsSeparator
// @param {string|boolean} [options.keySeparator] The value used to override this.options.keySeparator
var keys = _lodash["default"].isString(this.options.keySeparator) ? key.split(this.options.keySeparator) : [key];
var lng = opts.lng ? opts.lng : this.options.fallbackLng;
var namespaces = resStore[lng] || {};
var value = namespaces[ns];
var x = 0;
}, {
key: 'set',
value: function set(key) {
var _this5 = this;
while (keys[x]) {
value = value && value[keys[x]];
x++;
}
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return value;
}
// Backward compatibility
if (_lodash2.default.isString(options)) {
var _defaultValue = options;
options = {
defaultValue: _defaultValue
};
}
return resStore;
} // Set translation key with an optional defaultValue to i18n resource store
// @param {string} key The translation key
// @param {object} [options] The options object
// @param {boolean|function} [options.fallbackKey] When the key is missing, pass `true` to return `options.defaultValue` as key, or pass a function to return user-defined key.
// @param {string} [options.defaultValue] defaultValue to return if translation not found
// @param {number} [options.count] count value used for plurals
// @param {string} [options.context] used for contexts (eg. male)
// @param {string} [options.ns] namespace for the translation
// @param {string|boolean} [options.nsSeparator] The value used to override this.options.nsSeparator
// @param {string|boolean} [options.keySeparator] The value used to override this.options.keySeparator
var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
}, {
key: "set",
value: function set(key) {
var _this5 = this;
var ns = options.ns || this.options.defaultNs;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
console.assert(_lodash2.default.isString(ns) && !!ns.length, 'ns is not a valid string', ns);
// Backward compatibility
if (_lodash["default"].isString(options)) {
var _defaultValue = options;
options = {
defaultValue: _defaultValue
};
}
// http://i18next.com/translate/keyBasedFallback/
// Set nsSeparator and keySeparator to false if you prefer
// having keys as the fallback for translation.
// i18next.init({
// nsSeparator: false,
// keySeparator: false
// })
var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var ns = options.ns || this.options.defaultNs;
console.assert(_lodash["default"].isString(ns) && !!ns.length, 'ns is not a valid string', ns); // http://i18next.com/translate/keyBasedFallback/
// Set nsSeparator and keySeparator to false if you prefer
// having keys as the fallback for translation.
// i18next.init({
// nsSeparator: false,
// keySeparator: false
// })
if (_lodash2.default.isString(nsSeparator) && key.indexOf(nsSeparator) > -1) {
var parts = key.split(nsSeparator);
if (_lodash["default"].isString(nsSeparator) && key.indexOf(nsSeparator) > -1) {
var parts = key.split(nsSeparator);
ns = parts[0];
key = parts[1];
}
ns = parts[0];
key = parts[1];
}
var keys = [];
var keys = [];
if (key) {
keys = _lodash["default"].isString(keySeparator) ? key.split(keySeparator) : [key];
} else {
// fallback key
if (options.fallbackKey === true) {
key = options.defaultValue;
}
if (key) {
keys = _lodash2.default.isString(keySeparator) ? key.split(keySeparator) : [key];
} else {
// fallback key
if (options.fallbackKey === true) {
key = options.defaultValue;
}
if (typeof options.fallbackKey === 'function') {
key = options.fallbackKey(ns, options.defaultValue);
}
if (typeof options.fallbackKey === 'function') {
key = options.fallbackKey(ns, options.defaultValue);
}
if (!key) {
// Ignore empty key
return;
}
if (!key) {
// Ignore empty key
return;
}
keys = [key];
}
keys = [key];
}
var _options = this.options,
lngs = _options.lngs,
context = _options.context,
contextFallback = _options.contextFallback,
contextSeparator = _options.contextSeparator,
plural = _options.plural,
pluralFallback = _options.pluralFallback,
pluralSeparator = _options.pluralSeparator,
defaultLng = _options.defaultLng,
defaultValue = _options.defaultValue;
var _this$options = this.options,
lngs = _this$options.lngs,
context = _this$options.context,
contextFallback = _this$options.contextFallback,
contextSeparator = _this$options.contextSeparator,
plural = _this$options.plural,
pluralFallback = _this$options.pluralFallback,
pluralSeparator = _this$options.pluralSeparator,
defaultLng = _this$options.defaultLng,
defaultValue = _this$options.defaultValue;
lngs.forEach(function (lng) {
var resLoad = _this5.resStore[lng] && _this5.resStore[lng][ns];
var resScan = _this5.resScan[lng] && _this5.resScan[lng][ns];
if (!_lodash["default"].isPlainObject(resLoad)) {
// Skip undefined namespace
_this5.error("".concat(_chalk["default"].yellow(JSON.stringify(ns)), " does not exist in the namespaces (").concat(_chalk["default"].yellow(JSON.stringify(_this5.options.ns)), "): key=").concat(_chalk["default"].yellow(JSON.stringify(key)), ", options=").concat(_chalk["default"].yellow(JSON.stringify(options))));
lngs.forEach(function (lng) {
var resLoad = _this5.resStore[lng] && _this5.resStore[lng][ns];
var resScan = _this5.resScan[lng] && _this5.resScan[lng][ns];
return;
}
if (!_lodash2.default.isPlainObject(resLoad)) {
// Skip undefined namespace
_this5.error(_chalk2.default.yellow(JSON.stringify(ns)) + ' does not exist in the namespaces (' + _chalk2.default.yellow(JSON.stringify(_this5.options.ns)) + '): key=' + _chalk2.default.yellow(JSON.stringify(key)) + ', options=' + _chalk2.default.yellow(JSON.stringify(options)));
return;
}
Object.keys(keys).forEach(function (index) {
var key = keys[index];
Object.keys(keys).forEach(function (index) {
var key = keys[index];
if (index < keys.length - 1) {
resLoad[key] = resLoad[key] || {};
resLoad = resLoad[key];
resScan[key] = resScan[key] || {};
resScan = resScan[key];
return; // continue
} // Context & Plural
// http://i18next.com/translate/context/
// http://i18next.com/translate/pluralSimple/
//
// Format:
// "<key>[[{{contextSeparator}}<context>]{{pluralSeparator}}<plural>]"
//
// Example:
// {
// "translation": {
// "friend": "A friend",
// "friend_male": "A boyfriend",
// "friend_female": "A girlfriend",
// "friend_male_plural": "{{count}} boyfriends",
// "friend_female_plural": "{{count}} girlfriends"
// }
// }
if (index < keys.length - 1) {
resLoad[key] = resLoad[key] || {};
resLoad = resLoad[key];
resScan[key] = resScan[key] || {};
resScan = resScan[key];
return; // continue
}
// Context & Plural
// http://i18next.com/translate/context/
// http://i18next.com/translate/pluralSimple/
//
// Format:
// "<key>[[{{contextSeparator}}<context>]{{pluralSeparator}}<plural>]"
//
// Example:
// {
// "translation": {
// "friend": "A friend",
// "friend_male": "A boyfriend",
// "friend_female": "A girlfriend",
// "friend_male_plural": "{{count}} boyfriends",
// "friend_female_plural": "{{count}} girlfriends"
// }
// }
var resKeys = [];
var resKeys = []; // http://i18next.com/translate/context/
// http://i18next.com/translate/context/
var containsContext = function () {
if (!context) {
return false;
}
if (_lodash2.default.isUndefined(options.context)) {
return false;
}
return _lodash2.default.isFunction(context) ? context(lng, ns, key, options) : !!context;
}();
var containsContext = function () {
if (!context) {
return false;
}
// http://i18next.com/translate/pluralSimple/
var containsPlural = function () {
if (!plural) {
return false;
}
if (_lodash2.default.isUndefined(options.count)) {
return false;
}
return _lodash2.default.isFunction(plural) ? plural(lng, ns, key, options) : !!plural;
}();
if (_lodash["default"].isUndefined(options.context)) {
return false;
}
if (containsPlural) {
var suffixes = pluralFallback ? _this5.pluralSuffixes[lng] : _this5.pluralSuffixes[lng].slice(1);
return _lodash["default"].isFunction(context) ? context(lng, ns, key, options) : !!context;
}(); // http://i18next.com/translate/pluralSimple/
suffixes.forEach(function (pluralSuffix) {
resKeys.push('' + key + pluralSuffix);
});
if (containsContext && containsPlural) {
suffixes.forEach(function (pluralSuffix) {
resKeys.push('' + key + contextSeparator + options.context + pluralSuffix);
});
}
} else {
if (!containsContext || containsContext && contextFallback) {
resKeys.push(key);
}
var containsPlural = function () {
if (!plural) {
return false;
}
if (containsContext) {
resKeys.push('' + key + contextSeparator + options.context);
}
}
if (_lodash["default"].isUndefined(options.count)) {
return false;
}
resKeys.forEach(function (resKey) {
if (resLoad[resKey] === undefined) {
if (options.defaultValue_plural !== undefined && resKey.endsWith(pluralSeparator + 'plural')) {
resLoad[resKey] = options.defaultValue_plural;
} else if (options.defaultValue !== undefined) {
// Use `options.defaultValue` if specified
resLoad[resKey] = options.defaultValue;
} else {
// Fallback to `defaultValue`
resLoad[resKey] = _lodash2.default.isFunction(defaultValue) ? defaultValue(lng, ns, key, options) : defaultValue;
}
_this5.log('Added a new translation key { ' + _chalk2.default.yellow(JSON.stringify(resKey)) + ': ' + _chalk2.default.yellow(JSON.stringify(resLoad[resKey])) + ' } to ' + _chalk2.default.yellow(JSON.stringify(_this5.formatResourceLoadPath(lng, ns))));
} else if (options.defaultValue && (!options.defaultValue_plural || !resKey.endsWith(pluralSeparator + 'plural'))) {
if (!resLoad[resKey]) {
// Use `options.defaultValue` if specified
resLoad[resKey] = options.defaultValue;
} else if (resLoad[resKey] !== options.defaultValue && lng === defaultLng) {
// A default value has provided but it's different with the expected default
_this5.log('The translation key ' + _chalk2.default.yellow(JSON.stringify(resKey)) + ' has a different default value, you may need to check the translation key of default language (' + defaultLng + ')');
}
} else if (options.defaultValue_plural && resKey.endsWith(pluralSeparator + 'plural')) {
if (!resLoad[resKey]) {
// Use `options.defaultValue_plural` if specified
resLoad[resKey] = options.defaultValue_plural;
} else if (resLoad[resKey] !== options.defaultValue_plural && lng === defaultLng) {
// A default value has provided but it's different with the expected default
_this5.log('The translation key ' + _chalk2.default.yellow(JSON.stringify(resKey)) + ' has a different default value, you may need to check the translation key of default language (' + defaultLng + ')');
}
}
return _lodash["default"].isFunction(plural) ? plural(lng, ns, key, options) : !!plural;
}();
resScan[resKey] = resLoad[resKey];
});
});
if (containsPlural) {
var suffixes = pluralFallback ? _this5.pluralSuffixes[lng] : _this5.pluralSuffixes[lng].slice(1);
suffixes.forEach(function (pluralSuffix) {
resKeys.push("".concat(key).concat(pluralSuffix));
});
}
// Returns a JSON string containing translation information
// @param {object} [options] The options object
// @param {boolean} [options.sort] True to sort object by key
// @param {function|string[]|number[]} [options.replacer] The same as the JSON.stringify()
// @param {string|number} [options.space] The same as the JSON.stringify() method
// @return {string}
if (containsContext && containsPlural) {
suffixes.forEach(function (pluralSuffix) {
resKeys.push("".concat(key).concat(contextSeparator).concat(options.context).concat(pluralSuffix));
});
}
} else {
if (!containsContext || containsContext && contextFallback) {
resKeys.push(key);
}
}, {
key: 'toJSON',
value: function toJSON() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (containsContext) {
resKeys.push("".concat(key).concat(contextSeparator).concat(options.context));
}
}
var replacer = options.replacer,
space = options.space,
others = _objectWithoutProperties(options, ['replacer', 'space']);
resKeys.forEach(function (resKey) {
if (resLoad[resKey] === undefined) {
if (options.defaultValue_plural !== undefined && resKey.endsWith("".concat(pluralSeparator, "plural"))) {
resLoad[resKey] = options.defaultValue_plural;
} else if (options.defaultValue !== undefined) {
// Use `options.defaultValue` if specified
resLoad[resKey] = options.defaultValue;
} else {
// Fallback to `defaultValue`
resLoad[resKey] = _lodash["default"].isFunction(defaultValue) ? defaultValue(lng, ns, key, options) : defaultValue;
}
return JSON.stringify(this.get(others), replacer, space);
}
}]);
_this5.log("Added a new translation key { ".concat(_chalk["default"].yellow(JSON.stringify(resKey)), ": ").concat(_chalk["default"].yellow(JSON.stringify(resLoad[resKey])), " } to ").concat(_chalk["default"].yellow(JSON.stringify(_this5.formatResourceLoadPath(lng, ns)))));
} else if (options.defaultValue && (!options.defaultValue_plural || !resKey.endsWith("".concat(pluralSeparator, "plural")))) {
if (!resLoad[resKey]) {
// Use `options.defaultValue` if specified
resLoad[resKey] = options.defaultValue;
} else if (resLoad[resKey] !== options.defaultValue && lng === defaultLng) {
// A default value has provided but it's different with the expected default
_this5.log("The translation key ".concat(_chalk["default"].yellow(JSON.stringify(resKey)), " has a different default value, you may need to check the translation key of default language (").concat(defaultLng, ")"));
}
} else if (options.defaultValue_plural && resKey.endsWith("".concat(pluralSeparator, "plural"))) {
if (!resLoad[resKey]) {
// Use `options.defaultValue_plural` if specified
resLoad[resKey] = options.defaultValue_plural;
} else if (resLoad[resKey] !== options.defaultValue_plural && lng === defaultLng) {
// A default value has provided but it's different with the expected default
_this5.log("The translation key ".concat(_chalk["default"].yellow(JSON.stringify(resKey)), " has a different default value, you may need to check the translation key of default language (").concat(defaultLng, ")"));
}
}
return Parser;
resScan[resKey] = resLoad[resKey];
});
});
});
} // Returns a JSON string containing translation information
// @param {object} [options] The options object
// @param {boolean} [options.sort] True to sort object by key
// @param {function|string[]|number[]} [options.replacer] The same as the JSON.stringify()
// @param {string|number} [options.space] The same as the JSON.stringify() method
// @return {string}
}, {
key: "toJSON",
value: function toJSON() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var replacer = options.replacer,
space = options.space,
others = _objectWithoutProperties(options, ["replacer", "space"]);
return JSON.stringify(this.get(others), replacer, space);
}
}]);
return Parser;
}();
_i18next2.default.init();
_i18next["default"].init();
exports.default = Parser;
var _default = Parser;
exports["default"] = _default;
{
"name": "i18next-scanner",
"version": "2.10.2",
"version": "2.10.3",
"description": "Scan your code, extract translation keys/values, and merge them into i18n resource files.",

@@ -22,6 +22,4 @@ "homepage": "https://github.com/i18next/i18next-scanner",

"eslint": "eslint ./src",
"coveralls": "tap test/*.js --coverage --coverage-report=text-lcov --nyc-arg=--require --nyc-arg=babel-register --nyc-arg=--require --nyc-arg=babel-polyfill | coveralls",
"coverage": "tap test/*.js --coverage --coverage-report=json --nyc-arg=--require --nyc-arg=babel-register --nyc-arg=--require --nyc-arg=babel-polyfill",
"coverage_report": "istanbul report text-summary",
"test": "tap test/*.js --node-arg=--require --node-arg=babel-register --node-arg=--require --node-arg=babel-polyfill"
"coveralls": "tap test/*.js --coverage --coverage-report=text-lcov --nyc-arg=--require --nyc-arg=babel-register | coveralls",
"test": "tap test/*.js --no-esm --no-timeout --node-arg=--require --node-arg=@babel/register"
},

@@ -34,3 +32,3 @@ "repository": {

"engines": {
"node": ">=4"
"node": ">=6"
},

@@ -54,11 +52,11 @@ "keywords": [

"dependencies": {
"acorn": "^6.1.1",
"acorn": "^6.0.0",
"acorn-dynamic-import": "^4.0.0",
"acorn-jsx": "^5.0.1",
"acorn-stage3": "^2.0.0",
"acorn-walk": "^6.1.1",
"acorn-walk": "^6.0.0",
"chalk": "^2.4.1",
"clone-deep": "^4.0.0",
"commander": "^2.15.1",
"deepmerge": "^2.1.1",
"commander": "^3.0.1",
"deepmerge": "^4.0.0",
"ensure-array": "^1.0.0",

@@ -72,3 +70,3 @@ "eol": "^0.9.1",

"sortobject": "^1.1.1",
"through2": "^2.0.3",
"through2": "^3.0.1",
"vinyl": "^2.2.0",

@@ -78,21 +76,21 @@ "vinyl-fs": "^3.0.1"

"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"@babel/cli": "~7.6.0",
"@babel/core": "~7.6.0",
"@babel/preset-env": "~7.6.0",
"@babel/register": "~7.6.0",
"@trendmicro/babel-config": "~1.0.0-alpha",
"babel-eslint": "~10.0.3",
"coveralls": "^3.0.2",
"eslint": "^5.6.0",
"eslint": "^6.4.0",
"eslint-config-trendmicro": "^1.4.1",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-react": "^7.11.1",
"gulp": "^3.9.1",
"gulp-tap": "^1.0.1",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.14.3",
"gulp": "^4.0.2",
"gulp-tap": "^2.0.0",
"gulp-util": "^3.0.8",
"istanbul": "^0.4.5",
"sha1": "^1.1.1",
"tap": "~12.4.1",
"tap": "^14.6.4",
"text-table": "^0.2.0"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc