taon 18.0.25 → 18.0.27

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 (197) hide show
  1. package/README.md +112 -51
  2. package/assets/shared/shared_folder_info.txt +1 -1
  3. package/browser/esm2022/lib/endpoint-context.mjs +4 -1
  4. package/browser/esm2022/lib/index.mjs +2 -2
  5. package/browser/esm2022/lib/models.mjs +1 -1
  6. package/browser/esm2022/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.mjs +11 -11
  7. package/browser/fesm2022/taon.mjs +3 -0
  8. package/browser/fesm2022/taon.mjs.map +1 -1
  9. package/browser/lib/models.d.ts +5 -0
  10. package/browser/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.d.ts +4 -4
  11. package/cli.js +11 -17
  12. package/cli.js.map +1 -1
  13. package/client/esm2022/lib/endpoint-context.mjs +4 -1
  14. package/client/esm2022/lib/index.mjs +2 -2
  15. package/client/esm2022/lib/models.mjs +1 -1
  16. package/client/esm2022/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.mjs +11 -11
  17. package/client/fesm2022/taon.mjs +3 -0
  18. package/client/fesm2022/taon.mjs.map +1 -1
  19. package/client/lib/models.d.ts +5 -0
  20. package/client/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.d.ts +4 -4
  21. package/index.js +15 -2
  22. package/index.js.map +1 -1
  23. package/lib/base-classes/base-abstract-entity.js +30 -28
  24. package/lib/base-classes/base-abstract-entity.js.map +1 -1
  25. package/lib/base-classes/base-class.js +9 -17
  26. package/lib/base-classes/base-class.js.map +1 -1
  27. package/lib/base-classes/base-context.js +4 -4
  28. package/lib/base-classes/base-context.js.map +1 -1
  29. package/lib/base-classes/base-controller.js +15 -15
  30. package/lib/base-classes/base-controller.js.map +1 -1
  31. package/lib/base-classes/base-crud-controller.js +211 -329
  32. package/lib/base-classes/base-crud-controller.js.map +1 -1
  33. package/lib/base-classes/base-entity.js +15 -15
  34. package/lib/base-classes/base-entity.js.map +1 -1
  35. package/lib/base-classes/base-injector.js +99 -124
  36. package/lib/base-classes/base-injector.js.map +1 -1
  37. package/lib/base-classes/base-migration.js +15 -31
  38. package/lib/base-classes/base-migration.js.map +1 -1
  39. package/lib/base-classes/base-provider.js +3 -9
  40. package/lib/base-classes/base-provider.js.map +1 -1
  41. package/lib/base-classes/base-repository.js +310 -444
  42. package/lib/base-classes/base-repository.js.map +1 -1
  43. package/lib/base-classes/base-subscriber-for-entity.js +73 -73
  44. package/lib/base-classes/base-subscriber-for-entity.js.map +1 -1
  45. package/lib/base-classes/base.js +10 -10
  46. package/lib/base-classes/base.js.map +1 -1
  47. package/lib/build-info._auto-generated_.js.map +1 -1
  48. package/lib/constants.js.map +1 -1
  49. package/lib/context-db-migrations.js +325 -581
  50. package/lib/context-db-migrations.js.map +1 -1
  51. package/lib/create-context.js +80 -109
  52. package/lib/create-context.js.map +1 -1
  53. package/lib/decorators/classes/controller-decorator.js +15 -13
  54. package/lib/decorators/classes/controller-decorator.js.map +1 -1
  55. package/lib/decorators/classes/entity-decorator.js +23 -20
  56. package/lib/decorators/classes/entity-decorator.js.map +1 -1
  57. package/lib/decorators/classes/migration-decorator.js +7 -13
  58. package/lib/decorators/classes/migration-decorator.js.map +1 -1
  59. package/lib/decorators/classes/provider-decorator.js +7 -13
  60. package/lib/decorators/classes/provider-decorator.js.map +1 -1
  61. package/lib/decorators/classes/repository-decorator.js +7 -13
  62. package/lib/decorators/classes/repository-decorator.js.map +1 -1
  63. package/lib/decorators/classes/subscriber-decorator.js +8 -13
  64. package/lib/decorators/classes/subscriber-decorator.js.map +1 -1
  65. package/lib/decorators/http/http-decorators.js +4 -4
  66. package/lib/decorators/http/http-decorators.js.map +1 -1
  67. package/lib/decorators/http/http-methods-decorators.js +19 -25
  68. package/lib/decorators/http/http-methods-decorators.js.map +1 -1
  69. package/lib/decorators/http/http-params-decorators.js +7 -9
  70. package/lib/decorators/http/http-params-decorators.js.map +1 -1
  71. package/lib/dependency-injection/di-container.js +13 -18
  72. package/lib/dependency-injection/di-container.js.map +1 -1
  73. package/lib/endpoint-context.js +1196 -1543
  74. package/lib/endpoint-context.js.map +1 -1
  75. package/lib/entity-process.js +102 -112
  76. package/lib/entity-process.js.map +1 -1
  77. package/lib/env.js +2 -2
  78. package/lib/env.js.map +1 -1
  79. package/lib/formly/formly-group-wrapper-component.js +45 -23
  80. package/lib/formly/formly-group-wrapper-component.js.map +1 -1
  81. package/lib/formly/formly-repeat-component.js +74 -27
  82. package/lib/formly/formly-repeat-component.js.map +1 -1
  83. package/lib/formly/formly.models.js.map +1 -1
  84. package/lib/formly/fromly.js +57 -61
  85. package/lib/formly/fromly.js.map +1 -1
  86. package/lib/formly/type-from-entity.js +11 -16
  87. package/lib/formly/type-from-entity.js.map +1 -1
  88. package/lib/get-response-value.js +22 -33
  89. package/lib/get-response-value.js.map +1 -1
  90. package/lib/helpers/class-helpers.js +62 -73
  91. package/lib/helpers/class-helpers.js.map +1 -1
  92. package/lib/helpers/taon-helpers.js +33 -31
  93. package/lib/helpers/taon-helpers.js.map +1 -1
  94. package/lib/index._auto-generated_.d.ts +1 -0
  95. package/lib/index._auto-generated_.js.map +1 -1
  96. package/lib/index.d.ts +1 -25
  97. package/lib/index.js +44 -41
  98. package/lib/index.js.map +1 -1
  99. package/lib/inject.js +15 -15
  100. package/lib/inject.js.map +1 -1
  101. package/lib/models.d.ts +5 -0
  102. package/lib/models.js +124 -100
  103. package/lib/models.js.map +1 -1
  104. package/lib/orm.js +13 -27
  105. package/lib/orm.js.map +1 -1
  106. package/lib/realtime/realtime-client.js +70 -65
  107. package/lib/realtime/realtime-client.js.map +1 -1
  108. package/lib/realtime/realtime-core.js +48 -29
  109. package/lib/realtime/realtime-core.js.map +1 -1
  110. package/lib/realtime/realtime-server.js +81 -80
  111. package/lib/realtime/realtime-server.js.map +1 -1
  112. package/lib/realtime/realtime-strategy/index.js +18 -5
  113. package/lib/realtime/realtime-strategy/index.js.map +1 -1
  114. package/lib/realtime/realtime-strategy/realtime-strategy-ipc.js +132 -172
  115. package/lib/realtime/realtime-strategy/realtime-strategy-ipc.js.map +1 -1
  116. package/lib/realtime/realtime-strategy/realtime-strategy-mock.js +158 -241
  117. package/lib/realtime/realtime-strategy/realtime-strategy-mock.js.map +1 -1
  118. package/lib/realtime/realtime-strategy/realtime-strategy-socket-io.js +18 -29
  119. package/lib/realtime/realtime-strategy/realtime-strategy-socket-io.js.map +1 -1
  120. package/lib/realtime/realtime-strategy/realtime-strategy.js +9 -13
  121. package/lib/realtime/realtime-strategy/realtime-strategy.js.map +1 -1
  122. package/lib/realtime/realtime-subs-manager.js +29 -30
  123. package/lib/realtime/realtime-subs-manager.js.map +1 -1
  124. package/lib/realtime/realtime.models.js.map +1 -1
  125. package/lib/storage.js +1 -1
  126. package/lib/storage.js.map +1 -1
  127. package/lib/symbols.js +62 -66
  128. package/lib/symbols.js.map +1 -1
  129. package/lib/ui/directives/index.js +2 -2
  130. package/lib/ui/directives/index.js.map +1 -1
  131. package/lib/ui/directives/view-mode.js.map +1 -1
  132. package/lib/ui/index.js +2 -2
  133. package/lib/ui/index.js.map +1 -1
  134. package/lib/ui/taon-admin-mode-configuration/components/taon-admin-edit-mode/index.d.ts +2 -0
  135. package/lib/ui/taon-admin-mode-configuration/components/taon-admin-edit-mode/index.js +5 -0
  136. package/lib/ui/taon-admin-mode-configuration/components/taon-admin-edit-mode/index.js.map +1 -0
  137. package/lib/ui/taon-admin-mode-configuration/components/taon-admin-edit-mode/taon-admin-edit-mode.component.d.ts +29 -0
  138. package/lib/ui/taon-admin-mode-configuration/components/taon-admin-edit-mode/taon-admin-edit-mode.module.d.ts +2 -0
  139. package/lib/ui/taon-admin-mode-configuration/components/taon-db-admin/index.d.ts +1 -0
  140. package/lib/ui/taon-admin-mode-configuration/components/taon-db-admin/index.js +5 -0
  141. package/lib/ui/taon-admin-mode-configuration/components/taon-db-admin/index.js.map +1 -0
  142. package/lib/ui/taon-admin-mode-configuration/components/taon-db-admin/taon-db-admin.component.d.ts +8 -0
  143. package/lib/ui/taon-admin-mode-configuration/components/taon-file-general-opt/index.d.ts +2 -0
  144. package/lib/ui/taon-admin-mode-configuration/components/taon-file-general-opt/index.js +5 -0
  145. package/lib/ui/taon-admin-mode-configuration/components/taon-file-general-opt/index.js.map +1 -0
  146. package/lib/ui/taon-admin-mode-configuration/components/taon-file-general-opt/taon-file-general-opt.component.d.ts +13 -0
  147. package/lib/ui/taon-admin-mode-configuration/components/taon-file-general-opt/taon-file-general-opt.module.d.ts +2 -0
  148. package/lib/ui/taon-admin-mode-configuration/index.js +2 -2
  149. package/lib/ui/taon-admin-mode-configuration/index.js.map +1 -1
  150. package/lib/ui/taon-admin-mode-configuration/models/taon-admin-mode-tabs.d.ts +5 -0
  151. package/lib/ui/taon-admin-mode-configuration/models/taon-admin-mode-tabs.js +3 -0
  152. package/lib/ui/taon-admin-mode-configuration/models/taon-admin-mode-tabs.js.map +1 -0
  153. package/lib/ui/taon-admin-mode-configuration/taon-admin-control.service.d.ts +14 -0
  154. package/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.d.ts +4 -4
  155. package/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.module.d.ts +2 -0
  156. package/lib/ui/taon-admin-mode-configuration/taon-admin.models.js.map +1 -1
  157. package/lib/ui/taon-github-fork-me-corner/index.js +2 -2
  158. package/lib/ui/taon-github-fork-me-corner/index.js.map +1 -1
  159. package/lib/ui/taon-github-fork-me-ribbon/index.js +2 -2
  160. package/lib/ui/taon-github-fork-me-ribbon/index.js.map +1 -1
  161. package/lib/ui/taon-notifications/index.js +15 -2
  162. package/lib/ui/taon-notifications/index.js.map +1 -1
  163. package/lib/ui/taon-notifications/taon-notifications.models.js +2 -2
  164. package/lib/ui/taon-notifications/taon-notifications.models.js.map +1 -1
  165. package/lib/ui/taon-progress-bar/index.js +2 -2
  166. package/lib/ui/taon-progress-bar/index.js.map +1 -1
  167. package/lib/ui/taon-progress-bar/taon-progress-bar.component.d.ts +2 -1
  168. package/lib/ui/taon-session-passcode/index.js +2 -2
  169. package/lib/ui/taon-session-passcode/index.js.map +1 -1
  170. package/lib/ui/taon-table/index.js +2 -2
  171. package/lib/ui/taon-table/index.js.map +1 -1
  172. package/lib/ui/taon.models.js.map +1 -1
  173. package/lib/validators.js +48 -16
  174. package/lib/validators.js.map +1 -1
  175. package/migrations/index.js +15 -2
  176. package/migrations/index.js.map +1 -1
  177. package/migrations/migrations_index._auto-generated_.d.ts +1 -0
  178. package/migrations/migrations_index._auto-generated_.js.map +1 -1
  179. package/old-app .d.ts +1 -0
  180. package/old-app .js +67 -78
  181. package/old-app .js.map +1 -1
  182. package/package.json +18 -65
  183. package/playground.d.ts +1 -0
  184. package/playground.js.map +1 -1
  185. package/src.d.ts +1 -1
  186. package/taon.jsonc +39 -42
  187. package/tmp-environment.json +8 -401
  188. package/websql/esm2022/lib/endpoint-context.mjs +4 -1
  189. package/websql/esm2022/lib/index.mjs +2 -2
  190. package/websql/esm2022/lib/models.mjs +1 -1
  191. package/websql/esm2022/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.mjs +11 -11
  192. package/websql/fesm2022/taon.mjs +3 -0
  193. package/websql/fesm2022/taon.mjs.map +1 -1
  194. package/websql/lib/models.d.ts +5 -0
  195. package/websql/lib/ui/taon-admin-mode-configuration/taon-admin-mode-configuration.component.d.ts +4 -4
  196. package/browser/package.json +0 -25
  197. package/websql/package.json +0 -25
@@ -1,598 +1,414 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EndpointContext = void 0;
4
- var tslib_1 = require("tslib");
5
4
  /* eslint-disable @typescript-eslint/typedef */
6
5
  //#region imports
7
6
  //#region @websql
8
- var taon_typeorm_1 = require("taon-typeorm");
9
- var taon_typeorm_2 = require("taon-typeorm");
7
+ const taon_typeorm_1 = require("taon-typeorm");
8
+ const taon_typeorm_2 = require("taon-typeorm");
10
9
  //#endregion
11
10
  //#region @backend
12
- var express = require("express");
13
- var expressSession = require("express-session");
14
- var cors = require("cors");
15
- var bodyParser = require("body-parser");
16
- var cookieParser = require("cookie-parser");
17
- var methodOverride = require("method-override");
18
- var fileUpload = require("express-fileupload");
19
- var url_1 = require("url");
20
- var tnp_core_1 = require("tnp-core");
11
+ const express = require("express");
12
+ const expressSession = require("express-session");
13
+ const cors = require("cors");
14
+ const bodyParser = require("body-parser");
15
+ const cookieParser = require("cookie-parser");
16
+ const methodOverride = require("method-override");
17
+ const fileUpload = require("express-fileupload");
18
+ const url_1 = require("url");
19
+ const tnp_core_1 = require("tnp-core");
21
20
  //#endregion
22
21
  /* */
23
22
  /* */
24
- var tnp_core_2 = require("tnp-core");
25
- var tnp_core_3 = require("tnp-core");
26
- var models_1 = require("./models");
27
- var class_helpers_1 = require("./helpers/class-helpers");
28
- var symbols_1 = require("./symbols");
29
- var tnp_core_4 = require("tnp-core");
30
- var di_container_1 = require("./dependency-injection/di-container");
31
- var taon_helpers_1 = require("./helpers/taon-helpers");
32
- var ng2_rest_1 = require("ng2-rest");
33
- var json10_1 = require("json10");
34
- var rxjs_1 = require("rxjs");
35
- var entity_process_1 = require("./entity-process");
36
- var get_response_value_1 = require("./get-response-value");
37
- var axios_1 = require("axios");
38
- var taon_typeorm_3 = require("taon-typeorm");
39
- var env_1 = require("./env");
40
- var realtime_core_1 = require("./realtime/realtime-core");
41
- var context_db_migrations_1 = require("./context-db-migrations");
23
+ const tnp_core_2 = require("tnp-core");
24
+ const tnp_core_3 = require("tnp-core");
25
+ const models_1 = require("./models");
26
+ const class_helpers_1 = require("./helpers/class-helpers");
27
+ const symbols_1 = require("./symbols");
28
+ const tnp_core_4 = require("tnp-core");
29
+ const di_container_1 = require("./dependency-injection/di-container");
30
+ const taon_helpers_1 = require("./helpers/taon-helpers");
31
+ const ng2_rest_1 = require("ng2-rest");
32
+ const json10_1 = require("json10");
33
+ const rxjs_1 = require("rxjs");
34
+ const entity_process_1 = require("./entity-process");
35
+ const get_response_value_1 = require("./get-response-value");
36
+ const axios_1 = require("axios");
37
+ const taon_typeorm_3 = require("taon-typeorm");
38
+ const env_1 = require("./env");
39
+ const realtime_core_1 = require("./realtime/realtime-core");
40
+ const context_db_migrations_1 = require("./context-db-migrations");
42
41
  //#endregion
43
- var EndpointContext = /** @class */ (function () {
42
+ class EndpointContext {
43
+ originalConfig;
44
+ configFn;
45
+ //#region static
46
+ /* */
47
+ /* */
48
+ static initNgZone(ngZone) {
49
+ /* */
50
+ /* */
51
+ }
52
+ // public static findForTraget(classFnOrObject: any): EndpointContext {
53
+ // const obj = ClassHelpers.getClassFnFromObject(classFnOrObject) || {};
54
+ // return (
55
+ // classFnOrObject[Symbols.ctxInClassOrClassObj] ||
56
+ // obj[Symbols.ctxInClassOrClassObj]
57
+ // );
58
+ // }
59
+ //#endregion
60
+ //#region fields
61
+ //#region fields / flags
62
+ disabledRealtime = false;
63
+ /**
64
+ * check whether context is inited
65
+ * (with init() function )
66
+ */
67
+ inited = false;
68
+ //#endregion
69
+ dbMigrations = new context_db_migrations_1.ContextDbMigrations(this);
70
+ localInstaceObjSymbol = Symbol('localInstaceObjSymbol');
71
+ //#region fields / all instances of classes from context
72
+ /**
73
+ * all instances of classes from context
74
+ * key is class name
75
+ */
76
+ allClassesInstances = {};
77
+ //#endregion
78
+ //#region fields / class instances by name
79
+ classInstancesByNameObj = {};
80
+ //#endregion
81
+ //#region fields / obj with classes instances arr
82
+ objWithClassesInstancesArr = {};
83
+ //#endregion
84
+ //#region fields / active routes
85
+ activeRoutes = [];
86
+ //#endregion
87
+ skipWritingServerRoutes = false;
88
+ //#region fields / types from contexts
89
+ injectableTypesfromContexts = [
90
+ models_1.Models.ClassType.CONTROLLER,
91
+ models_1.Models.ClassType.PROVIDER,
92
+ models_1.Models.ClassType.REPOSITORY,
93
+ models_1.Models.ClassType.SUBSCRIBER,
94
+ models_1.Models.ClassType.MIGRATION,
95
+ ];
96
+ //#endregion
97
+ allTypesfromContexts = [
98
+ ...this.injectableTypesfromContexts,
99
+ models_1.Models.ClassType.ENTITY,
100
+ ];
101
+ // public __contextForControllerInstanceAccess?: EndpointContext;
102
+ //#region fields / express app
103
+ expressApp = {};
104
+ //#endregion
105
+ //#region fields / server tcp udp
106
+ serverTcpUdp;
107
+ //#endregion
108
+ //#region fields / database config
109
+ databaseConfig;
110
+ //#endregion
111
+ //#region fields / mode
112
+ mode;
113
+ //#endregion
114
+ //#region fields / only migration start
115
+ onlyMigrationRun = false;
116
+ onlyMigrationRevertToTimestamp = undefined;
117
+ get isRunOrRevertOnlyMigrationAppStart() {
118
+ return !!(this.onlyMigrationRun || this.onlyMigrationRevertToTimestamp);
119
+ }
120
+ //#endregion
121
+ //#region fields / session
122
+ session;
123
+ //#endregion
124
+ //#region fields / connection
125
+ connection;
126
+ //#endregion
127
+ //#region fields / entities triggers
128
+ entitiesTriggers = {};
129
+ //#endregion
130
+ //#region fields / realtime
131
+ realtime;
132
+ get realtimeClient() {
133
+ return this.realtime.client;
134
+ }
135
+ get realtimeServer() {
136
+ return this.realtime.server;
137
+ }
138
+ //#endregion
139
+ //#region fields / config
140
+ /**
141
+ * available after init()
142
+ */
143
+ config;
144
+ //#endregion
145
+ //#region fields / logs
146
+ get logHttp() {
147
+ if (tnp_core_4._.isObject(this.config?.logs)) {
148
+ return !!this.config.logs.http;
149
+ }
150
+ return this.config?.logs === true;
151
+ }
152
+ get logRealtime() {
153
+ if (tnp_core_4._.isObject(this.config?.logs)) {
154
+ return !!this.config.logs.realtime;
155
+ }
156
+ return this.config?.logs === true;
157
+ }
158
+ get logFramework() {
159
+ if (tnp_core_4._.isObject(this.config?.logs)) {
160
+ return !!this.config.logs.framework;
161
+ }
162
+ return this.config?.logs === true;
163
+ }
164
+ get logDb() {
165
+ if (tnp_core_4._.isObject(this.config?.logs)) {
166
+ return !!this.config.logs.db;
167
+ }
168
+ return this.config?.logs === true;
169
+ }
170
+ get logMigrations() {
171
+ if (tnp_core_4._.isObject(this.config?.logs)) {
172
+ return !!this.config.logs.migrations;
173
+ }
174
+ return this.config?.logs === true;
175
+ }
44
176
  //#endregion
45
177
  //#endregion
46
178
  //#region constructor
47
- function EndpointContext(originalConfig, configFn) {
48
- var _this = this;
179
+ constructor(originalConfig, configFn) {
49
180
  this.originalConfig = originalConfig;
50
181
  this.configFn = configFn;
51
- // public static findForTraget(classFnOrObject: any): EndpointContext {
52
- // const obj = ClassHelpers.getClassFnFromObject(classFnOrObject) || {};
53
- // return (
54
- // classFnOrObject[Symbols.ctxInClassOrClassObj] ||
55
- // obj[Symbols.ctxInClassOrClassObj]
56
- // );
57
- // }
58
- //#endregion
59
- //#region fields
60
- //#region fields / flags
61
- this.disabledRealtime = false;
62
- /**
63
- * check whether context is inited
64
- * (with init() function )
65
- */
66
- this.inited = false;
67
- //#endregion
68
- this.dbMigrations = new context_db_migrations_1.ContextDbMigrations(this);
69
- this.localInstaceObjSymbol = Symbol('localInstaceObjSymbol');
70
- //#region fields / all instances of classes from context
71
- /**
72
- * all instances of classes from context
73
- * key is class name
74
- */
75
- this.allClassesInstances = {};
76
- //#endregion
77
- //#region fields / class instances by name
78
- this.classInstancesByNameObj = {};
79
- //#endregion
80
- //#region fields / obj with classes instances arr
81
- this.objWithClassesInstancesArr = {};
182
+ }
183
+ //#endregion
184
+ //#region methods & getters / init
185
+ async init(options) {
186
+ const { initFromRecrusiveContextResovle, overrideHost, overrideRemoteHost, onlyMigrationRun, onlyMigrationRevertToTimestamp, } = options || {}; // TODO use it ?
187
+ this.inited = true;
188
+ // @ts-ignore
189
+ this.onlyMigrationRun = onlyMigrationRun;
190
+ // @ts-ignore
191
+ this.onlyMigrationRevertToTimestamp = onlyMigrationRevertToTimestamp;
192
+ this.config = this.configFn(env_1.ENV);
193
+ if (tnp_core_4._.isObject(this.config.database)) {
194
+ this.config.database = models_1.Models.DatabaseConfig.from(this.config.database).databaseConfigTypeORM;
195
+ }
196
+ if (overrideHost && overrideRemoteHost) {
197
+ tnp_core_4.Helpers.throw(`[taon-config] You can't have overrideHost and overrideRemoteHost at the same time`);
198
+ }
199
+ this.config.host = !tnp_core_4._.isUndefined(overrideHost)
200
+ ? overrideHost
201
+ : this.config.host;
202
+ this.config.remoteHost = !tnp_core_4._.isUndefined(overrideRemoteHost)
203
+ ? overrideRemoteHost
204
+ : this.config.remoteHost;
205
+ this.config.host = this.host === null ? void 0 : this.host;
206
+ this.config.remoteHost =
207
+ this.remoteHost === null ? void 0 : this.remoteHost;
208
+ if (this.config.host &&
209
+ !this.config.host.startsWith('http://') &&
210
+ !this.config.host.startsWith('https://')) {
211
+ tnp_core_4.Helpers.throw(`[taon-config] Your 'host' must start with http:// or https://`);
212
+ }
213
+ if (tnp_core_4._.isUndefined(this.config.useIpcWhenElectron)) {
214
+ this.config.useIpcWhenElectron = true;
215
+ }
216
+ if (this.config.remoteHost &&
217
+ !this.config.remoteHost.startsWith('http://') &&
218
+ !this.config.remoteHost.startsWith('https://')) {
219
+ tnp_core_4.Helpers.throw(`[taon-config] Your 'remoteHost' must start with http:// or https://`);
220
+ }
221
+ //#region resolve if skipping writing server routes
222
+ //@ts-expect-error overriding readonly
223
+ this.skipWritingServerRoutes = tnp_core_4._.isBoolean(this.config.skipWritingServerRoutes)
224
+ ? this.config.skipWritingServerRoutes
225
+ : false;
82
226
  //#endregion
83
- //#region fields / active routes
84
- this.activeRoutes = [];
227
+ //#region resolve mode
228
+ if (this.config.host) {
229
+ this.mode = 'backend-frontend(tcp+udp)';
230
+ /* */
231
+ /* */
232
+ }
233
+ if (this.config.remoteHost) {
234
+ if (this.config.host) {
235
+ tnp_core_4.Helpers.throw(`[taon] You can't have remoteHost and host at the same time`);
236
+ }
237
+ this.mode = 'remote-backend(tcp+udp)';
238
+ }
239
+ if (this.config.useIpcWhenElectron && tnp_core_4.Helpers.isElectron) {
240
+ if (tnp_core_4.Helpers.isWebSQL) {
241
+ this.mode = 'backend-frontend(websql-electron)';
242
+ }
243
+ else {
244
+ this.mode = 'backend-frontend(ipc-electron)';
245
+ }
246
+ }
247
+ if (!this.mode && !this.config.abstract) {
248
+ tnp_core_4.Helpers.error(`[taon] Context "${this.contextName}": You need to provide host or remoteHost or useIpcWhenElectron`, false, true);
249
+ //#region @backend
250
+ process.exit(1);
251
+ //#endregion
252
+ }
85
253
  //#endregion
86
- this.skipWritingServerRoutes = false;
87
- //#region fields / types from contexts
88
- this.injectableTypesfromContexts = [
89
- models_1.Models.ClassType.CONTROLLER,
90
- models_1.Models.ClassType.PROVIDER,
91
- models_1.Models.ClassType.REPOSITORY,
92
- models_1.Models.ClassType.SUBSCRIBER,
93
- models_1.Models.ClassType.MIGRATION,
94
- ];
254
+ //#region resolve database config
255
+ if (this.config.database === true) {
256
+ this.databaseConfig = this.getAutoGeneratedConfig();
257
+ }
258
+ else if (tnp_core_4._.isObject(this.config.database)) {
259
+ this.databaseConfig = tnp_core_4._.merge(this.getAutoGeneratedConfig(), tnp_core_4._.cloneDeep(this.config.database));
260
+ }
95
261
  //#endregion
96
- this.allTypesfromContexts = tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(this.injectableTypesfromContexts), false), [
97
- models_1.Models.ClassType.ENTITY,
98
- ], false);
99
- // public __contextForControllerInstanceAccess?: EndpointContext;
100
- //#region fields / express app
101
- this.expressApp = {};
262
+ //#region resolve session
263
+ if (this.config.session) {
264
+ this.session = tnp_core_4._.cloneDeep(this.config.session);
265
+ const oneHour = 1000 * 60 * 60 * 1; // 24;
266
+ if (!this.session.cookieMaxAge) {
267
+ this.session.cookieMaxAge = oneHour;
268
+ }
269
+ // serever and browser cookie authentication
270
+ axios_1.default.defaults.withCredentials = true;
271
+ }
102
272
  //#endregion
103
- //#region fields / only migration start
104
- this.onlyMigrationRun = false;
105
- this.onlyMigrationRevertToTimestamp = undefined;
273
+ //#region prepare & gather all classes recrusively
274
+ this.config.contexts = this.config.contexts || {};
275
+ this.config.entities = this.config.entities || {};
276
+ this.config.controllers = this.config.controllers || {};
277
+ this.config.repositories = this.config.repositories || {};
278
+ this.config.providers = this.config.providers || {};
279
+ this.config.subscribers = this.config.subscribers || {};
280
+ this.config.migrations = this.config.migrations || {};
281
+ this.config.entities = {
282
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.ENTITY)),
283
+ ...this.config.entities,
284
+ };
285
+ this.config.controllers = {
286
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.CONTROLLER)),
287
+ ...this.config.controllers,
288
+ };
289
+ this.config.providers = {
290
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.PROVIDER)),
291
+ ...this.config.providers,
292
+ };
293
+ this.config.subscribers = {
294
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.SUBSCRIBER)),
295
+ ...this.config.subscribers,
296
+ };
297
+ this.config.repositories = {
298
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.REPOSITORY)),
299
+ ...this.config.repositories,
300
+ };
301
+ this.config.migrations = {
302
+ ...(await this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.MIGRATION)),
303
+ ...this.config.migrations,
304
+ };
305
+ // console.log(this.config);
306
+ // debugger;
106
307
  //#endregion
107
- //#region fields / entities triggers
108
- this.entitiesTriggers = {};
308
+ //#region prepare classes instances/functions clones
309
+ this.config.controllers = this.cloneClassesObjWithNewMetadata({
310
+ classesInput: this.config.controllers,
311
+ config: this.config,
312
+ ctx: this,
313
+ classType: models_1.Models.ClassType.CONTROLLER,
314
+ });
315
+ this.config.repositories = this.cloneClassesObjWithNewMetadata({
316
+ classesInput: this.config.repositories,
317
+ config: this.config,
318
+ ctx: this,
319
+ classType: models_1.Models.ClassType.REPOSITORY,
320
+ });
321
+ this.config.providers = this.cloneClassesObjWithNewMetadata({
322
+ classesInput: this.config.providers,
323
+ config: this.config,
324
+ ctx: this,
325
+ classType: models_1.Models.ClassType.PROVIDER,
326
+ });
327
+ this.config.subscribers = this.cloneClassesObjWithNewMetadata({
328
+ classesInput: this.config.subscribers,
329
+ config: this.config,
330
+ ctx: this,
331
+ classType: models_1.Models.ClassType.SUBSCRIBER,
332
+ });
333
+ this.config.migrations = this.cloneClassesObjWithNewMetadata({
334
+ classesInput: this.config.migrations,
335
+ config: this.config,
336
+ ctx: this,
337
+ classType: models_1.Models.ClassType.MIGRATION,
338
+ });
109
339
  //#endregion
110
- //#region methods & getters / clone class
111
- // eslint-disable-next-line @typescript-eslint/typedef
112
- this.cloneClassWithNewMetadata = function (_a) {
113
- var BaseClass = _a.BaseClass, className = _a.className, config = _a.config, ctx = _a.ctx, classType = _a.classType;
114
- // Return a new class that extends the base class
115
- var cloneClass = function () {
116
- var _a, _b, _c, _d, _e, _f;
117
- if (BaseClass[symbols_1.Symbols.fullClassNameStaticProperty] ===
118
- "".concat(ctx.contextName, ".").concat(className)) {
119
- return BaseClass;
120
- }
121
- return _f = /** @class */ (function (_super) {
122
- tslib_1.__extends(class_1, _super);
123
- function class_1() {
124
- var _this = _super.apply(this, tslib_1.__spreadArray([], tslib_1.__read(arguments), false)) || this;
125
- _this[_e] = ctx;
126
- return _this;
127
- // You can override prototype properties or methods here if needed
128
- // static properties override allowed
129
- }
130
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/typedef
131
- class_1.__getFullPathForClass__ = function (arr) {
132
- if (arr === void 0) { arr = []; }
133
- var name = this[symbols_1.Symbols.fullClassNameStaticProperty];
134
- arr.push(name);
135
- // @ts-ignore
136
- if (this[symbols_1.Symbols.orignalClass] && // @ts-ignore
137
- this[symbols_1.Symbols.orignalClass].__getFullPathForClass__) {
138
- // @ts-ignore
139
- this[symbols_1.Symbols.orignalClass].__getFullPathForClass__(arr);
140
- }
141
- return arr.join('/');
142
- };
143
- Object.defineProperty(class_1, "fullPathForClass", {
144
- get: function () {
145
- return this.__getFullPathForClass__();
146
- },
147
- enumerable: false,
148
- configurable: true
149
- });
150
- return class_1;
151
- }(BaseClass)),
152
- _a = symbols_1.Symbols.orignalClass,
153
- _b = symbols_1.Symbols.fullClassNameStaticProperty,
154
- _c = symbols_1.Symbols.classNameStaticProperty,
155
- _d = symbols_1.Symbols.ctxInClassOrClassObj,
156
- _e = symbols_1.Symbols.ctxInClassOrClassObj,
157
- // static ['_'] = BaseClass['_'];
158
- // eslint-disable-next-line @typescript-eslint/typedef
159
- // @ts-ignore
160
- _f[_a] = BaseClass,
161
- // eslint-disable-next-line @typescript-eslint/typedef
162
- // @ts-ignore
163
- _f[_b] = "".concat(ctx.contextName, ".").concat(className),
164
- // eslint-disable-next-line @typescript-eslint/typedef
165
- // @ts-ignore
166
- _f[_c] = className,
167
- // eslint-disable-next-line @typescript-eslint/typedef
168
- _f[_d] = ctx,
169
- _f;
170
- };
171
- var cloneClassFunction = cloneClass();
172
- //#region gather all instances for all contexts
173
- // TODO this is not needed anymore - for typeorm I use normal entities
174
- // this thinng belowe is nice for debugging purpose
175
- // if (_.isUndefined(cloneClassFunction[Symbols.orignalClassClonesObj])) {
176
- // cloneClassFunction[Symbols.orignalClassClonesObj] = {};
177
- // }
178
- // if (_.isUndefined(BaseClass[Symbols.orignalClassClonesObj])) {
179
- // BaseClass[Symbols.orignalClassClonesObj] = {};
180
- // }
181
- // const all = {
182
- // ...BaseClass[Symbols.orignalClassClonesObj],
183
- // ...cloneClassFunction[Symbols.orignalClassClonesObj],
184
- // };
185
- // all[ctx.contextName] = cloneClassFunction;
186
- // cloneClassFunction[Symbols.orignalClassClonesObj] = all;
187
- // BaseClass[Symbols.orignalClassClonesObj] = all;
188
- //#endregion
189
- return cloneClassFunction;
190
- };
340
+ //#region prepare instances
341
+ for (const classTypeName of this.injectableTypesfromContexts) {
342
+ this.classInstancesByNameObj[classTypeName] = {};
343
+ this.objWithClassesInstancesArr[classTypeName] = [];
344
+ }
345
+ for (const classTypeName of this.injectableTypesfromContexts) {
346
+ await this.createInstances(this.config[models_1.Models.ClassTypeKey[classTypeName]], classTypeName);
347
+ }
191
348
  //#endregion
192
- //#region methods & getters / clone classes obj with new metadata
193
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
194
- this.cloneClassesObjWithNewMetadata = function (_a) {
195
- var e_1, _b;
196
- var classesInput = _a.classesInput, config = _a.config, ctx = _a.ctx, classType = _a.classType;
197
- var classes = {};
198
- try {
199
- // console.log(Object.keys(classesInput))
200
- for (var _c = tslib_1.__values(Object.keys(classesInput || {})), _d = _c.next(); !_d.done; _d = _c.next()) {
201
- var key = _d.value;
202
- var BaseClass_1 = classesInput[key];
203
- if (!BaseClass_1) {
204
- tnp_core_4.Helpers.error("Class ".concat(key, " is not defined in context ").concat(ctx.contextName, "\n\n Please check if you have correct import in context file\n\n "));
205
- }
206
- var className = Reflect.getMetadata(symbols_1.Symbols.metadata.className, BaseClass_1);
207
- // console.log('Metadata className', className, BaseClass);
208
- // if (!className) {
209
- // console.warn(`Please provide className for ${BaseClass.name} class`);
210
- // }
211
- className = className || key;
212
- BaseClass_1[symbols_1.Symbols.classNameStaticProperty] = className;
213
- var clonedClass = _this.cloneClassWithNewMetadata({
214
- BaseClass: BaseClass_1,
215
- className: className,
216
- config: config,
217
- ctx: ctx,
218
- classType: classType,
219
- });
220
- classes[className] = clonedClass;
221
- }
349
+ if (!this.isRunOrRevertOnlyMigrationAppStart) {
350
+ //#region prepares server
351
+ if (this.mode === 'backend-frontend(tcp+udp)' && !this.config.abstract) {
352
+ //#region @backend
353
+ this.expressApp = express();
354
+ this.initMiddlewares();
355
+ this.serverTcpUdp = this.isHttpServer
356
+ ? new tnp_core_1.https.Server({
357
+ key: this.config.https?.key,
358
+ cert: this.config.https?.cert,
359
+ }, this.expressApp)
360
+ : new tnp_core_1.http.Server(this.expressApp);
361
+ this.publicAssets.forEach(asset => {
362
+ this.expressApp.use(asset.serverPath, express.static(asset.locationOnDisk));
363
+ });
364
+ //#endregion
222
365
  }
223
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
224
- finally {
225
- try {
226
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
366
+ //#endregion
367
+ //#region prepare realtime
368
+ if (!this.config.abstract) {
369
+ this.disabledRealtime = !!this.config.disabledRealtime;
370
+ //#region @backend
371
+ if (tnp_core_4.Helpers.isRunningIn.cliMode()) {
372
+ // TODO for now...
373
+ this.disabledRealtime = true;
227
374
  }
228
- finally { if (e_1) throw e_1.error; }
229
- }
230
- return classes;
231
- };
232
- }
233
- //#region static
234
- /* */
235
- /* */
236
- EndpointContext.initNgZone = function (ngZone) {
237
- /* */
238
- /* */
239
- };
240
- Object.defineProperty(EndpointContext.prototype, "isRunOrRevertOnlyMigrationAppStart", {
241
- get: function () {
242
- return !!(this.onlyMigrationRun || this.onlyMigrationRevertToTimestamp);
243
- },
244
- enumerable: false,
245
- configurable: true
246
- });
247
- Object.defineProperty(EndpointContext.prototype, "realtimeClient", {
248
- get: function () {
249
- return this.realtime.client;
250
- },
251
- enumerable: false,
252
- configurable: true
253
- });
254
- Object.defineProperty(EndpointContext.prototype, "realtimeServer", {
255
- get: function () {
256
- return this.realtime.server;
257
- },
258
- enumerable: false,
259
- configurable: true
260
- });
261
- Object.defineProperty(EndpointContext.prototype, "logHttp", {
262
- //#endregion
263
- //#region fields / logs
264
- get: function () {
265
- var _a, _b;
266
- if (tnp_core_4._.isObject((_a = this.config) === null || _a === void 0 ? void 0 : _a.logs)) {
267
- return !!this.config.logs.http;
268
- }
269
- return ((_b = this.config) === null || _b === void 0 ? void 0 : _b.logs) === true;
270
- },
271
- enumerable: false,
272
- configurable: true
273
- });
274
- Object.defineProperty(EndpointContext.prototype, "logRealtime", {
275
- get: function () {
276
- var _a, _b;
277
- if (tnp_core_4._.isObject((_a = this.config) === null || _a === void 0 ? void 0 : _a.logs)) {
278
- return !!this.config.logs.realtime;
279
- }
280
- return ((_b = this.config) === null || _b === void 0 ? void 0 : _b.logs) === true;
281
- },
282
- enumerable: false,
283
- configurable: true
284
- });
285
- Object.defineProperty(EndpointContext.prototype, "logFramework", {
286
- get: function () {
287
- var _a, _b;
288
- if (tnp_core_4._.isObject((_a = this.config) === null || _a === void 0 ? void 0 : _a.logs)) {
289
- return !!this.config.logs.framework;
375
+ //#endregion
376
+ this.realtime = new realtime_core_1.RealtimeCore(this);
290
377
  }
291
- return ((_b = this.config) === null || _b === void 0 ? void 0 : _b.logs) === true;
292
- },
293
- enumerable: false,
294
- configurable: true
295
- });
296
- Object.defineProperty(EndpointContext.prototype, "logDb", {
297
- get: function () {
298
- var _a, _b;
299
- if (tnp_core_4._.isObject((_a = this.config) === null || _a === void 0 ? void 0 : _a.logs)) {
300
- return !!this.config.logs.db;
378
+ //#endregion
379
+ }
380
+ //#region show context info
381
+ // console.log({ ref })
382
+ if (this.config.abstract) {
383
+ this.logFramework &&
384
+ tnp_core_4.Helpers.info(`[taon] Create abstract context: ${this.config.contextName}`);
385
+ }
386
+ else {
387
+ if (this.config.remoteHost) {
388
+ this.logFramework &&
389
+ tnp_core_4.Helpers.info(`[taon] Create context for remote host: ${this.config.remoteHost}`);
301
390
  }
302
- return ((_b = this.config) === null || _b === void 0 ? void 0 : _b.logs) === true;
303
- },
304
- enumerable: false,
305
- configurable: true
306
- });
307
- Object.defineProperty(EndpointContext.prototype, "logMigrations", {
308
- get: function () {
309
- var _a, _b;
310
- if (tnp_core_4._.isObject((_a = this.config) === null || _a === void 0 ? void 0 : _a.logs)) {
311
- return !!this.config.logs.migrations;
391
+ else {
392
+ this.logFramework &&
393
+ tnp_core_4.Helpers.info(`[taon] Create context for host: ${this.config.host}`);
312
394
  }
313
- return ((_b = this.config) === null || _b === void 0 ? void 0 : _b.logs) === true;
314
- },
315
- enumerable: false,
316
- configurable: true
317
- });
318
- //#endregion
319
- //#region methods & getters / init
320
- EndpointContext.prototype.init = function (options) {
321
- return tslib_1.__awaiter(this, void 0, void 0, function () {
322
- var _a, initFromRecrusiveContextResovle, overrideHost, overrideRemoteHost, onlyMigrationRun, onlyMigrationRevertToTimestamp, oneHour, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, classTypeName, _r, _s, classTypeName, e_2_1;
323
- var e_3, _t, e_2, _u;
324
- var _this = this;
325
- var _v, _w;
326
- return tslib_1.__generator(this, function (_x) {
327
- switch (_x.label) {
328
- case 0:
329
- _a = options || {}, initFromRecrusiveContextResovle = _a.initFromRecrusiveContextResovle, overrideHost = _a.overrideHost, overrideRemoteHost = _a.overrideRemoteHost, onlyMigrationRun = _a.onlyMigrationRun, onlyMigrationRevertToTimestamp = _a.onlyMigrationRevertToTimestamp;
330
- this.inited = true;
331
- // @ts-ignore
332
- this.onlyMigrationRun = onlyMigrationRun;
333
- // @ts-ignore
334
- this.onlyMigrationRevertToTimestamp = onlyMigrationRevertToTimestamp;
335
- this.config = this.configFn(env_1.ENV);
336
- if (tnp_core_4._.isObject(this.config.database)) {
337
- this.config.database = models_1.Models.DatabaseConfig.from(this.config.database).databaseConfigTypeORM;
338
- }
339
- if (overrideHost && overrideRemoteHost) {
340
- tnp_core_4.Helpers.throw("[taon-config] You can't have overrideHost and overrideRemoteHost at the same time");
341
- }
342
- this.config.host = !tnp_core_4._.isUndefined(overrideHost)
343
- ? overrideHost
344
- : this.config.host;
345
- this.config.remoteHost = !tnp_core_4._.isUndefined(overrideRemoteHost)
346
- ? overrideRemoteHost
347
- : this.config.remoteHost;
348
- this.config.host = this.host === null ? void 0 : this.host;
349
- this.config.remoteHost =
350
- this.remoteHost === null ? void 0 : this.remoteHost;
351
- if (this.config.host &&
352
- !this.config.host.startsWith('http://') &&
353
- !this.config.host.startsWith('https://')) {
354
- tnp_core_4.Helpers.throw("[taon-config] Your 'host' must start with http:// or https://");
355
- }
356
- if (this.config.remoteHost &&
357
- !this.config.remoteHost.startsWith('http://') &&
358
- !this.config.remoteHost.startsWith('https://')) {
359
- tnp_core_4.Helpers.throw("[taon-config] Your 'remoteHost' must start with http:// or https://");
360
- }
361
- //#region resolve if skipping writing server routes
362
- //@ts-expect-error overriding readonly
363
- this.skipWritingServerRoutes = tnp_core_4._.isBoolean(this.config.skipWritingServerRoutes)
364
- ? this.config.skipWritingServerRoutes
365
- : false;
366
- //#endregion
367
- //#region resolve mode
368
- if (this.config.host) {
369
- this.mode = 'backend-frontend(tcp+udp)';
370
- /* */
371
- /* */
372
- }
373
- if (this.config.remoteHost) {
374
- if (this.config.host) {
375
- tnp_core_4.Helpers.throw("[taon] You can't have remoteHost and host at the same time");
376
- }
377
- this.mode = 'remote-backend(tcp+udp)';
378
- }
379
- if (this.config.useIpcWhenElectron && tnp_core_4.Helpers.isElectron) {
380
- if (tnp_core_4.Helpers.isWebSQL) {
381
- this.mode = 'backend-frontend(websql-electron)';
382
- }
383
- else {
384
- this.mode = 'backend-frontend(ipc-electron)';
385
- }
386
- }
387
- if (!this.mode && !this.config.abstract) {
388
- tnp_core_4.Helpers.error("[taon] Context \"".concat(this.contextName, "\": You need to provide host or remoteHost or useIpcWhenElectron"), false, true);
389
- //#region @backend
390
- process.exit(1);
391
- //#endregion
392
- }
393
- //#endregion
394
- //#region resolve database config
395
- if (this.config.database === true) {
396
- this.databaseConfig = this.getAutoGeneratedConfig();
397
- }
398
- else if (tnp_core_4._.isObject(this.config.database)) {
399
- this.databaseConfig = tnp_core_4._.merge(this.getAutoGeneratedConfig(), tnp_core_4._.cloneDeep(this.config.database));
400
- }
401
- //#endregion
402
- //#region resolve session
403
- if (this.config.session) {
404
- this.session = tnp_core_4._.cloneDeep(this.config.session);
405
- oneHour = 1000 * 60 * 60 * 1;
406
- if (!this.session.cookieMaxAge) {
407
- this.session.cookieMaxAge = oneHour;
408
- }
409
- // serever and browser cookie authentication
410
- axios_1.default.defaults.withCredentials = true;
411
- }
412
- //#endregion
413
- //#region prepare & gather all classes recrusively
414
- this.config.contexts = this.config.contexts || {};
415
- this.config.entities = this.config.entities || {};
416
- this.config.controllers = this.config.controllers || {};
417
- this.config.repositories = this.config.repositories || {};
418
- this.config.providers = this.config.providers || {};
419
- this.config.subscribers = this.config.subscribers || {};
420
- this.config.migrations = this.config.migrations || {};
421
- _b = this.config;
422
- _c = [{}];
423
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.ENTITY)];
424
- case 1:
425
- _b.entities = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _c.concat([(_x.sent())])), this.config.entities]);
426
- _d = this.config;
427
- _e = [{}];
428
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.CONTROLLER)];
429
- case 2:
430
- _d.controllers = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _e.concat([(_x.sent())])), this.config.controllers]);
431
- _f = this.config;
432
- _g = [{}];
433
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.PROVIDER)];
434
- case 3:
435
- _f.providers = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _g.concat([(_x.sent())])), this.config.providers]);
436
- _h = this.config;
437
- _j = [{}];
438
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.SUBSCRIBER)];
439
- case 4:
440
- _h.subscribers = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _j.concat([(_x.sent())])), this.config.subscribers]);
441
- _k = this.config;
442
- _l = [{}];
443
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.REPOSITORY)];
444
- case 5:
445
- _k.repositories = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _l.concat([(_x.sent())])), this.config.repositories]);
446
- _m = this.config;
447
- _o = [{}];
448
- return [4 /*yield*/, this.getRecrusiveClassesfromContextsObj(models_1.Models.ClassType.MIGRATION)];
449
- case 6:
450
- _m.migrations = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _o.concat([(_x.sent())])), this.config.migrations]);
451
- // console.log(this.config);
452
- // debugger;
453
- //#endregion
454
- //#region prepare classes instances/functions clones
455
- this.config.controllers = this.cloneClassesObjWithNewMetadata({
456
- classesInput: this.config.controllers,
457
- config: this.config,
458
- ctx: this,
459
- classType: models_1.Models.ClassType.CONTROLLER,
460
- });
461
- this.config.repositories = this.cloneClassesObjWithNewMetadata({
462
- classesInput: this.config.repositories,
463
- config: this.config,
464
- ctx: this,
465
- classType: models_1.Models.ClassType.REPOSITORY,
466
- });
467
- this.config.providers = this.cloneClassesObjWithNewMetadata({
468
- classesInput: this.config.providers,
469
- config: this.config,
470
- ctx: this,
471
- classType: models_1.Models.ClassType.PROVIDER,
472
- });
473
- this.config.subscribers = this.cloneClassesObjWithNewMetadata({
474
- classesInput: this.config.subscribers,
475
- config: this.config,
476
- ctx: this,
477
- classType: models_1.Models.ClassType.SUBSCRIBER,
478
- });
479
- this.config.migrations = this.cloneClassesObjWithNewMetadata({
480
- classesInput: this.config.migrations,
481
- config: this.config,
482
- ctx: this,
483
- classType: models_1.Models.ClassType.MIGRATION,
484
- });
485
- try {
486
- //#endregion
487
- //#region prepare instances
488
- for (_p = tslib_1.__values(this.injectableTypesfromContexts), _q = _p.next(); !_q.done; _q = _p.next()) {
489
- classTypeName = _q.value;
490
- this.classInstancesByNameObj[classTypeName] = {};
491
- this.objWithClassesInstancesArr[classTypeName] = [];
492
- }
493
- }
494
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
495
- finally {
496
- try {
497
- if (_q && !_q.done && (_t = _p.return)) _t.call(_p);
498
- }
499
- finally { if (e_3) throw e_3.error; }
500
- }
501
- _x.label = 7;
502
- case 7:
503
- _x.trys.push([7, 12, 13, 14]);
504
- _r = tslib_1.__values(this.injectableTypesfromContexts), _s = _r.next();
505
- _x.label = 8;
506
- case 8:
507
- if (!!_s.done) return [3 /*break*/, 11];
508
- classTypeName = _s.value;
509
- return [4 /*yield*/, this.createInstances(this.config[models_1.Models.ClassTypeKey[classTypeName]], classTypeName)];
510
- case 9:
511
- _x.sent();
512
- _x.label = 10;
513
- case 10:
514
- _s = _r.next();
515
- return [3 /*break*/, 8];
516
- case 11: return [3 /*break*/, 14];
517
- case 12:
518
- e_2_1 = _x.sent();
519
- e_2 = { error: e_2_1 };
520
- return [3 /*break*/, 14];
521
- case 13:
522
- try {
523
- if (_s && !_s.done && (_u = _r.return)) _u.call(_r);
524
- }
525
- finally { if (e_2) throw e_2.error; }
526
- return [7 /*endfinally*/];
527
- case 14:
528
- //#endregion
529
- if (!this.isRunOrRevertOnlyMigrationAppStart) {
530
- //#region prepares server
531
- if (this.mode === 'backend-frontend(tcp+udp)' && !this.config.abstract) {
532
- //#region @backend
533
- this.expressApp = express();
534
- this.initMiddlewares();
535
- this.serverTcpUdp = this.isHttpServer
536
- ? new tnp_core_1.https.Server({
537
- key: (_v = this.config.https) === null || _v === void 0 ? void 0 : _v.key,
538
- cert: (_w = this.config.https) === null || _w === void 0 ? void 0 : _w.cert,
539
- }, this.expressApp)
540
- : new tnp_core_1.http.Server(this.expressApp);
541
- this.publicAssets.forEach(function (asset) {
542
- _this.expressApp.use(asset.serverPath, express.static(asset.locationOnDisk));
543
- });
544
- //#endregion
545
- }
546
- //#endregion
547
- //#region prepare realtime
548
- if (!this.config.abstract) {
549
- this.disabledRealtime = !!this.config.disabledRealtime;
550
- //#region @backend
551
- if (tnp_core_4.Helpers.isRunningIn.cliMode()) {
552
- // TODO for now...
553
- this.disabledRealtime = true;
554
- }
555
- //#endregion
556
- this.realtime = new realtime_core_1.RealtimeCore(this);
557
- }
558
- //#endregion
559
- }
560
- //#region show context info
561
- // console.log({ ref })
562
- if (this.config.abstract) {
563
- this.logFramework &&
564
- tnp_core_4.Helpers.info("[taon] Create abstract context: ".concat(this.config.contextName));
565
- }
566
- else {
567
- if (this.config.remoteHost) {
568
- this.logFramework &&
569
- tnp_core_4.Helpers.info("[taon] Create context for remote host: ".concat(this.config.remoteHost));
570
- }
571
- else {
572
- this.logFramework &&
573
- tnp_core_4.Helpers.info("[taon] Create context for host: ".concat(this.config.host));
574
- }
575
- }
576
- //#endregion
577
- // update first exposed config
578
- Object.keys(this.config).forEach(function (key) {
579
- _this.originalConfig[key] = _this.config[key];
580
- });
581
- return [2 /*return*/];
582
- }
583
- });
395
+ }
396
+ //#endregion
397
+ // update first exposed config
398
+ Object.keys(this.config).forEach(key => {
399
+ this.originalConfig[key] = this.config[key];
584
400
  });
585
- };
401
+ }
586
402
  //#endregion
587
403
  //#region methods & getters / get auto generated config
588
- EndpointContext.prototype.getAutoGeneratedConfig = function () {
404
+ getAutoGeneratedConfig() {
589
405
  //#region @websqlFunc
590
- var databaseConfig = models_1.Models.DatabaseConfig.from({});
406
+ let databaseConfig = models_1.Models.DatabaseConfig.from({});
591
407
  if (tnp_core_2.UtilsOs.isRunningInDocker()) {
592
408
  tnp_core_4.Helpers.info('Running in docker, using in mysql database');
593
409
  // TODO auto resolve database config in docker
594
410
  databaseConfig = models_1.Models.DatabaseConfig.from({
595
- database: "db-".concat(this.contextName, ".sqlite"),
411
+ database: `db-${this.contextName}.sqlite`,
596
412
  type: 'mysql',
597
413
  recreateMode: 'PRESERVE_DATA+MIGRATIONS',
598
414
  logging: this.logDb,
@@ -604,12 +420,12 @@ var EndpointContext = /** @class */ (function () {
604
420
  }
605
421
  else {
606
422
  this.logFramework &&
607
- tnp_core_4.Helpers.info("[taon][database] Automatically resolving database config for mode ".concat(this.mode));
423
+ tnp_core_4.Helpers.info(`[taon][database] Automatically resolving database config for mode ${this.mode}`);
608
424
  switch (this.mode) {
609
425
  //#region resolve database config for mode backend-frontend(tcp+udp)
610
426
  case 'backend-frontend(ipc-electron)':
611
427
  databaseConfig = models_1.Models.DatabaseConfig.from({
612
- location: "db-".concat(this.contextName, ".sqlite"),
428
+ location: `db-${this.contextName}.sqlite`,
613
429
  type: 'sqljs',
614
430
  recreateMode: 'DROP_DB+MIGRATIONS',
615
431
  logging: this.logDb,
@@ -619,12 +435,12 @@ var EndpointContext = /** @class */ (function () {
619
435
  //#region resolve database config for mode backend-frontend(websql)
620
436
  case 'backend-frontend(websql-electron)':
621
437
  case 'backend-frontend(websql)':
622
- var keepWebsqlDbDataAfterReload = false;
438
+ let keepWebsqlDbDataAfterReload = false;
623
439
  /* */
624
440
  /* */
625
441
  /* */
626
442
  databaseConfig = databaseConfig = models_1.Models.DatabaseConfig.from({
627
- location: "db-".concat(this.contextName, ".sqlite"),
443
+ location: `db-${this.contextName}.sqlite`,
628
444
  type: 'sqljs',
629
445
  useLocalForage: true, // !!window['localforage'], // TODO this need to be checked in runtime
630
446
  recreateMode: keepWebsqlDbDataAfterReload
@@ -637,8 +453,8 @@ var EndpointContext = /** @class */ (function () {
637
453
  //#region resolve database config for mode backend-frontend(tcp+udp)
638
454
  case 'backend-frontend(tcp+udp)':
639
455
  databaseConfig = models_1.Models.DatabaseConfig.from({
640
- database: "context-db-".concat(this.contextName),
641
- location: "db-".concat(this.contextName, ".sqlite"),
456
+ database: `context-db-${this.contextName}`,
457
+ location: `db-${this.contextName}.sqlite`,
642
458
  type: 'sqljs',
643
459
  recreateMode: 'DROP_DB+MIGRATIONS',
644
460
  logging: this.logDb,
@@ -649,30 +465,28 @@ var EndpointContext = /** @class */ (function () {
649
465
  }
650
466
  return databaseConfig.databaseConfigTypeORM;
651
467
  //#endregion
652
- };
653
- Object.defineProperty(EndpointContext.prototype, "ngZone", {
654
- //#endregion
655
- //#region methods & getters / ng zone
656
- get: function () {
657
- /* */
658
- /* */
659
- return;
660
- },
661
- enumerable: false,
662
- configurable: true
663
- });
468
+ }
469
+ //#endregion
470
+ //#region methods & getters / ng zone
471
+ get ngZone() {
472
+ /* */
473
+ /* */
474
+ return;
475
+ }
664
476
  //#endregion
665
477
  //#region methods & getters / start server
666
- EndpointContext.prototype.startServer = function () {
667
- var _this = this;
478
+ startServer() {
668
479
  //#region @backendFunc
669
480
  if (this.remoteHost || this.isRunOrRevertOnlyMigrationAppStart) {
670
481
  return;
671
482
  }
672
483
  if (this.mode === 'backend-frontend(tcp+udp)') {
673
484
  // this.displayRoutes(this.expressApp);
674
- this.serverTcpUdp.listen(Number(this.uri.port), function () {
675
- tnp_core_4.Helpers.log("[taon][express-server]listening on port: ".concat(_this.uri.port, ", hostname: ").concat(_this.uri.pathname, ",\n address: ").concat(_this.uri.protocol, "//localhost:").concat(_this.uri.port).concat(_this.uri.pathname, "\n env: ").concat(_this.expressApp.settings.env, "\n "));
485
+ this.serverTcpUdp.listen(Number(this.uri.port), () => {
486
+ tnp_core_4.Helpers.log(`[taon][express-server]listening on port: ${this.uri.port}, hostname: ${this.uri.pathname},
487
+ address: ${this.uri.protocol}//localhost:${this.uri.port}${this.uri.pathname}
488
+ env: ${this.expressApp.settings.env}
489
+ `);
676
490
  });
677
491
  }
678
492
  else {
@@ -680,18 +494,17 @@ var EndpointContext = /** @class */ (function () {
680
494
  tnp_core_4.Helpers.info('Ipc communication enable instead tcp/upd');
681
495
  }
682
496
  //#endregion
683
- };
497
+ }
684
498
  //#endregion
685
499
  //#region methods & getters / display express routes
686
- EndpointContext.prototype.displayRoutes = function (app) {
687
- var _a;
500
+ displayRoutes(app) {
688
501
  //#region @backend
689
- var routes = [];
690
- (_a = app._router) === null || _a === void 0 ? void 0 : _a.stack.forEach(function (middleware) {
502
+ const routes = [];
503
+ app._router?.stack.forEach(function (middleware) {
691
504
  if (middleware.route) {
692
505
  // routes registered directly on the app
693
- var methods = [];
694
- for (var method in middleware.route.methods) {
506
+ const methods = [];
507
+ for (let method in middleware.route.methods) {
695
508
  if (middleware.route.methods[method]) {
696
509
  methods.push(method.toUpperCase());
697
510
  }
@@ -701,8 +514,8 @@ var EndpointContext = /** @class */ (function () {
701
514
  else if (middleware.name === 'router') {
702
515
  // router middleware
703
516
  middleware.handle.stack.forEach(function (handler) {
704
- var methods = [];
705
- for (var method in handler.route.methods) {
517
+ const methods = [];
518
+ for (let method in handler.route.methods) {
706
519
  if (handler.route.methods[method]) {
707
520
  methods.push(method.toUpperCase());
708
521
  }
@@ -713,146 +526,201 @@ var EndpointContext = /** @class */ (function () {
713
526
  });
714
527
  console.log(routes);
715
528
  //#endregion
716
- };
717
- Object.defineProperty(EndpointContext.prototype, "modeAllowsDatabaseCreation", {
718
- //#endregion
719
- //#region methods & getters / mode allows database creation
720
- get: function () {
721
- return (this.mode === 'backend-frontend(tcp+udp)' ||
722
- this.mode === 'backend-frontend(websql)' ||
723
- this.mode === 'backend-frontend(ipc-electron)');
724
- },
725
- enumerable: false,
726
- configurable: true
727
- });
529
+ }
728
530
  //#endregion
729
- //#region methods & getters / get recursive classes from contexts
730
- EndpointContext.prototype.getRecrusiveClassesfromContextsObj = function (classType) {
731
- return tslib_1.__awaiter(this, void 0, void 0, function () {
732
- var arr;
733
- return tslib_1.__generator(this, function (_a) {
734
- switch (_a.label) {
735
- case 0: return [4 /*yield*/, this.getRecrusiveClassesfromContexts(classType)];
736
- case 1:
737
- arr = _a.sent();
738
- return [2 /*return*/, arr.reduce(function (acc, c) {
739
- acc[class_helpers_1.ClassHelpers.getName(c)] = c;
740
- return acc;
741
- }, {})];
531
+ //#region methods & getters / mode allows database creation
532
+ get modeAllowsDatabaseCreation() {
533
+ return (this.mode === 'backend-frontend(tcp+udp)' ||
534
+ this.mode === 'backend-frontend(websql)' ||
535
+ this.mode === 'backend-frontend(ipc-electron)');
536
+ }
537
+ //#endregion
538
+ //#region methods & getters / clone class
539
+ // eslint-disable-next-line @typescript-eslint/typedef
540
+ cloneClassWithNewMetadata = ({ BaseClass, className, config, ctx, classType, }) => {
541
+ // Return a new class that extends the base class
542
+ const cloneClass = () => {
543
+ if (BaseClass[symbols_1.Symbols.fullClassNameStaticProperty] ===
544
+ `${ctx.contextName}.${className}`) {
545
+ return BaseClass;
546
+ }
547
+ return class extends BaseClass {
548
+ // static ['_'] = BaseClass['_'];
549
+ // eslint-disable-next-line @typescript-eslint/typedef
550
+ // @ts-ignore
551
+ static [symbols_1.Symbols.orignalClass] = BaseClass;
552
+ // eslint-disable-next-line @typescript-eslint/typedef
553
+ // @ts-ignore
554
+ static [symbols_1.Symbols.fullClassNameStaticProperty] = `${ctx.contextName}.${className}`;
555
+ // eslint-disable-next-line @typescript-eslint/typedef
556
+ // @ts-ignore
557
+ static [symbols_1.Symbols.classNameStaticProperty] = className;
558
+ // eslint-disable-next-line @typescript-eslint/typedef
559
+ static [symbols_1.Symbols.ctxInClassOrClassObj] = ctx;
560
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/typedef
561
+ static __getFullPathForClass__(arr = []) {
562
+ const name = this[symbols_1.Symbols.fullClassNameStaticProperty];
563
+ arr.push(name);
564
+ // @ts-ignore
565
+ if (this[symbols_1.Symbols.orignalClass] && // @ts-ignore
566
+ this[symbols_1.Symbols.orignalClass].__getFullPathForClass__) {
567
+ // @ts-ignore
568
+ this[symbols_1.Symbols.orignalClass].__getFullPathForClass__(arr);
569
+ }
570
+ return arr.join('/');
742
571
  }
743
- });
744
- });
745
- };
746
- EndpointContext.prototype.getRecrusiveClassesfromContexts = function (classType_1) {
747
- return tslib_1.__awaiter(this, arguments, void 0, function (classType, arr) {
748
- var contexts, contexts_1, contexts_1_1, ctx, ref, classesInput, clonedClasses, e_4_1;
749
- var e_4, _a;
750
- if (arr === void 0) { arr = []; }
751
- return tslib_1.__generator(this, function (_b) {
752
- switch (_b.label) {
753
- case 0:
754
- contexts = Object.values(this.config.contexts || {});
755
- _b.label = 1;
756
- case 1:
757
- _b.trys.push([1, 7, 8, 9]);
758
- contexts_1 = tslib_1.__values(contexts), contexts_1_1 = contexts_1.next();
759
- _b.label = 2;
760
- case 2:
761
- if (!!contexts_1_1.done) return [3 /*break*/, 6];
762
- ctx = contexts_1_1.value;
763
- return [4 /*yield*/, ctx.__ref()];
764
- case 3:
765
- ref = _b.sent();
766
- classesInput = ref.getClassFunBy(classType);
767
- clonedClasses = Object.values(this.cloneClassesObjWithNewMetadata({
768
- classesInput: classesInput,
769
- config: this.config,
770
- ctx: this,
771
- classType: classType,
772
- }));
773
- // console.log(`${classType} clonedClasses`, clonedClasses);
774
- clonedClasses.forEach(function (c) { return arr.push(c); });
775
- return [4 /*yield*/, ref.getRecrusiveClassesfromContexts(classType, arr)];
776
- case 4:
777
- _b.sent();
778
- _b.label = 5;
779
- case 5:
780
- contexts_1_1 = contexts_1.next();
781
- return [3 /*break*/, 2];
782
- case 6: return [3 /*break*/, 9];
783
- case 7:
784
- e_4_1 = _b.sent();
785
- e_4 = { error: e_4_1 };
786
- return [3 /*break*/, 9];
787
- case 8:
788
- try {
789
- if (contexts_1_1 && !contexts_1_1.done && (_a = contexts_1.return)) _a.call(contexts_1);
790
- }
791
- finally { if (e_4) throw e_4.error; }
792
- return [7 /*endfinally*/];
793
- case 9: return [2 /*return*/, arr];
572
+ static get fullPathForClass() {
573
+ return this.__getFullPathForClass__();
794
574
  }
575
+ [symbols_1.Symbols.ctxInClassOrClassObj] = ctx;
576
+ };
577
+ };
578
+ const cloneClassFunction = cloneClass();
579
+ //#region gather all instances for all contexts
580
+ // TODO this is not needed anymore - for typeorm I use normal entities
581
+ // this thinng belowe is nice for debugging purpose
582
+ // if (_.isUndefined(cloneClassFunction[Symbols.orignalClassClonesObj])) {
583
+ // cloneClassFunction[Symbols.orignalClassClonesObj] = {};
584
+ // }
585
+ // if (_.isUndefined(BaseClass[Symbols.orignalClassClonesObj])) {
586
+ // BaseClass[Symbols.orignalClassClonesObj] = {};
587
+ // }
588
+ // const all = {
589
+ // ...BaseClass[Symbols.orignalClassClonesObj],
590
+ // ...cloneClassFunction[Symbols.orignalClassClonesObj],
591
+ // };
592
+ // all[ctx.contextName] = cloneClassFunction;
593
+ // cloneClassFunction[Symbols.orignalClassClonesObj] = all;
594
+ // BaseClass[Symbols.orignalClassClonesObj] = all;
595
+ //#endregion
596
+ return cloneClassFunction;
597
+ };
598
+ //#endregion
599
+ //#region methods & getters / clone classes obj with new metadata
600
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
601
+ cloneClassesObjWithNewMetadata = ({ classesInput, config, ctx, classType, }) => {
602
+ const classes = {};
603
+ // console.log(Object.keys(classesInput))
604
+ for (const key of Object.keys(classesInput || {})) {
605
+ const BaseClass = classesInput[key];
606
+ if (!BaseClass) {
607
+ tnp_core_4.Helpers.error(`Class ${key} is not defined in context ${ctx.contextName}
608
+
609
+ Please check if you have correct import in context file
610
+
611
+ `);
612
+ }
613
+ var className = Reflect.getMetadata(symbols_1.Symbols.metadata.className, BaseClass);
614
+ // console.log('Metadata className', className, BaseClass);
615
+ // if (!className) {
616
+ // console.warn(`Please provide className for ${BaseClass.name} class`);
617
+ // }
618
+ className = className || key;
619
+ BaseClass[symbols_1.Symbols.classNameStaticProperty] = className;
620
+ const clonedClass = this.cloneClassWithNewMetadata({
621
+ BaseClass,
622
+ className,
623
+ config,
624
+ ctx,
625
+ classType,
795
626
  });
796
- });
627
+ classes[className] = clonedClass;
628
+ }
629
+ return classes;
797
630
  };
798
631
  //#endregion
632
+ //#region methods & getters / get recursive classes from contexts
633
+ async getRecrusiveClassesfromContextsObj(classType) {
634
+ const arr = await this.getRecrusiveClassesfromContexts(classType);
635
+ return arr.reduce((acc, c) => {
636
+ acc[class_helpers_1.ClassHelpers.getName(c)] = c;
637
+ return acc;
638
+ }, {});
639
+ }
640
+ async getRecrusiveClassesfromContexts(classType, arr = []) {
641
+ const contexts = Object.values(this.config.contexts || {});
642
+ // console.log({
643
+ // contexts,
644
+ // });
645
+ for (const ctx of contexts) {
646
+ // console.log(`STARTING ${ctx.contextName}`);
647
+ const ref = await ctx.__ref();
648
+ // console.log(`CTX FROM ${ctx.contextName}`, ref.contextName);
649
+ const classesInput = ref.getClassFunBy(classType);
650
+ // console.log(`${ref.contextName} - ${classType}`, { classesInput });
651
+ const clonedClasses = Object.values(this.cloneClassesObjWithNewMetadata({
652
+ classesInput,
653
+ config: this.config,
654
+ ctx: this,
655
+ classType,
656
+ }));
657
+ // console.log(`${classType} clonedClasses`, clonedClasses);
658
+ clonedClasses.forEach(c => arr.push(c));
659
+ await ref.getRecrusiveClassesfromContexts(classType, arr);
660
+ }
661
+ return arr;
662
+ }
663
+ //#endregion
799
664
  //#region methods & getters / get class instances by class type
800
- EndpointContext.prototype.getClassInstanceObjBy = function (classType) {
665
+ getClassInstanceObjBy(classType) {
801
666
  return this.classInstancesByNameObj[classType];
802
- };
667
+ }
803
668
  //#endregion
804
669
  //#region methods & getters / get class instances arr
805
- EndpointContext.prototype.getClassesInstancesArrBy = function (classType) {
670
+ getClassesInstancesArrBy(classType) {
806
671
  return this.objWithClassesInstancesArr[classType];
807
- };
672
+ }
808
673
  //#endregion
809
674
  //#region methods & getters / inject
810
- EndpointContext.prototype.inject = function (ctor, options) {
811
- var _a;
675
+ inject(ctor, options) {
812
676
  if (!options) {
813
677
  options = {};
814
678
  }
815
- var className = class_helpers_1.ClassHelpers.getName(ctor);
816
- var locaInstanceConstructorArgs = options.locaInstanceConstructorArgs || [];
679
+ const className = class_helpers_1.ClassHelpers.getName(ctor);
680
+ const locaInstanceConstructorArgs = options.locaInstanceConstructorArgs || [];
817
681
  if (this.isCLassType(models_1.Models.ClassType.REPOSITORY, ctor)) {
818
682
  options.localInstance = true;
819
683
  }
820
- if (options === null || options === void 0 ? void 0 : options.localInstance) {
821
- var ctxClassFn = this.getClassFunByClassName(className);
822
- var entityName = '';
684
+ if (options?.localInstance) {
685
+ const ctxClassFn = this.getClassFunByClassName(className);
686
+ let entityName = '';
823
687
  if (className === 'BaseRepository') {
824
- var entityFn = locaInstanceConstructorArgs[0];
825
- var entity = entityFn && entityFn();
688
+ const entityFn = locaInstanceConstructorArgs[0];
689
+ const entity = entityFn && entityFn();
826
690
  entityName = entity && class_helpers_1.ClassHelpers.getName(entity);
827
691
  }
828
692
  if (!options.contextClassInstance[this.localInstaceObjSymbol]) {
829
693
  options.contextClassInstance[this.localInstaceObjSymbol] = {};
830
694
  }
831
- var instanceKey = className + (entityName ? ".".concat(entityName) : '');
832
- var existed = options.contextClassInstance[this.localInstaceObjSymbol][instanceKey];
695
+ const instanceKey = className + (entityName ? `.${entityName}` : '');
696
+ const existed = options.contextClassInstance[this.localInstaceObjSymbol][instanceKey];
833
697
  if (existed) {
834
698
  // console.log(`exited `, existed)
835
699
  return existed;
836
700
  }
837
701
  if (!ctxClassFn) {
838
- throw new Error("Not able to inject \"".concat(className, "\" inside context \"").concat(this.contextName, "\"\n\n Make sure they share the same context or import context where \"").concat(className, "\" is defined.\n\n "));
702
+ throw new Error(`Not able to inject "${className}" inside context "${this.contextName}"
703
+
704
+ Make sure they share the same context or import context where "${className}" is defined.
705
+
706
+ `);
839
707
  }
840
- var injectedInstance = new ((_a = ctxClassFn).bind.apply(_a, tslib_1.__spreadArray([void 0], tslib_1.__read(locaInstanceConstructorArgs), false)))();
708
+ const injectedInstance = new ctxClassFn(...locaInstanceConstructorArgs);
841
709
  options.contextClassInstance[this.localInstaceObjSymbol][instanceKey] =
842
710
  injectedInstance;
843
711
  // console.log(`injectedInstance `, existed)
844
712
  return injectedInstance;
845
713
  }
846
- var contextScopeInstance = this.allClassesInstances[className];
714
+ const contextScopeInstance = this.allClassesInstances[className];
847
715
  // if (className === 'TopicController') {
848
716
  // debugger;
849
717
  // }
850
718
  return contextScopeInstance;
851
- };
719
+ }
852
720
  /**
853
721
  * alias for inject
854
722
  */
855
- EndpointContext.prototype.getInstanceBy = function (ctor) {
723
+ getInstanceBy(ctor) {
856
724
  // if (!!this.__contextForControllerInstanceAccess) {
857
725
  // const className = ClassHelpers.getName(ctor);
858
726
  // const allControllers = this.getClassFunByArr(Models.ClassType.CONTROLLER);
@@ -867,17 +735,24 @@ var EndpointContext = /** @class */ (function () {
867
735
  // }
868
736
  // }
869
737
  return this.inject(ctor, { localInstance: false });
870
- };
738
+ }
871
739
  //#endregion
872
740
  //#region methods & getters / check if context initialized
873
- EndpointContext.prototype.checkIfContextInitialized = function () {
741
+ checkIfContextInitialized() {
874
742
  if (tnp_core_4._.isUndefined(this.config)) {
875
- throw new Error("Please check if your context has been initialized.\n\n // ...\n await Context.initialize();\n // ...\n\n\n ");
743
+ throw new Error(`Please check if your context has been initialized.
744
+
745
+ // ...
746
+ await Context.initialize();
747
+ // ...
748
+
749
+
750
+ `);
876
751
  }
877
- };
752
+ }
878
753
  //#endregion
879
754
  //#region methods & getters / get class function by class type name
880
- EndpointContext.prototype.getClassFunBy = function (classType) {
755
+ getClassFunBy(classType) {
881
756
  this.checkIfContextInitialized();
882
757
  switch (classType) {
883
758
  case models_1.Models.ClassType.CONTROLLER:
@@ -893,517 +768,329 @@ var EndpointContext = /** @class */ (function () {
893
768
  case models_1.Models.ClassType.MIGRATION:
894
769
  return this.config.migrations;
895
770
  }
896
- };
897
- EndpointContext.prototype.isCLassType = function (classType, classFn) {
771
+ }
772
+ isCLassType(classType, classFn) {
898
773
  return !!this.getClassFunBy(classType)[class_helpers_1.ClassHelpers.getName(classFn)];
899
- };
774
+ }
900
775
  /**
901
776
  * Only for injectable types
902
777
  * Only for classType: CONTROLLER, REPOSITORY, PROVIDER
903
778
  */
904
- EndpointContext.prototype.getClassFunByClassName = function (className) {
905
- var e_5, _a;
906
- try {
907
- for (var _b = tslib_1.__values(this.allTypesfromContexts), _c = _b.next(); !_c.done; _c = _b.next()) {
908
- var classTypeName = _c.value;
909
- var classesForInjectableType = this.config[models_1.Models.ClassTypeKey[classTypeName]];
910
- if (classesForInjectableType[className]) {
911
- return classesForInjectableType[className];
779
+ getClassFunByClassName(className) {
780
+ for (const classTypeName of this.allTypesfromContexts) {
781
+ const classesForInjectableType = this.config[models_1.Models.ClassTypeKey[classTypeName]];
782
+ if (classesForInjectableType[className]) {
783
+ return classesForInjectableType[className];
784
+ }
785
+ }
786
+ }
787
+ getClassFunByClass(classFunction) {
788
+ const className = class_helpers_1.ClassHelpers.getName(classFunction);
789
+ return this.getClassFunByClassName(className);
790
+ }
791
+ getClassFunByArr(classType) {
792
+ return Object.values(this.getClassFunBy(classType) || {});
793
+ }
794
+ //#endregion
795
+ //#region methods & getters / create class instances
796
+ async createInstances(classes, classType) {
797
+ // const recrusiveValuesFromContext =
798
+ // await this.getRecrusiveClassesfromContexts(classType);
799
+ // console.log(this.config.contexts);
800
+ // console.log('recrusiveValuesFromContext', recrusiveValuesFromContext);
801
+ for (const classFn of [
802
+ // ...recrusiveValuesFromContext,
803
+ ...Object.values(classes),
804
+ ]) {
805
+ const instance = di_container_1.DITaonContainer.resolve(classFn);
806
+ const classInstancesByNameObj = this.classInstancesByNameObj[classType];
807
+ const className = class_helpers_1.ClassHelpers.getName(classFn);
808
+ // console.log({ classFn, classType, instance, place, className, 'classInstancesByNameObj': this.classInstancesByNameObj });
809
+ classInstancesByNameObj[className] = instance;
810
+ // update config
811
+ this.config[models_1.Models.ClassTypeKey[classType]][className] = classFn;
812
+ this.objWithClassesInstancesArr[classType].push(instance);
813
+ this.allClassesInstances[className] = instance;
814
+ }
815
+ }
816
+ //#endregion
817
+ //#region methods & getters / reinit controllers db example data
818
+ async reinitControllers() {
819
+ if (this.remoteHost || Object.keys(this.config.migrations).length > 0) {
820
+ return;
821
+ }
822
+ // Helpers.taskStarted(
823
+ // `[taon] REINITING CONTROLLERS ${this.contextName} STARTED`,
824
+ // );
825
+ const controllers = this.getClassesInstancesArrBy(models_1.Models.ClassType.CONTROLLER);
826
+ // console.log('CONTROLLERS TO REINIT', controllers);
827
+ for (const ctrl of controllers) {
828
+ if (tnp_core_4._.isFunction(ctrl.initExampleDbData)) {
829
+ await tnp_core_4.Helpers.runSyncOrAsync({
830
+ functionFn: ctrl.initExampleDbData,
831
+ context: ctrl,
832
+ });
833
+ }
834
+ }
835
+ // Helpers.taskDone(
836
+ // `[taon] REINITING CONTROLLERS ${this.contextName} DONE`,
837
+ // );
838
+ }
839
+ async initClasses() {
840
+ if (this.remoteHost) {
841
+ return;
842
+ }
843
+ for (const classTypeName of [
844
+ models_1.Models.ClassType.PROVIDER,
845
+ models_1.Models.ClassType.REPOSITORY,
846
+ models_1.Models.ClassType.CONTROLLER,
847
+ models_1.Models.ClassType.ENTITY,
848
+ models_1.Models.ClassType.MIGRATION,
849
+ ]) {
850
+ //#region init class static _ property
851
+ // Helpers.taskStarted(
852
+ // `[taon] REINITING _ CLASS FN ${classTypeName} ${this.contextName} STARTED`,
853
+ // );
854
+ for (const classFun of this.getClassFunByArr(classTypeName)) {
855
+ if (tnp_core_4._.isFunction(classFun._)) {
856
+ await tnp_core_4.Helpers.runSyncOrAsync({
857
+ functionFn: classFun._,
858
+ context: classFun,
859
+ });
860
+ // const orgClass = ClassHelpers.getOrginalClass(classFun);
861
+ // // orgClass['ctrl'] = classFun['ctrl'];
862
+ // await Helpers.runSyncOrAsync({
863
+ // functionFn: orgClass._,
864
+ // context: orgClass,
865
+ // });
912
866
  }
913
867
  }
868
+ // Helpers.taskStarted(
869
+ // `[taon] REINITING _ CLASS FN ${classTypeName} ${this.contextName} DONE`,
870
+ // );
871
+ //#endregion
914
872
  }
915
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
916
- finally {
917
- try {
918
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
873
+ for (const classTypeName of [
874
+ models_1.Models.ClassType.PROVIDER,
875
+ models_1.Models.ClassType.REPOSITORY,
876
+ models_1.Models.ClassType.CONTROLLER,
877
+ models_1.Models.ClassType.MIGRATION,
878
+ ]) {
879
+ //#region init providers, repositories _ property
880
+ // Helpers.taskStarted(
881
+ // `[taon] REINITING _ INS FN ${classTypeName} ${this.contextName} STARTED`,
882
+ // );
883
+ for (const ctrl of this.getClassesInstancesArrBy(classTypeName)) {
884
+ if (tnp_core_4._.isFunction(ctrl._)) {
885
+ await tnp_core_4.Helpers.runSyncOrAsync({
886
+ functionFn: ctrl._,
887
+ context: ctrl,
888
+ });
889
+ }
919
890
  }
920
- finally { if (e_5) throw e_5.error; }
891
+ // Helpers.taskStarted(
892
+ // `[taon] REINITING _ INS FN ${classTypeName} ${this.contextName} DONE`,
893
+ // );
894
+ //#endregion
921
895
  }
922
- };
923
- EndpointContext.prototype.getClassFunByClass = function (classFunction) {
924
- var className = class_helpers_1.ClassHelpers.getName(classFunction);
925
- return this.getClassFunByClassName(className);
926
- };
927
- EndpointContext.prototype.getClassFunByArr = function (classType) {
928
- return Object.values(this.getClassFunBy(classType) || {});
929
- };
930
- //#endregion
931
- //#region methods & getters / create class instances
932
- EndpointContext.prototype.createInstances = function (classes, classType) {
933
- return tslib_1.__awaiter(this, void 0, void 0, function () {
934
- var _a, _b, classFn, instance, classInstancesByNameObj, className;
935
- var e_6, _c;
936
- return tslib_1.__generator(this, function (_d) {
937
- try {
938
- // const recrusiveValuesFromContext =
939
- // await this.getRecrusiveClassesfromContexts(classType);
940
- // console.log(this.config.contexts);
941
- // console.log('recrusiveValuesFromContext', recrusiveValuesFromContext);
942
- for (_a = tslib_1.__values(tslib_1.__spreadArray([], tslib_1.__read(Object.values(classes)), false)), _b = _a.next(); !_b.done; _b = _a.next()) {
943
- classFn = _b.value;
944
- instance = di_container_1.DITaonContainer.resolve(classFn);
945
- classInstancesByNameObj = this.classInstancesByNameObj[classType];
946
- className = class_helpers_1.ClassHelpers.getName(classFn);
947
- // console.log({ classFn, classType, instance, place, className, 'classInstancesByNameObj': this.classInstancesByNameObj });
948
- classInstancesByNameObj[className] = instance;
949
- // update config
950
- this.config[models_1.Models.ClassTypeKey[classType]][className] = classFn;
951
- this.objWithClassesInstancesArr[classType].push(instance);
952
- this.allClassesInstances[className] = instance;
953
- }
954
- }
955
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
956
- finally {
957
- try {
958
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
959
- }
960
- finally { if (e_6) throw e_6.error; }
961
- }
962
- return [2 /*return*/];
963
- });
964
- });
965
- };
966
- //#endregion
967
- //#region methods & getters / reinit controllers db example data
968
- EndpointContext.prototype.reinitControllers = function () {
969
- return tslib_1.__awaiter(this, void 0, void 0, function () {
970
- var controllers, controllers_1, controllers_1_1, ctrl, e_7_1;
971
- var e_7, _a;
972
- return tslib_1.__generator(this, function (_b) {
973
- switch (_b.label) {
974
- case 0:
975
- if (this.remoteHost || Object.keys(this.config.migrations).length > 0) {
976
- return [2 /*return*/];
977
- }
978
- controllers = this.getClassesInstancesArrBy(models_1.Models.ClassType.CONTROLLER);
979
- _b.label = 1;
980
- case 1:
981
- _b.trys.push([1, 6, 7, 8]);
982
- controllers_1 = tslib_1.__values(controllers), controllers_1_1 = controllers_1.next();
983
- _b.label = 2;
984
- case 2:
985
- if (!!controllers_1_1.done) return [3 /*break*/, 5];
986
- ctrl = controllers_1_1.value;
987
- if (!tnp_core_4._.isFunction(ctrl.initExampleDbData)) return [3 /*break*/, 4];
988
- return [4 /*yield*/, tnp_core_4.Helpers.runSyncOrAsync({
989
- functionFn: ctrl.initExampleDbData,
990
- context: ctrl,
991
- })];
992
- case 3:
993
- _b.sent();
994
- _b.label = 4;
995
- case 4:
996
- controllers_1_1 = controllers_1.next();
997
- return [3 /*break*/, 2];
998
- case 5: return [3 /*break*/, 8];
999
- case 6:
1000
- e_7_1 = _b.sent();
1001
- e_7 = { error: e_7_1 };
1002
- return [3 /*break*/, 8];
1003
- case 7:
1004
- try {
1005
- if (controllers_1_1 && !controllers_1_1.done && (_a = controllers_1.return)) _a.call(controllers_1);
1006
- }
1007
- finally { if (e_7) throw e_7.error; }
1008
- return [7 /*endfinally*/];
1009
- case 8: return [2 /*return*/];
1010
- }
1011
- });
1012
- });
1013
- };
1014
- EndpointContext.prototype.initClasses = function () {
1015
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1016
- var _a, _b, classTypeName, _c, _d, classFun, e_8_1, e_9_1, _e, _f, classTypeName, _g, _h, ctrl, e_10_1, e_11_1;
1017
- var e_9, _j, e_8, _k, e_11, _l, e_10, _m;
1018
- return tslib_1.__generator(this, function (_o) {
1019
- switch (_o.label) {
1020
- case 0:
1021
- if (this.remoteHost) {
1022
- return [2 /*return*/];
1023
- }
1024
- _o.label = 1;
1025
- case 1:
1026
- _o.trys.push([1, 12, 13, 14]);
1027
- _a = tslib_1.__values([
1028
- models_1.Models.ClassType.PROVIDER,
1029
- models_1.Models.ClassType.REPOSITORY,
1030
- models_1.Models.ClassType.CONTROLLER,
1031
- models_1.Models.ClassType.ENTITY,
1032
- models_1.Models.ClassType.MIGRATION,
1033
- ]), _b = _a.next();
1034
- _o.label = 2;
1035
- case 2:
1036
- if (!!_b.done) return [3 /*break*/, 11];
1037
- classTypeName = _b.value;
1038
- _o.label = 3;
1039
- case 3:
1040
- _o.trys.push([3, 8, 9, 10]);
1041
- _c = (e_8 = void 0, tslib_1.__values(this.getClassFunByArr(classTypeName))), _d = _c.next();
1042
- _o.label = 4;
1043
- case 4:
1044
- if (!!_d.done) return [3 /*break*/, 7];
1045
- classFun = _d.value;
1046
- if (!tnp_core_4._.isFunction(classFun._)) return [3 /*break*/, 6];
1047
- return [4 /*yield*/, tnp_core_4.Helpers.runSyncOrAsync({
1048
- functionFn: classFun._,
1049
- context: classFun,
1050
- })];
1051
- case 5:
1052
- _o.sent();
1053
- _o.label = 6;
1054
- case 6:
1055
- _d = _c.next();
1056
- return [3 /*break*/, 4];
1057
- case 7: return [3 /*break*/, 10];
1058
- case 8:
1059
- e_8_1 = _o.sent();
1060
- e_8 = { error: e_8_1 };
1061
- return [3 /*break*/, 10];
1062
- case 9:
1063
- try {
1064
- if (_d && !_d.done && (_k = _c.return)) _k.call(_c);
1065
- }
1066
- finally { if (e_8) throw e_8.error; }
1067
- return [7 /*endfinally*/];
1068
- case 10:
1069
- _b = _a.next();
1070
- return [3 /*break*/, 2];
1071
- case 11: return [3 /*break*/, 14];
1072
- case 12:
1073
- e_9_1 = _o.sent();
1074
- e_9 = { error: e_9_1 };
1075
- return [3 /*break*/, 14];
1076
- case 13:
1077
- try {
1078
- if (_b && !_b.done && (_j = _a.return)) _j.call(_a);
1079
- }
1080
- finally { if (e_9) throw e_9.error; }
1081
- return [7 /*endfinally*/];
1082
- case 14:
1083
- _o.trys.push([14, 25, 26, 27]);
1084
- _e = tslib_1.__values([
1085
- models_1.Models.ClassType.PROVIDER,
1086
- models_1.Models.ClassType.REPOSITORY,
1087
- models_1.Models.ClassType.CONTROLLER,
1088
- models_1.Models.ClassType.MIGRATION,
1089
- ]), _f = _e.next();
1090
- _o.label = 15;
1091
- case 15:
1092
- if (!!_f.done) return [3 /*break*/, 24];
1093
- classTypeName = _f.value;
1094
- _o.label = 16;
1095
- case 16:
1096
- _o.trys.push([16, 21, 22, 23]);
1097
- _g = (e_10 = void 0, tslib_1.__values(this.getClassesInstancesArrBy(classTypeName))), _h = _g.next();
1098
- _o.label = 17;
1099
- case 17:
1100
- if (!!_h.done) return [3 /*break*/, 20];
1101
- ctrl = _h.value;
1102
- if (!tnp_core_4._.isFunction(ctrl._)) return [3 /*break*/, 19];
1103
- return [4 /*yield*/, tnp_core_4.Helpers.runSyncOrAsync({
1104
- functionFn: ctrl._,
1105
- context: ctrl,
1106
- })];
1107
- case 18:
1108
- _o.sent();
1109
- _o.label = 19;
1110
- case 19:
1111
- _h = _g.next();
1112
- return [3 /*break*/, 17];
1113
- case 20: return [3 /*break*/, 23];
1114
- case 21:
1115
- e_10_1 = _o.sent();
1116
- e_10 = { error: e_10_1 };
1117
- return [3 /*break*/, 23];
1118
- case 22:
1119
- try {
1120
- if (_h && !_h.done && (_m = _g.return)) _m.call(_g);
1121
- }
1122
- finally { if (e_10) throw e_10.error; }
1123
- return [7 /*endfinally*/];
1124
- case 23:
1125
- _f = _e.next();
1126
- return [3 /*break*/, 15];
1127
- case 24: return [3 /*break*/, 27];
1128
- case 25:
1129
- e_11_1 = _o.sent();
1130
- e_11 = { error: e_11_1 };
1131
- return [3 /*break*/, 27];
1132
- case 26:
1133
- try {
1134
- if (_f && !_f.done && (_l = _e.return)) _l.call(_e);
1135
- }
1136
- finally { if (e_11) throw e_11.error; }
1137
- return [7 /*endfinally*/];
1138
- case 27: return [2 /*return*/];
1139
- }
1140
- });
1141
- });
1142
- };
896
+ }
1143
897
  //#endregion
1144
898
  //#region methods & getters / is active on
1145
- EndpointContext.prototype.isActiveOn = function (classInstance) {
1146
- var contextRef = classInstance[symbols_1.Symbols.ctxInClassOrClassObj];
899
+ isActiveOn(classInstance) {
900
+ let contextRef = classInstance[symbols_1.Symbols.ctxInClassOrClassObj];
1147
901
  return this === contextRef;
1148
- };
1149
- Object.defineProperty(EndpointContext.prototype, "uri", {
1150
- //#endregion
1151
- //#region methods & getters / uri
1152
- get: function () {
1153
- var url = this.host
1154
- ? new url_1.URL(this.host)
1155
- : this.remoteHost
1156
- ? new url_1.URL(this.remoteHost)
1157
- : void 0;
1158
- return url;
1159
- },
1160
- enumerable: false,
1161
- configurable: true
1162
- });
1163
- Object.defineProperty(EndpointContext.prototype, "isHttpServer", {
1164
- //#endregion
1165
- //#region methods & getters / is https server
1166
- get: function () {
1167
- return this.uri.protocol === 'https:';
1168
- },
1169
- enumerable: false,
1170
- configurable: true
1171
- });
1172
- Object.defineProperty(EndpointContext.prototype, "contextName", {
1173
- //#endregion
1174
- //#region methods & getters / public assets
1175
- /**
1176
- * ipc/udp needs this
1177
- */
1178
- get: function () {
1179
- return this.config.contextName;
1180
- },
1181
- enumerable: false,
1182
- configurable: true
1183
- });
1184
- Object.defineProperty(EndpointContext.prototype, "publicAssets", {
1185
- //#endregion
1186
- //#region methods & getters / public assets
1187
- get: function () {
1188
- var _a;
1189
- return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.publicAssets) || [];
1190
- },
1191
- enumerable: false,
1192
- configurable: true
1193
- });
1194
- Object.defineProperty(EndpointContext.prototype, "isProductionMode", {
1195
- //#endregion
1196
- //#region methods & getters / is production mode
1197
- get: function () {
1198
- return this.config.productionMode;
1199
- },
1200
- enumerable: false,
1201
- configurable: true
1202
- });
1203
- Object.defineProperty(EndpointContext.prototype, "remoteHost", {
1204
- //#endregion
1205
- //#region methods & getters / remote host
1206
- get: function () {
1207
- return this.config.remoteHost;
1208
- },
1209
- enumerable: false,
1210
- configurable: true
1211
- });
1212
- Object.defineProperty(EndpointContext.prototype, "host", {
1213
- //#endregion
1214
- //#region methods & getters / host
1215
- get: function () {
1216
- return this.config.host;
1217
- },
1218
- enumerable: false,
1219
- configurable: true
1220
- });
1221
- Object.defineProperty(EndpointContext.prototype, "orgin", {
1222
- //#endregion
1223
- //#region methods & getters / host
1224
- get: function () {
1225
- var _a;
1226
- return (_a = this.uri) === null || _a === void 0 ? void 0 : _a.origin;
1227
- },
1228
- enumerable: false,
1229
- configurable: true
1230
- });
902
+ }
903
+ //#endregion
904
+ //#region methods & getters / uri
905
+ get uri() {
906
+ const url = this.host
907
+ ? new url_1.URL(this.host)
908
+ : this.remoteHost
909
+ ? new url_1.URL(this.remoteHost)
910
+ : void 0;
911
+ return url;
912
+ }
913
+ //#endregion
914
+ //#region methods & getters / is https server
915
+ get isHttpServer() {
916
+ return this.uri.protocol === 'https:';
917
+ }
918
+ //#endregion
919
+ //#region methods & getters / public assets
920
+ /**
921
+ * ipc/udp needs this
922
+ */
923
+ get contextName() {
924
+ return this.config.contextName;
925
+ }
926
+ //#endregion
927
+ //#region methods & getters / public assets
928
+ get publicAssets() {
929
+ return this.config?.publicAssets || [];
930
+ }
931
+ //#endregion
932
+ //#region methods & getters / is production mode
933
+ get isProductionMode() {
934
+ return this.config.productionMode;
935
+ }
936
+ //#endregion
937
+ //#region methods & getters / remote host
938
+ get remoteHost() {
939
+ return this.config.remoteHost;
940
+ }
941
+ //#endregion
942
+ //#region methods & getters / host
943
+ get host() {
944
+ return this.config.host;
945
+ }
946
+ //#endregion
947
+ //#region methods & getters / host
948
+ get orgin() {
949
+ return this.uri?.origin;
950
+ }
1231
951
  //#endregion
1232
952
  //#region methods & getters / init subscribers
1233
- EndpointContext.prototype.initSubscribers = function () {
1234
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1235
- var subscriberClasses, subscriberClasses_1, subscriberClasses_1_1, subscriberClassFn, options;
1236
- var e_12, _a;
1237
- return tslib_1.__generator(this, function (_b) {
1238
- //#region @websqlFunc
1239
- if (this.remoteHost) {
1240
- return [2 /*return*/];
1241
- }
1242
- subscriberClasses = this.getClassFunByArr(models_1.Models.ClassType.SUBSCRIBER);
1243
- try {
1244
- for (subscriberClasses_1 = tslib_1.__values(subscriberClasses), subscriberClasses_1_1 = subscriberClasses_1.next(); !subscriberClasses_1_1.done; subscriberClasses_1_1 = subscriberClasses_1.next()) {
1245
- subscriberClassFn = subscriberClasses_1_1.value;
1246
- options = Reflect.getMetadata(symbols_1.Symbols.metadata.options.subscriber, subscriberClassFn);
1247
- // console.log('subscriber options', options);
1248
- // const nameForSubscriber = ClassHelpers.getName(subscriber);
1249
- (0, taon_typeorm_1.EventSubscriber)()(subscriberClassFn);
1250
- }
1251
- }
1252
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
1253
- finally {
1254
- try {
1255
- if (subscriberClasses_1_1 && !subscriberClasses_1_1.done && (_a = subscriberClasses_1.return)) _a.call(subscriberClasses_1);
1256
- }
1257
- finally { if (e_12) throw e_12.error; }
1258
- }
1259
- return [2 /*return*/];
1260
- });
1261
- });
1262
- };
953
+ async initSubscribers() {
954
+ //#region @websqlFunc
955
+ if (this.remoteHost) {
956
+ return;
957
+ }
958
+ const subscriberClasses = this.getClassFunByArr(models_1.Models.ClassType.SUBSCRIBER);
959
+ for (const subscriberClassFn of subscriberClasses) {
960
+ const options = Reflect.getMetadata(symbols_1.Symbols.metadata.options.subscriber, subscriberClassFn);
961
+ // console.log('subscriber options', options);
962
+ // const nameForSubscriber = ClassHelpers.getName(subscriber);
963
+ (0, taon_typeorm_1.EventSubscriber)()(subscriberClassFn);
964
+ }
965
+ //#endregion
966
+ }
1263
967
  //#endregion
1264
968
  //#region methods & getters / init entities
1265
- EndpointContext.prototype.initEntities = function () {
1266
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1267
- var entities, entities_1, entities_1_1, entity, options, createTable, nameForEntity;
1268
- var e_13, _a;
1269
- return tslib_1.__generator(this, function (_b) {
1270
- //#region @websql
1271
- if (this.remoteHost) {
1272
- return [2 /*return*/];
1273
- }
1274
- entities = this.getClassFunByArr(models_1.Models.ClassType.ENTITY);
1275
- try {
1276
- for (entities_1 = tslib_1.__values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {
1277
- entity = entities_1_1.value;
1278
- options = Reflect.getMetadata(symbols_1.Symbols.metadata.options.entity, entity);
1279
- createTable = tnp_core_4._.isUndefined(options.createTable)
1280
- ? true
1281
- : options.createTable;
1282
- nameForEntity = class_helpers_1.ClassHelpers.getName(entity);
1283
- if (tnp_core_4._.isUndefined(options.createTable) ? true : options.createTable) {
1284
- this.logDb &&
1285
- console.info("[taon][typeorm] create table for entity \"".concat(nameForEntity, "\" ? '").concat(createTable, "'"));
1286
- // console.log('TypeormEntity', { TypeormEntity });
1287
- (0, taon_typeorm_2.Entity)(nameForEntity)(entity);
1288
- }
1289
- else {
1290
- this.logDb &&
1291
- console.info("[taon][typeorm] create table for entity \"".concat(nameForEntity, "\" ? '").concat(createTable, "'"));
1292
- }
1293
- }
1294
- }
1295
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1296
- finally {
1297
- try {
1298
- if (entities_1_1 && !entities_1_1.done && (_a = entities_1.return)) _a.call(entities_1);
1299
- }
1300
- finally { if (e_13) throw e_13.error; }
1301
- }
1302
- return [2 /*return*/];
1303
- });
1304
- });
1305
- };
969
+ async initEntities() {
970
+ //#region @websql
971
+ if (this.remoteHost) {
972
+ return;
973
+ }
974
+ const entities = this.getClassFunByArr(models_1.Models.ClassType.ENTITY);
975
+ for (const entity of entities) {
976
+ const options = Reflect.getMetadata(symbols_1.Symbols.metadata.options.entity, entity);
977
+ const createTable = tnp_core_4._.isUndefined(options.createTable)
978
+ ? true
979
+ : options.createTable;
980
+ const nameForEntity = class_helpers_1.ClassHelpers.getName(entity);
981
+ if (tnp_core_4._.isUndefined(options.createTable) ? true : options.createTable) {
982
+ this.logDb &&
983
+ console.info(`[taon][typeorm] create table for entity "${nameForEntity}" ? '${createTable}'`);
984
+ // console.log('TypeormEntity', { TypeormEntity });
985
+ (0, taon_typeorm_2.Entity)(nameForEntity)(entity);
986
+ }
987
+ else {
988
+ this.logDb &&
989
+ console.info(`[taon][typeorm] create table for entity "${nameForEntity}" ? '${createTable}'`);
990
+ }
991
+ }
992
+ //#endregion
993
+ }
1306
994
  //#endregion
1307
995
  //#region methods & getters / init connection
1308
- EndpointContext.prototype.initDatabaseConnection = function () {
1309
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1310
- var entities, subscribers, dataSourceDbConfig, connection, error_1;
1311
- var _a, _b;
1312
- return tslib_1.__generator(this, function (_c) {
1313
- switch (_c.label) {
1314
- case 0:
1315
- //#region @websqlFunc
1316
- if (this.remoteHost) {
1317
- return [2 /*return*/];
1318
- }
1319
- entities = this.getClassFunByArr(models_1.Models.ClassType.ENTITY).map(function (entityFn) {
1320
- return class_helpers_1.ClassHelpers.getOrginalClass(entityFn);
1321
- });
1322
- subscribers = this.getClassFunByArr(models_1.Models.ClassType.SUBSCRIBER);
1323
- dataSourceDbConfig = tnp_core_4._.isObject(this.databaseConfig)
1324
- ? {
1325
- type: this.databaseConfig.type,
1326
- port: this.databaseConfig.databasePort,
1327
- host: this.databaseConfig.databaseHost,
1328
- database: this.databaseConfig.database,
1329
- username: this.databaseConfig.databaseUsername,
1330
- password: this.databaseConfig.databasePassword,
1331
- useLocalForage: this.databaseConfig.useLocalForage,
1332
- // I am not using typeorm migration system
1333
- entities: entities,
1334
- subscribers: subscribers,
1335
- synchronize: this.isRunOrRevertOnlyMigrationAppStart
1336
- ? false
1337
- : this.databaseConfig.synchronize,
1338
- autoSave: !tnp_core_4._.isNil(this.databaseConfig.autoSave)
1339
- ? this.databaseConfig.autoSave
1340
- : !tnp_core_2.UtilsOs.isRunningInDocker(), // in docker I am using mysql or posgress
1341
- dropSchema: this.isRunOrRevertOnlyMigrationAppStart
1342
- ? false
1343
- : this.databaseConfig.dropSchema,
1344
- logging: !!this.databaseConfig.logging,
1345
- location: this.databaseConfig.location,
1346
- }
1347
- : {};
1348
- // debugger;
1349
- this.logFramework &&
1350
- console.log("[Context: \"".concat(this.contextName, "\"] dataSourceDbConfig"), dataSourceDbConfig);
1351
- if (!(this.modeAllowsDatabaseCreation && this.databaseConfig)) return [3 /*break*/, 5];
1352
- this.logDb &&
1353
- this.logFramework &&
1354
- tnp_core_4.Helpers.info('[taon][database] prepare typeorm connection...');
1355
- _c.label = 1;
1356
- case 1:
1357
- _c.trys.push([1, 3, , 4]);
1358
- connection = new taon_typeorm_3.DataSource(dataSourceDbConfig);
1359
- this.connection = connection;
1360
- return [4 /*yield*/, this.connection.initialize()];
1361
- case 2:
1362
- _c.sent();
1363
- return [3 /*break*/, 4];
1364
- case 3:
1365
- error_1 = _c.sent();
1366
- console.error((error_1 === null || error_1 === void 0 ? void 0 : error_1.message) || error_1);
1367
- return [3 /*break*/, 4];
1368
- case 4:
1369
- if (!((_a = this.connection) === null || _a === void 0 ? void 0 : _a.isInitialized)) {
1370
- console.log('WRONG CONFIG', dataSourceDbConfig);
1371
- throw new Error("Something wrong with connection init in ".concat(this.mode));
1372
- //#region @backend
1373
- process.exit(1);
1374
- //#endregion
1375
- }
1376
- if (this.logDb || this.logFramework) {
1377
- console.info("\n\n CONTECTION OK for ".concat(this.contextName, " - ").concat(this.mode, "\n\n [taon][typeorm] db prepration done.. db initialize=").concat((_b = this.connection) === null || _b === void 0 ? void 0 : _b.isInitialized, "\n\n\n "), dataSourceDbConfig, { 'this.connection': !!this.connection });
1378
- console.log("Database file location: ".concat(this.connection.options.database));
1379
- }
1380
- return [3 /*break*/, 6];
1381
- case 5:
1382
- tnp_core_4.Helpers.info("[taon][typeorm] Not initing db for mode ".concat(this.mode));
1383
- _c.label = 6;
1384
- case 6: return [2 /*return*/];
1385
- }
1386
- });
996
+ async initDatabaseConnection() {
997
+ //#region @websqlFunc
998
+ if (this.remoteHost) {
999
+ return;
1000
+ }
1001
+ const entities = this.getClassFunByArr(models_1.Models.ClassType.ENTITY).map(entityFn => {
1002
+ return class_helpers_1.ClassHelpers.getOrginalClass(entityFn);
1387
1003
  });
1388
- };
1004
+ const subscribers = this.getClassFunByArr(models_1.Models.ClassType.SUBSCRIBER);
1005
+ const dataSourceDbConfig = tnp_core_4._.isObject(this.databaseConfig)
1006
+ ? {
1007
+ type: this.databaseConfig.type,
1008
+ port: this.databaseConfig.databasePort,
1009
+ host: this.databaseConfig.databaseHost,
1010
+ database: this.databaseConfig.database,
1011
+ username: this.databaseConfig.databaseUsername,
1012
+ password: this.databaseConfig.databasePassword,
1013
+ useLocalForage: this.databaseConfig.useLocalForage,
1014
+ // I am not using typeorm migration system
1015
+ entities,
1016
+ subscribers,
1017
+ synchronize: this.isRunOrRevertOnlyMigrationAppStart
1018
+ ? false
1019
+ : this.databaseConfig.synchronize,
1020
+ autoSave: !tnp_core_4._.isNil(this.databaseConfig.autoSave)
1021
+ ? this.databaseConfig.autoSave
1022
+ : !tnp_core_2.UtilsOs.isRunningInDocker(), // in docker I am using mysql or posgress
1023
+ dropSchema: this.isRunOrRevertOnlyMigrationAppStart
1024
+ ? false
1025
+ : this.databaseConfig.dropSchema,
1026
+ logging: !!this.databaseConfig.logging,
1027
+ location: this.databaseConfig.location,
1028
+ }
1029
+ : {};
1030
+ // debugger;
1031
+ this.logFramework &&
1032
+ console.log(`[Context: "${this.contextName}"] dataSourceDbConfig`, dataSourceDbConfig);
1033
+ if (this.modeAllowsDatabaseCreation && this.databaseConfig) {
1034
+ this.logDb &&
1035
+ this.logFramework &&
1036
+ tnp_core_4.Helpers.info('[taon][database] prepare typeorm connection...');
1037
+ try {
1038
+ const connection = new taon_typeorm_3.DataSource(dataSourceDbConfig);
1039
+ this.connection = connection;
1040
+ await this.connection.initialize();
1041
+ }
1042
+ catch (error) {
1043
+ console.error(error?.message || error);
1044
+ }
1045
+ if (!this.connection?.isInitialized) {
1046
+ console.log('WRONG CONFIG', dataSourceDbConfig);
1047
+ throw new Error(`Something wrong with connection init in ${this.mode}`);
1048
+ //#region @backend
1049
+ process.exit(1);
1050
+ //#endregion
1051
+ }
1052
+ if (this.logDb || this.logFramework) {
1053
+ console.info(`
1054
+
1055
+ CONTECTION OK for ${this.contextName} - ${this.mode}
1056
+
1057
+ [taon][typeorm] db prepration done.. db initialize=${this.connection?.isInitialized}
1058
+
1059
+
1060
+ `, dataSourceDbConfig, { 'this.connection': !!this.connection });
1061
+ console.log(`Database file location: ${this.connection.options.database}`);
1062
+ }
1063
+ // const entityMetadata = getMetadataArgsStorage();
1064
+ // console.log(
1065
+ // `
1066
+ // entityMetadata after connection init for ${this.contextName} - ${this.mode}
1067
+ // `,
1068
+ // entityMetadata,
1069
+ // );
1070
+ // debugger;
1071
+ }
1072
+ else {
1073
+ tnp_core_4.Helpers.info(`[taon][typeorm] Not initing db for mode ${this.mode}`);
1074
+ }
1075
+ //#endregion
1076
+ }
1389
1077
  //#endregion
1390
1078
  //#region methods & getters / initialize metadata
1391
- EndpointContext.prototype.initControllers = function () {
1392
- var e_14, _a;
1393
- var _this = this;
1079
+ initControllers() {
1394
1080
  if (this.isRunOrRevertOnlyMigrationAppStart) {
1395
1081
  return;
1396
1082
  }
1397
- var allControllers = this.getClassFunByArr(models_1.Models.ClassType.CONTROLLER);
1398
- var _loop_1 = function (controllerClassFn) {
1083
+ const allControllers = this.getClassFunByArr(models_1.Models.ClassType.CONTROLLER);
1084
+ // console.log('allControllers', allControllers)11
1085
+ for (const controllerClassFn of allControllers) {
1399
1086
  controllerClassFn[symbols_1.Symbols.classMethodsNames] =
1400
1087
  class_helpers_1.ClassHelpers.getMethodsNames(controllerClassFn);
1401
- var configs = class_helpers_1.ClassHelpers.getControllerConfigs(controllerClassFn);
1088
+ const configs = class_helpers_1.ClassHelpers.getControllerConfigs(controllerClassFn);
1402
1089
  // console.log(`Class config for ${ClassHelpers.getName(controllerClassFn)}`, configs)
1403
- var classConfig = configs[0];
1404
- var parentscalculatedPath = tnp_core_4._.slice(configs, 1)
1090
+ const classConfig = configs[0];
1091
+ const parentscalculatedPath = tnp_core_4._.slice(configs, 1)
1405
1092
  .reverse()
1406
- .map(function (bc) {
1093
+ .map(bc => {
1407
1094
  if (taon_helpers_1.TaonHelpers.isGoodPath(bc.path)) {
1408
1095
  return bc.path;
1409
1096
  }
@@ -1415,20 +1102,20 @@ var EndpointContext = /** @class */ (function () {
1415
1102
  }
1416
1103
  else {
1417
1104
  classConfig.calculatedPath =
1418
- "".concat(parentscalculatedPath, "/").concat(class_helpers_1.ClassHelpers.getName(controllerClassFn))
1105
+ `${parentscalculatedPath}/${class_helpers_1.ClassHelpers.getName(controllerClassFn)}`
1419
1106
  .replace(/\/\//g, '/')
1420
1107
  .split('/')
1421
- .reduce(function (acc, bc) {
1422
- return tnp_core_4._.last(acc) === bc ? acc : tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(acc), false), [bc], false);
1108
+ .reduce((acc, bc) => {
1109
+ return tnp_core_4._.last(acc) === bc ? acc : [...acc, bc];
1423
1110
  }, [])
1424
1111
  .join('/');
1425
1112
  }
1426
- tnp_core_4._.slice(configs, 1).forEach(function (bc) {
1427
- var alreadyIs = classConfig.methods;
1428
- var toMerge = tnp_core_4._.cloneDeep(bc.methods);
1429
- for (var key in toMerge) {
1113
+ tnp_core_4._.slice(configs, 1).forEach(bc => {
1114
+ const alreadyIs = classConfig.methods;
1115
+ const toMerge = tnp_core_4._.cloneDeep(bc.methods);
1116
+ for (const key in toMerge) {
1430
1117
  if (toMerge.hasOwnProperty(key) && !alreadyIs[key]) {
1431
- var element = toMerge[key];
1118
+ const element = toMerge[key];
1432
1119
  alreadyIs[key] = element;
1433
1120
  }
1434
1121
  }
@@ -1436,31 +1123,30 @@ var EndpointContext = /** @class */ (function () {
1436
1123
  //#region @backend
1437
1124
  if (!tnp_core_4.Helpers.isRunningIn.cliMode()) {
1438
1125
  //#endregion
1439
- this_1.logHttp &&
1440
- console.groupCollapsed("[taon][express-server] routes [".concat(classConfig.className, "]"));
1126
+ this.logHttp &&
1127
+ console.groupCollapsed(`[taon][express-server] routes [${classConfig.className}]`);
1441
1128
  //#region @backend
1442
1129
  }
1443
1130
  //#endregion
1444
1131
  // console.log('methods', classConfig.methods);
1445
- Object.keys(classConfig.methods).forEach(function (methodName) {
1446
- var _a;
1447
- var methodConfig = classConfig.methods[methodName];
1132
+ Object.keys(classConfig.methods).forEach(methodName => {
1133
+ const methodConfig = classConfig.methods[methodName];
1448
1134
  // debugger
1449
- var type = methodConfig.type;
1450
- var expressPath = methodConfig.global
1451
- ? "/".concat((_a = methodConfig.path) === null || _a === void 0 ? void 0 : _a.replace(/\//, ''))
1135
+ const type = methodConfig.type;
1136
+ const expressPath = methodConfig.global
1137
+ ? `/${methodConfig.path?.replace(/\//, '')}`
1452
1138
  : taon_helpers_1.TaonHelpers.getExpressPath(classConfig, methodConfig);
1453
1139
  // console.log({ expressPath })
1454
1140
  if (tnp_core_4.Helpers.isNode || tnp_core_4.Helpers.isWebSQL) {
1455
1141
  //#region @websql
1456
- var _b = _this.initServer(type, methodConfig, classConfig, expressPath, controllerClassFn), routePath = _b.routePath, method = _b.method;
1457
- _this.activeRoutes.push({
1458
- routePath: routePath,
1459
- method: method,
1142
+ const { routePath, method } = this.initServer(type, methodConfig, classConfig, expressPath, controllerClassFn);
1143
+ this.activeRoutes.push({
1144
+ routePath,
1145
+ method,
1460
1146
  });
1461
1147
  //#endregion
1462
1148
  }
1463
- var shouldInitClient = tnp_core_4.Helpers.isBrowser || _this.remoteHost || tnp_core_4.Helpers.isWebSQL;
1149
+ const shouldInitClient = tnp_core_4.Helpers.isBrowser || this.remoteHost || tnp_core_4.Helpers.isWebSQL;
1464
1150
  // console.log('shouldInitClient', shouldInitClient);
1465
1151
  if (shouldInitClient) {
1466
1152
  // console.log(
@@ -1470,93 +1156,76 @@ var EndpointContext = /** @class */ (function () {
1470
1156
  // methodConfig,
1471
1157
  // expressPath,
1472
1158
  // );
1473
- _this.initClient(controllerClassFn, type, methodConfig, expressPath);
1159
+ this.initClient(controllerClassFn, type, methodConfig, expressPath);
1474
1160
  }
1475
1161
  });
1476
1162
  //#region @backend
1477
1163
  if (!tnp_core_4.Helpers.isRunningIn.cliMode()) {
1478
1164
  //#endregion
1479
- this_1.logHttp && console.groupEnd();
1165
+ this.logHttp && console.groupEnd();
1480
1166
  //#region @backend
1481
1167
  }
1482
- };
1483
- var this_1 = this;
1484
- try {
1485
- // console.log('allControllers', allControllers)11
1486
- for (var allControllers_1 = tslib_1.__values(allControllers), allControllers_1_1 = allControllers_1.next(); !allControllers_1_1.done; allControllers_1_1 = allControllers_1.next()) {
1487
- var controllerClassFn = allControllers_1_1.value;
1488
- _loop_1(controllerClassFn);
1489
- }
1490
- }
1491
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
1492
- finally {
1493
- try {
1494
- if (allControllers_1_1 && !allControllers_1_1.done && (_a = allControllers_1.return)) _a.call(allControllers_1);
1495
- }
1496
- finally { if (e_14) throw e_14.error; }
1168
+ //#endregion
1497
1169
  }
1498
- };
1170
+ }
1499
1171
  //#endregion
1500
1172
  //#region methods & getters / write active routes
1501
- EndpointContext.prototype.writeActiveRoutes = function () {
1502
- var _this = this;
1173
+ writeActiveRoutes() {
1503
1174
  if (this.remoteHost ||
1504
1175
  this.isRunOrRevertOnlyMigrationAppStart ||
1505
1176
  this.skipWritingServerRoutes) {
1506
1177
  return;
1507
1178
  }
1508
- var contexts = [this];
1179
+ const contexts = [this];
1509
1180
  //#region @websql
1510
- var troutes = tnp_core_2.Utils.uniqArray(this.activeRoutes.map(function (f) {
1511
- return "".concat(f.method, " ").concat(f.routePath);
1512
- })).map(function (f) {
1513
- var _a = tslib_1.__read(f.split(' '), 2), method = _a[0], routePath = _a[1];
1514
- return ("\n### ".concat(tnp_core_4._.startCase(tnp_core_4._.last(routePath.split('/'))), "\n") +
1181
+ const troutes = tnp_core_2.Utils.uniqArray(this.activeRoutes.map(f => {
1182
+ return `${f.method} ${f.routePath}`;
1183
+ })).map(f => {
1184
+ const [method, routePath] = f.split(' ');
1185
+ return (`\n### ${tnp_core_4._.startCase(tnp_core_4._.last(routePath.split('/')))}\n` +
1515
1186
  taon_helpers_1.TaonHelpers.fillUpTo(method.toUpperCase() + ' ', 10) +
1516
- _this.uri.href.replace(/\/$/, '') +
1187
+ this.uri.href.replace(/\/$/, '') +
1517
1188
  routePath);
1518
1189
  // return `${TaonHelpers.string(method.toUpperCase() + ':')
1519
1190
  // .fillUpTo(10)}${context.uri.href.replace(/\/$/, '')}${routePath}`
1520
1191
  });
1521
- var routes = tslib_1.__spreadArray(tslib_1.__spreadArray([], ['', "# ROUTES FOR HOST ".concat(this.uri.href, " ")], false), tslib_1.__read(troutes), false).join('\n');
1522
- var fileName = (0, tnp_core_3.crossPlatformPath)([
1192
+ const routes = [
1193
+ ...['', `# ROUTES FOR HOST ${this.uri.href} `],
1194
+ ...troutes,
1195
+ ].join('\n');
1196
+ const fileName = (0, tnp_core_3.crossPlatformPath)([
1523
1197
  //#region @backend
1524
1198
  process.cwd(),
1525
1199
  //#endregion
1526
- "routes-".concat(this.config.contextName, ".rest"),
1200
+ `routes-${this.config.contextName}.rest`,
1527
1201
  ]);
1528
- this.logFramework && console.log("[taon] routes file: ".concat(fileName, " "));
1202
+ this.logFramework && console.log(`[taon] routes file: ${fileName} `);
1529
1203
  // Helpers.log(JSON.stringify(routes, null, 4))
1530
1204
  //#region @backend
1531
1205
  tnp_core_4.Helpers.writeFile(fileName, routes);
1532
1206
  //#endregion
1533
1207
  //#endregion
1534
- };
1535
- Object.defineProperty(EndpointContext.prototype, "middlewares", {
1208
+ }
1209
+ //#endregion
1210
+ //#region methods & getters / middlewares
1211
+ get middlewares() {
1212
+ //#region @backendFunc
1213
+ return this.config.middlewares || [];
1536
1214
  //#endregion
1537
- //#region methods & getters / middlewares
1538
- get: function () {
1539
- //#region @backendFunc
1540
- return this.config.middlewares || [];
1541
- //#endregion
1542
- },
1543
- enumerable: false,
1544
- configurable: true
1545
- });
1215
+ }
1546
1216
  //#endregion
1547
1217
  //#region methods & getters / init middlewares
1548
- EndpointContext.prototype.initMiddlewares = function () {
1549
- var _this = this;
1218
+ initMiddlewares() {
1550
1219
  //#region @backend
1551
- var app = this.expressApp;
1220
+ const app = this.expressApp;
1552
1221
  if (this.middlewares) {
1553
- this.middlewares.forEach(function (m) {
1554
- var _a = tslib_1.__read(m, 2), fun = _a[0], args = _a[1];
1222
+ this.middlewares.forEach(m => {
1223
+ const [fun, args] = m;
1555
1224
  app.use(fun.apply(null, args));
1556
1225
  });
1557
1226
  }
1558
- this.expressApp.get('/helloworld', function (req, res) {
1559
- res.send("Hello, world from context ".concat(_this.contextName));
1227
+ this.expressApp.get('/helloworld', (req, res) => {
1228
+ res.send(`Hello, world from context ${this.contextName}`);
1560
1229
  });
1561
1230
  app.use(fileUpload());
1562
1231
  app.use(bodyParser.urlencoded({ extended: true }));
@@ -1566,13 +1235,13 @@ var EndpointContext = /** @class */ (function () {
1566
1235
  if (this.session) {
1567
1236
  tnp_core_4.Helpers.info('[taon][express-server] session enabled for this context ' +
1568
1237
  this.contextName);
1569
- var cookieMaxAge = this.session.cookieMaxAge;
1570
- var frontendHost = this.config.frontendHost;
1571
- var sessionObj = {
1572
- frontendHost: frontendHost,
1238
+ const { cookieMaxAge } = this.session;
1239
+ const frontendHost = this.config.frontendHost;
1240
+ const sessionObj = {
1241
+ frontendHost,
1573
1242
  secret: 'mysecretsessioncookithing',
1574
1243
  saveUninitialized: true,
1575
- cookieMaxAge: cookieMaxAge,
1244
+ cookieMaxAge,
1576
1245
  secure: frontendHost.startsWith('https://'),
1577
1246
  resave: false,
1578
1247
  };
@@ -1581,12 +1250,16 @@ var EndpointContext = /** @class */ (function () {
1581
1250
  origin: frontendHost,
1582
1251
  }));
1583
1252
  app.use(expressSession(sessionObj));
1584
- console.log("\n\n CORS ENABLED FOR SESSION\n\n ");
1253
+ console.log(`
1254
+
1255
+ CORS ENABLED FOR SESSION
1256
+
1257
+ `);
1585
1258
  }
1586
1259
  else {
1587
1260
  // if(this.config?.serverLogs) {
1588
1261
  this.logHttp &&
1589
- tnp_core_4.Helpers.info("[taon][express-server] session not enabled for this context '".concat(this.contextName, "'"));
1262
+ tnp_core_4.Helpers.info(`[taon][express-server] session not enabled for this context '${this.contextName}'`);
1590
1263
  // }
1591
1264
  app.use(cors({
1592
1265
  // origin: "http://localhost:5555",
@@ -1595,10 +1268,14 @@ var EndpointContext = /** @class */ (function () {
1595
1268
  // credentials: true
1596
1269
  }));
1597
1270
  this.logHttp &&
1598
- console.log("\n\n CORS ENABLED WITHOUT SESSION\n\n ");
1271
+ console.log(`
1272
+
1273
+ CORS ENABLED WITHOUT SESSION
1274
+
1275
+ `);
1599
1276
  }
1600
- (function () {
1601
- app.use(function (req, res, next) {
1277
+ (() => {
1278
+ app.use((req, res, next) => {
1602
1279
  //#region good for cors session obj
1603
1280
  // if (this.context.session) {
1604
1281
  // res.header('Access-Control-Allow-Origin', this.context.session.frontendHost);
@@ -1625,68 +1302,51 @@ var EndpointContext = /** @class */ (function () {
1625
1302
  });
1626
1303
  })();
1627
1304
  //#endregion
1628
- };
1305
+ }
1629
1306
  //#endregion
1630
1307
  //#region methods & getters / init methods node
1631
- EndpointContext.prototype.initServer = function (
1308
+ initServer(
1632
1309
  //#region parameters
1633
1310
  type, methodConfig, classConfig, expressPath, target) {
1634
- var _this = this;
1635
1311
  //#region resolve variables
1636
1312
  //#region @websql
1637
- var requestHandler = methodConfig.requestHandler &&
1313
+ const requestHandler = methodConfig.requestHandler &&
1638
1314
  typeof methodConfig.requestHandler === 'function'
1639
1315
  ? methodConfig.requestHandler
1640
- : function (req, res, next) {
1316
+ : (req, res, next) => {
1641
1317
  next();
1642
1318
  };
1643
1319
  //#endregion
1644
- var url = this.uri;
1320
+ const url = this.uri;
1645
1321
  //#region get result
1646
- var getResult = function (resolvedParams, req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
1647
- var response, result;
1648
- return tslib_1.__generator(this, function (_a) {
1649
- switch (_a.label) {
1650
- case 0:
1651
- response = methodConfig.descriptor.value.apply(
1652
- /**
1653
- * Context for method @GET,@PUT etc.
1654
- */
1655
- this.getInstanceBy(target),
1656
- /**
1657
- * Params for metjod @GET, @PUT etc.
1658
- */
1659
- resolvedParams);
1660
- return [4 /*yield*/, (0, get_response_value_1.getResponseValue)(response, { req: req, res: res })];
1661
- case 1:
1662
- result = _a.sent();
1663
- return [2 /*return*/, result];
1664
- }
1665
- });
1666
- }); };
1322
+ const getResult = async (resolvedParams, req, res) => {
1323
+ const response = methodConfig.descriptor.value.apply(
1324
+ /**
1325
+ * Context for method @GET,@PUT etc.
1326
+ */
1327
+ this.getInstanceBy(target),
1328
+ /**
1329
+ * Params for metjod @GET, @PUT etc.
1330
+ */
1331
+ resolvedParams);
1332
+ let result = await (0, get_response_value_1.getResponseValue)(response, { req, res });
1333
+ return result;
1334
+ };
1667
1335
  //#endregion
1668
1336
  url.pathname = url.pathname.replace(/\/$/, '');
1669
1337
  expressPath = url.pathname.startsWith('/')
1670
- ? "".concat(url.pathname).concat(expressPath)
1338
+ ? `${url.pathname}${expressPath}`
1671
1339
  : expressPath;
1672
1340
  expressPath = expressPath.replace(/\/\//g, '/');
1673
1341
  // console.log(`BACKEND: expressPath: ${ expressPath } `)
1674
1342
  //#endregion
1675
1343
  if (tnp_core_4.Helpers.isElectron) {
1676
1344
  //#region @backend
1677
- var ipcKeyName = taon_helpers_1.TaonHelpers.ipcKeyNameRequest(target, methodConfig, expressPath);
1678
- tnp_core_4.Helpers.ipcMain.on(ipcKeyName, function (event, paramsFromBrowser) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
1679
- var responseJsonData;
1680
- return tslib_1.__generator(this, function (_a) {
1681
- switch (_a.label) {
1682
- case 0: return [4 /*yield*/, getResult(paramsFromBrowser, void 0, void 0)];
1683
- case 1:
1684
- responseJsonData = _a.sent();
1685
- event.sender.send(taon_helpers_1.TaonHelpers.ipcKeyNameResponse(target, methodConfig, expressPath), responseJsonData);
1686
- return [2 /*return*/];
1687
- }
1688
- });
1689
- }); });
1345
+ const ipcKeyName = taon_helpers_1.TaonHelpers.ipcKeyNameRequest(target, methodConfig, expressPath);
1346
+ tnp_core_4.Helpers.ipcMain.on(ipcKeyName, async (event, paramsFromBrowser) => {
1347
+ const responseJsonData = await getResult(paramsFromBrowser, void 0, void 0);
1348
+ event.sender.send(taon_helpers_1.TaonHelpers.ipcKeyNameResponse(target, methodConfig, expressPath), responseJsonData);
1349
+ });
1690
1350
  return {
1691
1351
  routePath: expressPath,
1692
1352
  method: methodConfig.type,
@@ -1698,208 +1358,205 @@ var EndpointContext = /** @class */ (function () {
1698
1358
  //#region @websql
1699
1359
  if (tnp_core_4.Helpers.isWebSQL) {
1700
1360
  if (!this.expressApp[type.toLowerCase()]) {
1701
- this.expressApp[type.toLowerCase()] = function () { };
1361
+ this.expressApp[type.toLowerCase()] = () => { };
1702
1362
  }
1703
1363
  }
1704
1364
  //#endregion
1705
1365
  //#endregion
1706
1366
  //#region @backend
1707
- this.logHttp && console.log("[".concat(type.toUpperCase(), "] ").concat(expressPath, " "));
1708
- this.expressApp[type.toLowerCase()](expressPath, requestHandler, function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
1709
- var args, tBody, tParams, tQuery, entity, entity, resolvedParams, result, blob, file, _a, _b, img_base64, m, _c, _1, content_type, file_base64, file, error_2, err, err;
1710
- return tslib_1.__generator(this, function (_d) {
1711
- switch (_d.label) {
1712
- case 0:
1713
- args = [];
1714
- tBody = req.body;
1715
- tParams = req.params;
1716
- tQuery = req.query;
1717
- if (req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY]) {
1718
- try {
1719
- tBody = JSON.parse(JSON.stringify(tBody), JSON.parse(req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY]));
1720
- }
1721
- catch (e) { }
1722
- }
1723
- if (req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM]) {
1724
- try {
1725
- tQuery = JSON.parse(JSON.stringify(tQuery), JSON.parse(req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM]));
1726
- }
1727
- catch (e) { }
1728
- }
1729
- // make class instance from body
1730
- // console.log('req.headers', req.headers)
1731
- if (req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS]) {
1732
- try {
1733
- entity = JSON.parse(req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS]);
1734
- tBody = ng2_rest_1.Mapping.encode(tBody, entity);
1735
- }
1736
- catch (e) { }
1737
- }
1738
- else {
1739
- Object.keys(tBody).forEach(function (paramName) {
1740
- try {
1741
- var entityForParam = JSON.parse(req.headers["".concat(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS).concat(paramName, " ")]);
1742
- tBody[paramName] = ng2_rest_1.Mapping.encode(tBody[paramName], entityForParam);
1743
- }
1744
- catch (e) { }
1745
- });
1746
- }
1747
- // make class instance from query params
1748
- // console.log('req.headers', tQuery)
1749
- if (req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS]) {
1367
+ this.logHttp && console.log(`[${type.toUpperCase()}] ${expressPath} `);
1368
+ this.expressApp[type.toLowerCase()](expressPath, requestHandler, async (req, res) => {
1369
+ // console.log(`[${type.toUpperCase()}] ${expressPath} `);
1370
+ //#region process params
1371
+ const args = [];
1372
+ let tBody = req.body;
1373
+ let tParams = req.params;
1374
+ let tQuery = req.query;
1375
+ if (req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY]) {
1376
+ try {
1377
+ tBody = JSON.parse(JSON.stringify(tBody), JSON.parse(req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY]));
1378
+ }
1379
+ catch (e) { }
1380
+ }
1381
+ if (req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM]) {
1382
+ try {
1383
+ tQuery = JSON.parse(JSON.stringify(tQuery), JSON.parse(req.headers[symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM]));
1384
+ }
1385
+ catch (e) { }
1386
+ }
1387
+ // make class instance from body
1388
+ // console.log('req.headers', req.headers)
1389
+ if (req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS]) {
1390
+ try {
1391
+ const entity = JSON.parse(req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS]);
1392
+ tBody = ng2_rest_1.Mapping.encode(tBody, entity);
1393
+ }
1394
+ catch (e) { }
1395
+ }
1396
+ else {
1397
+ Object.keys(tBody).forEach(paramName => {
1398
+ try {
1399
+ const entityForParam = JSON.parse(req.headers[`${symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS}${paramName} `]);
1400
+ tBody[paramName] = ng2_rest_1.Mapping.encode(tBody[paramName], entityForParam);
1401
+ }
1402
+ catch (e) { }
1403
+ });
1404
+ }
1405
+ // make class instance from query params
1406
+ // console.log('req.headers', tQuery)
1407
+ if (req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS]) {
1408
+ try {
1409
+ const entity = JSON.parse(req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS]);
1410
+ tQuery = taon_helpers_1.TaonHelpers.parseJSONwithStringJSONs(ng2_rest_1.Mapping.encode(tQuery, entity));
1411
+ }
1412
+ catch (e) { }
1413
+ }
1414
+ else {
1415
+ Object.keys(tQuery).forEach(queryParamName => {
1416
+ try {
1417
+ const entityForParam = JSON.parse(req.headers[`${symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS}${queryParamName} `]);
1418
+ let beforeTransofrm = tQuery[queryParamName];
1419
+ if (tnp_core_4._.isString(beforeTransofrm)) {
1750
1420
  try {
1751
- entity = JSON.parse(req.headers[symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS]);
1752
- tQuery = taon_helpers_1.TaonHelpers.parseJSONwithStringJSONs(ng2_rest_1.Mapping.encode(tQuery, entity));
1421
+ const paresed = taon_helpers_1.TaonHelpers.tryTransformParam(beforeTransofrm);
1422
+ beforeTransofrm = paresed;
1753
1423
  }
1754
1424
  catch (e) { }
1755
1425
  }
1756
- else {
1757
- Object.keys(tQuery).forEach(function (queryParamName) {
1758
- try {
1759
- var entityForParam = JSON.parse(req.headers["".concat(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS).concat(queryParamName, " ")]);
1760
- var beforeTransofrm = tQuery[queryParamName];
1761
- if (tnp_core_4._.isString(beforeTransofrm)) {
1762
- try {
1763
- var paresed = taon_helpers_1.TaonHelpers.tryTransformParam(beforeTransofrm);
1764
- beforeTransofrm = paresed;
1765
- }
1766
- catch (e) { }
1767
- }
1768
- var afterEncoding = ng2_rest_1.Mapping.encode(beforeTransofrm, entityForParam);
1769
- tQuery[queryParamName] =
1770
- taon_helpers_1.TaonHelpers.parseJSONwithStringJSONs(afterEncoding);
1771
- }
1772
- catch (e) { }
1773
- });
1774
- }
1775
- Object.keys(methodConfig.parameters).forEach(function (paramName) {
1776
- var p = methodConfig.parameters[paramName];
1777
- if (p.paramType === 'Path' && tParams) {
1778
- args.push(tParams[p.paramName]);
1779
- }
1780
- if (p.paramType === 'Query' && tQuery) {
1781
- if (p.paramName) {
1782
- args.push(tQuery[p.paramName]);
1783
- }
1784
- else {
1785
- args.push(tQuery);
1786
- }
1787
- }
1788
- if (p.paramType === 'Header' && req.headers) {
1789
- args.push(req.headers[p.paramName.toLowerCase()]);
1790
- }
1791
- if (p.paramType === 'Cookie' && req.cookies) {
1792
- args.push(req.cookies[p.paramName]);
1793
- }
1794
- if (p.paramType === 'Body' && tBody) {
1795
- if (p.paramName && typeof tBody === 'object') {
1796
- args.push(tBody[p.paramName]);
1797
- }
1798
- else {
1799
- args.push(tBody);
1800
- }
1801
- }
1802
- });
1803
- resolvedParams = args
1804
- .reverse()
1805
- .map(function (v) { return taon_helpers_1.TaonHelpers.tryTransformParam(v); });
1806
- _d.label = 1;
1807
- case 1:
1808
- _d.trys.push([1, 8, , 9]);
1809
- return [4 /*yield*/, getResult(resolvedParams, req, res)];
1810
- case 2:
1811
- result = _d.sent();
1812
- if (!(result instanceof Blob &&
1813
- methodConfig.responseType ===
1814
- 'blob')) return [3 /*break*/, 4];
1815
- blob = result;
1816
- _b = (_a = Buffer).from;
1817
- return [4 /*yield*/, blob.arrayBuffer()];
1818
- case 3:
1819
- file = _b.apply(_a, [_d.sent()]);
1820
- res.writeHead(200, {
1821
- 'Content-Type': blob.type,
1822
- 'Content-Length': file.length,
1823
- });
1824
- res.end(file);
1825
- return [3 /*break*/, 7];
1826
- case 4:
1827
- if (!(tnp_core_4._.isString(result) &&
1828
- methodConfig.responseType ===
1829
- 'blob')) return [3 /*break*/, 5];
1830
- img_base64 = result;
1831
- m = /^data:(.+?);base64,(.+)$/.exec(img_base64);
1832
- if (!m) {
1833
- throw new Error("[taon - framework] Not a base64 image[".concat(img_base64, "]"));
1834
- }
1835
- _c = tslib_1.__read(m, 3), _1 = _c[0], content_type = _c[1], file_base64 = _c[2];
1836
- file = Buffer.from(file_base64, 'base64');
1837
- res.writeHead(200, {
1838
- 'Content-Type': content_type,
1839
- 'Content-Length': file.length,
1840
- });
1841
- res.end(file);
1842
- return [3 /*break*/, 7];
1843
- case 5:
1844
- //#region process json request
1845
- return [4 /*yield*/, entity_process_1.EntityProcess.init(result, res)];
1846
- case 6:
1847
- //#region process json request
1848
- _d.sent();
1849
- _d.label = 7;
1850
- case 7: return [3 /*break*/, 9];
1851
- case 8:
1852
- error_2 = _d.sent();
1853
- //#region process error
1854
- if (tnp_core_4._.isString(error_2)) {
1855
- res.status(400).send(json10_1.JSON10.stringify({
1856
- message: "\n Error inside: ".concat(req.path, "\n\n ").concat(error_2, "\n\n"),
1857
- }));
1858
- }
1859
- else if (error_2 instanceof models_1.Models.Http.Errors) {
1860
- tnp_core_4.Helpers.error(error_2, true, false);
1861
- err = error_2;
1862
- res.status(400).send(json10_1.JSON10.stringify(err));
1863
- }
1864
- else if (error_2 instanceof Error) {
1865
- err = error_2;
1866
- tnp_core_4.Helpers.error(error_2, true, false);
1867
- res.status(400).send(json10_1.JSON10.stringify({
1868
- stack: err.stack,
1869
- message: err.message,
1870
- }));
1871
- }
1872
- else {
1873
- tnp_core_4.Helpers.log(error_2);
1874
- tnp_core_4.Helpers.error("[Taon] Bad result isomorphic method: ".concat(error_2, " "), true, false);
1875
- res.status(400).send(json10_1.JSON10.stringify(error_2));
1876
- }
1877
- return [3 /*break*/, 9];
1878
- case 9: return [2 /*return*/];
1426
+ const afterEncoding = ng2_rest_1.Mapping.encode(beforeTransofrm, entityForParam);
1427
+ tQuery[queryParamName] =
1428
+ taon_helpers_1.TaonHelpers.parseJSONwithStringJSONs(afterEncoding);
1429
+ }
1430
+ catch (e) { }
1431
+ });
1432
+ }
1433
+ Object.keys(methodConfig.parameters).forEach(paramName => {
1434
+ let p = methodConfig.parameters[paramName];
1435
+ if (p.paramType === 'Path' && tParams) {
1436
+ args.push(tParams[p.paramName]);
1437
+ }
1438
+ if (p.paramType === 'Query' && tQuery) {
1439
+ if (p.paramName) {
1440
+ args.push(tQuery[p.paramName]);
1441
+ }
1442
+ else {
1443
+ args.push(tQuery);
1444
+ }
1445
+ }
1446
+ if (p.paramType === 'Header' && req.headers) {
1447
+ args.push(req.headers[p.paramName.toLowerCase()]);
1448
+ }
1449
+ if (p.paramType === 'Cookie' && req.cookies) {
1450
+ args.push(req.cookies[p.paramName]);
1451
+ }
1452
+ if (p.paramType === 'Body' && tBody) {
1453
+ if (p.paramName && typeof tBody === 'object') {
1454
+ args.push(tBody[p.paramName]);
1455
+ }
1456
+ else {
1457
+ args.push(tBody);
1458
+ }
1879
1459
  }
1880
1460
  });
1881
- }); });
1461
+ //#endregion
1462
+ const resolvedParams = args
1463
+ .reverse()
1464
+ .map(v => taon_helpers_1.TaonHelpers.tryTransformParam(v));
1465
+ try {
1466
+ let result = await getResult(resolvedParams, req, res);
1467
+ if (result instanceof Blob &&
1468
+ methodConfig.responseType ===
1469
+ 'blob') {
1470
+ // console.log('INSTANCE OF BLOB')
1471
+ //#region processs blob result type
1472
+ const blob = result;
1473
+ const file = Buffer.from(await blob.arrayBuffer());
1474
+ res.writeHead(200, {
1475
+ 'Content-Type': blob.type,
1476
+ 'Content-Length': file.length,
1477
+ });
1478
+ res.end(file);
1479
+ //#endregion
1480
+ }
1481
+ else if (tnp_core_4._.isString(result) &&
1482
+ methodConfig.responseType ===
1483
+ 'blob') {
1484
+ // console.log('BASE64')
1485
+ //#region process string buffer TODO refacetor
1486
+ const img_base64 = result;
1487
+ const m = /^data:(.+?);base64,(.+)$/.exec(img_base64);
1488
+ if (!m) {
1489
+ throw new Error(`[taon - framework] Not a base64 image[${img_base64}]`);
1490
+ }
1491
+ const [_, content_type, file_base64] = m;
1492
+ const file = Buffer.from(file_base64, 'base64');
1493
+ res.writeHead(200, {
1494
+ 'Content-Type': content_type,
1495
+ 'Content-Length': file.length,
1496
+ });
1497
+ res.end(file);
1498
+ //#endregion
1499
+ }
1500
+ else {
1501
+ //#region process json request
1502
+ await entity_process_1.EntityProcess.init(result, res);
1503
+ //#endregion
1504
+ }
1505
+ }
1506
+ catch (error) {
1507
+ //#region process error
1508
+ if (tnp_core_4._.isString(error)) {
1509
+ res.status(400).send(json10_1.JSON10.stringify({
1510
+ message: `
1511
+ Error inside: ${req.path}
1512
+
1513
+ ${error}
1514
+
1515
+ `,
1516
+ }));
1517
+ }
1518
+ else if (error instanceof models_1.Models.Http.Errors) {
1519
+ tnp_core_4.Helpers.error(error, true, false);
1520
+ const err = error;
1521
+ res.status(400).send(json10_1.JSON10.stringify(err));
1522
+ }
1523
+ else if (error instanceof Error) {
1524
+ const err = error;
1525
+ tnp_core_4.Helpers.error(error, true, false);
1526
+ res.status(400).send(json10_1.JSON10.stringify({
1527
+ stack: err.stack,
1528
+ message: err.message,
1529
+ }));
1530
+ }
1531
+ else {
1532
+ tnp_core_4.Helpers.log(error);
1533
+ tnp_core_4.Helpers.error(`[Taon] Bad result isomorphic method: ${error} `, true, false);
1534
+ res.status(400).send(json10_1.JSON10.stringify(error));
1535
+ }
1536
+ //#endregion
1537
+ }
1538
+ });
1882
1539
  //#endregion
1883
1540
  }
1884
1541
  return {
1885
1542
  routePath: expressPath,
1886
1543
  method: methodConfig.type,
1887
1544
  };
1888
- };
1545
+ }
1889
1546
  //#endregion
1890
1547
  //#region methods & getters / init client
1891
1548
  /**
1892
1549
  * client can be browser or nodejs (when remote host)
1893
1550
  */
1894
- EndpointContext.prototype.initClient = function (
1551
+ initClient(
1895
1552
  //#region parameters
1896
1553
  target, type, methodConfig, expressPath) {
1897
- var ctx = this;
1554
+ const ctx = this;
1898
1555
  // : { received: any; /* Rest<any, any> */ }
1899
- this.logHttp && console.log("".concat(type === null || type === void 0 ? void 0 : type.toUpperCase(), " ").concat(expressPath, " "));
1556
+ this.logHttp && console.log(`${type?.toUpperCase()} ${expressPath} `);
1900
1557
  // console.log('INITING', methodConfig); // TODO inject in static
1901
1558
  //#region resolve storage
1902
- var storage;
1559
+ let storage;
1903
1560
  if (tnp_core_4.Helpers.isBrowser) {
1904
1561
  storage = window;
1905
1562
  }
@@ -1909,48 +1566,39 @@ var EndpointContext = /** @class */ (function () {
1909
1566
  }
1910
1567
  //#endregion
1911
1568
  //#endregion
1912
- var orgMethods = target.prototype[methodConfig.methodName];
1569
+ const orgMethods = target.prototype[methodConfig.methodName];
1913
1570
  //#region handle electron ipc request
1914
1571
  if (tnp_core_4.Helpers.isElectron) {
1915
- target.prototype[methodConfig.methodName] = function () {
1916
- var _this = this;
1917
- var args = [];
1918
- for (var _i = 0; _i < arguments.length; _i++) {
1919
- args[_i] = arguments[_i];
1920
- }
1921
- var received = new Promise(function (resolve, reject) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
1922
- var headers, _a, request, response;
1923
- return tslib_1.__generator(this, function (_b) {
1924
- headers = {};
1925
- _a = taon_helpers_1.TaonHelpers.websqlMocks(headers), request = _a.request, response = _a.response;
1926
- tnp_core_4.Helpers.ipcRenderer.once(taon_helpers_1.TaonHelpers.ipcKeyNameResponse(target, methodConfig, expressPath), function (event, responseData) {
1927
- var res = responseData;
1928
- console.log({ responseData: responseData });
1929
- try {
1930
- var body_1 = res;
1931
- res = new ng2_rest_1.Models.HttpResponse({
1932
- body: void 0,
1933
- isArray: void 0,
1934
- method: methodConfig.type,
1935
- url: "".concat(ctx.uri.origin).concat('' // TODO express path
1936
- ).concat(methodConfig.path, " "),
1937
- }, tnp_core_4.Helpers.isBlob(body_1) || tnp_core_4._.isString(body_1)
1938
- ? body_1
1939
- : JSON.stringify(body_1), ng2_rest_1.RestHeaders.from(headers), void 0, function () { return body_1; });
1940
- resolve(res);
1941
- }
1942
- catch (error) {
1943
- console.error(error);
1944
- reject(error);
1945
- }
1946
- });
1947
- tnp_core_4.Helpers.ipcRenderer.send(taon_helpers_1.TaonHelpers.ipcKeyNameRequest(target, methodConfig, expressPath), args);
1948
- return [2 /*return*/];
1572
+ target.prototype[methodConfig.methodName] = function (...args) {
1573
+ const received = new Promise(async (resolve, reject) => {
1574
+ const headers = {};
1575
+ const { request, response } = taon_helpers_1.TaonHelpers.websqlMocks(headers);
1576
+ tnp_core_4.Helpers.ipcRenderer.once(taon_helpers_1.TaonHelpers.ipcKeyNameResponse(target, methodConfig, expressPath), (event, responseData) => {
1577
+ let res = responseData;
1578
+ console.log({ responseData });
1579
+ try {
1580
+ const body = res;
1581
+ res = new ng2_rest_1.Models.HttpResponse({
1582
+ body: void 0,
1583
+ isArray: void 0,
1584
+ method: methodConfig.type,
1585
+ url: `${ctx.uri.origin}${'' // TODO express path
1586
+ }${methodConfig.path} `,
1587
+ }, tnp_core_4.Helpers.isBlob(body) || tnp_core_4._.isString(body)
1588
+ ? body
1589
+ : JSON.stringify(body), ng2_rest_1.RestHeaders.from(headers), void 0, () => body);
1590
+ resolve(res);
1591
+ }
1592
+ catch (error) {
1593
+ console.error(error);
1594
+ reject(error);
1595
+ }
1949
1596
  });
1950
- }); });
1597
+ tnp_core_4.Helpers.ipcRenderer.send(taon_helpers_1.TaonHelpers.ipcKeyNameRequest(target, methodConfig, expressPath), args);
1598
+ });
1951
1599
  received['observable'] = (0, rxjs_1.from)(received);
1952
1600
  return {
1953
- received: received,
1601
+ received,
1954
1602
  };
1955
1603
  };
1956
1604
  return;
@@ -2101,22 +1749,18 @@ var EndpointContext = /** @class */ (function () {
2101
1749
  /* */
2102
1750
  //#endregion
2103
1751
  //#region handle normal request
2104
- target.prototype[methodConfig.methodName] = function () {
1752
+ target.prototype[methodConfig.methodName] = function (...args) {
2105
1753
  // console.log('[init method browser] FRONTEND expressPath', expressPath)
2106
1754
  // const productionMode = FrameworkContext.isProductionMode;
2107
- var args = [];
2108
- for (var _i = 0; _i < arguments.length; _i++) {
2109
- args[_i] = arguments[_i];
2110
- }
2111
1755
  //#region resolve frontend parameters
2112
1756
  if (!storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG])
2113
1757
  storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG] = {};
2114
1758
  if (!storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG][ctx.uri.href])
2115
1759
  storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG][ctx.uri.href] = {};
2116
- var endpoints = storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG];
2117
- var rest;
1760
+ const endpoints = storage[symbols_1.Symbols.old.ENDPOINT_META_CONFIG];
1761
+ let rest;
2118
1762
  if (!endpoints[ctx.uri.href][expressPath]) {
2119
- var headers = {};
1763
+ let headers = {};
2120
1764
  if (methodConfig.contentType && !methodConfig.responseType) {
2121
1765
  rest = ng2_rest_1.Resource.create(ctx.uri.href, expressPath, symbols_1.Symbols.old.MAPPING_CONFIG_HEADER, symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY, ng2_rest_1.RestHeaders.from({
2122
1766
  'Content-Type': methodConfig.contentType,
@@ -2143,15 +1787,15 @@ var EndpointContext = /** @class */ (function () {
2143
1787
  else {
2144
1788
  rest = endpoints[ctx.uri.href][expressPath];
2145
1789
  }
2146
- var method = type.toLowerCase();
2147
- var isWithBody = method === 'put' || method === 'post';
2148
- var pathPrams = {};
2149
- var queryParams = {};
2150
- var bodyObject = {};
2151
- args.forEach(function (param, i) {
2152
- var currentParam = void 0;
2153
- for (var pp in methodConfig.parameters) {
2154
- var v = methodConfig.parameters[pp];
1790
+ const method = type.toLowerCase();
1791
+ const isWithBody = method === 'put' || method === 'post';
1792
+ const pathPrams = {};
1793
+ let queryParams = {};
1794
+ let bodyObject = {};
1795
+ args.forEach((param, i) => {
1796
+ let currentParam = void 0;
1797
+ for (let pp in methodConfig.parameters) {
1798
+ let v = methodConfig.parameters[pp];
2155
1799
  if (v.index === i) {
2156
1800
  currentParam = v;
2157
1801
  break;
@@ -2162,14 +1806,14 @@ var EndpointContext = /** @class */ (function () {
2162
1806
  }
2163
1807
  if (currentParam.paramType === 'Query') {
2164
1808
  if (currentParam.paramName) {
2165
- var mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
1809
+ const mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
2166
1810
  if (mapping) {
2167
- rest.headers.set("".concat(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS).concat(currentParam.paramName, " "), JSON.stringify(mapping));
1811
+ rest.headers.set(`${symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS}${currentParam.paramName} `, JSON.stringify(mapping));
2168
1812
  }
2169
1813
  queryParams[currentParam.paramName] = param;
2170
1814
  }
2171
1815
  else {
2172
- var mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
1816
+ const mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
2173
1817
  if (mapping) {
2174
1818
  rest.headers.set(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_QUERY_PARAMS, JSON.stringify(mapping));
2175
1819
  }
@@ -2187,7 +1831,7 @@ var EndpointContext = /** @class */ (function () {
2187
1831
  }
2188
1832
  }
2189
1833
  else {
2190
- for (var header in param) {
1834
+ for (let header in param) {
2191
1835
  rest.headers.set(header, param[header]);
2192
1836
  }
2193
1837
  }
@@ -2198,16 +1842,26 @@ var EndpointContext = /** @class */ (function () {
2198
1842
  if (currentParam.paramType === 'Body') {
2199
1843
  if (currentParam.paramName) {
2200
1844
  if (class_helpers_1.ClassHelpers.getName(bodyObject) === 'FormData') {
2201
- throw new Error("[taon - framework] Don use param names when posting / putting FormData.\n Use this:\n// ...\n(@Taon.Http.Param.Body() formData: FormData) ...\n// ...\n\ninstead\n // ...\n (@Taon.Http.Param.Body('".concat(currentParam.paramName, "') formData: FormData) ...\n// ...\n"));
1845
+ throw new Error(`[taon - framework] Don use param names when posting / putting FormData.
1846
+ Use this:
1847
+ // ...
1848
+ (@Taon.Http.Param.Body() formData: FormData) ...
1849
+ // ...
1850
+
1851
+ instead
1852
+ // ...
1853
+ (@Taon.Http.Param.Body('${currentParam.paramName}') formData: FormData) ...
1854
+ // ...
1855
+ `);
2202
1856
  }
2203
- var mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
1857
+ const mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
2204
1858
  if (mapping) {
2205
- rest.headers.set("".concat(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS).concat(currentParam.paramName, " "), JSON.stringify(mapping));
1859
+ rest.headers.set(`${symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS}${currentParam.paramName} `, JSON.stringify(mapping));
2206
1860
  }
2207
1861
  bodyObject[currentParam.paramName] = param;
2208
1862
  }
2209
1863
  else {
2210
- var mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
1864
+ const mapping = ng2_rest_1.Mapping.decode(param, !ctx.isProductionMode);
2211
1865
  if (mapping) {
2212
1866
  rest.headers.set(symbols_1.Symbols.old.MAPPING_CONFIG_HEADER_BODY_PARAMS, JSON.stringify(mapping));
2213
1867
  }
@@ -2217,21 +1871,21 @@ var EndpointContext = /** @class */ (function () {
2217
1871
  });
2218
1872
  if (typeof bodyObject === 'object' &&
2219
1873
  class_helpers_1.ClassHelpers.getName(bodyObject) !== 'FormData') {
2220
- var circuralFromItem_1 = [];
2221
- bodyObject = json10_1.JSON10.parse(json10_1.JSON10.stringify(bodyObject, void 0, void 0, function (circs) {
2222
- circuralFromItem_1 = circs;
1874
+ let circuralFromItem = [];
1875
+ bodyObject = json10_1.JSON10.parse(json10_1.JSON10.stringify(bodyObject, void 0, void 0, circs => {
1876
+ circuralFromItem = circs;
2223
1877
  }));
2224
- rest.headers.set(symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY, json10_1.JSON10.stringify(circuralFromItem_1));
1878
+ rest.headers.set(symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_BODY, json10_1.JSON10.stringify(circuralFromItem));
2225
1879
  }
2226
1880
  if (typeof queryParams === 'object') {
2227
- var circuralFromQueryParams_1 = [];
2228
- queryParams = json10_1.JSON10.parse(json10_1.JSON10.stringify(queryParams, void 0, void 0, function (circs) {
2229
- circuralFromQueryParams_1 = circs;
1881
+ let circuralFromQueryParams = [];
1882
+ queryParams = json10_1.JSON10.parse(json10_1.JSON10.stringify(queryParams, void 0, void 0, circs => {
1883
+ circuralFromQueryParams = circs;
2230
1884
  }));
2231
- rest.headers.set(symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM, json10_1.JSON10.stringify(circuralFromQueryParams_1));
1885
+ rest.headers.set(symbols_1.Symbols.old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM, json10_1.JSON10.stringify(circuralFromQueryParams));
2232
1886
  }
2233
1887
  //#endregion
2234
- var httpResultObj = {
1888
+ const httpResultObj = {
2235
1889
  received: isWithBody
2236
1890
  ? rest.model(pathPrams)[method](bodyObject, [queryParams])
2237
1891
  : rest.model(pathPrams)[method]([queryParams]),
@@ -2239,8 +1893,7 @@ var EndpointContext = /** @class */ (function () {
2239
1893
  return httpResultObj;
2240
1894
  };
2241
1895
  //#endregion
2242
- };
2243
- return EndpointContext;
2244
- }());
1896
+ }
1897
+ }
2245
1898
  exports.EndpointContext = EndpointContext;
2246
1899
  //# sourceMappingURL=endpoint-context.js.map