esp-js-di
Version:
A tiny DI container (formally microdi-js)
2 lines • 11.8 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["esp-js-di"]=t():e["esp-js-di"]=t()}(self,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e,t){var r=arguments,n=1;return e.replace(/%((%)|s)/g,(function(e){return e[2]||r[n++]}))}function n(e){return"[object String]"===Object.prototype.toString.call(e)}function i(e){return"[object Number]"===Object.prototype.toString.call(e)}e.r(t),e.d(t,{Container:()=>v,EspDiConsts:()=>u,RegistrationModifier:()=>g,ResolverContext:()=>s,ResolverNames:()=>p,default:()=>y});class s{constructor(){this._isResolving=!1,this._resolutionChain=[],this._hasEnded=!1}beginResolve(e){var t=this;if(-1!==t._resolutionChain.indexOf(e)){for(var n=t._resolutionChain[0],i=1;i<t._resolutionChain.length;i++)n+=" -required-> "+t._resolutionChain[i];throw n+=" -required-> "+e,new Error(r("Circular dependency detected when resolving item by name '%s'.\r\nThe resolution chain was:\r\n%s",e,n))}return this._isResolving||(this._isResolving=!0),t._resolutionChain.push(e),{endResolve:function(){if(!this._hasEnded){this._hasEnded=!0;var r=t._resolutionChain.indexOf(e);r>-1&&t._resolutionChain.splice(r,1),0===t._resolutionChain.length&&(t._isResolving=!1)}}}}}const o="transient",a="singleton",l="singletonPerContainer",c="external";class h{static isNotNullOrUndefined(e,t){null==e&&d(t)}static isFalsey(e,t){e&&d(t)}static lengthIs(e,t,r){e.length!==t&&d(r)}static lengthGreaterThan(e,t,r){e.length<t&&d(r)}static lengthIsAtLeast(e,t,r){e.length<t&&d(r)}static isString(e,t){n(e)||d(t)}static isNonEmptyString(e,t){n(e)&&!h.lengthIsAtLeast(e,1,t)||d(t)}static isNumber(e,t){i(e)||d(t)}static isTrue(e,t){e||d(t)}static isFunction(e,t){"function"!=typeof e&&d(t)}static isObject(e,t){"object"!=typeof e&&d(t)}}function d(e){if(void 0===e||""===e)throw new Error("EspDi: Argument error");throw new Error("EspDi: "+e)}class g{constructor(e,t,r){this._registration=e,this._instanceCache=t,this._registrationGroups=r,this.singleton()}inject(){this._ensureInstanceNotCreated();var e=Array.prototype.slice.call(arguments);return this._validateDependencyList(e),this._registration.dependencyList=e,this}transient(){return this._ensureInstanceNotCreated(),this._registration.instanceLifecycleType=o,this}singleton(){return this._ensureInstanceNotCreated(),this._registration.instanceLifecycleType=a,this}singletonPerContainer(){return this._ensureInstanceNotCreated(),this._registration.instanceLifecycleType=l,this}inGroup(e){h.isNonEmptyString(e,"Error calling inGroup(groupName). The name argument must be a string and can not be ''"),this._ensureInstanceNotCreated();var t,n,i=!0,s=this._registrationGroups[e];if(s&&(i=this._registrationGroups.hasOwnProperty(e)),void 0!==s&&i||(s=[],this._registrationGroups[e]=s),-1!==(t=s,n=this._registration.name,("function"==typeof Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t=-1,r=-1;for(t=0;t<this.length;t++)if(this[t]===e){r=t;break}return r}).call(t,n)))throw new Error(r("Instance already created for key [%s]",this._registration.name));return s.push(this._registration.name),this}_ensureInstanceNotCreated(){if(this._registration.hasOwnProperty(this._registration.name)&&this._instanceCache.hasOwnProperty(this._registration.name))throw new Error(r("Instance already created for key [%s]",this._registration.name))}_validateDependencyList(e){}}class u{static get owningContainer(){return"EspDi_OwningContainer"}}class p{static get delegate(){return"delegate"}static get factory(){return"factory"}static get externalFactory(){return"externalFactory"}static get literal(){return"literal"}}const f={searchParentContainers:!0};class v{constructor(){this._isChildContainer=!1,this._parent=void 0,this._registrations={},this._registrationGroups={},this._instanceCache={},this._resolverContext=new s,this._resolvers=this._createDefaultResolvers(),this._isDisposed=!1,this._childContainers=[],this._containerEventHandlers=new Map,this._registerSelf()}createChildContainer(){this._throwIfDisposed();var e=Object.create(this);return e._parent=this,e._isChildContainer=!0,e._registrations=Object.create(this._registrations),e._registrationGroups=Object.create(this._registrationGroups),e._instanceCache=Object.create(this._instanceCache),e._resolvers=Object.create(this._resolvers),e._isDisposed=!1,e._childContainers=[],e._registerSelf(),this._childContainers.push(e),e}register(e,t){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling register(name, proto). The name argument must be a string and can not be ''"),h.isNotNullOrUndefined(t,`Error calling register(name, proto). Registered item for [${e}] can not be null or undefined`),h.isTrue(!n(t),`Error calling register(name, proto). Can not register a string instance against key [${e}], use registerInstance(name, instance)`),h.isTrue(!i(t),`Error calling register(name, proto). Can not register a number instance against key [${e}], use registerInstance(name, instance)`);var r={name:e,proto:t,dependencyList:[],instanceLifecycleType:a};return this._registrations[e]=r,new g(r,this._instanceCache,this._registrationGroups)}registerFactory(e,t){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling registerFactory(name, factory). The name argument must be a string and can not be ''"),h.isFunction(t,`Error calling registerFactory(name, factory). Provided factory for [${e}] must be a function`);let r={resolver:"externalFactory",factory:t,isResolverKey:!0};return this.register(e,r)}registerInstance(e,t,r=!0){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling register(name, instance, isExternallyOwned = true). The name argument must be a string and can not be ''"),h.isNotNullOrUndefined(t,`Error calling registerInstance(name, instance, isExternallyOwned = true). Provided instance for [${e}] can not be null or undefined`),this._registrations[e]={name:e,instanceLifecycleType:r?c:a},this._instanceCache[e]=t,this._raiseContainerEvent("instanceRegistered",e,t)}isRegistered(e,t=f){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling isRegistered(name). The name argument must be a string and can not be ''");return t.searchParentContainers?!!this._registrations[e]:this._registrations.hasOwnProperty(e)}isGroupRegistered(e,t=f){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling isGroupRegistered(groupName). The groupName argument must be a string and can not be ''");return t.searchParentContainers?!!this._registrationGroups[e]:this._registrationGroups.hasOwnProperty(e)}resolve(e,...t){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling resolve(name, ...additionalDependencies). The name argument must be a string and can not be ''");var n,i,s=this._registrations[e];if(!s)throw i=r("Nothing registered for dependency [%s]",e),new Error(i);if(n=this._tryRetrieveFromCache(e)){if(t.length>0)throw new Error("The provided additional dependencies can't be used to construct the instance as an existing instance was found in the container")}else n=this._buildInstance(e,t),s.instanceLifecycleType!==a&&s.instanceLifecycleType!==l||(this._instanceCache[e]=n),this._raiseContainerEvent("instanceCreated",e,n);return n}resolveGroup(e,...t){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling resolveGroup(groupName). The groupName argument must be a string and can not be ''");var n,i,s=[];if(!(n=this._registrationGroups[e]))throw i=r("No group with name [%s] registered",e),new Error(i);for(let e=0,r=n.length;e<r;e++)s.push(this.resolve(n[e],...t));return s}addResolver(e,t){this._throwIfDisposed(),h.isNonEmptyString(e,"Error calling addResolver(name, resolver). The name argument must be a string and can not be ''"),h.isNotNullOrUndefined(t,`Error calling addResolver(name, resolver). Provided resolver for [${e}] can not be null or undefined`),this._resolvers[e]=t}on(e,t){h.isNonEmptyString(e,"Error calling on(eventType, eventHandler). The eventType argument must be a string and can not be ''"),h.isFunction(t,"Error calling on(eventType, eventHandler). The eventHandler argument must be a function can not be null or undefined");let r=this._containerEventHandlers.get(e);r||(r=[],this._containerEventHandlers.set(e,r));let n=r.some((e=>e===t));h.isFalsey(n,"Error calling on(eventType, eventHandler). The eventHandler passed is already registered"),r.push(t)}off(e,t){h.isNonEmptyString(e,"Error calling off(eventType, eventHandler). The eventType argument must be a string and can not be ''"),h.isFunction(t,"Error calling off(eventType, eventHandler). The eventHandler argument must be a function can not be null or undefined");let r=this._containerEventHandlers.get(e);if(!r)return;const n=r.indexOf(t);n>-1&&r.splice(n,1)}dispose(){this._disposeContainer()}_tryRetrieveFromCache(e){var t,r,n,i,s,o=this._registrations[e],c=this._instanceCache[e];return this._isChildContainer&&(t=this._registrations.hasOwnProperty(e),void 0===c?(n=o.instanceLifecycleType===a,!t&&n&&(c=this._parent.resolve(e))):(r=this._instanceCache.hasOwnProperty(e))||(i=t&&!r,s=!t&&o.instanceLifecycleType===l,(i||s)&&(c=void 0))),c}_buildInstance(e,t){var i,s,o,a,l,c=this._registrations[e],h=[];o=this._resolverContext.beginResolve(e);try{if(void 0!==c.dependencyList)for(let t=0,o=c.dependencyList.length;t<o;t++){if(n(s=c.dependencyList[t]))i=this.isGroupRegistered(s)?this.resolveGroup(s):this.resolve(s);else{if(!s.hasOwnProperty("resolver")||!n(s.resolver))throw new Error(r("Error resolving [%s]. It's dependency at index [%s] had an unknown resolver",e,t));if(void 0===(l=this._resolvers[s.resolver]))throw new Error(r("Error resolving [%s]. No resolver registered to resolve dependency key for resolver [%s]",e,s.resolver));i=l.resolve(this,s)}h.push(i)}for(let e=0,r=t.length;e<r;e++)h.push(t[e]);if(c.proto.isResolverKey){if(!c.proto.resolver)throw new Error("Registered resolverKey is missing it's resolver property");a=(l=this._resolvers[c.proto.resolver]).resolve(this,c.proto,...h)}else if("function"==typeof c.proto){a=new(c.proto.bind.apply(c.proto,[null].concat(h)))}else void 0!==(a=Object.create(c.proto)).init&&(a=a.init.apply(a,h)||a)}finally{o.endResolve()}return a}_createDefaultResolvers(){return{[p.delegate]:{resolve:(e,t)=>t.resolve(e)},[p.factory]:{resolve:(e,t)=>function(){var r=[].slice.call(arguments);return r.unshift(t.key),e.resolve.apply(e,r)}},[p.externalFactory]:{resolve:function(e,t,...r){return t.factory.apply(null,[e,...r])}},[p.literal]:{resolve:function(e,t){return h.isNotNullOrUndefined(t.value,"Invalid container configuration. A literal resolver key is missing the 'value' property. That property should hold the value to be resolved."),t.value}}}}_registerSelf(){this.registerInstance(u.owningContainer,this)}_raiseContainerEvent(e,t,r){let n=this._containerEventHandlers.get(e);if(!n)return;let i={name:t,instance:r,eventType:e},s=n.slice(0);for(let e=0;e<s.length;e++)s[e](i)}_throwIfDisposed(){if(this._isDisposed)throw new Error("Container has been disposed")}_disposeContainer(){if(!this._isDisposed){for(var e in this._isDisposed=!0,this._instanceCache){if(this._instanceCache.hasOwnProperty(e))if(this._registrations[e].instanceLifecycleType!==c){var t=this._instanceCache[e];t.dispose&&t.dispose()}}for(var r=0,n=this._childContainers.length;r<n;r++){this._childContainers[r]._disposeContainer()}}}}const y={Container:v,RegistrationModifier:g,ResolverContext:s,EspDiConsts:u,ResolverNames:p};return t})()));
//# sourceMappingURL=esp-js-di.min.js.map