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