@tsed/di 7.0.0-alpha.1 → 7.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/lib/cjs/constants/index.js +7 -0
  2. package/lib/cjs/constants/index.js.map +1 -0
  3. package/lib/cjs/decorators/configuration.js +24 -0
  4. package/lib/cjs/decorators/configuration.js.map +1 -0
  5. package/lib/cjs/decorators/constant.js +55 -0
  6. package/lib/cjs/decorators/constant.js.map +1 -0
  7. package/lib/cjs/decorators/controller.js +53 -0
  8. package/lib/cjs/decorators/controller.js.map +1 -0
  9. package/lib/cjs/decorators/index.js +19 -0
  10. package/lib/cjs/decorators/index.js.map +1 -0
  11. package/lib/cjs/decorators/inject.js +79 -0
  12. package/lib/cjs/decorators/inject.js.map +1 -0
  13. package/lib/cjs/decorators/injectable.js +34 -0
  14. package/lib/cjs/decorators/injectable.js.map +1 -0
  15. package/lib/cjs/decorators/intercept.js +28 -0
  16. package/lib/cjs/decorators/intercept.js.map +1 -0
  17. package/lib/cjs/decorators/interceptor.js +21 -0
  18. package/lib/cjs/decorators/interceptor.js.map +1 -0
  19. package/lib/cjs/decorators/lazyInject.js +71 -0
  20. package/lib/cjs/decorators/lazyInject.js.map +1 -0
  21. package/lib/cjs/decorators/module.js +31 -0
  22. package/lib/cjs/decorators/module.js.map +1 -0
  23. package/lib/cjs/decorators/opts.js +54 -0
  24. package/lib/cjs/decorators/opts.js.map +1 -0
  25. package/lib/cjs/decorators/overrideProvider.js +17 -0
  26. package/lib/cjs/decorators/overrideProvider.js.map +1 -0
  27. package/lib/cjs/decorators/scope.js +16 -0
  28. package/lib/cjs/decorators/scope.js.map +1 -0
  29. package/lib/cjs/decorators/service.js +18 -0
  30. package/lib/cjs/decorators/service.js.map +1 -0
  31. package/lib/cjs/decorators/useOpts.js +65 -0
  32. package/lib/cjs/decorators/useOpts.js.map +1 -0
  33. package/lib/cjs/decorators/value.js +55 -0
  34. package/lib/cjs/decorators/value.js.map +1 -0
  35. package/lib/cjs/domain/Container.js +72 -0
  36. package/lib/cjs/domain/Container.js.map +1 -0
  37. package/lib/cjs/domain/ContextLogger.js +85 -0
  38. package/lib/cjs/domain/ContextLogger.js.map +1 -0
  39. package/lib/cjs/domain/DIContext.js +45 -0
  40. package/lib/cjs/domain/DIContext.js.map +1 -0
  41. package/lib/cjs/domain/InjectablePropertyType.js +12 -0
  42. package/lib/cjs/domain/InjectablePropertyType.js.map +1 -0
  43. package/lib/cjs/domain/LocalsContainer.js +55 -0
  44. package/lib/cjs/domain/LocalsContainer.js.map +1 -0
  45. package/lib/cjs/domain/Provider.js +122 -0
  46. package/lib/cjs/domain/Provider.js.map +1 -0
  47. package/lib/cjs/domain/ProviderScope.js +10 -0
  48. package/lib/cjs/domain/ProviderScope.js.map +1 -0
  49. package/lib/cjs/domain/ProviderType.js +15 -0
  50. package/lib/cjs/domain/ProviderType.js.map +1 -0
  51. package/lib/cjs/domain/index.js +12 -0
  52. package/lib/cjs/domain/index.js.map +1 -0
  53. package/lib/cjs/errors/InjectionError.js +58 -0
  54. package/lib/cjs/errors/InjectionError.js.map +1 -0
  55. package/lib/cjs/errors/UndefinedTokenError.js +11 -0
  56. package/lib/cjs/errors/UndefinedTokenError.js.map +1 -0
  57. package/lib/cjs/index.js +21 -0
  58. package/lib/cjs/index.js.map +1 -0
  59. package/lib/cjs/interfaces/DIConfigurationOptions.js +3 -0
  60. package/lib/cjs/interfaces/DIConfigurationOptions.js.map +1 -0
  61. package/lib/cjs/interfaces/DILogger.js +3 -0
  62. package/lib/cjs/interfaces/DILogger.js.map +1 -0
  63. package/lib/cjs/interfaces/DIResolver.js +3 -0
  64. package/lib/cjs/interfaces/DIResolver.js.map +1 -0
  65. package/lib/cjs/interfaces/IProvider.js +3 -0
  66. package/lib/cjs/interfaces/IProvider.js.map +1 -0
  67. package/lib/cjs/interfaces/InjectableProperties.js +3 -0
  68. package/lib/cjs/interfaces/InjectableProperties.js.map +1 -0
  69. package/lib/cjs/interfaces/InterceptorContext.js +3 -0
  70. package/lib/cjs/interfaces/InterceptorContext.js.map +1 -0
  71. package/lib/cjs/interfaces/InterceptorMethods.js +3 -0
  72. package/lib/cjs/interfaces/InterceptorMethods.js.map +1 -0
  73. package/lib/cjs/interfaces/InvokeOptions.js +3 -0
  74. package/lib/cjs/interfaces/InvokeOptions.js.map +1 -0
  75. package/lib/cjs/interfaces/OnDestroy.js +3 -0
  76. package/lib/cjs/interfaces/OnDestroy.js.map +1 -0
  77. package/lib/cjs/interfaces/OnInit.js +3 -0
  78. package/lib/cjs/interfaces/OnInit.js.map +1 -0
  79. package/lib/cjs/interfaces/RegistrySettings.js +3 -0
  80. package/lib/cjs/interfaces/RegistrySettings.js.map +1 -0
  81. package/lib/cjs/interfaces/ResolvedInvokeOptions.js +3 -0
  82. package/lib/cjs/interfaces/ResolvedInvokeOptions.js.map +1 -0
  83. package/lib/cjs/interfaces/TokenProvider.js +3 -0
  84. package/lib/cjs/interfaces/TokenProvider.js.map +1 -0
  85. package/lib/cjs/interfaces/index.js +18 -0
  86. package/lib/cjs/interfaces/index.js.map +1 -0
  87. package/lib/cjs/registries/GlobalProviders.js +124 -0
  88. package/lib/cjs/registries/GlobalProviders.js.map +1 -0
  89. package/lib/cjs/registries/ProviderRegistry.js +85 -0
  90. package/lib/cjs/registries/ProviderRegistry.js.map +1 -0
  91. package/lib/cjs/services/DIConfiguration.js +129 -0
  92. package/lib/cjs/services/DIConfiguration.js.map +1 -0
  93. package/lib/cjs/services/DILogger.js +13 -0
  94. package/lib/cjs/services/DILogger.js.map +1 -0
  95. package/lib/cjs/services/DITest.js +108 -0
  96. package/lib/cjs/services/DITest.js.map +1 -0
  97. package/lib/cjs/services/InjectorService.js +566 -0
  98. package/lib/cjs/services/InjectorService.js.map +1 -0
  99. package/lib/cjs/utils/colors.js +10 -0
  100. package/lib/cjs/utils/colors.js.map +1 -0
  101. package/lib/cjs/utils/createContainer.js +14 -0
  102. package/lib/cjs/utils/createContainer.js.map +1 -0
  103. package/lib/cjs/utils/data/Test1.js +8 -0
  104. package/lib/cjs/utils/data/Test1.js.map +1 -0
  105. package/lib/cjs/utils/data/Test2.js +8 -0
  106. package/lib/cjs/utils/data/Test2.js.map +1 -0
  107. package/lib/cjs/utils/getConfiguration.js +20 -0
  108. package/lib/cjs/utils/getConfiguration.js.map +1 -0
  109. package/lib/cjs/utils/setLoggerLevel.js +16 -0
  110. package/lib/cjs/utils/setLoggerLevel.js.map +1 -0
  111. package/lib/esm/constants/index.js +4 -0
  112. package/lib/esm/constants/index.js.map +1 -0
  113. package/lib/esm/decorators/configuration.js +20 -0
  114. package/lib/esm/decorators/configuration.js.map +1 -0
  115. package/lib/esm/decorators/constant.js +51 -0
  116. package/lib/esm/decorators/constant.js.map +1 -0
  117. package/lib/esm/decorators/controller.js +49 -0
  118. package/lib/esm/decorators/controller.js.map +1 -0
  119. package/lib/esm/decorators/index.js +16 -0
  120. package/lib/esm/decorators/index.js.map +1 -0
  121. package/lib/esm/decorators/inject.js +74 -0
  122. package/lib/esm/decorators/inject.js.map +1 -0
  123. package/lib/esm/decorators/injectable.js +30 -0
  124. package/lib/esm/decorators/injectable.js.map +1 -0
  125. package/lib/esm/decorators/intercept.js +24 -0
  126. package/lib/esm/decorators/intercept.js.map +1 -0
  127. package/lib/esm/decorators/interceptor.js +17 -0
  128. package/lib/esm/decorators/interceptor.js.map +1 -0
  129. package/lib/esm/decorators/lazyInject.js +66 -0
  130. package/lib/esm/decorators/lazyInject.js.map +1 -0
  131. package/lib/esm/decorators/module.js +27 -0
  132. package/lib/esm/decorators/module.js.map +1 -0
  133. package/lib/esm/decorators/opts.js +50 -0
  134. package/lib/esm/decorators/opts.js.map +1 -0
  135. package/lib/esm/decorators/overrideProvider.js +13 -0
  136. package/lib/esm/decorators/overrideProvider.js.map +1 -0
  137. package/lib/esm/decorators/scope.js +12 -0
  138. package/lib/esm/decorators/scope.js.map +1 -0
  139. package/lib/esm/decorators/service.js +14 -0
  140. package/lib/esm/decorators/service.js.map +1 -0
  141. package/lib/esm/decorators/useOpts.js +61 -0
  142. package/lib/esm/decorators/useOpts.js.map +1 -0
  143. package/lib/esm/decorators/value.js +51 -0
  144. package/lib/esm/decorators/value.js.map +1 -0
  145. package/lib/esm/domain/Container.js +68 -0
  146. package/lib/esm/domain/Container.js.map +1 -0
  147. package/lib/esm/domain/ContextLogger.js +81 -0
  148. package/lib/esm/domain/ContextLogger.js.map +1 -0
  149. package/lib/esm/domain/DIContext.js +41 -0
  150. package/lib/esm/domain/DIContext.js.map +1 -0
  151. package/lib/esm/domain/InjectablePropertyType.js +9 -0
  152. package/lib/esm/domain/InjectablePropertyType.js.map +1 -0
  153. package/lib/esm/domain/LocalsContainer.js +51 -0
  154. package/lib/esm/domain/LocalsContainer.js.map +1 -0
  155. package/lib/esm/domain/Provider.js +118 -0
  156. package/lib/esm/domain/Provider.js.map +1 -0
  157. package/lib/esm/domain/ProviderScope.js +7 -0
  158. package/lib/esm/domain/ProviderScope.js.map +1 -0
  159. package/lib/esm/domain/ProviderType.js +12 -0
  160. package/lib/esm/domain/ProviderType.js.map +1 -0
  161. package/lib/esm/domain/index.js +9 -0
  162. package/lib/esm/domain/index.js.map +1 -0
  163. package/lib/esm/errors/InjectionError.js +54 -0
  164. package/lib/esm/errors/InjectionError.js.map +1 -0
  165. package/lib/esm/errors/UndefinedTokenError.js +7 -0
  166. package/lib/esm/errors/UndefinedTokenError.js.map +1 -0
  167. package/lib/esm/index.js +18 -0
  168. package/lib/esm/index.js.map +1 -0
  169. package/lib/esm/interfaces/DIConfigurationOptions.js +2 -0
  170. package/lib/esm/interfaces/DIConfigurationOptions.js.map +1 -0
  171. package/lib/esm/interfaces/DILogger.js +2 -0
  172. package/lib/esm/interfaces/DILogger.js.map +1 -0
  173. package/lib/esm/interfaces/DIResolver.js +2 -0
  174. package/lib/esm/interfaces/DIResolver.js.map +1 -0
  175. package/lib/esm/interfaces/IProvider.js +2 -0
  176. package/lib/esm/interfaces/IProvider.js.map +1 -0
  177. package/lib/esm/interfaces/InjectableProperties.js +2 -0
  178. package/lib/esm/interfaces/InjectableProperties.js.map +1 -0
  179. package/lib/esm/interfaces/InterceptorContext.js +2 -0
  180. package/lib/esm/interfaces/InterceptorContext.js.map +1 -0
  181. package/lib/esm/interfaces/InterceptorMethods.js +2 -0
  182. package/lib/esm/interfaces/InterceptorMethods.js.map +1 -0
  183. package/lib/esm/interfaces/InvokeOptions.js +2 -0
  184. package/lib/esm/interfaces/InvokeOptions.js.map +1 -0
  185. package/lib/esm/interfaces/OnDestroy.js +2 -0
  186. package/lib/esm/interfaces/OnDestroy.js.map +1 -0
  187. package/lib/esm/interfaces/OnInit.js +2 -0
  188. package/lib/esm/interfaces/OnInit.js.map +1 -0
  189. package/lib/esm/interfaces/RegistrySettings.js +2 -0
  190. package/lib/esm/interfaces/RegistrySettings.js.map +1 -0
  191. package/lib/esm/interfaces/ResolvedInvokeOptions.js +2 -0
  192. package/lib/esm/interfaces/ResolvedInvokeOptions.js.map +1 -0
  193. package/lib/esm/interfaces/TokenProvider.js +2 -0
  194. package/lib/esm/interfaces/TokenProvider.js.map +1 -0
  195. package/lib/esm/interfaces/index.js +15 -0
  196. package/lib/esm/interfaces/index.js.map +1 -0
  197. package/lib/esm/registries/GlobalProviders.js +120 -0
  198. package/lib/esm/registries/GlobalProviders.js.map +1 -0
  199. package/lib/esm/registries/ProviderRegistry.js +80 -0
  200. package/lib/esm/registries/ProviderRegistry.js.map +1 -0
  201. package/lib/esm/services/DIConfiguration.js +125 -0
  202. package/lib/esm/services/DIConfiguration.js.map +1 -0
  203. package/lib/esm/services/DILogger.js +11 -0
  204. package/lib/esm/services/DILogger.js.map +1 -0
  205. package/lib/esm/services/DITest.js +104 -0
  206. package/lib/esm/services/DITest.js.map +1 -0
  207. package/lib/esm/services/InjectorService.js +563 -0
  208. package/lib/esm/services/InjectorService.js.map +1 -0
  209. package/lib/esm/utils/colors.js +7 -0
  210. package/lib/esm/utils/colors.js.map +1 -0
  211. package/lib/esm/utils/createContainer.js +10 -0
  212. package/lib/esm/utils/createContainer.js.map +1 -0
  213. package/lib/esm/utils/data/Test1.js +4 -0
  214. package/lib/esm/utils/data/Test1.js.map +1 -0
  215. package/lib/esm/utils/data/Test2.js +4 -0
  216. package/lib/esm/utils/data/Test2.js.map +1 -0
  217. package/lib/esm/utils/getConfiguration.js +16 -0
  218. package/lib/esm/utils/getConfiguration.js.map +1 -0
  219. package/lib/esm/utils/setLoggerLevel.js +12 -0
  220. package/lib/esm/utils/setLoggerLevel.js.map +1 -0
  221. package/lib/{constants → types/constants}/index.d.ts +0 -0
  222. package/lib/{decorators → types/decorators}/configuration.d.ts +0 -0
  223. package/lib/{decorators → types/decorators}/constant.d.ts +0 -0
  224. package/lib/types/decorators/controller.d.ts +43 -0
  225. package/lib/{decorators → types/decorators}/index.d.ts +2 -0
  226. package/lib/{decorators → types/decorators}/inject.d.ts +2 -0
  227. package/lib/{decorators → types/decorators}/injectable.d.ts +2 -1
  228. package/lib/{decorators → types/decorators}/intercept.d.ts +0 -0
  229. package/lib/{decorators → types/decorators}/interceptor.d.ts +0 -0
  230. package/lib/types/decorators/lazyInject.d.ts +43 -0
  231. package/lib/{decorators → types/decorators}/module.d.ts +0 -0
  232. package/lib/{decorators → types/decorators}/opts.d.ts +0 -0
  233. package/lib/{decorators → types/decorators}/overrideProvider.d.ts +0 -0
  234. package/lib/{decorators → types/decorators}/scope.d.ts +0 -0
  235. package/lib/{decorators → types/decorators}/service.d.ts +0 -0
  236. package/lib/{decorators → types/decorators}/useOpts.d.ts +0 -0
  237. package/lib/{decorators → types/decorators}/value.d.ts +0 -0
  238. package/lib/{domain → types/domain}/Container.d.ts +2 -3
  239. package/lib/{domain → types/domain}/ContextLogger.d.ts +5 -1
  240. package/lib/{domain → types/domain}/DIContext.d.ts +6 -7
  241. package/lib/{domain → types/domain}/InjectablePropertyType.d.ts +0 -0
  242. package/lib/{domain → types/domain}/LocalsContainer.d.ts +0 -0
  243. package/lib/{domain → types/domain}/Provider.d.ts +17 -3
  244. package/lib/{domain → types/domain}/ProviderScope.d.ts +0 -0
  245. package/lib/{domain → types/domain}/ProviderType.d.ts +0 -0
  246. package/lib/{domain → types/domain}/index.d.ts +0 -0
  247. package/lib/{errors → types/errors}/InjectionError.d.ts +0 -0
  248. package/lib/{errors → types/errors}/UndefinedTokenError.d.ts +0 -0
  249. package/lib/{index.d.ts → types/index.d.ts} +1 -0
  250. package/lib/{interfaces → types/interfaces}/DIConfigurationOptions.d.ts +0 -0
  251. package/lib/{interfaces → types/interfaces}/DILogger.d.ts +0 -0
  252. package/lib/{interfaces → types/interfaces}/DIResolver.d.ts +0 -0
  253. package/lib/{interfaces → types/interfaces}/IProvider.d.ts +0 -0
  254. package/lib/{interfaces → types/interfaces}/InjectableProperties.d.ts +8 -4
  255. package/lib/{interfaces → types/interfaces}/InterceptorContext.d.ts +0 -0
  256. package/lib/{interfaces → types/interfaces}/InterceptorMethods.d.ts +0 -0
  257. package/lib/{interfaces → types/interfaces}/InvokeOptions.d.ts +0 -0
  258. package/lib/{interfaces → types/interfaces}/OnDestroy.d.ts +0 -0
  259. package/lib/{interfaces → types/interfaces}/OnInit.d.ts +0 -0
  260. package/lib/{interfaces → types/interfaces}/RegistrySettings.d.ts +6 -2
  261. package/lib/types/interfaces/ResolvedInvokeOptions.d.ts +12 -0
  262. package/lib/{interfaces → types/interfaces}/TokenProvider.d.ts +0 -0
  263. package/lib/{interfaces → types/interfaces}/index.d.ts +1 -0
  264. package/lib/{registries → types/registries}/GlobalProviders.d.ts +5 -1
  265. package/lib/{registries → types/registries}/ProviderRegistry.d.ts +0 -0
  266. package/lib/{services → types/services}/DIConfiguration.d.ts +0 -0
  267. package/lib/{services → types/services}/DILogger.d.ts +0 -0
  268. package/lib/{services → types/services}/DITest.d.ts +5 -1
  269. package/lib/{services → types/services}/InjectorService.d.ts +31 -14
  270. package/lib/types/utils/colors.d.ts +5 -0
  271. package/lib/{utils → types/utils}/createContainer.d.ts +0 -0
  272. package/lib/types/utils/data/Test1.d.ts +3 -0
  273. package/lib/types/utils/data/Test2.d.ts +3 -0
  274. package/lib/{utils → types/utils}/getConfiguration.d.ts +0 -0
  275. package/lib/{utils → types/utils}/setLoggerLevel.d.ts +0 -0
  276. package/package.json +15 -11
  277. package/readme.md +1 -1
  278. package/tsconfig.compile.esm.json +24 -0
  279. package/lib/index.js +0 -2271
  280. package/lib/index.js.map +0 -1
  281. package/lib/index.modern.js +0 -2235
  282. package/lib/index.modern.js.map +0 -1
@@ -1,2235 +0,0 @@
1
- import { getClassOrSymbol, Store, isClass, classOf, nameOf, StoreSet, decoratorTypeOf, UnsupportedDecoratorType, DecoratorTypes, Metadata, useDecorators, isString, getConstructorArgNames, proxyDelegation, setValue, getValue, deepMerge, deepClone, ancestorsOf, prototypeOf, isPromise, isInheritedFrom, isFunction, Env } from '@tsed/core';
2
- import { levels, Logger, $log } from '@tsed/logger';
3
- import { __decorate, __metadata } from 'tslib';
4
- import chalk from 'chalk';
5
-
6
- const INJECTABLE_PROP = "DI:INJECTABLE_PROP";
7
- const DI_PARAMS = "DI:PARAMS";
8
- const DI_PARAM_OPTIONS = "DI:PARAM:OPTIONS";
9
-
10
- function _extends() {
11
- _extends = Object.assign || function (target) {
12
- for (var i = 1; i < arguments.length; i++) {
13
- var source = arguments[i];
14
-
15
- for (var key in source) {
16
- if (Object.prototype.hasOwnProperty.call(source, key)) {
17
- target[key] = source[key];
18
- }
19
- }
20
- }
21
-
22
- return target;
23
- };
24
-
25
- return _extends.apply(this, arguments);
26
- }
27
-
28
- function _objectWithoutPropertiesLoose(source, excluded) {
29
- if (source == null) return {};
30
- var target = {};
31
- var sourceKeys = Object.keys(source);
32
- var key, i;
33
-
34
- for (i = 0; i < sourceKeys.length; i++) {
35
- key = sourceKeys[i];
36
- if (excluded.indexOf(key) >= 0) continue;
37
- target[key] = source[key];
38
- }
39
-
40
- return target;
41
- }
42
-
43
- var id = 0;
44
-
45
- function _classPrivateFieldLooseKey(name) {
46
- return "__private_" + id++ + "_" + name;
47
- }
48
-
49
- function _classPrivateFieldLooseBase(receiver, privateKey) {
50
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
51
- throw new TypeError("attempted to use private field on non-instance");
52
- }
53
-
54
- return receiver;
55
- }
56
-
57
- var ProviderScope;
58
-
59
- (function (ProviderScope) {
60
- ProviderScope["SINGLETON"] = "singleton";
61
- ProviderScope["REQUEST"] = "request";
62
- ProviderScope["INSTANCE"] = "instance";
63
- })(ProviderScope || (ProviderScope = {}));
64
-
65
- var ProviderType;
66
-
67
- (function (ProviderType) {
68
- ProviderType["VALUE"] = "value";
69
- ProviderType["FACTORY"] = "factory";
70
- ProviderType["SERVICE"] = "service";
71
- ProviderType["PROVIDER"] = "provider";
72
- ProviderType["MODULE"] = "module";
73
- ProviderType["CONTROLLER"] = "controller";
74
- ProviderType["INTERCEPTOR"] = "interceptor";
75
- ProviderType["MIDDLEWARE"] = "middleware";
76
- })(ProviderType || (ProviderType = {}));
77
-
78
- var _provide = /*#__PURE__*/_classPrivateFieldLooseKey("provide");
79
-
80
- var _store = /*#__PURE__*/_classPrivateFieldLooseKey("store");
81
-
82
- var _tokenStore = /*#__PURE__*/_classPrivateFieldLooseKey("tokenStore");
83
-
84
- class Provider {
85
- constructor(token, options = {}) {
86
- Object.defineProperty(this, _provide, {
87
- writable: true,
88
- value: void 0
89
- });
90
- Object.defineProperty(this, _store, {
91
- writable: true,
92
- value: void 0
93
- });
94
- Object.defineProperty(this, _tokenStore, {
95
- writable: true,
96
- value: void 0
97
- });
98
- this.type = ProviderType.PROVIDER;
99
- this.provide = token;
100
- this.useClass = token;
101
- Object.assign(this, options);
102
- }
103
-
104
- get token() {
105
- return _classPrivateFieldLooseBase(this, _provide)[_provide];
106
- }
107
-
108
- get provide() {
109
- return _classPrivateFieldLooseBase(this, _provide)[_provide];
110
- }
111
-
112
- set provide(value) {
113
- if (value) {
114
- _classPrivateFieldLooseBase(this, _provide)[_provide] = getClassOrSymbol(value);
115
- _classPrivateFieldLooseBase(this, _tokenStore)[_tokenStore] = _classPrivateFieldLooseBase(this, _store)[_store] = Store.from(value);
116
- }
117
- }
118
-
119
- get useClass() {
120
- return this._useClass;
121
- }
122
- /**
123
- * Create a new store if the given value is a class. Otherwise the value is ignored.
124
- * @param value
125
- */
126
-
127
-
128
- set useClass(value) {
129
- if (isClass(value)) {
130
- this._useClass = classOf(value);
131
- _classPrivateFieldLooseBase(this, _store)[_store] = Store.from(value);
132
- }
133
- }
134
-
135
- get className() {
136
- return this.name;
137
- }
138
-
139
- get name() {
140
- return nameOf(this.provide);
141
- }
142
-
143
- get store() {
144
- return _classPrivateFieldLooseBase(this, _store)[_store];
145
- }
146
- /**
147
- * Get the scope of the provider.
148
- *
149
- * ::: tip Note
150
- * Async provider is always a SINGLETON
151
- * :::
152
- *
153
- * @returns {boolean}
154
- */
155
-
156
-
157
- get scope() {
158
- if (this.isAsync()) {
159
- return ProviderScope.SINGLETON;
160
- }
161
-
162
- return this.get("scope");
163
- }
164
- /**
165
- * Change the scope value of the provider.
166
- * @param scope
167
- */
168
-
169
-
170
- set scope(scope) {
171
- this.store.set("scope", scope);
172
- }
173
-
174
- get configuration() {
175
- return this.get("configuration");
176
- }
177
-
178
- set configuration(configuration) {
179
- this.store.set("configuration", configuration);
180
- }
181
-
182
- get(key) {
183
- return this.store.get(key) || _classPrivateFieldLooseBase(this, _tokenStore)[_tokenStore].get(key);
184
- }
185
-
186
- isAsync() {
187
- return !!this.useAsyncFactory;
188
- }
189
-
190
- clone() {
191
- return new (classOf(this))(_classPrivateFieldLooseBase(this, _provide)[_provide], this);
192
- }
193
-
194
- toString() {
195
- return ["Token", this.name, this.useClass && nameOf(this.useClass), this.useFactory && "Factory", this.useValue && "Value", this.useAsyncFactory && "AsyncFactory"].filter(Boolean).join(":");
196
- }
197
-
198
- }
199
-
200
- var _settings = /*#__PURE__*/_classPrivateFieldLooseKey("settings");
201
-
202
- class GlobalProviderRegistry extends Map {
203
- constructor() {
204
- super(...arguments);
205
- Object.defineProperty(this, _settings, {
206
- writable: true,
207
- value: void 0
208
- });
209
- _classPrivateFieldLooseBase(this, _settings)[_settings] = new Map();
210
- }
211
-
212
- /**
213
- * The get() method returns a specified element from a Map object.
214
- * @param key Required. The key of the element to return from the Map object.
215
- * @returns {T} Returns the element associated with the specified key or undefined if the key can't be found in the Map object.
216
- */
217
- get(key) {
218
- return super.get(getClassOrSymbol(key));
219
- }
220
- /**
221
- * The has() method returns a boolean indicating whether an element with the specified key exists or not.
222
- * @param key
223
- * @returns {boolean}
224
- */
225
-
226
-
227
- has(key) {
228
- return super.has(getClassOrSymbol(key));
229
- }
230
- /**
231
- * The set() method adds or updates an element with a specified key and value to a Map object.
232
- * @param key Required. The key of the element to add to the Map object.
233
- * @param metadata Required. The value of the element to add to the Map object.
234
- */
235
-
236
-
237
- set(key, metadata) {
238
- super.set(getClassOrSymbol(key), metadata);
239
- return this;
240
- }
241
- /**
242
- *
243
- * @param target
244
- * @param options
245
- */
246
-
247
-
248
- merge(target, options) {
249
- const meta = this.createIfNotExists(target, options);
250
- Object.keys(options).forEach(key => {
251
- meta[key] = options[key];
252
- });
253
- this.set(target, meta);
254
- }
255
- /**
256
- * The delete() method removes the specified element from a Map object.
257
- * @param key Required. The key of the element to remove from the Map object.
258
- * @returns {boolean} Returns true if an element in the Map object existed and has been removed, or false if the element does not exist.
259
- */
260
-
261
-
262
- delete(key) {
263
- return super.delete(getClassOrSymbol(key));
264
- }
265
-
266
- createRegistry(type, model, options = {}) {
267
- const defaultOptions = this.getRegistrySettings(type);
268
- options = Object.assign(defaultOptions, _extends({}, options, {
269
- model
270
- }));
271
-
272
- _classPrivateFieldLooseBase(this, _settings)[_settings].set(type, options);
273
-
274
- return this;
275
- }
276
-
277
- onInvoke(provider, locals, deps) {
278
- const settings = _classPrivateFieldLooseBase(this, _settings)[_settings].get(provider.type);
279
-
280
- if (settings != null && settings.onInvoke) {
281
- settings.onInvoke(provider, locals, deps);
282
- }
283
- }
284
-
285
- getRegistrySettings(target) {
286
- let type = "provider";
287
-
288
- if (typeof target === "string") {
289
- type = target;
290
- } else {
291
- const provider = this.get(target);
292
-
293
- if (provider) {
294
- type = provider.type;
295
- }
296
- }
297
-
298
- return _classPrivateFieldLooseBase(this, _settings)[_settings].get(type) || {
299
- model: Provider
300
- };
301
- }
302
-
303
- createRegisterFn(type) {
304
- return (provider, instance) => {
305
- // istanbul ignore next
306
- if (!provider.provide) {
307
- provider = {
308
- provide: provider
309
- };
310
- }
311
-
312
- provider = Object.assign({
313
- instance
314
- }, provider, {
315
- type
316
- });
317
- this.merge(provider.provide, provider);
318
- };
319
- }
320
- /**
321
- *
322
- * @param key
323
- * @param options
324
- */
325
-
326
-
327
- createIfNotExists(key, options) {
328
- const type = options.type || ProviderType.PROVIDER;
329
-
330
- if (!this.has(key)) {
331
- const {
332
- model = Provider
333
- } = _classPrivateFieldLooseBase(this, _settings)[_settings].get(type) || {};
334
- const item = new model(key);
335
- this.set(key, item);
336
- }
337
-
338
- return this.get(key);
339
- }
340
-
341
- }
342
- /**
343
- *
344
- * @type {GlobalProviders}
345
- */
346
- // tslint:disable-next-line: variable-name
347
-
348
- const GlobalProviders = new GlobalProviderRegistry();
349
-
350
- class LocalsContainer extends Map {
351
- /**
352
- * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
353
- * @param eventName The event name to emit at all services.
354
- * @param args List of the parameters to give to each services.
355
- * @returns {Promise<any[]>} A list of promises.
356
- */
357
- async emit(eventName, ...args) {
358
- for (const handler of this.getListeners(eventName)) {
359
- await handler(...args);
360
- }
361
- }
362
- /**
363
- * @param eventName
364
- * @param value
365
- * @param args
366
- */
367
-
368
-
369
- alter(eventName, value, ...args) {
370
- for (const handler of this.getListeners(eventName)) {
371
- value = handler(value, ...args);
372
- }
373
-
374
- return value;
375
- }
376
- /**
377
- * @param eventName
378
- * @param value
379
- * @param args
380
- */
381
-
382
-
383
- async alterAsync(eventName, value, ...args) {
384
- for (const handler of this.getListeners(eventName)) {
385
- value = handler(value, ...args);
386
- }
387
-
388
- return value;
389
- }
390
-
391
- toArray() {
392
- return [...this.values()];
393
- }
394
-
395
- async destroy() {
396
- await this.emit("$onDestroy");
397
- this.clear();
398
- }
399
-
400
- getListeners(event) {
401
- return this.toArray().reduce((listeners, instance) => {
402
- if (typeof instance === "object" && instance && event in instance) {
403
- return listeners.concat(instance[event].bind(instance));
404
- }
405
-
406
- return listeners;
407
- }, []);
408
- }
409
-
410
- }
411
-
412
- class Container extends LocalsContainer {
413
- /**
414
- *
415
- * @param token
416
- * @param settings
417
- */
418
- add(token, settings = {}) {
419
- const provider = GlobalProviders.has(token) ? GlobalProviders.get(token).clone() : new Provider(token);
420
- Object.assign(provider, settings);
421
- return super.set(token, provider);
422
- }
423
- /**
424
- * Add a provider to the
425
- * @param token
426
- * @param settings
427
- */
428
-
429
-
430
- addProvider(token, settings = {}) {
431
- return this.add(token, settings);
432
- }
433
- /**
434
- *
435
- * @param token
436
- */
437
-
438
-
439
- hasProvider(token) {
440
- return super.has(token);
441
- }
442
- /**
443
- * Add a provider to the
444
- * @param token
445
- * @param provider
446
- */
447
-
448
-
449
- setProvider(token, provider) {
450
- return super.set(token, provider);
451
- }
452
- /**
453
- * The getProvider() method returns a specified element from a Map object.
454
- * @returns {T} Returns the element associated with the specified key or undefined if the key can't be found in the Map object.
455
- * @param token
456
- */
457
-
458
-
459
- getProvider(token) {
460
- return super.get(token);
461
- }
462
- /**
463
- * Get all providers registered in the injector container.
464
- *
465
- * @param {ProviderType} type Filter the list by the given ProviderType.
466
- * @returns {[TokenProvider , Provider<any>][]}
467
- */
468
-
469
-
470
- getProviders(type) {
471
- return Array.from(this).filter(([_, provider]) => type ? provider.type === type : true).map(([_, provider]) => provider);
472
- }
473
-
474
- addProviders(container) {
475
- container.forEach(provider => {
476
- if (!this.hasProvider(provider.provide)) {
477
- this.setProvider(provider.provide, provider.clone());
478
- }
479
- });
480
- }
481
-
482
- }
483
-
484
- var InjectablePropertyType;
485
-
486
- (function (InjectablePropertyType) {
487
- InjectablePropertyType["METHOD"] = "method";
488
- InjectablePropertyType["PROPERTY"] = "property";
489
- InjectablePropertyType["CONSTANT"] = "constant";
490
- InjectablePropertyType["VALUE"] = "value";
491
- InjectablePropertyType["INTERCEPTOR"] = "interceptor";
492
- })(InjectablePropertyType || (InjectablePropertyType = {}));
493
-
494
- var _additionalProps = /*#__PURE__*/_classPrivateFieldLooseKey("additionalProps");
495
-
496
- var _dateStart = /*#__PURE__*/_classPrivateFieldLooseKey("dateStart");
497
-
498
- var _ignoreLog = /*#__PURE__*/_classPrivateFieldLooseKey("ignoreLog");
499
-
500
- var _stack = /*#__PURE__*/_classPrivateFieldLooseKey("stack");
501
-
502
- var _level = /*#__PURE__*/_classPrivateFieldLooseKey("level");
503
-
504
- class ContextLogger {
505
- constructor(logger, {
506
- id,
507
- url = "",
508
- dateStart = new Date(),
509
- ignoreUrlPatterns = [],
510
- minimalRequestPicker,
511
- completeRequestPicker,
512
- level = "all",
513
- maxStackSize = 30,
514
- ignoreLog,
515
- additionalProps
516
- }) {
517
- Object.defineProperty(this, _additionalProps, {
518
- writable: true,
519
- value: void 0
520
- });
521
- Object.defineProperty(this, _dateStart, {
522
- writable: true,
523
- value: void 0
524
- });
525
- Object.defineProperty(this, _ignoreLog, {
526
- writable: true,
527
- value: void 0
528
- });
529
- Object.defineProperty(this, _stack, {
530
- writable: true,
531
- value: void 0
532
- });
533
- Object.defineProperty(this, _level, {
534
- writable: true,
535
- value: void 0
536
- });
537
- this.logger = logger;
538
- _classPrivateFieldLooseBase(this, _stack)[_stack] = [];
539
- this.id = id;
540
- this.url = url;
541
- _classPrivateFieldLooseBase(this, _additionalProps)[_additionalProps] = additionalProps || {};
542
- _classPrivateFieldLooseBase(this, _dateStart)[_dateStart] = dateStart;
543
-
544
- _classPrivateFieldLooseBase(this, _ignoreLog)[_ignoreLog] = ignoreLog || (() => false);
545
-
546
- this.minimalRequestPicker = minimalRequestPicker || (l => l);
547
-
548
- this.completeRequestPicker = completeRequestPicker || (l => l); // @ts-ignore
549
-
550
-
551
- _classPrivateFieldLooseBase(this, _level)[_level] = levels()[level.toUpperCase()] || levels().ALL;
552
- this.maxStackSize = maxStackSize;
553
- }
554
-
555
- info(obj) {
556
- this.run(levels().INFO, obj, obj => this.minimalRequestPicker(this.getData(obj)));
557
- return this;
558
- }
559
-
560
- debug(obj, withRequest = true) {
561
- this.run(levels().DEBUG, obj, obj => {
562
- obj = this.getData(obj);
563
- return withRequest ? this.completeRequestPicker(obj) : obj;
564
- });
565
- return this;
566
- }
567
-
568
- warn(obj) {
569
- this.run(levels().WARN, obj, obj => this.completeRequestPicker(this.getData(obj)));
570
- return this;
571
- }
572
-
573
- error(obj) {
574
- this.run(levels().ERROR, obj, obj => this.completeRequestPicker(this.getData(obj)));
575
- return this;
576
- }
577
-
578
- trace(obj) {
579
- this.run(levels().TRACE, obj, obj => this.completeRequestPicker(this.getData(obj)));
580
- return this;
581
- }
582
-
583
- flush() {
584
- if (_classPrivateFieldLooseBase(this, _stack)[_stack].length) {
585
- _classPrivateFieldLooseBase(this, _stack)[_stack].forEach(({
586
- level,
587
- data
588
- }) => {
589
- this.logger[level](data);
590
- });
591
-
592
- _classPrivateFieldLooseBase(this, _stack)[_stack] = [];
593
- }
594
- }
595
-
596
- isLevelEnabled(otherLevel) {
597
- return _classPrivateFieldLooseBase(this, _level)[_level].isLessThanOrEqualTo(otherLevel);
598
- }
599
-
600
- destroy() {
601
- this.flush();
602
- this.logger = undefined;
603
- _classPrivateFieldLooseBase(this, _stack)[_stack] = undefined;
604
- }
605
- /**
606
- * Return the duration between the time when LogIncomingRequest has handle the request and now.
607
- * @returns {number}
608
- */
609
-
610
-
611
- getDuration() {
612
- return new Date().getTime() - _classPrivateFieldLooseBase(this, _dateStart)[_dateStart].getTime();
613
- }
614
-
615
- getData(obj) {
616
- if (typeof obj === "string") {
617
- obj = {
618
- message: obj
619
- };
620
- }
621
-
622
- return _extends({}, _classPrivateFieldLooseBase(this, _additionalProps)[_additionalProps], {
623
- reqId: this.id,
624
- time: new Date(),
625
- duration: this.getDuration()
626
- }, obj);
627
- }
628
-
629
- run(level, obj, mapper) {
630
- if (!this.isLevelEnabled(level)) {
631
- return;
632
- }
633
-
634
- if (!_classPrivateFieldLooseBase(this, _ignoreLog)[_ignoreLog](obj)) {
635
- _classPrivateFieldLooseBase(this, _stack)[_stack].push({
636
- level: level.levelStr.toLowerCase(),
637
- data: mapper(obj)
638
- });
639
- }
640
-
641
- if (this.maxStackSize < _classPrivateFieldLooseBase(this, _stack)[_stack].length) {
642
- this.flush();
643
- }
644
- }
645
-
646
- }
647
-
648
- const _excluded$1 = ["id", "injector", "logger", "ignoreLog"];
649
-
650
- var _container = /*#__PURE__*/_classPrivateFieldLooseKey("container");
651
-
652
- var _injector = /*#__PURE__*/_classPrivateFieldLooseKey("injector");
653
-
654
- class DIContext extends Map {
655
- constructor(_ref) {
656
- let {
657
- id,
658
- injector,
659
- logger,
660
- ignoreLog
661
- } = _ref,
662
- options = _objectWithoutPropertiesLoose(_ref, _excluded$1);
663
-
664
- super();
665
- /**
666
- * Date when request have been handled by the server. @@RequestLogger@@ use this date to log request duration.
667
- */
668
-
669
- Object.defineProperty(this, _container, {
670
- writable: true,
671
- value: void 0
672
- });
673
- Object.defineProperty(this, _injector, {
674
- writable: true,
675
- value: void 0
676
- });
677
- this.dateStart = new Date();
678
- _classPrivateFieldLooseBase(this, _container)[_container] = new LocalsContainer();
679
- this.id = id;
680
- injector && (_classPrivateFieldLooseBase(this, _injector)[_injector] = injector);
681
- this.logger = new ContextLogger(logger, _extends({}, options, {
682
- dateStart: this.dateStart,
683
- id,
684
- ignoreLog
685
- }));
686
- }
687
-
688
- /**
689
- * The request container used by the Ts.ED DI. It contain all services annotated with `@Scope(ProviderScope.REQUEST)`
690
- */
691
- get container() {
692
- return _classPrivateFieldLooseBase(this, _container)[_container];
693
- }
694
- /**
695
- *
696
- */
697
-
698
-
699
- get injector() {
700
- return _classPrivateFieldLooseBase(this, _injector)[_injector];
701
- }
702
-
703
- get env() {
704
- return this.injector.settings.env;
705
- }
706
-
707
- async destroy() {
708
- await this.container.destroy();
709
- this.logger.destroy(); // @ts-ignore
710
-
711
- delete this.logger;
712
- }
713
-
714
- async emit(eventName, ...args) {
715
- var _this$injector;
716
-
717
- return (_this$injector = this.injector) == null ? void 0 : _this$injector.emit(eventName, ...args);
718
- }
719
-
720
- }
721
-
722
- /**
723
- *
724
- * @param {"request" | "singleton" | ProviderScope} scope
725
- * @returns {Function}
726
- * @constructor
727
- */
728
-
729
- function Scope(scope = ProviderScope.REQUEST) {
730
- return StoreSet("scope", scope);
731
- }
732
-
733
- /**
734
- *
735
- */
736
-
737
- GlobalProviders.createRegistry(ProviderType.CONTROLLER, Provider);
738
- /**
739
- * Register a provider configuration.
740
- * @param {IProvider<any>} provider
741
- */
742
-
743
- function registerProvider(provider) {
744
- if (!provider.provide) {
745
- throw new Error("Provider.provide is required");
746
- }
747
-
748
- GlobalProviders.merge(provider.provide, provider);
749
- }
750
- /**
751
- * Add a new value in the `ProviderRegistry`.
752
- *
753
- * #### Example with symbol definition
754
- *
755
- *
756
- * ```typescript
757
- * import {registerValue, InjectorService} from "@tsed/di";
758
- *
759
- * const MyValue = Symbol.from("MyValue")
760
- *
761
- * registerValue({token: MyValue, useValue: "myValue"});
762
- *
763
- * @Service()
764
- * export class OtherService {
765
- * constructor(@Inject(MyValue) myValue: string){
766
- * console.log(myValue); /// "myValue"
767
- * }
768
- * }
769
- * ```
770
- */
771
-
772
- const registerValue = (provider, value) => {
773
- if (!provider.provide) {
774
- provider = {
775
- provide: provider
776
- };
777
- }
778
-
779
- provider = Object.assign({
780
- scope: ProviderScope.SINGLETON,
781
- useValue: value
782
- }, provider, {
783
- type: ProviderType.VALUE
784
- });
785
- GlobalProviders.merge(provider.provide, provider);
786
- };
787
- /**
788
- * Add a new controller in the `ProviderRegistry`. This controller will be built when `InjectorService` will be loaded.
789
- *
790
- * #### Example
791
- *
792
- * ```typescript
793
- * import {registerController, InjectorService} from "@tsed/di";
794
- *
795
- * export default class MyController {
796
- * constructor(){}
797
- * transform() {
798
- * return "test";
799
- * }
800
- * }
801
- *
802
- * registerController({provide: MyController});
803
- * // or
804
- * registerController(MyController);
805
- *
806
- * const injector = new InjectorService();
807
- * injector.load();
808
- *
809
- * const myController = injector.get<MyController>(MyController);
810
- * myController.getFoo(); // test
811
- * ```
812
- *
813
- * @param provider Provider configuration.
814
- */
815
-
816
- const registerController = GlobalProviders.createRegisterFn(ProviderType.CONTROLLER);
817
-
818
- /**
819
- * The decorators `@Injectable()` declare a new service can be injected in other service, controller, interceptor, etc.. on there `constructor`.
820
- * All classes annotated with `@Injectable()` are built one time, excepted if you change the default provider configuration.
821
- *
822
- * <<< @/docs/snippets/providers/getting-started-injectable.ts
823
- *
824
- * ::: tip
825
- * `@Injectable()` use the `reflect-metadata` to collect and inject the built provided to other services.
826
- * :::
827
- *
828
- * ### Options
829
- *
830
- * - type (@@ProviderType@@ or `string`): Kind of provider. (Default: `ProviderType.PROVIDER`)
831
- * - scope (@@ProviderScope@): Kind of provider. (Default: `ProviderScope.SINGLETON`)
832
- * - deps (`Type<any>`): List of class or provider which will be injected to the constructor (Note: This options override default metadata generated by Typescript).
833
- *
834
- * @returns {Function}
835
- * @decorator
836
- */
837
-
838
- function Injectable(options = {}) {
839
- return provide => {
840
- registerProvider(_extends({}, options, {
841
- provide
842
- }));
843
- };
844
- }
845
-
846
- /**
847
- * The decorators `@Service()` declare a new service can be injected in other service or controller on there `constructor`.
848
- * All services annotated with `@Service()` are constructed one time.
849
- *
850
- * > `@Service()` use the `reflect-metadata` to collect and inject service on controllers or other services.
851
- *
852
- * @returns {Function}
853
- * @decorator
854
- */
855
-
856
- function Service() {
857
- return Injectable();
858
- }
859
-
860
- /**
861
- * Override a provider which is already registered in ProviderRegistry.
862
- * @returns {Function}
863
- * @decorators
864
- * @param originalProvider
865
- */
866
-
867
- function OverrideProvider(originalProvider) {
868
- return target => {
869
- GlobalProviders.get(originalProvider).useClass = target;
870
- };
871
- }
872
-
873
- /**
874
- * Inject a provider to another provider.
875
- *
876
- * Use this decorator to inject a custom provider on constructor parameter or property.
877
- *
878
- * ```typescript
879
- * @Injectable()
880
- * export class MyService {
881
- * @Inject(CONNECTION)
882
- * connection: CONNECTION;
883
- * }
884
- * ```
885
- *
886
- * @param symbol
887
- * @param onGet Use the given name method to inject
888
- * @returns {Function}
889
- * @decorator
890
- */
891
-
892
- function Inject(symbol, onGet) {
893
- return (target, propertyKey, descriptor) => {
894
- const bindingType = decoratorTypeOf([target, propertyKey, descriptor]);
895
-
896
- switch (bindingType) {
897
- case DecoratorTypes.PARAM:
898
- case DecoratorTypes.PARAM_CTOR:
899
- if (symbol) {
900
- const paramTypes = Metadata.getParamTypes(target, propertyKey);
901
- paramTypes[descriptor] = symbol;
902
- Metadata.setParamTypes(target, propertyKey, paramTypes);
903
- }
904
-
905
- break;
906
-
907
- case DecoratorTypes.PROP:
908
- Store.from(target).merge(INJECTABLE_PROP, {
909
- [propertyKey]: {
910
- bindingType,
911
- propertyKey,
912
- onGet,
913
- useType: symbol || Metadata.getType(target, propertyKey)
914
- }
915
- });
916
- break;
917
-
918
- case DecoratorTypes.METHOD:
919
- Store.from(target).merge(INJECTABLE_PROP, {
920
- [propertyKey]: {
921
- bindingType,
922
- propertyKey
923
- }
924
- });
925
- return descriptor;
926
-
927
- default:
928
- throw new UnsupportedDecoratorType(Inject, [target, propertyKey, descriptor]);
929
- }
930
- };
931
- }
932
-
933
- /**
934
- * Return value from Configuration.
935
- *
936
- * ## Example
937
- *
938
- * ```typescript
939
- * import {Env} from "@tsed/core";
940
- * import {Constant, Value} from "@tsed/di";
941
- *
942
- * export class MyClass {
943
- *
944
- * @Constant("env")
945
- * env: Env;
946
- *
947
- * @Value("swagger.path")
948
- * swaggerPath: string;
949
- *
950
- * @Value("swagger.path", "defaultValue")
951
- * swaggerPath: string;
952
- *
953
- * constructor() {
954
- * console.log(this.swaggerPath) // undefined. Not available on constructor
955
- * }
956
- *
957
- * $onInit() {
958
- * console.log(this.swaggerPath) // something
959
- * }
960
- * }
961
- * ```
962
- *
963
- * @param {string} expression
964
- * @param defaultValue
965
- * @returns {(targetClass: any, attributeName: string) => any}
966
- * @decorator
967
- */
968
-
969
- function Constant(expression, defaultValue) {
970
- return (target, propertyKey) => {
971
- Store.from(target).merge(INJECTABLE_PROP, {
972
- [propertyKey]: {
973
- bindingType: InjectablePropertyType.CONSTANT,
974
- propertyKey,
975
- expression,
976
- defaultValue
977
- }
978
- });
979
- };
980
- }
981
-
982
- /**
983
- * Return value from Configuration.
984
- *
985
- * ## Example
986
- *
987
- * ```typescript
988
- * import {Env} from "@tsed/core";
989
- * import {Constant, Value} from "@tsed/di";
990
- *
991
- * export class MyClass {
992
- *
993
- * @Constant("env")
994
- * env: Env;
995
- *
996
- * @Value("swagger.path")
997
- * swaggerPath: string;
998
- *
999
- * @Value("swagger.path", "defaultValue")
1000
- * swaggerPath: string;
1001
- *
1002
- * constructor() {
1003
- * console.log(this.swaggerPath) // undefined. Not available on constructor
1004
- * }
1005
- *
1006
- * $onInit() {
1007
- * console.log(this.swaggerPath) // something
1008
- * }
1009
- * }
1010
- * ```
1011
- *
1012
- * @param expression
1013
- * @param defaultValue
1014
- * @returns {(targetClass: any, attributeName: string) => any}
1015
- * @decorator
1016
- */
1017
-
1018
- function Value(expression, defaultValue) {
1019
- return (target, propertyKey) => {
1020
- Store.from(target).merge(INJECTABLE_PROP, {
1021
- [propertyKey]: {
1022
- bindingType: InjectablePropertyType.VALUE,
1023
- propertyKey,
1024
- expression,
1025
- defaultValue
1026
- }
1027
- });
1028
- };
1029
- }
1030
-
1031
- /**
1032
- * Attaches interceptor to method call and executes the before and after methods
1033
- *
1034
- * @param interceptor
1035
- * @param options
1036
- * @decorator
1037
- */
1038
-
1039
- function Intercept(interceptor, options) {
1040
- return (target, propertyKey, descriptor) => {
1041
- Store.from(target).merge(INJECTABLE_PROP, {
1042
- [propertyKey]: {
1043
- bindingType: InjectablePropertyType.INTERCEPTOR,
1044
- propertyKey,
1045
- useType: interceptor,
1046
- options
1047
- }
1048
- });
1049
- return descriptor;
1050
- };
1051
- }
1052
-
1053
- /**
1054
- * The decorators `@Service()` declare a new service can be injected in other service or controller on there `constructor`.
1055
- * All services annotated with `@Service()` are constructed one time.
1056
- *
1057
- * > `@Service()` use the `reflect-metadata` to collect and inject service on controllers or other services.
1058
- *
1059
- * @returns {Function}
1060
- * @decorator
1061
- */
1062
-
1063
- function Interceptor() {
1064
- return Injectable({
1065
- type: ProviderType.INTERCEPTOR
1066
- });
1067
- }
1068
-
1069
- /**
1070
- * Get or set Configuration on a class.
1071
- *
1072
- * @decorator
1073
- */
1074
-
1075
- function Configuration(configuration = {}) {
1076
- return (...args) => {
1077
- switch (decoratorTypeOf(args)) {
1078
- case DecoratorTypes.CLASS:
1079
- StoreSet("configuration", configuration)(args[0]);
1080
- break;
1081
-
1082
- default:
1083
- case DecoratorTypes.PARAM_CTOR:
1084
- return Inject(Configuration)(args[0], args[1], args[2]);
1085
- }
1086
- };
1087
- }
1088
-
1089
- const _excluded = ["scopes", "imports", "resolvers", "deps", "scope"];
1090
- /**
1091
- * Declare a new Ts.ED module
1092
- *
1093
- * ## Options
1094
- * - imports: List of Provider which must be built by injector before invoking the module
1095
- * - resolvers: List of external DI must be used to resolve unknown provider
1096
- * - deps: List of provider must be injected to the module constructor (explicit declaration)
1097
- *
1098
- * @param options
1099
- * @decorator
1100
- */
1101
-
1102
- function Module(options = {}) {
1103
- const {
1104
- imports,
1105
- resolvers,
1106
- deps
1107
- } = options,
1108
- configuration = _objectWithoutPropertiesLoose(options, _excluded);
1109
-
1110
- return useDecorators(Configuration(configuration), Injectable({
1111
- type: ProviderType.MODULE,
1112
- scope: ProviderScope.SINGLETON,
1113
- imports,
1114
- deps,
1115
- injectable: false,
1116
- resolvers
1117
- }));
1118
- }
1119
-
1120
- /**
1121
- * Get instance options. This options depending on his invocation context.
1122
- *
1123
- * ```typescript
1124
- * import {Injectable, Opts, UseOpts} from "@tsed/di";
1125
- *
1126
- * @Injectable()
1127
- * class MyConfigurableService {
1128
- * source: string;
1129
- * constructor(@Opts options: any = {}) {
1130
- * console.log("Hello ", options.source); // log: Hello Service1 then Hello Service2
1131
- *
1132
- * this.source = options.source;
1133
- * }
1134
- * }
1135
- *
1136
- * @Injectable()
1137
- * class MyService1 {
1138
- * constructor(@UseOpts({source: 'Service1'}) service: MyConfigurableService) {
1139
- * console.log(service.source) // log: Service1
1140
- * }
1141
- * }
1142
- *
1143
- * @Injectable()
1144
- * class MyService2 {
1145
- * constructor(@UseOpts({source: 'Service2'}) service: MyConfigurableService) {
1146
- * console.log(service.source) // log: Service2
1147
- * }
1148
- * }
1149
- * ```
1150
- *
1151
- * ::: warning
1152
- * Using @@Opts@@ decorator on a constructor parameter change the Scope of the provider to `ProviderScope.INSTANCE`.
1153
- * :::
1154
- *
1155
- * @param target
1156
- * @param propertyKey
1157
- * @param index
1158
- * @decorator
1159
- */
1160
-
1161
- function Opts(target, propertyKey, index) {
1162
- Scope(ProviderScope.INSTANCE)(classOf(target));
1163
- Inject(DI_PARAM_OPTIONS)(target, propertyKey, index);
1164
- }
1165
-
1166
- /**
1167
- * Add options to invoke the Service.
1168
- *
1169
- * ```typescript
1170
- * import {Injectable, Opts, UseOpts} from "@tsed/di";
1171
- *
1172
- * @Injectable()
1173
- * class MyConfigurableService {
1174
- * source: string;
1175
- * constructor(@Opts options: any = {}) {
1176
- * console.log("Hello ", options.source); // log: Hello Service1 then Hello Service2
1177
- *
1178
- * this.source = options.source;
1179
- * }
1180
- * }
1181
- *
1182
- * @Injectable()
1183
- * class MyService1 {
1184
- * constructor(@UseOpts({source: 'Service1'}) service: MyConfigurableService) {
1185
- * console.log(service.source) // log: Service1
1186
- * }
1187
- * }
1188
- *
1189
- * @Injectable()
1190
- * class MyService2 {
1191
- * constructor(@UseOpts({source: 'Service2'}) service: MyConfigurableService) {
1192
- * console.log(service.source) // log: Service2
1193
- * }
1194
- * }
1195
- * ```
1196
- *
1197
- * ::: warning
1198
- * Using @@Opts@@ decorator on a constructor parameter change the Scope of the provider to `ProviderScope.INSTANCE`.
1199
- * :::
1200
- *
1201
- * @returns {Function}
1202
- * @decorator
1203
- * @param options
1204
- */
1205
-
1206
- function UseOpts(options) {
1207
- return (target, propertyKey, index) => {
1208
- const bindingType = decoratorTypeOf([target, propertyKey, index]);
1209
-
1210
- switch (bindingType) {
1211
- case DecoratorTypes.PARAM_CTOR:
1212
- Store.from(target).merge(`${DI_PARAM_OPTIONS}:${index}`, options);
1213
- break;
1214
-
1215
- case DecoratorTypes.PROP:
1216
- Store.from(target).merge(INJECTABLE_PROP, {
1217
- [propertyKey]: {
1218
- options
1219
- }
1220
- });
1221
- break;
1222
-
1223
- default:
1224
- throw new UnsupportedDecoratorType(UseOpts, [target, propertyKey, index]);
1225
- }
1226
- };
1227
- }
1228
-
1229
- class InjectionError extends Error {
1230
- constructor(token, origin) {
1231
- super(isString(origin) ? origin : "");
1232
- this.name = "INJECTION_ERROR";
1233
- this.tokens = [];
1234
- this.tokens = [token];
1235
-
1236
- if (origin) {
1237
- if (isString(origin)) {
1238
- this.origin = {
1239
- message: origin,
1240
- stack: this.stack
1241
- };
1242
- } else {
1243
- if (origin.tokens) {
1244
- this.tokens = this.tokens.concat(origin.tokens);
1245
- this.origin = origin.origin;
1246
- } else {
1247
- this.origin = origin;
1248
- this.stack = origin.stack;
1249
- }
1250
- }
1251
- }
1252
-
1253
- const originMessage = this.origin ? "\nOrigin: " + this.origin.message : "";
1254
- const tokensMessage = this.tokens.map(token => nameOf(token)).join(" > ");
1255
- this.message = `Injection failed on ${tokensMessage}${originMessage}`;
1256
- }
1257
-
1258
- static throwInjectorError(token, currentDependency, error) {
1259
- if (currentDependency && isClass(token)) {
1260
- error.message = printDependencyInjectionError(token, _extends({}, currentDependency, {
1261
- message: error.message
1262
- }));
1263
- }
1264
-
1265
- throw new InjectionError(token, error);
1266
- }
1267
-
1268
- }
1269
-
1270
- function printDependencyInjectionError(token, options) {
1271
- let erroredArg = "";
1272
- const args = getConstructorArgNames(token).map((arg, index) => {
1273
- if (options.index === index) {
1274
- erroredArg = arg;
1275
- arg = chalk.red(arg);
1276
- }
1277
-
1278
- return `${arg}: ${nameOf(options.deps[index])}`;
1279
- }).join(", ");
1280
- const signature = nameOf(token) + "->constructor(" + args + ")";
1281
- const indexOf = signature.indexOf(erroredArg) - 5;
1282
-
1283
- const drawline = indexOf => " ".repeat(indexOf) + chalk.red("^" + "‾".repeat(erroredArg.length - 1));
1284
-
1285
- return "Unable to inject dependency. " + options.message + "\n\n" + signature + "\n" + (indexOf > -1 ? drawline(indexOf) : "");
1286
- }
1287
-
1288
- class UndefinedTokenError extends Error {
1289
- constructor() {
1290
- super("Given token is undefined. Have you enabled emitDecoratorMetadata in your tsconfig.json or decorated your class with @Injectable, @Service, ... decorator ?");
1291
- this.name = "UNDEFINED_TOKEN_ERROR";
1292
- }
1293
-
1294
- }
1295
-
1296
- function createContainer(rootModule) {
1297
- const container = new Container(GlobalProviders.entries());
1298
-
1299
- if (rootModule) {
1300
- container.delete(rootModule);
1301
- }
1302
-
1303
- return container;
1304
- }
1305
-
1306
- class DIConfiguration {
1307
- constructor(initialProps = {}) {
1308
- this.default = new Map();
1309
- this.map = new Map();
1310
- Object.entries(_extends({
1311
- scopes: {},
1312
- resolvers: [],
1313
- imports: []
1314
- }, initialProps)).forEach(([key, value]) => {
1315
- this.default.set(key, value);
1316
- });
1317
- return proxyDelegation(this, {
1318
- ownKeys(target) {
1319
- return [...target.default.keys(), ...target.map.keys()];
1320
- }
1321
-
1322
- });
1323
- }
1324
-
1325
- get scopes() {
1326
- return this.getRaw("scopes");
1327
- }
1328
-
1329
- set scopes(value) {
1330
- this.setRaw("scopes", value);
1331
- }
1332
-
1333
- get resolvers() {
1334
- return this.getRaw("resolvers");
1335
- }
1336
-
1337
- set resolvers(resolvers) {
1338
- this.setRaw("resolvers", resolvers);
1339
- }
1340
-
1341
- get imports() {
1342
- return this.getRaw("imports");
1343
- }
1344
-
1345
- set imports(imports) {
1346
- this.setRaw("imports", imports);
1347
- }
1348
- /**
1349
- *
1350
- * @param callbackfn
1351
- * @param thisArg
1352
- */
1353
-
1354
-
1355
- forEach(callbackfn, thisArg) {
1356
- return new Set([...Array.from(this.default.keys()), ...Array.from(this.map.keys())]).forEach(key => {
1357
- callbackfn(this.getRaw(key), key, this.map);
1358
- }, thisArg);
1359
- }
1360
- /**
1361
- *
1362
- * @param propertyKey
1363
- * @param value
1364
- */
1365
-
1366
-
1367
- set(propertyKey, value) {
1368
- if (typeof propertyKey === "string") {
1369
- this.setRaw(propertyKey, value);
1370
- } else {
1371
- Object.entries(propertyKey).forEach(([key, value]) => {
1372
- this[key] = value;
1373
- });
1374
- }
1375
-
1376
- return this;
1377
- }
1378
-
1379
- setRaw(propertyKey, value) {
1380
- setValue(this.map, propertyKey, value);
1381
- return this;
1382
- }
1383
- /**
1384
- *
1385
- * @param propertyKey
1386
- * @param defaultValue
1387
- * @returns {undefined|any}
1388
- */
1389
-
1390
-
1391
- get(propertyKey, defaultValue) {
1392
- return this.resolve(this.getRaw(propertyKey, defaultValue));
1393
- }
1394
-
1395
- getRaw(propertyKey, defaultValue) {
1396
- const value = getValue(this.map, propertyKey);
1397
-
1398
- if (value !== undefined) {
1399
- return value;
1400
- }
1401
-
1402
- return getValue(this.default, propertyKey, defaultValue);
1403
- }
1404
-
1405
- merge(obj) {
1406
- Object.entries(obj).forEach(([key, value]) => {
1407
- const descriptor = Object.getOwnPropertyDescriptor(DIConfiguration.prototype, key);
1408
- const originalValue = this.get(key);
1409
- value = deepMerge(value, originalValue);
1410
-
1411
- if (descriptor && !["default", "set", "map", "get"].includes(key)) {
1412
- this[key] = value;
1413
- }
1414
- });
1415
- }
1416
- /**
1417
- *
1418
- * @param value
1419
- * @returns {any}
1420
- */
1421
-
1422
-
1423
- resolve(value) {
1424
- if (typeof value === "object" && value !== null) {
1425
- if (![Array, Object].includes(classOf(value))) {
1426
- return value;
1427
- }
1428
-
1429
- return Object.entries(value).reduce((o, [k, v]) => {
1430
- // @ts-ignore
1431
- o[k] = this.resolve(v);
1432
- return o;
1433
- }, Array.isArray(value) ? [] : {});
1434
- }
1435
-
1436
- if (typeof value === "string") {
1437
- const replacer = (match, key) => getValue(this.map, key);
1438
-
1439
- return value.replace(/\${([\w.]+)}/gi, replacer).replace(/<([\w.]+)>/gi, replacer).replace(/{{([\w.]+)}}/gi, replacer);
1440
- }
1441
-
1442
- return value;
1443
- }
1444
-
1445
- build() {
1446
- this.forEach((value, key) => this.map.set(key, this.resolve(value)));
1447
- this.set = this.setRaw;
1448
-
1449
- this.get = this.getRaw = (propertyKey, defaultValue) => getValue(this.map, propertyKey, defaultValue);
1450
- }
1451
-
1452
- }
1453
-
1454
- var InjectorService_1;
1455
- /**
1456
- * This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.
1457
- *
1458
- * ### Example:
1459
- *
1460
- * ```typescript
1461
- * import {InjectorService} from "@tsed/di";
1462
- *
1463
- * // Import the services (all services are decorated with @Service()";
1464
- * import MyService1 from "./services/service1";
1465
- * import MyService2 from "./services/service2";
1466
- * import MyService3 from "./services/service3";
1467
- *
1468
- * // When all services is imported you can load InjectorService.
1469
- * const injector = new InjectorService()
1470
- *
1471
- * await injector.load();
1472
- *
1473
- * const myService1 = injector.get<MyService1>(MyServcice1);
1474
- * ```
1475
- */
1476
-
1477
- let InjectorService = InjectorService_1 = class InjectorService extends Container {
1478
- constructor() {
1479
- super();
1480
- this.settings = new DIConfiguration();
1481
- this.logger = console;
1482
- this.resolvedConfiguration = false;
1483
- const provider = this.addProvider(InjectorService_1).getProvider(InjectorService_1);
1484
- provider.instance = this;
1485
- }
1486
-
1487
- get resolvers() {
1488
- return this.settings.resolvers;
1489
- }
1490
-
1491
- get scopes() {
1492
- return this.settings.scopes || {};
1493
- }
1494
- /**
1495
- * Retrieve default scope for a given provider.
1496
- * @param provider
1497
- */
1498
-
1499
-
1500
- scopeOf(provider) {
1501
- return provider.scope || this.scopes[provider.type] || ProviderScope.SINGLETON;
1502
- }
1503
- /**
1504
- * Clone a provider from GlobalProviders and the given token. forkProvider method build automatically the provider if the instance parameter ins't given.
1505
- * @param token
1506
- * @param settings
1507
- */
1508
-
1509
-
1510
- forkProvider(token, settings = {}) {
1511
- if (!this.hasProvider(token)) {
1512
- this.addProvider(token);
1513
- }
1514
-
1515
- const provider = this.getProvider(token);
1516
- Object.assign(provider, settings);
1517
- provider.instance = this.invoke(token);
1518
- return provider;
1519
- }
1520
- /**
1521
- * Return a list of instance build by the injector.
1522
- */
1523
-
1524
-
1525
- toArray() {
1526
- return super.toArray().map(provider => provider.instance);
1527
- }
1528
- /**
1529
- * Get a service or factory already constructed from his symbol or class.
1530
- *
1531
- * #### Example
1532
- *
1533
- * ```typescript
1534
- * import {InjectorService} from "@tsed/di";
1535
- * import MyService from "./services";
1536
- *
1537
- * class OtherService {
1538
- * constructor(injectorService: InjectorService) {
1539
- * const myService = injectorService.get<MyService>(MyService);
1540
- * }
1541
- * }
1542
- * ```
1543
- *
1544
- * @param token The class or symbol registered in InjectorService.
1545
- * @param options
1546
- * @returns {boolean}
1547
- */
1548
-
1549
-
1550
- get(token, options = {}) {
1551
- var _super$get;
1552
-
1553
- const instance = (_super$get = super.get(getClassOrSymbol(token))) == null ? void 0 : _super$get.instance;
1554
-
1555
- if (instance !== undefined) {
1556
- return instance;
1557
- }
1558
-
1559
- if (!this.hasProvider(token)) {
1560
- for (const resolver of this.resolvers) {
1561
- const result = resolver.get(token, options);
1562
-
1563
- if (result !== undefined) {
1564
- return result;
1565
- }
1566
- }
1567
- }
1568
- }
1569
- /**
1570
- * The has() method returns a boolean indicating whether an element with the specified key exists or not.
1571
- * @returns {boolean}
1572
- * @param token
1573
- */
1574
-
1575
-
1576
- has(token) {
1577
- return super.has(getClassOrSymbol(token)) && this.get(token) !== undefined;
1578
- }
1579
- /**
1580
- * Invoke the class and inject all services that required by the class constructor.
1581
- *
1582
- * #### Example
1583
- *
1584
- * ```typescript
1585
- * import {InjectorService} from "@tsed/di";
1586
- * import MyService from "./services";
1587
- *
1588
- * class OtherService {
1589
- * constructor(injectorService: InjectorService) {
1590
- * const myService = injectorService.invoke<MyService>(MyService);
1591
- * }
1592
- * }
1593
- * ```
1594
- *
1595
- * @param token The injectable class to invoke. Class parameters are injected according constructor signature.
1596
- * @param locals Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
1597
- * @param options
1598
- * @returns {T} The class constructed.
1599
- */
1600
-
1601
-
1602
- invoke(token, locals = new LocalsContainer(), options = {}) {
1603
- const provider = this.ensureProvider(token);
1604
- let instance;
1605
- !locals.has(Configuration) && locals.set(Configuration, this.settings);
1606
-
1607
- if (locals.has(token)) {
1608
- return locals.get(token);
1609
- }
1610
-
1611
- if (token === DI_PARAM_OPTIONS) {
1612
- return {};
1613
- }
1614
-
1615
- if (!provider || options.rebuild) {
1616
- instance = this.resolve(token, locals, options);
1617
- this.hasProvider(token) && (this.getProvider(token).instance = instance);
1618
- return instance;
1619
- }
1620
-
1621
- switch (this.scopeOf(provider)) {
1622
- case ProviderScope.SINGLETON:
1623
- if (!this.has(token)) {
1624
- provider.instance = this.resolve(token, locals, options);
1625
-
1626
- if (provider.isAsync()) {
1627
- provider.instance.then(instance => {
1628
- provider.instance = instance;
1629
- });
1630
- }
1631
- }
1632
-
1633
- instance = this.get(token);
1634
- break;
1635
-
1636
- case ProviderScope.REQUEST:
1637
- instance = this.resolve(token, locals, options);
1638
- locals.set(token, instance);
1639
- break;
1640
-
1641
- case ProviderScope.INSTANCE:
1642
- instance = this.resolve(provider.provide, locals, options);
1643
- break;
1644
- }
1645
-
1646
- return instance;
1647
- }
1648
- /**
1649
- * Build only providers which are asynchronous.
1650
- */
1651
-
1652
-
1653
- async loadAsync(locals = new LocalsContainer()) {
1654
- for (const [, provider] of this) {
1655
- if (!locals.has(provider.token)) {
1656
- if (provider.isAsync()) {
1657
- await this.invoke(provider.token, locals);
1658
- }
1659
-
1660
- if (provider.instance) {
1661
- locals.set(provider.token, provider.instance);
1662
- }
1663
- }
1664
- }
1665
-
1666
- return locals;
1667
- }
1668
-
1669
- loadSync(locals = new LocalsContainer()) {
1670
- for (const [, provider] of this) {
1671
- if (!locals.has(provider.token) && this.scopeOf(provider) === ProviderScope.SINGLETON) {
1672
- this.invoke(provider.token, locals);
1673
- }
1674
-
1675
- if (provider.instance !== undefined) {
1676
- locals.set(provider.token, provider.instance);
1677
- }
1678
- }
1679
-
1680
- return locals;
1681
- }
1682
- /**
1683
- * Boostrap injector from container and resolve configuration.
1684
- *
1685
- * @param container
1686
- */
1687
-
1688
-
1689
- bootstrap(container = createContainer()) {
1690
- // Clone all providers in the container
1691
- this.addProviders(container); // Resolve all configuration
1692
-
1693
- this.resolveConfiguration();
1694
- return this;
1695
- }
1696
- /**
1697
- * Build all providers from given container (or GlobalProviders) and emit `$onInit` event.
1698
- *
1699
- * @param container
1700
- * @param rootModule
1701
- */
1702
-
1703
-
1704
- async load(container = createContainer(), rootModule) {
1705
- this.bootstrap(container); // build async and sync provider
1706
-
1707
- let locals = await this.loadAsync();
1708
-
1709
- if (rootModule) {
1710
- await this.invoke(rootModule);
1711
- } // load sync provider
1712
-
1713
-
1714
- locals = this.loadSync(locals);
1715
- await locals.emit("$onInit");
1716
- return locals;
1717
- }
1718
- /**
1719
- * Load all configurations registered on providers
1720
- */
1721
-
1722
-
1723
- resolveConfiguration() {
1724
- if (this.resolvedConfiguration) {
1725
- return;
1726
- }
1727
-
1728
- const mergedConfiguration = new Map();
1729
- super.forEach(provider => {
1730
- if (provider.configuration) {
1731
- Object.entries(provider.configuration).forEach(([key, value]) => {
1732
- value = mergedConfiguration.has(key) ? deepMerge(mergedConfiguration.get(key), value) : deepClone(value);
1733
- mergedConfiguration.set(key, value);
1734
- });
1735
- }
1736
-
1737
- if (provider.resolvers) {
1738
- this.resolvers.push(...provider.resolvers);
1739
- }
1740
- });
1741
- mergedConfiguration.forEach((value, key) => {
1742
- this.settings[key] = deepMerge(value, this.settings[key]);
1743
- });
1744
- this.settings.build();
1745
- this.resolvedConfiguration = true;
1746
- }
1747
- /**
1748
- *
1749
- * @param instance
1750
- * @param locals
1751
- * @param options
1752
- */
1753
-
1754
-
1755
- bindInjectableProperties(instance, locals, options) {
1756
- const properties = ancestorsOf(classOf(instance)).reduce((properties, target) => {
1757
- const store = Store.from(target);
1758
- return _extends({}, properties, store.get(INJECTABLE_PROP) || {});
1759
- }, {});
1760
- Object.values(properties).forEach(definition => {
1761
- switch (definition.bindingType) {
1762
- case InjectablePropertyType.METHOD:
1763
- this.bindMethod(instance, definition);
1764
- break;
1765
-
1766
- case InjectablePropertyType.PROPERTY:
1767
- this.bindProperty(instance, definition, locals, options);
1768
- break;
1769
-
1770
- case InjectablePropertyType.CONSTANT:
1771
- this.bindConstant(instance, definition);
1772
- break;
1773
-
1774
- case InjectablePropertyType.VALUE:
1775
- this.bindValue(instance, definition);
1776
- break;
1777
-
1778
- case InjectablePropertyType.INTERCEPTOR:
1779
- this.bindInterceptor(instance, definition);
1780
- break;
1781
- }
1782
- });
1783
- }
1784
- /**
1785
- *
1786
- * @param instance
1787
- * @param {string} propertyKey
1788
- */
1789
-
1790
-
1791
- bindMethod(instance, {
1792
- propertyKey
1793
- }) {
1794
- const target = classOf(instance);
1795
- const originalMethod = instance[propertyKey];
1796
- const deps = Metadata.getParamTypes(prototypeOf(target), propertyKey);
1797
-
1798
- instance[propertyKey] = () => {
1799
- const services = deps.map(dependency => this.get(dependency));
1800
- return originalMethod.call(instance, ...services);
1801
- };
1802
- }
1803
- /**
1804
- * Create an injectable property.
1805
- *
1806
- * @param instance
1807
- * @param {string} propertyKey
1808
- * @param {any} useType
1809
- * @param onGet
1810
- * @param options
1811
- * @param locals
1812
- * @param invokeOptions
1813
- */
1814
-
1815
-
1816
- bindProperty(instance, {
1817
- propertyKey,
1818
- useType,
1819
- onGet = f => f,
1820
- options
1821
- }, locals, invokeOptions) {
1822
- invokeOptions = _extends({}, invokeOptions);
1823
- locals.set(DI_PARAM_OPTIONS, _extends({}, options));
1824
- let bean = this.invoke(useType, locals, invokeOptions);
1825
- locals.delete(DI_PARAM_OPTIONS);
1826
-
1827
- if (isPromise(bean)) {
1828
- bean.then(result => {
1829
- bean = result;
1830
- });
1831
- }
1832
-
1833
- Object.defineProperty(instance, propertyKey, {
1834
- get: () => onGet(bean)
1835
- });
1836
- }
1837
- /**
1838
- *
1839
- * @param instance
1840
- * @param {string} propertyKey
1841
- * @param {any} useType
1842
- */
1843
-
1844
-
1845
- bindValue(instance, {
1846
- propertyKey,
1847
- expression,
1848
- defaultValue
1849
- }) {
1850
- const descriptor = {
1851
- get: () => this.settings.get(expression) || defaultValue,
1852
- set: value => this.settings.set(expression, value),
1853
- enumerable: true,
1854
- configurable: true
1855
- };
1856
- Object.defineProperty(instance, propertyKey, descriptor);
1857
- }
1858
- /**
1859
- *
1860
- * @param instance
1861
- * @param {string} propertyKey
1862
- * @param {any} useType
1863
- */
1864
-
1865
-
1866
- bindConstant(instance, {
1867
- propertyKey,
1868
- expression,
1869
- defaultValue
1870
- }) {
1871
- const clone = o => {
1872
- if (o) {
1873
- return Object.freeze(deepClone(o));
1874
- }
1875
-
1876
- return defaultValue;
1877
- };
1878
-
1879
- const descriptor = {
1880
- get: () => clone(this.settings.get(expression)),
1881
- enumerable: true,
1882
- configurable: true
1883
- };
1884
- Object.defineProperty(instance, propertyKey, descriptor);
1885
- return descriptor;
1886
- }
1887
- /**
1888
- *
1889
- * @param instance
1890
- * @param propertyKey
1891
- * @param useType
1892
- * @param options
1893
- */
1894
-
1895
-
1896
- bindInterceptor(instance, {
1897
- propertyKey,
1898
- useType,
1899
- options
1900
- }) {
1901
- const target = classOf(instance);
1902
- const originalMethod = instance[propertyKey];
1903
-
1904
- instance[propertyKey] = (...args) => {
1905
- const next = err => {
1906
- if (!err) {
1907
- return originalMethod.apply(instance, args);
1908
- }
1909
-
1910
- throw err;
1911
- };
1912
-
1913
- const context = {
1914
- target,
1915
- propertyKey,
1916
- args,
1917
- options,
1918
- next
1919
- };
1920
- const interceptor = this.get(useType);
1921
- return interceptor.intercept(_extends({}, context, {
1922
- options
1923
- }), next);
1924
- };
1925
- }
1926
- /**
1927
- * Allow handler hack for AsyncHookContext plugin.
1928
- * @param ctx
1929
- * @param cb
1930
- * @protected
1931
- */
1932
-
1933
-
1934
- runInContext(ctx, cb) {
1935
- return cb();
1936
- }
1937
-
1938
- ensureProvider(token) {
1939
- if (!this.hasProvider(token) && GlobalProviders.has(token)) {
1940
- this.addProvider(token);
1941
- }
1942
-
1943
- return this.getProvider(token);
1944
- }
1945
- /**
1946
- * Invoke a class method and inject service.
1947
- *
1948
- * #### IInjectableMethod options
1949
- *
1950
- * * **target**: Optional. The class instance.
1951
- * * **methodName**: `string` Optional. The method name.
1952
- * * **designParamTypes**: `any[]` Optional. List of injectable types.
1953
- * * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
1954
- *
1955
- * #### Example
1956
- *
1957
- * @param target
1958
- * @param locals
1959
- * @param options
1960
- * @private
1961
- */
1962
-
1963
-
1964
- resolve(target, locals, options = {}) {
1965
- const {
1966
- token,
1967
- deps,
1968
- construct,
1969
- isBindable,
1970
- imports,
1971
- provider
1972
- } = this.mapInvokeOptions(target, locals, options);
1973
-
1974
- if (provider) {
1975
- GlobalProviders.onInvoke(provider, locals, deps);
1976
- }
1977
-
1978
- let instance;
1979
- let currentDependency = false;
1980
-
1981
- try {
1982
- const invokeDependency = parent => (token, index) => {
1983
- currentDependency = {
1984
- token,
1985
- index,
1986
- deps
1987
- };
1988
-
1989
- if (token !== DI_PARAM_OPTIONS) {
1990
- var _provider$store;
1991
-
1992
- const options = provider == null ? void 0 : (_provider$store = provider.store) == null ? void 0 : _provider$store.get(`${DI_PARAM_OPTIONS}:${index}`);
1993
- locals.set(DI_PARAM_OPTIONS, options || {});
1994
- }
1995
-
1996
- return isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {
1997
- parent
1998
- });
1999
- }; // Invoke manually imported providers
2000
-
2001
-
2002
- imports.forEach(invokeDependency()); // Inject dependencies
2003
-
2004
- const services = deps.map(invokeDependency(token));
2005
- currentDependency = false;
2006
- instance = construct(services);
2007
- } catch (error) {
2008
- InjectionError.throwInjectorError(token, currentDependency, error);
2009
- }
2010
-
2011
- if (instance === undefined) {
2012
- throw new InjectionError(token, `Unable to create new instance from undefined value. Check your provider declaration for ${nameOf(token)}`);
2013
- }
2014
-
2015
- if (instance && isBindable) {
2016
- this.bindInjectableProperties(instance, locals, options);
2017
- }
2018
-
2019
- return instance;
2020
- }
2021
- /**
2022
- * Create options to invoke a provider or class.
2023
- * @param token
2024
- * @param locals
2025
- * @param options
2026
- */
2027
-
2028
-
2029
- mapInvokeOptions(token, locals, options) {
2030
- let imports = options.imports;
2031
- let deps = options.deps;
2032
- let scope = options.scope;
2033
- let construct;
2034
- let isBindable = false;
2035
-
2036
- if (!token) {
2037
- throw new UndefinedTokenError();
2038
- }
2039
-
2040
- let provider;
2041
-
2042
- if (!this.hasProvider(token)) {
2043
- provider = new Provider(token);
2044
- this.resolvers.forEach(resolver => {
2045
- const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));
2046
-
2047
- if (result !== undefined) {
2048
- provider.useFactory = () => result;
2049
- }
2050
- });
2051
- } else {
2052
- provider = this.getProvider(token);
2053
- }
2054
-
2055
- scope = scope || this.scopeOf(provider);
2056
- deps = deps || provider.deps;
2057
- imports = imports || provider.imports;
2058
-
2059
- if (provider.useValue !== undefined) {
2060
- construct = () => isFunction(provider.useValue) ? provider.useValue() : provider.useValue;
2061
- } else if (provider.useFactory) {
2062
- construct = deps => provider.useFactory(...deps);
2063
- } else if (provider.useAsyncFactory) {
2064
- construct = deps => provider.useAsyncFactory(...deps);
2065
- } else {
2066
- // useClass
2067
- isBindable = true;
2068
- deps = deps || Metadata.getParamTypes(provider.useClass);
2069
-
2070
- construct = deps => new provider.useClass(...deps);
2071
- }
2072
-
2073
- return {
2074
- token,
2075
- scope: scope || Store.from(token).get("scope") || ProviderScope.SINGLETON,
2076
- deps: deps || [],
2077
- imports: imports || [],
2078
- isBindable,
2079
- construct,
2080
- provider
2081
- };
2082
- }
2083
-
2084
- };
2085
- InjectorService = InjectorService_1 = __decorate([Injectable({
2086
- scope: ProviderScope.SINGLETON,
2087
- global: true
2088
- }), __metadata("design:paramtypes", [])], InjectorService);
2089
-
2090
- registerProvider({
2091
- provide: Logger,
2092
- deps: [InjectorService],
2093
-
2094
- useFactory(injector) {
2095
- return injector.logger;
2096
- }
2097
-
2098
- });
2099
-
2100
- /**
2101
- * @ignore
2102
- * @param injector
2103
- */
2104
- function setLoggerLevel(injector) {
2105
- var _injector$settings$lo;
2106
-
2107
- const level = (_injector$settings$lo = injector.settings.logger) == null ? void 0 : _injector$settings$lo.level;
2108
-
2109
- if (level) {
2110
- injector.logger.level = level;
2111
- }
2112
- }
2113
-
2114
- /**
2115
- * Tool to run test with lightweight DI sandbox.
2116
- */
2117
-
2118
- class DITest {
2119
- static get injector() {
2120
- if (DITest._injector) {
2121
- return DITest._injector;
2122
- }
2123
- /* istanbul ignore next */
2124
-
2125
-
2126
- throw new Error("PlatformTest.injector is not initialized. Use PlatformTest.create(): Promise before PlatformTest.invoke() or PlatformTest.injector.\n" + "Example:\n" + "before(async () => {\n" + " await PlatformTest.create()\n" + " await PlatformTest.invoke(MyService, [])\n" + "})");
2127
- }
2128
-
2129
- static set injector(injector) {
2130
- DITest._injector = injector;
2131
- }
2132
-
2133
- static hasInjector() {
2134
- return !!DITest._injector;
2135
- }
2136
-
2137
- static async create(settings = {}) {
2138
- DITest.injector = DITest.createInjector(settings);
2139
- const container = new Container();
2140
- DITest.injector.bootstrap(container);
2141
- await DITest.injector.load(container);
2142
- }
2143
- /**
2144
- * Create a new injector with the right default services
2145
- */
2146
-
2147
-
2148
- static createInjector(settings = {}) {
2149
- const injector = new InjectorService();
2150
- injector.logger = $log; // @ts-ignore
2151
-
2152
- injector.settings.set(DITest.configure(settings));
2153
- setLoggerLevel(injector);
2154
- return injector;
2155
- }
2156
- /**
2157
- * Resets the test injector of the test context, so it won't pollute your next test. Call this in your `tearDown` logic.
2158
- */
2159
-
2160
-
2161
- static async reset() {
2162
- if (DITest.hasInjector()) {
2163
- await DITest.injector.destroy();
2164
- DITest._injector = null;
2165
- }
2166
- }
2167
- /**
2168
- * Invoke a provider and return a fresh instance
2169
- * @param target
2170
- * @param providers
2171
- */
2172
-
2173
-
2174
- static invoke(target, providers = []) {
2175
- const locals = new LocalsContainer();
2176
- providers.forEach(p => {
2177
- locals.set(p.token, p.use);
2178
- });
2179
- locals.set(InjectorService, DITest.injector);
2180
- const instance = DITest.injector.invoke(target, locals, {
2181
- rebuild: true
2182
- });
2183
-
2184
- if (instance && instance.$onInit) {
2185
- // await instance.$onInit();
2186
- const result = instance.$onInit();
2187
-
2188
- if (result instanceof Promise) {
2189
- return result.then(() => instance);
2190
- }
2191
- }
2192
-
2193
- return instance;
2194
- }
2195
- /**
2196
- * Return the instance from injector registry
2197
- * @param target
2198
- * @param options
2199
- */
2200
-
2201
-
2202
- static get(target, options = {}) {
2203
- return DITest.injector.get(target, options);
2204
- }
2205
-
2206
- static configure(settings = {}) {
2207
- return _extends({}, settings, {
2208
- env: getValue(settings, "env", Env.TEST),
2209
- logger: _extends({}, getValue(settings, "logger", {}), {
2210
- level: getValue(settings, "logger.level", "off")
2211
- })
2212
- });
2213
- }
2214
-
2215
- }
2216
- DITest._injector = null;
2217
-
2218
- function getConfiguration(module, configuration = {}) {
2219
- const store = Store.from(module).get("configuration") || {};
2220
-
2221
- const config = _extends({}, store, configuration);
2222
-
2223
- if (store.mount && configuration.mount) {
2224
- config.mount = deepMerge(store.mount, configuration.mount);
2225
- }
2226
-
2227
- if (store.componentsScan && configuration.componentsScan) {
2228
- config.componentsScan = [...store.componentsScan, ...configuration.componentsScan];
2229
- }
2230
-
2231
- return config;
2232
- }
2233
-
2234
- export { Configuration, Constant, Container, ContextLogger, DIConfiguration, DIContext, DITest, DI_PARAMS, DI_PARAM_OPTIONS, GlobalProviderRegistry, GlobalProviders, INJECTABLE_PROP, Inject, Injectable, InjectablePropertyType, InjectionError, InjectorService, Intercept, Interceptor, LocalsContainer, Module, Opts, OverrideProvider, Provider, ProviderScope, ProviderType, Scope, Service, UndefinedTokenError, UseOpts, Value, createContainer, getConfiguration, registerController, registerProvider, registerValue, setLoggerLevel };
2235
- //# sourceMappingURL=index.modern.js.map