UNPKG

70.5 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'tslib'], factory) :
4 (global = global || self, factory(global['injection-js'] = {}, global.tslib));
5}(this, (function (exports, tslib) { 'use strict';
6
7 var globalScope;
8 if (typeof window === 'undefined') {
9 if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
10 // TODO: Replace any with WorkerGlobalScope from lib.webworker.d.ts #3492
11 globalScope = self;
12 }
13 else {
14 globalScope = global;
15 }
16 }
17 else {
18 globalScope = window;
19 }
20 // Need to declare a new variable for global here since TypeScript
21 // exports the original value of the symbol.
22 var _global = globalScope;
23 function stringify(token) {
24 if (typeof token === 'string') {
25 return token;
26 }
27 if (token == null) {
28 return '' + token;
29 }
30 if (token.overriddenName) {
31 return "" + token.overriddenName;
32 }
33 if (token.name) {
34 return "" + token.name;
35 }
36 var res = token.toString();
37 var newLineIndex = res.indexOf('\n');
38 return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
39 }
40
41 /**
42 * @license
43 * Copyright Google Inc. All Rights Reserved.
44 *
45 * Use of this source code is governed by an MIT-style license that can be
46 * found in the LICENSE file at https://angular.io/license
47 */
48 var _nextClassId = 0;
49 var Reflect = _global['Reflect'];
50 function extractAnnotation(annotation) {
51 if (typeof annotation === 'function' && annotation.hasOwnProperty('annotation')) {
52 // it is a decorator, extract annotation
53 annotation = annotation.annotation;
54 }
55 return annotation;
56 }
57 function applyParams(fnOrArray, key) {
58 if (fnOrArray === Object || fnOrArray === String || fnOrArray === Function || fnOrArray === Number || fnOrArray === Array) {
59 throw new Error("Can not use native " + stringify(fnOrArray) + " as constructor");
60 }
61 if (typeof fnOrArray === 'function') {
62 return fnOrArray;
63 }
64 if (Array.isArray(fnOrArray)) {
65 var annotations = fnOrArray;
66 var annoLength = annotations.length - 1;
67 var fn = fnOrArray[annoLength];
68 if (typeof fn !== 'function') {
69 throw new Error("Last position of Class method array must be Function in key " + key + " was '" + stringify(fn) + "'");
70 }
71 if (annoLength !== fn.length) {
72 throw new Error("Number of annotations (" + annoLength + ") does not match number of arguments (" + fn.length + ") in the function: " + stringify(fn));
73 }
74 var paramsAnnotations = [];
75 for (var i = 0, ii = annotations.length - 1; i < ii; i++) {
76 var paramAnnotations = [];
77 paramsAnnotations.push(paramAnnotations);
78 var annotation = annotations[i];
79 if (Array.isArray(annotation)) {
80 for (var j = 0; j < annotation.length; j++) {
81 paramAnnotations.push(extractAnnotation(annotation[j]));
82 }
83 }
84 else if (typeof annotation === 'function') {
85 paramAnnotations.push(extractAnnotation(annotation));
86 }
87 else {
88 paramAnnotations.push(annotation);
89 }
90 }
91 Reflect.defineMetadata('parameters', paramsAnnotations, fn);
92 return fn;
93 }
94 throw new Error("Only Function or Array is supported in Class definition for key '" + key + "' is '" + stringify(fnOrArray) + "'");
95 }
96 /**
97 * Provides a way for expressing ES6 classes with parameter annotations in ES5.
98 *
99 * ## Basic Example
100 *
101 * ```
102 * var Greeter = ng.Class({
103 * constructor: function(name) {
104 * this.name = name;
105 * },
106 *
107 * greet: function() {
108 * alert('Hello ' + this.name + '!');
109 * }
110 * });
111 * ```
112 *
113 * is equivalent to ES6:
114 *
115 * ```
116 * class Greeter {
117 * constructor(name) {
118 * this.name = name;
119 * }
120 *
121 * greet() {
122 * alert('Hello ' + this.name + '!');
123 * }
124 * }
125 * ```
126 *
127 * or equivalent to ES5:
128 *
129 * ```
130 * var Greeter = function (name) {
131 * this.name = name;
132 * }
133 *
134 * Greeter.prototype.greet = function () {
135 * alert('Hello ' + this.name + '!');
136 * }
137 * ```
138 *
139 * ### Example with parameter annotations
140 *
141 * ```
142 * var MyService = ng.Class({
143 * constructor: [String, [new Optional(), Service], function(name, myService) {
144 * ...
145 * }]
146 * });
147 * ```
148 *
149 * is equivalent to ES6:
150 *
151 * ```
152 * class MyService {
153 * constructor(name: string, @Optional() myService: Service) {
154 * ...
155 * }
156 * }
157 * ```
158 *
159 * ### Example with inheritance
160 *
161 * ```
162 * var Shape = ng.Class({
163 * constructor: (color) {
164 * this.color = color;
165 * }
166 * });
167 *
168 * var Square = ng.Class({
169 * extends: Shape,
170 * constructor: function(color, size) {
171 * Shape.call(this, color);
172 * this.size = size;
173 * }
174 * });
175 * ```
176 * @suppress {globalThis}
177 * @stable
178 */
179 function Class(clsDef) {
180 var constructor = applyParams(clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor');
181 var proto = constructor.prototype;
182 if (clsDef.hasOwnProperty('extends')) {
183 if (typeof clsDef.extends === 'function') {
184 constructor.prototype = proto = Object.create(clsDef.extends.prototype);
185 }
186 else {
187 throw new Error("Class definition 'extends' property must be a constructor function was: " + stringify(clsDef.extends));
188 }
189 }
190 for (var key in clsDef) {
191 if (key !== 'extends' && key !== 'prototype' && clsDef.hasOwnProperty(key)) {
192 proto[key] = applyParams(clsDef[key], key);
193 }
194 }
195 if (this && this.annotations instanceof Array) {
196 Reflect.defineMetadata('annotations', this.annotations, constructor);
197 }
198 var constructorName = constructor['name'];
199 if (!constructorName || constructorName === 'constructor') {
200 constructor['overriddenName'] = "class" + _nextClassId++;
201 }
202 return constructor;
203 }
204 /**
205 * @suppress {globalThis}
206 */
207 function makeDecorator(name, props, parentClass, chainFn) {
208 var metaCtor = makeMetadataCtor([props]);
209 function DecoratorFactory(objOrType) {
210 if (!(Reflect && Reflect.getOwnMetadata)) {
211 throw 'reflect-metadata shim is required when using class decorators';
212 }
213 if (this instanceof DecoratorFactory) {
214 metaCtor.call(this, objOrType);
215 return this;
216 }
217 var annotationInstance = new DecoratorFactory(objOrType);
218 var chainAnnotation = typeof this === 'function' && Array.isArray(this.annotations) ? this.annotations : [];
219 chainAnnotation.push(annotationInstance);
220 var TypeDecorator = function TypeDecorator(cls) {
221 var annotations = Reflect.getOwnMetadata('annotations', cls) || [];
222 annotations.push(annotationInstance);
223 Reflect.defineMetadata('annotations', annotations, cls);
224 return cls;
225 };
226 TypeDecorator.annotations = chainAnnotation;
227 TypeDecorator.Class = Class;
228 if (chainFn)
229 chainFn(TypeDecorator);
230 return TypeDecorator;
231 }
232 if (parentClass) {
233 DecoratorFactory.prototype = Object.create(parentClass.prototype);
234 }
235 DecoratorFactory.prototype.toString = function () { return "@" + name; };
236 DecoratorFactory.annotationCls = DecoratorFactory;
237 return DecoratorFactory;
238 }
239 function makeMetadataCtor(props) {
240 return function ctor() {
241 var _this = this;
242 var args = [];
243 for (var _i = 0; _i < arguments.length; _i++) {
244 args[_i] = arguments[_i];
245 }
246 props.forEach(function (prop, i) {
247 var argVal = args[i];
248 if (Array.isArray(prop)) {
249 // plain parameter
250 _this[prop[0]] = argVal === undefined ? prop[1] : argVal;
251 }
252 else {
253 for (var propName in prop) {
254 _this[propName] = argVal && argVal.hasOwnProperty(propName) ? argVal[propName] : prop[propName];
255 }
256 }
257 });
258 };
259 }
260 function makeParamDecorator(name, props, parentClass) {
261 var metaCtor = makeMetadataCtor(props);
262 function ParamDecoratorFactory() {
263 var _a;
264 var args = [];
265 for (var _i = 0; _i < arguments.length; _i++) {
266 args[_i] = arguments[_i];
267 }
268 if (this instanceof ParamDecoratorFactory) {
269 metaCtor.apply(this, args);
270 return this;
271 }
272 var annotationInstance = new ((_a = ParamDecoratorFactory).bind.apply(_a, tslib.__spreadArrays([void 0], args)))();
273 ParamDecorator.annotation = annotationInstance;
274 return ParamDecorator;
275 function ParamDecorator(cls, unusedKey, index) {
276 var parameters = Reflect.getOwnMetadata('parameters', cls) || [];
277 // there might be gaps if some in between parameters do not have annotations.
278 // we pad with nulls.
279 while (parameters.length <= index) {
280 parameters.push(null);
281 }
282 parameters[index] = parameters[index] || [];
283 parameters[index].push(annotationInstance);
284 Reflect.defineMetadata('parameters', parameters, cls);
285 return cls;
286 }
287 }
288 if (parentClass) {
289 ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
290 }
291 ParamDecoratorFactory.prototype.toString = function () { return "@" + name; };
292 ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
293 return ParamDecoratorFactory;
294 }
295 function makePropDecorator(name, props, parentClass) {
296 var metaCtor = makeMetadataCtor(props);
297 function PropDecoratorFactory() {
298 var _a;
299 var args = [];
300 for (var _i = 0; _i < arguments.length; _i++) {
301 args[_i] = arguments[_i];
302 }
303 if (this instanceof PropDecoratorFactory) {
304 metaCtor.apply(this, args);
305 return this;
306 }
307 var decoratorInstance = new ((_a = PropDecoratorFactory).bind.apply(_a, tslib.__spreadArrays([void 0], args)))();
308 return function PropDecorator(target, name) {
309 var meta = Reflect.getOwnMetadata('propMetadata', target.constructor) || {};
310 meta[name] = (meta.hasOwnProperty(name) && meta[name]) || [];
311 meta[name].unshift(decoratorInstance);
312 Reflect.defineMetadata('propMetadata', meta, target.constructor);
313 };
314 }
315 if (parentClass) {
316 PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
317 }
318 PropDecoratorFactory.prototype.toString = function () { return "@" + name; };
319 PropDecoratorFactory.annotationCls = PropDecoratorFactory;
320 return PropDecoratorFactory;
321 }
322
323 /**
324 * @license
325 * Copyright Google Inc. All Rights Reserved.
326 *
327 * Use of this source code is governed by an MIT-style license that can be
328 * found in the LICENSE file at https://angular.io/license
329 */
330 /**
331 * Inject decorator and metadata.
332 *
333 * @stable
334 * @Annotation
335 */
336 var Inject = makeParamDecorator('Inject', [['token', undefined]]);
337 /**
338 * Optional decorator and metadata.
339 *
340 * @stable
341 * @Annotation
342 */
343 var Optional = makeParamDecorator('Optional', []);
344 /**
345 * Injectable decorator and metadata.
346 *
347 * @stable
348 * @Annotation
349 */
350 var Injectable = makeDecorator('Injectable', []);
351 /**
352 * Self decorator and metadata.
353 *
354 * @stable
355 * @Annotation
356 */
357 var Self = makeParamDecorator('Self', []);
358 /**
359 * SkipSelf decorator and metadata.
360 *
361 * @stable
362 * @Annotation
363 */
364 var SkipSelf = makeParamDecorator('SkipSelf', []);
365 /**
366 * Host decorator and metadata.
367 *
368 * @stable
369 * @Annotation
370 */
371 var Host = makeParamDecorator('Host', []);
372
373 /**
374 * @license
375 * Copyright Google Inc. All Rights Reserved.
376 *
377 * Use of this source code is governed by an MIT-style license that can be
378 * found in the LICENSE file at https://angular.io/license
379 */
380 /**
381 * Allows to refer to references which are not yet defined.
382 *
383 * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
384 * DI is declared,
385 * but not yet defined. It is also used when the `token` which we use when creating a query is not
386 * yet defined.
387 *
388 * ### Example
389 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
390 * @experimental
391 */
392 function forwardRef(forwardRefFn) {
393 forwardRefFn.__forward_ref__ = forwardRef;
394 forwardRefFn.toString = function () {
395 return stringify(this());
396 };
397 return forwardRefFn;
398 }
399 /**
400 * Lazily retrieves the reference value from a forwardRef.
401 *
402 * Acts as the identity function when given a non-forward-ref value.
403 *
404 * ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview))
405 *
406 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
407 *
408 * See: {@link forwardRef}
409 * @experimental
410 */
411 function resolveForwardRef(type) {
412 if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__') && type.__forward_ref__ === forwardRef) {
413 return type();
414 }
415 else {
416 return type;
417 }
418 }
419
420 /**
421 * @license
422 * Copyright Google Inc. All Rights Reserved.
423 *
424 * Use of this source code is governed by an MIT-style license that can be
425 * found in the LICENSE file at https://angular.io/license
426 */
427 var _THROW_IF_NOT_FOUND = new Object();
428 var THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
429 // tslint:disable-next-line:class-name no-use-before-declare
430 var _NullInjector = /** @class */ (function () {
431 function _NullInjector() {
432 }
433 _NullInjector.prototype.get = function (token, notFoundValue) {
434 if (notFoundValue === void 0) { notFoundValue = _THROW_IF_NOT_FOUND; }
435 if (notFoundValue === _THROW_IF_NOT_FOUND) {
436 throw new Error("No provider for " + stringify(token) + "!");
437 }
438 return notFoundValue;
439 };
440 return _NullInjector;
441 }());
442 /**
443 * @whatItDoes Injector interface
444 * @howToUse
445 * ```
446 * const injector: Injector = ...;
447 * injector.get(...);
448 * ```
449 *
450 * @description
451 * For more details, see the {@linkDocs guide/dependency-injection "Dependency Injection Guide"}.
452 *
453 * ### Example
454 *
455 * {@example core/di/ts/injector_spec.ts region='Injector'}
456 *
457 * `Injector` returns itself when given `Injector` as a token:
458 * {@example core/di/ts/injector_spec.ts region='injectInjector'}
459 *
460 * @stable
461 */
462 var Injector = /** @class */ (function () {
463 function Injector() {
464 }
465 Injector.THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
466 Injector.NULL = new _NullInjector();
467 return Injector;
468 }());
469
470 /**
471 * @license
472 * Copyright Google Inc. All Rights Reserved.
473 *
474 * Use of this source code is governed by an MIT-style license that can be
475 * found in the LICENSE file at https://angular.io/license
476 */
477 var ERROR_ORIGINAL_ERROR = 'ngOriginalError';
478 function getOriginalError(error) {
479 return error[ERROR_ORIGINAL_ERROR];
480 }
481 function wrappedError(message, originalError) {
482 var msg = message + " caused by: " + (originalError instanceof Error ? originalError.message : originalError);
483 var error = Error(msg);
484 error[ERROR_ORIGINAL_ERROR] = originalError;
485 return error;
486 }
487
488 /**
489 * @license
490 * Copyright Google Inc. All Rights Reserved.
491 *
492 * Use of this source code is governed by an MIT-style license that can be
493 * found in the LICENSE file at https://angular.io/license
494 */
495 function findFirstClosedCycle(keys) {
496 var res = [];
497 for (var i = 0; i < keys.length; ++i) {
498 if (res.indexOf(keys[i]) > -1) {
499 res.push(keys[i]);
500 return res;
501 }
502 res.push(keys[i]);
503 }
504 return res;
505 }
506 function constructResolvingPath(keys) {
507 if (keys.length > 1) {
508 var reversed = findFirstClosedCycle(keys.slice().reverse());
509 var tokenStrs = reversed.map(function (k) { return stringify(k.token); });
510 return ' (' + tokenStrs.join(' -> ') + ')';
511 }
512 return '';
513 }
514 function injectionError(injector, key, constructResolvingMessage, originalError) {
515 var error = (originalError ? wrappedError('', originalError) : Error());
516 error.addKey = addKey;
517 error.keys = [key];
518 error.injectors = [injector];
519 error.constructResolvingMessage = constructResolvingMessage;
520 error.message = error.constructResolvingMessage();
521 error[ERROR_ORIGINAL_ERROR] = originalError;
522 return error;
523 }
524 function addKey(injector, key) {
525 this.injectors.push(injector);
526 this.keys.push(key);
527 this.message = this.constructResolvingMessage();
528 }
529 /**
530 * Thrown when trying to retrieve a dependency by key from {@link Injector}, but the
531 * {@link Injector} does not have a {@link Provider} for the given key.
532 *
533 * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
534 *
535 * ```typescript
536 * class A {
537 * constructor(b:B) {}
538 * }
539 *
540 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
541 * ```
542 */
543 function noProviderError(injector, key) {
544 return injectionError(injector, key, function () {
545 var first = stringify(this.keys[0].token);
546 return "No provider for " + first + "!" + constructResolvingPath(this.keys);
547 });
548 }
549 /**
550 * Thrown when dependencies form a cycle.
551 *
552 * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
553 *
554 * ```typescript
555 * var injector = Injector.resolveAndCreate([
556 * {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
557 * {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
558 * ]);
559 *
560 * expect(() => injector.get("one")).toThrowError();
561 * ```
562 *
563 * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
564 */
565 function cyclicDependencyError(injector, key) {
566 return injectionError(injector, key, function () {
567 return "Cannot instantiate cyclic dependency!" + constructResolvingPath(this.keys);
568 });
569 }
570 /**
571 * Thrown when a constructing type returns with an Error.
572 *
573 * The `InstantiationError` class contains the original error plus the dependency graph which caused
574 * this object to be instantiated.
575 *
576 * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
577 *
578 * ```typescript
579 * class A {
580 * constructor() {
581 * throw new Error('message');
582 * }
583 * }
584 *
585 * var injector = Injector.resolveAndCreate([A]);
586
587 * try {
588 * injector.get(A);
589 * } catch (e) {
590 * expect(e instanceof InstantiationError).toBe(true);
591 * expect(e.originalException.message).toEqual("message");
592 * expect(e.originalStack).toBeDefined();
593 * }
594 * ```
595 */
596 function instantiationError(injector, originalException, originalStack, key) {
597 return injectionError(injector, key, function () {
598 var first = stringify(this.keys[0].token);
599 return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + ".";
600 }, originalException);
601 }
602 /**
603 * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
604 * creation.
605 *
606 * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
607 *
608 * ```typescript
609 * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
610 * ```
611 */
612 function invalidProviderError(provider) {
613 return Error("Invalid provider - only instances of Provider and Type are allowed, got: " + provider);
614 }
615 /**
616 * Thrown when the class has no annotation information.
617 *
618 * Lack of annotation information prevents the {@link Injector} from determining which dependencies
619 * need to be injected into the constructor.
620 *
621 * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
622 *
623 * ```typescript
624 * class A {
625 * constructor(b) {}
626 * }
627 *
628 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
629 * ```
630 *
631 * This error is also thrown when the class not marked with {@link Injectable} has parameter types.
632 *
633 * ```typescript
634 * class B {}
635 *
636 * class A {
637 * constructor(b:B) {} // no information about the parameter types of A is available at runtime.
638 * }
639 *
640 * expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
641 * ```
642 * @stable
643 */
644 function noAnnotationError(typeOrFunc, params) {
645 var signature = [];
646 for (var i = 0, ii = params.length; i < ii; i++) {
647 var parameter = params[i];
648 if (!parameter || parameter.length === 0) {
649 signature.push('?');
650 }
651 else {
652 signature.push(parameter.map(stringify).join(' '));
653 }
654 }
655 return Error("Cannot resolve all parameters for '" +
656 stringify(typeOrFunc) +
657 "'(" +
658 signature.join(', ') +
659 '). ' +
660 "Make sure that all the parameters are decorated with Inject or have valid type annotations and that '" +
661 stringify(typeOrFunc) +
662 "' is decorated with Injectable.");
663 }
664 /**
665 * Thrown when getting an object by index.
666 *
667 * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
668 *
669 * ```typescript
670 * class A {}
671 *
672 * var injector = Injector.resolveAndCreate([A]);
673 *
674 * expect(() => injector.getAt(100)).toThrowError();
675 * ```
676 * @stable
677 */
678 function outOfBoundsError(index) {
679 return Error("Index " + index + " is out-of-bounds.");
680 }
681 // TODO: add a working example after alpha38 is released
682 /**
683 * Thrown when a multi provider and a regular provider are bound to the same token.
684 *
685 * ### Example
686 *
687 * ```typescript
688 * expect(() => Injector.resolveAndCreate([
689 * { provide: "Strings", useValue: "string1", multi: true},
690 * { provide: "Strings", useValue: "string2", multi: false}
691 * ])).toThrowError();
692 * ```
693 */
694 function mixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
695 return Error("Cannot mix multi providers and regular providers, got: " + provider1 + " " + provider2);
696 }
697
698 /**
699 * @license
700 * Copyright Google Inc. All Rights Reserved.
701 *
702 * Use of this source code is governed by an MIT-style license that can be
703 * found in the LICENSE file at https://angular.io/license
704 */
705 /**
706 * A unique object used for retrieving items from the {@link ReflectiveInjector}.
707 *
708 * Keys have:
709 * - a system-wide unique `id`.
710 * - a `token`.
711 *
712 * `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
713 * the
714 * injector to store created objects in a more efficient way.
715 *
716 * `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
717 * resolving
718 * providers.
719 * @experimental
720 */
721 var ReflectiveKey = /** @class */ (function () {
722 /**
723 * Private
724 */
725 function ReflectiveKey(token, id) {
726 this.token = token;
727 this.id = id;
728 if (!token) {
729 throw new Error('Token must be defined!');
730 }
731 }
732 Object.defineProperty(ReflectiveKey.prototype, "displayName", {
733 /**
734 * Returns a stringified token.
735 */
736 get: function () {
737 return stringify(this.token);
738 },
739 enumerable: false,
740 configurable: true
741 });
742 /**
743 * Retrieves a `Key` for a token.
744 */
745 ReflectiveKey.get = function (token) {
746 // tslint:disable-next-line:no-use-before-declare
747 return _globalKeyRegistry.get(resolveForwardRef(token));
748 };
749 Object.defineProperty(ReflectiveKey, "numberOfKeys", {
750 /**
751 * @returns the number of keys registered in the system.
752 */
753 get: function () {
754 // tslint:disable-next-line:no-use-before-declare
755 return _globalKeyRegistry.numberOfKeys;
756 },
757 enumerable: false,
758 configurable: true
759 });
760 return ReflectiveKey;
761 }());
762 /**
763 * @internal
764 */
765 var KeyRegistry = /** @class */ (function () {
766 function KeyRegistry() {
767 this._allKeys = new Map();
768 }
769 KeyRegistry.prototype.get = function (token) {
770 if (token instanceof ReflectiveKey)
771 return token;
772 if (this._allKeys.has(token)) {
773 return this._allKeys.get(token);
774 }
775 var newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
776 this._allKeys.set(token, newKey);
777 return newKey;
778 };
779 Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", {
780 get: function () {
781 return this._allKeys.size;
782 },
783 enumerable: false,
784 configurable: true
785 });
786 return KeyRegistry;
787 }());
788 var _globalKeyRegistry = new KeyRegistry();
789
790 /**
791 * @license
792 * Copyright Google Inc. All Rights Reserved.
793 *
794 * Use of this source code is governed by an MIT-style license that can be
795 * found in the LICENSE file at https://angular.io/license
796 */
797 /**
798 * @whatItDoes Represents a type that a Component or other object is instances of.
799 *
800 * @description
801 *
802 * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
803 * the `MyCustomComponent` constructor function.
804 *
805 * @stable
806 */
807 var Type = Function;
808 function isType(v) {
809 return typeof v === 'function';
810 }
811
812 /**
813 * @license
814 * Copyright Google Inc. All Rights Reserved.
815 *
816 * Use of this source code is governed by an MIT-style license that can be
817 * found in the LICENSE file at https://angular.io/license
818 */
819 /**
820 * Attention: This regex has to hold even if the code is minified!
821 */
822 var DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/;
823 var ReflectionCapabilities = /** @class */ (function () {
824 function ReflectionCapabilities(reflect) {
825 this._reflect = reflect || _global['Reflect'];
826 }
827 ReflectionCapabilities.prototype.isReflectionEnabled = function () {
828 return true;
829 };
830 ReflectionCapabilities.prototype.factory = function (t) {
831 return function () {
832 var args = [];
833 for (var _i = 0; _i < arguments.length; _i++) {
834 args[_i] = arguments[_i];
835 }
836 return new (t.bind.apply(t, tslib.__spreadArrays([void 0], args)))();
837 };
838 };
839 /** @internal */
840 ReflectionCapabilities.prototype._zipTypesAndAnnotations = function (paramTypes, paramAnnotations) {
841 var result;
842 if (typeof paramTypes === 'undefined') {
843 result = new Array(paramAnnotations.length);
844 }
845 else {
846 result = new Array(paramTypes.length);
847 }
848 for (var i = 0; i < result.length; i++) {
849 // TS outputs Object for parameters without types, while Traceur omits
850 // the annotations. For now we preserve the Traceur behavior to aid
851 // migration, but this can be revisited.
852 if (typeof paramTypes === 'undefined') {
853 result[i] = [];
854 // tslint:disable-next-line:triple-equals
855 }
856 else if (paramTypes[i] != Object) {
857 result[i] = [paramTypes[i]];
858 }
859 else {
860 result[i] = [];
861 }
862 if (paramAnnotations && paramAnnotations[i] != null) {
863 result[i] = result[i].concat(paramAnnotations[i]);
864 }
865 }
866 return result;
867 };
868 ReflectionCapabilities.prototype._ownParameters = function (type, parentCtor) {
869 // If we have no decorators, we only have function.length as metadata.
870 // In that case, to detect whether a child class declared an own constructor or not,
871 // we need to look inside of that constructor to check whether it is
872 // just calling the parent.
873 // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
874 // that sets 'design:paramtypes' to []
875 // if a class inherits from another class but has no ctor declared itself.
876 if (DELEGATE_CTOR.exec(type.toString())) {
877 return null;
878 }
879 // Prefer the direct API.
880 if (type.parameters && type.parameters !== parentCtor.parameters) {
881 return type.parameters;
882 }
883 // API of tsickle for lowering decorators to properties on the class.
884 var tsickleCtorParams = type.ctorParameters;
885 if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
886 // Newer tsickle uses a function closure
887 // Retain the non-function case for compatibility with older tsickle
888 var ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
889 var paramTypes = ctorParameters.map(function (ctorParam) { return ctorParam && ctorParam.type; });
890 var paramAnnotations = ctorParameters.map(function (ctorParam) { return ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators); });
891 return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
892 }
893 // API for metadata created by invoking the decorators.
894 if (this._reflect != null && this._reflect.getOwnMetadata != null) {
895 var paramAnnotations = this._reflect.getOwnMetadata('parameters', type);
896 var paramTypes = this._reflect.getOwnMetadata('design:paramtypes', type);
897 if (paramTypes || paramAnnotations) {
898 return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
899 }
900 }
901 // If a class has no decorators, at least create metadata
902 // based on function.length.
903 // Note: We know that this is a real constructor as we checked
904 // the content of the constructor above.
905 return new Array(type.length).fill(undefined);
906 };
907 ReflectionCapabilities.prototype.parameters = function (type) {
908 // Note: only report metadata if we have at least one class decorator
909 // to stay in sync with the static reflector.
910 if (!isType(type)) {
911 return [];
912 }
913 var parentCtor = getParentCtor(type);
914 var parameters = this._ownParameters(type, parentCtor);
915 if (!parameters && parentCtor !== Object) {
916 parameters = this.parameters(parentCtor);
917 }
918 return parameters || [];
919 };
920 ReflectionCapabilities.prototype._ownAnnotations = function (typeOrFunc, parentCtor) {
921 // Prefer the direct API.
922 if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
923 var annotations = typeOrFunc.annotations;
924 if (typeof annotations === 'function' && annotations.annotations) {
925 annotations = annotations.annotations;
926 }
927 return annotations;
928 }
929 // API of tsickle for lowering decorators to properties on the class.
930 if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
931 return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
932 }
933 // API for metadata created by invoking the decorators.
934 if (this._reflect && this._reflect.getOwnMetadata) {
935 return this._reflect.getOwnMetadata('annotations', typeOrFunc);
936 }
937 return null;
938 };
939 ReflectionCapabilities.prototype.annotations = function (typeOrFunc) {
940 if (!isType(typeOrFunc)) {
941 return [];
942 }
943 var parentCtor = getParentCtor(typeOrFunc);
944 var ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
945 var parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
946 return parentAnnotations.concat(ownAnnotations);
947 };
948 ReflectionCapabilities.prototype._ownPropMetadata = function (typeOrFunc, parentCtor) {
949 // Prefer the direct API.
950 if (typeOrFunc.propMetadata && typeOrFunc.propMetadata !== parentCtor.propMetadata) {
951 var propMetadata = typeOrFunc.propMetadata;
952 if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
953 propMetadata = propMetadata.propMetadata;
954 }
955 return propMetadata;
956 }
957 // API of tsickle for lowering decorators to properties on the class.
958 if (typeOrFunc.propDecorators && typeOrFunc.propDecorators !== parentCtor.propDecorators) {
959 var propDecorators_1 = typeOrFunc.propDecorators;
960 var propMetadata_1 = {};
961 Object.keys(propDecorators_1).forEach(function (prop) {
962 propMetadata_1[prop] = convertTsickleDecoratorIntoMetadata(propDecorators_1[prop]);
963 });
964 return propMetadata_1;
965 }
966 // API for metadata created by invoking the decorators.
967 if (this._reflect && this._reflect.getOwnMetadata) {
968 return this._reflect.getOwnMetadata('propMetadata', typeOrFunc);
969 }
970 return null;
971 };
972 ReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
973 if (!isType(typeOrFunc)) {
974 return {};
975 }
976 var parentCtor = getParentCtor(typeOrFunc);
977 var propMetadata = {};
978 if (parentCtor !== Object) {
979 var parentPropMetadata_1 = this.propMetadata(parentCtor);
980 Object.keys(parentPropMetadata_1).forEach(function (propName) {
981 propMetadata[propName] = parentPropMetadata_1[propName];
982 });
983 }
984 var ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
985 if (ownPropMetadata) {
986 Object.keys(ownPropMetadata).forEach(function (propName) {
987 var decorators = [];
988 if (propMetadata.hasOwnProperty(propName)) {
989 decorators.push.apply(decorators, propMetadata[propName]);
990 }
991 decorators.push.apply(decorators, ownPropMetadata[propName]);
992 propMetadata[propName] = decorators;
993 });
994 }
995 return propMetadata;
996 };
997 ReflectionCapabilities.prototype.hasLifecycleHook = function (type, lcProperty) {
998 return type instanceof Type && lcProperty in type.prototype;
999 };
1000 ReflectionCapabilities.prototype.getter = function (name) {
1001 return new Function('o', 'return o.' + name + ';');
1002 };
1003 ReflectionCapabilities.prototype.setter = function (name) {
1004 return new Function('o', 'v', 'return o.' + name + ' = v;');
1005 };
1006 ReflectionCapabilities.prototype.method = function (name) {
1007 var functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);";
1008 return new Function('o', 'args', functionBody);
1009 };
1010 // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
1011 ReflectionCapabilities.prototype.importUri = function (type) {
1012 // StaticSymbol
1013 if (typeof type === 'object' && type['filePath']) {
1014 return type['filePath'];
1015 }
1016 // Runtime type
1017 return "./" + stringify(type);
1018 };
1019 ReflectionCapabilities.prototype.resourceUri = function (type) {
1020 return "./" + stringify(type);
1021 };
1022 ReflectionCapabilities.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
1023 return runtime;
1024 };
1025 ReflectionCapabilities.prototype.resolveEnum = function (enumIdentifier, name) {
1026 return enumIdentifier[name];
1027 };
1028 return ReflectionCapabilities;
1029 }());
1030 function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
1031 if (!decoratorInvocations) {
1032 return [];
1033 }
1034 return decoratorInvocations.map(function (decoratorInvocation) {
1035 var decoratorType = decoratorInvocation.type;
1036 var annotationCls = decoratorType.annotationCls;
1037 var annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
1038 return new (annotationCls.bind.apply(annotationCls, tslib.__spreadArrays([void 0], annotationArgs)))();
1039 });
1040 }
1041 function getParentCtor(ctor) {
1042 if (!ctor.prototype) {
1043 return Object;
1044 }
1045 var parentProto = Object.getPrototypeOf(ctor.prototype);
1046 var parentCtor = parentProto ? parentProto.constructor : null;
1047 // Note: We always use `Object` as the null value
1048 // to simplify checking later on.
1049 return parentCtor || Object;
1050 }
1051
1052 /**
1053 * @license
1054 * Copyright Google Inc. All Rights Reserved.
1055 *
1056 * Use of this source code is governed by an MIT-style license that can be
1057 * found in the LICENSE file at https://angular.io/license
1058 */
1059 /**
1060 * Provides read-only access to reflection data about symbols. Used internally by Angular
1061 * to power dependency injection and compilation.
1062 */
1063 var ReflectorReader = /** @class */ (function () {
1064 function ReflectorReader() {
1065 }
1066 return ReflectorReader;
1067 }());
1068
1069 /**
1070 * @license
1071 * Copyright Google Inc. All Rights Reserved.
1072 *
1073 * Use of this source code is governed by an MIT-style license that can be
1074 * found in the LICENSE file at https://angular.io/license
1075 */
1076 /**
1077 * Provides access to reflection data about symbols. Used internally by Angular
1078 * to power dependency injection and compilation.
1079 */
1080 var Reflector = /** @class */ (function (_super) {
1081 tslib.__extends(Reflector, _super);
1082 function Reflector(reflectionCapabilities) {
1083 var _this = _super.call(this) || this;
1084 _this.reflectionCapabilities = reflectionCapabilities;
1085 return _this;
1086 }
1087 Reflector.prototype.updateCapabilities = function (caps) {
1088 this.reflectionCapabilities = caps;
1089 };
1090 Reflector.prototype.factory = function (type) {
1091 return this.reflectionCapabilities.factory(type);
1092 };
1093 Reflector.prototype.parameters = function (typeOrFunc) {
1094 return this.reflectionCapabilities.parameters(typeOrFunc);
1095 };
1096 Reflector.prototype.annotations = function (typeOrFunc) {
1097 return this.reflectionCapabilities.annotations(typeOrFunc);
1098 };
1099 Reflector.prototype.propMetadata = function (typeOrFunc) {
1100 return this.reflectionCapabilities.propMetadata(typeOrFunc);
1101 };
1102 Reflector.prototype.hasLifecycleHook = function (type, lcProperty) {
1103 return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
1104 };
1105 Reflector.prototype.getter = function (name) {
1106 return this.reflectionCapabilities.getter(name);
1107 };
1108 Reflector.prototype.setter = function (name) {
1109 return this.reflectionCapabilities.setter(name);
1110 };
1111 Reflector.prototype.method = function (name) {
1112 return this.reflectionCapabilities.method(name);
1113 };
1114 Reflector.prototype.importUri = function (type) {
1115 return this.reflectionCapabilities.importUri(type);
1116 };
1117 Reflector.prototype.resourceUri = function (type) {
1118 return this.reflectionCapabilities.resourceUri(type);
1119 };
1120 Reflector.prototype.resolveIdentifier = function (name, moduleUrl, members, runtime) {
1121 return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
1122 };
1123 Reflector.prototype.resolveEnum = function (identifier, name) {
1124 return this.reflectionCapabilities.resolveEnum(identifier, name);
1125 };
1126 return Reflector;
1127 }(ReflectorReader));
1128
1129 /**
1130 * @license
1131 * Copyright Google Inc. All Rights Reserved.
1132 *
1133 * Use of this source code is governed by an MIT-style license that can be
1134 * found in the LICENSE file at https://angular.io/license
1135 */
1136 /**
1137 * The {@link Reflector} used internally in Angular to access metadata
1138 * about symbols.
1139 */
1140 var reflector = new Reflector(new ReflectionCapabilities());
1141
1142 /**
1143 * @license
1144 * Copyright Google Inc. All Rights Reserved.
1145 *
1146 * Use of this source code is governed by an MIT-style license that can be
1147 * found in the LICENSE file at https://angular.io/license
1148 */
1149 /**
1150 * Creates a token that can be used in a DI Provider.
1151 *
1152 * ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
1153 *
1154 * ```typescript
1155 * var t = new OpaqueToken("value");
1156 *
1157 * var injector = Injector.resolveAndCreate([
1158 * {provide: t, useValue: "bindingValue"}
1159 * ]);
1160 *
1161 * expect(injector.get(t)).toEqual("bindingValue");
1162 * ```
1163 *
1164 * Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
1165 * caused by multiple providers using the same string as two different tokens.
1166 *
1167 * Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
1168 * error messages.
1169 * @deprecated since v4.0.0 because it does not support type information, use `InjectionToken<?>`
1170 * instead.
1171 */
1172 var OpaqueToken = /** @class */ (function () {
1173 function OpaqueToken(_desc) {
1174 this._desc = _desc;
1175 }
1176 OpaqueToken.prototype.toString = function () {
1177 return "Token " + this._desc;
1178 };
1179 return OpaqueToken;
1180 }());
1181 /**
1182 * Creates a token that can be used in a DI Provider.
1183 *
1184 * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
1185 * runtime representation) such as when injecting an interface, callable type, array or
1186 * parametrized type.
1187 *
1188 * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
1189 * the `Injector`. This provides additional level of type safety.
1190 *
1191 * ```
1192 * interface MyInterface {...}
1193 * var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
1194 * // myInterface is inferred to be MyInterface.
1195 * ```
1196 *
1197 * ### Example
1198 *
1199 * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
1200 *
1201 * @stable
1202 */
1203 var InjectionToken = /** @class */ (function (_super) {
1204 tslib.__extends(InjectionToken, _super);
1205 function InjectionToken(desc) {
1206 return _super.call(this, desc) || this;
1207 }
1208 InjectionToken.prototype.toString = function () {
1209 return "InjectionToken " + this._desc;
1210 };
1211 return InjectionToken;
1212 }(OpaqueToken));
1213
1214 /**
1215 * @license
1216 * Copyright Google Inc. All Rights Reserved.
1217 *
1218 * Use of this source code is governed by an MIT-style license that can be
1219 * found in the LICENSE file at https://angular.io/license
1220 */
1221 /**
1222 * `Dependency` is used by the framework to extend DI.
1223 * This is internal to Angular and should not be used directly.
1224 */
1225 var ReflectiveDependency = /** @class */ (function () {
1226 function ReflectiveDependency(key, optional, visibility) {
1227 this.key = key;
1228 this.optional = optional;
1229 this.visibility = visibility;
1230 }
1231 ReflectiveDependency.fromKey = function (key) {
1232 return new ReflectiveDependency(key, false, null);
1233 };
1234 return ReflectiveDependency;
1235 }());
1236 var _EMPTY_LIST = [];
1237 // tslint:disable-next-line:class-name
1238 var ResolvedReflectiveProvider_ = /** @class */ (function () {
1239 function ResolvedReflectiveProvider_(key, resolvedFactories, multiProvider) {
1240 this.key = key;
1241 this.resolvedFactories = resolvedFactories;
1242 this.multiProvider = multiProvider;
1243 }
1244 Object.defineProperty(ResolvedReflectiveProvider_.prototype, "resolvedFactory", {
1245 get: function () {
1246 return this.resolvedFactories[0];
1247 },
1248 enumerable: false,
1249 configurable: true
1250 });
1251 return ResolvedReflectiveProvider_;
1252 }());
1253 /**
1254 * An internal resolved representation of a factory function created by resolving {@link
1255 * Provider}.
1256 * @experimental
1257 */
1258 var ResolvedReflectiveFactory = /** @class */ (function () {
1259 function ResolvedReflectiveFactory(
1260 /**
1261 * Factory function which can return an instance of an object represented by a key.
1262 */
1263 factory,
1264 /**
1265 * Arguments (dependencies) to the `factory` function.
1266 */
1267 dependencies) {
1268 this.factory = factory;
1269 this.dependencies = dependencies;
1270 }
1271 return ResolvedReflectiveFactory;
1272 }());
1273 /**
1274 * Resolve a single provider.
1275 */
1276 function resolveReflectiveFactory(provider) {
1277 var factoryFn;
1278 var resolvedDeps;
1279 if (provider.useClass) {
1280 var useClass = resolveForwardRef(provider.useClass);
1281 factoryFn = reflector.factory(useClass);
1282 resolvedDeps = _dependenciesFor(useClass);
1283 }
1284 else if (provider.useExisting) {
1285 factoryFn = function (aliasInstance) { return aliasInstance; };
1286 resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
1287 }
1288 else if (provider.useFactory) {
1289 factoryFn = provider.useFactory;
1290 resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
1291 }
1292 else {
1293 factoryFn = function () { return provider.useValue; };
1294 resolvedDeps = _EMPTY_LIST;
1295 }
1296 return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
1297 }
1298 /**
1299 * Converts the {@link Provider} into {@link ResolvedProvider}.
1300 *
1301 * {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
1302 * convenience provider syntax.
1303 */
1304 function resolveReflectiveProvider(provider) {
1305 return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false);
1306 }
1307 /**
1308 * Resolve a list of Providers.
1309 */
1310 function resolveReflectiveProviders(providers) {
1311 var normalized = _normalizeProviders(providers, []);
1312 var resolved = normalized.map(resolveReflectiveProvider);
1313 var resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
1314 return Array.from(resolvedProviderMap.values());
1315 }
1316 /**
1317 * Merges a list of ResolvedProviders into a list where
1318 * each key is contained exactly once and multi providers
1319 * have been merged.
1320 */
1321 function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
1322 for (var i = 0; i < providers.length; i++) {
1323 var provider = providers[i];
1324 var existing = normalizedProvidersMap.get(provider.key.id);
1325 if (existing) {
1326 if (provider.multiProvider !== existing.multiProvider) {
1327 throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
1328 }
1329 if (provider.multiProvider) {
1330 for (var j = 0; j < provider.resolvedFactories.length; j++) {
1331 existing.resolvedFactories.push(provider.resolvedFactories[j]);
1332 }
1333 }
1334 else {
1335 normalizedProvidersMap.set(provider.key.id, provider);
1336 }
1337 }
1338 else {
1339 var resolvedProvider = void 0;
1340 if (provider.multiProvider) {
1341 resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
1342 }
1343 else {
1344 resolvedProvider = provider;
1345 }
1346 normalizedProvidersMap.set(provider.key.id, resolvedProvider);
1347 }
1348 }
1349 return normalizedProvidersMap;
1350 }
1351 function _normalizeProviders(providers, res) {
1352 providers.forEach(function (b) {
1353 if (b instanceof Type) {
1354 res.push({ provide: b, useClass: b });
1355 }
1356 else if (b && typeof b === 'object' && b.provide !== undefined) {
1357 res.push(b);
1358 }
1359 else if (b instanceof Array) {
1360 _normalizeProviders(b, res);
1361 }
1362 else {
1363 throw invalidProviderError(b);
1364 }
1365 });
1366 return res;
1367 }
1368 function constructDependencies(typeOrFunc, dependencies) {
1369 if (!dependencies) {
1370 return _dependenciesFor(typeOrFunc);
1371 }
1372 else {
1373 var params_1 = dependencies.map(function (t) { return [t]; });
1374 return dependencies.map(function (t) { return _extractToken(typeOrFunc, t, params_1); });
1375 }
1376 }
1377 function _dependenciesFor(typeOrFunc) {
1378 var params = reflector.parameters(typeOrFunc);
1379 if (!params)
1380 return [];
1381 if (params.some(function (p) { return p == null; })) {
1382 throw noAnnotationError(typeOrFunc, params);
1383 }
1384 return params.map(function (p) { return _extractToken(typeOrFunc, p, params); });
1385 }
1386 function _extractToken(typeOrFunc, metadata, params) {
1387 var token = null;
1388 var optional = false;
1389 if (!Array.isArray(metadata)) {
1390 if (metadata instanceof Inject) {
1391 return _createDependency(metadata['token'], optional, null);
1392 }
1393 else {
1394 return _createDependency(metadata, optional, null);
1395 }
1396 }
1397 var visibility = null;
1398 for (var i = 0; i < metadata.length; ++i) {
1399 var paramMetadata = metadata[i];
1400 if (paramMetadata instanceof Type) {
1401 token = paramMetadata;
1402 }
1403 else if (paramMetadata instanceof Inject) {
1404 token = paramMetadata['token'];
1405 }
1406 else if (paramMetadata instanceof Optional) {
1407 optional = true;
1408 }
1409 else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
1410 visibility = paramMetadata;
1411 }
1412 else if (paramMetadata instanceof InjectionToken) {
1413 token = paramMetadata;
1414 }
1415 }
1416 token = resolveForwardRef(token);
1417 if (token != null) {
1418 return _createDependency(token, optional, visibility);
1419 }
1420 else {
1421 throw noAnnotationError(typeOrFunc, params);
1422 }
1423 }
1424 function _createDependency(token, optional, visibility) {
1425 return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
1426 }
1427
1428 /**
1429 * @license
1430 * Copyright Google Inc. All Rights Reserved.
1431 *
1432 * Use of this source code is governed by an MIT-style license that can be
1433 * found in the LICENSE file at https://angular.io/license
1434 */
1435 // Threshold for the dynamic version
1436 var UNDEFINED = new Object();
1437 /**
1438 * A ReflectiveDependency injection container used for instantiating objects and resolving
1439 * dependencies.
1440 *
1441 * An `Injector` is a replacement for a `new` operator, which can automatically resolve the
1442 * constructor dependencies.
1443 *
1444 * In typical use, application code asks for the dependencies in the constructor and they are
1445 * resolved by the `Injector`.
1446 *
1447 * ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
1448 *
1449 * The following example creates an `Injector` configured to create `Engine` and `Car`.
1450 *
1451 * ```typescript
1452 * @Injectable()
1453 * class Engine {
1454 * }
1455 *
1456 * @Injectable()
1457 * class Car {
1458 * constructor(public engine:Engine) {}
1459 * }
1460 *
1461 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
1462 * var car = injector.get(Car);
1463 * expect(car instanceof Car).toBe(true);
1464 * expect(car.engine instanceof Engine).toBe(true);
1465 * ```
1466 *
1467 * Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
1468 * resolve all of the object's dependencies automatically.
1469 *
1470 * @stable
1471 */
1472 var ReflectiveInjector = /** @class */ (function () {
1473 function ReflectiveInjector() {
1474 }
1475 /**
1476 * Turns an array of provider definitions into an array of resolved providers.
1477 *
1478 * A resolution is a process of flattening multiple nested arrays and converting individual
1479 * providers into an array of {@link ResolvedReflectiveProvider}s.
1480 *
1481 * ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
1482 *
1483 * ```typescript
1484 * @Injectable()
1485 * class Engine {
1486 * }
1487 *
1488 * @Injectable()
1489 * class Car {
1490 * constructor(public engine:Engine) {}
1491 * }
1492 *
1493 * var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
1494 *
1495 * expect(providers.length).toEqual(2);
1496 *
1497 * expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
1498 * expect(providers[0].key.displayName).toBe("Car");
1499 * expect(providers[0].dependencies.length).toEqual(1);
1500 * expect(providers[0].factory).toBeDefined();
1501 *
1502 * expect(providers[1].key.displayName).toBe("Engine");
1503 * });
1504 * ```
1505 *
1506 * See {@link ReflectiveInjector#fromResolvedProviders} for more info.
1507 */
1508 ReflectiveInjector.resolve = function (providers) {
1509 return resolveReflectiveProviders(providers);
1510 };
1511 /**
1512 * Resolves an array of providers and creates an injector from those providers.
1513 *
1514 * The passed-in providers can be an array of `Type`, {@link Provider},
1515 * or a recursive array of more providers.
1516 *
1517 * ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
1518 *
1519 * ```typescript
1520 * @Injectable()
1521 * class Engine {
1522 * }
1523 *
1524 * @Injectable()
1525 * class Car {
1526 * constructor(public engine:Engine) {}
1527 * }
1528 *
1529 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
1530 * expect(injector.get(Car) instanceof Car).toBe(true);
1531 * ```
1532 *
1533 * This function is slower than the corresponding `fromResolvedProviders`
1534 * because it needs to resolve the passed-in providers first.
1535 * See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}.
1536 */
1537 ReflectiveInjector.resolveAndCreate = function (providers, parent) {
1538 var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
1539 return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
1540 };
1541 /**
1542 * Creates an injector from previously resolved providers.
1543 *
1544 * This API is the recommended way to construct injectors in performance-sensitive parts.
1545 *
1546 * ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
1547 *
1548 * ```typescript
1549 * @Injectable()
1550 * class Engine {
1551 * }
1552 *
1553 * @Injectable()
1554 * class Car {
1555 * constructor(public engine:Engine) {}
1556 * }
1557 *
1558 * var providers = ReflectiveInjector.resolve([Car, Engine]);
1559 * var injector = ReflectiveInjector.fromResolvedProviders(providers);
1560 * expect(injector.get(Car) instanceof Car).toBe(true);
1561 * ```
1562 * @experimental
1563 */
1564 ReflectiveInjector.fromResolvedProviders = function (providers, parent) {
1565 // tslint:disable-next-line:no-use-before-declare
1566 return new ReflectiveInjector_(providers, parent);
1567 };
1568 return ReflectiveInjector;
1569 }());
1570 // tslint:disable-next-line:class-name
1571 var ReflectiveInjector_ = /** @class */ (function () {
1572 /**
1573 * Private
1574 */
1575 function ReflectiveInjector_(_providers, _parent) {
1576 /** @internal */
1577 this._constructionCounter = 0;
1578 this._providers = _providers;
1579 this._parent = _parent || null;
1580 var len = _providers.length;
1581 this.keyIds = new Array(len);
1582 this.objs = new Array(len);
1583 for (var i = 0; i < len; i++) {
1584 this.keyIds[i] = _providers[i].key.id;
1585 this.objs[i] = UNDEFINED;
1586 }
1587 }
1588 ReflectiveInjector_.prototype.get = function (token, notFoundValue) {
1589 if (notFoundValue === void 0) { notFoundValue = THROW_IF_NOT_FOUND; }
1590 return this._getByKey(ReflectiveKey.get(token), null, notFoundValue);
1591 };
1592 Object.defineProperty(ReflectiveInjector_.prototype, "parent", {
1593 get: function () {
1594 return this._parent;
1595 },
1596 enumerable: false,
1597 configurable: true
1598 });
1599 ReflectiveInjector_.prototype.resolveAndCreateChild = function (providers) {
1600 var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
1601 return this.createChildFromResolved(ResolvedReflectiveProviders);
1602 };
1603 ReflectiveInjector_.prototype.createChildFromResolved = function (providers) {
1604 var inj = new ReflectiveInjector_(providers);
1605 inj._parent = this;
1606 return inj;
1607 };
1608 ReflectiveInjector_.prototype.resolveAndInstantiate = function (provider) {
1609 return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
1610 };
1611 ReflectiveInjector_.prototype.instantiateResolved = function (provider) {
1612 return this._instantiateProvider(provider);
1613 };
1614 ReflectiveInjector_.prototype.getProviderAtIndex = function (index) {
1615 if (index < 0 || index >= this._providers.length) {
1616 throw outOfBoundsError(index);
1617 }
1618 return this._providers[index];
1619 };
1620 /** @internal */
1621 ReflectiveInjector_.prototype._new = function (provider) {
1622 if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
1623 throw cyclicDependencyError(this, provider.key);
1624 }
1625 return this._instantiateProvider(provider);
1626 };
1627 ReflectiveInjector_.prototype._getMaxNumberOfObjects = function () {
1628 return this.objs.length;
1629 };
1630 ReflectiveInjector_.prototype._instantiateProvider = function (provider) {
1631 if (provider.multiProvider) {
1632 var res = new Array(provider.resolvedFactories.length);
1633 for (var i = 0; i < provider.resolvedFactories.length; ++i) {
1634 res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
1635 }
1636 return res;
1637 }
1638 else {
1639 return this._instantiate(provider, provider.resolvedFactories[0]);
1640 }
1641 };
1642 ReflectiveInjector_.prototype._instantiate = function (provider, ResolvedReflectiveFactory) {
1643 var _this = this;
1644 var factory = ResolvedReflectiveFactory.factory;
1645 var deps;
1646 try {
1647 deps = ResolvedReflectiveFactory.dependencies.map(function (dep) { return _this._getByReflectiveDependency(dep); });
1648 }
1649 catch (e) {
1650 if (e.addKey) {
1651 e.addKey(this, provider.key);
1652 }
1653 throw e;
1654 }
1655 var obj;
1656 try {
1657 obj = factory.apply(void 0, deps);
1658 }
1659 catch (e) {
1660 throw instantiationError(this, e, e.stack, provider.key);
1661 }
1662 return obj;
1663 };
1664 ReflectiveInjector_.prototype._getByReflectiveDependency = function (dep) {
1665 return this._getByKey(dep.key, dep.visibility, dep.optional ? null : THROW_IF_NOT_FOUND);
1666 };
1667 ReflectiveInjector_.prototype._getByKey = function (key, visibility, notFoundValue) {
1668 // tslint:disable-next-line:no-use-before-declare
1669 if (key === INJECTOR_KEY) {
1670 return this;
1671 }
1672 if (visibility instanceof Self) {
1673 return this._getByKeySelf(key, notFoundValue);
1674 }
1675 else {
1676 return this._getByKeyDefault(key, notFoundValue, visibility);
1677 }
1678 };
1679 ReflectiveInjector_.prototype._getObjByKeyId = function (keyId) {
1680 for (var i = 0; i < this.keyIds.length; i++) {
1681 if (this.keyIds[i] === keyId) {
1682 if (this.objs[i] === UNDEFINED) {
1683 this.objs[i] = this._new(this._providers[i]);
1684 }
1685 return this.objs[i];
1686 }
1687 }
1688 return UNDEFINED;
1689 };
1690 /** @internal */
1691 ReflectiveInjector_.prototype._throwOrNull = function (key, notFoundValue) {
1692 if (notFoundValue !== THROW_IF_NOT_FOUND) {
1693 return notFoundValue;
1694 }
1695 else {
1696 throw noProviderError(this, key);
1697 }
1698 };
1699 /** @internal */
1700 ReflectiveInjector_.prototype._getByKeySelf = function (key, notFoundValue) {
1701 var obj = this._getObjByKeyId(key.id);
1702 return obj !== UNDEFINED ? obj : this._throwOrNull(key, notFoundValue);
1703 };
1704 /** @internal */
1705 ReflectiveInjector_.prototype._getByKeyDefault = function (key, notFoundValue, visibility) {
1706 var inj;
1707 if (visibility instanceof SkipSelf) {
1708 inj = this._parent;
1709 }
1710 else {
1711 inj = this;
1712 }
1713 while (inj instanceof ReflectiveInjector_) {
1714 var inj_ = inj;
1715 var obj = inj_._getObjByKeyId(key.id);
1716 if (obj !== UNDEFINED)
1717 return obj;
1718 inj = inj_._parent;
1719 }
1720 if (inj !== null) {
1721 return inj.get(key.token, notFoundValue);
1722 }
1723 else {
1724 return this._throwOrNull(key, notFoundValue);
1725 }
1726 };
1727 Object.defineProperty(ReflectiveInjector_.prototype, "displayName", {
1728 get: function () {
1729 var providers = _mapProviders(this, function (b) { return ' "' + b.key.displayName + '" '; }).join(', ');
1730 return "ReflectiveInjector(providers: [" + providers + "])";
1731 },
1732 enumerable: false,
1733 configurable: true
1734 });
1735 ReflectiveInjector_.prototype.toString = function () {
1736 return this.displayName;
1737 };
1738 return ReflectiveInjector_;
1739 }());
1740 var INJECTOR_KEY = ReflectiveKey.get(Injector);
1741 function _mapProviders(injector, fn) {
1742 var res = new Array(injector._providers.length);
1743 for (var i = 0; i < injector._providers.length; ++i) {
1744 res[i] = fn(injector.getProviderAtIndex(i));
1745 }
1746 return res;
1747 }
1748
1749 /**
1750 * This utility function receives a spread of injectable classes
1751 * and returns an array of all their dependencies. Also resolves
1752 * optional dependencies.
1753 *
1754 * ### Important:
1755 *
1756 * Dynamically resolving dependencies using this function
1757 * will not play nice with static analysis tools, including tree-shaking.
1758 * From a static analysis perspective, any dependencies which are only resolved
1759 * using this function will look as though they are not used (and will be
1760 * removed by tree-shaking). This *severely* limits the usefulness of this function.
1761 *
1762 * ### Example:
1763 *
1764 * ```typescript
1765 * class HTTP {}
1766 * class Database {}
1767 *
1768 * // commenting out the decorator because the `@` symbol is spoiling
1769 * // jsDoc rendering in vscode
1770 * // @Injectable()
1771 * class PersonService {
1772 * constructor(
1773 * private http: HTTP,
1774 * private database: Database,
1775 * ) {}
1776 * }
1777 *
1778 * // @Injectable()
1779 * class OrganizationService {
1780 * constructor(
1781 * private http: HTTP,
1782 * private personService: PersonService,
1783 * ) {}
1784 * }
1785 *
1786 * const injector = ReflectiveInjector.resolveAndCreate(
1787 * resolveDependencies(OrganizationService)
1788 * );
1789 *
1790 * const organizationService = injector.get(OrganizationService);
1791 * ```
1792 */
1793 function resolveDependencies() {
1794 var inputs = [];
1795 for (var _i = 0; _i < arguments.length; _i++) {
1796 inputs[_i] = arguments[_i];
1797 }
1798 var deps = new Set();
1799 function resolver(klass) {
1800 if (deps.has(klass))
1801 return;
1802 deps.add(klass);
1803 // resolve all dependencies of the provided class and run the `resolver()` function
1804 // on their constructor functions.
1805 ReflectiveInjector.resolve([klass])
1806 .reduce(function (a, x) { return a.concat(x.resolvedFactories); }, [])
1807 .reduce(function (a, r) { return a.concat(r.dependencies); }, [])
1808 .forEach(function (d) { return resolver(d.key.token); });
1809 }
1810 for (var _a = 0, inputs_1 = inputs; _a < inputs_1.length; _a++) {
1811 var input = inputs_1[_a];
1812 resolver(input);
1813 }
1814 return Array.from(deps);
1815 }
1816
1817 exports.Class = Class;
1818 exports.Host = Host;
1819 exports.Inject = Inject;
1820 exports.Injectable = Injectable;
1821 exports.InjectionToken = InjectionToken;
1822 exports.Injector = Injector;
1823 exports.OpaqueToken = OpaqueToken;
1824 exports.Optional = Optional;
1825 exports.ReflectiveInjector = ReflectiveInjector;
1826 exports.ReflectiveKey = ReflectiveKey;
1827 exports.ResolvedReflectiveFactory = ResolvedReflectiveFactory;
1828 exports.Self = Self;
1829 exports.SkipSelf = SkipSelf;
1830 exports.Type = Type;
1831 exports.forwardRef = forwardRef;
1832 exports.isType = isType;
1833 exports.makeDecorator = makeDecorator;
1834 exports.makeParamDecorator = makeParamDecorator;
1835 exports.makePropDecorator = makePropDecorator;
1836 exports.resolveDependencies = resolveDependencies;
1837 exports.resolveForwardRef = resolveForwardRef;
1838
1839 Object.defineProperty(exports, '__esModule', { value: true });
1840
1841})));