UNPKG

brandi

Version:

The dependency injection container.

433 lines (411 loc) • 13.4 kB
// src/registries/callableRegistry.ts var callableRegistry = new WeakMap(); // src/registries/injectsRegistry.ts var injectsRegistry = new Map(); // src/registries/tagsRegistry.ts var tagsRegistry = new Map(); // src/container/bindings/Binding.ts var Type; (function(Type2) { Type2[Type2["Constant"] = 0] = "Constant"; Type2[Type2["Instance"] = 1] = "Instance"; Type2[Type2["Factory"] = 2] = "Factory"; })(Type || (Type = {})); var Scope; (function(Scope2) { Scope2[Scope2["Container"] = 0] = "Container"; Scope2[Scope2["Resolution"] = 1] = "Resolution"; Scope2[Scope2["Singleton"] = 2] = "Singleton"; Scope2[Scope2["Transient"] = 3] = "Transient"; })(Scope || (Scope = {})); // src/container/bindings/ConstantBinding.ts var ConstantBinding = class { constructor(impl) { this.impl = impl; this.type = Type.Constant; } }; // src/container/bindings/FactoryBinding.ts var FactoryBinding = class { constructor(impl) { this.impl = impl; this.type = Type.Factory; } }; var isFactoryBinding = (binding) => binding.type === Type.Factory; // src/container/bindings/InstanceBinding.ts var InstanceBinding = class { constructor(impl) { this.impl = impl; this.type = Type.Instance; } }; var InstanceContainerScopedBinding = class extends InstanceBinding { constructor() { super(...arguments); this.scope = Scope.Container; this.cache = new WeakMap(); } }; var InstanceResolutionScopedBinding = class extends InstanceBinding { constructor() { super(...arguments); this.scope = Scope.Resolution; } }; var InstanceSingletonScopedBinding = class extends InstanceBinding { constructor(impl) { super(impl); this.impl = impl; this.scope = Scope.Singleton; if (process.env.NODE_ENV !== "production") { this.clone = () => { const binding = new InstanceSingletonScopedBinding(this.impl); binding.cache = this.cache; return binding; }; } } }; var InstanceTransientScopedBinding = class extends InstanceBinding { constructor() { super(...arguments); this.scope = Scope.Transient; } }; var isInstanceBinding = (binding) => binding.type === Type.Instance; var isInstanceContainerScopedBinding = (binding) => binding.scope === Scope.Container; var isInstanceResolutionScopedBinding = (binding) => binding.scope === Scope.Resolution; var isInstanceSingletonScopedBinding = (binding) => binding.scope === Scope.Singleton; // src/pointers/tag.ts var tag = (description) => Symbol(description); // src/pointers/token.ts var token = (description) => { const s = Symbol(description); return { __t: null, __d: description, __s: s, __o: false, optional: { __t: null, __d: description, __s: s, __o: true } }; }; // src/container/BindingsVault.ts var _BindingsVault = class { constructor() { this.parent = null; this.map = new Map(); if (process.env.NODE_ENV !== "production") { this.copy = () => this.from((prev) => { const next = new Map(); prev.forEach((binding, key) => { if (binding instanceof _BindingsVault) { next.set(key, binding.copy()); } else { next.set(key, binding.clone?.() ?? binding); } }); return next; }); } } set(binding, token2, condition = _BindingsVault.notag) { const current = this.map.get(token2.__s); if (current) current.set(condition, binding); else this.map.set(token2.__s, new Map().set(condition, binding)); } find(token2, conditions, target) { const bindings = this.map.get(token2.__s); if (bindings === void 0) return void 0; if (target) { const targetBinding = bindings.get(target); if (targetBinding) return targetBinding; } if (process.env.NODE_ENV !== "production" && conditions && conditions.reduce((acc, condition) => bindings.has(condition) ? acc + 1 : acc, 0) > 1) { const conditionsDisplayString = conditions.map((condition) => typeof condition === "function" ? condition.name : `tag(${condition.description})`).join(", "); console.warn(`Warning: When resolving a binding by '${token2.__d}' token with [${conditionsDisplayString}] conditions, more than one binding was found. In this case, Brandi resolves the binding by the first tag assigned by 'tagged(target, ...tags)' function or, if you explicitly passed conditions through 'Container.get(token, conditions)' method, by the first resolved condition. Try to avoid such implicit logic.`); } if (conditions) { for (let i = 0, len = conditions.length; i < len; i += 1) { const binding = bindings.get(conditions[i]); if (binding) return binding; } } return bindings.get(_BindingsVault.notag); } resolve(token2, cache, conditions, target) { const binding = this.find(token2, conditions, target); if (binding === void 0) return this.parent ? this.parent.resolve(token2, cache, conditions, target) : null; if (binding instanceof _BindingsVault) { cache.vaults.push(binding); return binding.resolve(token2, cache, conditions, target); } return binding; } get(token2, cache, conditions, target) { const ownBinding = this.resolve(token2, cache, conditions, target); if (ownBinding) return ownBinding; for (let i = 0, v = cache.vaults, len = v.length; i < len; i += 1) { const cacheBinding = v[i].resolve(token2, cache, conditions, target); if (cacheBinding) return cacheBinding; } return null; } from(callback) { const vault = new _BindingsVault(); vault.parent = this.parent; this.map.forEach((bindings, key) => { vault.map.set(key, callback(bindings)); }); return vault; } clone() { return this.from((prev) => new Map(prev)); } }; var BindingsVault = _BindingsVault; BindingsVault.notag = tag("NO_TAG"); // src/container/syntax/FromSyntax.ts var FromSyntax = class { constructor(vault, tokens, getVault, condition) { this.vault = vault; this.tokens = tokens; this.getVault = getVault; this.condition = condition; } from(dependencyModule) { const {tokens} = this; for (let i = 0, len = tokens.length; i < len; i += 1) { this.vault.set(this.getVault(dependencyModule), tokens[i], this.condition); } } }; // src/container/syntax/ScopeSyntax.ts var ScopeSyntax = class { constructor(vault, impl, token2, condition) { this.vault = vault; this.impl = impl; this.token = token2; this.condition = condition; if (process.env.NODE_ENV !== "production") { this.warningTimeout = setTimeout(() => { console.warn(`Warning: did you forget to set a scope for '${this.token.__d}' token binding? Call 'inTransientScope()', 'inSingletonScope()', 'inContainerScope()' or 'inResolutionScope()'.`); }); } } inContainerScope() { this.set(InstanceContainerScopedBinding); } inResolutionScope() { this.set(InstanceResolutionScopedBinding); } inSingletonScope() { this.set(InstanceSingletonScopedBinding); } inTransientScope() { this.set(InstanceTransientScopedBinding); } set(Ctor) { if (process.env.NODE_ENV !== "production") clearTimeout(this.warningTimeout); this.vault.set(new Ctor(this.impl), this.token, this.condition); } }; // src/container/syntax/TypeSyntax.ts var TypeSyntax = class { constructor(vault, token2, condition) { this.vault = vault; this.token = token2; this.condition = condition; } toConstant(value) { this.vault.set(new ConstantBinding(value), this.token, this.condition); } toFactory(creator, initializer) { this.vault.set(new FactoryBinding({creator, initializer}), this.token, this.condition); } toInstance(creator) { return new ScopeSyntax(this.vault, creator, this.token, this.condition); } }; // src/container/syntax/BindOrUseSyntax.ts var BindOrUseSyntax = class { constructor(vault, condition) { this.vault = vault; this.condition = condition; } static vault(target) { return target.vault; } bind(token2) { return new TypeSyntax(this.vault, token2, this.condition); } use(...tokens) { return new FromSyntax(this.vault, tokens, BindOrUseSyntax.vault, this.condition); } }; // src/container/syntax/WhenSyntax.ts var WhenSyntax = class extends BindOrUseSyntax { when(condition) { return new BindOrUseSyntax(this.vault, condition); } }; // src/container/DependencyModule.ts var DependencyModule = class extends WhenSyntax { constructor() { super(new BindingsVault()); } }; // src/container/ResolutionCache.ts var ResolutionCache = class { constructor(instances = new Map(), vaults = []) { this.instances = instances; this.vaults = vaults; } split() { return new ResolutionCache(this.instances, this.vaults.slice()); } }; // src/container/Container.ts var Container = class extends DependencyModule { constructor() { super(); this.snapshot = null; if (process.env.NODE_ENV !== "production") { this.capture = () => { this.snapshot = this.vault.copy(); }; this.restore = () => { if (this.snapshot) { this.vault = this.snapshot.copy(); } else { console.error("Error: It looks like a trying to restore a non-captured container state. Did you forget to call 'capture()' method?"); } }; } } extend(container) { this.vault.parent = container === null ? null : container.vault; return this; } clone() { const container = new Container(); container.vault = this.vault.clone(); return container; } get(token2, conditions) { return this.resolveToken(token2, conditions); } resolveTokens(tokens, cache, conditions, target) { return tokens.map((token2) => this.resolveToken(token2, conditions, target, cache.split())); } resolveToken(token2, conditions, target, cache = new ResolutionCache()) { const binding = this.vault.get(token2, cache, conditions, target); if (binding) return this.resolveBinding(binding, cache); if (token2.__o) return void 0; throw new Error(`No matching bindings found for '${token2.__d}' token.`); } resolveBinding(binding, cache) { if (isInstanceBinding(binding)) { if (isInstanceSingletonScopedBinding(binding)) { return this.resolveCache(binding, cache, () => binding.cache, (instance) => { binding.cache = instance; }); } if (isInstanceContainerScopedBinding(binding)) { return this.resolveCache(binding, cache, () => binding.cache.get(this.vault), (instance) => { binding.cache.set(this.vault, instance); }); } if (isInstanceResolutionScopedBinding(binding)) { return this.resolveCache(binding, cache, () => cache.instances.get(binding), (instance) => { cache.instances.set(binding, instance); }); } return this.createInstance(binding.impl, cache); } if (isFactoryBinding(binding)) { return (...args) => { const instance = this.createInstance(binding.impl.creator, cache); return instance instanceof Promise ? instance.then((i) => Container.resolveInitialization(i, args, binding.impl.initializer)) : Container.resolveInitialization(instance, args, binding.impl.initializer); }; } return binding.impl; } resolveCache(binding, cache, getCache, setCache) { const instanceCache = getCache(); if (instanceCache !== void 0) return instanceCache; const instance = this.createInstance(binding.impl, cache); setCache(instance); return instance; } createInstance(creator, cache) { const parameters = this.getParameters(creator, cache); const isCallable = callableRegistry.get(creator); if (isCallable !== void 0) { return isCallable ? creator(...parameters) : new creator(...parameters); } try { const instance = creator(...parameters); callableRegistry.set(creator, true); return instance; } catch { const instance = new creator(...parameters); callableRegistry.set(creator, false); return instance; } } getParameters(target, cache) { const injects = injectsRegistry.get(target); if (injects) return this.resolveTokens(injects, cache, tagsRegistry.get(target), target); if (target.length === 0) return []; throw new Error(`Missing required 'injected' registration of '${target.name}'`); } static resolveInitialization(instance, args, initializer) { const initialization = initializer?.(instance, ...args); return initialization instanceof Promise ? initialization.then(() => instance) : instance; } }; // src/container/createContainer.ts var createContainer = () => new Container(); // src/container/createDependencyModule.ts var createDependencyModule = () => new DependencyModule(); // src/registrators/injected.ts var injected = (target, ...tokens) => { injectsRegistry.set(target, tokens); return target; }; // src/registrators/tagged.ts var tagged = (target, ...tags) => { tagsRegistry.set(target, tags); return target; }; export { Container, DependencyModule, createContainer, createDependencyModule, injected, tag, tagged, token }; //# sourceMappingURL=brandi.next.js.map