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

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