UNPKG

@shahen.poghosyan/awilix

Version:

Extremely powerful dependency injection container.

1,467 lines (1,437 loc) 56.9 kB
/*! ***************************************************************************** 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 = function(d, b) { 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]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __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; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } 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 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, 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 }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } var tslib_1 = /*#__PURE__*/Object.freeze({ __extends: __extends, get __assign () { return __assign; }, __rest: __rest, __decorate: __decorate, __param: __param, __metadata: __metadata, __awaiter: __awaiter, __generator: __generator, __exportStar: __exportStar, __values: __values, __read: __read, __spread: __spread, __await: __await, __asyncGenerator: __asyncGenerator, __asyncDelegator: __asyncDelegator, __asyncValues: __asyncValues, __makeTemplateObject: __makeTemplateObject, __importStar: __importStar, __importDefault: __importDefault }); /** * Newline. */ var EOL = '\n'; /** * An extendable error class. * @author https://github.com/bjyoungblood/es6-error/ */ var ExtendableError = /** @class */ (function (_super) { __extends(ExtendableError, _super); /** * Constructor for the error. * * @param {String} message * The error message. */ function ExtendableError(message) { var _this = _super.call(this, message) || this; // extending Error is weird and does not propagate `message` Object.defineProperty(_this, 'message', { enumerable: false, value: message }); Object.defineProperty(_this, 'name', { enumerable: false, value: _this.constructor.name }); Error.captureStackTrace(_this, _this.constructor); return _this; } return ExtendableError; }(Error)); /** * Base error for all Awilix-specific errors. */ var AwilixError = /** @class */ (function (_super) { __extends(AwilixError, _super); function AwilixError() { return _super !== null && _super.apply(this, arguments) || this; } return AwilixError; }(ExtendableError)); /** * Error thrown to indicate a type mismatch. * TODO(v3): remove `AwilixNotAFunctionError` and use this. */ var AwilixTypeError = /** @class */ (function (_super) { __extends(AwilixTypeError, _super); /** * Constructor, takes the function name, expected and given * type to produce an error. * * @param {string} funcDescription * Name of the function being guarded. * * @param {string} paramName * The parameter there was an issue with. * * @param {string} expectedType * Name of the expected type. * * @param {string} givenType * Name of the given type. */ function AwilixTypeError(funcDescription, paramName, expectedType, givenType) { return _super.call(this, funcDescription + ": expected " + paramName + " to be " + expectedType + ", but got " + givenType + ".") || this; } /** * Asserts the given condition, throws an error otherwise. * * @param {*} condition * The condition to check * * @param {string} funcDescription * Name of the function being guarded. * * @param {string} paramName * The parameter there was an issue with. * * @param {string} expectedType * Name of the expected type. * * @param {string} givenType * Name of the given type. */ AwilixTypeError.assert = function (condition, funcDescription, paramName, expectedType, givenType) { if (!condition) { throw new AwilixTypeError(funcDescription, paramName, expectedType, givenType); } return condition; }; return AwilixTypeError; }(AwilixError)); /** * A nice error class so we can do an instanceOf check. */ var AwilixResolutionError = /** @class */ (function (_super) { __extends(AwilixResolutionError, _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 resolved. * * @param {string[]} resolutionStack * The current resolution stack */ function AwilixResolutionError(name, resolutionStack, message) { var _this = this; if (typeof name === 'symbol') { name = name.toString(); } resolutionStack = resolutionStack.slice(); resolutionStack.push(name); var resolutionPathString = resolutionStack.join(' -> '); var msg = "Could not resolve '" + name + "'."; if (message) { msg += " " + message; } msg += EOL + EOL; msg += "Resolution path: " + resolutionPathString; _this = _super.call(this, msg) || this; return _this; } return AwilixResolutionError; }(AwilixError)); /** * Creates a tokenizer for the specified source. * * @param source */ function createTokenizer(source) { var end = source.length; var pos = 0; var type = 'EOF'; var value = ''; var flags = 0 /* None */; // These are used to greedily skip as much as possible. // Whenever we reach a paren, we increment these. var parenLeft = 0; var parenRight = 0; return { next: next, done: done }; /** * Advances the tokenizer and returns the next token. */ function next(nextFlags) { if (nextFlags === void 0) { nextFlags = 0 /* None */; } flags = nextFlags; advance(); return createToken(); } /** * Advances the tokenizer state. */ function advance() { value = ''; type = 'EOF'; while (true) { if (pos >= end) { return (type = 'EOF'); } var ch = source.charAt(pos); // Whitespace is irrelevant if (isWhiteSpace(ch)) { pos++; continue; } switch (ch) { case '(': pos++; parenLeft++; return (type = ch); case ')': pos++; parenRight++; return (type = ch); case '*': pos++; return (type = ch); case ',': pos++; return (type = ch); case '=': pos++; if ((flags & 1 /* Dumb */) === 0) { // Not in dumb-mode, so attempt to skip. skipExpression(); } // We need to know that there's a default value so we can // skip it if it does not exist when resolving. return (type = ch); case '/': pos++; var nextCh = source.charAt(pos); if (nextCh === '/') { skipUntil(function (c) { return c === '\n'; }); pos++; } if (nextCh === '*') { skipUntil(function (c) { var closing = source.charAt(pos + 1); return c === '*' && closing === '/'; }); pos++; } continue; default: // Scans an identifier. if (isIdentifierStart(ch)) { scanIdentifier(); return type; } // Elegantly skip over tokens we don't care about. pos++; } } } /** * Scans an identifier, given it's already been proven * we are ready to do so. */ function scanIdentifier() { var identStart = source.charAt(pos); var start = ++pos; while (isIdentifierPart(source.charAt(pos))) { pos++; } value = '' + identStart + source.substring(start, pos); type = value === 'function' || value === 'class' ? value : 'ident'; if (type !== 'ident') { value = ''; } return value; } /** * Skips everything until the next comma or the end of the parameter list. * Checks the parenthesis balance so we correctly skip function calls. */ function skipExpression() { skipUntil(function (ch) { var isAtRoot = parenLeft === parenRight + 1; if (ch === ',' && isAtRoot) { return true; } if (ch === '(') { parenLeft++; return false; } if (ch === ')') { parenRight++; if (isAtRoot) { return true; } } return false; }); } /** * Skips strings and whilespace until the predicate is true. */ function skipUntil(callback) { while (pos < source.length) { var ch = source.charAt(pos); if (callback(ch)) { return; } if (isWhiteSpace(ch)) { pos++; continue; } if (isStringQuote(ch)) { skipString(); continue; } pos++; } } /** * Given the current position is at a string quote, skips the entire string. */ function skipString() { var quote = source.charAt(pos); pos++; while (pos < source.length) { var ch = source.charAt(pos); var prev = source.charAt(pos - 1); // Checks if the quote was escaped. if (ch === quote && prev !== '\\') { pos++; return; } // Template strings are a bit tougher, we want to skip the interpolated values. if (quote === '`') { var next_1 = source.charAt(pos + 1); if (next_1 === '$') { var afterDollar = source.charAt(pos + 2); if (afterDollar === '{') { // This is the start of an interpolation; skip the ${ pos = pos + 2; // Skip strings and whitespace until we reach the ending }. // This includes skipping nested interpolated strings. :D skipUntil(function (ch) { return ch === '}'; }); } } } pos++; } } /** * Creates a token from the current state. */ function createToken() { if (value) { return { value: value, type: type }; } return { type: type }; } /** * Determines if we are done parsing. */ function done() { return type === 'EOF'; } } /** * Determines if the given character is a whitespace character. * * @param {string} ch * @return {Boolean} */ function isWhiteSpace(ch) { switch (ch) { case '\r': case '\n': case ' ': return true; } return false; } /** * Determines if the specified character is a string quote. * @param {string} ch * @return {Boolean} */ function isStringQuote(ch) { switch (ch) { case "'": case '"': case '`': return true; } return false; } // NOTE: I've added the `.` character so that member expression paths // are seen as identifiers. This is so we don't get a constructor token for // stuff like `MyClass.prototype.constructor()` var IDENT_START_EXPR = /^[_$a-zA-Z\xA0-\uFFFF]$/; var IDENT_PART_EXPR = /^[._$a-zA-Z0-9\xA0-\uFFFF]$/; /** * Determines if the character is a valid JS identifier start character. */ function isIdentifierStart(ch) { return IDENT_START_EXPR.test(ch); } /** * Determines if the character is a valid JS identifier start character. */ function isIdentifierPart(ch) { return IDENT_PART_EXPR.test(ch); } /** * Creates a { name: value } object if the input isn't already in that format. * * @param {string|object} name * Either a string or an object. * * @param {*} value * The value, only used if name is not an object. * * @return {object} */ function nameValueToObject(name, value) { var _a; var obj = name; if (typeof obj === 'string' || typeof obj === 'symbol') { return _a = {}, _a[name] = value, _a; } return obj; } /** * Returns the last item in the array. * * @param {*[]} arr * The array. * * @return {*} * The last element. */ function last(arr) { return arr[arr.length - 1]; } /** * Determines if the given function is a class. * * @param {Function} fn * @return {Boolean} */ function isClass(fn) { /*tslint:disable-next-line*/ if (typeof fn !== 'function') { return false; } // Should only need 2 tokens. var tokenizer = createTokenizer(fn.toString()); var first = tokenizer.next(); if (first.type === 'class') { return true; } var second = tokenizer.next(); if (first.type === 'function' && second.value) { if (second.value[0] === second.value[0].toUpperCase()) { return true; } } return false; } /** * Determines if the given value is a function. * * @param {Any} val * Any value to check if it's a function. * * @return {Boolean} * true if the value is a function, false otherwise. */ function isFunction(val) { return typeof val === 'function'; } /** * Returns the unique items in the array. * * @param {Array<T>} * The array to remove dupes from. * * @return {Array<T>} * The deduped array. */ function uniq(arr) { var result = []; for (var idx in arr) { var item = arr[idx]; if (result.indexOf(item) === -1) { result.push(item); } } return result; } /** * 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' }; /* * Parses the parameter list of a function string, including ES6 class constructors. * * @param {string} source * The source of a function to extract the parameter list from * * @return {Array<Parameter>} * Returns an array of parameters. */ function parseParameterList(source) { var _a = createTokenizer(source), _next = _a.next, done = _a.done; var params = []; var t = null; nextToken(); while (!done()) { switch (t.type) { case 'class': skipUntilConstructor(); // Next token is the constructor identifier. nextToken(); break; case 'function': var next = nextToken(); if (next.type === 'ident' || next.type === '*') { // This is the function name or a generator star. Skip it. nextToken(); } break; case '(': // Start parsing parameter names. parseParams(); break; case ')': // We're now out of the parameter list. return params; case 'ident': // Likely a paren-less arrow function // which can have no default args. var param = { name: t.value, optional: false }; if (t.value === 'async') { // Given it's the very first token, we can assume it's an async function, // so skip the async keyword if the next token is not an equals sign, in which // case it is a single-arg arrow func. var next_1 = nextToken(); if (next_1 && next_1.type !== '=') { break; } } params.push(param); return params; /* istanbul ignore next */ default: throw unexpected(); } } return params; /** * After having been placed within the parameter list of * a function, parses the parameters. */ function parseParams() { // Current token is a left-paren var param = { name: '', optional: false }; while (!done()) { nextToken(); switch (t.type) { case 'ident': param.name = t.value; break; case '=': param.optional = true; break; case ',': params.push(param); param = { name: '', optional: false }; break; case ')': if (param.name) { params.push(param); } return; /* istanbul ignore next */ default: throw unexpected(); } } } /** * Skips until we reach the constructor identifier. */ function skipUntilConstructor() { while (!isConstructorToken() && !done()) { nextToken(1 /* Dumb */); } } /** * Determines if the current token represents a constructor, and the next token after it is a paren */ function isConstructorToken() { return t.type === 'ident' && t.value === 'constructor'; } /** * Advances the tokenizer and stores the previous token in history */ function nextToken(flags) { if (flags === void 0) { flags = 0 /* None */; } t = _next(flags); return t; } /** * Returns an error describing an unexpected token. */ /* istanbul ignore next */ function unexpected() { return new SyntaxError("Parsing parameter list, did not expect " + t.type + " token" + (t.value ? " (" + t.value + ")" : '')); } } /** * RESOLVER symbol can be used by modules loaded by * `loadModules` to configure their lifetime, injection mode, etc. */ var RESOLVER = Symbol('Awilix Resolver Config'); /** * Creates a simple value resolver where the given value will always be resolved. * * @param {string} name * The name to register the value as. * * @param {*} value * The value to resolve. * * @return {object} * The resolver. */ function asValue(value) { return { resolve: function () { return value; } }; } /** * Creates a factory resolver, where the given factory function * will be invoked with `new` when requested. * * @param {string} name * The name to register the value as. * * @param {Function} fn * The function to register. * * @param {object} opts * Additional options for the resolver. * * @return {object} * The resolver. */ function asFunction(fn, opts) { if (!isFunction(fn)) { throw new AwilixTypeError('asFunction', 'fn', 'function', fn); } var defaults = { lifetime: Lifetime.TRANSIENT }; opts = makeOptions(defaults, opts, fn[RESOLVER]); var resolve = generateResolve(fn); var result = __assign({ resolve: resolve }, opts); return createDisposableResolver(createBuildResolver(result)); } /** * Like a factory resolver, but for classes that require `new`. * * @param {string} name * The name to register the value as. * * @param {Class} Type * The function to register. * * @param {object} opts * Additional options for the resolver. * * @return {object} * The resolver. */ function asClass(Type, opts) { if (!isFunction(Type)) { throw new AwilixTypeError('asClass', 'Type', 'class', Type); } var defaults = { lifetime: Lifetime.TRANSIENT }; opts = makeOptions(defaults, opts, Type[RESOLVER]); // A function to handle object construction for us, as to make the generateResolve more reusable var newClass = function newClass() { return Reflect.construct(Type, arguments); }; var resolve = makeResolveLazy(generateResolve(newClass, Type)); return createDisposableResolver(createBuildResolver(__assign({}, opts, { resolve: resolve }))); } /** * Resolves to the specified registration. */ function aliasTo(name) { return { resolve: function (container) { return container.resolve(name); } }; } /** * Given an options object, creates a fluid interface * to manage it. * * @param {*} obj * The object to return. * * @return {object} * The interface. */ function createBuildResolver(obj) { function setLifetime(value) { return createBuildResolver(__assign({}, this, { lifetime: value })); } function setInjectionMode(value) { return createBuildResolver(__assign({}, this, { injectionMode: value })); } function inject(injector) { return createBuildResolver(__assign({}, this, { injector: injector })); } return updateResolver(obj, { setLifetime: setLifetime, inject: inject, transient: partial(setLifetime, Lifetime.TRANSIENT), scoped: partial(setLifetime, Lifetime.SCOPED), singleton: partial(setLifetime, Lifetime.SINGLETON), setInjectionMode: setInjectionMode, proxy: partial(setInjectionMode, InjectionMode.PROXY), classic: partial(setInjectionMode, InjectionMode.CLASSIC) }); } /** * Given a resolver, returns an object with methods to manage the disposer * function. * @param obj */ function createDisposableResolver(obj) { function disposer(dispose) { return createDisposableResolver(__assign({}, this, { dispose: dispose })); } return updateResolver(obj, { disposer: disposer }); } /** * Partially apply arguments to the given function. */ function partial(fn, arg1) { return function partiallyApplied() { return fn.call(this, arg1); }; } /** * Makes an options object based on defaults. * * @param {object} defaults * Default options. * * @param {...} rest * The input to check and possibly assign to the resulting object * * @return {object} */ 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)); } /** * Creates a new resolver with props merged from both. * * @param source * @param target */ function updateResolver(source, target) { var result = __assign({}, source, target); return result; } /** * Returns a wrapped `resolve` function that provides values * from the injector and defers to `container.resolve`. * * @param {AwilixContainer} container * @param {Object} locals * @return {Function} */ function wrapWithLocals(container, locals) { return function wrappedResolve(name, resolveOpts) { if (name in locals) { return locals[name]; } return container.resolve(name, resolveOpts); }; } /** * Returns a new Proxy that checks the result from `injector` * for values before delegating to the actual container. * * @param {Object} cradle * @param {Function} injector * @return {Proxy} */ function createInjectorProxy(container, injector) { 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. var proxy = new Proxy({}, { /** * Resolves the value by first checking the locals, then the container. */ get: function (target, name) { if (name === Symbol.iterator) { 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*/]; } }); }; } if (name in locals) { return locals[name]; } return container.resolve(name); }, /** * Used for `Object.keys`. */ ownKeys: function () { return allKeys; }, /** * Used for `Object.keys`. */ getOwnPropertyDescriptor: function (target, key) { if (allKeys.indexOf(key) > -1) { return { enumerable: true, configurable: true }; } return undefined; } }); return proxy; } /** * Makes dependency resolution lazy by wrapping the resolved value of original resolve function in a Proxy object * * @this {Registration} * The `this` context is a resolver. * * @param {Function} originalResolve * The original function for dependency resolution * * @return {Function} * The function used for lazy dependency resolution */ function makeResolveLazy(originalResolve) { var resolved = null; return function resolve(container) { var self = this; return new Proxy({}, { construct: function (_, argArray, newTarget) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.construct(resolved, argArray, newTarget); }, defineProperty: function (_, p, attributes) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.defineProperty(resolved, p, attributes); }, deleteProperty: function (_, propertyKey) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.deleteProperty(resolved, propertyKey); }, enumerate: function (_) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.enumerate(resolved); }, get: function (_, name) { if (!resolved) { resolved = originalResolve.call(self, container); } return resolved[name]; }, getOwnPropertyDescriptor: function (_, p) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.getOwnPropertyDescriptor(resolved, p); }, getPrototypeOf: function () { if (!resolved) { resolved = originalResolve.call(self, container); } return Object.getPrototypeOf(resolved); }, has: function (_, p) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.has(resolved, p); }, isExtensible: function () { if (!resolved) { resolved = originalResolve.call(self, container); } return resolved.isExtensible(); }, ownKeys: function (_) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.ownKeys(resolved); }, preventExtensions: function (_) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.preventExtensions(resolved); }, set: function (_, p, value) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.set(resolved, p, value); }, setPrototypeOf: function (_, proto) { if (!resolved) { resolved = originalResolve.call(self, container); } return Reflect.setPrototypeOf(resolved, proto); } }); }; } /** * Returns a resolve function used to construct the dependency graph * * @this {Registration} * The `this` context is a resolver. * * @param {Function} fn * The function to construct * * @param {Function} dependencyParseTarget * The function to parse for the dependencies of the construction target * * @param {boolean} isFunction * Is the resolution target an actual function or a mask for a constructor? * * @return {Function} * The function used for dependency resolution */ function generateResolve(fn, dependencyParseTarget) { // If the function used for dependency parsing is falsy, use the supplied function if (!dependencyParseTarget) { dependencyParseTarget = fn; } // Parse out the dependencies // NOTE: we do this regardless of whether PROXY is used or not, // because if this fails, we want it to fail early (at startup) rather // than at resolution time. var dependencies = parseDependencies(dependencyParseTarget); // Use a regular function instead of an arrow function to facilitate binding to the resolver. return function resolve(container) { // Because the container holds a global reolutionMode we need to determine it in the proper order of precedence: // resolver -> container -> default value var injectionMode = this.injectionMode || container.options.injectionMode || InjectionMode.PROXY; if (injectionMode !== InjectionMode.CLASSIC) { // If we have a custom injector, we need to wrap the cradle. var cradle = this.injector ? createInjectorProxy(container, this.injector) : container.cradle; // Return the target injected with the cradle return fn(cradle); } // We have dependencies so we need to resolve them manually if (dependencies.length > 0) { var resolve_1 = this.injector ? wrapWithLocals(container, this.injector(container)) : container.resolve; var children = dependencies.map(function (p) { return resolve_1(p.name, { allowUnregistered: p.optional }); }); return fn.apply(void 0, children); } return fn(); }; } /** * Parses the dependencies from the given function. * If it's a class and has an extends clause, and no reported dependencies, attempt to parse it's super constructor. */ function parseDependencies(fn) { var result = parseParameterList(fn.toString()); if (result.length > 0) { return result; } var parent = Object.getPrototypeOf(fn); if (typeof parent === 'function' && parent !== Function.prototype) { // Try to parse the parent return parseDependencies(parent); } return result; } /** * Family tree symbol. * @type {Symbol} */ var FAMILY_TREE = Symbol('familyTree'); /** * Roll Up Registrations symbol. * @type {Symbol} */ var ROLL_UP_REGISTRATIONS = Symbol('rollUpRegistrations'); /** * Creates an Awilix container instance. * * @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'. * * @return {object} * The container. */ function createContainer(options, parentContainer) { 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 = []; // For performance reasons, we store // the rolled-up registrations when starting a resolve. var computedRegistrations = null; // Internal registration store for this container. var registrations = {}; /** * The `Proxy` that is passed to functions so they can resolve their dependencies without * knowing where they come from. I call it the "cradle" because * it is where registered things come to life at resolution-time. */ var cradle = new Proxy({ /* removed in browser build */ }, { /** * The `get` handler is invoked whenever a get-call for `container.cradle.*` is made. * * @param {object} target * The proxy target. Irrelevant. * * @param {string} name * The property name. * * @return {*} * Whatever the resolve call returns. */ get: function (target, name) { return resolve(name); }, /** * Setting things on the cradle throws an error. * * @param {object} target * @param {string} name */ set: function (_target, name, value) { throw new Error("Attempted setting property \"" + name + "\" on container cradle - this is not allowed."); }, /** * Used for `Object.keys`. */ ownKeys: function () { return Array.from(cradle); }, /** * Used for `Object.keys`. */ getOwnPropertyDescriptor: function (target, key) { var regs = rollUpRegistrations(); if (Object.getOwnPropertyDescriptor(regs, key)) { return { enumerable: true, configurable: true }; } return undefined; } }); // The container being exposed. 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, has: has, dispose: dispose }, /* removed in browser build */ // tslint:disable-next-line _a[ROLL_UP_REGISTRATIONS] = rollUpRegistrations, Object.defineProperty(_a, "registrations", { get: function () { return rollUpRegistrations(); }, enumerable: true, configurable: true }), _a); // Track the family tree. var familyTree = parentContainer ? [container].concat(parentContainer[FAMILY_TREE]) : [container]; container[FAMILY_TREE] = familyTree; // We need a reference to the root container, // so we can retrieve and store singletons. var rootContainer = last(familyTree); return container; /** * Used by util.inspect (which is used by console.log). */ function inspect(depth, opts) { return "[AwilixContainer (" + (parentContainer ? 'scoped, ' : '') + "registrations: " + Object.keys(container.registrations).length + ")]"; } /** * Rolls up registrations from the family tree. * This is cached until `bustCache` clears it. * * @param {boolean} bustCache * Forces a recomputation. * * @return {object} * The merged registrations object. */ function rollUpRegistrations(bustCache) { if (bustCache === void 0) { bustCache = false; } if (computedRegistrations && !bustCache) { return computedRegistrations; } computedRegistrations = __assign({}, (parentContainer && parentContainer[ROLL_UP_REGISTRATIONS](bustCache)), registrations); return computedRegistrations; } /** * Used for providing an iterator to the cradle. */ 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*/]; } }); } /** * Creates a scoped container. * * @return {object} * The scoped container. */ function createScope() { return createContainer(options, container); } /** * Adds a registration for a resolver. */ function register(arg1, arg2) { 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; } // Invalidates the computed registrations. computedRegistrations = null; return container;