redi.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@wendellhu/redi"] = {}));
  5. })(this, (function (exports) { 'use strict';
  6. var IdentifierDecoratorSymbol = Symbol('$$IDENTIFIER_DECORATOR');
  7. function isIdentifierDecorator(thing) {
  8. return thing && thing[IdentifierDecoratorSymbol] === true;
  9. }
  10. function isCtor(thing) {
  11. return typeof thing === 'function';
  12. }
  13. function isClassDependencyItem(thing) {
  14. if (thing && typeof thing.useClass !== 'undefined') {
  15. return true;
  16. }
  17. return false;
  18. }
  19. function isFactoryDependencyItem(thing) {
  20. if (thing && typeof thing.useFactory !== 'undefined') {
  21. return true;
  22. }
  23. return false;
  24. }
  25. function isValueDependencyItem(thing) {
  26. if (thing && typeof thing.useValue !== 'undefined') {
  27. return true;
  28. }
  29. return false;
  30. }
  31. function isExistingDependencyItem(thing) {
  32. if (thing && typeof thing.useExisting !== 'undefined') {
  33. return true;
  34. }
  35. return false;
  36. }
  37. function isAsyncDependencyItem(thing) {
  38. if (thing && typeof thing.useAsync !== 'undefined') {
  39. return true;
  40. }
  41. return false;
  42. }
  43. var AsyncHookSymbol = Symbol('AsyncHook');
  44. function isAsyncHook(thing) {
  45. if (thing && thing['__symbol'] === AsyncHookSymbol) {
  46. // FIXME@wzhudev: should not be undefined but a symbol here
  47. return true;
  48. }
  49. return false;
  50. }
  51. function prettyPrintIdentifier(id) {
  52. if (typeof id === 'undefined') {
  53. return 'undefined';
  54. }
  55. return isCtor(id) && !id[IdentifierDecoratorSymbol]
  56. ? id.name
  57. : id.toString();
  58. }
  59. exports.Quantity = void 0;
  60. (function (Quantity) {
  61. Quantity["MANY"] = "many";
  62. Quantity["OPTIONAL"] = "optional";
  63. Quantity["REQUIRED"] = "required";
  64. })(exports.Quantity || (exports.Quantity = {}));
  65. exports.LookUp = void 0;
  66. (function (LookUp) {
  67. LookUp["SELF"] = "self";
  68. LookUp["SKIP_SELF"] = "skipSelf";
  69. })(exports.LookUp || (exports.LookUp = {}));
  70. var __extends$4 = (undefined && undefined.__extends) || (function () {
  71. var extendStatics = function (d, b) {
  72. extendStatics = Object.setPrototypeOf ||
  73. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  74. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  75. return extendStatics(d, b);
  76. };
  77. return function (d, b) {
  78. if (typeof b !== "function" && b !== null)
  79. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  80. extendStatics(d, b);
  81. function __() { this.constructor = d; }
  82. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  83. };
  84. })();
  85. var RediError = /** @class */ (function (_super) {
  86. __extends$4(RediError, _super);
  87. function RediError(message) {
  88. return _super.call(this, "[redi]: ".concat(message)) || this;
  89. }
  90. return RediError;
  91. }(Error));
  92. var __extends$3 = (undefined && undefined.__extends) || (function () {
  93. var extendStatics = function (d, b) {
  94. extendStatics = Object.setPrototypeOf ||
  95. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  96. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  97. return extendStatics(d, b);
  98. };
  99. return function (d, b) {
  100. if (typeof b !== "function" && b !== null)
  101. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  102. extendStatics(d, b);
  103. function __() { this.constructor = d; }
  104. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105. };
  106. })();
  107. var TARGET = Symbol('$$TARGET');
  108. var DEPENDENCIES = Symbol('$$DEPENDENCIES');
  109. var DependencyDescriptorNotFoundError = /** @class */ (function (_super) {
  110. __extends$3(DependencyDescriptorNotFoundError, _super);
  111. function DependencyDescriptorNotFoundError(index, target) {
  112. var msg = "Could not find dependency registered on the ".concat(index, " (indexed) parameter of the constructor of \"").concat(prettyPrintIdentifier(target), "\".");
  113. return _super.call(this, msg) || this;
  114. }
  115. return DependencyDescriptorNotFoundError;
  116. }(RediError));
  117. var IdentifierUndefinedError = /** @class */ (function (_super) {
  118. __extends$3(IdentifierUndefinedError, _super);
  119. function IdentifierUndefinedError(target, index) {
  120. var msg = "It seems that you register \"undefined\" as dependency on the ".concat(index + 1, " parameter of \"").concat(prettyPrintIdentifier(target), "\". Please make sure that there is not cyclic dependency among your TypeScript files, or consider using \"forwardRef\". For more info please visit our website https://redi.wendell.fun/docs/debug#could-not-find-dependency-registered-on");
  121. return _super.call(this, msg) || this;
  122. }
  123. return IdentifierUndefinedError;
  124. }(RediError));
  125. /**
  126. * @internal
  127. */
  128. function getDependencies(registerTarget) {
  129. var target = registerTarget;
  130. return target[DEPENDENCIES] || [];
  131. }
  132. /**
  133. * @internal
  134. */
  135. function getDependencyByIndex(registerTarget, index) {
  136. var allDependencies = getDependencies(registerTarget);
  137. var dep = allDependencies.find(function (descriptor) { return descriptor.paramIndex === index; });
  138. if (!dep) {
  139. throw new DependencyDescriptorNotFoundError(index, registerTarget);
  140. }
  141. return dep;
  142. }
  143. /**
  144. * @internal
  145. */
  146. function setDependency(registerTarget, identifier, paramIndex, quantity, lookUp) {
  147. if (quantity === void 0) { quantity = exports.Quantity.REQUIRED; }
  148. var descriptor = {
  149. paramIndex: paramIndex,
  150. identifier: identifier,
  151. quantity: quantity,
  152. lookUp: lookUp,
  153. withNew: false,
  154. };
  155. // sometimes identifier could be 'undefined' if user meant to pass in an ES class
  156. // this is related to how classes are transpiled
  157. if (typeof identifier === 'undefined') {
  158. throw new IdentifierUndefinedError(registerTarget, paramIndex);
  159. }
  160. var target = registerTarget;
  161. // deal with inheritance, subclass need to declare dependencies on its on
  162. if (target[TARGET] === target) {
  163. target[DEPENDENCIES].push(descriptor);
  164. }
  165. else {
  166. target[DEPENDENCIES] = [descriptor];
  167. target[TARGET] = target;
  168. }
  169. }
  170. var knownIdentifiers = new Set();
  171. /**
  172. * Create a dependency identifier
  173. *
  174. * @param id name of the identifier
  175. * @returns Identifier that could also be used as a decorator
  176. */
  177. function createIdentifier(id) {
  178. if (knownIdentifiers.has(id)) {
  179. throw new RediError("Identifier \"".concat(id, "\" already exists."));
  180. }
  181. else {
  182. knownIdentifiers.add(id);
  183. }
  184. var decorator = (function (registerTarget, _key, index) {
  185. setDependency(registerTarget, decorator, index);
  186. }); // decorator as an identifier
  187. // TODO: @wzhudev should assign a name to the function so it would be easy to debug in inspect tools
  188. // decorator.name = `[redi]: ${id}`;
  189. decorator.toString = function () { return id; };
  190. decorator[IdentifierDecoratorSymbol] = true;
  191. return decorator;
  192. }
  193. /**
  194. * @internal
  195. */
  196. /* istanbul ignore next */
  197. function TEST_ONLY_clearKnownIdentifiers() {
  198. knownIdentifiers.clear();
  199. }
  200. var __extends$2 = (undefined && undefined.__extends) || (function () {
  201. var extendStatics = function (d, b) {
  202. extendStatics = Object.setPrototypeOf ||
  203. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  204. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  205. return extendStatics(d, b);
  206. };
  207. return function (d, b) {
  208. if (typeof b !== "function" && b !== null)
  209. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  210. extendStatics(d, b);
  211. function __() { this.constructor = d; }
  212. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  213. };
  214. })();
  215. var QuantityCheckError = /** @class */ (function (_super) {
  216. __extends$2(QuantityCheckError, _super);
  217. function QuantityCheckError(id, quantity, actual) {
  218. var msg = "Expect \"".concat(quantity, "\" dependency items for id \"").concat(prettyPrintIdentifier(id), "\" but get ").concat(actual, ".");
  219. return _super.call(this, msg) || this;
  220. }
  221. return QuantityCheckError;
  222. }(RediError));
  223. function checkQuantity(id, quantity, length) {
  224. if ((quantity === exports.Quantity.OPTIONAL && length > 1) ||
  225. (quantity === exports.Quantity.REQUIRED && length !== 1)) {
  226. throw new QuantityCheckError(id, quantity, length);
  227. }
  228. }
  229. function retrieveQuantity(quantity, arr) {
  230. if (quantity === exports.Quantity.MANY) {
  231. return arr;
  232. }
  233. else {
  234. return arr[0];
  235. }
  236. }
  237. function changeQuantity(target, index, quantity) {
  238. var descriptor = getDependencyByIndex(target, index);
  239. descriptor.quantity = quantity;
  240. }
  241. function quantifyDecoratorFactoryProducer(quantity) {
  242. return function decoratorFactory(id) {
  243. if (this instanceof decoratorFactory) {
  244. return this;
  245. }
  246. return function (registerTarget, _key, index) {
  247. if (id) {
  248. setDependency(registerTarget, id, index, quantity);
  249. }
  250. else {
  251. if (quantity === exports.Quantity.REQUIRED) {
  252. throw new IdentifierUndefinedError(registerTarget, index);
  253. }
  254. changeQuantity(registerTarget, index, quantity);
  255. }
  256. };
  257. };
  258. }
  259. var Many = quantifyDecoratorFactoryProducer(exports.Quantity.MANY);
  260. var Optional = quantifyDecoratorFactoryProducer(exports.Quantity.OPTIONAL);
  261. var Inject = quantifyDecoratorFactoryProducer(exports.Quantity.REQUIRED);
  262. function forwardRef(wrapper) {
  263. return {
  264. unwrap: wrapper,
  265. };
  266. }
  267. function isForwardRef(thing) {
  268. return !!thing && typeof thing.unwrap === 'function';
  269. }
  270. function normalizeForwardRef(id) {
  271. if (isForwardRef(id)) {
  272. return id.unwrap();
  273. }
  274. return id;
  275. }
  276. function isDisposable(thing) {
  277. return !!thing && typeof thing.dispose === 'function';
  278. }
  279. var __extends$1 = (undefined && undefined.__extends) || (function () {
  280. var extendStatics = function (d, b) {
  281. extendStatics = Object.setPrototypeOf ||
  282. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  283. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  284. return extendStatics(d, b);
  285. };
  286. return function (d, b) {
  287. if (typeof b !== "function" && b !== null)
  288. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  289. extendStatics(d, b);
  290. function __() { this.constructor = d; }
  291. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  292. };
  293. })();
  294. function isBareClassDependency(thing) {
  295. return thing.length === 1;
  296. }
  297. var ResolvingStack = [];
  298. function pushResolvingStack(id) {
  299. ResolvingStack.push(id);
  300. }
  301. function popupResolvingStack() {
  302. ResolvingStack.pop();
  303. }
  304. function clearResolvingStack() {
  305. ResolvingStack.length = 0;
  306. }
  307. var DependencyNotFoundForModuleError = /** @class */ (function (_super) {
  308. __extends$1(DependencyNotFoundForModuleError, _super);
  309. function DependencyNotFoundForModuleError(toInstantiate, id, index) {
  310. var _this = this;
  311. var msg = "Cannot find \"".concat(prettyPrintIdentifier(id), "\" registered by any injector. It is the ").concat(index, "th param of \"").concat(isIdentifierDecorator(toInstantiate)
  312. ? prettyPrintIdentifier(toInstantiate)
  313. : toInstantiate.name, "\". The stack of dependencies is: \"").concat(ResolvingStack.map(function (id) { return prettyPrintIdentifier(id); }).join(' -> '), "\".");
  314. _this = _super.call(this, msg) || this;
  315. clearResolvingStack();
  316. return _this;
  317. }
  318. return DependencyNotFoundForModuleError;
  319. }(RediError));
  320. var DependencyNotFoundError = /** @class */ (function (_super) {
  321. __extends$1(DependencyNotFoundError, _super);
  322. function DependencyNotFoundError(id) {
  323. var msg = "Cannot find \"".concat(prettyPrintIdentifier(id), "\" registered by any injector. The stack of dependencies is: \"").concat(ResolvingStack.map(function (id) { return prettyPrintIdentifier(id); }).join(' -> '), "\".");
  324. return _super.call(this, msg) || this;
  325. }
  326. return DependencyNotFoundError;
  327. }(RediError));
  328. /**
  329. * Store unresolved dependencies in an injector.
  330. *
  331. * @internal
  332. */
  333. var DependencyCollection = /** @class */ (function () {
  334. function DependencyCollection(dependencies) {
  335. var _this = this;
  336. this.dependencyMap = new Map();
  337. this.normalizeDependencies(dependencies).map(function (pair) {
  338. return _this.add(pair[0], pair[1]);
  339. });
  340. }
  341. DependencyCollection.prototype.add = function (ctorOrId, val) {
  342. if (typeof val === 'undefined') {
  343. val = { useClass: ctorOrId, lazy: false };
  344. }
  345. var arr = this.dependencyMap.get(ctorOrId);
  346. if (typeof arr === 'undefined') {
  347. arr = [];
  348. this.dependencyMap.set(ctorOrId, arr);
  349. }
  350. arr.push(val);
  351. };
  352. DependencyCollection.prototype.delete = function (id) {
  353. this.dependencyMap.delete(id);
  354. };
  355. DependencyCollection.prototype.get = function (id, quantity) {
  356. if (quantity === void 0) { quantity = exports.Quantity.REQUIRED; }
  357. var ret = this.dependencyMap.get(id);
  358. checkQuantity(id, quantity, ret.length);
  359. return retrieveQuantity(quantity, ret);
  360. };
  361. DependencyCollection.prototype.has = function (id) {
  362. return this.dependencyMap.has(id);
  363. };
  364. DependencyCollection.prototype.append = function (dependencies) {
  365. var _this = this;
  366. this.normalizeDependencies(dependencies).forEach(function (pair) {
  367. return _this.add(pair[0], pair[1]);
  368. });
  369. };
  370. DependencyCollection.prototype.dispose = function () {
  371. this.dependencyMap.clear();
  372. };
  373. /**
  374. * normalize dependencies to `DependencyItem`
  375. */
  376. DependencyCollection.prototype.normalizeDependencies = function (dependencies) {
  377. return dependencies.map(function (dependency) {
  378. var id = dependency[0];
  379. var val;
  380. if (isBareClassDependency(dependency)) {
  381. val = {
  382. useClass: dependency[0],
  383. lazy: false,
  384. };
  385. }
  386. else {
  387. val = dependency[1];
  388. }
  389. return [id, val];
  390. });
  391. };
  392. return DependencyCollection;
  393. }());
  394. /**
  395. * Store resolved dependencies.
  396. *
  397. * @internal
  398. */
  399. var ResolvedDependencyCollection = /** @class */ (function () {
  400. function ResolvedDependencyCollection() {
  401. this.resolvedDependencies = new Map();
  402. }
  403. ResolvedDependencyCollection.prototype.add = function (id, val) {
  404. var arr = this.resolvedDependencies.get(id);
  405. if (typeof arr === 'undefined') {
  406. arr = [];
  407. this.resolvedDependencies.set(id, arr);
  408. }
  409. arr.push(val);
  410. };
  411. ResolvedDependencyCollection.prototype.has = function (id) {
  412. return this.resolvedDependencies.has(id);
  413. };
  414. ResolvedDependencyCollection.prototype.delete = function (id) {
  415. if (this.resolvedDependencies.has(id)) {
  416. var things = this.resolvedDependencies.get(id);
  417. things.forEach(function (t) { return (isDisposable(t) ? t.dispose() : void 0); });
  418. this.resolvedDependencies.delete(id);
  419. }
  420. };
  421. ResolvedDependencyCollection.prototype.get = function (id, quantity) {
  422. if (quantity === void 0) { quantity = exports.Quantity.REQUIRED; }
  423. var ret = this.resolvedDependencies.get(id);
  424. if (!ret) {
  425. throw new DependencyNotFoundError(id);
  426. }
  427. checkQuantity(id, quantity, ret.length);
  428. if (quantity === exports.Quantity.MANY) {
  429. return ret;
  430. }
  431. else {
  432. return ret[0];
  433. }
  434. };
  435. ResolvedDependencyCollection.prototype.dispose = function () {
  436. Array.from(this.resolvedDependencies.values()).forEach(function (items) {
  437. items.forEach(function (item) { return (isDisposable(item) ? item.dispose() : void 0); });
  438. });
  439. this.resolvedDependencies.clear();
  440. };
  441. return ResolvedDependencyCollection;
  442. }());
  443. function changeLookup(target, index, lookUp) {
  444. var descriptor = getDependencyByIndex(target, index);
  445. descriptor.lookUp = lookUp;
  446. }
  447. function lookupDecoratorFactoryProducer(lookUp) {
  448. return function DecoratorFactory() {
  449. if (this instanceof DecoratorFactory) {
  450. return this;
  451. }
  452. return function (target, _key, index) {
  453. changeLookup(target, index, lookUp);
  454. };
  455. };
  456. }
  457. /**
  458. * when resolving this dependency, skip the current injector
  459. */
  460. var SkipSelf = lookupDecoratorFactoryProducer(exports.LookUp.SKIP_SELF);
  461. /**
  462. * when resolving this dependency, only search the current injector
  463. */
  464. var Self = lookupDecoratorFactoryProducer(exports.LookUp.SELF);
  465. function changeToSelf(target, index, withNew) {
  466. var descriptor = getDependencyByIndex(target, index);
  467. descriptor.withNew = withNew;
  468. }
  469. function withNewDecoratorFactoryProducer(withNew) {
  470. return function DecoratorFactory() {
  471. if (this instanceof DecoratorFactory) {
  472. return this;
  473. }
  474. return function (target, _key, index) {
  475. changeToSelf(target, index, withNew);
  476. };
  477. };
  478. }
  479. /**
  480. * Always initialize a new instance of that dependency instead of getting the cached instance from the injector.
  481. */
  482. var WithNew = withNewDecoratorFactoryProducer(true);
  483. function normalizeFactoryDeps(deps) {
  484. if (!deps) {
  485. return [];
  486. }
  487. return deps.map(function (dep, index) {
  488. if (!Array.isArray(dep)) {
  489. return {
  490. paramIndex: index,
  491. identifier: dep,
  492. quantity: exports.Quantity.REQUIRED,
  493. withNew: false,
  494. };
  495. }
  496. var modifiers = dep.slice(0, dep.length - 1);
  497. var identifier = dep[dep.length - 1];
  498. var lookUp = undefined;
  499. var quantity = exports.Quantity.REQUIRED;
  500. var withNew = false;
  501. modifiers.forEach(function (modifier) {
  502. if (modifier instanceof Self) {
  503. lookUp = exports.LookUp.SELF;
  504. }
  505. else if (modifier instanceof SkipSelf) {
  506. lookUp = exports.LookUp.SKIP_SELF;
  507. }
  508. else if (modifier instanceof Optional) {
  509. quantity = exports.Quantity.OPTIONAL;
  510. }
  511. else if (modifier instanceof Many) {
  512. quantity = exports.Quantity.MANY;
  513. }
  514. else if (modifier instanceof WithNew) {
  515. withNew = true;
  516. }
  517. else {
  518. throw new RediError("unknown dep modifier ".concat(modifier, "."));
  519. }
  520. });
  521. return {
  522. paramIndex: index,
  523. identifier: identifier,
  524. quantity: quantity,
  525. lookUp: lookUp,
  526. withNew: withNew,
  527. };
  528. });
  529. }
  530. /**
  531. * this run the callback when CPU is idle. Will fallback to setTimeout if
  532. * the browser doesn't support requestIdleCallback
  533. */
  534. var runWhenIdle;
  535. (function () {
  536. if (typeof requestIdleCallback !== 'undefined' &&
  537. typeof cancelIdleCallback !== 'undefined') {
  538. // use native requestIdleCallback
  539. runWhenIdle = function (runner, timeout) {
  540. var handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout: timeout } : undefined);
  541. var disposed = false;
  542. return function () {
  543. if (disposed) {
  544. return;
  545. }
  546. disposed = true;
  547. cancelIdleCallback(handle);
  548. };
  549. };
  550. }
  551. else {
  552. // use setTimeout as hack
  553. var dummyIdle_1 = Object.freeze({
  554. didTimeout: true,
  555. timeRemaining: function () {
  556. return 15;
  557. },
  558. });
  559. runWhenIdle = function (runner) {
  560. var handle = setTimeout(function () { return runner(dummyIdle_1); });
  561. var disposed = false;
  562. return function () {
  563. if (disposed) {
  564. return;
  565. }
  566. disposed = true;
  567. clearTimeout(handle);
  568. };
  569. };
  570. }
  571. })();
  572. /**
  573. * a wrapper of a executor so it can be evaluated when it's necessary or the CPU is idle
  574. *
  575. * the type of the returned value of the executor would be T
  576. */
  577. var IdleValue = /** @class */ (function () {
  578. function IdleValue(executor) {
  579. var _this = this;
  580. this.didRun = false;
  581. this.selfExecutor = function () {
  582. try {
  583. _this.value = executor();
  584. }
  585. catch (err) {
  586. _this.error = err;
  587. }
  588. finally {
  589. _this.didRun = true;
  590. }
  591. };
  592. this.disposeCallback = runWhenIdle(function () { return _this.selfExecutor(); });
  593. }
  594. IdleValue.prototype.hasRun = function () {
  595. return this.didRun;
  596. };
  597. IdleValue.prototype.dispose = function () {
  598. this.disposeCallback();
  599. };
  600. IdleValue.prototype.getValue = function () {
  601. if (!this.didRun) {
  602. this.dispose();
  603. this.selfExecutor();
  604. }
  605. if (this.error) {
  606. throw this.error;
  607. }
  608. return this.value;
  609. };
  610. return IdleValue;
  611. }());
  612. var __extends = (undefined && undefined.__extends) || (function () {
  613. var extendStatics = function (d, b) {
  614. extendStatics = Object.setPrototypeOf ||
  615. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  616. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  617. return extendStatics(d, b);
  618. };
  619. return function (d, b) {
  620. if (typeof b !== "function" && b !== null)
  621. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  622. extendStatics(d, b);
  623. function __() { this.constructor = d; }
  624. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  625. };
  626. })();
  627. var __assign = (undefined && undefined.__assign) || function () {
  628. __assign = Object.assign || function(t) {
  629. for (var s, i = 1, n = arguments.length; i < n; i++) {
  630. s = arguments[i];
  631. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  632. t[p] = s[p];
  633. }
  634. return t;
  635. };
  636. return __assign.apply(this, arguments);
  637. };
  638. var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
  639. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  640. if (ar || !(i in from)) {
  641. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  642. ar[i] = from[i];
  643. }
  644. }
  645. return to.concat(ar || Array.prototype.slice.call(from));
  646. };
  647. var MAX_RESOLUTIONS_QUEUED = 300;
  648. var NotInstantiatedSymbol = Symbol('$$NOT_INSTANTIATED_SYMBOL');
  649. var CircularDependencyError = /** @class */ (function (_super) {
  650. __extends(CircularDependencyError, _super);
  651. function CircularDependencyError(id) {
  652. return _super.call(this, "Detecting cyclic dependency. The last identifier is \"".concat(prettyPrintIdentifier(id), "\".")) || this;
  653. }
  654. return CircularDependencyError;
  655. }(RediError));
  656. var InjectorAlreadyDisposedError = /** @class */ (function (_super) {
  657. __extends(InjectorAlreadyDisposedError, _super);
  658. function InjectorAlreadyDisposedError() {
  659. return _super.call(this, 'Injector cannot be accessed after it was disposed.') || this;
  660. }
  661. return InjectorAlreadyDisposedError;
  662. }(RediError));
  663. var AsyncItemReturnAsyncItemError = /** @class */ (function (_super) {
  664. __extends(AsyncItemReturnAsyncItemError, _super);
  665. function AsyncItemReturnAsyncItemError(id) {
  666. return _super.call(this, "Async item \"".concat(prettyPrintIdentifier(id), "\" returns another async item.")) || this;
  667. }
  668. return AsyncItemReturnAsyncItemError;
  669. }(RediError));
  670. var GetAsyncItemFromSyncApiError = /** @class */ (function (_super) {
  671. __extends(GetAsyncItemFromSyncApiError, _super);
  672. function GetAsyncItemFromSyncApiError(id) {
  673. return _super.call(this, "Cannot get async item \"".concat(prettyPrintIdentifier(id), "\" from sync api.")) || this;
  674. }
  675. return GetAsyncItemFromSyncApiError;
  676. }(RediError));
  677. var AddDependencyAfterResolutionError = /** @class */ (function (_super) {
  678. __extends(AddDependencyAfterResolutionError, _super);
  679. function AddDependencyAfterResolutionError(id) {
  680. return _super.call(this, "Cannot add dependency \"".concat(prettyPrintIdentifier(id), "\" after it is already resolved.")) || this;
  681. }
  682. return AddDependencyAfterResolutionError;
  683. }(RediError));
  684. var DeleteDependencyAfterResolutionError = /** @class */ (function (_super) {
  685. __extends(DeleteDependencyAfterResolutionError, _super);
  686. function DeleteDependencyAfterResolutionError(id) {
  687. return _super.call(this, "Cannot dependency dependency \"".concat(prettyPrintIdentifier(id), "\" after it is already resolved.")) || this;
  688. }
  689. return DeleteDependencyAfterResolutionError;
  690. }(RediError));
  691. /**
  692. *
  693. */
  694. var Injector = /** @class */ (function () {
  695. /**
  696. * Create a new `Injector` instance
  697. * @param dependencies Dependencies that should be resolved by this injector instance.
  698. * @param parent Optional parent injector.
  699. */
  700. function Injector(dependencies, parent) {
  701. if (parent === void 0) { parent = null; }
  702. this.parent = parent;
  703. this.children = [];
  704. this.resolutionOngoing = 0;
  705. this.disposed = false;
  706. this.dependencyCollection = new DependencyCollection(dependencies || []);
  707. this.resolvedDependencyCollection = new ResolvedDependencyCollection();
  708. if (parent) {
  709. parent.children.push(this);
  710. }
  711. }
  712. /**
  713. * Create a child inject with a set of dependencies.
  714. * @param dependencies Dependencies that should be resolved by the newly created child injector.
  715. * @returns The child injector.
  716. */
  717. Injector.prototype.createChild = function (dependencies) {
  718. this._ensureInjectorNotDisposed();
  719. return new Injector(dependencies, this);
  720. };
  721. /**
  722. * Dispose the injector and all dependencies held by this injector. Note that its child injectors will dispose first.
  723. */
  724. Injector.prototype.dispose = function () {
  725. // Dispose child injectors first.
  726. this.children.forEach(function (c) { return c.dispose(); });
  727. this.children.length = 0;
  728. // Call `dispose` method on each instantiated dependencies if they are `IDisposable` and clear collections.
  729. this.dependencyCollection.dispose();
  730. this.resolvedDependencyCollection.dispose();
  731. this.deleteSelfFromParent();
  732. this.disposed = true;
  733. };
  734. Injector.prototype.deleteSelfFromParent = function () {
  735. if (this.parent) {
  736. var index = this.parent.children.indexOf(this);
  737. if (index > -1) {
  738. this.parent.children.splice(index, 1);
  739. }
  740. }
  741. };
  742. /**
  743. * Add a dependency or its instance into injector. It would throw an error if the dependency
  744. * has already been instantiated.
  745. *
  746. * @param dependency The dependency or an instance that would be add in the injector.
  747. */
  748. Injector.prototype.add = function (dependency) {
  749. this._ensureInjectorNotDisposed();
  750. var identifierOrCtor = dependency[0];
  751. var item = dependency[1];
  752. if (this.resolvedDependencyCollection.has(identifierOrCtor)) {
  753. throw new AddDependencyAfterResolutionError(identifierOrCtor);
  754. }
  755. if (typeof item === 'undefined') {
  756. // Add dependency
  757. this.dependencyCollection.add(identifierOrCtor);
  758. }
  759. else if (isAsyncDependencyItem(item) ||
  760. isClassDependencyItem(item) ||
  761. isValueDependencyItem(item) ||
  762. isFactoryDependencyItem(item)) {
  763. // Add dependency
  764. this.dependencyCollection.add(identifierOrCtor, item);
  765. }
  766. else {
  767. // Add instance
  768. this.resolvedDependencyCollection.add(identifierOrCtor, item);
  769. }
  770. };
  771. /**
  772. * Replace an injection mapping for interface-based injection. It would throw an error if the dependency
  773. * has already been instantiated.
  774. *
  775. * @param dependency The dependency that will replace the already existed dependency.
  776. */
  777. Injector.prototype.replace = function (dependency) {
  778. this._ensureInjectorNotDisposed();
  779. var identifier = dependency[0];
  780. if (this.resolvedDependencyCollection.has(identifier)) {
  781. throw new AddDependencyAfterResolutionError(identifier);
  782. }
  783. this.dependencyCollection.delete(identifier);
  784. if (dependency.length === 1) {
  785. this.dependencyCollection.add(identifier);
  786. }
  787. else {
  788. this.dependencyCollection.add(identifier, dependency[1]);
  789. }
  790. };
  791. /**
  792. * Delete a dependency from an injector. It would throw an error when the deleted dependency
  793. * has already been instantiated.
  794. *
  795. * @param identifier The identifier of the dependency that is supposed to be deleted.
  796. */
  797. Injector.prototype.delete = function (identifier) {
  798. this._ensureInjectorNotDisposed();
  799. if (this.resolvedDependencyCollection.has(identifier)) {
  800. throw new DeleteDependencyAfterResolutionError(identifier);
  801. }
  802. this.dependencyCollection.delete(identifier);
  803. };
  804. /**
  805. * Invoke a function with dependencies injected. The function could only get dependency from the injector
  806. * and other methods are not accessible for the function.
  807. *
  808. * @param cb the function to be executed
  809. * @param args arguments to be passed into the function
  810. * @returns the return value of the function
  811. */
  812. Injector.prototype.invoke = function (cb) {
  813. var _this = this;
  814. var args = [];
  815. for (var _i = 1; _i < arguments.length; _i++) {
  816. args[_i - 1] = arguments[_i];
  817. }
  818. this._ensureInjectorNotDisposed();
  819. var accessor = {
  820. get: function (id, quantityOrLookup, lookUp) {
  821. return _this._get(id, quantityOrLookup, lookUp);
  822. },
  823. };
  824. return cb.apply(void 0, __spreadArray([accessor], args, false));
  825. };
  826. /**
  827. * Check if the injector could initialize a dependency.
  828. *
  829. * @param id Identifier of the dependency
  830. */
  831. Injector.prototype.has = function (id) {
  832. var _a;
  833. return this.dependencyCollection.has(id) || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.has(id)) || false;
  834. };
  835. /**
  836. * Get dependency instance(s).
  837. *
  838. * @param id Identifier of the dependency
  839. * @param quantityOrLookup @link{Quantity} or @link{LookUp}
  840. * @param lookUp @link{LookUp}
  841. */
  842. Injector.prototype.get = function (id, quantityOrLookup, lookUp) {
  843. this._ensureInjectorNotDisposed();
  844. try {
  845. var newResult = this._get(id, quantityOrLookup, lookUp);
  846. if ((Array.isArray(newResult) && newResult.some(function (r) { return isAsyncHook(r); })) || isAsyncHook(newResult)) {
  847. throw new GetAsyncItemFromSyncApiError(id);
  848. }
  849. return newResult;
  850. }
  851. catch (e) {
  852. if (e instanceof DependencyNotFoundError) {
  853. clearResolvingStack();
  854. }
  855. throw e;
  856. }
  857. };
  858. Injector.prototype._get = function (id, quantityOrLookup, lookUp, toSelf) {
  859. var quantity = exports.Quantity.REQUIRED;
  860. if (quantityOrLookup === exports.Quantity.REQUIRED ||
  861. quantityOrLookup === exports.Quantity.OPTIONAL ||
  862. quantityOrLookup === exports.Quantity.MANY) {
  863. quantity = quantityOrLookup;
  864. }
  865. else {
  866. lookUp = quantityOrLookup;
  867. }
  868. if (!toSelf) {
  869. // see if the dependency is already resolved, return it and check quantity
  870. var cachedResult = this.getValue(id, quantity, lookUp);
  871. if (cachedResult !== NotInstantiatedSymbol) {
  872. return cachedResult;
  873. }
  874. }
  875. // see if the dependency can be instantiated by itself or its parent
  876. return this.createDependency(id, quantity, lookUp, !toSelf);
  877. };
  878. /**
  879. * Get a dependency in the async way.
  880. */
  881. Injector.prototype.getAsync = function (id) {
  882. this._ensureInjectorNotDisposed();
  883. var cachedResult = this.getValue(id, exports.Quantity.REQUIRED);
  884. if (cachedResult !== NotInstantiatedSymbol) {
  885. return Promise.resolve(cachedResult);
  886. }
  887. var newResult = this.createDependency(id, exports.Quantity.REQUIRED);
  888. if (!isAsyncHook(newResult)) {
  889. return Promise.resolve(newResult);
  890. }
  891. return newResult.whenReady();
  892. };
  893. /**
  894. * Instantiate a class. The created instance would not be held by the injector.
  895. */
  896. Injector.prototype.createInstance = function (ctor) {
  897. var customArgs = [];
  898. for (var _i = 1; _i < arguments.length; _i++) {
  899. customArgs[_i - 1] = arguments[_i];
  900. }
  901. this._ensureInjectorNotDisposed();
  902. return this._resolveClassImpl.apply(this, __spreadArray([ctor], customArgs, false));
  903. };
  904. Injector.prototype._resolveDependency = function (id, item, shouldCache) {
  905. if (shouldCache === void 0) { shouldCache = true; }
  906. var result;
  907. pushResolvingStack(id);
  908. try {
  909. if (isValueDependencyItem(item)) {
  910. result = this._resolveValueDependency(id, item);
  911. }
  912. else if (isFactoryDependencyItem(item)) {
  913. result = this._resolveFactory(id, item, shouldCache);
  914. }
  915. else if (isClassDependencyItem(item)) {
  916. result = this._resolveClass(id, item, shouldCache);
  917. }
  918. else if (isExistingDependencyItem(item)) {
  919. result = this._resolveExisting(id, item);
  920. }
  921. else {
  922. result = this._resolveAsync(id, item);
  923. }
  924. popupResolvingStack();
  925. }
  926. catch (e) {
  927. popupResolvingStack();
  928. throw e;
  929. }
  930. return result;
  931. };
  932. Injector.prototype._resolveExisting = function (id, item) {
  933. var thing = this.get(item.useExisting);
  934. this.resolvedDependencyCollection.add(id, thing);
  935. return thing;
  936. };
  937. Injector.prototype._resolveValueDependency = function (id, item) {
  938. var thing = item.useValue;
  939. this.resolvedDependencyCollection.add(id, thing);
  940. return thing;
  941. };
  942. Injector.prototype._resolveClass = function (id, item, shouldCache) {
  943. var _this = this;
  944. if (shouldCache === void 0) { shouldCache = true; }
  945. var ctor = item.useClass;
  946. var thing;
  947. if (item.lazy) {
  948. var idle_1 = new IdleValue(function () {
  949. _this._ensureInjectorNotDisposed();
  950. return _this._resolveClassImpl(ctor);
  951. });
  952. thing = new Proxy(Object.create(null), {
  953. get: function (target, key) {
  954. var _a;
  955. if (key in target) {
  956. return target[key]; // such as toString
  957. }
  958. // hack checking if it's a async loader
  959. if (key === 'whenReady') {
  960. return undefined;
  961. }
  962. var hasInstantiated = idle_1.hasRun();
  963. var thing = idle_1.getValue();
  964. if (!hasInstantiated) {
  965. (_a = item.onInstantiation) === null || _a === void 0 ? void 0 : _a.call(item, thing);
  966. }
  967. var property = thing[key];
  968. if (typeof property !== 'function') {
  969. return property;
  970. }
  971. property = property.bind(thing);
  972. target[key] = property;
  973. return property;
  974. },
  975. set: function (_target, key, value) {
  976. ;
  977. idle_1.getValue()[key] = value;
  978. return true;
  979. },
  980. });
  981. }
  982. else {
  983. thing = this._resolveClassImpl(ctor);
  984. }
  985. if (id && shouldCache) {
  986. this.resolvedDependencyCollection.add(id, thing);
  987. }
  988. return thing;
  989. };
  990. Injector.prototype._resolveClassImpl = function (ctor) {
  991. var extraParams = [];
  992. for (var _i = 1; _i < arguments.length; _i++) {
  993. extraParams[_i - 1] = arguments[_i];
  994. }
  995. this.markNewResolution(ctor);
  996. var declaredDependencies = getDependencies(ctor)
  997. .sort(function (a, b) { return a.paramIndex - b.paramIndex; })
  998. .map(function (descriptor) { return (__assign(__assign({}, descriptor), { identifier: normalizeForwardRef(descriptor.identifier) })); });
  999. var resolvedArgs = [];
  1000. for (var _a = 0, declaredDependencies_1 = declaredDependencies; _a < declaredDependencies_1.length; _a++) {
  1001. var dep = declaredDependencies_1[_a];
  1002. // recursive happens here
  1003. try {
  1004. var thing_1 = this._get(dep.identifier, dep.quantity, dep.lookUp, dep.withNew);
  1005. resolvedArgs.push(thing_1);
  1006. }
  1007. catch (error) {
  1008. if (error instanceof DependencyNotFoundError) {
  1009. throw new DependencyNotFoundForModuleError(ctor, dep.identifier, dep.paramIndex);
  1010. }
  1011. throw error;
  1012. }
  1013. }
  1014. var args = __spreadArray([], extraParams, true);
  1015. var firstDependencyArgIndex = declaredDependencies.length > 0
  1016. ? declaredDependencies[0].paramIndex
  1017. : args.length;
  1018. if (args.length !== firstDependencyArgIndex) {
  1019. console.warn("[redi]: Expect ".concat(firstDependencyArgIndex, " custom parameter(s) of ").concat(ctor.toString(), " but get ").concat(args.length, "."));
  1020. var delta = firstDependencyArgIndex - args.length;
  1021. if (delta > 0) {
  1022. args = __spreadArray(__spreadArray([], args, true), new Array(delta).fill(undefined), true);
  1023. }
  1024. else {
  1025. args = args.slice(0, firstDependencyArgIndex);
  1026. }
  1027. }
  1028. var thing = new (ctor.bind.apply(ctor, __spreadArray(__spreadArray([void 0], args, false), resolvedArgs, false)))();
  1029. this.markResolutionCompleted();
  1030. return thing;
  1031. };
  1032. Injector.prototype._resolveFactory = function (id, item, shouldCache) {
  1033. var _a;
  1034. this.markNewResolution(id);
  1035. var declaredDependencies = normalizeFactoryDeps(item.deps);
  1036. var resolvedArgs = [];
  1037. for (var _i = 0, declaredDependencies_2 = declaredDependencies; _i < declaredDependencies_2.length; _i++) {
  1038. var dep = declaredDependencies_2[_i];
  1039. try {
  1040. var thing_2 = this._get(dep.identifier, dep.quantity, dep.lookUp, dep.withNew);
  1041. resolvedArgs.push(thing_2);
  1042. }
  1043. catch (error) {
  1044. if (error instanceof DependencyNotFoundError) {
  1045. throw new DependencyNotFoundForModuleError(id, dep.identifier, dep.paramIndex);
  1046. }
  1047. throw error;
  1048. }
  1049. }
  1050. var thing = item.useFactory.apply(null, resolvedArgs);
  1051. if (shouldCache) {
  1052. this.resolvedDependencyCollection.add(id, thing);
  1053. }
  1054. this.markResolutionCompleted();
  1055. (_a = item === null || item === void 0 ? void 0 : item.onInstantiation) === null || _a === void 0 ? void 0 : _a.call(item, thing);
  1056. return thing;
  1057. };
  1058. Injector.prototype._resolveAsync = function (id, item) {
  1059. var _this = this;
  1060. var asyncLoader = {
  1061. __symbol: AsyncHookSymbol,
  1062. whenReady: function () { return _this._resolveAsyncImpl(id, item); },
  1063. };
  1064. return asyncLoader;
  1065. };
  1066. Injector.prototype._resolveAsyncImpl = function (id, item) {
  1067. var _this = this;
  1068. return item.useAsync().then(function (thing) {
  1069. // check if another promise has been resolved,
  1070. // do not resolve the async item twice
  1071. var resolvedCheck = _this.getValue(id);
  1072. if (resolvedCheck !== NotInstantiatedSymbol) {
  1073. return resolvedCheck;
  1074. }
  1075. var ret;
  1076. if (Array.isArray(thing)) {
  1077. var item_1 = thing[1];
  1078. if (isAsyncDependencyItem(item_1)) {
  1079. throw new AsyncItemReturnAsyncItemError(id);
  1080. }
  1081. else {
  1082. ret = _this._resolveDependency(id, item_1);
  1083. }
  1084. }
  1085. else if (isCtor(thing)) {
  1086. ret = _this._resolveClassImpl(thing);
  1087. }
  1088. else {
  1089. ret = thing;
  1090. }
  1091. _this.resolvedDependencyCollection.add(id, ret);
  1092. return ret;
  1093. });
  1094. };
  1095. Injector.prototype.getValue = function (id, quantity, lookUp) {
  1096. var _this = this;
  1097. if (quantity === void 0) { quantity = exports.Quantity.REQUIRED; }
  1098. var onSelf = function () {
  1099. if (_this.dependencyCollection.has(id) &&
  1100. !_this.resolvedDependencyCollection.has(id)) {
  1101. return NotInstantiatedSymbol;
  1102. }
  1103. return _this.resolvedDependencyCollection.get(id, quantity);
  1104. };
  1105. var onParent = function () {
  1106. if (_this.parent) {
  1107. return _this.parent.getValue(id, quantity);
  1108. }
  1109. else {
  1110. return NotInstantiatedSymbol;
  1111. }
  1112. };
  1113. if (lookUp === exports.LookUp.SKIP_SELF) {
  1114. return onParent();
  1115. }
  1116. if (lookUp === exports.LookUp.SELF) {
  1117. return onSelf();
  1118. }
  1119. if (this.resolvedDependencyCollection.has(id) ||
  1120. this.dependencyCollection.has(id)) {
  1121. return onSelf();
  1122. }
  1123. return onParent();
  1124. };
  1125. Injector.prototype.createDependency = function (id, quantity, lookUp, shouldCache) {
  1126. var _this = this;
  1127. if (quantity === void 0) { quantity = exports.Quantity.REQUIRED; }
  1128. if (shouldCache === void 0) { shouldCache = true; }
  1129. var onSelf = function () {
  1130. var registrations = _this.dependencyCollection.get(id, quantity);
  1131. var ret = null;
  1132. if (Array.isArray(registrations)) {
  1133. ret = registrations.map(function (dependencyItem) { return _this._resolveDependency(id, dependencyItem, shouldCache); });
  1134. }
  1135. else if (registrations) {
  1136. ret = _this._resolveDependency(id, registrations, shouldCache);
  1137. }
  1138. return ret;
  1139. };
  1140. var onParent = function () {
  1141. if (_this.parent) {
  1142. return _this.parent.createDependency(id, quantity, undefined, shouldCache);
  1143. }
  1144. else {
  1145. if (quantity === exports.Quantity.OPTIONAL) {
  1146. return null;
  1147. }
  1148. pushResolvingStack(id);
  1149. throw new DependencyNotFoundError(id);
  1150. }
  1151. };
  1152. if (lookUp === exports.LookUp.SKIP_SELF) {
  1153. return onParent();
  1154. }
  1155. if (id === Injector) {
  1156. return this;
  1157. }
  1158. if (this.dependencyCollection.has(id)) {
  1159. return onSelf();
  1160. }
  1161. return onParent();
  1162. };
  1163. Injector.prototype.markNewResolution = function (id) {
  1164. this.resolutionOngoing += 1;
  1165. if (this.resolutionOngoing >= MAX_RESOLUTIONS_QUEUED) {
  1166. throw new CircularDependencyError(id);
  1167. }
  1168. };
  1169. Injector.prototype.markResolutionCompleted = function () {
  1170. this.resolutionOngoing -= 1;
  1171. };
  1172. Injector.prototype._ensureInjectorNotDisposed = function () {
  1173. if (this.disposed) {
  1174. throw new InjectorAlreadyDisposedError();
  1175. }
  1176. };
  1177. return Injector;
  1178. }());
  1179. /**
  1180. * Register dependencies on a class.
  1181. *
  1182. * @param registerTarget The target constructor
  1183. * @param deps Dependencies
  1184. */
  1185. function setDependencies(registerTarget, deps) {
  1186. var normalizedDescriptors = normalizeFactoryDeps(deps);
  1187. normalizedDescriptors.forEach(function (descriptor) {
  1188. setDependency(registerTarget, descriptor.identifier, descriptor.paramIndex, descriptor.quantity, descriptor.lookUp);
  1189. });
  1190. }
  1191. var globalObject = (typeof globalThis !== 'undefined' && globalThis) ||
  1192. (typeof window !== 'undefined' && window) ||
  1193. (typeof global !== 'undefined' && global);
  1194. var __REDI_GLOBAL_LOCK__ = 'REDI_GLOBAL_LOCK';
  1195. var isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
  1196. if (globalObject[__REDI_GLOBAL_LOCK__]) {
  1197. if (!isNode) {
  1198. console.error("[redi]: You are loading scripts of redi more than once! This may cause undesired behavior in your application.\nMaybe your dependencies added redi as its dependency and bundled redi to its dist files. Or you import different versions of redi.\nFor more info please visit our website: https://redi.wendell.fun/en-US/docs/debug#import-scripts-of-redi-more-than-once");
  1199. }
  1200. }
  1201. else {
  1202. globalObject[__REDI_GLOBAL_LOCK__] = true;
  1203. }
  1204. exports.Inject = Inject;
  1205. exports.Injector = Injector;
  1206. exports.Many = Many;
  1207. exports.Optional = Optional;
  1208. exports.RediError = RediError;
  1209. exports.Self = Self;
  1210. exports.SkipSelf = SkipSelf;
  1211. exports.WithNew = WithNew;
  1212. exports.createIdentifier = createIdentifier;
  1213. exports.forwardRef = forwardRef;
  1214. exports.isAsyncDependencyItem = isAsyncDependencyItem;
  1215. exports.isAsyncHook = isAsyncHook;
  1216. exports.isClassDependencyItem = isClassDependencyItem;
  1217. exports.isCtor = isCtor;
  1218. exports.isDisposable = isDisposable;
  1219. exports.isFactoryDependencyItem = isFactoryDependencyItem;
  1220. exports.isValueDependencyItem = isValueDependencyItem;
  1221. exports.setDependencies = setDependencies;
  1222. Object.defineProperty(exports, '__esModule', { value: true });
  1223. }));
  1224. //# sourceMappingURL=redi.js.map