Socket
Socket
Sign inDemoInstall

awilix

Package Overview
Dependencies
23
Maintainers
1
Versions
81
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 9.0.0 to 10.0.0

225

lib/awilix.browser.js

@@ -206,11 +206,10 @@ /******************************************************************************

function AwilixResolutionError(name, resolutionStack, message) {
if (typeof name === 'symbol') {
name = name.toString();
}
resolutionStack = resolutionStack.map(function (val) {
return typeof val === 'symbol' ? val.toString() : val;
var stringName = name.toString();
var nameStack = resolutionStack.map(function (_a) {
var val = _a.name;
return val.toString();
});
resolutionStack.push(name);
var resolutionPathString = resolutionStack.join(' -> ');
var msg = "Could not resolve '".concat(name, "'.");
nameStack.push(stringName);
var resolutionPathString = nameStack.join(' -> ');
var msg = "Could not resolve '".concat(stringName, "'.");
if (message) {

@@ -225,4 +224,72 @@ msg += " ".concat(message);

}(AwilixError));
/**
* A nice error class so we can do an instanceOf check.
*/
var AwilixRegistrationError = /** @class */ (function (_super) {
__extends(AwilixRegistrationError, _super);
/**
* Constructor, takes the registered modules and unresolved tokens
* to create a message.
*
* @param {string|symbol} name
* The name of the module that could not be registered.
*/
function AwilixRegistrationError(name, message) {
var stringName = name.toString();
var msg = "Could not register '".concat(stringName, "'.");
if (message) {
msg += " ".concat(message);
}
return _super.call(this, msg) || this;
}
return AwilixRegistrationError;
}(AwilixError));
/**
* Resolution modes.
*/
var InjectionMode = {
/**
* The dependencies will be resolved by injecting the cradle proxy.
*
* @type {String}
*/
PROXY: 'PROXY',
/**
* The dependencies will be resolved by inspecting parameter names of the function/constructor.
*
* @type {String}
*/
CLASSIC: 'CLASSIC',
};
/**
* Lifetime types.
*/
var Lifetime = {
/**
* The registration will be resolved once and only once.
* @type {String}
*/
SINGLETON: 'SINGLETON',
/**
* The registration will be resolved every time (never cached).
* @type {String}
*/
TRANSIENT: 'TRANSIENT',
/**
* The registration will be resolved once per scope.
* @type {String}
*/
SCOPED: 'SCOPED',
};
/**
* Returns true if and only if the first lifetime is strictly longer than the second.
*/
function isLifetimeLonger(a, b) {
return ((a === Lifetime.SINGLETON && b !== Lifetime.SINGLETON) ||
(a === Lifetime.SCOPED && b === Lifetime.TRANSIENT));
}
/**
* Creates a tokenizer for the specified source.

@@ -567,41 +634,2 @@ *

/**
* Lifetime types.
*/
var Lifetime = {
/**
* The registration will be resolved once and only once.
* @type {String}
*/
SINGLETON: 'SINGLETON',
/**
* The registration will be resolved every time (never cached).
* @type {String}
*/
TRANSIENT: 'TRANSIENT',
/**
* The registration will be resolved once per scope.
* @type {String}
*/
SCOPED: 'SCOPED',
};
/**
* Resolution modes.
*/
var InjectionMode = {
/**
* The dependencies will be resolved by injecting the cradle proxy.
*
* @type {String}
*/
PROXY: 'PROXY',
/**
* The dependencies will be resolved by inspecting parameter names of the function/constructor.
*
* @type {String}
*/
CLASSIC: 'CLASSIC',
};
/*

@@ -742,12 +770,11 @@ * Parses the parameter list of a function string, including ES6 class constructors.

/**
* Creates a simple value resolver where the given value will always be resolved.
* Creates a simple value resolver where the given value will always be resolved. The value is
* marked as leak-safe since in strict mode, the value will only be resolved when it is not leaking
* upwards from a child scope to a parent singleton.
*
* @param {string} name
* The name to register the value as.
* @param {string} name The name to register the value as.
*
* @param {*} value
* The value to resolve.
* @param {*} value The value to resolve.
*
* @return {object}
* The resolver.
* @return {object} The resolver.
*/

@@ -757,2 +784,3 @@ function asValue(value) {

resolve: function () { return value; },
isLeakSafe: true,
};

@@ -823,3 +851,4 @@ }

/**
* Resolves to the specified registration.
* Resolves to the specified registration. Marked as leak-safe since the alias target is what should
* be checked for lifetime leaks.
*/

@@ -831,2 +860,3 @@ function aliasTo(name) {

},
isLeakSafe: true,
};

@@ -1113,19 +1143,24 @@ }

*
* @param {Function} options.require
* The require function to use. Defaults to require.
* @param {Function} options.require The require function to use. Defaults to require.
*
* @param {string} options.injectionMode
* The mode used by the container to resolve dependencies. Defaults to 'Proxy'.
* @param {string} options.injectionMode The mode used by the container to resolve dependencies.
* Defaults to 'Proxy'.
*
* @return {AwilixContainer<T>}
* The container.
* @param {boolean} options.strict True if the container should run in strict mode with additional
* validation for resolver configuration correctness. Defaults to false.
*
* @return {AwilixContainer<T>} The container.
*/
function createContainer(options, parentContainer) {
function createContainer(options) {
if (options === void 0) { options = {}; }
return createContainerInternal(options);
}
function createContainerInternal(options, parentContainer, parentResolutionStack) {
var _a;
options = __assign({ injectionMode: InjectionMode.PROXY }, options);
// The resolution stack is used to keep track
// of what modules are being resolved, so when
// an error occurs, we have something to present
// to the poor developer who fucked up.
var resolutionStack = [];
options = __assign({ injectionMode: InjectionMode.PROXY, strict: false }, options);
/**
* Tracks the names and lifetimes of the modules being resolved. Used to detect circular
* dependencies and, in strict mode, lifetime leakage issues.
*/
var resolutionStack = parentResolutionStack !== null && parentResolutionStack !== void 0 ? parentResolutionStack : [];
// Internal registration store for this container.

@@ -1278,3 +1313,3 @@ var registrations = {};

function createScope() {
return createContainer(options, container);
return createContainerInternal(options, container, resolutionStack);
}

@@ -1289,4 +1324,11 @@ /**

var key = keys_1[_i];
var value = obj[key];
registrations[key] = value;
var resolver = obj[key];
// If strict mode is enabled, check to ensure we are not registering a singleton on a non-root
// container.
if (options.strict && resolver.lifetime === Lifetime.SINGLETON) {
if (parentContainer) {
throw new AwilixRegistrationError(key, 'Cannot register a singleton on a scoped container.');
}
}
registrations[key] = resolver;
}

@@ -1335,3 +1377,6 @@ return container;

var resolver = getRegistration(name);
if (resolutionStack.indexOf(name) > -1) {
if (resolutionStack.some(function (_a) {
var parentName = _a.name;
return parentName === name;
})) {
throw new AwilixResolutionError(name, resolutionStack, 'Cyclic dependencies detected.');

@@ -1371,8 +1416,20 @@ }

}
// Pushes the currently-resolving module name onto the stack
resolutionStack.push(name);
var lifetime_1 = resolver.lifetime || Lifetime.TRANSIENT;
// if we are running in strict mode, this resolver is not explicitly marked leak-safe, and any
// of the parents have a shorter lifetime than the one requested, throw an error.
if (options.strict && !resolver.isLeakSafe) {
var maybeLongerLifetimeParentIndex = resolutionStack.findIndex(function (_a) {
var parentLifetime = _a.lifetime;
return isLifetimeLonger(parentLifetime, lifetime_1);
});
if (maybeLongerLifetimeParentIndex > -1) {
throw new AwilixResolutionError(name, resolutionStack, "Dependency '".concat(name.toString(), "' has a shorter lifetime than its ancestor: '").concat(resolutionStack[maybeLongerLifetimeParentIndex].name.toString(), "'"));
}
}
// Pushes the currently-resolving module information onto the stack
resolutionStack.push({ name: name, lifetime: lifetime_1 });
// Do the thing
var cached = void 0;
var resolved = void 0;
switch (resolver.lifetime || Lifetime.TRANSIENT) {
switch (lifetime_1) {
case Lifetime.TRANSIENT:

@@ -1386,3 +1443,5 @@ // Transient lifetime means resolve every time.

if (!cached) {
resolved = resolver.resolve(container);
// if we are running in strict mode, perform singleton resolution using the root
// container only.
resolved = resolver.resolve(options.strict ? rootContainer : container);
rootContainer.cache.set(name, { resolver: resolver, value: resolved });

@@ -1397,4 +1456,5 @@ }

// that resolves the registration also caches it.
// When a registration is not found, we travel up
// the family tree until we find one that is cached.
// If this container cache does not have it,
// resolve and cache it rather than using the parent
// container's cache.
cached = container.cache.get(name);

@@ -1418,4 +1478,5 @@ if (cached !== undefined) {

catch (err) {
// When we get an error we need to reset the stack.
resolutionStack = [];
// When we get an error we need to reset the stack. Mutate the existing array rather than
// updating the reference to ensure all parent containers' stacks are also updated.
resolutionStack.length = 0;
throw err;

@@ -1441,3 +1502,3 @@ }

*
* @param {Resolver|Class|Function} targetOrResolver
* @param {Resolver|Constructor|Function} targetOrResolver
* @param {ResolverOptions} opts

@@ -1477,2 +1538,2 @@ */

export { AwilixError, AwilixResolutionError, AwilixTypeError, ExtendableError, InjectionMode, Lifetime, RESOLVER, aliasTo, asClass, asFunction, asValue, createBuildResolver, createContainer, createDisposableResolver };
export { AwilixError, AwilixRegistrationError, AwilixResolutionError, AwilixTypeError, InjectionMode, Lifetime, aliasTo, asClass, asFunction, asValue, createContainer };

@@ -1,6 +0,6 @@

export * from './errors';
export * from './list-modules';
export * from './container';
export * from './resolvers';
export * from './injection-mode';
export * from './lifetime';
export { AwilixContainer, ContainerOptions, createContainer } from './container';
export { AwilixError, AwilixRegistrationError, AwilixResolutionError, AwilixTypeError, } from './errors';
export { InjectionMode, InjectionModeType } from './injection-mode';
export { Lifetime, LifetimeType } from './lifetime';
export { GlobWithOptions, ListModulesOptions, ModuleDescriptor, listModules, } from './list-modules';
export { BuildResolverOptions, Disposer, InjectorFunction, aliasTo, asClass, asFunction, asValue, } from './resolvers';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./errors"), exports);
__exportStar(require("./list-modules"), exports);
__exportStar(require("./container"), exports);
__exportStar(require("./resolvers"), exports);
__exportStar(require("./injection-mode"), exports);
__exportStar(require("./lifetime"), exports);
exports.asValue = exports.asFunction = exports.asClass = exports.aliasTo = exports.listModules = exports.Lifetime = exports.InjectionMode = exports.AwilixTypeError = exports.AwilixResolutionError = exports.AwilixRegistrationError = exports.AwilixError = exports.createContainer = void 0;
var container_1 = require("./container");
Object.defineProperty(exports, "createContainer", { enumerable: true, get: function () { return container_1.createContainer; } });
var errors_1 = require("./errors");
Object.defineProperty(exports, "AwilixError", { enumerable: true, get: function () { return errors_1.AwilixError; } });
Object.defineProperty(exports, "AwilixRegistrationError", { enumerable: true, get: function () { return errors_1.AwilixRegistrationError; } });
Object.defineProperty(exports, "AwilixResolutionError", { enumerable: true, get: function () { return errors_1.AwilixResolutionError; } });
Object.defineProperty(exports, "AwilixTypeError", { enumerable: true, get: function () { return errors_1.AwilixTypeError; } });
var injection_mode_1 = require("./injection-mode");
Object.defineProperty(exports, "InjectionMode", { enumerable: true, get: function () { return injection_mode_1.InjectionMode; } });
var lifetime_1 = require("./lifetime");
Object.defineProperty(exports, "Lifetime", { enumerable: true, get: function () { return lifetime_1.Lifetime; } });
var list_modules_1 = require("./list-modules");
Object.defineProperty(exports, "listModules", { enumerable: true, get: function () { return list_modules_1.listModules; } });
var resolvers_1 = require("./resolvers");
Object.defineProperty(exports, "aliasTo", { enumerable: true, get: function () { return resolvers_1.aliasTo; } });
Object.defineProperty(exports, "asClass", { enumerable: true, get: function () { return resolvers_1.asClass; } });
Object.defineProperty(exports, "asFunction", { enumerable: true, get: function () { return resolvers_1.asFunction; } });
Object.defineProperty(exports, "asValue", { enumerable: true, get: function () { return resolvers_1.asValue; } });
//# sourceMappingURL=awilix.js.map

@@ -212,11 +212,10 @@ (function (global, factory) {

function AwilixResolutionError(name, resolutionStack, message) {
if (typeof name === 'symbol') {
name = name.toString();
}
resolutionStack = resolutionStack.map(function (val) {
return typeof val === 'symbol' ? val.toString() : val;
var stringName = name.toString();
var nameStack = resolutionStack.map(function (_a) {
var val = _a.name;
return val.toString();
});
resolutionStack.push(name);
var resolutionPathString = resolutionStack.join(' -> ');
var msg = "Could not resolve '".concat(name, "'.");
nameStack.push(stringName);
var resolutionPathString = nameStack.join(' -> ');
var msg = "Could not resolve '".concat(stringName, "'.");
if (message) {

@@ -231,4 +230,72 @@ msg += " ".concat(message);

}(AwilixError));
/**
* A nice error class so we can do an instanceOf check.
*/
var AwilixRegistrationError = /** @class */ (function (_super) {
__extends(AwilixRegistrationError, _super);
/**
* Constructor, takes the registered modules and unresolved tokens
* to create a message.
*
* @param {string|symbol} name
* The name of the module that could not be registered.
*/
function AwilixRegistrationError(name, message) {
var stringName = name.toString();
var msg = "Could not register '".concat(stringName, "'.");
if (message) {
msg += " ".concat(message);
}
return _super.call(this, msg) || this;
}
return AwilixRegistrationError;
}(AwilixError));
/**
* Resolution modes.
*/
var InjectionMode = {
/**
* The dependencies will be resolved by injecting the cradle proxy.
*
* @type {String}
*/
PROXY: 'PROXY',
/**
* The dependencies will be resolved by inspecting parameter names of the function/constructor.
*
* @type {String}
*/
CLASSIC: 'CLASSIC',
};
/**
* Lifetime types.
*/
var Lifetime = {
/**
* The registration will be resolved once and only once.
* @type {String}
*/
SINGLETON: 'SINGLETON',
/**
* The registration will be resolved every time (never cached).
* @type {String}
*/
TRANSIENT: 'TRANSIENT',
/**
* The registration will be resolved once per scope.
* @type {String}
*/
SCOPED: 'SCOPED',
};
/**
* Returns true if and only if the first lifetime is strictly longer than the second.
*/
function isLifetimeLonger(a, b) {
return ((a === Lifetime.SINGLETON && b !== Lifetime.SINGLETON) ||
(a === Lifetime.SCOPED && b === Lifetime.TRANSIENT));
}
/**
* Creates a tokenizer for the specified source.

@@ -573,41 +640,2 @@ *

/**
* Lifetime types.
*/
var Lifetime = {
/**
* The registration will be resolved once and only once.
* @type {String}
*/
SINGLETON: 'SINGLETON',
/**
* The registration will be resolved every time (never cached).
* @type {String}
*/
TRANSIENT: 'TRANSIENT',
/**
* The registration will be resolved once per scope.
* @type {String}
*/
SCOPED: 'SCOPED',
};
/**
* Resolution modes.
*/
var InjectionMode = {
/**
* The dependencies will be resolved by injecting the cradle proxy.
*
* @type {String}
*/
PROXY: 'PROXY',
/**
* The dependencies will be resolved by inspecting parameter names of the function/constructor.
*
* @type {String}
*/
CLASSIC: 'CLASSIC',
};
/*

@@ -748,12 +776,11 @@ * Parses the parameter list of a function string, including ES6 class constructors.

/**
* Creates a simple value resolver where the given value will always be resolved.
* Creates a simple value resolver where the given value will always be resolved. The value is
* marked as leak-safe since in strict mode, the value will only be resolved when it is not leaking
* upwards from a child scope to a parent singleton.
*
* @param {string} name
* The name to register the value as.
* @param {string} name The name to register the value as.
*
* @param {*} value
* The value to resolve.
* @param {*} value The value to resolve.
*
* @return {object}
* The resolver.
* @return {object} The resolver.
*/

@@ -763,2 +790,3 @@ function asValue(value) {

resolve: function () { return value; },
isLeakSafe: true,
};

@@ -829,3 +857,4 @@ }

/**
* Resolves to the specified registration.
* Resolves to the specified registration. Marked as leak-safe since the alias target is what should
* be checked for lifetime leaks.
*/

@@ -837,2 +866,3 @@ function aliasTo(name) {

},
isLeakSafe: true,
};

@@ -1119,19 +1149,24 @@ }

*
* @param {Function} options.require
* The require function to use. Defaults to require.
* @param {Function} options.require The require function to use. Defaults to require.
*
* @param {string} options.injectionMode
* The mode used by the container to resolve dependencies. Defaults to 'Proxy'.
* @param {string} options.injectionMode The mode used by the container to resolve dependencies.
* Defaults to 'Proxy'.
*
* @return {AwilixContainer<T>}
* The container.
* @param {boolean} options.strict True if the container should run in strict mode with additional
* validation for resolver configuration correctness. Defaults to false.
*
* @return {AwilixContainer<T>} The container.
*/
function createContainer(options, parentContainer) {
function createContainer(options) {
if (options === void 0) { options = {}; }
return createContainerInternal(options);
}
function createContainerInternal(options, parentContainer, parentResolutionStack) {
var _a;
options = __assign({ injectionMode: InjectionMode.PROXY }, options);
// The resolution stack is used to keep track
// of what modules are being resolved, so when
// an error occurs, we have something to present
// to the poor developer who fucked up.
var resolutionStack = [];
options = __assign({ injectionMode: InjectionMode.PROXY, strict: false }, options);
/**
* Tracks the names and lifetimes of the modules being resolved. Used to detect circular
* dependencies and, in strict mode, lifetime leakage issues.
*/
var resolutionStack = parentResolutionStack !== null && parentResolutionStack !== void 0 ? parentResolutionStack : [];
// Internal registration store for this container.

@@ -1284,3 +1319,3 @@ var registrations = {};

function createScope() {
return createContainer(options, container);
return createContainerInternal(options, container, resolutionStack);
}

@@ -1295,4 +1330,11 @@ /**

var key = keys_1[_i];
var value = obj[key];
registrations[key] = value;
var resolver = obj[key];
// If strict mode is enabled, check to ensure we are not registering a singleton on a non-root
// container.
if (options.strict && resolver.lifetime === Lifetime.SINGLETON) {
if (parentContainer) {
throw new AwilixRegistrationError(key, 'Cannot register a singleton on a scoped container.');
}
}
registrations[key] = resolver;
}

@@ -1341,3 +1383,6 @@ return container;

var resolver = getRegistration(name);
if (resolutionStack.indexOf(name) > -1) {
if (resolutionStack.some(function (_a) {
var parentName = _a.name;
return parentName === name;
})) {
throw new AwilixResolutionError(name, resolutionStack, 'Cyclic dependencies detected.');

@@ -1377,8 +1422,20 @@ }

}
// Pushes the currently-resolving module name onto the stack
resolutionStack.push(name);
var lifetime_1 = resolver.lifetime || Lifetime.TRANSIENT;
// if we are running in strict mode, this resolver is not explicitly marked leak-safe, and any
// of the parents have a shorter lifetime than the one requested, throw an error.
if (options.strict && !resolver.isLeakSafe) {
var maybeLongerLifetimeParentIndex = resolutionStack.findIndex(function (_a) {
var parentLifetime = _a.lifetime;
return isLifetimeLonger(parentLifetime, lifetime_1);
});
if (maybeLongerLifetimeParentIndex > -1) {
throw new AwilixResolutionError(name, resolutionStack, "Dependency '".concat(name.toString(), "' has a shorter lifetime than its ancestor: '").concat(resolutionStack[maybeLongerLifetimeParentIndex].name.toString(), "'"));
}
}
// Pushes the currently-resolving module information onto the stack
resolutionStack.push({ name: name, lifetime: lifetime_1 });
// Do the thing
var cached = void 0;
var resolved = void 0;
switch (resolver.lifetime || Lifetime.TRANSIENT) {
switch (lifetime_1) {
case Lifetime.TRANSIENT:

@@ -1392,3 +1449,5 @@ // Transient lifetime means resolve every time.

if (!cached) {
resolved = resolver.resolve(container);
// if we are running in strict mode, perform singleton resolution using the root
// container only.
resolved = resolver.resolve(options.strict ? rootContainer : container);
rootContainer.cache.set(name, { resolver: resolver, value: resolved });

@@ -1403,4 +1462,5 @@ }

// that resolves the registration also caches it.
// When a registration is not found, we travel up
// the family tree until we find one that is cached.
// If this container cache does not have it,
// resolve and cache it rather than using the parent
// container's cache.
cached = container.cache.get(name);

@@ -1424,4 +1484,5 @@ if (cached !== undefined) {

catch (err) {
// When we get an error we need to reset the stack.
resolutionStack = [];
// When we get an error we need to reset the stack. Mutate the existing array rather than
// updating the reference to ensure all parent containers' stacks are also updated.
resolutionStack.length = 0;
throw err;

@@ -1447,3 +1508,3 @@ }

*
* @param {Resolver|Class|Function} targetOrResolver
* @param {Resolver|Constructor|Function} targetOrResolver
* @param {ResolverOptions} opts

@@ -1484,8 +1545,7 @@ */

exports.AwilixError = AwilixError;
exports.AwilixRegistrationError = AwilixRegistrationError;
exports.AwilixResolutionError = AwilixResolutionError;
exports.AwilixTypeError = AwilixTypeError;
exports.ExtendableError = ExtendableError;
exports.InjectionMode = InjectionMode;
exports.Lifetime = Lifetime;
exports.RESOLVER = RESOLVER;
exports.aliasTo = aliasTo;

@@ -1495,6 +1555,4 @@ exports.asClass = asClass;

exports.asValue = asValue;
exports.createBuildResolver = createBuildResolver;
exports.createContainer = createContainer;
exports.createDisposableResolver = createDisposableResolver;
}));

@@ -0,5 +1,6 @@

import { InjectionModeType } from './injection-mode';
import { LifetimeType } from './lifetime';
import { GlobWithOptions } from './list-modules';
import { LoadModulesOptions } from './load-modules';
import { Resolver, Constructor, BuildResolverOptions } from './resolvers';
import { InjectionModeType } from './injection-mode';
import { BuildResolverOptions, Constructor, Resolver } from './resolvers';
/**

@@ -157,2 +158,3 @@ * The container returned from createContainer has some methods and properties.

injectionMode?: InjectionModeType;
strict?: boolean;
}

@@ -163,19 +165,19 @@ /**

export type RegistrationHash = Record<string | symbol | number, Resolver<any>>;
export type ResolutionStack = Array<{
name: string | symbol;
lifetime: LifetimeType;
}>;
/**
* Resolution stack.
*/
export interface ResolutionStack extends Array<string | symbol> {
}
/**
* Creates an Awilix container instance.
*
* @param {Function} options.require
* The require function to use. Defaults to require.
* @param {Function} options.require The require function to use. Defaults to require.
*
* @param {string} options.injectionMode
* The mode used by the container to resolve dependencies. Defaults to 'Proxy'.
* @param {string} options.injectionMode The mode used by the container to resolve dependencies.
* Defaults to 'Proxy'.
*
* @return {AwilixContainer<T>}
* The container.
* @param {boolean} options.strict True if the container should run in strict mode with additional
* validation for resolver configuration correctness. Defaults to false.
*
* @return {AwilixContainer<T>} The container.
*/
export declare function createContainer<T extends object = any, U extends object = any>(options?: ContainerOptions, parentContainer?: AwilixContainer<U>): AwilixContainer<T>;
export declare function createContainer<T extends object = any>(options?: ContainerOptions): AwilixContainer<T>;

@@ -5,10 +5,10 @@ "use strict";

const util = require("util");
const errors_1 = require("./errors");
const injection_mode_1 = require("./injection-mode");
const lifetime_1 = require("./lifetime");
const list_modules_1 = require("./list-modules");
const load_module_native_js_1 = require("./load-module-native.js");
const load_modules_1 = require("./load-modules");
const resolvers_1 = require("./resolvers");
const utils_1 = require("./utils");
const injection_mode_1 = require("./injection-mode");
const lifetime_1 = require("./lifetime");
const errors_1 = require("./errors");
const load_module_native_js_1 = require("./load-module-native.js");
/**

@@ -29,18 +29,23 @@ * Family tree symbol.

*
* @param {Function} options.require
* The require function to use. Defaults to require.
* @param {Function} options.require The require function to use. Defaults to require.
*
* @param {string} options.injectionMode
* The mode used by the container to resolve dependencies. Defaults to 'Proxy'.
* @param {string} options.injectionMode The mode used by the container to resolve dependencies.
* Defaults to 'Proxy'.
*
* @return {AwilixContainer<T>}
* The container.
* @param {boolean} options.strict True if the container should run in strict mode with additional
* validation for resolver configuration correctness. Defaults to false.
*
* @return {AwilixContainer<T>} The container.
*/
function createContainer(options, parentContainer) {
options = Object.assign({ injectionMode: injection_mode_1.InjectionMode.PROXY }, options);
// The resolution stack is used to keep track
// of what modules are being resolved, so when
// an error occurs, we have something to present
// to the poor developer who fucked up.
let resolutionStack = [];
function createContainer(options = {}) {
return createContainerInternal(options);
}
exports.createContainer = createContainer;
function createContainerInternal(options, parentContainer, parentResolutionStack) {
options = Object.assign({ injectionMode: injection_mode_1.InjectionMode.PROXY, strict: false }, options);
/**
* Tracks the names and lifetimes of the modules being resolved. Used to detect circular
* dependencies and, in strict mode, lifetime leakage issues.
*/
const resolutionStack = parentResolutionStack !== null && parentResolutionStack !== void 0 ? parentResolutionStack : [];
// Internal registration store for this container.

@@ -166,3 +171,3 @@ const registrations = {};

function createScope() {
return createContainer(options, container);
return createContainerInternal(options, container, resolutionStack);
}

@@ -176,4 +181,11 @@ /**

for (const key of keys) {
const value = obj[key];
registrations[key] = value;
const resolver = obj[key];
// If strict mode is enabled, check to ensure we are not registering a singleton on a non-root
// container.
if (options.strict && resolver.lifetime === lifetime_1.Lifetime.SINGLETON) {
if (parentContainer) {
throw new errors_1.AwilixRegistrationError(key, 'Cannot register a singleton on a scoped container.');
}
}
registrations[key] = resolver;
}

@@ -222,3 +234,3 @@ return container;

const resolver = getRegistration(name);
if (resolutionStack.indexOf(name) > -1) {
if (resolutionStack.some(({ name: parentName }) => parentName === name)) {
throw new errors_1.AwilixResolutionError(name, resolutionStack, 'Cyclic dependencies detected.');

@@ -259,8 +271,17 @@ }

}
// Pushes the currently-resolving module name onto the stack
resolutionStack.push(name);
const lifetime = resolver.lifetime || lifetime_1.Lifetime.TRANSIENT;
// if we are running in strict mode, this resolver is not explicitly marked leak-safe, and any
// of the parents have a shorter lifetime than the one requested, throw an error.
if (options.strict && !resolver.isLeakSafe) {
const maybeLongerLifetimeParentIndex = resolutionStack.findIndex(({ lifetime: parentLifetime }) => (0, lifetime_1.isLifetimeLonger)(parentLifetime, lifetime));
if (maybeLongerLifetimeParentIndex > -1) {
throw new errors_1.AwilixResolutionError(name, resolutionStack, `Dependency '${name.toString()}' has a shorter lifetime than its ancestor: '${resolutionStack[maybeLongerLifetimeParentIndex].name.toString()}'`);
}
}
// Pushes the currently-resolving module information onto the stack
resolutionStack.push({ name, lifetime });
// Do the thing
let cached;
let resolved;
switch (resolver.lifetime || lifetime_1.Lifetime.TRANSIENT) {
switch (lifetime) {
case lifetime_1.Lifetime.TRANSIENT:

@@ -274,3 +295,5 @@ // Transient lifetime means resolve every time.

if (!cached) {
resolved = resolver.resolve(container);
// if we are running in strict mode, perform singleton resolution using the root
// container only.
resolved = resolver.resolve(options.strict ? rootContainer : container);
rootContainer.cache.set(name, { resolver, value: resolved });

@@ -285,4 +308,5 @@ }

// that resolves the registration also caches it.
// When a registration is not found, we travel up
// the family tree until we find one that is cached.
// If this container cache does not have it,
// resolve and cache it rather than using the parent
// container's cache.
cached = container.cache.get(name);

@@ -306,4 +330,5 @@ if (cached !== undefined) {

catch (err) {
// When we get an error we need to reset the stack.
resolutionStack = [];
// When we get an error we need to reset the stack. Mutate the existing array rather than
// updating the reference to ensure all parent containers' stacks are also updated.
resolutionStack.length = 0;
throw err;

@@ -329,3 +354,3 @@ }

*
* @param {Resolver|Class|Function} targetOrResolver
* @param {Resolver|Constructor|Function} targetOrResolver
* @param {ResolverOptions} opts

@@ -390,3 +415,2 @@ */

}
exports.createContainer = createContainer;
//# sourceMappingURL=container.js.map

@@ -77,1 +77,14 @@ import { ResolutionStack } from './container';

}
/**
* A nice error class so we can do an instanceOf check.
*/
export declare class AwilixRegistrationError extends AwilixError {
/**
* Constructor, takes the registered modules and unresolved tokens
* to create a message.
*
* @param {string|symbol} name
* The name of the module that could not be registered.
*/
constructor(name: string | symbol, message?: string);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AwilixResolutionError = exports.AwilixTypeError = exports.AwilixError = exports.ExtendableError = void 0;
exports.AwilixRegistrationError = exports.AwilixResolutionError = exports.AwilixTypeError = exports.AwilixError = exports.ExtendableError = void 0;
/**

@@ -116,9 +116,7 @@ * Newline.

constructor(name, resolutionStack, message) {
if (typeof name === 'symbol') {
name = name.toString();
}
resolutionStack = resolutionStack.map((val) => typeof val === 'symbol' ? val.toString() : val);
resolutionStack.push(name);
const resolutionPathString = resolutionStack.join(' -> ');
let msg = `Could not resolve '${name}'.`;
const stringName = name.toString();
const nameStack = resolutionStack.map(({ name: val }) => val.toString());
nameStack.push(stringName);
const resolutionPathString = nameStack.join(' -> ');
let msg = `Could not resolve '${stringName}'.`;
if (message) {

@@ -133,2 +131,23 @@ msg += ` ${message}`;

exports.AwilixResolutionError = AwilixResolutionError;
/**
* A nice error class so we can do an instanceOf check.
*/
class AwilixRegistrationError extends AwilixError {
/**
* Constructor, takes the registered modules and unresolved tokens
* to create a message.
*
* @param {string|symbol} name
* The name of the module that could not be registered.
*/
constructor(name, message) {
const stringName = name.toString();
let msg = `Could not register '${stringName}'.`;
if (message) {
msg += ` ${message}`;
}
super(msg);
}
}
exports.AwilixRegistrationError = AwilixRegistrationError;
//# sourceMappingURL=errors.js.map

@@ -9,1 +9,5 @@ /**

export declare const Lifetime: Record<LifetimeType, LifetimeType>;
/**
* Returns true if and only if the first lifetime is strictly longer than the second.
*/
export declare function isLifetimeLonger(a: LifetimeType, b: LifetimeType): boolean;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lifetime = void 0;
exports.isLifetimeLonger = exports.Lifetime = void 0;
/**

@@ -24,2 +24,10 @@ * Lifetime types.

};
/**
* Returns true if and only if the first lifetime is strictly longer than the second.
*/
function isLifetimeLonger(a, b) {
return ((a === exports.Lifetime.SINGLETON && b !== exports.Lifetime.SINGLETON) ||
(a === exports.Lifetime.SCOPED && b === exports.Lifetime.TRANSIENT));
}
exports.isLifetimeLonger = isLifetimeLonger;
//# sourceMappingURL=lifetime.js.map

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

import { ModuleDescriptor, GlobWithOptions, listModules } from './list-modules';
import { AwilixContainer } from './container';
import { GlobWithOptions, ModuleDescriptor, listModules } from './list-modules';
import { BuildResolverOptions } from './resolvers';
import { AwilixContainer } from './container';
/**

@@ -5,0 +5,0 @@ * Metadata of the module as well as the loaded module itself.

@@ -13,2 +13,3 @@ "use strict";

exports.loadModules = void 0;
const camel_case_1 = require("camel-case");
const url_1 = require("url");

@@ -18,3 +19,2 @@ const lifetime_1 = require("./lifetime");

const utils_1 = require("./utils");
const camel_case_1 = require("camel-case");
const nameFormatters = {

@@ -21,0 +21,0 @@ camelCase: (s) => (0, camel_case_1.camelCase)(s),

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

import { AwilixContainer, FunctionReturning } from './container';
import { InjectionModeType } from './injection-mode';
import { LifetimeType } from './lifetime';
import { InjectionModeType } from './injection-mode';
import { AwilixContainer, FunctionReturning } from './container';
/**

@@ -71,2 +71,7 @@ * RESOLVER symbol can be used by modules loaded by

register?: (...args: any[]) => Resolver<T>;
/**
* True if this resolver should be excluded from lifetime leak checking. Used by resolvers that
* wish to uphold the anti-leakage contract themselves. Defaults to false.
*/
isLeakSafe?: boolean;
}

@@ -98,12 +103,11 @@ /**

/**
* Creates a simple value resolver where the given value will always be resolved.
* Creates a simple value resolver where the given value will always be resolved. The value is
* marked as leak-safe since in strict mode, the value will only be resolved when it is not leaking
* upwards from a child scope to a parent singleton.
*
* @param {string} name
* The name to register the value as.
* @param {string} name The name to register the value as.
*
* @param {*} value
* The value to resolve.
* @param {*} value The value to resolve.
*
* @return {object}
* The resolver.
* @return {object} The resolver.
*/

@@ -145,21 +149,5 @@ export declare function asValue<T>(value: T): Resolver<T>;

/**
* Resolves to the specified registration.
* Resolves to the specified registration. Marked as leak-safe since the alias target is what should
* be checked for lifetime leaks.
*/
export declare function aliasTo<T>(name: Parameters<AwilixContainer['resolve']>[0]): Resolver<T>;
/**
* Given an options object, creates a fluid interface
* to manage it.
*
* @param {*} obj
* The object to return.
*
* @return {object}
* The interface.
*/
export declare function createBuildResolver<T, B extends Resolver<T>>(obj: B): BuildResolver<T> & B;
/**
* Given a resolver, returns an object with methods to manage the disposer
* function.
* @param obj
*/
export declare function createDisposableResolver<T, B extends Resolver<T>>(obj: B): DisposableResolver<T> & B;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDisposableResolver = exports.createBuildResolver = exports.aliasTo = exports.asClass = exports.asFunction = exports.asValue = exports.RESOLVER = void 0;
exports.aliasTo = exports.asClass = exports.asFunction = exports.asValue = exports.RESOLVER = void 0;
const errors_1 = require("./errors");
const injection_mode_1 = require("./injection-mode");
const lifetime_1 = require("./lifetime");
const injection_mode_1 = require("./injection-mode");
const param_parser_1 = require("./param-parser");
const utils_1 = require("./utils");
const param_parser_1 = require("./param-parser");
const errors_1 = require("./errors");
// We parse the signature of any `Function`, so we want to allow `Function` types.

@@ -17,12 +17,11 @@ /* eslint-disable @typescript-eslint/ban-types */

/**
* Creates a simple value resolver where the given value will always be resolved.
* Creates a simple value resolver where the given value will always be resolved. The value is
* marked as leak-safe since in strict mode, the value will only be resolved when it is not leaking
* upwards from a child scope to a parent singleton.
*
* @param {string} name
* The name to register the value as.
* @param {string} name The name to register the value as.
*
* @param {*} value
* The value to resolve.
* @param {*} value The value to resolve.
*
* @return {object}
* The resolver.
* @return {object} The resolver.
*/

@@ -32,2 +31,3 @@ function asValue(value) {

resolve: () => value,
isLeakSafe: true,
};

@@ -97,3 +97,4 @@ }

/**
* Resolves to the specified registration.
* Resolves to the specified registration. Marked as leak-safe since the alias target is what should
* be checked for lifetime leaks.
*/

@@ -105,2 +106,3 @@ function aliasTo(name) {

},
isLeakSafe: true,
};

@@ -140,3 +142,2 @@ }

}
exports.createBuildResolver = createBuildResolver;
/**

@@ -155,3 +156,2 @@ * Given a resolver, returns an object with methods to manage the disposer

}
exports.createDisposableResolver = createDisposableResolver;
/**

@@ -158,0 +158,0 @@ * Partially apply arguments to the given function.

{
"name": "awilix",
"version": "9.0.0",
"version": "10.0.0",
"description": "Extremely powerful dependency injection container.",

@@ -52,17 +52,17 @@ "main": "lib/awilix.js",

"devDependencies": {
"@babel/core": "^7.23.2",
"@babel/plugin-transform-runtime": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"@babel/runtime": "^7.23.2",
"@types/jest": "^29.5.5",
"@types/node": "^20.8.4",
"@typescript-eslint/eslint-plugin": "^6.7.5",
"@typescript-eslint/parser": "^6.7.5",
"@babel/core": "^7.23.7",
"@babel/plugin-transform-runtime": "^7.23.7",
"@babel/preset-env": "^7.23.7",
"@babel/runtime": "^7.23.7",
"@types/jest": "^29.5.11",
"@types/node": "^20.10.7",
"@typescript-eslint/eslint-plugin": "^6.18.0",
"@typescript-eslint/parser": "^6.18.0",
"babel-jest": "^29.7.0",
"eslint": "^8.51.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"husky": "^8.0.3",
"istanbul": "^0.4.5",
"jest": "^29.7.0",
"lint-staged": "^13.2.0",
"prettier": "^3.0.3",
"prettier": "^3.1.1",
"rimraf": "^5.0.5",

@@ -78,7 +78,7 @@ "rollup": "^3.20.2",

"tslib": "^2.6.2",
"typescript": "^5.2.2"
"typescript": "^5.3.3"
},
"dependencies": {
"camel-case": "^4.1.2",
"fast-glob": "^3.3.1"
"fast-glob": "^3.3.2"
},

@@ -127,3 +127,4 @@ "lint-staged": {

"lib",
"src/load-module-native.js"
"src/load-module-native.js",
"src/awilix.ts"
],

@@ -130,0 +131,0 @@ "moduleFileExtensions": [

@@ -12,3 +12,3 @@ # Awilix

Extremely powerful, performant, & battle-tested **Dependency Injection** (DI) container for JavaScript/Node,
written in [TypeScript](http://typescriptlang.org).
written in [TypeScript](http://typescriptlang.org).

@@ -28,2 +28,3 @@ Awilix enables you to write **composable, testable software** using dependency injection **without special annotations**, which in turn decouples your core application code from the intricacies of the DI mechanism.

- [Scoped lifetime](#scoped-lifetime)
- [Strict mode](#strict-mode)
- [Injection modes](#injection-modes)

@@ -44,2 +45,3 @@ - [Auto-loading modules](#auto-loading-modules)

- [`AwilixResolutionError`](#awilixresolutionerror)
- [`AwilixRegistrationError`](#awilixregistrationerror)
- [The `AwilixContainer` object](#the-awilixcontainer-object)

@@ -80,5 +82,5 @@ - [`container.cradle`](#containercradle)

```html
<script src="https://unpkg.com/awilix/lib/awilix.umd.js"/>
<script src="https://unpkg.com/awilix/lib/awilix.umd.js" />
<script>
const container = Awilix.createContainer()
const container = Awilix.createContainer()
</script>

@@ -102,4 +104,6 @@ ```

// Create the container and set the injectionMode to PROXY (which is also the default).
// Enable strict mode for extra correctness checks (highly recommended).
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY
injectionMode: awilix.InjectionMode.PROXY,
strict: true,
})

@@ -126,3 +130,3 @@

// userController: by instantiating a class.
userController: awilix.asClass(UserController)
userController: awilix.asClass(UserController),
})

@@ -135,5 +139,5 @@

return {
getUser: id => {
getUser: (id) => {
return db.query(`select * from users where id=${id}`)
}
},
}

@@ -145,3 +149,3 @@ }

// invoking the function.
userService: awilix.asFunction(makeUserService)
userService: awilix.asFunction(makeUserService),
})

@@ -160,3 +164,3 @@

Database.prototype.query = function(sql) {
Database.prototype.query = function (sql) {
// blah....

@@ -171,3 +175,3 @@ return this.conn.rawSql(sql)

container.register({
db: awilix.asClass(Database).classic()
db: awilix.asClass(Database).classic(),
})

@@ -182,3 +186,3 @@

connectionString: awilix.asValue(process.env.CONN_STR),
timeout: awilix.asValue(1000)
timeout: awilix.asValue(1000),
})

@@ -233,3 +237,3 @@

container.register({
mailService: asClass(MailService, { lifetime: Lifetime.SINGLETON })
mailService: asClass(MailService, { lifetime: Lifetime.SINGLETON }),
})

@@ -239,3 +243,3 @@

container.register({
mailService: asClass(MailService).setLifetime(Lifetime.SINGLETON)
mailService: asClass(MailService).setLifetime(Lifetime.SINGLETON),
})

@@ -245,3 +249,3 @@

container.register({
mailService: asClass(MailService).singleton()
mailService: asClass(MailService).singleton(),
})

@@ -277,3 +281,3 @@

container.register({
messageService: asClass(MessageService).scoped()
messageService: asClass(MessageService).scoped(),
})

@@ -288,3 +292,3 @@

req.scope.register({
currentUser: asValue(req.user)
currentUser: asValue(req.user),
})

@@ -298,3 +302,3 @@

const messageService = req.scope.resolve('messageService')
messageService.getMessages().then(messages => {
messageService.getMessages().then((messages) => {
res.send(200, messages)

@@ -309,8 +313,16 @@ })

**IMPORTANT!** If a singleton is resolved, and it depends on a scoped or
transient registration, those will remain in the singleton for it's lifetime!
transient registration, those will remain in the singleton for its lifetime!
Similarly, if a scoped module is resolved, and it depends on a transient
registration, that remains in the scoped module for its lifetime.
In the example above, if `messageService` was a singleton, it would be cached
in the root container, and would always have the `currentUser` from the first
request. Modules should generally not have a longer lifetime than their
dependencies, as this can cause issues of stale data.
```js
const makePrintTime = ({ time }) => () => {
console.log('Time:', time)
}
const makePrintTime =
({ time }) =>
() => {
console.log('Time:', time)
}

@@ -321,3 +333,3 @@ const getTime = () => new Date().toString()

printTime: asFunction(makePrintTime).singleton(),
time: asFunction(getTime).transient()
time: asFunction(getTime).transient(),
})

@@ -337,5 +349,30 @@

If you want a mismatched configuration like this to error, set
`strict` in the container options. This will trigger
the following error at runtime when the singleton `printTime` is resolved:
`AwilixResolutionError: Could not resolve 'time'. Dependency 'time' has a shorter lifetime than its ancestor: 'printTime'`
In addition, registering a singleton on a scope other than the root container results in
unpredictable behavior. In particular, if two different singletons are registered on two different
scopes, they will share a cache entry and collide with each other. To throw a runtime error when a
singleton is registered on a scope other than the root container, enable [strict mode](#strict-mode).
Read the documentation for [`container.createScope()`](#containercreatescope)
for more examples.
# Strict mode
Strict mode is a new feature in Awilix 10. It enables additional correctness checks that can help
you catch bugs early.
In particular, strict mode enables the following checks:
- When a singleton or scoped registration depends on a transient non-value registration, an error is
thrown. This detects and prevents the issue where a shorter lifetime dependency can leak outside
its intended lifetime due to its preservation in a longer lifetime module.
- Singleton registrations on any scopes are disabled. This prevents the issue where a singleton is
registered on a scope other than the root container, which results in unpredictable behavior.
- Singleton resolution is performed using registrations from the root container only, which prevents
potential leaks in which scoped registrations are preserved in singletons.
# Injection modes

@@ -374,7 +411,7 @@

- `InjectionMode.CLASSIC`: Parses the function/constructor parameters, and
matches them with registrations in the container. `CLASSIC` mode has a
slightly higher initialization cost as it has to parse the function/class
to figure out the dependencies at the time of registration, however resolving
them will be **much faster** than when using `PROXY`. _Don't use `CLASSIC` if
you minify your code!_ We recommend using `CLASSIC` in Node and `PROXY` in
matches them with registrations in the container. `CLASSIC` mode has a
slightly higher initialization cost as it has to parse the function/class
to figure out the dependencies at the time of registration, however resolving
them will be **much faster** than when using `PROXY`. _Don't use `CLASSIC` if
you minify your code!_ We recommend using `CLASSIC` in Node and `PROXY` in
environments where minification is needed.

@@ -447,4 +484,4 @@

resolverOptions: {
injectionMode: InjectionMode.CLASSIC
}
injectionMode: InjectionMode.CLASSIC,
},
})

@@ -489,3 +526,3 @@ ```

timeout: 4000,
connectionString: 'localhost:1337;user=123...'
connectionString: 'localhost:1337;user=123...',
})

@@ -547,31 +584,34 @@ ```

// Load our modules!
container.loadModules([
// Globs!
container.loadModules(
[
// To have different resolverOptions for specific modules.
'models/**/*.js',
{
register: awilix.asValue,
lifetime: Lifetime.SINGLETON
}
// Globs!
[
// To have different resolverOptions for specific modules.
'models/**/*.js',
{
register: awilix.asValue,
lifetime: Lifetime.SINGLETON,
},
],
'services/**/*.js',
'repositories/**/*.js',
],
'services/**/*.js',
'repositories/**/*.js'
], {
// We want to register `UserService` as `userService` -
// by default loaded modules are registered with the
// name of the file (minus the extension)
formatName: 'camelCase',
// Apply resolver options to all modules.
resolverOptions: {
// We can give these auto-loaded modules
// the deal of a lifetime! (see what I did there?)
// By default it's `TRANSIENT`.
lifetime: Lifetime.SINGLETON,
// We can tell Awilix what to register everything as,
// instead of guessing. If omitted, will inspect the
// module to determine what to register as.
register: awilix.asClass
}
})
{
// We want to register `UserService` as `userService` -
// by default loaded modules are registered with the
// name of the file (minus the extension)
formatName: 'camelCase',
// Apply resolver options to all modules.
resolverOptions: {
// We can give these auto-loaded modules
// the deal of a lifetime! (see what I did there?)
// By default it's `TRANSIENT`.
lifetime: Lifetime.SINGLETON,
// We can tell Awilix what to register everything as,
// instead of guessing. If omitted, will inspect the
// module to determine what to register as.
register: awilix.asClass,
},
},
)

@@ -602,6 +642,6 @@ // We are now ready! We now have a userService, userRepository and emailService!

Promise.delay(timeout).then(() =>
Promise.reject(new Error('Timed out'))
)
Promise.reject(new Error('Timed out')),
),
])
}
},
}

@@ -625,3 +665,3 @@ }

// it is attached to.
.inject(() => ({ timeout: 2000 }))
.inject(() => ({ timeout: 2000 })),
})

@@ -632,4 +672,4 @@

userRepository: asFunction(createUserRepository, {
injector: () => ({ timeout: 2000 })
})
injector: () => ({ timeout: 2000 }),
}),
})

@@ -641,4 +681,4 @@

asFunction(createUserRepository, {
injector: () => ({ timeout: 2000 })
})
injector: () => ({ timeout: 2000 }),
}),
)

@@ -676,3 +716,3 @@

lifetime: Lifetime.SCOPED,
injectionMode: InjectionMode.CLASSIC
injectionMode: InjectionMode.CLASSIC,
}

@@ -688,3 +728,3 @@ ```

const container = createContainer().register({
awesomeService: asClass(AwesomeService)
awesomeService: asClass(AwesomeService),
})

@@ -753,3 +793,3 @@

// If it returns a Promise, it will be awaited by `dispose`.
.disposer(pool => pool.end())
.disposer((pool) => pool.end()),
})

@@ -830,2 +870,4 @@ }

module explicitly
- `isLeakSafe`: true if this resolver should be excluded from lifetime-leak checking performed in
[strict mode](#strict-mode). Defaults to false.

@@ -836,3 +878,3 @@ **Examples of usage:**

container.register({
stuff: asClass(MyClass, { injectionMode: InjectionMode.CLASSIC })
stuff: asClass(MyClass, { injectionMode: InjectionMode.CLASSIC }),
})

@@ -842,4 +884,4 @@

resolverOptions: {
lifetime: Lifetime.SCOPED
}
lifetime: Lifetime.SCOPED,
},
})

@@ -867,2 +909,3 @@ ```

class constructor as `repo`.
- `options.strict`: Enables [strict mode](#strict-mode). Defaults to `false`.

@@ -907,3 +950,3 @@ ## `asFunction()`

val: asValue(123),
aliasVal: aliasTo('val')
aliasVal: aliasTo('val'),
})

@@ -952,2 +995,7 @@

## `AwilixRegistrationError`
This is a special error thrown when Awilix is unable to register a dependency due to a strict mode
violation. You can catch this error and use `err instanceof AwilixRegistrationError` if you wish.
## The `AwilixContainer` object

@@ -982,3 +1030,3 @@

container.register({
count: asFunction(() => counter++).singleton()
count: asFunction(() => counter++).singleton(),
})

@@ -999,3 +1047,3 @@

const container = createContainer({
injectionMode: InjectionMode.CLASSIC
injectionMode: InjectionMode.CLASSIC,
})

@@ -1016,3 +1064,3 @@

container.register({
leet: asFunction(() => 1337)
leet: asFunction(() => 1337),
})

@@ -1065,3 +1113,3 @@

mailService: asFunction(makeMailService, { lifetime: Lifetime.SINGLETON }),
context: asClass(SessionContext, { lifetime: Lifetime.SCOPED })
context: asClass(SessionContext, { lifetime: Lifetime.SCOPED }),
})

@@ -1073,3 +1121,3 @@

'mailService',
asFunction(makeMailService).setLifetime(Lifetime.SINGLETON)
asFunction(makeMailService).setLifetime(Lifetime.SINGLETON),
)

@@ -1115,5 +1163,5 @@ // .. is the same as this:

the lifetime, injection mode and more of the loaded modules.
- `opts.esModules`: Loads modules using Node's native ES modules.
**This makes `container.loadModules` asynchronous, and will therefore return a `Promise`!**
This is only supported on Node 14.0+ and should only be used if you're using
- `opts.esModules`: Loads modules using Node's native ES modules.
**This makes `container.loadModules` asynchronous, and will therefore return a `Promise`!**
This is only supported on Node 14.0+ and should only be used if you're using
the [Native Node ES modules](https://nodejs.org/api/esm.html)

@@ -1195,3 +1243,3 @@

container.register({
counterValue: asFunction(() => counter++).scoped()
counterValue: asFunction(() => counter++).scoped(),
})

@@ -1216,3 +1264,3 @@ const scope1 = container.createScope()

container.register({
counterValue: asFunction(() => counter++).scoped()
counterValue: asFunction(() => counter++).scoped(),
})

@@ -1243,3 +1291,3 @@ const scope1 = container.createScope()

container.register({
scopedValue: asFunction(cradle => 'Hello ' + cradle.someValue)
scopedValue: asFunction((cradle) => 'Hello ' + cradle.someValue),
})

@@ -1250,3 +1298,3 @@

scope.register({
someValue: asValue('scope')
someValue: asValue('scope'),
})

@@ -1261,3 +1309,5 @@

Things registered in the scope take precedence over it's parent.
Things registered in the scope take precedence over registrations in the parent scope(s). This
applies to both the registration directly requested from the scope container, and any dependencies
that the registration uses.

@@ -1267,3 +1317,3 @@ ```js

// it will still have anything that is registered
// in it's parent.
// in its parent.
const scope = container.createScope()

@@ -1273,13 +1323,20 @@

value: asValue('root'),
usedValue: asFunction(cradle => cradle.value)
usedValue: asFunction((cradle) => `hello from ${cradle.value}`),
})
scope.register({
value: asValue('scope')
value: asValue('scope'),
})
container.cradle.usedValue === 'root'
scope.cradle.usedValue === 'scope'
container.cradle.value === 'root'
scope.cradle.value === 'scope'
container.cradle.usedValue === 'hello from root'
scope.cradle.usedValue === 'hello from scope'
```
Registering singletons in a scope results in unpredictable behavior and should be avoided. Having
more than one singleton with the same name in different scopes will result in them sharing a cache
entry and colliding with each other. To disallow such registrations, enable
[strict mode](#strict-mode) in the container options.
### `container.build()`

@@ -1319,7 +1376,7 @@

const createMyFunc = ({ ping }) => ({
pong: () => ping
pong: () => ping,
})
container.register({
ping: asValue('pong')
ping: asValue('pong'),
})

@@ -1358,5 +1415,5 @@

pool: asFunction(() => new pg.Pool())
.disposer(pool => pool.end())
.disposer((pool) => pool.end())
// IMPORTANT! Must be either singleton or scoped!
.singleton()
.singleton(),
})

@@ -1403,7 +1460,7 @@

* [`awilix-manager`](https://github.com/kibertoad/awilix-manager): Wrapper that allows eager injection, asynchronous init methods and dependency lookup by tags.
* [`awilix-express`](https://github.com/jeffijoe/awilix-express): Bindings for the Express HTTP library.
* [`awilix-koa`](https://github.com/jeffijoe/awilix-koa): Bindings for the Koa HTTP library.
* [`awilix-router-core`](https://github.com/jeffijoe/awilix-router-core): Library for building HTTP bindings for Awilix with routing.
* [`fastify-awilix`](https://github.com/fastify/fastify-awilix): Bindings for the Fastify framework.
- [`awilix-manager`](https://github.com/kibertoad/awilix-manager): Wrapper that allows eager injection, asynchronous init methods and dependency lookup by tags.
- [`awilix-express`](https://github.com/jeffijoe/awilix-express): Bindings for the Express HTTP library.
- [`awilix-koa`](https://github.com/jeffijoe/awilix-koa): Bindings for the Koa HTTP library.
- [`awilix-router-core`](https://github.com/jeffijoe/awilix-router-core): Library for building HTTP bindings for Awilix with routing.
- [`fastify-awilix`](https://github.com/fastify/fastify-awilix): Bindings for the Fastify framework.

@@ -1410,0 +1467,0 @@ # Contributing

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc