New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@odinjs/odin

Package Overview
Dependencies
Maintainers
6
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@odinjs/odin - npm Package Compare versions

Comparing version 1.4.2 to 1.5.2

lib/config/Config.d.ts

18

lib/config/Config.js

@@ -1,16 +0,4 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Configuration = require('./Configuration');
var _Configuration2 = _interopRequireDefault(_Configuration);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var instance = new _Configuration2.default();
exports.default = instance;
import Configuration from './Configuration';
const instance = new Configuration();
export default instance;
//# sourceMappingURL=Config.js.map

@@ -1,86 +0,23 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var STRICT = Symbol('strict');
var INITIALIZED = Symbol('initialized');
/**
* Odin configuration, mantain all configuration options.
*
* Should exists only one instance at time.
*/
var Configuration = function () {
function Configuration() {
_classCallCheck(this, Configuration);
this[STRICT] = false;
this[INITIALIZED] = false;
}
_createClass(Configuration, [{
key: 'setStrict',
/**
* Setter for the Odin strict state.
*
* @param {boolean} strict whether Odin should use strict mode.
*/
value: function setStrict() {
var strict = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
this[STRICT] = strict;
var _a, _b;
const STRICT = Symbol('strict');
const INITIALIZED = Symbol('initialized');
export default class Configuration {
constructor() {
this[_a] = false;
this[_b] = false;
}
/**
* Whether Odin is in strict mode.
*
* @returns {boolean}
*/
}, {
key: 'isStrict',
value: function isStrict() {
return this[STRICT];
setStrict(strict = false) {
this[STRICT] = strict;
}
/**
* Setter for the config initialized state.
*
* @param {boolean} initialized Whether the config should be set as initialized.
*/
}, {
key: 'setInitialized',
value: function setInitialized() {
var initialized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
this[INITIALIZED] = initialized;
isStrict() {
return this[STRICT];
}
/**
* Whether the config has been initialized.
*
* @returns {boolean}
*/
}, {
key: 'isInitialized',
value: function isInitialized() {
return this[INITIALIZED];
setInitialized(initialized = false) {
this[INITIALIZED] = initialized;
}
}]);
return Configuration;
}();
exports.default = Configuration;
isInitialized() {
return this[INITIALIZED];
}
}
_a = STRICT, _b = INITIALIZED;
//# sourceMappingURL=Configuration.js.map

@@ -1,43 +0,19 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = OdinConfig;
var _Config = require('../Config');
var _Config2 = _interopRequireDefault(_Config);
var _Logger = require('../../utils/Logger');
var _MetaValidator = require('../../utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var paramsValidator = _MetaValidator2.default.create().bool('strict', true).validator();
function OdinConfig(definition) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (_Config2.default.isInitialized()) {
(0, _Logger.error)('@OdinConfig can only be used once');
}
var validate = _MetaValidator2.default.validateDecorator(OdinConfig, paramsValidator, definition, params);
if (validate) {
return validate;
}
if (params.hasOwnProperty('strict')) {
_Config2.default.setStrict(params.strict);
}
_Config2.default.setInitialized(true);
return definition;
import Config from '../Config';
import { error } from '../../utils/Logger';
import MetaValidator from '../../utils/MetaValidator';
const paramsValidator = MetaValidator.create().bool('strict', true).validator();
export default function OdinConfig(definition, params = {}) {
if (Config.isInitialized()) {
error('@OdinConfig can only be used once');
}
const validate = MetaValidator.validateDecorator(OdinConfig, paramsValidator, definition, params);
if (validate) {
return validate;
}
if (Object.prototype.hasOwnProperty.call(params, 'strict')) {
Config.setStrict(params.strict);
}
Config.setInitialized(true);
return definition;
}
//# sourceMappingURL=OdinConfig.js.map

@@ -1,53 +0,20 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = autobind;
var VALIDS = ['action', 'state']; //sad, sooooo sad </3
const VALIDS = ['action', 'state'];
function isValid(name) {
return name.startsWith('on') || VALIDS.indexOf(name) > -1;
return (name.startsWith('on') || VALIDS.indexOf(name) > -1);
}
function autobind(instance, proto) {
var protoToCheck = proto || Object.getPrototypeOf(instance);
if (protoToCheck === Object.prototype) {
return;
}
var propertyNames = Object.getOwnPropertyNames(protoToCheck);
propertyNames = propertyNames.filter(isValid);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = propertyNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var name = _step.value;
var value = instance[name];
if (typeof value === 'function') {
instance[name] = instance[name].bind(instance);
}
export default function autobind(instance, proto) {
const protoToCheck = proto || Object.getPrototypeOf(instance);
if (protoToCheck === Object.prototype) {
return;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
let propertyNames = Object.getOwnPropertyNames(protoToCheck);
propertyNames = propertyNames.filter(isValid);
for (let name of propertyNames) {
const value = instance[name];
if (typeof value === 'function') {
instance[name] = instance[name].bind(instance);
}
}
}
autobind(instance, Object.getPrototypeOf(protoToCheck));
autobind(instance, Object.getPrototypeOf(protoToCheck));
}
//# sourceMappingURL=autobind.js.map

@@ -1,295 +0,103 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
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; }; }();
exports.getContainer = getContainer;
var _Secrets = require('./Secrets');
var _Secrets2 = _interopRequireDefault(_Secrets);
var _CustomProvider = require('./CustomProvider');
var _CustomProvider2 = _interopRequireDefault(_CustomProvider);
var _ValueResolver = require('./ValueResolver');
var _autobind = require('./autobind');
var _autobind2 = _interopRequireDefault(_autobind);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var INJECTABLE_DEF = Symbol('injectable-def');
var CONTAINER_ACCESSOR = Symbol('container-accessor'); //NEVER export!
function noop() {}
// do nothing :|
/**
* Describes the expected class registered as injectable.
* @typedef {{new (): object}} Injectable
*/
/**
* Container responsible for manage injectables life-cycle.
* Using the container is possible to retrieve dependecies without
* previous knowlodg about what it is, or from where it comes.
*
* Container works using a domained bundle and a resolver to custom dependencies.
* The bundle contains the dependencies registered throught odin (usually Injectable/Singleton or custom ones).
*
*/
var Container = function () {
/**
* Holds the injectable instances.
* @type {Object.<string, object>}
*/
/**
* Bundle containing the dependecies definition.
* @type Bundle
*/
function Container(bundle) {
var resolver = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new _CustomProvider2.default();
_classCallCheck(this, Container);
this.bundle = null;
this.resolver = null;
this.instances = {};
this.resolvers = {};
this.bundle = bundle;
this.resolver = resolver;
}
/**
* Check if there is an instance of the injectable with the given identifier.
*
* @param {string} identifier the identifier of ther injectable.
*/
/**
* Holds the resolvers for injetable values.
* @type {Object.<string, ValueResolver>}
*/
/**
* Resolve to non-default injectables.
*/
_createClass(Container, [{
key: 'has',
value: function has(identifier) {
return !!this.instances[identifier];
import Secrets from './Secrets';
import CustomProvider from './CustomProvider';
import { FinalValueResolver, ValueResolver } from './ValueResolver';
import autobind from './autobind';
const INJECTABLE_DEF = Symbol('injectable-def');
const CONTAINER_ACCESSOR = Symbol('container-accessor');
function noop() {
}
export default class Container {
constructor(bundle, resolver = new CustomProvider()) {
this.bundle = null;
this.resolver = null;
this.instances = {};
this.resolvers = {};
this.bundle = bundle;
this.resolver = resolver;
}
/**
* Get or provide a resolver of the injectable by the given identifier.
* The resolve may be a instance of ValueResolver or VolatileValue.
* When any resolver knows the dependenct, null might be return as well.
*
* The identifier is normalized to retrieve the dependency, so is possible to use the custom name.
* If the injectable is marked as `singleton`, it'll be reused according with the properly life-cycle.
*
* @param {string} identifier the identifier of ther injectable.
* @returns {ValueResolver} a instance of ValueResolver, VolatileValue or null.
*/
}, {
key: 'provide',
value: function provide(identifier) {
var resolve = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var ref = this.bundle.getId(identifier);
var resolver = null;
if (this.has(ref)) {
resolver = this.get(ref);
return resolve ? resolver.get() : resolver;
}
var injectable = this.bundle.get(ref);
if (injectable) {
resolver = this.resolve(injectable);
} else {
resolver = this.resolver.resolve(identifier);
}
if (resolver && resolve) {
return resolver.get() || null;
}
return resolver || null;
has(identifier) {
return !!this.instances[identifier];
}
/**
* Get an instance of the injectable with the given identifier.
*
* @param {string} identifier the identifier of ther injectable.
*/
}, {
key: 'get',
value: function get(identifier) {
var ref = this.bundle.getId(identifier);
return this.resolvers[ref] || null;
provide(identifier, resolve = false) {
const ref = this.bundle.getId(identifier);
let resolver = null;
if (this.has(ref)) {
resolver = this.get(ref);
return resolve ? resolver.get() : resolver;
}
const injectable = this.bundle.get(ref);
if (injectable) {
resolver = this.resolve(injectable);
}
else {
resolver = this.resolver.resolve(identifier);
}
if (resolver && resolve) {
return resolver.get() || null;
}
return resolver || null;
}
/**
* Discard the injectable value.
* It's only possible to dicard injectables marked as `singleton`, if it is marked as `dicardable`.
*
* @param {string} identifier the identifier of ther injectable.
*/
}, {
key: 'discard',
value: function discard(identifier) {
var ref = this.bundle.getId(identifier);
var instance = this.instances[ref] || identifier;
var def = this.getDef(instance);
if (def && _Secrets2.default.isDiscardable(def.definition)) {
delete this.instances[def.id];
}
get(identifier) {
const ref = this.bundle.getId(identifier);
return this.resolvers[ref] || null;
}
/**
* Resolve an instance of the given injectable definition.
*
* @param {Injectable} injectable the definition to be built.
*/
}, {
key: 'resolve',
value: function resolve(injectable) {
var id = injectable.id,
definition = injectable.definition;
var instance = this.bundle.instantiate(injectable);
(0, _autobind2.default)(instance);
var resolver = this.resolvers[id];
if (!resolver) {
if (!_Secrets2.default.isSingleton(definition) || !_Secrets2.default.isDiscardable(definition)) {
resolver = new _ValueResolver.FinalValueResolver(function () {
return instance;
});
} else {
resolver = this.createValueResolver(injectable, id);
discard(identifier) {
const ref = this.bundle.getId(identifier);
const instance = this.instances[ref] || identifier;
const def = this.getDef(instance);
if (def && Secrets.isDiscardable(def.definition)) {
delete this.instances[def.id];
}
}
if (_Secrets2.default.isSingleton(definition)) {
this.instances[id] = instance;
this.resolvers[id] = resolver;
}
instance[INJECTABLE_DEF] = Object.assign({}, injectable);
setContainer(instance, this);
this.invokeEagers(instance);
this.invokePostConstruct(instance);
return resolver;
}
}, {
key: 'createValueResolver',
value: function createValueResolver(injectable, id) {
var _this = this;
return new _ValueResolver.ValueResolver(function () {
if (!_this.instances[id]) {
_this.resolve(injectable);
resolve(injectable) {
const { id, definition } = injectable;
let instance = this.bundle.instantiate(injectable);
autobind(instance);
let resolver = this.resolvers[id];
if (!resolver) {
if (!Secrets.isSingleton(definition) || !Secrets.isDiscardable(definition)) {
resolver = new FinalValueResolver(() => instance);
}
else {
resolver = this.createValueResolver(injectable, id);
}
}
return _this.instances[id] || null;
});
if (Secrets.isSingleton(definition)) {
this.instances[id] = instance;
this.resolvers[id] = resolver;
}
instance[INJECTABLE_DEF] = Object.assign({}, injectable);
setContainer(instance, this);
this.invokeEagers(instance);
this.invokePostConstruct(instance);
return resolver;
}
/**
* Invoke the eager injected properties to bootstrap them.
*
* @param {object} injectable the instance to initialize.
*/
}, {
key: 'invokeEagers',
value: function invokeEagers(instance) {
var eagers = _Secrets2.default.getEagers(instance);
eagers.forEach(function (eager) {
return noop(instance[eager]);
});
createValueResolver(injectable, id) {
return new ValueResolver(() => {
if (!this.instances[id]) {
this.resolve(injectable);
}
return this.instances[id] || null;
});
}
/**
* Invoke the method decorated with PostConstruct.
*
* @param {*} instance the injectable instance to invoke the post construct method.
*/
}, {
key: 'invokePostConstruct',
value: function invokePostConstruct(instance) {
var methodName = _Secrets2.default.getPostContruct(instance);
if (methodName) {
instance[methodName]();
}
invokeEagers(instance) {
const eagers = Secrets.getEagers(instance);
eagers.forEach(eager => noop(instance[eager]));
}
/**
* Obtain the definitions of the injectable.
* It returns an object containing: { id, definition, args }.
*
* @param {Injectable} instance the injectable instance.
*/
}, {
key: 'getDef',
value: function getDef(instance) {
return instance[INJECTABLE_DEF];
invokePostConstruct(instance) {
const methodName = Secrets.getPostContruct(instance);
if (methodName) {
instance[methodName]();
}
}
}]);
return Container;
}();
/**
* Setter that creates a hidden property containing the feature injector container.
* The container only can be accessed through the Inject decorator.
*
* @param {object} injectable the injectable instance to receive the hidden property.
* @param {object} container the container instance to store into the injectable.
*/
exports.default = Container;
getDef(instance) {
return instance[INJECTABLE_DEF];
}
}
function setContainer(injectable, container) {
injectable[CONTAINER_ACCESSOR] = container;
injectable[CONTAINER_ACCESSOR] = container;
}
/**
* Getter to retrieve a hidden property which contains feature injector container.
*
* NEVER EXPORT/USE OUTSIDE ODIN OR YOU'LL BE FIRED
*
* @param {object} injectable the injectable instance to receive the hidden property.
*/
function getContainer(injectable) {
return injectable[CONTAINER_ACCESSOR];
export function getContainer(injectable) {
return injectable[CONTAINER_ACCESSOR];
}
//# sourceMappingURL=Container.js.map

@@ -1,92 +0,34 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Logger = require('../utils/Logger');
var _ValueResolver = require('./ValueResolver');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Custom provider to retrieve non odin provide values.
*/
var CustomProvider = function () {
function CustomProvider() {
_classCallCheck(this, CustomProvider);
this.injectables = {};
}
_createClass(CustomProvider, [{
key: 'register',
/**
* Register a custom injectable generator.
* @param {string} identifier the generator identifier.
* @param {ValueResolver} resolver the value resolver.
*
* @returns {string} the registered name.
* @throws if the identifier is already registered.
*/
value: function register(identifier, resolver) {
var name = String(identifier).toLowerCase();
if (this.has(name)) {
(0, _Logger.error)('The injectable \'' + name + '\' was already registered.');
} else if (!(resolver instanceof _ValueResolver.ValueResolver)) {
(0, _Logger.error)('The injectable \'' + name + '\' must be \'ValueResolver\'.');
}
this.injectables[name] = {
name: name,
resolver: resolver
};
return name;
import { error } from '../utils/Logger';
import { ValueResolver } from './ValueResolver';
export default class CustomProvider {
constructor() {
this.injectables = {};
}
/**
* Check if there is a registered injectable with the given identifier.
*
* @param {string} ref the identifier.
*/
}, {
key: 'has',
value: function has() {
var ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var str = String(ref).toLowerCase();
return !!this.injectables[str];
register(identifier, resolver) {
const name = String(identifier).toLowerCase();
if (this.has(name)) {
error(`The injectable '${name}' was already registered.`);
}
else if (!(resolver instanceof ValueResolver)) {
error(`The injectable '${name}' must be 'ValueResolver'.`);
}
this.injectables[name] = {
name,
resolver,
};
return name;
}
/**
* Provide the value resolver based on param.
*
* @param {string} identifier the dependency name.
* @returns the dependency if exists, or null.
*/
}, {
key: 'resolve',
value: function resolve(identifier) {
var name = String(identifier).toLowerCase();
var injectable = this.injectables[name];
if (injectable) {
return injectable.resolver;
}
return null;
has(ref = '') {
const str = String(ref).toLowerCase();
return !!this.injectables[str];
}
}]);
return CustomProvider;
}();
exports.default = CustomProvider;
resolve(identifier) {
const name = String(identifier).toLowerCase();
const injectable = this.injectables[name];
if (injectable) {
return injectable.resolver;
}
return null;
}
}
//# sourceMappingURL=CustomProvider.js.map

@@ -1,85 +0,39 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Inject;
var _Secrets = require('../Secrets');
var _Secrets2 = _interopRequireDefault(_Secrets);
var _Config = require('../../config/Config');
var _Config2 = _interopRequireDefault(_Config);
var _Logger = require('../../utils/Logger');
var _MetaValidator = require('../../utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
var _ValueResolver = require('../ValueResolver');
var _Container = require('../Container');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Decorator used to bind injected properties.
* Only works assigned to classes properties and the class must be known by odin.
*
* @param {class} definition the object class definition.
* @param {string} name the property name.
* @param {object} descriptor the original property descriptor.
* @param {object} params the params received.
*/
function Inject(definition, name, descriptor) {
var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (typeof definition === 'string') {
if (arguments.length > 1) {
(0, _Logger.error)('@Inject should receive only one argument.');
import Secrets from '../Secrets';
import Config from '../../config/Config';
import { error } from '../../utils/Logger';
import MetaValidator from '../../utils/MetaValidator';
import { FinalValueResolver } from '../ValueResolver';
import { getContainer } from '../Container';
export default function Inject(definition, name, descriptor, params = {}) {
if (typeof definition === 'string') {
if (arguments.length > 1) {
error('@Inject should receive only one argument.');
}
definition = { name: definition };
}
definition = { name: definition };
}
var paramsValidator = _MetaValidator2.default.create().str('name', _Config2.default.isStrict()).bool('eager').validator();
var validate = _MetaValidator2.default.validateDecorator(Inject, paramsValidator, definition, params);
if (validate) {
return validate;
}
if (params.eager) {
_Secrets2.default.setEager(definition, name);
}
function get() {
var _this = this;
var container = (0, _Container.getContainer)(this);
if (!container) {
(0, _Logger.error)('There is no container at \'' + definition + '\'.');
const paramsValidator = MetaValidator.create().str('name', Config.isStrict()).bool('eager').validator();
const validate = MetaValidator.validateDecorator(Inject, paramsValidator, definition, params);
if (validate) {
return validate;
}
var injectableName = params.name || name;
var resolver = container.provide(injectableName);
if (resolver) {
var value = resolver.get(this);
var isFinal = resolver instanceof _ValueResolver.FinalValueResolver;
var newDescriptor = isFinal ? { value: value } : { get: function get() {
return resolver.get(_this);
} };
Object.defineProperty(this, name, newDescriptor);
return value;
if (params.eager) {
Secrets.setEager(definition, name);
}
}
return { get: get };
function get() {
const container = getContainer(this);
if (!container) {
error(`There is no container at '${definition}'.`);
}
const injectableName = params.name || name;
let resolver = container.provide(injectableName);
if (resolver) {
const value = resolver.get(this);
const isFinal = (resolver instanceof FinalValueResolver);
const newDescriptor = isFinal ? { value } : { get: () => resolver.get(this) };
Object.defineProperty(this, name, newDescriptor);
return value;
}
}
return { get };
}
//# sourceMappingURL=Inject.js.map

@@ -1,52 +0,18 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.paramsValidator = undefined;
exports.default = Injectable;
exports.register = register;
var _Odin = require('../../Odin');
var _Odin2 = _interopRequireDefault(_Odin);
var _MetaValidator = require('../../utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var paramsValidator = exports.paramsValidator = _MetaValidator2.default.create().str('domain').validator();
/**
* Decorator used to bind a injectable to odin.
* Only works assigned to class.
*
* @param {*} definition the class to be registered.
* @param {object} params the params received.
*/
function Injectable(definition) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var validate = _MetaValidator2.default.validateDecorator(Injectable, paramsValidator, definition, params);
if (validate) {
return validate;
}
var domain = params.domain;
_MetaValidator2.default.validateDomain(params.domain);
return register(definition, domain, params);
import odin from '../../Odin';
import MetaValidator from '../../utils/MetaValidator';
export const paramsValidator = MetaValidator.create().str('domain').validator();
export default function Injectable(definition, params = {}) {
const validate = MetaValidator.validateDecorator(Injectable, paramsValidator, definition, params);
if (validate) {
return validate;
}
const { domain } = params;
MetaValidator.validateDomain(params.domain);
return register(definition, domain, params);
}
function register(definition, domain, args) {
var bundle = _Odin2.default.bundle(domain);
bundle.register(definition, args);
return definition;
export function register(definition, domain, args) {
const bundle = odin.bundle(domain);
bundle.register(definition, args);
return definition;
}
//# sourceMappingURL=Injectable.js.map

@@ -1,37 +0,12 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = PostConstruct;
var _Logger = require('../../utils/Logger');
var _MetaValidator = require('../../utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
var _Secrets = require('../Secrets');
var _Secrets2 = _interopRequireDefault(_Secrets);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Decorator used to bind the method that must be invoked when the injectable is built.
* Only works assigned to classes method and the class must be registered on the injector system.
*
* @param {class} instance the object class definition.
* @param {string} name the property name.
* @param {object} descriptor the original property descriptor.
*/
function PostConstruct(definition, name, descriptor) {
_MetaValidator2.default.checkDef(definition, 'PostConstruct');
if (_Secrets2.default.getPostContruct(definition)) {
(0, _Logger.error)('The class \'' + definition.constructor.name + '\' must constains no more than one PostConstruct method.');
}
_Secrets2.default.setPostContruct(definition, name);
return descriptor;
import { error } from '../../utils/Logger';
import MetaValidator from '../../utils/MetaValidator';
import Secrets from '../Secrets';
export default function PostConstruct(definition, name, descriptor) {
MetaValidator.checkDef(definition, 'PostConstruct');
if (Secrets.getPostContruct(definition)) {
error(`The class '${definition.constructor.name}' must constains no more than one PostConstruct method.`);
}
Secrets.setPostContruct(definition, name);
return descriptor;
}
//# sourceMappingURL=PostConstruct.js.map

@@ -1,43 +0,14 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Singleton;
var _Injectable = require('./Injectable');
var _MetaValidator = require('../../utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
var _Secrets = require('../Secrets');
var _Secrets2 = _interopRequireDefault(_Secrets);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Decorator used to bind a singleton to odin.
* Only works assigned to class.
*
* @param {*} definition the class to be registered.
* @param {object} params the params received.
*/
function Singleton(definition) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var validate = _MetaValidator2.default.validateDecorator(Singleton, _Injectable.paramsValidator, definition, params);
if (validate) {
return validate;
}
var domain = params.domain;
_MetaValidator2.default.validateDomain(params.domain);
_Secrets2.default.setSingleton(definition);
return (0, _Injectable.register)(definition, domain, params);
import { paramsValidator, register } from './Injectable';
import MetaValidator from '../../utils/MetaValidator';
import Secrets from '../Secrets';
export default function Singleton(definition, params = {}) {
const validate = MetaValidator.validateDecorator(Singleton, paramsValidator, definition, params);
if (validate) {
return validate;
}
const { domain } = params;
MetaValidator.validateDomain(params.domain);
Secrets.setSingleton(definition);
return register(definition, domain, params);
}
//# sourceMappingURL=Singleton.js.map

@@ -1,161 +0,39 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SINGLETON_DEF = Symbol('singleton-def'); //NEVER export!
var DISCARDABLE_DEF = Symbol('discardable-def'); //NEVER export!
var CUSTOM_DEF = Symbol('custom-def'); //NEVER export!
var POST_CONSTRUCTOR_ACCESSOR = Symbol('post-contructor-accessor'); //NEVER export!
var EAGER_ACCESSOR = Symbol('eager-accessor'); //NEVER export!
/**
* Helper responsible to mark and check tag Injectable's.
*/
var Secrets = function () {
function Secrets() {
_classCallCheck(this, Secrets);
}
_createClass(Secrets, null, [{
key: 'setSingleton',
/**
* Mark Injectable as singleton.
*
* @param {Injectable} definition the injectable to mark.
*/
value: function setSingleton(definition) {
definition[SINGLETON_DEF] = true;
const SINGLETON_DEF = Symbol('singleton-def');
const DISCARDABLE_DEF = Symbol('discardable-def');
const CUSTOM_DEF = Symbol('custom-def');
const POST_CONSTRUCTOR_ACCESSOR = Symbol('post-contructor-accessor');
const EAGER_ACCESSOR = Symbol('eager-accessor');
export default class Secrets {
static setSingleton(definition) {
definition[SINGLETON_DEF] = true;
}
/**
* Check if Injectable is singleton.
*
* @param {Injectable} definition the injectable to check.
* @returns {boolean} true if it is.
*/
}, {
key: 'isSingleton',
value: function isSingleton(definition) {
return definition[SINGLETON_DEF] === true;
static isSingleton(definition) {
return definition[SINGLETON_DEF] === true;
}
/**
* Mark Injectable as discardable.
*
* @param {Injectable} definition the injectable to mark.
*/
}, {
key: 'setDiscardable',
value: function setDiscardable(definition) {
definition[DISCARDABLE_DEF] = true;
static setDiscardable(definition) {
definition[DISCARDABLE_DEF] = true;
}
/**
* Check if Injectable is discardable.
*
* @param {Injectable} definition the injectable to check.
* @returns {boolean} true if it is.
*/
}, {
key: 'isDiscardable',
value: function isDiscardable(definition) {
return definition[DISCARDABLE_DEF] === true;
static isDiscardable(definition) {
return definition[DISCARDABLE_DEF] === true;
}
/**
* Mark Injectable as custom.
*
* @param {Injectable} definition the injectable to mark.
*/
}, {
key: 'setCustom',
value: function setCustom(definition) {
definition[CUSTOM_DEF] = true;
static setCustom(definition) {
definition[CUSTOM_DEF] = true;
}
/**
* Check if Injectable is custom.
*
* @param {Injectable} definition the injectable to check.
* @returns {boolean} true if it is.
*/
}, {
key: 'isCustom',
value: function isCustom(definition) {
return definition[CUSTOM_DEF] === true;
static isCustom(definition) {
return definition[CUSTOM_DEF] === true;
}
/**
* Set postContruct method name into definition.
*
* @param {Injectable} definition the injectable to set.
* @param {string} name the postContruct method name.
*/
}, {
key: 'setPostContruct',
value: function setPostContruct(definition, name) {
definition[POST_CONSTRUCTOR_ACCESSOR] = name;
static setPostContruct(definition, name) {
definition[POST_CONSTRUCTOR_ACCESSOR] = name;
}
/**
* Get postConstruct method name from definition.
*
* @param {Injectable} definition the injectable to get from.
* @returns {string} the method name.
*/
}, {
key: 'getPostContruct',
value: function getPostContruct(definition) {
return definition[POST_CONSTRUCTOR_ACCESSOR];
static getPostContruct(definition) {
return definition[POST_CONSTRUCTOR_ACCESSOR];
}
/**
* Push eager prop into definition.
*
* @param {Injectable} definition the injectable to define.
* @param {string} name the eager prop name.
*/
}, {
key: 'setEager',
value: function setEager(definition, name) {
definition[EAGER_ACCESSOR] = definition[EAGER_ACCESSOR] || [];
definition[EAGER_ACCESSOR].push(name);
static setEager(definition, name) {
definition[EAGER_ACCESSOR] = definition[EAGER_ACCESSOR] || [];
definition[EAGER_ACCESSOR].push(name);
}
/**
* Get eager props name from definition.
*
* @param {Injectable} definition the injectable to get from.
* @returns the eager props name.
*/
}, {
key: 'getEagers',
value: function getEagers(definition) {
return definition[EAGER_ACCESSOR] || [];
static getEagers(definition) {
return definition[EAGER_ACCESSOR] || [];
}
}]);
return Secrets;
}();
exports.default = Secrets;
}
//# sourceMappingURL=Secrets.js.map

@@ -1,75 +0,19 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var RESOLVER = Symbol('resolver'); // NEVER export!
var VALUE = Symbol('value'); // NEVER export!
/**
* Wrapper to provided value resolver.
* It resolves the value each time that the get is invoked.
*/
var ValueResolver = exports.ValueResolver = function () {
function ValueResolver(resolver) {
_classCallCheck(this, ValueResolver);
this[RESOLVER] = resolver;
}
/**
* Resolve the value based on the instance retrieving it.
* @param {Injectable} instance the injectable retrieving.
*/
_createClass(ValueResolver, [{
key: 'get',
value: function get(instance) {
return this[RESOLVER](instance);
const RESOLVER = Symbol('resolver');
const VALUE = Symbol('value');
export class ValueResolver {
constructor(resolver) {
this[RESOLVER] = resolver;
}
}]);
return ValueResolver;
}();
/**
* Wrapper to provided value resolver.
* It only evals the value once.
*/
var FinalValueResolver = exports.FinalValueResolver = function (_ValueResolver) {
_inherits(FinalValueResolver, _ValueResolver);
function FinalValueResolver() {
_classCallCheck(this, FinalValueResolver);
return _possibleConstructorReturn(this, (FinalValueResolver.__proto__ || Object.getPrototypeOf(FinalValueResolver)).apply(this, arguments));
}
_createClass(FinalValueResolver, [{
key: 'get',
value: function get(instance) {
if (this[VALUE] === undefined) {
this[VALUE] = _get(FinalValueResolver.prototype.__proto__ || Object.getPrototypeOf(FinalValueResolver.prototype), 'get', this).call(this, instance);
}
return this[VALUE];
get(instance) {
return this[RESOLVER](instance);
}
}]);
return FinalValueResolver;
}(ValueResolver);
}
export class FinalValueResolver extends ValueResolver {
get(instance) {
if (this[VALUE] === undefined) {
this[VALUE] = super.get(instance);
}
return this[VALUE];
}
}
//# sourceMappingURL=ValueResolver.js.map

@@ -1,66 +0,14 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.OdinConfig = exports.Logger = exports.MetaValidator = exports.FinalValueResolver = exports.ValueResolver = exports.CustomProvider = exports.Secrets = exports.Inject = exports.PostConstruct = exports.Singleton = exports.Injectable = undefined;
var _Odin = require('./Odin');
var _Odin2 = _interopRequireDefault(_Odin);
var _Injectable = require('./container/decorator/Injectable');
var _Injectable2 = _interopRequireDefault(_Injectable);
var _Singleton = require('./container/decorator/Singleton');
var _Singleton2 = _interopRequireDefault(_Singleton);
var _PostConstruct = require('./container/decorator/PostConstruct');
var _PostConstruct2 = _interopRequireDefault(_PostConstruct);
var _Inject = require('./container/decorator/Inject');
var _Inject2 = _interopRequireDefault(_Inject);
var _Secrets = require('./container/Secrets');
var _Secrets2 = _interopRequireDefault(_Secrets);
var _CustomProvider = require('./container/CustomProvider');
var _CustomProvider2 = _interopRequireDefault(_CustomProvider);
var _ValueResolver = require('./container/ValueResolver');
var _MetaValidator = require('./utils/MetaValidator');
var _MetaValidator2 = _interopRequireDefault(_MetaValidator);
var _Logger = require('./utils/Logger');
var Logger = _interopRequireWildcard(_Logger);
var _OdinConfig = require('./config/decorator/OdinConfig');
var _OdinConfig2 = _interopRequireDefault(_OdinConfig);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _Odin2.default;
exports.Injectable = _Injectable2.default;
exports.Singleton = _Singleton2.default;
exports.PostConstruct = _PostConstruct2.default;
exports.Inject = _Inject2.default;
exports.Secrets = _Secrets2.default;
exports.CustomProvider = _CustomProvider2.default;
exports.ValueResolver = _ValueResolver.ValueResolver;
exports.FinalValueResolver = _ValueResolver.FinalValueResolver;
exports.MetaValidator = _MetaValidator2.default;
exports.Logger = Logger;
exports.OdinConfig = _OdinConfig2.default;
import odin from './Odin';
import Injectable from './container/decorator/Injectable';
import Singleton from './container/decorator/Singleton';
import PostConstruct from './container/decorator/PostConstruct';
import Inject from './container/decorator/Inject';
import Secrets from './container/Secrets';
import CustomProvider from './container/CustomProvider';
import { FinalValueResolver, ValueResolver } from './container/ValueResolver';
import MetaValidator from './utils/MetaValidator';
import * as Logger from './utils/Logger';
import OdinConfig from './config/decorator/OdinConfig';
export default odin;
export { Injectable, Singleton, PostConstruct, Inject, Secrets, CustomProvider, ValueResolver, FinalValueResolver, MetaValidator, Logger, OdinConfig, };
//# sourceMappingURL=index.js.map

@@ -1,16 +0,4 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _OdinCore = require('./OdinCore');
var _OdinCore2 = _interopRequireDefault(_OdinCore);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var instance = new _OdinCore2.default();
exports.default = instance;
import OdinCore from './OdinCore';
const instance = new OdinCore();
export default instance;
//# sourceMappingURL=Odin.js.map

@@ -1,102 +0,36 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Bundle = require('./registry/Bundle');
var _Bundle2 = _interopRequireDefault(_Bundle);
var _Container = require('./container/Container');
var _Container2 = _interopRequireDefault(_Container);
var _CustomProvider = require('./container/CustomProvider');
var _CustomProvider2 = _interopRequireDefault(_CustomProvider);
var _Logger = require('./utils/Logger');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var BUNDLE = Symbol('bundle');
/**
* Core of Odin, mantain all bundles and injectables registereds.
* It builds Container's based on domain.
*
* Should exists only one instance at time.
*/
var OdinCore = function () {
function OdinCore() {
_classCallCheck(this, OdinCore);
this[BUNDLE] = new _Bundle2.default('odin');
}
/**
* Navigate througt domains based on path domain received and get it.
*
* @param {string} domain the domain to navigate and get the bundle.
* @param {*} create if should create the bundle, when does not exist.
*/
_createClass(OdinCore, [{
key: 'bundle',
value: function bundle(domain) {
var create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var bundle = this[BUNDLE];
if (domain) {
if (domain !== domain.trim()) {
(0, _Logger.error)('Invalid domain \'' + domain + '\'.');
import Bundle from './registry/Bundle';
import Container from './container/Container';
import CustomProvider from './container/CustomProvider';
import { error } from './utils/Logger';
const BUNDLE = Symbol('bundle');
export default class OdinCore {
constructor() {
this[BUNDLE] = new Bundle('odin');
}
bundle(domain, create = true) {
let bundle = this[BUNDLE];
if (domain) {
if (domain !== domain.trim()) {
error(`Invalid domain '${domain}'.`);
}
const path = domain.toLowerCase().split('/');
bundle = path.reduce((b, p) => {
if (p !== p.trim()) {
error(`Invalid sub domain '${p}' on domain '${domain}'.`);
}
if (create || (b && b.hasChild(p))) {
return b.child(p);
}
}, bundle);
}
var path = domain.toLowerCase().split('/');
bundle = path.reduce(function (b, p) {
if (p !== p.trim()) {
(0, _Logger.error)('Invalid sub domain \'' + p + '\' on domain \'' + domain + '\'.');
}
if (create || b && b.hasChild(p)) {
return b.child(p);
}
}, bundle);
}
return bundle;
return bundle;
}
/**
* Create a new container to the domain, never reusing.
* Every call returns a new instance, and this one is not managed by this class.
*
* @param {string} domain the domain that must create a container.
* @param {CustomProvider} resolver resolver responsible to for dependencies not registered in bundles.
*/
}, {
key: 'container',
value: function container(domain) {
var resolver = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new _CustomProvider2.default();
var bundle = this.bundle(domain, false);
if (!bundle) {
(0, _Logger.error)('There is no bundle to domain \'' + domain + '\'.');
}
return new _Container2.default(bundle, resolver);
container(domain, resolver = new CustomProvider()) {
const bundle = this.bundle(domain, false);
if (!bundle) {
error(`There is no bundle to domain '${domain}'.`);
}
return new Container(bundle, resolver);
}
}]);
return OdinCore;
}();
exports.default = OdinCore;
}
//# sourceMappingURL=OdinCore.js.map

@@ -1,244 +0,74 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Registry = require('./Registry');
var _Registry2 = _interopRequireDefault(_Registry);
var _Config = require('../config/Config');
var _Config2 = _interopRequireDefault(_Config);
var _Logger = require('../utils/Logger');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Describes the expected class registered as injectable.
* @typedef {{new (): object}} Injectable
*/
/**
* Bundle responsible for holds a Registry.
* It's possible to chain Bundle's and every bundle has a parent.
*/
var Bundle = function () {
/**
* Create a new Bundle.
*
* @param {string} id id.
* @param {Bundle} parent parent bundle.
*/
/**
* @type {Object.<string, Bundle>}
*/
/**
* The Bundle identifier.
* @type {string}
*/
function Bundle(id) {
var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new DummyBundle();
_classCallCheck(this, Bundle);
this.injectables = new _Registry2.default();
this.children = {};
this.childrenName = [];
if (!id) {
(0, _Logger.error)('Invalid bundle id \'' + id + '\'.');
import Registry from './Registry';
import Config from '../config/Config';
import { error } from '../utils/Logger';
export default class Bundle {
constructor(id, parent = new DummyBundle()) {
this.injectables = new Registry();
this.children = {};
this.childrenName = [];
if (!id) {
error(`Invalid bundle id '${id}'.`);
}
this.id = id;
this.parent = parent;
}
this.id = id;
this.parent = parent;
}
/**
* Create a new child bundle.
*
* @param {string} id the bundle id.
*/
/**
* @type {Array.<string>}
*/
/**
* The Bundle registry containing its dependencies.
* @type Registry
*/
_createClass(Bundle, [{
key: 'child',
value: function child(id) {
if (!id) {
(0, _Logger.error)('The value \'' + id + '\' is not valid as bundle id.');
}
var lowerName = id.toLowerCase();
var child = this.children[lowerName];
if (!child) {
child = this.children[lowerName] = {
id: id,
bundle: new Bundle(id, this)
};
}
return child.bundle;
child(id) {
if (!id) {
error(`The value '${id}' is not valid as bundle id.`);
}
const lowerName = id.toLowerCase();
let child = this.children[lowerName];
if (!child) {
child = this.children[lowerName] = {
id,
bundle: new Bundle(id, this),
};
}
return child.bundle;
}
/**
* Checks if there is a child id as param.
*
* @param {string} id child id.
*/
}, {
key: 'hasChild',
value: function hasChild() {
var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var lowerName = id.toLowerCase();
return !!this.children[lowerName];
hasChild(id = '') {
const lowerName = id.toLowerCase();
return !!this.children[lowerName];
}
/**
* Register a injectable for this Bundle.
* It checks if alread exists an injectable with the given idenfier or name.
*
* @param {Injectable} definition class definition for the injectable.
* @param {string} otherArgs other arguments.
* @returns {string} the registered name.
*/
}, {
key: 'register',
value: function register(definition) {
var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.checkHas(definition, args.name);
return this.injectables.register(definition, args);
register(definition, args = {}) {
this.checkHas(definition, args.name);
return this.injectables.register(definition, args);
}
/**
* Receives a injectable definition and provides a new instance.
*
* @param {InjectableDef} def the defition to instance.
*/
}, {
key: 'instantiate',
value: function instantiate(def) {
var definition = def.definition,
args = def.args;
var argsCopy = Object.assign({}, args);
return new definition(argsCopy);
unregister(definition, args = {}) {
return this.injectables.unregister(definition, args);
}
/**
* Check if the injectable is already registered.
* If there already is a injectable with the given name/identiier, throws error.
*
* @param {InjectableDef} def the injectable to check.
*/
}, {
key: 'checkHas',
value: function checkHas(def, name) {
return this.injectables.checkHas(def, name) || this.parent.checkHas(def, name);
instantiate(def) {
const { definition, args } = def;
const argsCopy = Object.assign({}, args);
return new definition(argsCopy);
}
/**
* Verify if there is a injectable registered with the given identifier.
*
* @param {string|Injectable} def the identifier.
*/
}, {
key: 'has',
value: function has(def) {
var name = typeof def === 'function' ? def.name : def;
return this.injectables.has(name) || this.parent.has(name);
checkHas(def, name) {
return this.injectables.checkHas(def, name) || this.parent.checkHas(def, name);
}
/**
* Obtain the registered injectable, if exists.
* @param {string} def the definition identifier.
*/
}, {
key: 'get',
value: function get(def) {
return this.injectables.get(def) || this.parent.get(def);
has(def) {
const name = typeof def === 'function' ? def.name : def;
return this.injectables.has(name) || this.parent.has(name);
}
/**
* Obtain the injectable idenfier used to retrieve.
*
* @param {*} ref the injectable identifier.
*/
}, {
key: 'getId',
value: function getId(ref) {
var str = _Config2.default.isStrict() ? String(ref) : String(ref).toLowerCase();
return this.injectables.getId(ref) || this.parent.getId(ref) || str;
get(def) {
return this.injectables.get(def) || this.parent.get(def);
}
}]);
return Bundle;
}();
/**
* Dummy class to clear check.
*/
exports.default = Bundle;
var DummyBundle = function () {
function DummyBundle() {
_classCallCheck(this, DummyBundle);
}
_createClass(DummyBundle, [{
key: 'has',
value: function has() {
return false;
getId(ref) {
const str = Config.isStrict() ? String(ref) : String(ref).toLowerCase();
return this.injectables.getId(ref) || this.parent.getId(ref) || str;
}
}, {
key: 'checkHas',
value: function checkHas() {
return false;
}
class DummyBundle {
has() {
return false;
}
}, {
key: 'get',
value: function get() {
return null;
checkHas() {
return false;
}
}, {
key: 'getId',
value: function getId() {
return null;
get() {
return null;
}
}]);
return DummyBundle;
}();
getId() {
return null;
}
}
//# sourceMappingURL=Bundle.js.map

@@ -1,39 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Data that defines a Injectable.
*/
var InjectableDef =
/**
* The Injectable class.
* @type {Object.new}
*/
function InjectableDef(id, definition, args) {
_classCallCheck(this, InjectableDef);
this.id = id;
this.definition = definition;
this.args = args;
export default class InjectableDef {
constructor(id, definition, args) {
this.id = id;
this.definition = definition;
this.args = args;
}
}
/**
* The arguments when instanciate the definition.
* @type {Object}
*/
/**
* The Injectable identifier.
* @type {string}
*/
;
exports.default = InjectableDef;
//# sourceMappingURL=InjectableDef.js.map

@@ -1,197 +0,75 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Config = require("../config/Config");
var _Config2 = _interopRequireDefault(_Config);
var _Logger = require("../utils/Logger");
var _InjectableDef = require("./InjectableDef");
var _InjectableDef2 = _interopRequireDefault(_InjectableDef);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Describes the expected class registered as injectable.
* @typedef {{new (): object}} Injectable
*/
/**
* Injectable's registry.
* It maps and holds the injectable definitions.
*/
var Registry = function () {
function Registry() {
_classCallCheck(this, Registry);
this.injectables = {};
this.identifierByName = {};
this.names = [];
}
/**
* Map the injectable's classes.
* @type {Object.<string, InjectableDef>}
*/
/**
* Map the injectable's identifiers by name.
* @type {Object.<string, string>}
*/
/**
* Set of registered names.
* @type {Array.<string>}
*/
_createClass(Registry, [{
key: "register",
/**
* Register a injectable class.
* The class should be retrieved using the class name or a custom name.
* The custom name must be inside the parameter args as property `name`.
*
* @param {Injectable} definition injectable class.
* @param {string} args object containing other arguments.
* @returns {string} the registered identifier.
*/
value: function register(definition) {
var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var name = args.name;
this.checkHas(definition, name);
var id = getAsString(definition.name);
this.injectables[id] = new _InjectableDef2.default(id, definition, args);
if (name) {
var lowerName = getAsString(name);
this.names.push(lowerName);
this.identifierByName[lowerName] = id;
}
return id;
import Config from '../config/Config';
import { error } from '../utils/Logger';
import InjectableDef from './InjectableDef';
export default class Registry {
constructor() {
this.injectables = {};
this.identifierByName = {};
this.names = [];
}
/**
* Check if exists an injectable with the given identifier.
* It checks if exists another injectable using the custom name, as well.
*
* @param {Injectable} def the injectable.
* @param {string} name the custom name.
*/
}, {
key: "checkHas",
value: function checkHas(def) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var id = getAsString(def.name);
if (name && this.hasName(name)) {
(0, _Logger.error)("There already is a injectable named '" + name + "' registered.");
} else if (this.hasName(id)) {
(0, _Logger.error)("There already is a injectable named '" + id + "' registered.");
} else if (name && this.has(name)) {
(0, _Logger.error)("There already is a injectable '" + name + "' registered.");
} else if (this.has(id)) {
(0, _Logger.error)("There already is a injectable '" + id + "' registered.");
}
register(definition, args = {}) {
const { name } = args;
this.checkHas(definition, name);
const id = getAsString(definition.name);
this.injectables[id] = new InjectableDef(id, definition, args);
if (name) {
const lowerName = getAsString(name);
this.names.push(lowerName);
this.identifierByName[lowerName] = id;
}
return id;
}
/**
* Check if there is a registered injectable with the given identifier.
*
* @param {string} ref the identifier.
*/
}, {
key: "has",
value: function has() {
var ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var str = getAsString(ref);
return this.hasName(ref) || !!this.injectables[str];
unregister(definition, args = {}) {
const { name } = args;
const id = getAsString(definition.name);
if (!this.injectables[id]) {
return;
}
delete this.injectables[id];
if (name) {
const lowerName = getAsString(name);
const index = this.names.findIndex(n => n === lowerName);
this.names.splice(index, 1);
delete this.identifierByName[lowerName];
}
}
/**
* Check if there is a registered injectable with the given name.
*
* @param {string} name the name.
*/
}, {
key: "hasName",
value: function hasName() {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var str = getAsString(name);
return this.names.indexOf(str) > -1;
checkHas(def, name = '') {
const id = getAsString(def.name);
if (name && this.hasName(name)) {
error(`There already is a injectable named '${name}' registered.`);
}
else if (this.hasName(id)) {
error(`There already is a injectable named '${id}' registered.`);
}
else if (name && this.has(name)) {
error(`There already is a injectable '${name}' registered.`);
}
else if (this.has(id)) {
error(`There already is a injectable '${id}' registered.`);
}
}
/**
* Try to get the injectable class difinition.
* It would retrieve the class using the arguments as identifier or name.
* If found the injectable using any of both, will return.
*
* @param {string} ref the identifier or name.
*/
}, {
key: "get",
value: function get() {
var ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var str = getAsString(ref);
var name = this.identifierByName[str];
return this.injectables[str] || this.injectables[name] || null;
has(ref = '') {
const str = getAsString(ref);
return this.hasName(ref) || !!this.injectables[str];
}
/**
* Get injectable id from given name.
*
* @param {string} ref the injectable name.
*/
}, {
key: "getId",
value: function getId() {
var ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var str = getAsString(ref);
return this.identifierByName[str] || null;
hasName(name = '') {
const str = getAsString(name);
return this.names.indexOf(str) > -1;
}
}]);
return Registry;
}();
/**
* Helper to obtain a string based on Odin strict rule.
*
* @param {str} str the string to be mutated.
*/
exports.default = Registry;
get(ref = '') {
const str = getAsString(ref);
const name = this.identifierByName[str];
return this.injectables[str] || this.injectables[name] || null;
}
getId(ref = '') {
const str = getAsString(ref);
return this.identifierByName[str] || null;
}
}
function getAsString(str) {
if (_Config2.default.isStrict()) {
return String(str);
}
return String(str).toLowerCase();
if (Config.isStrict()) {
return String(str);
}
return String(str).toLowerCase();
}
//# sourceMappingURL=Registry.js.map

@@ -1,10 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.error = error;
function error(msg) {
throw new Error("[ODIN] " + msg);
export function error(msg) {
throw new Error(`[ODIN] ${msg}`);
}
//# sourceMappingURL=Logger.js.map

@@ -1,186 +0,88 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _Logger = require('./Logger');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Helper to generate a validator to check the decorators meta info.
* There are other util methods too.
*/
var MetaValidator = function () {
function MetaValidator() {
_classCallCheck(this, MetaValidator);
}
_createClass(MetaValidator, null, [{
key: 'create',
/**
* Create a validator to check the decorators meta info.
*/
value: function create() {
var meta = {};
var mim = {
str: function str(name, mandatory, depends) {
return newProp(name, 'string', mandatory, depends);
},
bool: function bool(name, mandatory, depends) {
return newProp(name, 'boolean', mandatory, depends);
},
number: function number(name, mandatory, depends) {
return newProp(name, 'number', mandatory, depends);
},
validator: function validator() {
return createValidator(meta);
import { error } from './Logger';
export default class MetaValidator {
static create() {
const meta = {};
const mim = {
str: (name, mandatory, depends) => newProp(name, 'string', mandatory, depends),
bool: (name, mandatory, depends) => newProp(name, 'boolean', mandatory, depends),
number: (name, mandatory, depends) => newProp(name, 'number', mandatory, depends),
validator: () => {
return createValidator(meta);
},
};
function newProp(name, type, mandatory = false, depends = []) {
meta[name] = { type, mandatory, depends };
return mim;
}
};
function newProp(name, type) {
var mandatory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var depends = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
meta[name] = { type: type, mandatory: mandatory, depends: depends };
return mim;
}
return mim;
}
/**
* Validate if the decorator structure is right.
* @param {function} fn the decorator being applyed.
* @param {*} paramsValidator function that validate params.
* @param {*} definition tha class receiving the decorator.
* @param {*} params the received params.
*/
}, {
key: 'validateDecorator',
value: function validateDecorator(fn, paramsValidator, definition, params) {
var name = fn.name;
MetaValidator.checkDef(definition, name);
if (definition.constructor === Object) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return fn.apply(undefined, args.concat([definition]));
};
}
paramsValidator(params, definition, name);
static validateDecorator(fn, paramsValidator, definition, params) {
const name = fn.name;
MetaValidator.checkDef(definition, name);
if (definition.constructor === Object) {
return (...args) => fn(...args, definition);
}
paramsValidator(params, definition, name);
}
/**
* Check if decorator is being invoked without params.
*
* @param {class} definition the receiving the decorator.
* @param {*} name decorator name.
*/
}, {
key: 'checkDef',
value: function checkDef(definition, name) {
if (!definition) {
logError(name, '', 'If there are no params, remove the ()');
}
static checkDef(definition, name) {
if (!definition) {
logError(name, '', `If there are no params, remove the ()`);
}
}
/**
* Check if is a valid domain.
*
* @param {string} domain the domain to check.
* @param {number} min the min amount of chunks.
* @param {number} max the max amount of chunks.
*/
}, {
key: 'validateDomain',
value: function validateDomain(domain) {
var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 999;
if (min <= 0 && !domain) {
return;
}
var chunks = String(domain).split('/');
chunks.forEach(function (chunk) {
var t = chunk.trim();
if (t !== chunk) {
(0, _Logger.error)('Invalid domain \'' + domain + '\', should not has empty spaces in \'' + chunk + '\'.');
} else if (!t) {
(0, _Logger.error)('Invalid domain \'' + domain + '\', remove empty chunks.');
static validateDomain(domain, min = 0, max = 999) {
if (min <= 0 && !domain) {
return;
}
});
var length = chunks.length;
if (length < min || length > max) {
(0, _Logger.error)('Invalid domain \'' + domain + '\', domain must have at least ' + min + ' and no more than ' + max + ' chunks.');
}
const chunks = String(domain).split('/');
chunks.forEach(chunk => {
const t = chunk.trim();
if (t !== chunk) {
error(`Invalid domain '${domain}', should not has empty spaces in '${chunk}'.`);
}
else if (!t) {
error(`Invalid domain '${domain}', remove empty chunks.`);
}
});
const length = chunks.length;
if (length < min || length > max) {
error(`Invalid domain '${domain}', domain must have at least ${min} and no more than ${max} chunks.`);
}
}
}]);
return MetaValidator;
}();
////////
// UTILS
////////
exports.default = MetaValidator;
}
function createValidator(knewProps) {
var props = Object.getOwnPropertyNames(knewProps);
var mandatories = props.filter(function (p) {
return knewProps[p].mandatory;
});
return function (foundParams, definition, field) {
var isFunction = typeof definition === 'function';
var defName = isFunction ? definition.name : definition.constructor.name;
validateParams(knewProps, mandatories, foundParams, defName, field);
};
const props = Object.getOwnPropertyNames(knewProps);
const mandatories = props.filter(p => knewProps[p].mandatory);
return (foundParams, definition, field) => {
const isFunction = typeof definition === 'function';
const defName = isFunction ? definition.name : definition.constructor.name;
validateParams(knewProps, mandatories, foundParams, defName, field);
};
}
function validateParams(knewProps, mandatories, foundParams, defName) {
var field = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
if (field) {
field = '[' + field + ']';
}
var props = Object.getOwnPropertyNames(foundParams);
props.forEach(function (prop) {
var tp = knewProps[prop];
if (!tp) logError(defName, field, 'unknow property \'' + prop + '\'');
var typeOfParam = _typeof(foundParams[prop]);
if (tp && typeOfParam !== tp.type) logError(defName, field, 'expected property \'' + prop + '\' as \'' + tp.type + '\', found \'' + typeOfParam + '\'');
if (tp && tp.depends) {
tp.depends.forEach(function (dep) {
if (props.indexOf(dep) === -1) logError(defName, field, 'when has \'' + prop + '\', props \'' + tp.depends + '\' are mandatory');
});
function validateParams(knewProps, mandatories, foundParams, defName, field = '') {
if (field) {
field = `[${field}]`;
}
});
mandatories.forEach(function (prop) {
if (foundParams[prop] === undefined) logError(defName, field, 'mandatory property \'' + prop + '\' not found');
});
const props = Object.getOwnPropertyNames(foundParams);
props.forEach(prop => {
const tp = knewProps[prop];
if (!tp)
logError(defName, field, `unknow property '${prop}'`);
const typeOfParam = typeof foundParams[prop];
if (tp && typeOfParam !== tp.type)
logError(defName, field, `expected property '${prop}' as '${tp.type}', found '${typeOfParam}'`);
if (tp && tp.depends) {
tp.depends.forEach(dep => {
if (props.indexOf(dep) === -1)
logError(defName, field, `when has '${prop}', props '${tp.depends}' are mandatory`);
});
}
});
mandatories.forEach(prop => {
if (foundParams[prop] === undefined)
logError(defName, field, `mandatory property '${prop}' not found`);
});
}
function logError(defName, field, msg) {
(0, _Logger.error)('' + defName + field + ': ' + msg + '.');
error(`${defName}${field}: ${msg}.`);
}
//# sourceMappingURL=MetaValidator.js.map
{
"name": "@odinjs/odin",
"version": "1.4.2",
"version": "1.5.2",
"description": "On-demand Dependency InjectioN",

@@ -19,33 +19,34 @@ "author": "Thiago Teixeira <thiago.teixeira@philips.com>",

"scripts": {
"clean": "rimraf lib",
"lint": "eslint src",
"babel": "babel -d lib src --copy-files --source-maps --ignore '**/*.spec.js'",
"build": "npm run clean && npm run lint && npm run babel",
"test": "BABEL_ENV=test karma start --single-run",
"test:watch": "karma start"
"build": "npm-run-all --sequential lint build:compile",
"build:compile": "tsc --build",
"ci:build": "npm run build:compile",
"ci:setup": "npm ci",
"ci:test": "npm run test -- --ci",
"clean": "rimraf lib **/.eslintcache **/*.log **/*.tsbuildinfo **/test/coverage",
"env:fresh": "npm-run-all --sequential env:reset env:setup",
"env:reset": "npm run clean && npx rimraf node_modules",
"env:setup": "npm run ci:setup",
"lint": "eslint . --ext .js,.ts --cache --max-warnings 0",
"test": "jest --config jest.config.js",
"test:clear-cache": "jest --clearCache",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watch"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "8.1.1",
"babel-loader": "^7.1.4",
"babel-plugin-istanbul": "^5.1.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-env": "^1.6.1",
"eslint": "^4.19.1",
"eslint-plugin-babel": "^5.0.0",
"jasmine-core": "^3.1.0",
"karma": "^4.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-jasmine": "^1.1.1",
"karma-mocha-reporter": "^2.2.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.0",
"rimraf": "^2.6.2",
"webpack": "^4.3.0",
"webpack-cli": "^2.0.13"
"@types/jest": "28.1.3",
"@typescript-eslint/eslint-plugin": "5.30.0",
"@typescript-eslint/parser": "5.30.0",
"eslint": "8.18.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jest": "26.5.3",
"jest": "28.1.1",
"npm-run-all": "4.1.5",
"rimraf": "3.0.2",
"ts-jest": "28.0.5",
"typescript": "4.7.4"
},
"engines": {
"node": ">= 16.11",
"npm": ">= 8"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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