moost 0.3.9 → 0.3.11

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.
package/dist/index.cjs CHANGED
@@ -5,1163 +5,1111 @@ var infact$1 = require('@prostojs/infact');
5
5
  var eventCore = require('@wooksjs/event-core');
6
6
  var logger = require('@prostojs/logger');
7
7
 
8
- /******************************************************************************
9
- Copyright (c) Microsoft Corporation.
10
-
11
- Permission to use, copy, modify, and/or distribute this software for any
12
- purpose with or without fee is hereby granted.
13
-
14
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
15
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
16
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
17
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
18
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
19
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
20
- PERFORMANCE OF THIS SOFTWARE.
21
- ***************************************************************************** */
22
- /* global Reflect, Promise */
23
-
24
-
25
- function __awaiter(thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
8
+ const METADATA_WORKSPACE = 'moost';
9
+ const moostMate = new mate$1.Mate(METADATA_WORKSPACE, {
10
+ readType: true,
11
+ readReturnType: true,
12
+ collectPropKeys: true,
13
+ inherit(classMeta, targetMeta, level) {
14
+ if (level === 'CLASS') {
15
+ return !!classMeta?.inherit;
16
+ }
17
+ if (level === 'PROP') {
18
+ return (!!targetMeta?.inherit || !!(classMeta?.inherit && !targetMeta));
19
+ }
20
+ return !!targetMeta?.inherit;
21
+ },
22
+ });
23
+ function getMoostMate() {
24
+ return moostMate;
33
25
  }
34
26
 
35
- const METADATA_WORKSPACE = 'moost';
36
- const moostMate = new mate$1.Mate(METADATA_WORKSPACE, {
37
- readType: true,
38
- readReturnType: true,
39
- collectPropKeys: true,
40
- inherit(classMeta, targetMeta, level) {
41
- if (level === 'CLASS') {
42
- return !!(classMeta === null || classMeta === void 0 ? void 0 : classMeta.inherit);
43
- }
44
- if (level === 'PROP') {
45
- return (!!(targetMeta === null || targetMeta === void 0 ? void 0 : targetMeta.inherit) || !!((classMeta === null || classMeta === void 0 ? void 0 : classMeta.inherit) && !targetMeta));
46
- }
47
- return !!(targetMeta === null || targetMeta === void 0 ? void 0 : targetMeta.inherit);
48
- },
49
- });
50
- function getMoostMate() {
51
- return moostMate;
27
+ async function runPipes(pipes, initialValue, metas, level, restoreCtx) {
28
+ let v = initialValue;
29
+ for (const pipe of pipes) {
30
+ restoreCtx && restoreCtx();
31
+ v = await pipe.handler(v, metas, level);
32
+ }
33
+ return v;
52
34
  }
53
35
 
54
- function runPipes(pipes, initialValue, metas, level, restoreCtx) {
55
- return __awaiter(this, void 0, void 0, function* () {
56
- let v = initialValue;
57
- for (const pipe of pipes) {
58
- restoreCtx && restoreCtx();
59
- v = yield pipe.handler(v, metas, level);
60
- }
61
- return v;
62
- });
36
+ const sharedMoostInfact = getNewMoostInfact();
37
+ function getMoostInfact() {
38
+ return sharedMoostInfact;
63
39
  }
64
-
65
- const sharedMoostInfact = getNewMoostInfact();
66
- function getMoostInfact() {
67
- return sharedMoostInfact;
68
- }
69
- function getNewMoostInfact() {
70
- return new infact$1.Infact({
71
- describeClass(classConstructor) {
72
- const meta = getMoostMate().read(classConstructor);
73
- const infactMeta = {
74
- injectable: !!(meta === null || meta === void 0 ? void 0 : meta.injectable),
75
- global: false,
76
- constructorParams: (meta === null || meta === void 0 ? void 0 : meta.params) || [],
77
- provide: meta === null || meta === void 0 ? void 0 : meta.provide,
78
- properties: (meta === null || meta === void 0 ? void 0 : meta.properties) || [],
79
- scopeId: (meta === null || meta === void 0 ? void 0 : meta.injectable) === 'FOR_EVENT'
80
- ? eventCore.useEventId().getId()
81
- : undefined,
82
- };
83
- return infactMeta;
84
- },
85
- resolveParam({ paramMeta, classMeta, customData, classConstructor, index }) {
86
- if (paramMeta && customData && customData.pipes) {
87
- return runPipes(customData.pipes, undefined, {
88
- paramMeta,
89
- type: classConstructor,
90
- key: 'constructor',
91
- classMeta: classMeta,
92
- index,
93
- targetMeta: paramMeta,
94
- }, 'PARAM');
95
- }
96
- },
97
- describeProp(classConstructor, key) {
98
- const meta = getMoostMate().read(classConstructor, key);
99
- return meta;
100
- },
101
- resolveProp({ instance, key, initialValue, propMeta, classMeta, customData, classConstructor, }) {
102
- if (propMeta && customData && customData.pipes) {
103
- return runPipes(customData.pipes, initialValue, {
104
- instance,
105
- type: classConstructor,
106
- key,
107
- propMeta,
108
- targetMeta: propMeta,
109
- classMeta: classMeta,
110
- }, 'PROP');
111
- }
112
- },
113
- storeProvideRegByInstance: true,
114
- });
40
+ function getNewMoostInfact() {
41
+ return new infact$1.Infact({
42
+ describeClass(classConstructor) {
43
+ const meta = getMoostMate().read(classConstructor);
44
+ const infactMeta = {
45
+ injectable: !!meta?.injectable,
46
+ global: false,
47
+ constructorParams: meta?.params || [],
48
+ provide: meta?.provide,
49
+ properties: meta?.properties || [],
50
+ scopeId: meta?.injectable === 'FOR_EVENT'
51
+ ? eventCore.useEventId().getId()
52
+ : undefined,
53
+ };
54
+ return infactMeta;
55
+ },
56
+ resolveParam({ paramMeta, classMeta, customData, classConstructor, index }) {
57
+ if (paramMeta && customData && customData.pipes) {
58
+ return runPipes(customData.pipes, undefined, {
59
+ paramMeta,
60
+ type: classConstructor,
61
+ key: 'constructor',
62
+ classMeta: classMeta,
63
+ index,
64
+ targetMeta: paramMeta,
65
+ }, 'PARAM');
66
+ }
67
+ },
68
+ describeProp(classConstructor, key) {
69
+ const meta = getMoostMate().read(classConstructor, key);
70
+ return meta;
71
+ },
72
+ resolveProp({ instance, key, initialValue, propMeta, classMeta, customData, classConstructor, }) {
73
+ if (propMeta && customData && customData.pipes) {
74
+ return runPipes(customData.pipes, initialValue, {
75
+ instance,
76
+ type: classConstructor,
77
+ key,
78
+ propMeta,
79
+ targetMeta: propMeta,
80
+ classMeta: classMeta,
81
+ }, 'PROP');
82
+ }
83
+ },
84
+ storeProvideRegByInstance: true,
85
+ });
115
86
  }
116
87
 
117
- function getInstanceOwnMethods(instance) {
118
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
119
- const proto = Object.getPrototypeOf(instance);
120
- return [
121
- ...getParentProps(mate$1.getConstructor(instance)),
122
- ...Object.getOwnPropertyNames(proto),
123
- ...Object.getOwnPropertyNames(instance),
124
- ].filter((m) => typeof instance[m] === 'function');
125
- }
126
- const fnProto = Object.getPrototypeOf(Function);
127
- function getParentProps(constructor) {
128
- const parent = Object.getPrototypeOf(constructor);
129
- if (typeof parent === 'function' &&
130
- parent !== fnProto &&
131
- parent !== constructor &&
132
- parent.prototype) {
133
- return [
134
- ...getParentProps(parent),
135
- ...Object.getOwnPropertyNames(parent.prototype),
136
- ];
137
- }
138
- return [];
88
+ function getInstanceOwnMethods(instance) {
89
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
90
+ const proto = Object.getPrototypeOf(instance);
91
+ return [
92
+ ...getParentProps(mate$1.getConstructor(instance)), // Inheritance support
93
+ ...Object.getOwnPropertyNames(proto),
94
+ ...Object.getOwnPropertyNames(instance),
95
+ ].filter((m) => typeof instance[m] === 'function');
96
+ }
97
+ const fnProto = Object.getPrototypeOf(Function);
98
+ function getParentProps(constructor) {
99
+ const parent = Object.getPrototypeOf(constructor);
100
+ if (typeof parent === 'function' &&
101
+ parent !== fnProto &&
102
+ parent !== constructor &&
103
+ parent.prototype) {
104
+ return [
105
+ ...getParentProps(parent),
106
+ ...Object.getOwnPropertyNames(parent.prototype),
107
+ ];
108
+ }
109
+ return [];
139
110
  }
140
111
 
141
- function getCallableFn(targetInstance, fn, restoreCtx, pipes, logger) {
142
- return __awaiter(this, void 0, void 0, function* () {
143
- const mate = getMoostMate();
144
- const meta = mate.read(fn);
145
- if (meta === null || meta === void 0 ? void 0 : meta.injectable) {
146
- const infact = getMoostInfact();
147
- infact.silent(true);
148
- const instance = (yield infact.getForInstance(targetInstance, fn, {
149
- syncContextFn: () => {
150
- restoreCtx && restoreCtx();
151
- },
152
- customData: {
153
- pipes: [...(pipes || []), ...(meta.pipes || [])].sort((a, b) => a.priority - b.priority),
154
- },
155
- }));
156
- infact.silent(false);
157
- return ((...args) => {
158
- return instance.handler(...args);
159
- });
160
- }
161
- if (typeof fn === 'function') {
162
- return fn;
163
- }
164
- const e = new Error(`getCallableFn failed for "${mate$1.getConstructor(targetInstance).name}" because the passed arg is not a Function nor TClassFunction`);
165
- logger.error(e);
166
- throw e;
167
- });
112
+ async function getCallableFn(targetInstance, fn, restoreCtx, pipes, logger) {
113
+ const mate = getMoostMate();
114
+ const meta = mate.read(fn);
115
+ if (meta?.injectable) {
116
+ const infact = getMoostInfact();
117
+ infact.silent(true);
118
+ const instance = (await infact.getForInstance(targetInstance, fn, {
119
+ syncContextFn: () => {
120
+ restoreCtx && restoreCtx();
121
+ },
122
+ customData: {
123
+ pipes: [...(pipes || []), ...(meta.pipes || [])].sort((a, b) => a.priority - b.priority),
124
+ },
125
+ }));
126
+ infact.silent(false);
127
+ return ((...args) => {
128
+ return instance.handler(...args);
129
+ });
130
+ }
131
+ if (typeof fn === 'function') {
132
+ return fn;
133
+ }
134
+ const e = new Error(`getCallableFn failed for "${mate$1.getConstructor(targetInstance).name}" because the passed arg is not a Function nor TClassFunction`);
135
+ logger.error(e);
136
+ throw e;
168
137
  }
169
138
 
170
- class InterceptorHandler {
171
- constructor(handlers) {
172
- this.handlers = handlers;
173
- this.before = [];
174
- this.after = [];
175
- this.onError = [];
176
- this.responseOverwritten = false;
177
- }
178
- replyFn(reply) {
179
- this.response = reply;
180
- this.responseOverwritten = true;
181
- }
182
- init() {
183
- return __awaiter(this, void 0, void 0, function* () {
184
- const { restoreCtx } = eventCore.useEventContext();
185
- for (const handler of this.handlers) {
186
- restoreCtx();
187
- const response = yield handler((fn) => {
188
- this.before.push(fn);
189
- }, (fn) => {
190
- this.after.unshift(fn);
191
- }, (fn) => {
192
- this.onError.unshift(fn);
193
- });
194
- if (typeof response !== 'undefined')
195
- return response;
196
- }
197
- });
198
- }
199
- fireBefore(response) {
200
- return __awaiter(this, void 0, void 0, function* () {
201
- const { restoreCtx } = eventCore.useEventContext();
202
- this.response = response;
203
- for (const handler of this.before) {
204
- restoreCtx();
205
- yield handler(this.replyFn.bind(this));
206
- if (this.responseOverwritten)
207
- break;
208
- }
209
- return this.response;
210
- });
211
- }
212
- fireAfter(response) {
213
- return __awaiter(this, void 0, void 0, function* () {
214
- const { restoreCtx } = eventCore.useEventContext();
215
- this.response = response;
216
- if (response instanceof Error) {
217
- for (const handler of this.onError) {
218
- restoreCtx();
219
- yield handler(response, this.replyFn.bind(this));
220
- }
221
- }
222
- else {
223
- for (const handler of this.after) {
224
- restoreCtx();
225
- yield handler(response, this.replyFn.bind(this));
226
- }
227
- }
228
- return this.response;
229
- });
230
- }
139
+ class InterceptorHandler {
140
+ constructor(handlers) {
141
+ this.handlers = handlers;
142
+ this.before = [];
143
+ this.after = [];
144
+ this.onError = [];
145
+ this.responseOverwritten = false;
146
+ }
147
+ replyFn(reply) {
148
+ this.response = reply;
149
+ this.responseOverwritten = true;
150
+ }
151
+ async init() {
152
+ const { restoreCtx } = eventCore.useEventContext();
153
+ for (const handler of this.handlers) {
154
+ restoreCtx();
155
+ const response = await handler((fn) => {
156
+ this.before.push(fn);
157
+ }, (fn) => {
158
+ this.after.unshift(fn);
159
+ }, (fn) => {
160
+ this.onError.unshift(fn);
161
+ });
162
+ if (typeof response !== 'undefined')
163
+ return response;
164
+ }
165
+ }
166
+ async fireBefore(response) {
167
+ const { restoreCtx } = eventCore.useEventContext();
168
+ this.response = response;
169
+ for (const handler of this.before) {
170
+ restoreCtx();
171
+ await handler(this.replyFn.bind(this));
172
+ if (this.responseOverwritten)
173
+ break;
174
+ }
175
+ return this.response;
176
+ }
177
+ async fireAfter(response) {
178
+ const { restoreCtx } = eventCore.useEventContext();
179
+ this.response = response;
180
+ if (response instanceof Error) {
181
+ for (const handler of this.onError) {
182
+ restoreCtx();
183
+ await handler(response, this.replyFn.bind(this));
184
+ }
185
+ }
186
+ else {
187
+ for (const handler of this.after) {
188
+ restoreCtx();
189
+ await handler(response, this.replyFn.bind(this));
190
+ }
191
+ }
192
+ return this.response;
193
+ }
231
194
  }
232
195
 
233
- const mate = getMoostMate();
234
- function getIterceptorHandlerFactory(interceptors, getTargetInstance, pipes, logger) {
235
- return () => {
236
- const interceptorHandlers = [];
237
- for (const { handler } of interceptors) {
238
- const interceptorMeta = mate.read(handler);
239
- if (interceptorMeta === null || interceptorMeta === void 0 ? void 0 : interceptorMeta.injectable) {
240
- interceptorHandlers.push((...args) => __awaiter(this, void 0, void 0, function* () {
241
- const { restoreCtx } = eventCore.useEventContext();
242
- const targetInstance = yield getTargetInstance();
243
- restoreCtx();
244
- return (yield getCallableFn(targetInstance, handler, restoreCtx, pipes, logger))(...args);
245
- }));
246
- }
247
- else {
248
- interceptorHandlers.push(handler);
249
- }
250
- }
251
- return Promise.resolve(new InterceptorHandler(interceptorHandlers));
252
- };
196
+ const mate = getMoostMate();
197
+ function getIterceptorHandlerFactory(interceptors, getTargetInstance, pipes, logger) {
198
+ return () => {
199
+ const interceptorHandlers = [];
200
+ for (const { handler } of interceptors) {
201
+ const interceptorMeta = mate.read(handler);
202
+ if (interceptorMeta?.injectable) {
203
+ interceptorHandlers.push(async (...args) => {
204
+ const { restoreCtx } = eventCore.useEventContext();
205
+ const targetInstance = await getTargetInstance();
206
+ restoreCtx();
207
+ return (await getCallableFn(targetInstance, handler, restoreCtx, pipes, logger))(...args);
208
+ });
209
+ }
210
+ else {
211
+ interceptorHandlers.push(handler);
212
+ }
213
+ }
214
+ return Promise.resolve(new InterceptorHandler(interceptorHandlers));
215
+ };
253
216
  }
254
217
 
255
- function bindControllerMethods(options) {
256
- var _a;
257
- return __awaiter(this, void 0, void 0, function* () {
258
- const opts = options || {};
259
- const { getInstance } = opts;
260
- const { classConstructor } = opts;
261
- const { adapters } = opts;
262
- opts.globalPrefix = opts.globalPrefix || '';
263
- opts.provide = opts.provide || {};
264
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
265
- const fakeInstance = Object.create(classConstructor.prototype);
266
- const methods = getInstanceOwnMethods(fakeInstance);
267
- const mate = getMoostMate();
268
- const meta = mate.read(classConstructor) || {};
269
- const ownPrefix = typeof opts.replaceOwnPrefix === 'string'
270
- ? opts.replaceOwnPrefix
271
- : ((_a = meta.controller) === null || _a === void 0 ? void 0 : _a.prefix) || '';
272
- const prefix = `${opts.globalPrefix}/${ownPrefix}`;
273
- const controllerOverview = {
274
- meta,
275
- computedPrefix: prefix,
276
- type: classConstructor,
277
- handlers: [],
278
- };
279
- for (const method of methods) {
280
- const methodMeta = getMoostMate().read(fakeInstance, method) || {};
281
- methodMeta.handlers;
282
- if (!methodMeta.handlers || !methodMeta.handlers.length)
283
- continue;
284
- const pipes = [...(opts.pipes || []), ...(methodMeta.pipes || [])].sort((a, b) => a.priority - b.priority);
285
- // preparing interceptors
286
- const interceptors = [
287
- ...(opts.interceptors || []),
288
- ...(meta.interceptors || []),
289
- ...(methodMeta.interceptors || []),
290
- ].sort((a, b) => a.priority - b.priority);
291
- const getIterceptorHandler = getIterceptorHandlerFactory(interceptors, getInstance, pipes, options.logger);
292
- // preparing pipes
293
- const argsPipes = [];
294
- for (const p of methodMeta.params || []) {
295
- argsPipes.push({
296
- meta: p,
297
- pipes: [...pipes, ...(p.pipes || [])].sort((a, b) => a.priority - b.priority),
298
- });
299
- }
300
- const resolveArgs = () => __awaiter(this, void 0, void 0, function* () {
301
- const args = [];
302
- const { restoreCtx } = eventCore.useEventContext();
303
- for (let i = 0; i < argsPipes.length; i++) {
304
- const { pipes, meta: paramMeta } = argsPipes[i];
305
- args[i] = yield runPipes(pipes, undefined, {
306
- classMeta: meta,
307
- methodMeta,
308
- paramMeta,
309
- type: classConstructor,
310
- key: method,
311
- index: i,
312
- targetMeta: paramMeta,
313
- }, 'PARAM', restoreCtx);
314
- }
315
- return args;
316
- });
317
- const wm = new WeakMap();
318
- controllerOverview.handlers.push(...methodMeta.handlers.map(h => {
319
- const data = {
320
- meta: methodMeta,
321
- path: h.path,
322
- type: h.type,
323
- method,
324
- handler: h,
325
- registeredAs: [],
326
- };
327
- wm.set(h, data);
328
- return data;
329
- }));
330
- for (const adapter of adapters) {
331
- yield adapter.bindHandler({
332
- prefix,
333
- fakeInstance,
334
- getInstance,
335
- method,
336
- handlers: methodMeta.handlers,
337
- getIterceptorHandler,
338
- resolveArgs,
339
- logHandler: (eventName) => options.logger.info(`• ${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`),
340
- register(h, path, args) {
341
- const data = wm.get(h);
342
- if (data) {
343
- data.registeredAs.push({
344
- path,
345
- args,
346
- });
347
- }
348
- },
349
- });
350
- }
351
- }
352
- return controllerOverview;
353
- });
218
+ async function bindControllerMethods(options) {
219
+ const opts = options || {};
220
+ const { getInstance } = opts;
221
+ const { classConstructor } = opts;
222
+ const { adapters } = opts;
223
+ opts.globalPrefix = opts.globalPrefix || '';
224
+ opts.provide = opts.provide || {};
225
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
226
+ const fakeInstance = Object.create(classConstructor.prototype);
227
+ const methods = getInstanceOwnMethods(fakeInstance);
228
+ const mate = getMoostMate();
229
+ const meta = mate.read(classConstructor) || {};
230
+ const ownPrefix = typeof opts.replaceOwnPrefix === 'string'
231
+ ? opts.replaceOwnPrefix
232
+ : meta.controller?.prefix || '';
233
+ const prefix = `${opts.globalPrefix}/${ownPrefix}`;
234
+ const controllerOverview = {
235
+ meta,
236
+ computedPrefix: prefix,
237
+ type: classConstructor,
238
+ handlers: [],
239
+ };
240
+ for (const method of methods) {
241
+ const methodMeta = getMoostMate().read(fakeInstance, method) || {};
242
+ methodMeta.handlers;
243
+ if (!methodMeta.handlers || !methodMeta.handlers.length)
244
+ continue;
245
+ const pipes = [...(opts.pipes || []), ...(methodMeta.pipes || [])].sort((a, b) => a.priority - b.priority);
246
+ // preparing interceptors
247
+ const interceptors = [
248
+ ...(opts.interceptors || []),
249
+ ...(meta.interceptors || []),
250
+ ...(methodMeta.interceptors || []),
251
+ ].sort((a, b) => a.priority - b.priority);
252
+ const getIterceptorHandler = getIterceptorHandlerFactory(interceptors, getInstance, pipes, options.logger);
253
+ // preparing pipes
254
+ const argsPipes = [];
255
+ for (const p of methodMeta.params || []) {
256
+ argsPipes.push({
257
+ meta: p,
258
+ pipes: [...pipes, ...(p.pipes || [])].sort((a, b) => a.priority - b.priority),
259
+ });
260
+ }
261
+ const resolveArgs = async () => {
262
+ const args = [];
263
+ const { restoreCtx } = eventCore.useEventContext();
264
+ for (let i = 0; i < argsPipes.length; i++) {
265
+ const { pipes, meta: paramMeta } = argsPipes[i];
266
+ args[i] = await runPipes(pipes, undefined, {
267
+ classMeta: meta,
268
+ methodMeta,
269
+ paramMeta,
270
+ type: classConstructor,
271
+ key: method,
272
+ index: i,
273
+ targetMeta: paramMeta,
274
+ }, 'PARAM', restoreCtx);
275
+ }
276
+ return args;
277
+ };
278
+ const wm = new WeakMap();
279
+ controllerOverview.handlers.push(...methodMeta.handlers.map(h => {
280
+ const data = {
281
+ meta: methodMeta,
282
+ path: h.path,
283
+ type: h.type,
284
+ method,
285
+ handler: h,
286
+ registeredAs: [],
287
+ };
288
+ wm.set(h, data);
289
+ return data;
290
+ }));
291
+ for (const adapter of adapters) {
292
+ await adapter.bindHandler({
293
+ prefix,
294
+ fakeInstance,
295
+ getInstance,
296
+ method,
297
+ handlers: methodMeta.handlers,
298
+ getIterceptorHandler,
299
+ resolveArgs,
300
+ logHandler: (eventName) => options.logger.info(`• ${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`),
301
+ register(h, path, args) {
302
+ const data = wm.get(h);
303
+ if (data) {
304
+ data.registeredAs.push({
305
+ path,
306
+ args,
307
+ });
308
+ }
309
+ },
310
+ });
311
+ }
312
+ }
313
+ return controllerOverview;
354
314
  }
355
315
 
356
- /**
357
- * ## Label
358
- * ### @Decorator
359
- * _Common purpose decorator that may be used by various adapters for various purposes_
360
- *
361
- * Stores Label metadata
362
- */
363
- function Label(value) {
364
- return getMoostMate().decorate('label', value);
365
- }
366
- /**
367
- * ## Description
368
- * ### @Decorator
369
- * _Common purpose decorator that may be used by various adapters for various purposes_
370
- *
371
- * Stores Description metadata
372
- */
373
- function Description(value) {
374
- return getMoostMate().decorate('description', value);
375
- }
376
- /**
377
- * ## Value
378
- * ### @Decorator
379
- * _Common purpose decorator that may be used by various adapters for various purposes_
380
- *
381
- * Stores Value metadata
382
- */
383
- function Value(value) {
384
- return getMoostMate().decorate('value', value);
385
- }
386
- /**
387
- * ## Id
388
- * ### @Decorator
389
- * _Common purpose decorator that may be used by various adapters for various purposes_
390
- *
391
- * Stores Id metadata
392
- */
393
- function Id(value) {
394
- return getMoostMate().decorate('id', value);
395
- }
396
- /**
397
- * ## Optional
398
- * ### @Decorator
399
- * _Common purpose decorator that may be used by various adapters for various purposes_
400
- *
401
- * Stores Optional metadata
402
- */
403
- function Optional() {
404
- return getMoostMate().decorate('optional', true);
405
- }
406
- /**
407
- * ## Required
408
- * ### @Decorator
409
- * _Common purpose decorator that may be used by various adapters for various purposes_
410
- *
411
- * Stores Required metadata
412
- */
413
- function Required() {
414
- const mate = getMoostMate();
415
- return mate.apply(mate.decorate('required', true),
416
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
417
- mate.decorateClass((meta, level, key, index) => {
418
- if (typeof index !== 'number' &&
419
- meta &&
420
- ['string', 'symbol'].includes(typeof key)) {
421
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
422
- meta.requiredProps = meta.requiredProps || [];
423
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
424
- meta.requiredProps.push(key);
425
- }
426
- return meta;
427
- }));
316
+ /**
317
+ * ## Label
318
+ * ### @Decorator
319
+ * _Common purpose decorator that may be used by various adapters for various purposes_
320
+ *
321
+ * Stores Label metadata
322
+ */
323
+ function Label(value) {
324
+ return getMoostMate().decorate('label', value);
325
+ }
326
+ /**
327
+ * ## Description
328
+ * ### @Decorator
329
+ * _Common purpose decorator that may be used by various adapters for various purposes_
330
+ *
331
+ * Stores Description metadata
332
+ */
333
+ function Description(value) {
334
+ return getMoostMate().decorate('description', value);
335
+ }
336
+ /**
337
+ * ## Value
338
+ * ### @Decorator
339
+ * _Common purpose decorator that may be used by various adapters for various purposes_
340
+ *
341
+ * Stores Value metadata
342
+ */
343
+ function Value(value) {
344
+ return getMoostMate().decorate('value', value);
345
+ }
346
+ /**
347
+ * ## Id
348
+ * ### @Decorator
349
+ * _Common purpose decorator that may be used by various adapters for various purposes_
350
+ *
351
+ * Stores Id metadata
352
+ */
353
+ function Id(value) {
354
+ return getMoostMate().decorate('id', value);
355
+ }
356
+ /**
357
+ * ## Optional
358
+ * ### @Decorator
359
+ * _Common purpose decorator that may be used by various adapters for various purposes_
360
+ *
361
+ * Stores Optional metadata
362
+ */
363
+ function Optional() {
364
+ return getMoostMate().decorate('optional', true);
365
+ }
366
+ /**
367
+ * ## Required
368
+ * ### @Decorator
369
+ * _Common purpose decorator that may be used by various adapters for various purposes_
370
+ *
371
+ * Stores Required metadata
372
+ */
373
+ function Required() {
374
+ const mate = getMoostMate();
375
+ return mate.apply(mate.decorate('required', true),
376
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
377
+ mate.decorateClass((meta, level, key, index) => {
378
+ if (typeof index !== 'number' &&
379
+ meta &&
380
+ ['string', 'symbol'].includes(typeof key)) {
381
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
382
+ meta.requiredProps = meta.requiredProps || [];
383
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
384
+ meta.requiredProps.push(key);
385
+ }
386
+ return meta;
387
+ }));
428
388
  }
429
389
 
430
- /**
431
- * Hook to the Response Status
432
- * @decorator
433
- * @param resolver - resolver function
434
- * @param label - field label
435
- * @paramType unknown
436
- */
437
- function Resolve(resolver, label) {
438
- return (target, key, index) => {
439
- const i = typeof index === 'number' ? index : undefined;
440
- getMoostMate().decorate('resolver', (metas, level) => {
441
- let newLabel = label;
442
- if (!newLabel && level === 'PROP' && typeof metas.key === 'string') {
443
- newLabel = metas.key;
444
- }
445
- fillLabel(target, key || '', i, newLabel);
446
- return resolver(metas, level);
447
- })(target, key, i);
448
- };
449
- }
450
- /**
451
- * Get Param Value from url parh
452
- * @decorator
453
- * @param name - param name
454
- * @paramType string
455
- */
456
- function Param(name) {
457
- return getMoostMate().apply(getMoostMate().decorate('paramSource', 'ROUTE'), getMoostMate().decorate('paramName', name), Resolve(() => eventCore.useRouteParams().get(name), name));
458
- }
459
- /**
460
- * Get Parsed Params from url parh
461
- * @decorator
462
- * @paramType object
463
- */
464
- function Params() {
465
- return Resolve(() => eventCore.useRouteParams().params, 'params');
466
- }
467
- /**
468
- * Provide Const Value
469
- * @decorator
470
- * @param value - provided value
471
- * @param label - label of the field
472
- * @paramType unknown
473
- */
474
- function Const(value, label) {
475
- return Resolve(() => value, label);
476
- }
477
- /**
478
- * Provide Const Value from Factory fn
479
- * @decorator
480
- * @param factory - value Factory fn
481
- * @param label - label of the field
482
- * @paramType unknown
483
- */
484
- function ConstFactory(factory, label) {
485
- return Resolve(() => __awaiter(this, void 0, void 0, function* () { return yield factory(); }), label);
486
- }
487
- /**
488
- * Resolves event logger from event context
489
- * @param topic
490
- * @returns Resolver to '@wooksjs/event-core' (EventLogger)
491
- */
492
- function InjectEventLogger(topic) {
493
- return Resolve(() => eventCore.useEventLogger(topic));
494
- }
495
- function fillLabel(target, key, index, name) {
496
- if (name) {
497
- const meta = getMoostMate().read(target, key);
498
- if (typeof index === 'number') {
499
- if (!(meta === null || meta === void 0 ? void 0 : meta.params) ||
500
- !(meta === null || meta === void 0 ? void 0 : meta.params[index]) ||
501
- !(meta === null || meta === void 0 ? void 0 : meta.params[index].label)) {
502
- Label(name)(target, key, index);
503
- }
504
- }
505
- else {
506
- if (!(meta === null || meta === void 0 ? void 0 : meta.label)) {
507
- Label(name)(target, key);
508
- }
509
- }
510
- }
390
+ /**
391
+ * Hook to the Response Status
392
+ * @decorator
393
+ * @param resolver - resolver function
394
+ * @param label - field label
395
+ * @paramType unknown
396
+ */
397
+ function Resolve(resolver, label) {
398
+ return (target, key, index) => {
399
+ const i = typeof index === 'number' ? index : undefined;
400
+ getMoostMate().decorate('resolver', (metas, level) => {
401
+ let newLabel = label;
402
+ if (!newLabel && level === 'PROP' && typeof metas.key === 'string') {
403
+ newLabel = metas.key;
404
+ }
405
+ fillLabel(target, key || '', i, newLabel);
406
+ return resolver(metas, level);
407
+ })(target, key, i);
408
+ };
409
+ }
410
+ /**
411
+ * Get Param Value from url parh
412
+ * @decorator
413
+ * @param name - param name
414
+ * @paramType string
415
+ */
416
+ function Param(name) {
417
+ return getMoostMate().apply(getMoostMate().decorate('paramSource', 'ROUTE'), getMoostMate().decorate('paramName', name), Resolve(() => eventCore.useRouteParams().get(name), name));
418
+ }
419
+ /**
420
+ * Get Parsed Params from url parh
421
+ * @decorator
422
+ * @paramType object
423
+ */
424
+ function Params() {
425
+ return Resolve(() => eventCore.useRouteParams().params, 'params');
426
+ }
427
+ /**
428
+ * Provide Const Value
429
+ * @decorator
430
+ * @param value - provided value
431
+ * @param label - label of the field
432
+ * @paramType unknown
433
+ */
434
+ function Const(value, label) {
435
+ return Resolve(() => value, label);
436
+ }
437
+ /**
438
+ * Provide Const Value from Factory fn
439
+ * @decorator
440
+ * @param factory - value Factory fn
441
+ * @param label - label of the field
442
+ * @paramType unknown
443
+ */
444
+ function ConstFactory(factory, label) {
445
+ return Resolve(async () => await factory(), label);
446
+ }
447
+ /**
448
+ * Resolves event logger from event context
449
+ * @param topic
450
+ * @returns Resolver to '@wooksjs/event-core' (EventLogger)
451
+ */
452
+ function InjectEventLogger(topic) {
453
+ return Resolve(() => eventCore.useEventLogger(topic));
454
+ }
455
+ function fillLabel(target, key, index, name) {
456
+ if (name) {
457
+ const meta = getMoostMate().read(target, key);
458
+ if (typeof index === 'number') {
459
+ if (!meta?.params ||
460
+ !meta?.params[index] ||
461
+ !meta?.params[index].label) {
462
+ Label(name)(target, key, index);
463
+ }
464
+ }
465
+ else {
466
+ if (!meta?.label) {
467
+ Label(name)(target, key);
468
+ }
469
+ }
470
+ }
511
471
  }
512
472
 
513
- /**
514
- * ## Injectable
515
- * ### @Decorator
516
- * Mark the Class as Injectable to enable it to be used in dependency injection
517
- * @param scope - Scope for injection ("FOR_EVENT" | "SINGLETON" | true)
518
- * FOR_EVENT - will create a new instance for each incoming request
519
- * SINGLETON | true - will create a new instance only once
520
- * @param label - field label
521
- */
522
- function Injectable(scope = true) {
523
- return getMoostMate().decorate('injectable', scope);
524
- }
525
- const insureInjectable = getMoostMate().decorate((meta) => {
526
- if (!meta.injectable)
527
- meta.injectable = true;
528
- return meta;
473
+ /**
474
+ * ## Injectable
475
+ * ### @Decorator
476
+ * Mark the Class as Injectable to enable it to be used in dependency injection
477
+ * @param scope - Scope for injection ("FOR_EVENT" | "SINGLETON" | true)
478
+ * FOR_EVENT - will create a new instance for each incoming request
479
+ * SINGLETON | true - will create a new instance only once
480
+ * @param label - field label
481
+ */
482
+ function Injectable(scope = true) {
483
+ return getMoostMate().decorate('injectable', scope);
484
+ }
485
+ const insureInjectable = getMoostMate().decorate((meta) => {
486
+ if (!meta.injectable)
487
+ meta.injectable = true;
488
+ return meta;
529
489
  });
530
490
 
531
- /**
532
- * ## Controller
533
- * ### @Decorator
534
- * Set Class as a Controller
535
- * @param prefix - define the prefix for all the paths of this controller
536
- */
537
- function Controller(prefix) {
538
- const mate = getMoostMate();
539
- return mate.apply(insureInjectable, mate.decorate('controller', { prefix: prefix || '' }));
540
- }
541
- function ImportController(prefix, controller, provide) {
542
- return getMoostMate().decorate('importController', {
543
- prefix: typeof prefix === 'string' ? prefix : undefined,
544
- typeResolver: typeof prefix === 'string'
545
- ? controller
546
- : prefix,
547
- provide: typeof prefix === 'string'
548
- ? provide || undefined
549
- : controller || undefined,
550
- }, true);
491
+ /**
492
+ * ## Controller
493
+ * ### @Decorator
494
+ * Set Class as a Controller
495
+ * @param prefix - define the prefix for all the paths of this controller
496
+ */
497
+ function Controller(prefix) {
498
+ const mate = getMoostMate();
499
+ return mate.apply(insureInjectable, mate.decorate('controller', { prefix: prefix || '' }));
500
+ }
501
+ function ImportController(prefix, controller, provide) {
502
+ return getMoostMate().decorate('importController', {
503
+ prefix: typeof prefix === 'string' ? prefix : undefined,
504
+ typeResolver: typeof prefix === 'string'
505
+ ? controller
506
+ : prefix,
507
+ provide: typeof prefix === 'string'
508
+ ? provide || undefined
509
+ : controller || undefined,
510
+ }, true);
551
511
  }
552
512
 
553
- function Circular(resolver) {
554
- return getMoostMate().decorate('circular', resolver);
513
+ function Circular(resolver) {
514
+ return getMoostMate().decorate('circular', resolver);
555
515
  }
556
516
 
557
- exports.TInterceptorPriority = void 0;
558
- (function (TInterceptorPriority) {
559
- TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
560
- TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
561
- TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
562
- TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
563
- TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
564
- TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
565
- TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
566
- })(exports.TInterceptorPriority || (exports.TInterceptorPriority = {}));
567
- /**
568
- * ## Intercept
569
- * ### @Decorator
570
- * Set interceptor
571
- * @param handler interceptor fn (use defineInterceptorFn)
572
- * @param priority interceptor priority
573
- * @returns
574
- */
575
- function Intercept(handler, priority) {
576
- return getMoostMate().decorate('interceptors', {
577
- handler,
578
- priority: priority ||
579
- handler.priority ||
580
- exports.TInterceptorPriority.INTERCEPTOR,
581
- }, true);
517
+ exports.TInterceptorPriority = void 0;
518
+ (function (TInterceptorPriority) {
519
+ TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
520
+ TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
521
+ TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
522
+ TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
523
+ TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
524
+ TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
525
+ TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
526
+ })(exports.TInterceptorPriority || (exports.TInterceptorPriority = {}));
527
+ /**
528
+ * ## Intercept
529
+ * ### @Decorator
530
+ * Set interceptor
531
+ * @param handler interceptor fn (use defineInterceptorFn)
532
+ * @param priority interceptor priority
533
+ * @returns
534
+ */
535
+ function Intercept(handler, priority) {
536
+ return getMoostMate().decorate('interceptors', {
537
+ handler,
538
+ priority: priority ||
539
+ handler.priority ||
540
+ exports.TInterceptorPriority.INTERCEPTOR,
541
+ }, true);
582
542
  }
583
543
 
584
- /**
585
- * ## Provide
586
- * ### @Decorator
587
- * Defines provide registry for class (and all the children)
588
- * @param type - string or class constructor
589
- * @param fn - factory function for provided value
590
- */
591
- function Provide(type, fn) {
592
- return getMoostMate().decorate((meta) => {
593
- meta.provide = meta.provide || {};
594
- Object.assign(meta.provide, infact$1.createProvideRegistry([type, fn]));
595
- return meta;
596
- });
597
- }
598
- /**
599
- * ## Inject
600
- * ### @Decorator
601
- * Defines a key from provide registry to inject value
602
- * (For optional values use with @Optional())
603
- * @param type - string or class constructor
604
- */
605
- function Inject(type) {
606
- return getMoostMate().decorate('inject', type);
544
+ /**
545
+ * ## Provide
546
+ * ### @Decorator
547
+ * Defines provide registry for class (and all the children)
548
+ * @param type - string or class constructor
549
+ * @param fn - factory function for provided value
550
+ */
551
+ function Provide(type, fn) {
552
+ return getMoostMate().decorate((meta) => {
553
+ meta.provide = meta.provide || {};
554
+ Object.assign(meta.provide, infact$1.createProvideRegistry([type, fn]));
555
+ return meta;
556
+ });
557
+ }
558
+ /**
559
+ * ## Inject
560
+ * ### @Decorator
561
+ * Defines a key from provide registry to inject value
562
+ * (For optional values use with @Optional())
563
+ * @param type - string or class constructor
564
+ */
565
+ function Inject(type) {
566
+ return getMoostMate().decorate('inject', type);
607
567
  }
608
568
 
609
- /**
610
- * ## Inherit
611
- * ### @Decorator
612
- * Inherit metadata from super class
613
- * @returns
614
- */
569
+ /**
570
+ * ## Inherit
571
+ * ### @Decorator
572
+ * Inherit metadata from super class
573
+ * @returns
574
+ */
615
575
  const Inherit = () => getMoostMate().decorate('inherit', true);
616
576
 
617
- exports.TPipePriority = void 0;
618
- (function (TPipePriority) {
619
- TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
620
- TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
621
- TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
622
- TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
623
- TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
624
- TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
625
- TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
626
- TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
627
- TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
577
+ exports.TPipePriority = void 0;
578
+ (function (TPipePriority) {
579
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
580
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
581
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
582
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
583
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
584
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
585
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
586
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
587
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
628
588
  })(exports.TPipePriority || (exports.TPipePriority = {}));
629
589
 
630
- /**
631
- * ## Pipe
632
- * ### @Decorator
633
- * Attach pipe
634
- * @param handler pipe handler
635
- * @param priority pipe priority
636
- * @returns
637
- */
638
- function Pipe(handler, priority) {
639
- if (typeof priority !== 'number') {
640
- priority =
641
- typeof handler.priority === 'number'
642
- ? handler.priority
643
- : exports.TPipePriority.TRANSFORM;
644
- }
645
- return getMoostMate().decorate('pipes', { handler, priority }, true);
590
+ /**
591
+ * ## Pipe
592
+ * ### @Decorator
593
+ * Attach pipe
594
+ * @param handler pipe handler
595
+ * @param priority pipe priority
596
+ * @returns
597
+ */
598
+ function Pipe(handler, priority) {
599
+ if (typeof priority !== 'number') {
600
+ priority =
601
+ typeof handler.priority === 'number'
602
+ ? handler.priority
603
+ : exports.TPipePriority.TRANSFORM;
604
+ }
605
+ return getMoostMate().decorate('pipes', { handler, priority }, true);
646
606
  }
647
607
 
648
- /**
649
- * ### Define Interceptor Function
650
- *
651
- * ```ts
652
- * defineInterceptorFn((before, after, onError) => {
653
- * //init
654
- * before(() => {
655
- * // before handler
656
- * })
657
- * after((response, reply) => {
658
- * // after handler
659
- * })
660
- * onError((error, reply) => {
661
- * // when error occured
662
- * })
663
- * },
664
- * TInterceptorPriority.INTERCEPTOR,
665
- * )
666
- * ```
667
- *
668
- * @param fn interceptor function
669
- * @param priority priority of the interceptor where BEFORE_ALL = 0, BEFORE_GUARD = 1, GUARD = 2, AFTER_GUARD = 3, INTERCEPTOR = 4, CATCH_ERROR = 5, AFTER_ALL = 6
670
- * @returns
671
- */
672
- function defineInterceptorFn(fn, priority = exports.TInterceptorPriority.INTERCEPTOR) {
673
- fn.priority = priority;
674
- return fn;
675
- }
676
- /**
677
- * ### Define Pipe Function
678
- *
679
- * ```ts
680
- * // example of a transform pipe
681
- * const uppercaseTransformPipe = definePipeFn((value, metas, level) => {
682
- * return typeof value === 'string' ? value.toUpperCase() : value
683
- * },
684
- * TPipePriority.TRANSFORM,
685
- * )
686
- * ```
687
- *
688
- * @param fn interceptor function
689
- * @param priority priority of the pipe where BEFORE_RESOLVE = 0, RESOLVE = 1, AFTER_RESOLVE = 2, BEFORE_TRANSFORM = 3, TRANSFORM = 4, AFTER_TRANSFORM = 5, BEFORE_VALIDATE = 6, VALIDATE = 7, AFTER_VALIDATE = 8
690
- * @returns
691
- */
692
- function definePipeFn(fn, priority = exports.TPipePriority.TRANSFORM) {
693
- fn.priority = priority;
694
- return fn;
608
+ /**
609
+ * ### Define Interceptor Function
610
+ *
611
+ * ```ts
612
+ * defineInterceptorFn((before, after, onError) => {
613
+ * //init
614
+ * before(() => {
615
+ * // before handler
616
+ * })
617
+ * after((response, reply) => {
618
+ * // after handler
619
+ * })
620
+ * onError((error, reply) => {
621
+ * // when error occured
622
+ * })
623
+ * },
624
+ * TInterceptorPriority.INTERCEPTOR,
625
+ * )
626
+ * ```
627
+ *
628
+ * @param fn interceptor function
629
+ * @param priority priority of the interceptor where BEFORE_ALL = 0, BEFORE_GUARD = 1, GUARD = 2, AFTER_GUARD = 3, INTERCEPTOR = 4, CATCH_ERROR = 5, AFTER_ALL = 6
630
+ * @returns
631
+ */
632
+ function defineInterceptorFn(fn, priority = exports.TInterceptorPriority.INTERCEPTOR) {
633
+ fn.priority = priority;
634
+ return fn;
635
+ }
636
+ /**
637
+ * ### Define Pipe Function
638
+ *
639
+ * ```ts
640
+ * // example of a transform pipe
641
+ * const uppercaseTransformPipe = definePipeFn((value, metas, level) => {
642
+ * return typeof value === 'string' ? value.toUpperCase() : value
643
+ * },
644
+ * TPipePriority.TRANSFORM,
645
+ * )
646
+ * ```
647
+ *
648
+ * @param fn interceptor function
649
+ * @param priority priority of the pipe where BEFORE_RESOLVE = 0, RESOLVE = 1, AFTER_RESOLVE = 2, BEFORE_TRANSFORM = 3, TRANSFORM = 4, AFTER_TRANSFORM = 5, BEFORE_VALIDATE = 6, VALIDATE = 7, AFTER_VALIDATE = 8
650
+ * @returns
651
+ */
652
+ function definePipeFn(fn, priority = exports.TPipePriority.TRANSFORM) {
653
+ fn.priority = priority;
654
+ return fn;
695
655
  }
696
656
 
697
- const resolvePipe = definePipeFn((_value, metas, level) => {
698
- var _a;
699
- const resolver = (_a = metas.targetMeta) === null || _a === void 0 ? void 0 : _a.resolver;
700
- if (resolver) {
701
- return resolver(metas, level);
702
- }
703
- return undefined;
657
+ const resolvePipe = definePipeFn((_value, metas, level) => {
658
+ const resolver = metas.targetMeta?.resolver;
659
+ if (resolver) {
660
+ return resolver(metas, level);
661
+ }
662
+ return undefined;
704
663
  }, exports.TPipePriority.RESOLVE);
705
664
 
706
- const sharedPipes = [
707
- {
708
- handler: resolvePipe,
709
- priority: exports.TPipePriority.RESOLVE,
710
- },
665
+ const sharedPipes = [
666
+ {
667
+ handler: resolvePipe,
668
+ priority: exports.TPipePriority.RESOLVE,
669
+ },
711
670
  ];
712
671
 
713
- function getDefaultLogger(topic) {
714
- return new logger.ProstoLogger({
715
- level: 4,
716
- transports: [
717
- logger.createConsoleTransort({
718
- format: logger.coloredConsole,
719
- }),
720
- ],
721
- }, topic);
672
+ function getDefaultLogger(topic) {
673
+ return new logger.ProstoLogger({
674
+ level: 4,
675
+ transports: [
676
+ logger.createConsoleTransort({
677
+ format: logger.coloredConsole,
678
+ }),
679
+ ],
680
+ }, topic);
722
681
  }
723
682
 
724
- /**
725
- * ## Moost
726
- * Main moostjs class that serves as a shell for Moost Adapters
727
- *
728
- * ### Usage with HTTP Adapter
729
- * ```ts
730
- * │ // HTTP server example
731
- * │ import { MoostHttp, Get } from '@moostjs/event-http'
732
- * │ import { Moost, Param } from 'moost'
733
- * │
734
- * │ class MyServer extends Moost {
735
- * │ @Get('test/:name')
736
- * │ test(@Param('name') name: string) {
737
- * │ return { message: `Hello ${name}!` }
738
- * │ }
739
- * │ }
740
- * │
741
- * │ const app = new MyServer()
742
- * │ const http = new MoostHttp()
743
- * │ app.adapter(http).listen(3000, () => {
744
- * │ app.getLogger('MyApp').log('Up on port 3000')
745
- * │ })
746
- * │ app.init()
747
- * ```
748
- * ### Usage with CLI Adapter
749
- * ```ts
750
- * │ // CLI example
751
- * │ import { MoostCli, Cli, CliOption, cliHelpInterceptor } from '@moostjs/event-cli'
752
- * │ import { Moost, Param } from 'moost'
753
- * │
754
- * │ class MyApp extends Moost {
755
- * │ @Cli('command/:arg')
756
- * │ command(
757
- * │ @Param('arg')
758
- * │ arg: string,
759
- * │ @CliOption('test', 't')
760
- * │ test: boolean,
761
- * │ ) {
762
- * │ return `command run with flag arg=${ arg }, test=${ test }`
763
- * │ }
764
- * │ }
765
- * │
766
- * │ const app = new MyApp()
767
- * │ app.applyGlobalInterceptors(cliHelpInterceptor())
768
- * │
769
- * │ const cli = new MoostCli()
770
- * │ app.adapter(cli)
771
- * │ app.init()
772
- * ```
773
- */
774
- class Moost {
775
- constructor(options) {
776
- this.options = options;
777
- this.pipes = [...sharedPipes];
778
- this.interceptors = [];
779
- this.adapters = [];
780
- this.controllersOverview = [];
781
- this.provide = infact$1.createProvideRegistry([infact$1.Infact, getMoostInfact], [mate$1.Mate, getMoostMate]);
782
- this.unregisteredControllers = [];
783
- this.logger = (options === null || options === void 0 ? void 0 : options.logger) || getDefaultLogger('moost');
784
- getMoostInfact().setLogger(this.getLogger('infact'));
785
- const mate = getMoostMate();
786
- Object.assign(mate, { logger: this.getLogger('mate') });
787
- }
788
- /**
789
- * ### getLogger
790
- * Provides application logger
791
- * ```js
792
- * // get logger with topic = "App"
793
- * const logger = app.getLogger('App')
794
- * logger.log('...')
795
- * ```
796
- * @param topic
797
- * @returns
798
- */
799
- getLogger(topic) {
800
- if (this.logger instanceof logger.ProstoLogger) {
801
- return this.logger.createTopic(topic);
802
- }
803
- return this.logger;
804
- }
805
- adapter(a) {
806
- this.adapters.push(a);
807
- return a;
808
- }
809
- getControllersOverview() {
810
- return this.controllersOverview;
811
- }
812
- /**
813
- * ### init
814
- * Ititializes adapter. Must be called after adapters are attached.
815
- */
816
- init() {
817
- return __awaiter(this, void 0, void 0, function* () {
818
- this.setProvideRegistry(infact$1.createProvideRegistry([Moost, () => this], [logger.ProstoLogger, () => this.logger], ['MOOST_LOGGER', () => this.logger]));
819
- for (const a of this.adapters) {
820
- const constructor = mate$1.getConstructor(a);
821
- if (constructor) {
822
- this.setProvideRegistry(infact$1.createProvideRegistry([
823
- constructor,
824
- () => a,
825
- ]));
826
- }
827
- if (typeof a.getProvideRegistry === 'function') {
828
- this.setProvideRegistry(a.getProvideRegistry());
829
- }
830
- }
831
- this.unregisteredControllers.unshift(this);
832
- yield this.bindControllers();
833
- for (const a of this.adapters) {
834
- yield (a.onInit && a.onInit(this));
835
- }
836
- });
837
- }
838
- bindControllers() {
839
- var _a;
840
- return __awaiter(this, void 0, void 0, function* () {
841
- const infact = getMoostInfact();
842
- infact.setLogger(this.logger);
843
- const meta = getMoostMate();
844
- const thisMeta = meta.read(this);
845
- const provide = Object.assign(Object.assign({}, ((thisMeta === null || thisMeta === void 0 ? void 0 : thisMeta.provide) || {})), this.provide);
846
- for (const _controller of this.unregisteredControllers) {
847
- let newPrefix = undefined;
848
- let controller = _controller;
849
- if (Array.isArray(_controller) && typeof _controller[0] === 'string') {
850
- newPrefix = _controller[0];
851
- controller = _controller[1];
852
- }
853
- yield this.bindController(controller, provide, ((_a = this.options) === null || _a === void 0 ? void 0 : _a.globalPrefix) || '', newPrefix);
854
- }
855
- this.unregisteredControllers = [];
856
- });
857
- }
858
- bindController(controller, provide, globalPrefix, replaceOwnPrefix) {
859
- var _a;
860
- return __awaiter(this, void 0, void 0, function* () {
861
- const mate = getMoostMate();
862
- const classMeta = mate.read(controller);
863
- const infact = getMoostInfact();
864
- const isControllerConsructor = mate$1.isConstructor(controller);
865
- const pipes = [...this.pipes, ...((classMeta === null || classMeta === void 0 ? void 0 : classMeta.pipes) || [])].sort((a, b) => a.priority - b.priority);
866
- let instance;
867
- const infactOpts = { provide, customData: { pipes } };
868
- if (isControllerConsructor &&
869
- ((classMeta === null || classMeta === void 0 ? void 0 : classMeta.injectable) === 'SINGLETON' ||
870
- (classMeta === null || classMeta === void 0 ? void 0 : classMeta.injectable) === true)) {
871
- instance = (yield infact.get(controller, infactOpts));
872
- }
873
- else if (!isControllerConsructor) {
874
- instance = controller;
875
- infact.setProvideRegByInstance(instance, provide);
876
- }
877
- // getInstance - instance factory for resolving SINGLETON and FOR_EVENT instance
878
- const getInstance = instance
879
- ? () => Promise.resolve(instance)
880
- : () => __awaiter(this, void 0, void 0, function* () {
881
- // if (!instance) {
882
- infact.silent(true);
883
- const { restoreCtx } = eventCore.useEventContext();
884
- const instance = (yield infact.get(controller, Object.assign(Object.assign({}, infactOpts), { syncContextFn: restoreCtx })));
885
- infact.silent(false);
886
- // }
887
- return instance;
888
- });
889
- const classConstructor = mate$1.isConstructor(controller)
890
- ? controller
891
- : mate$1.getConstructor(controller);
892
- this.controllersOverview.push(yield bindControllerMethods({
893
- getInstance,
894
- classConstructor,
895
- adapters: this.adapters,
896
- globalPrefix,
897
- replaceOwnPrefix,
898
- interceptors: [...this.interceptors],
899
- pipes,
900
- provide: (classMeta === null || classMeta === void 0 ? void 0 : classMeta.provide) || {},
901
- logger: this.logger,
902
- }));
903
- if (classMeta && classMeta.importController) {
904
- const prefix = typeof replaceOwnPrefix === 'string'
905
- ? replaceOwnPrefix
906
- : (_a = classMeta === null || classMeta === void 0 ? void 0 : classMeta.controller) === null || _a === void 0 ? void 0 : _a.prefix;
907
- const mergedProvide = Object.assign(Object.assign({}, provide), ((classMeta === null || classMeta === void 0 ? void 0 : classMeta.provide) || {}));
908
- for (const ic of classMeta.importController) {
909
- if (ic.typeResolver) {
910
- const isConstr = mate$1.isConstructor(ic.typeResolver);
911
- const isFunc = typeof ic.typeResolver === 'function';
912
- yield this.bindController(
913
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
914
- isConstr
915
- ? ic.typeResolver
916
- : isFunc
917
- ? yield ic.typeResolver()
918
- : ic.typeResolver, ic.provide
919
- ? Object.assign(Object.assign({}, mergedProvide), ic.provide) : mergedProvide, `${globalPrefix}/${prefix || ''}`, ic.prefix);
920
- }
921
- }
922
- }
923
- });
924
- }
925
- applyGlobalPipes(...items) {
926
- for (const item of items) {
927
- if (typeof item === 'function') {
928
- this.pipes.push({
929
- handler: item,
930
- priority: typeof item.priority === 'number'
931
- ? item.priority
932
- : exports.TPipePriority.TRANSFORM,
933
- });
934
- }
935
- else {
936
- this.pipes.push({
937
- handler: item.handler,
938
- priority: item.priority,
939
- });
940
- }
941
- }
942
- this.globalInterceptorHandler = undefined;
943
- return this;
944
- }
945
- /**
946
- * Provides InterceptorHandler with global interceptors and pipes.
947
- * Used to process interceptors when event handler was not found.
948
- *
949
- * @returns IterceptorHandler
950
- */
951
- getGlobalInterceptorHandler() {
952
- if (!this.globalInterceptorHandler) {
953
- const mate = getMoostMate();
954
- const thisMeta = mate.read(this);
955
- const pipes = [...(this.pipes || []), ...((thisMeta === null || thisMeta === void 0 ? void 0 : thisMeta.pipes) || [])].sort((a, b) => a.priority - b.priority);
956
- const interceptors = [...this.interceptors, ...((thisMeta === null || thisMeta === void 0 ? void 0 : thisMeta.interceptors) || [])]
957
- .sort((a, b) => a.priority - b.priority);
958
- this.globalInterceptorHandler = getIterceptorHandlerFactory(interceptors, () => Promise.resolve(this), pipes, this.logger);
959
- }
960
- return this.globalInterceptorHandler();
961
- }
962
- applyGlobalInterceptors(...items) {
963
- for (const item of items) {
964
- if (typeof item === 'function') {
965
- this.interceptors.push({
966
- handler: item,
967
- priority: typeof item.priority === 'number'
968
- ? item
969
- .priority
970
- : exports.TInterceptorPriority.INTERCEPTOR,
971
- });
972
- }
973
- else {
974
- this.interceptors.push({
975
- handler: item.handler,
976
- priority: item.priority,
977
- });
978
- }
979
- }
980
- this.globalInterceptorHandler = undefined;
981
- return this;
982
- }
983
- /**
984
- * Register new entried to provide as dependency injections
985
- * @param provide - Provide Registry (use createProvideRegistry from '\@prostojs/infact')
986
- * @returns
987
- */
988
- setProvideRegistry(provide) {
989
- this.provide = Object.assign(Object.assign({}, this.provide), provide);
990
- return this;
991
- }
992
- /**
993
- * Register controllers (similar to @ImportController decorator)
994
- * @param controllers - list of target controllers (instances)
995
- * @returns
996
- */
997
- registerControllers(...controllers) {
998
- this.unregisteredControllers.push(...controllers);
999
- return this;
1000
- }
683
+ /**
684
+ * ## Moost
685
+ * Main moostjs class that serves as a shell for Moost Adapters
686
+ *
687
+ * ### Usage with HTTP Adapter
688
+ * ```ts
689
+ * │ // HTTP server example
690
+ * │ import { MoostHttp, Get } from '@moostjs/event-http'
691
+ * │ import { Moost, Param } from 'moost'
692
+ * │
693
+ * │ class MyServer extends Moost {
694
+ * │ @Get('test/:name')
695
+ * │ test(@Param('name') name: string) {
696
+ * │ return { message: `Hello ${name}!` }
697
+ * │ }
698
+ * │ }
699
+ * │
700
+ * │ const app = new MyServer()
701
+ * │ const http = new MoostHttp()
702
+ * │ app.adapter(http).listen(3000, () => {
703
+ * │ app.getLogger('MyApp').log('Up on port 3000')
704
+ * │ })
705
+ * │ app.init()
706
+ * ```
707
+ * ### Usage with CLI Adapter
708
+ * ```ts
709
+ * │ // CLI example
710
+ * │ import { MoostCli, Cli, CliOption, cliHelpInterceptor } from '@moostjs/event-cli'
711
+ * │ import { Moost, Param } from 'moost'
712
+ * │
713
+ * │ class MyApp extends Moost {
714
+ * │ @Cli('command/:arg')
715
+ * │ command(
716
+ * │ @Param('arg')
717
+ * │ arg: string,
718
+ * │ @CliOption('test', 't')
719
+ * │ test: boolean,
720
+ * │ ) {
721
+ * │ return `command run with flag arg=${ arg }, test=${ test }`
722
+ * │ }
723
+ * │ }
724
+ * │
725
+ * │ const app = new MyApp()
726
+ * │ app.applyGlobalInterceptors(cliHelpInterceptor())
727
+ * │
728
+ * │ const cli = new MoostCli()
729
+ * │ app.adapter(cli)
730
+ * │ app.init()
731
+ * ```
732
+ */
733
+ class Moost {
734
+ constructor(options) {
735
+ this.options = options;
736
+ this.pipes = [...sharedPipes];
737
+ this.interceptors = [];
738
+ this.adapters = [];
739
+ this.controllersOverview = [];
740
+ this.provide = infact$1.createProvideRegistry([infact$1.Infact, getMoostInfact], [mate$1.Mate, getMoostMate]);
741
+ this.unregisteredControllers = [];
742
+ this.logger = options?.logger || getDefaultLogger('moost');
743
+ getMoostInfact().setLogger(this.getLogger('infact'));
744
+ const mate = getMoostMate();
745
+ Object.assign(mate, { logger: this.getLogger('mate') });
746
+ }
747
+ /**
748
+ * ### getLogger
749
+ * Provides application logger
750
+ * ```js
751
+ * // get logger with topic = "App"
752
+ * const logger = app.getLogger('App')
753
+ * logger.log('...')
754
+ * ```
755
+ * @param topic
756
+ * @returns
757
+ */
758
+ getLogger(topic) {
759
+ if (this.logger instanceof logger.ProstoLogger) {
760
+ return this.logger.createTopic(topic);
761
+ }
762
+ return this.logger;
763
+ }
764
+ adapter(a) {
765
+ this.adapters.push(a);
766
+ return a;
767
+ }
768
+ getControllersOverview() {
769
+ return this.controllersOverview;
770
+ }
771
+ /**
772
+ * ### init
773
+ * Ititializes adapter. Must be called after adapters are attached.
774
+ */
775
+ async init() {
776
+ this.setProvideRegistry(infact$1.createProvideRegistry([Moost, () => this], [logger.ProstoLogger, () => this.logger], ['MOOST_LOGGER', () => this.logger]));
777
+ for (const a of this.adapters) {
778
+ const constructor = mate$1.getConstructor(a);
779
+ if (constructor) {
780
+ this.setProvideRegistry(infact$1.createProvideRegistry([
781
+ constructor,
782
+ () => a,
783
+ ]));
784
+ }
785
+ if (typeof a.getProvideRegistry === 'function') {
786
+ this.setProvideRegistry(a.getProvideRegistry());
787
+ }
788
+ }
789
+ this.unregisteredControllers.unshift(this);
790
+ await this.bindControllers();
791
+ for (const a of this.adapters) {
792
+ await (a.onInit && a.onInit(this));
793
+ }
794
+ }
795
+ async bindControllers() {
796
+ const infact = getMoostInfact();
797
+ infact.setLogger(this.logger);
798
+ const meta = getMoostMate();
799
+ const thisMeta = meta.read(this);
800
+ const provide = { ...(thisMeta?.provide || {}), ...this.provide };
801
+ for (const _controller of this.unregisteredControllers) {
802
+ let newPrefix = undefined;
803
+ let controller = _controller;
804
+ if (Array.isArray(_controller) && typeof _controller[0] === 'string') {
805
+ newPrefix = _controller[0];
806
+ controller = _controller[1];
807
+ }
808
+ await this.bindController(controller, provide, this.options?.globalPrefix || '', newPrefix);
809
+ }
810
+ this.unregisteredControllers = [];
811
+ }
812
+ async bindController(controller, provide, globalPrefix, replaceOwnPrefix) {
813
+ const mate = getMoostMate();
814
+ const classMeta = mate.read(controller);
815
+ const infact = getMoostInfact();
816
+ const isControllerConsructor = mate$1.isConstructor(controller);
817
+ const pipes = [...this.pipes, ...(classMeta?.pipes || [])].sort((a, b) => a.priority - b.priority);
818
+ let instance;
819
+ const infactOpts = { provide, customData: { pipes } };
820
+ if (isControllerConsructor &&
821
+ (classMeta?.injectable === 'SINGLETON' ||
822
+ classMeta?.injectable === true)) {
823
+ instance = (await infact.get(controller, infactOpts));
824
+ }
825
+ else if (!isControllerConsructor) {
826
+ instance = controller;
827
+ infact.setProvideRegByInstance(instance, provide);
828
+ }
829
+ // getInstance - instance factory for resolving SINGLETON and FOR_EVENT instance
830
+ const getInstance = instance
831
+ ? () => Promise.resolve(instance)
832
+ : async () => {
833
+ // if (!instance) {
834
+ infact.silent(true);
835
+ const { restoreCtx } = eventCore.useEventContext();
836
+ const instance = (await infact.get(controller, { ...infactOpts, syncContextFn: restoreCtx }));
837
+ infact.silent(false);
838
+ // }
839
+ return instance;
840
+ };
841
+ const classConstructor = mate$1.isConstructor(controller)
842
+ ? controller
843
+ : mate$1.getConstructor(controller);
844
+ this.controllersOverview.push(await bindControllerMethods({
845
+ getInstance,
846
+ classConstructor,
847
+ adapters: this.adapters,
848
+ globalPrefix,
849
+ replaceOwnPrefix,
850
+ interceptors: [...this.interceptors],
851
+ pipes,
852
+ provide: classMeta?.provide || {},
853
+ logger: this.logger,
854
+ }));
855
+ if (classMeta && classMeta.importController) {
856
+ const prefix = typeof replaceOwnPrefix === 'string'
857
+ ? replaceOwnPrefix
858
+ : classMeta?.controller?.prefix;
859
+ const mergedProvide = { ...provide, ...(classMeta?.provide || {}) };
860
+ for (const ic of classMeta.importController) {
861
+ if (ic.typeResolver) {
862
+ const isConstr = mate$1.isConstructor(ic.typeResolver);
863
+ const isFunc = typeof ic.typeResolver === 'function';
864
+ await this.bindController(
865
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
866
+ isConstr
867
+ ? ic.typeResolver
868
+ : isFunc
869
+ ? await ic.typeResolver()
870
+ : ic.typeResolver, ic.provide
871
+ ? { ...mergedProvide, ...ic.provide }
872
+ : mergedProvide, `${globalPrefix}/${prefix || ''}`, ic.prefix);
873
+ }
874
+ }
875
+ }
876
+ }
877
+ applyGlobalPipes(...items) {
878
+ for (const item of items) {
879
+ if (typeof item === 'function') {
880
+ this.pipes.push({
881
+ handler: item,
882
+ priority: typeof item.priority === 'number'
883
+ ? item.priority
884
+ : exports.TPipePriority.TRANSFORM,
885
+ });
886
+ }
887
+ else {
888
+ this.pipes.push({
889
+ handler: item.handler,
890
+ priority: item.priority,
891
+ });
892
+ }
893
+ }
894
+ this.globalInterceptorHandler = undefined;
895
+ return this;
896
+ }
897
+ /**
898
+ * Provides InterceptorHandler with global interceptors and pipes.
899
+ * Used to process interceptors when event handler was not found.
900
+ *
901
+ * @returns IterceptorHandler
902
+ */
903
+ getGlobalInterceptorHandler() {
904
+ if (!this.globalInterceptorHandler) {
905
+ const mate = getMoostMate();
906
+ const thisMeta = mate.read(this);
907
+ const pipes = [...(this.pipes || []), ...(thisMeta?.pipes || [])].sort((a, b) => a.priority - b.priority);
908
+ const interceptors = [...this.interceptors, ...(thisMeta?.interceptors || [])]
909
+ .sort((a, b) => a.priority - b.priority);
910
+ this.globalInterceptorHandler = getIterceptorHandlerFactory(interceptors, () => Promise.resolve(this), pipes, this.logger);
911
+ }
912
+ return this.globalInterceptorHandler();
913
+ }
914
+ applyGlobalInterceptors(...items) {
915
+ for (const item of items) {
916
+ if (typeof item === 'function') {
917
+ this.interceptors.push({
918
+ handler: item,
919
+ priority: typeof item.priority === 'number'
920
+ ? item
921
+ .priority
922
+ : exports.TInterceptorPriority.INTERCEPTOR,
923
+ });
924
+ }
925
+ else {
926
+ this.interceptors.push({
927
+ handler: item.handler,
928
+ priority: item.priority,
929
+ });
930
+ }
931
+ }
932
+ this.globalInterceptorHandler = undefined;
933
+ return this;
934
+ }
935
+ /**
936
+ * Register new entried to provide as dependency injections
937
+ * @param provide - Provide Registry (use createProvideRegistry from '\@prostojs/infact')
938
+ * @returns
939
+ */
940
+ setProvideRegistry(provide) {
941
+ this.provide = { ...this.provide, ...provide };
942
+ return this;
943
+ }
944
+ /**
945
+ * Register controllers (similar to @ImportController decorator)
946
+ * @param controllers - list of target controllers (instances)
947
+ * @returns
948
+ */
949
+ registerControllers(...controllers) {
950
+ this.unregisteredControllers.push(...controllers);
951
+ return this;
952
+ }
1001
953
  }
1002
954
 
1003
- function setControllerContext(controller, method) {
1004
- const { store } = eventCore.useEventContext();
1005
- const { set } = store('controller');
1006
- set('instance', controller);
1007
- set('method', method);
1008
- }
1009
- function useControllerContext() {
1010
- const { store } = eventCore.useEventContext();
1011
- const { get } = store('controller');
1012
- const getController = () => get('instance');
1013
- const getMethod = () => get('method');
1014
- // todo: add generic types to getControllerMeta
1015
- const getControllerMeta = () => getMoostMate().read(getController());
1016
- // todo: add generic types to getMethodMeta
1017
- const getMethodMeta = (name) => getMoostMate().read(getController(), name || getMethod());
1018
- function instantiate(c) {
1019
- return getMoostInfact().getForInstance(getController(), c);
1020
- }
1021
- return {
1022
- instantiate,
1023
- getController,
1024
- getMethod,
1025
- getControllerMeta,
1026
- getMethodMeta,
1027
- getPropertiesList: () => { var _a; return ((_a = getControllerMeta()) === null || _a === void 0 ? void 0 : _a.properties) || []; },
1028
- getScope: () => { var _a; return ((_a = getControllerMeta()) === null || _a === void 0 ? void 0 : _a.injectable) || 'SINGLETON'; },
1029
- getParamsMeta: () => { var _a; return ((_a = getMethodMeta()) === null || _a === void 0 ? void 0 : _a.params) || []; },
1030
- getPropMeta: (name) => getMethodMeta(name),
1031
- };
955
+ function setControllerContext(controller, method) {
956
+ const { store } = eventCore.useEventContext();
957
+ const { set } = store('controller');
958
+ set('instance', controller);
959
+ set('method', method);
960
+ }
961
+ function useControllerContext() {
962
+ const { store } = eventCore.useEventContext();
963
+ const { get } = store('controller');
964
+ const getController = () => get('instance');
965
+ const getMethod = () => get('method');
966
+ // todo: add generic types to getControllerMeta
967
+ const getControllerMeta = () => getMoostMate().read(getController());
968
+ // todo: add generic types to getMethodMeta
969
+ const getMethodMeta = (name) => getMoostMate().read(getController(), name || getMethod());
970
+ function instantiate(c) {
971
+ return getMoostInfact().getForInstance(getController(), c);
972
+ }
973
+ return {
974
+ instantiate,
975
+ getController,
976
+ getMethod,
977
+ getControllerMeta,
978
+ getMethodMeta,
979
+ getPropertiesList: () => getControllerMeta()?.properties || [],
980
+ getScope: () => getControllerMeta()?.injectable || 'SINGLETON',
981
+ getParamsMeta: () => getMethodMeta()?.params || [],
982
+ getPropMeta: (name) => getMethodMeta(name),
983
+ };
1032
984
  }
1033
985
 
1034
- const infact = getMoostInfact();
1035
- function registerEventScope(scopeId) {
1036
- infact.registerScope(scopeId);
1037
- return () => infact.unregisterScope(scopeId);
1038
- }
1039
- function defineMoostEventHandler(options) {
1040
- return () => __awaiter(this, void 0, void 0, function* () {
1041
- var _a;
1042
- const { restoreCtx } = eventCore.useEventContext(options.contextType);
1043
- const scopeId = eventCore.useEventId().getId();
1044
- const logger = eventCore.useEventLogger(options.loggerTitle);
1045
- const unscope = registerEventScope(scopeId);
1046
- let response;
1047
- const hookOptions = {
1048
- restoreCtx,
1049
- scopeId,
1050
- logger,
1051
- unscope,
1052
- method: options.controllerMethod,
1053
- getResponse: () => response,
1054
- reply: (r) => response = r,
1055
- };
1056
- if ((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init) {
1057
- yield options.hooks.init(hookOptions);
1058
- restoreCtx();
1059
- }
1060
- const instance = yield options.getControllerInstance();
1061
- restoreCtx();
1062
- if (instance) {
1063
- setControllerContext(instance, options.controllerMethod || '');
1064
- }
1065
- const interceptorHandler = yield options.getIterceptorHandler();
1066
- if (interceptorHandler) {
1067
- restoreCtx();
1068
- try {
1069
- response = yield interceptorHandler.init();
1070
- if (typeof response !== 'undefined')
1071
- return endWithResponse();
1072
- }
1073
- catch (e) {
1074
- options.logErrors && logger.error(e);
1075
- response = e;
1076
- return endWithResponse(true);
1077
- }
1078
- }
1079
- let args = [];
1080
- if (options.resolveArgs) {
1081
- // params
1082
- restoreCtx();
1083
- try {
1084
- // logger.trace(`resolving method args for "${ opts.method as string }"`)
1085
- args = yield options.resolveArgs();
1086
- // logger.trace(`args for method "${ opts.method as string }" resolved (count ${String(args.length)})`)
1087
- }
1088
- catch (e) {
1089
- options.logErrors && logger.error(e);
1090
- response = e;
1091
- return endWithResponse(true);
1092
- }
1093
- }
1094
- if (interceptorHandler) {
1095
- restoreCtx();
1096
- response = yield interceptorHandler.fireBefore(response);
1097
- if (typeof response !== 'undefined')
1098
- return endWithResponse();
1099
- }
1100
- // fire request handler
1101
- const callControllerMethod = () => {
1102
- restoreCtx();
1103
- if (options.callControllerMethod) {
1104
- return options.callControllerMethod(args);
1105
- }
1106
- else if (instance && options.controllerMethod && typeof instance[options.controllerMethod] === 'function') {
1107
- return instance[options.controllerMethod](...args);
1108
- }
1109
- };
1110
- try {
1111
- response = callControllerMethod();
1112
- }
1113
- catch (e) {
1114
- options.logErrors && logger.error(e);
1115
- response = e;
1116
- return endWithResponse(true);
1117
- }
1118
- function endWithResponse(raise = false) {
1119
- var _a;
1120
- return __awaiter(this, void 0, void 0, function* () {
1121
- // fire after interceptors
1122
- if (interceptorHandler) {
1123
- restoreCtx();
1124
- try {
1125
- // logger.trace('firing after interceptors')
1126
- response = yield interceptorHandler.fireAfter(response);
1127
- }
1128
- catch (e) {
1129
- options.logErrors && logger.error(e);
1130
- if (!options.manualUnscope) {
1131
- unscope();
1132
- }
1133
- throw e;
1134
- }
1135
- }
1136
- if (!options.manualUnscope) {
1137
- unscope();
1138
- }
1139
- if ((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.end) {
1140
- yield options.hooks.end(hookOptions);
1141
- }
1142
- if (raise) {
1143
- throw response;
1144
- }
1145
- return response;
1146
- });
1147
- }
1148
- return yield endWithResponse();
1149
- });
986
+ const infact = getMoostInfact();
987
+ function registerEventScope(scopeId) {
988
+ infact.registerScope(scopeId);
989
+ return () => infact.unregisterScope(scopeId);
990
+ }
991
+ function defineMoostEventHandler(options) {
992
+ return async () => {
993
+ const { restoreCtx } = eventCore.useEventContext(options.contextType);
994
+ const scopeId = eventCore.useEventId().getId();
995
+ const logger = eventCore.useEventLogger(options.loggerTitle);
996
+ const unscope = registerEventScope(scopeId);
997
+ let response;
998
+ const hookOptions = {
999
+ restoreCtx,
1000
+ scopeId,
1001
+ logger,
1002
+ unscope,
1003
+ method: options.controllerMethod,
1004
+ getResponse: () => response,
1005
+ reply: (r) => response = r,
1006
+ };
1007
+ if (options.hooks?.init) {
1008
+ await options.hooks.init(hookOptions);
1009
+ restoreCtx();
1010
+ }
1011
+ const instance = await options.getControllerInstance();
1012
+ restoreCtx();
1013
+ if (instance) {
1014
+ setControllerContext(instance, options.controllerMethod || '');
1015
+ }
1016
+ const interceptorHandler = await options.getIterceptorHandler();
1017
+ if (interceptorHandler) {
1018
+ restoreCtx();
1019
+ try {
1020
+ response = await interceptorHandler.init();
1021
+ if (typeof response !== 'undefined')
1022
+ return endWithResponse();
1023
+ }
1024
+ catch (e) {
1025
+ options.logErrors && logger.error(e);
1026
+ response = e;
1027
+ return endWithResponse(true);
1028
+ }
1029
+ }
1030
+ let args = [];
1031
+ if (options.resolveArgs) {
1032
+ // params
1033
+ restoreCtx();
1034
+ try {
1035
+ // logger.trace(`resolving method args for "${ opts.method as string }"`)
1036
+ args = await options.resolveArgs();
1037
+ // logger.trace(`args for method "${ opts.method as string }" resolved (count ${String(args.length)})`)
1038
+ }
1039
+ catch (e) {
1040
+ options.logErrors && logger.error(e);
1041
+ response = e;
1042
+ return endWithResponse(true);
1043
+ }
1044
+ }
1045
+ if (interceptorHandler) {
1046
+ restoreCtx();
1047
+ response = await interceptorHandler.fireBefore(response);
1048
+ if (typeof response !== 'undefined')
1049
+ return endWithResponse();
1050
+ }
1051
+ // fire request handler
1052
+ const callControllerMethod = () => {
1053
+ restoreCtx();
1054
+ if (options.callControllerMethod) {
1055
+ return options.callControllerMethod(args);
1056
+ }
1057
+ else if (instance && options.controllerMethod && typeof instance[options.controllerMethod] === 'function') {
1058
+ return instance[options.controllerMethod](...args);
1059
+ }
1060
+ };
1061
+ try {
1062
+ response = callControllerMethod();
1063
+ }
1064
+ catch (e) {
1065
+ options.logErrors && logger.error(e);
1066
+ response = e;
1067
+ return endWithResponse(true);
1068
+ }
1069
+ async function endWithResponse(raise = false) {
1070
+ // fire after interceptors
1071
+ if (interceptorHandler) {
1072
+ restoreCtx();
1073
+ try {
1074
+ // logger.trace('firing after interceptors')
1075
+ response = await interceptorHandler.fireAfter(response);
1076
+ }
1077
+ catch (e) {
1078
+ options.logErrors && logger.error(e);
1079
+ if (!options.manualUnscope) {
1080
+ unscope();
1081
+ }
1082
+ throw e;
1083
+ }
1084
+ }
1085
+ if (!options.manualUnscope) {
1086
+ unscope();
1087
+ }
1088
+ if (options.hooks?.end) {
1089
+ await options.hooks.end(hookOptions);
1090
+ }
1091
+ if (raise) {
1092
+ throw response;
1093
+ }
1094
+ return response;
1095
+ }
1096
+ return await endWithResponse();
1097
+ };
1150
1098
  }
1151
1099
 
1152
- Object.defineProperty(exports, 'createProvideRegistry', {
1100
+ Object.defineProperty(exports, "createProvideRegistry", {
1153
1101
  enumerable: true,
1154
1102
  get: function () { return infact$1.createProvideRegistry; }
1155
1103
  });
1156
- Object.defineProperty(exports, 'EventLogger', {
1104
+ Object.defineProperty(exports, "EventLogger", {
1157
1105
  enumerable: true,
1158
1106
  get: function () { return eventCore.EventLogger; }
1159
1107
  });
1160
- Object.defineProperty(exports, 'useEventContext', {
1108
+ Object.defineProperty(exports, "useEventContext", {
1161
1109
  enumerable: true,
1162
1110
  get: function () { return eventCore.useEventContext; }
1163
1111
  });
1164
- Object.defineProperty(exports, 'useEventLogger', {
1112
+ Object.defineProperty(exports, "useEventLogger", {
1165
1113
  enumerable: true,
1166
1114
  get: function () { return eventCore.useEventLogger; }
1167
1115
  });