react-magnetic-di
Version:
Context driven dependency injection
57 lines (47 loc) • 2.19 kB
JavaScript
var getComponentDeclaration = function getComponentDeclaration(t, scope) {
// function declarations
if (scope.parentBlock.declaration) return scope.parentBlock.declaration.id;
if (scope.getBlockParent().block.id) return scope.getBlockParent().block.id; // variable declaration
if (scope.parentBlock.id) return scope.parentBlock.id; // class declarations
if (scope.parentBlock.type.includes('Class')) return scope.parent.block.id;
};
var assert = {
isValidBlock: function isValidBlock(t, ref) {
var block = ref.scope.block;
if (!t.isFunctionDeclaration(block) && !t.isFunctionExpression(block) && !t.isArrowFunctionExpression(block) && !t.isClassMethod(block)) {
throw ref.buildCodeFrameError('Invalid di(...) call: must be inside a render function of a component. ');
}
},
isValidCall: function isValidCall(t, ref) {
if (!ref.container.arguments.length) {
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);
})) {
throw ref.buildCodeFrameError('Invalid di(...) arguments: must be called with plain identifiers. ');
}
var decl = getComponentDeclaration(t, ref.scope);
if (decl && ref.container.arguments.some(function (v) {
return 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));
});
return statement;
};
var isEnabledEnv = function isEnabledEnv() {
return ['development', 'test'].includes(process.env.BABEL_ENV) || ['development', 'test'].includes(process.env.NODE_ENV) || !process.env.BABEL_ENV && !process.env.NODE_ENV;
};
module.exports = {
getComponentDeclaration: getComponentDeclaration,
assert: assert,
createNamedImport: createNamedImport,
isEnabledEnv: isEnabledEnv
};