react-magnetic-di
Advanced tools
Comparing version 2.2.6 to 2.2.7
@@ -11,3 +11,3 @@ "use strict"; | ||
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
@@ -74,3 +74,3 @@ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
var isInjected = function isInjected(vars, n) { | ||
return vars.some(function (v) { | ||
return vars === null || vars === void 0 ? void 0 : vars.some(function (v) { | ||
return v.name === n.name; | ||
@@ -81,3 +81,5 @@ }); | ||
var isReactIgnored = function isReactIgnored(n) { | ||
return reactVars.some(function (v) { | ||
var _reactVars; | ||
return (_reactVars = reactVars) === null || _reactVars === void 0 ? void 0 : _reactVars.some(function (v) { | ||
return v.name === n.name; | ||
@@ -84,0 +86,0 @@ }); |
@@ -20,5 +20,7 @@ "use strict"; | ||
do { | ||
var _scope; | ||
// if we reach module/global scope then is not local | ||
if (scope.type === 'module' || scope.type === 'global') return false; | ||
var isLocal = scope.variables.some(function (v) { | ||
var isLocal = (_scope = scope) === null || _scope === void 0 ? void 0 : _scope.variables.some(function (v) { | ||
return v.name === node.name; | ||
@@ -25,0 +27,0 @@ }); |
@@ -6,18 +6,18 @@ "use strict"; | ||
}); | ||
Object.defineProperty(exports, "di", { | ||
Object.defineProperty(exports, "DiProvider", { | ||
enumerable: true, | ||
get: function get() { | ||
return _consumer.di; | ||
return _provider.DiProvider; | ||
} | ||
}); | ||
Object.defineProperty(exports, "DiProvider", { | ||
Object.defineProperty(exports, "di", { | ||
enumerable: true, | ||
get: function get() { | ||
return _provider.DiProvider; | ||
return _consumer.di; | ||
} | ||
}); | ||
Object.defineProperty(exports, "withDi", { | ||
Object.defineProperty(exports, "injectable", { | ||
enumerable: true, | ||
get: function get() { | ||
return _provider.withDi; | ||
return _utils.injectable; | ||
} | ||
@@ -31,6 +31,6 @@ }); | ||
}); | ||
Object.defineProperty(exports, "injectable", { | ||
Object.defineProperty(exports, "withDi", { | ||
enumerable: true, | ||
get: function get() { | ||
return _utils.injectable; | ||
return _provider.withDi; | ||
} | ||
@@ -37,0 +37,0 @@ }); |
@@ -12,3 +12,3 @@ "use strict"; | ||
var Context = _react["default"].createContext({ | ||
var Context = /*#__PURE__*/_react["default"].createContext({ | ||
getDependencies: function getDependencies(deps) { | ||
@@ -15,0 +15,0 @@ return deps; |
"use strict"; | ||
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } | ||
@@ -8,4 +8,4 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.DiProvider = void 0; | ||
exports.withDi = withDi; | ||
exports.DiProvider = void 0; | ||
@@ -24,5 +24,5 @@ var _react = _interopRequireWildcard(require("react")); | ||
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } | ||
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; 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; } | ||
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; } | ||
@@ -78,3 +78,3 @@ function _extends() { _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; }; return _extends.apply(this, arguments); } | ||
target: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].arrayOf(_propTypes["default"].func)]), | ||
use: _propTypes["default"].arrayOf(_propTypes["default"].func).isRequired | ||
use: _propTypes["default"].arrayOf(_propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].object])).isRequired | ||
}; | ||
@@ -81,0 +81,0 @@ |
@@ -6,6 +6,6 @@ "use strict"; | ||
}); | ||
exports.warnOnce = warnOnce; | ||
exports.getDisplayName = getDisplayName; | ||
exports.injectable = injectable; | ||
exports.mock = void 0; | ||
exports.warnOnce = warnOnce; | ||
@@ -32,2 +32,7 @@ var _constants = require("./constants"); | ||
implementation.displayName = getDisplayName(implementation) || getDisplayName(from, 'di'); | ||
if (implementation[_constants.KEY] && implementation[_constants.KEY] !== from) { | ||
warnOnce("You are trying to use replacement \"".concat(implementation.displayName, "\" on multiple injectables. ") + "That will override only the last dependency, as each replacement is uniquely linked."); | ||
} | ||
implementation[_constants.KEY] = from; | ||
@@ -34,0 +39,0 @@ return implementation; |
@@ -1,29 +0,30 @@ | ||
var _require = require('./constants'), | ||
PACKAGE_NAME = _require.PACKAGE_NAME, | ||
PACKAGE_FUNCTION = _require.PACKAGE_FUNCTION, | ||
HOC_FUNCTION = _require.HOC_FUNCTION; | ||
const { | ||
PACKAGE_NAME, | ||
PACKAGE_FUNCTION, | ||
HOC_FUNCTION | ||
} = require('./constants'); | ||
var processDIReference = require('./processor-di'); | ||
const processDIReference = require('./processor-di'); | ||
var processHOCReference = require('./processor-hoc'); | ||
const processHOCReference = require('./processor-hoc'); | ||
var _require2 = require('./utils'), | ||
isEnabledEnv = _require2.isEnabledEnv; | ||
const { | ||
isEnabledEnv | ||
} = require('./utils'); | ||
module.exports = function (babel) { | ||
var t = babel.types; | ||
const { | ||
types: t | ||
} = babel; | ||
return { | ||
visitor: { | ||
ImportDeclaration: function ImportDeclaration(path, _ref) { | ||
var _ref$opts = _ref.opts, | ||
opts = _ref$opts === void 0 ? {} : _ref$opts; | ||
ImportDeclaration(path, _ref) { | ||
let { | ||
opts = {} | ||
} = _ref; | ||
// first we look at the imports: | ||
// if not our package and not the right function, ignore | ||
var importSource = path.node.source.value; | ||
var importDISpecifier = path.node.specifiers.find(function (s) { | ||
return s.imported && s.imported.name === PACKAGE_FUNCTION; | ||
}); | ||
var importHOCSpecifier = path.node.specifiers.find(function (s) { | ||
return s.imported && s.imported.name === HOC_FUNCTION; | ||
}); | ||
const importSource = path.node.source.value; | ||
const importDISpecifier = path.node.specifiers.find(s => s.imported && s.imported.name === PACKAGE_FUNCTION); | ||
const importHOCSpecifier = path.node.specifiers.find(s => s.imported && s.imported.name === HOC_FUNCTION); | ||
if (importSource !== PACKAGE_NAME) return; | ||
@@ -34,13 +35,9 @@ | ||
// ensuring we affect only locations where it is called | ||
var methodIdentifier = importDISpecifier.local.name; | ||
var binding = path.scope.getBinding(methodIdentifier); | ||
const methodIdentifier = importDISpecifier.local.name; | ||
const binding = path.scope.getBinding(methodIdentifier); | ||
if (!binding) return; | ||
var references = binding.referencePaths.filter(function (ref) { | ||
return t.isCallExpression(ref.container); | ||
}); | ||
var isEnabled = isEnabledEnv() || Boolean(opts.forceEnable); // for each of that location we apply a tranformation | ||
const references = binding.referencePaths.filter(ref => t.isCallExpression(ref.container)); | ||
const isEnabled = isEnabledEnv() || Boolean(opts.forceEnable); // for each of that location we apply a tranformation | ||
references.forEach(function (ref) { | ||
return processDIReference(t, ref, isEnabled); | ||
}); | ||
references.forEach(ref => processDIReference(t, ref, isEnabled)); | ||
} | ||
@@ -51,20 +48,13 @@ | ||
// ensuring we affect only locations where it is called | ||
var _methodIdentifier = importHOCSpecifier.local.name; | ||
const methodIdentifier = importHOCSpecifier.local.name; | ||
const binding = path.scope.getBinding(methodIdentifier); | ||
if (!binding) return; | ||
const references = binding.referencePaths.filter(ref => t.isCallExpression(ref.container)); // for each of that location we apply a tranformation | ||
var _binding = path.scope.getBinding(_methodIdentifier); | ||
if (!_binding) return; | ||
var _references = _binding.referencePaths.filter(function (ref) { | ||
return t.isCallExpression(ref.container); | ||
}); // for each of that location we apply a tranformation | ||
_references.forEach(function (ref) { | ||
return processHOCReference(t, ref); | ||
}); | ||
references.forEach(ref => processHOCReference(t, ref)); | ||
} | ||
} | ||
} | ||
}; | ||
}; |
@@ -1,48 +0,46 @@ | ||
var _require = require('babel-plugin-macros'), | ||
createMacro = _require.createMacro; | ||
const { | ||
createMacro | ||
} = require('babel-plugin-macros'); | ||
var _require2 = require('./constants'), | ||
PACKAGE_NAME = _require2.PACKAGE_NAME, | ||
PACKAGE_FUNCTION = _require2.PACKAGE_FUNCTION, | ||
HOC_FUNCTION = _require2.HOC_FUNCTION; | ||
const { | ||
PACKAGE_NAME, | ||
PACKAGE_FUNCTION, | ||
HOC_FUNCTION | ||
} = require('./constants'); | ||
var processDIReference = require('./processor-di'); | ||
const processDIReference = require('./processor-di'); | ||
var processHOCReference = require('./processor-hoc'); | ||
const processHOCReference = require('./processor-hoc'); | ||
var _require3 = require('./utils'), | ||
createNamedImport = _require3.createNamedImport, | ||
isEnabledEnv = _require3.isEnabledEnv; | ||
const { | ||
createNamedImport, | ||
isEnabledEnv | ||
} = require('./utils'); | ||
var diMacro = function diMacro(_ref) { | ||
var references = _ref.references, | ||
babel = _ref.babel, | ||
_ref$config = _ref.config, | ||
config = _ref$config === void 0 ? {} : _ref$config; | ||
var t = babel.types; | ||
var isEnabled = isEnabledEnv() || Boolean(config.forceEnable); | ||
var importedMethods = Object.keys(references).filter(function (v) { | ||
return references[v].length; | ||
}); | ||
var diImport = references[PACKAGE_FUNCTION] || []; | ||
var hocImports = references[HOC_FUNCTION] || []; // process all di calls | ||
const diMacro = _ref => { | ||
let { | ||
references, | ||
babel, | ||
config = {} | ||
} = _ref; | ||
const { | ||
types: t | ||
} = babel; | ||
const isEnabled = isEnabledEnv() || Boolean(config.forceEnable); | ||
const importedMethods = Object.keys(references).filter(v => references[v].length); | ||
const diImport = references[PACKAGE_FUNCTION] || []; | ||
const hocImports = references[HOC_FUNCTION] || []; // process all di calls | ||
diImport.forEach(function (ref) { | ||
return processDIReference(t, ref, isEnabled); | ||
}); // process all HOC calls | ||
diImport.forEach(ref => processDIReference(t, ref, isEnabled)); // process all HOC calls | ||
hocImports.forEach(function (ref) { | ||
return processHOCReference(t, ref); | ||
}); // if not enabled and only di was imported, let import to be stripped | ||
hocImports.forEach(ref => processHOCReference(t, ref)); // if not enabled and only di was imported, let import to be stripped | ||
if (importedMethods.length === 1 && importedMethods[0] === PACKAGE_FUNCTION && !isEnabled) return; // add named imports | ||
var methodScope = references[importedMethods[0]][0].scope; | ||
var statement = createNamedImport(t, PACKAGE_NAME, importedMethods, importedMethods.map(function (k) { | ||
return references[k][0].node; | ||
})); | ||
var programPath = methodScope.getProgramParent().path; | ||
var targetPath = programPath.get('body').find(function (p) { | ||
return p.node && p.node.source && p.node.source.value === PACKAGE_NAME + '/macro'; | ||
}); | ||
const { | ||
scope: methodScope | ||
} = references[importedMethods[0]][0]; | ||
const statement = createNamedImport(t, PACKAGE_NAME, importedMethods, importedMethods.map(k => references[k][0].node)); | ||
const programPath = methodScope.getProgramParent().path; | ||
const targetPath = programPath.get('body').find(p => p.node && p.node.source && p.node.source.value === PACKAGE_NAME + '/macro'); | ||
@@ -49,0 +47,0 @@ if (targetPath) { |
@@ -1,4 +0,5 @@ | ||
var _require = require('./utils'), | ||
assert = _require.assert, | ||
getComponentDeclaration = _require.getComponentDeclaration; | ||
const { | ||
assert, | ||
getComponentDeclaration | ||
} = require('./utils'); | ||
@@ -9,7 +10,5 @@ function processReference(t, ref, isEnabled) { | ||
var args = ref.container.arguments; | ||
var dependencyIdentifiers = args.map(function (v) { | ||
return t.identifier(v.name); | ||
}); | ||
var statement = ref.getStatementParent(); // if should not be enabled, just remove the statement and exit | ||
const args = ref.container.arguments; | ||
const dependencyIdentifiers = args.map(v => t.identifier(v.name)); | ||
const statement = ref.getStatementParent(); // if should not be enabled, just remove the statement and exit | ||
@@ -26,3 +25,3 @@ if (!isEnabled) { | ||
ref.scope.registerDeclaration(statement); | ||
args.forEach(function (argIdentifier) { | ||
args.forEach(argIdentifier => { | ||
// for each argument we get the dependency variable name | ||
@@ -32,3 +31,3 @@ // then we rename it locally so we get a new unique identifier. | ||
// so it still points to the original dependency identifier name | ||
var name = argIdentifier.name; | ||
const name = argIdentifier.name; | ||
ref.scope.rename(name); | ||
@@ -35,0 +34,0 @@ argIdentifier.name = name; |
@@ -1,5 +0,5 @@ | ||
var processReference = function processReference(t, ref) { | ||
var container = ref.parentPath.container; | ||
const processReference = (t, ref) => { | ||
const container = ref.parentPath.container; | ||
if (container.type !== 'VariableDeclarator') return; | ||
var containerID = container.id; | ||
const containerID = container.id; | ||
ref.getStatementParent().insertAfter(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(containerID, t.identifier('displayName')), t.stringLiteral(containerID.name)))); | ||
@@ -6,0 +6,0 @@ }; |
@@ -1,2 +0,2 @@ | ||
var getComponentDeclaration = function getComponentDeclaration(t, scope) { | ||
const getComponentDeclaration = (t, scope) => { | ||
// function declarations | ||
@@ -11,5 +11,7 @@ if (scope.parentBlock.declaration) return scope.parentBlock.declaration.id; | ||
var assert = { | ||
isValidBlock: function isValidBlock(t, ref) { | ||
var block = ref.scope.block; | ||
const assert = { | ||
isValidBlock(t, ref) { | ||
const { | ||
block | ||
} = ref.scope; | ||
@@ -20,3 +22,4 @@ if (!t.isFunctionDeclaration(block) && !t.isFunctionExpression(block) && !t.isArrowFunctionExpression(block) && !t.isClassMethod(block)) { | ||
}, | ||
isValidCall: function isValidCall(t, ref) { | ||
isValidCall(t, ref) { | ||
if (!ref.container.arguments.length) { | ||
@@ -26,27 +29,22 @@ throw ref.buildCodeFrameError('Invalid di(...) arguments: must be called with at least one argument. '); | ||
if (!ref.container.arguments.every(function (node) { | ||
return t.isIdentifier(node); | ||
})) { | ||
if (!ref.container.arguments.every(node => t.isIdentifier(node))) { | ||
throw ref.buildCodeFrameError('Invalid di(...) arguments: must be called with plain identifiers. '); | ||
} | ||
var decl = getComponentDeclaration(t, ref.scope); | ||
const decl = getComponentDeclaration(t, ref.scope); | ||
if (decl && ref.container.arguments.some(function (v) { | ||
return v.name === decl.name; | ||
})) { | ||
if (decl && ref.container.arguments.some(v => v.name === decl.name)) { | ||
throw ref.buildCodeFrameError('Invalid di(...) call: cannot inject self.'); | ||
} | ||
} | ||
}; | ||
var createNamedImport = function createNamedImport(t, pkgName, pkgFns, localNames) { | ||
var statement = t.importDeclaration([], t.stringLiteral(pkgName)); | ||
statement.specifiers = pkgFns.map(function (v, i) { | ||
return t.importSpecifier(t.identifier(localNames[i].name), t.identifier(v)); | ||
}); | ||
const createNamedImport = (t, pkgName, pkgFns, localNames) => { | ||
const statement = t.importDeclaration([], t.stringLiteral(pkgName)); | ||
statement.specifiers = pkgFns.map((v, i) => t.importSpecifier(t.identifier(localNames[i].name), t.identifier(v))); | ||
return statement; | ||
}; | ||
var isEnabledEnv = function isEnabledEnv() { | ||
const isEnabledEnv = () => { | ||
return ['development', 'test'].includes(process.env.BABEL_ENV) || ['development', 'test'].includes(process.env.NODE_ENV) || !process.env.BABEL_ENV && !process.env.NODE_ENV; | ||
@@ -56,6 +54,6 @@ }; | ||
module.exports = { | ||
getComponentDeclaration: getComponentDeclaration, | ||
assert: assert, | ||
createNamedImport: createNamedImport, | ||
isEnabledEnv: isEnabledEnv | ||
getComponentDeclaration, | ||
assert, | ||
createNamedImport, | ||
isEnabledEnv | ||
}; |
@@ -1,10 +0,10 @@ | ||
var order = require('./rules/order'); | ||
const order = require('./rules/order'); | ||
var exhaustiveInject = require('./rules/exhaustive-inject'); | ||
const exhaustiveInject = require('./rules/exhaustive-inject'); | ||
var noDuplicate = require('./rules/no-duplicate'); | ||
const noDuplicate = require('./rules/no-duplicate'); | ||
var noExtraneous = require('./rules/no-extraneous'); | ||
const noExtraneous = require('./rules/no-extraneous'); | ||
var sortDependencies = require('./rules/sort-dependencies'); | ||
const sortDependencies = require('./rules/sort-dependencies'); | ||
@@ -11,0 +11,0 @@ module.exports = { |
@@ -1,33 +0,18 @@ | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } | ||
const { | ||
getDiIdentifier, | ||
getDiStatements, | ||
getParentDiStatements, | ||
getDiVars, | ||
isHookName, | ||
isComponentName, | ||
isLocalVariable | ||
} = require('../utils'); | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } | ||
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } | ||
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } | ||
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
var _require = require('../utils'), | ||
getDiIdentifier = _require.getDiIdentifier, | ||
getDiStatements = _require.getDiStatements, | ||
getParentDiStatements = _require.getParentDiStatements, | ||
getDiVars = _require.getDiVars, | ||
isHookName = _require.isHookName, | ||
isComponentName = _require.isComponentName, | ||
isLocalVariable = _require.isLocalVariable; | ||
var getReactIdentifiers = function getReactIdentifiers(node) { | ||
const getReactIdentifiers = node => { | ||
if (node.source.value === 'react') { | ||
return node.specifiers.map(function (s) { | ||
return s.local; | ||
}).filter(function (n) { | ||
return !['useState', 'useContext', 'useReducer'].includes(n.name); | ||
}); | ||
return node.specifiers.map(s => s.local).filter(n => !['useState', 'useContext', 'useReducer'].includes(n.name)); | ||
} | ||
}; | ||
var isDefaultProp = function isDefaultProp(node, diStatement) { | ||
const isDefaultProp = (node, diStatement) => { | ||
// we assume order rule is enabled, so if the variable is used in an assignment | ||
@@ -64,68 +49,56 @@ // defined before our di() statements, then it's probably default props | ||
create: function create(context) { | ||
var diIdentifier; | ||
var reactVars; | ||
var userOptions = Object.assign({ | ||
let diIdentifier; | ||
let reactVars; | ||
const userOptions = Object.assign({ | ||
ignore: [] | ||
}, context.options[0]); | ||
var isInjected = function isInjected(vars, n) { | ||
return vars.some(function (v) { | ||
return v.name === n.name; | ||
}); | ||
}; | ||
const isInjected = (vars, n) => vars == null ? void 0 : vars.some(v => v.name === n.name); | ||
var isReactIgnored = function isReactIgnored(n) { | ||
return reactVars.some(function (v) { | ||
return v.name === n.name; | ||
}); | ||
}; | ||
const isReactIgnored = n => { | ||
var _reactVars; | ||
var isOptionsIgnored = function isOptionsIgnored(n) { | ||
return userOptions.ignore.includes(n.name); | ||
return (_reactVars = reactVars) == null ? void 0 : _reactVars.some(v => v.name === n.name); | ||
}; | ||
var report = function report(node, diStatement) { | ||
return context.report({ | ||
node: diStatement, | ||
messageId: 'missingInject', | ||
data: { | ||
name: node.name | ||
}, | ||
fix: function fix(fixer) { | ||
var lastArg = diStatement.expression.arguments.slice(-1)[0]; | ||
const isOptionsIgnored = n => userOptions.ignore.includes(n.name); | ||
if (!lastArg) { | ||
// if injection without args, let's add the var inside call | ||
var _diStatement$expressi = _slicedToArray(diStatement.expression.callee.range, 2), | ||
start = _diStatement$expressi[0], | ||
end = _diStatement$expressi[1]; | ||
const report = (node, diStatement) => context.report({ | ||
node: diStatement, | ||
messageId: 'missingInject', | ||
data: { | ||
name: node.name | ||
}, | ||
return fixer.insertTextAfterRange([start, end + 1], node.name); | ||
} | ||
fix(fixer) { | ||
const lastArg = diStatement.expression.arguments.slice(-1)[0]; | ||
return fixer.insertTextAfter(lastArg, ", ".concat(node.name)); | ||
if (!lastArg) { | ||
// if injection without args, let's add the var inside call | ||
const [start, end] = diStatement.expression.callee.range; | ||
return fixer.insertTextAfterRange([start, end + 1], node.name); | ||
} | ||
}); | ||
}; | ||
return fixer.insertTextAfter(lastArg, `, ${node.name}`); | ||
} | ||
}); | ||
return { | ||
ImportDeclaration: function ImportDeclaration(node) { | ||
ImportDeclaration(node) { | ||
if (!diIdentifier) diIdentifier = getDiIdentifier(node); | ||
if (!reactVars) reactVars = getReactIdentifiers(node); | ||
}, | ||
// this is to handle hooks and components recognised as used variables | ||
// it does not cover JSX variables | ||
BlockStatement: function BlockStatement(node) { | ||
BlockStatement(node) { | ||
if (!diIdentifier) return; | ||
var throughVars = context.getScope().through.map(function (v) { | ||
return v.identifier; | ||
}).filter(function (v) { | ||
return v.name !== diIdentifier.name; | ||
}); | ||
var diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
const throughVars = context.getScope().through.map(v => v.identifier).filter(v => v.name !== diIdentifier.name); | ||
const diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
if (!diStatements.length) return; | ||
var diVars = getDiVars(diStatements); | ||
throughVars.forEach(function (varNode) { | ||
var isInjectable = isHookName(varNode); | ||
const diVars = getDiVars(diStatements); | ||
throughVars.forEach(varNode => { | ||
const isInjectable = isHookName(varNode); | ||
if (!isInjectable || isInjected(diVars, varNode) || isReactIgnored(varNode) || isOptionsIgnored(varNode) || isLocalVariable(varNode, context.getScope()) || isDefaultProp(varNode, diStatements[0])) return; | ||
@@ -135,9 +108,10 @@ report(varNode, diStatements[diStatements.length - 1]); | ||
}, | ||
// as JSX elements are not treated as variables, for each JSX tag | ||
// we check if there is a block with di() above and if that includes it | ||
'JSXOpeningElement:exit': function JSXOpeningElementExit(node) { | ||
'JSXOpeningElement:exit'(node) { | ||
if (!diIdentifier) return; // ignore if the component is declared locally | ||
if (isLocalVariable(node.name, context.getScope())) return; | ||
var varNode; | ||
let varNode; | ||
@@ -148,3 +122,3 @@ switch (node.name.type) { | ||
varNode = node.name; | ||
var isInjectable = isComponentName(varNode); | ||
const isInjectable = isComponentName(varNode); | ||
if (!isInjectable || isReactIgnored(varNode) || isOptionsIgnored(varNode)) return; | ||
@@ -166,11 +140,12 @@ break; | ||
var diStatements = getParentDiStatements(varNode, diIdentifier); // ignore locations where di was not explicitly set | ||
const diStatements = getParentDiStatements(varNode, diIdentifier); // ignore locations where di was not explicitly set | ||
if (!diStatements.length) return; | ||
var diVars = getDiVars(diStatements); | ||
const diVars = getDiVars(diStatements); | ||
if (isInjected(diVars, varNode)) return; | ||
report(varNode, diStatements[diStatements.length - 1]); | ||
} | ||
}; | ||
} | ||
}; |
@@ -1,5 +0,6 @@ | ||
var _require = require('../utils'), | ||
getDiIdentifier = _require.getDiIdentifier, | ||
getDiStatements = _require.getDiStatements, | ||
getDiVars = _require.getDiVars; | ||
const { | ||
getDiIdentifier, | ||
getDiStatements, | ||
getDiVars | ||
} = require('../utils'); | ||
@@ -21,32 +22,28 @@ module.exports = { | ||
create: function create(context) { | ||
var diIdentifier; | ||
let diIdentifier; | ||
var report = function report(node) { | ||
return context.report({ | ||
node: node, | ||
messageId: 'duplicatedInjectable', | ||
data: { | ||
name: node.name | ||
} | ||
}); | ||
}; | ||
const report = node => context.report({ | ||
node, | ||
messageId: 'duplicatedInjectable', | ||
data: { | ||
name: node.name | ||
} | ||
}); | ||
return { | ||
ImportDeclaration: function ImportDeclaration(node) { | ||
ImportDeclaration(node) { | ||
if (!diIdentifier) diIdentifier = getDiIdentifier(node); | ||
}, | ||
BlockStatement: function BlockStatement(node) { | ||
BlockStatement(node) { | ||
if (!diIdentifier) return; | ||
var diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
const diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
if (!diStatements.length) return; | ||
var dupeDiVars = getDiVars(diStatements).filter(function (id, i, arr) { | ||
return arr.findIndex(function (n) { | ||
return n.name === id.name; | ||
}) !== i; | ||
}); | ||
const dupeDiVars = getDiVars(diStatements).filter((id, i, arr) => arr.findIndex(n => n.name === id.name) !== i); | ||
dupeDiVars.forEach(report); | ||
} | ||
}; | ||
} | ||
}; |
@@ -1,6 +0,7 @@ | ||
var _require = require('../utils'), | ||
getDiIdentifier = _require.getDiIdentifier, | ||
getDiStatements = _require.getDiStatements, | ||
getParentDiBlock = _require.getParentDiBlock, | ||
getDiVars = _require.getDiVars; | ||
const { | ||
getDiIdentifier, | ||
getDiStatements, | ||
getParentDiBlock, | ||
getDiVars | ||
} = require('../utils'); | ||
@@ -33,43 +34,41 @@ module.exports = { | ||
create: function create(context) { | ||
var diIdentifier; | ||
var blockReferences = new WeakMap(); | ||
let diIdentifier; | ||
const blockReferences = new WeakMap(); | ||
var report = function report(node) { | ||
return context.report({ | ||
node: node, | ||
messageId: 'extraneousInjectable', | ||
data: { | ||
name: node.name | ||
} // fix(fixer) { | ||
// const lastArg = diStatement.expression.arguments.slice(-1)[0]; | ||
// return fixer.insertTextAfter(lastArg, `, ${node.name}`); | ||
// }, | ||
const report = node => context.report({ | ||
node, | ||
messageId: 'extraneousInjectable', | ||
data: { | ||
name: node.name | ||
} // fix(fixer) { | ||
// const lastArg = diStatement.expression.arguments.slice(-1)[0]; | ||
// return fixer.insertTextAfter(lastArg, `, ${node.name}`); | ||
// }, | ||
}); | ||
}; | ||
}); | ||
return { | ||
ImportDeclaration: function ImportDeclaration(node) { | ||
ImportDeclaration(node) { | ||
if (!diIdentifier) diIdentifier = getDiIdentifier(node); | ||
}, | ||
// this is to handle hooks and components recognised as used variables | ||
// it does not cover JSX variables | ||
BlockStatement: function BlockStatement(node) { | ||
BlockStatement(node) { | ||
if (!diIdentifier) return; | ||
var diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
const diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
if (!diStatements.length) return; | ||
var diVars = getDiVars(diStatements); | ||
const diVars = getDiVars(diStatements); | ||
blockReferences.set(node, { | ||
di: diVars, | ||
through: context.getScope().through.map(function (v) { | ||
return v.identifier; | ||
}) | ||
through: context.getScope().through.map(v => v.identifier) | ||
}); | ||
}, | ||
// as JSX elements are not treated as variables, for each JSX tag | ||
// we check if there is a block with di() above and collect the tag as var | ||
'JSXOpeningElement:exit': function JSXOpeningElementExit(node) { | ||
'JSXOpeningElement:exit'(node) { | ||
if (!diIdentifier) return; | ||
var varNode; | ||
let varNode; | ||
@@ -95,15 +94,14 @@ switch (node.name.type) { | ||
var parentBlock = getParentDiBlock(varNode, diIdentifier); | ||
var blockVars = blockReferences.get(parentBlock); | ||
const parentBlock = getParentDiBlock(varNode, diIdentifier); | ||
const blockVars = blockReferences.get(parentBlock); | ||
if (!blockVars) return; | ||
blockVars.through.push(varNode); | ||
}, | ||
'BlockStatement:exit': function BlockStatementExit(node) { | ||
'BlockStatement:exit'(node) { | ||
if (!diIdentifier) return; | ||
var blockVars = blockReferences.get(node); | ||
const blockVars = blockReferences.get(node); | ||
if (!blockVars) return; | ||
blockVars.di.forEach(function (varNode) { | ||
var occurrences = blockVars.through.filter(function (v) { | ||
return v.name === varNode.name; | ||
}); | ||
blockVars.di.forEach(varNode => { | ||
const occurrences = blockVars.through.filter(v => v.name === varNode.name); | ||
if (occurrences.length > 1) return; | ||
@@ -113,4 +111,5 @@ report(varNode); | ||
} | ||
}; | ||
} | ||
}; |
@@ -1,4 +0,5 @@ | ||
var _require = require('../utils'), | ||
getDiIdentifier = _require.getDiIdentifier, | ||
isDiStatement = _require.isDiStatement; | ||
const { | ||
getDiIdentifier, | ||
isDiStatement | ||
} = require('../utils'); | ||
@@ -20,12 +21,13 @@ module.exports = { | ||
create: function create(context) { | ||
var diIdentifier = null; | ||
let diIdentifier = null; | ||
return { | ||
ImportDeclaration: function ImportDeclaration(node) { | ||
ImportDeclaration(node) { | ||
if (!diIdentifier) diIdentifier = getDiIdentifier(node); | ||
}, | ||
BlockStatement: function BlockStatement(node) { | ||
BlockStatement(node) { | ||
if (!diIdentifier) return; | ||
(node.body || []).forEach(function (statement, i) { | ||
(node.body || []).forEach((statement, i) => { | ||
if (!isDiStatement(statement, diIdentifier) || i === 0) return; | ||
var prev = node.body[i - 1]; | ||
const prev = node.body[i - 1]; | ||
@@ -40,4 +42,5 @@ if (!isDiStatement(prev, diIdentifier)) { | ||
} | ||
}; | ||
} | ||
}; |
@@ -1,9 +0,8 @@ | ||
var _require = require('../utils'), | ||
getDiIdentifier = _require.getDiIdentifier, | ||
getDiStatements = _require.getDiStatements; // use simple numeric comparison to have uppercase (components) first | ||
const { | ||
getDiIdentifier, | ||
getDiStatements | ||
} = require('../utils'); // use simple numeric comparison to have uppercase (components) first | ||
var compareName = function compareName(a, b) { | ||
return a.name > b.name ? 1 : -1; | ||
}; | ||
const compareName = (a, b) => a.name > b.name ? 1 : -1; | ||
@@ -25,43 +24,42 @@ module.exports = { | ||
create: function create(context) { | ||
var diIdentifier; | ||
let diIdentifier; | ||
var report = function report(node, prevNode, args, sortedArgs) { | ||
return context.report({ | ||
node: node, | ||
messageId: 'unsortedInjectable', | ||
data: { | ||
name: node.name, | ||
prevName: prevNode.name | ||
}, | ||
fix: function fix(fixer) { | ||
// grab whatever between 1st arg end / 2nd arg start as separator | ||
var separator = context.getSourceCode().text.slice(args[0].range[1], args[1].range[0]); | ||
var start = args[0].range[0]; | ||
var end = args[args.length - 1].range[1]; | ||
var sorted = sortedArgs.map(function (n) { | ||
return n.name; | ||
}).join(separator); // fixes all order issues at once | ||
// so avoids the need of multiple saves | ||
const report = (node, prevNode, args, sortedArgs) => context.report({ | ||
node, | ||
messageId: 'unsortedInjectable', | ||
data: { | ||
name: node.name, | ||
prevName: prevNode.name | ||
}, | ||
return fixer.replaceTextRange([start, end], sorted); | ||
} | ||
}); | ||
}; | ||
fix(fixer) { | ||
// grab whatever between 1st arg end / 2nd arg start as separator | ||
const separator = context.getSourceCode().text.slice(args[0].range[1], args[1].range[0]); | ||
const start = args[0].range[0]; | ||
const end = args[args.length - 1].range[1]; | ||
const sorted = sortedArgs.map(n => n.name).join(separator); // fixes all order issues at once | ||
// so avoids the need of multiple saves | ||
return fixer.replaceTextRange([start, end], sorted); | ||
} | ||
}); | ||
return { | ||
ImportDeclaration: function ImportDeclaration(node) { | ||
ImportDeclaration(node) { | ||
if (!diIdentifier) diIdentifier = getDiIdentifier(node); | ||
}, | ||
BlockStatement: function BlockStatement(node) { | ||
BlockStatement(node) { | ||
if (!diIdentifier) return; | ||
var diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
const diStatements = getDiStatements(node, diIdentifier); // ignore locations where di was not explicitly set | ||
if (!diStatements.length) return; | ||
diStatements.forEach(function (statement) { | ||
var args = statement.expression.arguments; // sort uppercase first, lowercase after | ||
diStatements.forEach(statement => { | ||
const args = statement.expression.arguments; // sort uppercase first, lowercase after | ||
// so we get components and hooks grouped | ||
var sortedArgs = args.slice().sort(compareName); | ||
args.forEach(function (arg, i) { | ||
var prevArg = args[i - 1]; | ||
const sortedArgs = args.slice().sort(compareName); | ||
args.forEach((arg, i) => { | ||
const prevArg = args[i - 1]; | ||
@@ -74,4 +72,5 @@ if (prevArg && compareName(arg, prevArg) < 0) { | ||
} | ||
}; | ||
} | ||
}; |
@@ -1,23 +0,17 @@ | ||
var PACKAGE_NAME = 'react-magnetic-di'; | ||
var PACKAGE_FUNCTION = 'di'; | ||
const PACKAGE_NAME = 'react-magnetic-di'; | ||
const PACKAGE_FUNCTION = 'di'; | ||
var isDiStatement = function isDiStatement(stm, spec) { | ||
return stm.type === 'ExpressionStatement' && stm.expression && stm.expression.callee && stm.expression.callee.name === spec.name; | ||
}; | ||
const isDiStatement = (stm, spec) => stm.type === 'ExpressionStatement' && stm.expression && stm.expression.callee && stm.expression.callee.name === spec.name; | ||
var isHookName = function isHookName(node) { | ||
return /^use[A-Z0-9].*$/.test(node.name); | ||
}; | ||
const isHookName = node => /^use[A-Z0-9].*$/.test(node.name); | ||
var isComponentName = function isComponentName(node) { | ||
return !/^[a-z]/.test(node.name); | ||
}; | ||
const isComponentName = node => !/^[a-z]/.test(node.name); | ||
var isLocalVariable = function isLocalVariable(node, scope) { | ||
const isLocalVariable = (node, scope) => { | ||
do { | ||
var _scope; | ||
// if we reach module/global scope then is not local | ||
if (scope.type === 'module' || scope.type === 'global') return false; | ||
var isLocal = scope.variables.some(function (v) { | ||
return v.name === node.name; | ||
}); | ||
const isLocal = (_scope = scope) == null ? void 0 : _scope.variables.some(v => v.name === node.name); | ||
if (isLocal) return true; // eslint-disable-next-line no-cond-assign | ||
@@ -29,7 +23,5 @@ } while (scope = scope.upper); | ||
var getDiIdentifier = function getDiIdentifier(node) { | ||
var importSource = node.source.value; | ||
var importSpecifier = node.specifiers.find(function (s) { | ||
return s.imported && s.imported.name === PACKAGE_FUNCTION; | ||
}); | ||
const getDiIdentifier = node => { | ||
const importSource = node.source.value; | ||
const importSpecifier = node.specifiers.find(s => s.imported && s.imported.name === PACKAGE_FUNCTION); | ||
@@ -41,9 +33,5 @@ if (importSource.startsWith(PACKAGE_NAME) && importSpecifier) { | ||
var getDiStatements = function getDiStatements(node, diIdentifier) { | ||
return (node.body || []).reduce(function (acc, statement) { | ||
return isDiStatement(statement, diIdentifier) ? acc.concat(statement) : acc; | ||
}, []); | ||
}; | ||
const getDiStatements = (node, diIdentifier) => (node.body || []).reduce((acc, statement) => isDiStatement(statement, diIdentifier) ? acc.concat(statement) : acc, []); | ||
var getParentDiBlock = function getParentDiBlock(node, diIdentifier) { | ||
const getParentDiBlock = (node, diIdentifier) => { | ||
// eslint-disable-next-line no-cond-assign | ||
@@ -59,4 +47,4 @@ while (node = node.parent) { | ||
var getParentDiStatements = function getParentDiStatements(node, diIdentifier) { | ||
var parentBlock = getParentDiBlock(node, diIdentifier); | ||
const getParentDiStatements = (node, diIdentifier) => { | ||
const parentBlock = getParentDiBlock(node, diIdentifier); | ||
if (parentBlock) return getDiStatements(parentBlock, diIdentifier); | ||
@@ -66,18 +54,14 @@ return []; | ||
var getDiVars = function getDiVars(statements) { | ||
return statements.reduce(function (acc, s) { | ||
return acc.concat(s.expression.arguments); | ||
}, []); | ||
}; | ||
const getDiVars = statements => statements.reduce((acc, s) => acc.concat(s.expression.arguments), []); | ||
module.exports = { | ||
isDiStatement: isDiStatement, | ||
isHookName: isHookName, | ||
isComponentName: isComponentName, | ||
isLocalVariable: isLocalVariable, | ||
getDiIdentifier: getDiIdentifier, | ||
getDiStatements: getDiStatements, | ||
getParentDiBlock: getParentDiBlock, | ||
getParentDiStatements: getParentDiStatements, | ||
getDiVars: getDiVars | ||
isDiStatement, | ||
isHookName, | ||
isComponentName, | ||
isLocalVariable, | ||
getDiIdentifier, | ||
getDiStatements, | ||
getParentDiBlock, | ||
getParentDiStatements, | ||
getDiVars | ||
}; |
@@ -1,2 +0,2 @@ | ||
export var KEY = Symbol["for"]('di'); | ||
export var PACKAGE_NAME = 'react-magnetic-di'; | ||
export const KEY = Symbol.for('di'); | ||
export const PACKAGE_NAME = 'react-magnetic-di'; |
@@ -10,11 +10,8 @@ import { PACKAGE_NAME } from './constants'; | ||
// from all Providers in the tree | ||
var _ref = Context._currentValue || {}, | ||
_ref$getDependencies = _ref.getDependencies, | ||
getDependencies = _ref$getDependencies === void 0 ? function (v) { | ||
return v; | ||
} : _ref$getDependencies; | ||
const { | ||
getDependencies = v => v | ||
} = Context._currentValue || {}; | ||
return getDependencies(deps, target); | ||
} else { | ||
warnOnce("Seems like you are using ".concat(PACKAGE_NAME, " without Babel plugin. ") + "Please add '".concat(PACKAGE_NAME, "/babel-plugin' to your Babel config ") + "or import from '".concat(PACKAGE_NAME, "/macro' if your are using 'babel-plugin-macros'. ") + 'di(...) run as a no-op.'); | ||
warnOnce(`Seems like you are using ${PACKAGE_NAME} without Babel plugin. ` + `Please add '${PACKAGE_NAME}/babel-plugin' to your Babel config ` + `or import from '${PACKAGE_NAME}/macro' if your are using 'babel-plugin-macros'. ` + 'di(...) run as a no-op.'); | ||
} | ||
@@ -21,0 +18,0 @@ } |
import React from 'react'; | ||
export var Context = React.createContext({ | ||
getDependencies: function getDependencies(deps) { | ||
export const Context = /*#__PURE__*/React.createContext({ | ||
getDependencies(deps) { | ||
return deps; | ||
} | ||
}); |
@@ -8,26 +8,24 @@ function _extends() { _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; }; return _extends.apply(this, arguments); } | ||
import { getDisplayName } from './utils'; | ||
export var DiProvider = function DiProvider(_ref) { | ||
var children = _ref.children, | ||
use = _ref.use, | ||
target = _ref.target; | ||
export const DiProvider = _ref => { | ||
let { | ||
children, | ||
use, | ||
target | ||
} = _ref; | ||
const { | ||
getDependencies | ||
} = useContext(Context); // memo provider value so gets computed only once | ||
var _useContext = useContext(Context), | ||
_getDependencies = _useContext.getDependencies; // memo provider value so gets computed only once | ||
var value = useMemo(function () { | ||
const value = useMemo(() => { | ||
// create a map of dependency real -> replacement for fast lookup | ||
var replacementMap = use.reduce(function (m, d) { | ||
return m.set(d[KEY], d); | ||
}, new Map()); // support single or multiple targets | ||
const replacementMap = use.reduce((m, d) => m.set(d[KEY], d), new Map()); // support single or multiple targets | ||
var targets = target && (Array.isArray(target) ? target : [target]); | ||
const targets = target && (Array.isArray(target) ? target : [target]); | ||
return { | ||
getDependencies: function getDependencies(realDeps, targetChild) { | ||
getDependencies(realDeps, targetChild) { | ||
// First we collect dependencies from parent provider(s) (if any) | ||
var dependencies = _getDependencies(realDeps, targetChild); // If no target or target is in the array of targets, map use | ||
const dependencies = getDependencies(realDeps, targetChild); // If no target or target is in the array of targets, map use | ||
if (!targetChild || !targets || targets.includes(targetChild)) { | ||
return dependencies.map(function (dep) { | ||
return dependencies.map(dep => { | ||
// dep can be either the original or a replacement | ||
@@ -37,3 +35,3 @@ // if another provider at the top has already swapped it | ||
// or return the original / parent replacement | ||
var real = dep[KEY] || dep; | ||
const real = dep[KEY] || dep; | ||
return replacementMap.get(real) || dep; | ||
@@ -45,4 +43,5 @@ }); | ||
} | ||
}; | ||
}, [_getDependencies]); // ignore use & target props | ||
}, [getDependencies]); // ignore use & target props | ||
@@ -56,16 +55,17 @@ return /*#__PURE__*/React.createElement(Context.Provider, { | ||
target: PropTypes.oneOfType([PropTypes.func, PropTypes.arrayOf(PropTypes.func)]), | ||
use: PropTypes.arrayOf(PropTypes.func).isRequired | ||
use: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object])).isRequired | ||
}; | ||
export function withDi(Comp, deps) { | ||
var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | ||
var WrappedComponent = /*#__PURE__*/forwardRef(function (props, ref) { | ||
return /*#__PURE__*/React.createElement(DiProvider, { | ||
use: deps, | ||
target: target | ||
}, /*#__PURE__*/React.createElement(Comp, _extends({ | ||
ref: ref | ||
}, props))); | ||
}); | ||
export function withDi(Comp, deps, target) { | ||
if (target === void 0) { | ||
target = null; | ||
} | ||
const WrappedComponent = /*#__PURE__*/forwardRef((props, ref) => /*#__PURE__*/React.createElement(DiProvider, { | ||
use: deps, | ||
target: target | ||
}, /*#__PURE__*/React.createElement(Comp, _extends({ | ||
ref: ref | ||
}, props)))); | ||
WrappedComponent.displayName = getDisplayName(Comp, 'withDi'); | ||
return WrappedComponent; | ||
} |
import { KEY } from './constants'; | ||
var hasWarned = false; | ||
let hasWarned = false; | ||
export function warnOnce(message) { | ||
@@ -10,9 +10,17 @@ if (!hasWarned) { | ||
} | ||
export function getDisplayName(Comp) { | ||
var wrapper = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; | ||
var name = Comp.displayName || Comp.name; | ||
return !name || !wrapper ? name : "".concat(wrapper, "(").concat(name, ")"); | ||
export function getDisplayName(Comp, wrapper) { | ||
if (wrapper === void 0) { | ||
wrapper = ''; | ||
} | ||
const name = Comp.displayName || Comp.name; | ||
return !name || !wrapper ? name : `${wrapper}(${name})`; | ||
} | ||
export function injectable(from, implementation) { | ||
implementation.displayName = getDisplayName(implementation) || getDisplayName(from, 'di'); | ||
if (implementation[KEY] && implementation[KEY] !== from) { | ||
warnOnce(`You are trying to use replacement "${implementation.displayName}" on multiple injectables. ` + `That will override only the last dependency, as each replacement is uniquely linked.`); | ||
} | ||
implementation[KEY] = from; | ||
@@ -23,2 +31,2 @@ return implementation; | ||
export var mock = injectable; | ||
export const mock = injectable; |
{ | ||
"name": "react-magnetic-di", | ||
"version": "2.2.6", | ||
"version": "2.2.7", | ||
"description": "Context driven dependency injection", | ||
@@ -36,6 +36,8 @@ "keywords": [ | ||
}, | ||
"dependencies": {}, | ||
"dependencies": { | ||
"@babel/eslint-parser": "^7.16.5" | ||
}, | ||
"peerDependencies": { | ||
"prop-types": "^15.0.0", | ||
"react": "^16.9.0" | ||
"react": "^16.9.0 || ^17.0.0" | ||
}, | ||
@@ -51,38 +53,37 @@ "peerDependenciesMeta": { | ||
"devDependencies": { | ||
"@babel/cli": "^7.10.1", | ||
"@babel/core": "^7.10.2", | ||
"@babel/plugin-proposal-class-properties": "^7.10.1", | ||
"@babel/plugin-transform-runtime": "^7.10.1", | ||
"@babel/preset-env": "^7.10.2", | ||
"@babel/preset-flow": "^7.10.1", | ||
"@babel/preset-react": "^7.10.1", | ||
"@babel/runtime": "^7.10.2", | ||
"@testing-library/react": "^10.2.1", | ||
"@types/react": "^16.9.35", | ||
"@types/react-dom": "^16.9.8", | ||
"babel-eslint": "^10.1.0", | ||
"babel-jest": "^26.0.1", | ||
"babel-loader": "^8.1.0", | ||
"babel-plugin-macros": "^2.8.0", | ||
"babel-plugin-module-resolver": "^4.0.0", | ||
"dtslint": "^3.6.10", | ||
"enzyme": "~3.11.0", | ||
"enzyme-adapter-react-16": "^1.15.0", | ||
"eslint": "^7.2.0", | ||
"eslint-plugin-flowtype": "^5.1.3", | ||
"eslint-plugin-import": "^2.20.2", | ||
"@babel/cli": "^7.16.8", | ||
"@babel/core": "^7.16.7", | ||
"@babel/plugin-proposal-class-properties": "^7.16.7", | ||
"@babel/plugin-transform-runtime": "^7.16.8", | ||
"@babel/preset-env": "^7.16.8", | ||
"@babel/preset-flow": "^7.16.7", | ||
"@babel/preset-react": "^7.16.7", | ||
"@babel/runtime": "^7.16.7", | ||
"@testing-library/react": "^12.1.2", | ||
"@types/react": "^17.0.38", | ||
"@types/react-dom": "^17.0.11", | ||
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.6", | ||
"babel-jest": "^27.4.6", | ||
"babel-loader": "^8.2.3", | ||
"babel-plugin-macros": "^3.1.0", | ||
"babel-plugin-module-resolver": "^4.1.0", | ||
"dtslint": "^4.2.1", | ||
"enzyme": "^3.11.0", | ||
"eslint": "^8.6.0", | ||
"eslint-plugin-flowtype": "^8.0.3", | ||
"eslint-plugin-import": "^2.25.4", | ||
"eslint-plugin-local": "^1.0.0", | ||
"eslint-plugin-react": "^7.20.0", | ||
"eslint-plugin-react-hooks": "^4.0.4", | ||
"flow-bin": "^0.125.1", | ||
"eslint-plugin-react": "^7.28.0", | ||
"eslint-plugin-react-hooks": "^4.3.0", | ||
"flow-bin": "^0.169.0", | ||
"flow-copy-source": "^2.0.9", | ||
"jest": "^26.0.1", | ||
"prettier": "^2.0.5", | ||
"prop-types": "^15.7.2", | ||
"react": "^16.13.1", | ||
"react-dom": "^16.13.1", | ||
"typescript": "^3.9.5", | ||
"webpack": "^4.43.0", | ||
"webpack-cli": "^3.3.11", | ||
"webpack-dev-server": "^3.11.0" | ||
"jest": "^27.4.7", | ||
"prettier": "^2.5.1", | ||
"prop-types": "^15.8.1", | ||
"react": "^17.0.2", | ||
"react-dom": "^17.0.2", | ||
"typescript": "^4.5.4", | ||
"webpack": "^4.46.0", | ||
"webpack-cli": "^3.3.12", | ||
"webpack-dev-server": "^3.11.3" | ||
}, | ||
@@ -89,0 +90,0 @@ "engines": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
35
82764
3
1610
+ Added@babel/eslint-parser@^7.16.5
+ Added@ampproject/remapping@2.3.0(transitive)
+ Added@babel/code-frame@7.26.2(transitive)
+ Added@babel/compat-data@7.26.2(transitive)
+ Added@babel/core@7.26.0(transitive)
+ Added@babel/eslint-parser@7.25.9(transitive)
+ Added@babel/generator@7.26.2(transitive)
+ Added@babel/helper-compilation-targets@7.25.9(transitive)
+ Added@babel/helper-module-imports@7.25.9(transitive)
+ Added@babel/helper-module-transforms@7.26.0(transitive)
+ Added@babel/helper-string-parser@7.25.9(transitive)
+ Added@babel/helper-validator-identifier@7.25.9(transitive)
+ Added@babel/helper-validator-option@7.25.9(transitive)
+ Added@babel/helpers@7.26.0(transitive)
+ Added@babel/parser@7.26.2(transitive)
+ Added@babel/template@7.25.9(transitive)
+ Added@babel/traverse@7.25.9(transitive)
+ Added@babel/types@7.26.0(transitive)
+ Added@eslint-community/eslint-utils@4.4.1(transitive)
+ Added@eslint-community/regexpp@4.12.1(transitive)
+ Added@eslint/config-array@0.19.0(transitive)
+ Added@eslint/core@0.9.0(transitive)
+ Added@eslint/eslintrc@3.2.0(transitive)
+ Added@eslint/js@9.15.0(transitive)
+ Added@eslint/object-schema@2.1.4(transitive)
+ Added@eslint/plugin-kit@0.2.3(transitive)
+ Added@humanfs/core@0.19.1(transitive)
+ Added@humanfs/node@0.16.6(transitive)
+ Added@humanwhocodes/module-importer@1.0.1(transitive)
+ Added@humanwhocodes/retry@0.3.10.4.1(transitive)
+ Added@jridgewell/gen-mapping@0.3.5(transitive)
+ Added@jridgewell/resolve-uri@3.1.2(transitive)
+ Added@jridgewell/set-array@1.2.1(transitive)
+ Added@jridgewell/sourcemap-codec@1.5.0(transitive)
+ Added@jridgewell/trace-mapping@0.3.25(transitive)
+ Added@nicolo-ribaudo/eslint-scope-5-internals@5.1.1-v1(transitive)
+ Added@types/estree@1.0.6(transitive)
+ Added@types/json-schema@7.0.15(transitive)
+ Addedacorn@8.14.0(transitive)
+ Addedacorn-jsx@5.3.2(transitive)
+ Addedajv@6.12.6(transitive)
+ Addedansi-styles@4.3.0(transitive)
+ Addedargparse@2.0.1(transitive)
+ Addedbalanced-match@1.0.2(transitive)
+ Addedbrace-expansion@1.1.11(transitive)
+ Addedbrowserslist@4.24.2(transitive)
+ Addedcallsites@3.1.0(transitive)
+ Addedcaniuse-lite@1.0.30001683(transitive)
+ Addedchalk@4.1.2(transitive)
+ Addedcolor-convert@2.0.1(transitive)
+ Addedcolor-name@1.1.4(transitive)
+ Addedconcat-map@0.0.1(transitive)
+ Addedconvert-source-map@2.0.0(transitive)
+ Addedcross-spawn@7.0.6(transitive)
+ Addeddebug@4.3.7(transitive)
+ Addeddeep-is@0.1.4(transitive)
+ Addedelectron-to-chromium@1.5.64(transitive)
+ Addedescalade@3.2.0(transitive)
+ Addedescape-string-regexp@4.0.0(transitive)
+ Addedeslint@9.15.0(transitive)
+ Addedeslint-scope@5.1.18.2.0(transitive)
+ Addedeslint-visitor-keys@2.1.03.4.34.2.0(transitive)
+ Addedespree@10.3.0(transitive)
+ Addedesquery@1.6.0(transitive)
+ Addedesrecurse@4.3.0(transitive)
+ Addedestraverse@4.3.05.3.0(transitive)
+ Addedesutils@2.0.3(transitive)
+ Addedfast-deep-equal@3.1.3(transitive)
+ Addedfast-json-stable-stringify@2.1.0(transitive)
+ Addedfast-levenshtein@2.0.6(transitive)
+ Addedfile-entry-cache@8.0.0(transitive)
+ Addedfind-up@5.0.0(transitive)
+ Addedflat-cache@4.0.1(transitive)
+ Addedflatted@3.3.2(transitive)
+ Addedgensync@1.0.0-beta.2(transitive)
+ Addedglob-parent@6.0.2(transitive)
+ Addedglobals@11.12.014.0.0(transitive)
+ Addedhas-flag@4.0.0(transitive)
+ Addedignore@5.3.2(transitive)
+ Addedimport-fresh@3.3.0(transitive)
+ Addedimurmurhash@0.1.4(transitive)
+ Addedis-extglob@2.1.1(transitive)
+ Addedis-glob@4.0.3(transitive)
+ Addedisexe@2.0.0(transitive)
+ Addedjs-yaml@4.1.0(transitive)
+ Addedjsesc@3.0.2(transitive)
+ Addedjson-buffer@3.0.1(transitive)
+ Addedjson-schema-traverse@0.4.1(transitive)
+ Addedjson-stable-stringify-without-jsonify@1.0.1(transitive)
+ Addedjson5@2.2.3(transitive)
+ Addedkeyv@4.5.4(transitive)
+ Addedlevn@0.4.1(transitive)
+ Addedlocate-path@6.0.0(transitive)
+ Addedlodash.merge@4.6.2(transitive)
+ Addedlru-cache@5.1.1(transitive)
+ Addedminimatch@3.1.2(transitive)
+ Addedms@2.1.3(transitive)
+ Addednatural-compare@1.4.0(transitive)
+ Addednode-releases@2.0.18(transitive)
+ Addedoptionator@0.9.4(transitive)
+ Addedp-limit@3.1.0(transitive)
+ Addedp-locate@5.0.0(transitive)
+ Addedparent-module@1.0.1(transitive)
+ Addedpath-exists@4.0.0(transitive)
+ Addedpath-key@3.1.1(transitive)
+ Addedpicocolors@1.1.1(transitive)
+ Addedprelude-ls@1.2.1(transitive)
+ Addedpunycode@2.3.1(transitive)
+ Addedreact@17.0.2(transitive)
+ Addedresolve-from@4.0.0(transitive)
+ Addedsemver@6.3.1(transitive)
+ Addedshebang-command@2.0.0(transitive)
+ Addedshebang-regex@3.0.0(transitive)
+ Addedstrip-json-comments@3.1.1(transitive)
+ Addedsupports-color@7.2.0(transitive)
+ Addedtype-check@0.4.0(transitive)
+ Addedupdate-browserslist-db@1.1.1(transitive)
+ Addeduri-js@4.4.1(transitive)
+ Addedwhich@2.0.2(transitive)
+ Addedword-wrap@1.2.5(transitive)
+ Addedyallist@3.1.1(transitive)
+ Addedyocto-queue@0.1.0(transitive)
- Removedreact@16.14.0(transitive)