Socket
Socket
Sign inDemoInstall

awilix

Package Overview
Dependencies
15
Maintainers
1
Versions
81
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 3.0.0-rc.6 to 3.0.0-rc.7

197

CHANGELOG.md
# Awilix Changelog
# v3.0.0
A lot of cool stuff has made it into version 3, and a few things were broken in
the process. I have done my best to list everything here.
## ✨ New Features
With v3 comes a few new cool features.
### Disposer support ([#48](https://github.com/jeffijoe/awilix/issues/48))
This has been a very requested feature. The idea is you can tell Awilix how to
dispose of a dependency—for example, to close a database connection—when calling
`container.dispose()`.
```js
const pg = require('pg')
const { createContainer, asFunction } = require('awilix')
const container = createContainer()
.register({
pool: (
asFunction(() => new pg.Pool({ ... }))
.singleton()
.disposer((pool) => pool.end())
)
})
// .. later, but only if a `pool` was ever created
container.dispose().then(() => {
console.log('One disposable connection.. disposed! Huehehehe')
})
```
### `alias` resolver ([#55](https://github.com/jeffijoe/awilix/issues/55))
This new resolver lets you alias a registration. This is best illustrated with
an example:
```js
const { alias, asValue, createContainer } = require('awilix')
const container = createContainer()
container.register({
laughingOutLoud: asValue('hahahahaha'),
lol: alias('laughingOutLoud')
})
container.resolve('lol') // 'hahahahaha'
```
It's essentially the exact same as calling
`container.resolve('laughingOutLoad')`, but `lol` might be easier to type out in
your constructors. 😎
### Default values in constructors/functions ([#46](https://github.com/jeffijoe/awilix/issues/46))
This is a pretty _small_ feature but was the most difficult to land, mainly
because I had to write a smarter
[parser](https://github.com/jeffijoe/awilix/tree/master/src/param-parser.ts) and
[tokenizer](https://github.com/jeffijoe/awilix/tree/master/src/function-tokenizer.ts),
not to mention they are now way better at skipping over code. Check out
[the tests](https://github.com/jeffijoe/awilix/tree/master/src/__tests__/param-parser.test.ts#L149),
it's pretty wild.
```js
class MyClass {
constructor(db, timeout = 1000) { /*...*/ }
}
container.register({
db: asFunction(..)
})
// Look! No errors!! :D
container.build(MyClass) instanceof MyClass // true
```
### Official support for running in the browser ([#69](https://github.com/jeffijoe/awilix/issues/69))
Awilix now ships with 4 module flavors: CommonJS (same old), ES Modules for
Node, ES Modules for the Browser and UMD.
Please see the
[Universal Module](https://github.com/jeffijoe/awilix#universal-module-browser-support)
section in the readme for details.
## 🚨 Known breaking changes
The following is a list of known breaking changes. If there's any I've missed
feel free to let me know.
### The entire library is now written in TypeScript! ([#49](https://github.com/jeffijoe/awilix/issues/49))
This means a bunch of interfaces have been renamed and made more correct. If
you're a TypeScript user, this is great news for you. 😄
### `ResolutionMode` is now `InjectionMode` ([#57](https://github.com/jeffijoe/awilix/issues/57))
* `ResolutionMode.js` renamed to `injection-mode.ts`
* `ResolutionMode` renamed to `InjectionMode`
### "Registrations" are now "Resolvers" ([#51](https://github.com/jeffijoe/awilix/issues/51))
The terminology is now "you _register_ a **resolver** to a **name**".
* TypeScript interfaces renamed
* `REGISTRATION` symbol renamed to `RESOLVER`
* `registrations.js` renamed to `resolvers.ts`
* `registrationOptions` in `loadModules` renamed to `resolverOptions`
### `registerClass`, `registerFunction` and `registerValue` removed ([#60](https://github.com/jeffijoe/awilix/issues/60))
This was done to simplify the API surface, and also simplifies the
implementation greatly (less overloads). You should be using
`container.register` with `asClass`, `asFunction` and `asValue` instead.
### Resolver configuration chaining API is now immutable ([#62](https://github.com/jeffijoe/awilix/issues/62))
This simplifies the TypeScript types and is also considered a good practice. All
configuration functions rely on `this`, meaning you **should not do**:
```js
// I don't know why you would, but DONT DO THIS!
const singleton = asClass(MyClass).singleton
singleton()
```
However, this also means you can now "split" a resolver to configure it
differently. For example:
```js
class GenericSender {
constructor(transport) {
this.transport = transport
}
send() {
if (this.transport === 'email') {
// ... etc
}
}
dispose() { /*...*/ }
}
const base = asClass(GenericSender).scoped().disposer((g) => g.dispose())
const emailSender = base.inject(() => ({ transport: 'email' })
const pushSender = base.inject(() => ({ transport: 'push' })
container.register({
emailSender,
pushSender
})
```
### Removed `AwilixNotAFunctionError` in favor of a generic `AwilixTypeError` ([#52](https://github.com/jeffijoe/awilix/issues/52))
This _should_ not have an impact on userland code but I thought I'd mention it.
There are a bunch of internal uses of this error, so I thought it made sense to
consolidate them into one error type.
## 👀 Other cool changes
* Code is now formatted with Prettier
* Awilix is now using `husky` + `lint-staged` to lint, format and test every
commit to ensure top code quality.
* Switched to Jest from Mocha
* Switched from eslint to tslint
* Rewrote the function parameter parser, it is now much better at correctly
skipping over default value expressions to reach the next parameter.
* Most (if not all) of the code is now documented and should be readable.
---
## 2.12.0

@@ -68,6 +244,6 @@

* **[BREAKING]**: Custom `isClass` function that will treat `function Capital ()
{}` as a class due to the capital first letter of the function name. This is
to improve compatibility with Babel's ES5 code generator, and is also a pretty
commonly accepted standard naming convention.
* **[BREAKING]**: Custom `isClass` function that will treat
`function Capital () {}` as a class due to the capital first letter of the
function name. This is to improve compatibility with Babel's ES5 code
generator, and is also a pretty commonly accepted standard naming convention.
([#28](https://github.com/jeffijoe/awilix/issues/28))

@@ -98,7 +274,7 @@ * **[NEW]**: Added support for passing in a `register` function to

([#24](https://github.com/jeffijoe/awilix/issues/24)).
* Fixed issue where passing a `Lifetime` like `.registerFunction('name', func,
Lifetime.SCOPED)` didn't work.
* Fixed issue where passing a `Lifetime` like
`.registerFunction('name', func, Lifetime.SCOPED)` didn't work.
* Documented `asClass`, `asValue` and `asFunction`.
* **[FIXED]**: nasty options leaking when using `registerClass/Function({ test1:
[Test1, { }], test2: [Test2, { }] })`.
* **[FIXED]**: nasty options leaking when using
`registerClass/Function({ test1: [Test1, { }], test2: [Test2, { }] })`.

@@ -124,4 +300,5 @@ ## 2.4.0

the sense that it solves the unexpected behavior, but it breaks existing
registrations that would register arrays by using `registerValue({ name: [[1,
2]] })` (multi-dimensional array to work around the pre-2.3.0 behavior)**
registrations that would register arrays by using
`registerValue({ name: [[1, 2]] })` (multi-dimensional array to work around
the pre-2.3.0 behavior)**
* [chore]: Updated packages.

@@ -128,0 +305,0 @@

487

lib/awilix.browser.js

@@ -0,5 +1,77 @@

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
/**
* Newline.
*/
const EOL = '\n';
var EOL = '\n';
/**

@@ -9,3 +81,4 @@ * An extendable error class.

*/
class ExtendableError extends Error {
var ExtendableError = /** @class */ (function (_super) {
__extends(ExtendableError, _super);
/**

@@ -17,21 +90,28 @@ * Constructor for the error.

*/
constructor(message) {
super(message);
function ExtendableError(message) {
var _this = _super.call(this, message) || this;
// extending Error is weird and does not propagate `message`
Object.defineProperty(this, 'message', {
Object.defineProperty(_this, 'message', {
enumerable: false,
value: message
});
Object.defineProperty(this, 'name', {
Object.defineProperty(_this, 'name', {
enumerable: false,
value: this.constructor.name
value: _this.constructor.name
});
Error.captureStackTrace(this, this.constructor);
Error.captureStackTrace(_this, _this.constructor);
return _this;
}
}
return ExtendableError;
}(Error));
/**
* Base error for all Awilix-specific errors.
*/
class AwilixError extends ExtendableError {
}
var AwilixError = /** @class */ (function (_super) {
__extends(AwilixError, _super);
function AwilixError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return AwilixError;
}(ExtendableError));
/**

@@ -41,3 +121,4 @@ * Error thrown to indicate a type mismatch.

*/
class AwilixTypeError extends AwilixError {
var AwilixTypeError = /** @class */ (function (_super) {
__extends(AwilixTypeError, _super);
/**

@@ -59,4 +140,4 @@ * Constructor, takes the function name, expected and given

*/
constructor(funcDescription, paramName, expectedType, givenType) {
super(`${funcDescription}: expected ${paramName} to be ${expectedType}, but got ${givenType}.`);
function AwilixTypeError(funcDescription, paramName, expectedType, givenType) {
return _super.call(this, funcDescription + ": expected " + paramName + " to be " + expectedType + ", but got " + givenType + ".") || this;
}

@@ -81,3 +162,3 @@ /**

*/
static assert(condition, funcDescription, paramName, expectedType, givenType) {
AwilixTypeError.assert = function (condition, funcDescription, paramName, expectedType, givenType) {
if (!condition) {

@@ -87,8 +168,10 @@ throw new AwilixTypeError(funcDescription, paramName, expectedType, givenType);

return condition;
}
}
};
return AwilixTypeError;
}(AwilixError));
/**
* A nice error class so we can do an instanceOf check.
*/
class AwilixResolutionError extends AwilixError {
var AwilixResolutionError = /** @class */ (function (_super) {
__extends(AwilixResolutionError, _super);
/**

@@ -104,3 +187,4 @@ * Constructor, takes the registered modules and unresolved tokens

*/
constructor(name, resolutionStack, message) {
function AwilixResolutionError(name, resolutionStack, message) {
var _this = this;
if (typeof name === 'symbol') {

@@ -111,12 +195,14 @@ name = name.toString();

resolutionStack.push(name);
const resolutionPathString = resolutionStack.join(' -> ');
let msg = `Could not resolve '${name}'.`;
var resolutionPathString = resolutionStack.join(' -> ');
var msg = "Could not resolve '" + name + "'.";
if (message) {
msg += ` ${message}`;
msg += " " + message;
}
msg += EOL + EOL;
msg += `Resolution path: ${resolutionPathString}`;
super(msg);
msg += "Resolution path: " + resolutionPathString;
_this = _super.call(this, msg) || this;
return _this;
}
}
return AwilixResolutionError;
}(AwilixError));

@@ -129,13 +215,13 @@ /**

function createTokenizer(source) {
const end = source.length;
let pos = 0;
let type = 'EOF';
let value = '';
var end = source.length;
var pos = 0;
var type = 'EOF';
var value = '';
// These are used to greedily skip as much as possible.
// Whenever we reach a paren, we increment these.
let parenLeft = 0;
let parenRight = 0;
var parenLeft = 0;
var parenRight = 0;
return {
next,
done
next: next,
done: done
};

@@ -159,3 +245,3 @@ /**

}
let ch = source.charAt(pos);
var ch = source.charAt(pos);
// Whitespace is irrelevant

@@ -200,4 +286,4 @@ if (isWhiteSpace(ch)) {

function scanIdentifier() {
const identStart = source.charAt(pos);
const start = ++pos;
var identStart = source.charAt(pos);
var start = ++pos;
while (isIdentifierPart(source.charAt(pos))) {

@@ -218,4 +304,4 @@ pos++;

function skipExpression() {
skipUntil(ch => {
const isAtRoot = parenLeft === parenRight + 1;
skipUntil(function (ch) {
var isAtRoot = parenLeft === parenRight + 1;
if (ch === ',' && isAtRoot) {

@@ -242,3 +328,3 @@ return true;

while (pos < source.length) {
let ch = source.charAt(pos);
var ch = source.charAt(pos);
if (callback(ch)) {

@@ -262,7 +348,7 @@ return;

function skipString() {
const quote = source.charAt(pos);
var quote = source.charAt(pos);
pos++;
while (pos < source.length) {
const ch = source.charAt(pos);
const prev = source.charAt(pos - 1);
var ch = source.charAt(pos);
var prev = source.charAt(pos - 1);
// Checks if the quote was escaped.

@@ -275,5 +361,5 @@ if (ch === quote && prev !== '\\') {

if (quote === '`') {
const next = source.charAt(pos + 1);
if (next === '$') {
const afterDollar = source.charAt(pos + 2);
var next_1 = source.charAt(pos + 1);
if (next_1 === '$') {
var afterDollar = source.charAt(pos + 2);
if (afterDollar === '{') {

@@ -284,3 +370,3 @@ // This is the start of an interpolation; skip the ${

// This includes skipping nested interpolated strings. :D
skipUntil(ch => ch === '}');
skipUntil(function (ch) { return ch === '}'; });
}

@@ -297,5 +383,5 @@ }

if (value) {
return { value, type };
return { value: value, type: type };
}
return { type };
return { type: type };
}

@@ -338,4 +424,4 @@ /**

}
const IDENT_START_EXPR = /^[_$a-zA-Z\xA0-\uFFFF]$/;
const IDENT_PART_EXPR = /^[_$a-zA-Z0-9\xA0-\uFFFF]$/;
var IDENT_START_EXPR = /^[_$a-zA-Z\xA0-\uFFFF]$/;
var IDENT_PART_EXPR = /^[_$a-zA-Z0-9\xA0-\uFFFF]$/;
/**

@@ -376,7 +462,8 @@ * Determines if the character is a valid JS identifier start character.

function nameValueToObject(name, value) {
let obj = name;
var obj = name;
if (typeof obj === 'string' || typeof obj === 'symbol') {
obj = { [name]: value };
obj = (_a = {}, _a[name] = value, _a);
}
return obj;
var _a;
}

@@ -407,8 +494,8 @@ /**

// Should only need 2 tokens.
const tokenizer = createTokenizer(fn.toString());
const first = tokenizer.next();
var tokenizer = createTokenizer(fn.toString());
var first = tokenizer.next();
if (first.type === 'class') {
return true;
}
const second = tokenizer.next();
var second = tokenizer.next();
if (first.type === 'function' && second.value) {

@@ -443,5 +530,5 @@ if (second.value[0] === second.value[0].toUpperCase()) {

function uniq(arr) {
const result = [];
for (const idx in arr) {
const item = arr[idx];
var result = [];
for (var idx in arr) {
var item = arr[idx];
if (result.indexOf(item) === -1) {

@@ -473,3 +560,3 @@ result.push(item);

*/
const Lifetime = {
var Lifetime = {
/**

@@ -495,3 +582,3 @@ * The registration will be resolved once and only once.

*/
const InjectionMode = {
var InjectionMode = {
/**

@@ -521,5 +608,5 @@ * The dependencies will be resolved by injecting the cradle proxy.

function parseParameterList(source) {
const { next: _next, done } = createTokenizer(source);
const params = [];
let t = null;
var _a = createTokenizer(source), _next = _a.next, done = _a.done;
var params = [];
var t = null;
nextToken();

@@ -563,3 +650,3 @@ while (!done()) {

// Current token is a left-paren
let param = { name: '', optional: false };
var param = { name: '', optional: false };
while (!done()) {

@@ -615,4 +702,4 @@ nextToken();

function unexpected() {
return new SyntaxError(`Parsing parameter list, did not expect ${t.type} token${t.value &&
` (${t.value})`}`);
return new SyntaxError("Parsing parameter list, did not expect " + t.type + " token" + (t.value &&
" (" + t.value + ")"));
}

@@ -625,3 +712,3 @@ }

*/
const RESOLVER = Symbol('Awilix Resolver Config');
var RESOLVER = Symbol('Awilix Resolver Config');
/**

@@ -641,3 +728,3 @@ * Creates a simple value resolver where the given value will always be resolved.

return {
resolve: () => value
resolve: function () { return value; }
};

@@ -665,8 +752,8 @@ }

}
const defaults = {
var defaults = {
lifetime: Lifetime.TRANSIENT
};
opts = makeOptions(defaults, opts, fn[RESOLVER]);
const resolve = generateResolve(fn);
let result = Object.assign({ resolve }, opts);
var resolve = generateResolve(fn);
var result = __assign({ resolve: resolve }, opts);
return createDisposableResolver(createBuildResolver(result));

@@ -693,3 +780,3 @@ }

}
const defaults = {
var defaults = {
lifetime: Lifetime.TRANSIENT

@@ -699,7 +786,7 @@ };

// A function to handle object construction for us, as to make the generateResolve more reusable
const newClass = function newClass() {
return new Type(...arguments);
var newClass = function newClass() {
return new (Type.bind.apply(Type, [void 0].concat(arguments)))();
};
const resolve = generateResolve(newClass, Type.prototype.constructor);
return createDisposableResolver(createBuildResolver(Object.assign({}, opts, { resolve })));
var resolve = generateResolve(newClass, Type.prototype.constructor);
return createDisposableResolver(createBuildResolver(__assign({}, opts, { resolve: resolve })));
}

@@ -711,3 +798,3 @@ /**

return {
resolve(container) {
resolve: function (container) {
return container.resolve(name);

@@ -729,17 +816,17 @@ }

function setLifetime(value) {
return createBuildResolver(Object.assign({}, this, { lifetime: value }));
return createBuildResolver(__assign({}, this, { lifetime: value }));
}
function setInjectionMode(value) {
return createBuildResolver(Object.assign({}, this, { injectionMode: value }));
return createBuildResolver(__assign({}, this, { injectionMode: value }));
}
function inject(injector) {
return createBuildResolver(Object.assign({}, this, { injector }));
return createBuildResolver(__assign({}, this, { injector: injector }));
}
return updateResolver(obj, {
setLifetime,
inject,
setLifetime: setLifetime,
inject: inject,
transient: partial(setLifetime, Lifetime.TRANSIENT),
scoped: partial(setLifetime, Lifetime.SCOPED),
singleton: partial(setLifetime, Lifetime.SINGLETON),
setInjectionMode,
setInjectionMode: setInjectionMode,
proxy: partial(setInjectionMode, InjectionMode.PROXY),

@@ -756,6 +843,6 @@ classic: partial(setInjectionMode, InjectionMode.CLASSIC)

function disposer(dispose) {
return createDisposableResolver(Object.assign({}, this, { dispose }));
return createDisposableResolver(__assign({}, this, { dispose: dispose }));
}
return updateResolver(obj, {
disposer
disposer: disposer
});

@@ -782,4 +869,8 @@ }

*/
function makeOptions(defaults, ...rest) {
return Object.assign({}, defaults, ...rest);
function makeOptions(defaults) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
return Object.assign.apply(Object, [{}, defaults].concat(rest));
}

@@ -793,3 +884,3 @@ /**

function updateResolver(source, target) {
const result = Object.assign({}, source, target);
var result = __assign({}, source, target);
return result;

@@ -822,22 +913,51 @@ }

function createInjectorProxy(container, injector) {
const locals = injector(container);
const allKeys = uniq([
...Reflect.ownKeys(container.cradle),
...Reflect.ownKeys(locals)
]);
var locals = injector(container);
var allKeys = uniq(Reflect.ownKeys(container.cradle).concat(Reflect.ownKeys(locals)));
// TODO: Lots of duplication here from the container proxy.
// Need to refactor.
const proxy = new Proxy({}, {
var proxy = new Proxy({}, {
/**
* Resolves the value by first checking the locals, then the container.
*/
get(target, name) {
get: function (target, name) {
if (name === Symbol.iterator) {
return function* iterateRegistrationsAndLocals() {
for (const prop in container.cradle) {
yield prop;
}
for (const prop in locals) {
yield prop;
}
return function iterateRegistrationsAndLocals() {
var _a, _b, _i, prop, _c, _d, _e, prop;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
_a = [];
for (_b in container.cradle)
_a.push(_b);
_i = 0;
_f.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
prop = _a[_i];
return [4 /*yield*/, prop];
case 2:
_f.sent();
_f.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
_c = [];
for (_d in locals)
_c.push(_d);
_e = 0;
_f.label = 5;
case 5:
if (!(_e < _c.length)) return [3 /*break*/, 8];
prop = _c[_e];
return [4 /*yield*/, prop];
case 6:
_f.sent();
_f.label = 7;
case 7:
_e++;
return [3 /*break*/, 5];
case 8: return [2 /*return*/];
}
});
};

@@ -853,3 +973,3 @@ }

*/
ownKeys() {
ownKeys: function () {
return allKeys;

@@ -860,3 +980,3 @@ },

*/
getOwnPropertyDescriptor(target, key) {
getOwnPropertyDescriptor: function (target, key) {
if (allKeys.indexOf(key) > -1) {

@@ -897,3 +1017,3 @@ return {

// Try to resolve the dependencies
const dependencies = parseParameterList(dependencyParseTarget.toString());
var dependencies = parseParameterList(dependencyParseTarget.toString());
// Use a regular function instead of an arrow function to facilitate binding to the resolver.

@@ -903,3 +1023,3 @@ return function resolve(container) {

// resolver -> container -> default value
const injectionMode = this.injectionMode ||
var injectionMode = this.injectionMode ||
container.options.injectionMode ||

@@ -909,3 +1029,3 @@ InjectionMode.PROXY;

// If we have a custom injector, we need to wrap the cradle.
const cradle = this.injector
var cradle = this.injector
? createInjectorProxy(container, this.injector)

@@ -918,7 +1038,9 @@ : container.cradle;

if (dependencies.length > 0) {
const resolve = this.injector
var resolve_1 = this.injector
? wrapWithLocals(container, this.injector(container))
: container.resolve;
const children = dependencies.map(p => resolve(p.name, { allowUnregistered: p.optional }));
return fn(...children);
var children = dependencies.map(function (p) {
return resolve_1(p.name, { allowUnregistered: p.optional });
});
return fn.apply(void 0, children);
}

@@ -960,3 +1082,3 @@ return fn();

*/
const FAMILY_TREE = Symbol('familyTree');
var FAMILY_TREE = Symbol('familyTree');
/**

@@ -966,3 +1088,3 @@ * Roll Up Registrations symbol.

*/
const ROLL_UP_REGISTRATIONS = Symbol('rollUpRegistrations');
var ROLL_UP_REGISTRATIONS = Symbol('rollUpRegistrations');
/**

@@ -981,3 +1103,3 @@ * Creates an Awilix container instance.

function createContainer(options, parentContainer) {
options = Object.assign({ injectionMode: InjectionMode.PROXY }, options);
options = __assign({ injectionMode: InjectionMode.PROXY }, options);
// The resolution stack is used to keep track

@@ -987,8 +1109,8 @@ // of what modules are being resolved, so when

// to the poor developer who fucked up.
let resolutionStack = [];
var resolutionStack = [];
// For performance reasons, we store
// the rolled-up registrations when starting a resolve.
let computedRegistrations = null;
var computedRegistrations = null;
// Internal registration store for this container.
const registrations = {};
var registrations = {};
/**

@@ -999,3 +1121,3 @@ * The `Proxy` that is passed to functions so they can resolve their dependencies without

*/
const cradle = new Proxy({}, {
var cradle = new Proxy({}, {
/**

@@ -1013,3 +1135,3 @@ * The `get` handler is invoked whenever a get-call for `container.cradle.*` is made.

*/
get: (target, name) => resolve(name),
get: function (target, name) { return resolve(name); },
/**

@@ -1021,4 +1143,4 @@ * Setting things on the cradle throws an error.

*/
set: (target, name, value) => {
throw new Error(`Attempted setting property "${name}" on container cradle - this is not allowed.`);
set: function (target, name, value) {
throw new Error("Attempted setting property \"" + name + "\" on container cradle - this is not allowed.");
},

@@ -1028,3 +1150,3 @@ /**

*/
ownKeys() {
ownKeys: function () {
return Array.from(cradle);

@@ -1035,4 +1157,4 @@ },

*/
getOwnPropertyDescriptor(target, key) {
const regs = rollUpRegistrations();
getOwnPropertyDescriptor: function (target, key) {
var regs = rollUpRegistrations();
if (Object.getOwnPropertyDescriptor(regs, key)) {

@@ -1048,21 +1170,22 @@ return {

// The container being exposed.
const container = {
options,
cradle: cradle,
inspect,
cache: new Map(),
loadModules: () => { throw new Error("loadModules is not supported in the browser."); },
createScope,
register: register,
build,
resolve,
dispose,
/* removed in browser build */
[ROLL_UP_REGISTRATIONS]: rollUpRegistrations,
get registrations() {
return rollUpRegistrations();
}
};
var container = (_a = {
options: options,
cradle: cradle,
inspect: inspect,
cache: new Map(),
loadModules: function () { throw new Error("loadModules is not supported in the browser."); },
createScope: createScope,
register: register,
build: build,
resolve: resolve,
dispose: dispose
}, _a[ROLL_UP_REGISTRATIONS] = rollUpRegistrations, Object.defineProperty(_a, "registrations", {
get: function () {
return rollUpRegistrations();
},
enumerable: true,
configurable: true
}), _a);
// Track the family tree.
const familyTree = parentContainer
var familyTree = parentContainer
? [container].concat(parentContainer[FAMILY_TREE])

@@ -1073,3 +1196,3 @@ : [container];

// so we can retrieve and store singletons.
const rootContainer = last(familyTree);
var rootContainer = last(familyTree);
return container;

@@ -1080,3 +1203,3 @@ /**

function inspect(depth, opts) {
return `[AwilixContainer (${parentContainer ? 'scoped, ' : ''}registrations: ${Object.keys(container.registrations).length})]`;
return "[AwilixContainer (" + (parentContainer ? 'scoped, ' : '') + "registrations: " + Object.keys(container.registrations).length + ")]";
}

@@ -1093,7 +1216,8 @@ /**

*/
function rollUpRegistrations(bustCache = false) {
function rollUpRegistrations(bustCache) {
if (bustCache === void 0) { bustCache = false; }
if (computedRegistrations && !bustCache) {
return computedRegistrations;
}
computedRegistrations = Object.assign({}, (parentContainer &&
computedRegistrations = __assign({}, (parentContainer &&
parentContainer[ROLL_UP_REGISTRATIONS](bustCache)), registrations);

@@ -1105,7 +1229,26 @@ return computedRegistrations;

*/
function* registrationNamesIterator() {
const registrations = rollUpRegistrations();
for (const registrationName in registrations) {
yield registrationName;
}
function registrationNamesIterator() {
var registrations, _a, _b, _i, registrationName;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
registrations = rollUpRegistrations();
_a = [];
for (_b in registrations)
_a.push(_b);
_i = 0;
_c.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
registrationName = _a[_i];
return [4 /*yield*/, registrationName];
case 2:
_c.sent();
_c.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
}

@@ -1125,6 +1268,7 @@ /**

function register(arg1, arg2) {
const obj = nameValueToObject(arg1, arg2);
const keys = [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
for (const key of keys) {
const value = obj[key];
var obj = nameValueToObject(arg1, arg2);
var keys = Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
var value = obj[key];
registrations[key] = value;

@@ -1160,3 +1304,3 @@ }

// Grab the registration by name.
const resolver = computedRegistrations[name];
var resolver = computedRegistrations[name];
if (resolutionStack.indexOf(name) > -1) {

@@ -1188,4 +1332,4 @@ throw new AwilixResolutionError(name, resolutionStack, 'Cyclic dependencies detected.');

// Do the thing
let cached;
let resolved;
var cached = void 0;
var resolved = void 0;
switch (resolver.lifetime || Lifetime.TRANSIENT) {

@@ -1201,3 +1345,3 @@ case Lifetime.TRANSIENT:

resolved = resolver.resolve(container);
rootContainer.cache.set(name, { resolver, value: resolved });
rootContainer.cache.set(name, { resolver: resolver, value: resolved });
}

@@ -1214,3 +1358,4 @@ else {

// Note: The first element in the family tree is this container.
for (const c of familyTree) {
for (var _i = 0, familyTree_1 = familyTree; _i < familyTree_1.length; _i++) {
var c = familyTree_1[_i];
cached = c.cache.get(name);

@@ -1226,7 +1371,7 @@ if (cached !== undefined) {

resolved = resolver.resolve(container);
container.cache.set(name, { resolver, value: resolved });
container.cache.set(name, { resolver: resolver, value: resolved });
}
break;
default:
throw new AwilixResolutionError(name, resolutionStack, `Unknown lifetime "${resolver.lifetime}"`);
throw new AwilixResolutionError(name, resolutionStack, "Unknown lifetime \"" + resolver.lifetime + "\"");
}

@@ -1255,7 +1400,7 @@ // Pop it from the stack again, ready for the next resolution

}
const funcName = 'build';
const paramName = 'targetOrResolver';
var funcName = 'build';
var paramName = 'targetOrResolver';
AwilixTypeError.assert(targetOrResolver, funcName, paramName, 'a registration, function or class', targetOrResolver);
AwilixTypeError.assert(typeof targetOrResolver === 'function', funcName, paramName, 'a function or class', targetOrResolver);
const resolver = isClass(targetOrResolver)
var resolver = isClass(targetOrResolver)
? asClass(targetOrResolver, opts)

@@ -1275,15 +1420,17 @@ : asFunction(targetOrResolver, opts);

function dispose() {
const entries = Array.from(container.cache.entries());
var entries = Array.from(container.cache.entries());
container.cache.clear();
return Promise.all(entries.map(([name, entry]) => {
const { resolver, value } = entry;
const disposable = resolver;
return Promise.all(entries.map(function (_a) {
var name = _a[0], entry = _a[1];
var resolver = entry.resolver, value = entry.value;
var disposable = resolver;
if (disposable.dispose) {
return Promise.resolve().then(() => disposable.dispose(value));
return Promise.resolve().then(function () { return disposable.dispose(value); });
}
return Promise.resolve();
})).then(() => undefined);
})).then(function () { return undefined; });
}
var _a;
}
export { ExtendableError, AwilixError, AwilixTypeError, AwilixResolutionError, createContainer, RESOLVER, asValue, asFunction, asClass, aliasTo, createBuildResolver, createDisposableResolver, InjectionMode, Lifetime };
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./errors"), exports);
tslib_1.__exportStar(require("./list-modules"), exports);
tslib_1.__exportStar(require("./container"), exports);
tslib_1.__exportStar(require("./resolvers"), exports);
tslib_1.__exportStar(require("./injection-mode"), exports);
tslib_1.__exportStar(require("./lifetime"), exports);
__export(require("./errors"));
__export(require("./list-modules"));
__export(require("./container"));
__export(require("./resolvers"));
__export(require("./injection-mode"));
__export(require("./lifetime"));
//# sourceMappingURL=awilix.js.map

@@ -7,6 +7,78 @@ (function (global, factory) {

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
/**
* Newline.
*/
const EOL = '\n';
var EOL = '\n';
/**

@@ -16,3 +88,4 @@ * An extendable error class.

*/
class ExtendableError extends Error {
var ExtendableError = /** @class */ (function (_super) {
__extends(ExtendableError, _super);
/**

@@ -24,21 +97,28 @@ * Constructor for the error.

*/
constructor(message) {
super(message);
function ExtendableError(message) {
var _this = _super.call(this, message) || this;
// extending Error is weird and does not propagate `message`
Object.defineProperty(this, 'message', {
Object.defineProperty(_this, 'message', {
enumerable: false,
value: message
});
Object.defineProperty(this, 'name', {
Object.defineProperty(_this, 'name', {
enumerable: false,
value: this.constructor.name
value: _this.constructor.name
});
Error.captureStackTrace(this, this.constructor);
Error.captureStackTrace(_this, _this.constructor);
return _this;
}
}
return ExtendableError;
}(Error));
/**
* Base error for all Awilix-specific errors.
*/
class AwilixError extends ExtendableError {
}
var AwilixError = /** @class */ (function (_super) {
__extends(AwilixError, _super);
function AwilixError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return AwilixError;
}(ExtendableError));
/**

@@ -48,3 +128,4 @@ * Error thrown to indicate a type mismatch.

*/
class AwilixTypeError extends AwilixError {
var AwilixTypeError = /** @class */ (function (_super) {
__extends(AwilixTypeError, _super);
/**

@@ -66,4 +147,4 @@ * Constructor, takes the function name, expected and given

*/
constructor(funcDescription, paramName, expectedType, givenType) {
super(`${funcDescription}: expected ${paramName} to be ${expectedType}, but got ${givenType}.`);
function AwilixTypeError(funcDescription, paramName, expectedType, givenType) {
return _super.call(this, funcDescription + ": expected " + paramName + " to be " + expectedType + ", but got " + givenType + ".") || this;
}

@@ -88,3 +169,3 @@ /**

*/
static assert(condition, funcDescription, paramName, expectedType, givenType) {
AwilixTypeError.assert = function (condition, funcDescription, paramName, expectedType, givenType) {
if (!condition) {

@@ -94,8 +175,10 @@ throw new AwilixTypeError(funcDescription, paramName, expectedType, givenType);

return condition;
}
}
};
return AwilixTypeError;
}(AwilixError));
/**
* A nice error class so we can do an instanceOf check.
*/
class AwilixResolutionError extends AwilixError {
var AwilixResolutionError = /** @class */ (function (_super) {
__extends(AwilixResolutionError, _super);
/**

@@ -111,3 +194,4 @@ * Constructor, takes the registered modules and unresolved tokens

*/
constructor(name, resolutionStack, message) {
function AwilixResolutionError(name, resolutionStack, message) {
var _this = this;
if (typeof name === 'symbol') {

@@ -118,12 +202,14 @@ name = name.toString();

resolutionStack.push(name);
const resolutionPathString = resolutionStack.join(' -> ');
let msg = `Could not resolve '${name}'.`;
var resolutionPathString = resolutionStack.join(' -> ');
var msg = "Could not resolve '" + name + "'.";
if (message) {
msg += ` ${message}`;
msg += " " + message;
}
msg += EOL + EOL;
msg += `Resolution path: ${resolutionPathString}`;
super(msg);
msg += "Resolution path: " + resolutionPathString;
_this = _super.call(this, msg) || this;
return _this;
}
}
return AwilixResolutionError;
}(AwilixError));

@@ -136,13 +222,13 @@ /**

function createTokenizer(source) {
const end = source.length;
let pos = 0;
let type = 'EOF';
let value = '';
var end = source.length;
var pos = 0;
var type = 'EOF';
var value = '';
// These are used to greedily skip as much as possible.
// Whenever we reach a paren, we increment these.
let parenLeft = 0;
let parenRight = 0;
var parenLeft = 0;
var parenRight = 0;
return {
next,
done
next: next,
done: done
};

@@ -166,3 +252,3 @@ /**

}
let ch = source.charAt(pos);
var ch = source.charAt(pos);
// Whitespace is irrelevant

@@ -207,4 +293,4 @@ if (isWhiteSpace(ch)) {

function scanIdentifier() {
const identStart = source.charAt(pos);
const start = ++pos;
var identStart = source.charAt(pos);
var start = ++pos;
while (isIdentifierPart(source.charAt(pos))) {

@@ -225,4 +311,4 @@ pos++;

function skipExpression() {
skipUntil(ch => {
const isAtRoot = parenLeft === parenRight + 1;
skipUntil(function (ch) {
var isAtRoot = parenLeft === parenRight + 1;
if (ch === ',' && isAtRoot) {

@@ -249,3 +335,3 @@ return true;

while (pos < source.length) {
let ch = source.charAt(pos);
var ch = source.charAt(pos);
if (callback(ch)) {

@@ -269,7 +355,7 @@ return;

function skipString() {
const quote = source.charAt(pos);
var quote = source.charAt(pos);
pos++;
while (pos < source.length) {
const ch = source.charAt(pos);
const prev = source.charAt(pos - 1);
var ch = source.charAt(pos);
var prev = source.charAt(pos - 1);
// Checks if the quote was escaped.

@@ -282,5 +368,5 @@ if (ch === quote && prev !== '\\') {

if (quote === '`') {
const next = source.charAt(pos + 1);
if (next === '$') {
const afterDollar = source.charAt(pos + 2);
var next_1 = source.charAt(pos + 1);
if (next_1 === '$') {
var afterDollar = source.charAt(pos + 2);
if (afterDollar === '{') {

@@ -291,3 +377,3 @@ // This is the start of an interpolation; skip the ${

// This includes skipping nested interpolated strings. :D
skipUntil(ch => ch === '}');
skipUntil(function (ch) { return ch === '}'; });
}

@@ -304,5 +390,5 @@ }

if (value) {
return { value, type };
return { value: value, type: type };
}
return { type };
return { type: type };
}

@@ -345,4 +431,4 @@ /**

}
const IDENT_START_EXPR = /^[_$a-zA-Z\xA0-\uFFFF]$/;
const IDENT_PART_EXPR = /^[_$a-zA-Z0-9\xA0-\uFFFF]$/;
var IDENT_START_EXPR = /^[_$a-zA-Z\xA0-\uFFFF]$/;
var IDENT_PART_EXPR = /^[_$a-zA-Z0-9\xA0-\uFFFF]$/;
/**

@@ -383,7 +469,8 @@ * Determines if the character is a valid JS identifier start character.

function nameValueToObject(name, value) {
let obj = name;
var obj = name;
if (typeof obj === 'string' || typeof obj === 'symbol') {
obj = { [name]: value };
obj = (_a = {}, _a[name] = value, _a);
}
return obj;
var _a;
}

@@ -414,8 +501,8 @@ /**

// Should only need 2 tokens.
const tokenizer = createTokenizer(fn.toString());
const first = tokenizer.next();
var tokenizer = createTokenizer(fn.toString());
var first = tokenizer.next();
if (first.type === 'class') {
return true;
}
const second = tokenizer.next();
var second = tokenizer.next();
if (first.type === 'function' && second.value) {

@@ -450,5 +537,5 @@ if (second.value[0] === second.value[0].toUpperCase()) {

function uniq(arr) {
const result = [];
for (const idx in arr) {
const item = arr[idx];
var result = [];
for (var idx in arr) {
var item = arr[idx];
if (result.indexOf(item) === -1) {

@@ -480,3 +567,3 @@ result.push(item);

*/
const Lifetime = {
var Lifetime = {
/**

@@ -502,3 +589,3 @@ * The registration will be resolved once and only once.

*/
const InjectionMode = {
var InjectionMode = {
/**

@@ -528,5 +615,5 @@ * The dependencies will be resolved by injecting the cradle proxy.

function parseParameterList(source) {
const { next: _next, done } = createTokenizer(source);
const params = [];
let t = null;
var _a = createTokenizer(source), _next = _a.next, done = _a.done;
var params = [];
var t = null;
nextToken();

@@ -570,3 +657,3 @@ while (!done()) {

// Current token is a left-paren
let param = { name: '', optional: false };
var param = { name: '', optional: false };
while (!done()) {

@@ -622,4 +709,4 @@ nextToken();

function unexpected() {
return new SyntaxError(`Parsing parameter list, did not expect ${t.type} token${t.value &&
` (${t.value})`}`);
return new SyntaxError("Parsing parameter list, did not expect " + t.type + " token" + (t.value &&
" (" + t.value + ")"));
}

@@ -632,3 +719,3 @@ }

*/
const RESOLVER = Symbol('Awilix Resolver Config');
var RESOLVER = Symbol('Awilix Resolver Config');
/**

@@ -648,3 +735,3 @@ * Creates a simple value resolver where the given value will always be resolved.

return {
resolve: () => value
resolve: function () { return value; }
};

@@ -672,8 +759,8 @@ }

}
const defaults = {
var defaults = {
lifetime: Lifetime.TRANSIENT
};
opts = makeOptions(defaults, opts, fn[RESOLVER]);
const resolve = generateResolve(fn);
let result = Object.assign({ resolve }, opts);
var resolve = generateResolve(fn);
var result = __assign({ resolve: resolve }, opts);
return createDisposableResolver(createBuildResolver(result));

@@ -700,3 +787,3 @@ }

}
const defaults = {
var defaults = {
lifetime: Lifetime.TRANSIENT

@@ -706,7 +793,7 @@ };

// A function to handle object construction for us, as to make the generateResolve more reusable
const newClass = function newClass() {
return new Type(...arguments);
var newClass = function newClass() {
return new (Type.bind.apply(Type, [void 0].concat(arguments)))();
};
const resolve = generateResolve(newClass, Type.prototype.constructor);
return createDisposableResolver(createBuildResolver(Object.assign({}, opts, { resolve })));
var resolve = generateResolve(newClass, Type.prototype.constructor);
return createDisposableResolver(createBuildResolver(__assign({}, opts, { resolve: resolve })));
}

@@ -718,3 +805,3 @@ /**

return {
resolve(container) {
resolve: function (container) {
return container.resolve(name);

@@ -736,17 +823,17 @@ }

function setLifetime(value) {
return createBuildResolver(Object.assign({}, this, { lifetime: value }));
return createBuildResolver(__assign({}, this, { lifetime: value }));
}
function setInjectionMode(value) {
return createBuildResolver(Object.assign({}, this, { injectionMode: value }));
return createBuildResolver(__assign({}, this, { injectionMode: value }));
}
function inject(injector) {
return createBuildResolver(Object.assign({}, this, { injector }));
return createBuildResolver(__assign({}, this, { injector: injector }));
}
return updateResolver(obj, {
setLifetime,
inject,
setLifetime: setLifetime,
inject: inject,
transient: partial(setLifetime, Lifetime.TRANSIENT),
scoped: partial(setLifetime, Lifetime.SCOPED),
singleton: partial(setLifetime, Lifetime.SINGLETON),
setInjectionMode,
setInjectionMode: setInjectionMode,
proxy: partial(setInjectionMode, InjectionMode.PROXY),

@@ -763,6 +850,6 @@ classic: partial(setInjectionMode, InjectionMode.CLASSIC)

function disposer(dispose) {
return createDisposableResolver(Object.assign({}, this, { dispose }));
return createDisposableResolver(__assign({}, this, { dispose: dispose }));
}
return updateResolver(obj, {
disposer
disposer: disposer
});

@@ -789,4 +876,8 @@ }

*/
function makeOptions(defaults, ...rest) {
return Object.assign({}, defaults, ...rest);
function makeOptions(defaults) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
return Object.assign.apply(Object, [{}, defaults].concat(rest));
}

@@ -800,3 +891,3 @@ /**

function updateResolver(source, target) {
const result = Object.assign({}, source, target);
var result = __assign({}, source, target);
return result;

@@ -829,22 +920,51 @@ }

function createInjectorProxy(container, injector) {
const locals = injector(container);
const allKeys = uniq([
...Reflect.ownKeys(container.cradle),
...Reflect.ownKeys(locals)
]);
var locals = injector(container);
var allKeys = uniq(Reflect.ownKeys(container.cradle).concat(Reflect.ownKeys(locals)));
// TODO: Lots of duplication here from the container proxy.
// Need to refactor.
const proxy = new Proxy({}, {
var proxy = new Proxy({}, {
/**
* Resolves the value by first checking the locals, then the container.
*/
get(target, name) {
get: function (target, name) {
if (name === Symbol.iterator) {
return function* iterateRegistrationsAndLocals() {
for (const prop in container.cradle) {
yield prop;
}
for (const prop in locals) {
yield prop;
}
return function iterateRegistrationsAndLocals() {
var _a, _b, _i, prop, _c, _d, _e, prop;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
_a = [];
for (_b in container.cradle)
_a.push(_b);
_i = 0;
_f.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
prop = _a[_i];
return [4 /*yield*/, prop];
case 2:
_f.sent();
_f.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
_c = [];
for (_d in locals)
_c.push(_d);
_e = 0;
_f.label = 5;
case 5:
if (!(_e < _c.length)) return [3 /*break*/, 8];
prop = _c[_e];
return [4 /*yield*/, prop];
case 6:
_f.sent();
_f.label = 7;
case 7:
_e++;
return [3 /*break*/, 5];
case 8: return [2 /*return*/];
}
});
};

@@ -860,3 +980,3 @@ }

*/
ownKeys() {
ownKeys: function () {
return allKeys;

@@ -867,3 +987,3 @@ },

*/
getOwnPropertyDescriptor(target, key) {
getOwnPropertyDescriptor: function (target, key) {
if (allKeys.indexOf(key) > -1) {

@@ -904,3 +1024,3 @@ return {

// Try to resolve the dependencies
const dependencies = parseParameterList(dependencyParseTarget.toString());
var dependencies = parseParameterList(dependencyParseTarget.toString());
// Use a regular function instead of an arrow function to facilitate binding to the resolver.

@@ -910,3 +1030,3 @@ return function resolve(container) {

// resolver -> container -> default value
const injectionMode = this.injectionMode ||
var injectionMode = this.injectionMode ||
container.options.injectionMode ||

@@ -916,3 +1036,3 @@ InjectionMode.PROXY;

// If we have a custom injector, we need to wrap the cradle.
const cradle = this.injector
var cradle = this.injector
? createInjectorProxy(container, this.injector)

@@ -925,7 +1045,9 @@ : container.cradle;

if (dependencies.length > 0) {
const resolve = this.injector
var resolve_1 = this.injector
? wrapWithLocals(container, this.injector(container))
: container.resolve;
const children = dependencies.map(p => resolve(p.name, { allowUnregistered: p.optional }));
return fn(...children);
var children = dependencies.map(function (p) {
return resolve_1(p.name, { allowUnregistered: p.optional });
});
return fn.apply(void 0, children);
}

@@ -967,3 +1089,3 @@ return fn();

*/
const FAMILY_TREE = Symbol('familyTree');
var FAMILY_TREE = Symbol('familyTree');
/**

@@ -973,3 +1095,3 @@ * Roll Up Registrations symbol.

*/
const ROLL_UP_REGISTRATIONS = Symbol('rollUpRegistrations');
var ROLL_UP_REGISTRATIONS = Symbol('rollUpRegistrations');
/**

@@ -988,3 +1110,3 @@ * Creates an Awilix container instance.

function createContainer(options, parentContainer) {
options = Object.assign({ injectionMode: InjectionMode.PROXY }, options);
options = __assign({ injectionMode: InjectionMode.PROXY }, options);
// The resolution stack is used to keep track

@@ -994,8 +1116,8 @@ // of what modules are being resolved, so when

// to the poor developer who fucked up.
let resolutionStack = [];
var resolutionStack = [];
// For performance reasons, we store
// the rolled-up registrations when starting a resolve.
let computedRegistrations = null;
var computedRegistrations = null;
// Internal registration store for this container.
const registrations = {};
var registrations = {};
/**

@@ -1006,3 +1128,3 @@ * The `Proxy` that is passed to functions so they can resolve their dependencies without

*/
const cradle = new Proxy({}, {
var cradle = new Proxy({}, {
/**

@@ -1020,3 +1142,3 @@ * The `get` handler is invoked whenever a get-call for `container.cradle.*` is made.

*/
get: (target, name) => resolve(name),
get: function (target, name) { return resolve(name); },
/**

@@ -1028,4 +1150,4 @@ * Setting things on the cradle throws an error.

*/
set: (target, name, value) => {
throw new Error(`Attempted setting property "${name}" on container cradle - this is not allowed.`);
set: function (target, name, value) {
throw new Error("Attempted setting property \"" + name + "\" on container cradle - this is not allowed.");
},

@@ -1035,3 +1157,3 @@ /**

*/
ownKeys() {
ownKeys: function () {
return Array.from(cradle);

@@ -1042,4 +1164,4 @@ },

*/
getOwnPropertyDescriptor(target, key) {
const regs = rollUpRegistrations();
getOwnPropertyDescriptor: function (target, key) {
var regs = rollUpRegistrations();
if (Object.getOwnPropertyDescriptor(regs, key)) {

@@ -1055,21 +1177,22 @@ return {

// The container being exposed.
const container = {
options,
cradle: cradle,
inspect,
cache: new Map(),
loadModules: () => { throw new Error("loadModules is not supported in the browser."); },
createScope,
register: register,
build,
resolve,
dispose,
/* removed in browser build */
[ROLL_UP_REGISTRATIONS]: rollUpRegistrations,
get registrations() {
return rollUpRegistrations();
}
};
var container = (_a = {
options: options,
cradle: cradle,
inspect: inspect,
cache: new Map(),
loadModules: function () { throw new Error("loadModules is not supported in the browser."); },
createScope: createScope,
register: register,
build: build,
resolve: resolve,
dispose: dispose
}, _a[ROLL_UP_REGISTRATIONS] = rollUpRegistrations, Object.defineProperty(_a, "registrations", {
get: function () {
return rollUpRegistrations();
},
enumerable: true,
configurable: true
}), _a);
// Track the family tree.
const familyTree = parentContainer
var familyTree = parentContainer
? [container].concat(parentContainer[FAMILY_TREE])

@@ -1080,3 +1203,3 @@ : [container];

// so we can retrieve and store singletons.
const rootContainer = last(familyTree);
var rootContainer = last(familyTree);
return container;

@@ -1087,3 +1210,3 @@ /**

function inspect(depth, opts) {
return `[AwilixContainer (${parentContainer ? 'scoped, ' : ''}registrations: ${Object.keys(container.registrations).length})]`;
return "[AwilixContainer (" + (parentContainer ? 'scoped, ' : '') + "registrations: " + Object.keys(container.registrations).length + ")]";
}

@@ -1100,7 +1223,8 @@ /**

*/
function rollUpRegistrations(bustCache = false) {
function rollUpRegistrations(bustCache) {
if (bustCache === void 0) { bustCache = false; }
if (computedRegistrations && !bustCache) {
return computedRegistrations;
}
computedRegistrations = Object.assign({}, (parentContainer &&
computedRegistrations = __assign({}, (parentContainer &&
parentContainer[ROLL_UP_REGISTRATIONS](bustCache)), registrations);

@@ -1112,7 +1236,26 @@ return computedRegistrations;

*/
function* registrationNamesIterator() {
const registrations = rollUpRegistrations();
for (const registrationName in registrations) {
yield registrationName;
}
function registrationNamesIterator() {
var registrations, _a, _b, _i, registrationName;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
registrations = rollUpRegistrations();
_a = [];
for (_b in registrations)
_a.push(_b);
_i = 0;
_c.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
registrationName = _a[_i];
return [4 /*yield*/, registrationName];
case 2:
_c.sent();
_c.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
}

@@ -1132,6 +1275,7 @@ /**

function register(arg1, arg2) {
const obj = nameValueToObject(arg1, arg2);
const keys = [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
for (const key of keys) {
const value = obj[key];
var obj = nameValueToObject(arg1, arg2);
var keys = Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
var value = obj[key];
registrations[key] = value;

@@ -1167,3 +1311,3 @@ }

// Grab the registration by name.
const resolver = computedRegistrations[name];
var resolver = computedRegistrations[name];
if (resolutionStack.indexOf(name) > -1) {

@@ -1195,4 +1339,4 @@ throw new AwilixResolutionError(name, resolutionStack, 'Cyclic dependencies detected.');

// Do the thing
let cached;
let resolved;
var cached = void 0;
var resolved = void 0;
switch (resolver.lifetime || Lifetime.TRANSIENT) {

@@ -1208,3 +1352,3 @@ case Lifetime.TRANSIENT:

resolved = resolver.resolve(container);
rootContainer.cache.set(name, { resolver, value: resolved });
rootContainer.cache.set(name, { resolver: resolver, value: resolved });
}

@@ -1221,3 +1365,4 @@ else {

// Note: The first element in the family tree is this container.
for (const c of familyTree) {
for (var _i = 0, familyTree_1 = familyTree; _i < familyTree_1.length; _i++) {
var c = familyTree_1[_i];
cached = c.cache.get(name);

@@ -1233,7 +1378,7 @@ if (cached !== undefined) {

resolved = resolver.resolve(container);
container.cache.set(name, { resolver, value: resolved });
container.cache.set(name, { resolver: resolver, value: resolved });
}
break;
default:
throw new AwilixResolutionError(name, resolutionStack, `Unknown lifetime "${resolver.lifetime}"`);
throw new AwilixResolutionError(name, resolutionStack, "Unknown lifetime \"" + resolver.lifetime + "\"");
}

@@ -1262,7 +1407,7 @@ // Pop it from the stack again, ready for the next resolution

}
const funcName = 'build';
const paramName = 'targetOrResolver';
var funcName = 'build';
var paramName = 'targetOrResolver';
AwilixTypeError.assert(targetOrResolver, funcName, paramName, 'a registration, function or class', targetOrResolver);
AwilixTypeError.assert(typeof targetOrResolver === 'function', funcName, paramName, 'a function or class', targetOrResolver);
const resolver = isClass(targetOrResolver)
var resolver = isClass(targetOrResolver)
? asClass(targetOrResolver, opts)

@@ -1282,13 +1427,15 @@ : asFunction(targetOrResolver, opts);

function dispose() {
const entries = Array.from(container.cache.entries());
var entries = Array.from(container.cache.entries());
container.cache.clear();
return Promise.all(entries.map(([name, entry]) => {
const { resolver, value } = entry;
const disposable = resolver;
return Promise.all(entries.map(function (_a) {
var name = _a[0], entry = _a[1];
var resolver = entry.resolver, value = entry.value;
var disposable = resolver;
if (disposable.dispose) {
return Promise.resolve().then(() => disposable.dispose(value));
return Promise.resolve().then(function () { return disposable.dispose(value); });
}
return Promise.resolve();
})).then(() => undefined);
})).then(function () { return undefined; });
}
var _a;
}

@@ -1295,0 +1442,0 @@

{
"name": "awilix",
"version": "3.0.0-rc.6",
"version": "3.0.0-rc.7",
"description": "Extremely powerful dependency injection container.",

@@ -19,3 +19,2 @@ "main": "lib/awilix.js",

"test": "npm run check && jest",
"test-watch": "npm run test -- --watch --reporter nyan",
"lint": "npm run check && tslint --project tsconfig.json --fix \"{src,examples}/**/*.ts\" && prettier --write \"{src,examples}/**/*.{ts,js}\"",

@@ -77,4 +76,3 @@ "precommit": "lint-staged && npm test",

"camel-case": "^3.0.0",
"glob": "^7.1.2",
"tslib": "^1.8.1"
"glob": "^7.1.2"
},

@@ -81,0 +79,0 @@ "lint-staged": {

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