moost 0.3.10 → 0.3.12

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,839 @@ 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
+ const proto = Object.getPrototypeOf(instance);
90
+ return [
91
+ ...getParentProps(mate$1.getConstructor(instance)),
92
+ ...Object.getOwnPropertyNames(proto),
93
+ ...Object.getOwnPropertyNames(instance),
94
+ ].filter((m) => typeof instance[m] === 'function');
95
+ }
96
+ const fnProto = Object.getPrototypeOf(Function);
97
+ function getParentProps(constructor) {
98
+ const parent = Object.getPrototypeOf(constructor);
99
+ if (typeof parent === 'function' &&
100
+ parent !== fnProto &&
101
+ parent !== constructor &&
102
+ parent.prototype) {
103
+ return [
104
+ ...getParentProps(parent),
105
+ ...Object.getOwnPropertyNames(parent.prototype),
106
+ ];
107
+ }
108
+ return [];
139
109
  }
140
110
 
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
- });
111
+ async function getCallableFn(targetInstance, fn, restoreCtx, pipes, logger) {
112
+ const mate = getMoostMate();
113
+ const meta = mate.read(fn);
114
+ if (meta?.injectable) {
115
+ const infact = getMoostInfact();
116
+ infact.silent(true);
117
+ const instance = (await infact.getForInstance(targetInstance, fn, {
118
+ syncContextFn: () => {
119
+ restoreCtx && restoreCtx();
120
+ },
121
+ customData: {
122
+ pipes: [...(pipes || []), ...(meta.pipes || [])].sort((a, b) => a.priority - b.priority),
123
+ },
124
+ }));
125
+ infact.silent(false);
126
+ return ((...args) => {
127
+ return instance.handler(...args);
128
+ });
129
+ }
130
+ if (typeof fn === 'function') {
131
+ return fn;
132
+ }
133
+ const e = new Error(`getCallableFn failed for "${mate$1.getConstructor(targetInstance).name}" because the passed arg is not a Function nor TClassFunction`);
134
+ logger.error(e);
135
+ throw e;
168
136
  }
169
137
 
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
- }
138
+ class InterceptorHandler {
139
+ constructor(handlers) {
140
+ this.handlers = handlers;
141
+ this.before = [];
142
+ this.after = [];
143
+ this.onError = [];
144
+ this.responseOverwritten = false;
145
+ }
146
+ replyFn(reply) {
147
+ this.response = reply;
148
+ this.responseOverwritten = true;
149
+ }
150
+ async init() {
151
+ const { restoreCtx } = eventCore.useEventContext();
152
+ for (const handler of this.handlers) {
153
+ restoreCtx();
154
+ const response = await handler((fn) => {
155
+ this.before.push(fn);
156
+ }, (fn) => {
157
+ this.after.unshift(fn);
158
+ }, (fn) => {
159
+ this.onError.unshift(fn);
160
+ });
161
+ if (typeof response !== 'undefined')
162
+ return response;
163
+ }
164
+ }
165
+ async fireBefore(response) {
166
+ const { restoreCtx } = eventCore.useEventContext();
167
+ this.response = response;
168
+ for (const handler of this.before) {
169
+ restoreCtx();
170
+ await handler(this.replyFn.bind(this));
171
+ if (this.responseOverwritten)
172
+ break;
173
+ }
174
+ return this.response;
175
+ }
176
+ async fireAfter(response) {
177
+ const { restoreCtx } = eventCore.useEventContext();
178
+ this.response = response;
179
+ if (response instanceof Error) {
180
+ for (const handler of this.onError) {
181
+ restoreCtx();
182
+ await handler(response, this.replyFn.bind(this));
183
+ }
184
+ }
185
+ else {
186
+ for (const handler of this.after) {
187
+ restoreCtx();
188
+ await handler(response, this.replyFn.bind(this));
189
+ }
190
+ }
191
+ return this.response;
192
+ }
231
193
  }
232
194
 
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
- };
195
+ const mate = getMoostMate();
196
+ function getIterceptorHandlerFactory(interceptors, getTargetInstance, pipes, logger) {
197
+ return () => {
198
+ const interceptorHandlers = [];
199
+ for (const { handler } of interceptors) {
200
+ const interceptorMeta = mate.read(handler);
201
+ if (interceptorMeta?.injectable) {
202
+ interceptorHandlers.push(async (...args) => {
203
+ const { restoreCtx } = eventCore.useEventContext();
204
+ const targetInstance = await getTargetInstance();
205
+ restoreCtx();
206
+ return (await getCallableFn(targetInstance, handler, restoreCtx, pipes, logger))(...args);
207
+ });
208
+ }
209
+ else {
210
+ interceptorHandlers.push(handler);
211
+ }
212
+ }
213
+ return Promise.resolve(new InterceptorHandler(interceptorHandlers));
214
+ };
253
215
  }
254
216
 
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
- });
217
+ async function bindControllerMethods(options) {
218
+ const opts = options || {};
219
+ const { getInstance } = opts;
220
+ const { classConstructor } = opts;
221
+ const { adapters } = opts;
222
+ opts.globalPrefix = opts.globalPrefix || '';
223
+ opts.provide = opts.provide || {};
224
+ const fakeInstance = Object.create(classConstructor.prototype);
225
+ const methods = getInstanceOwnMethods(fakeInstance);
226
+ const mate = getMoostMate();
227
+ const meta = mate.read(classConstructor) || {};
228
+ const ownPrefix = typeof opts.replaceOwnPrefix === 'string'
229
+ ? opts.replaceOwnPrefix
230
+ : meta.controller?.prefix || '';
231
+ const prefix = `${opts.globalPrefix}/${ownPrefix}`;
232
+ const controllerOverview = {
233
+ meta,
234
+ computedPrefix: prefix,
235
+ type: classConstructor,
236
+ handlers: [],
237
+ };
238
+ for (const method of methods) {
239
+ const methodMeta = getMoostMate().read(fakeInstance, method) || {};
240
+ methodMeta.handlers;
241
+ if (!methodMeta.handlers || !methodMeta.handlers.length)
242
+ continue;
243
+ const pipes = [...(opts.pipes || []), ...(methodMeta.pipes || [])].sort((a, b) => a.priority - b.priority);
244
+ const interceptors = [
245
+ ...(opts.interceptors || []),
246
+ ...(meta.interceptors || []),
247
+ ...(methodMeta.interceptors || []),
248
+ ].sort((a, b) => a.priority - b.priority);
249
+ const getIterceptorHandler = getIterceptorHandlerFactory(interceptors, getInstance, pipes, options.logger);
250
+ const argsPipes = [];
251
+ for (const p of methodMeta.params || []) {
252
+ argsPipes.push({
253
+ meta: p,
254
+ pipes: [...pipes, ...(p.pipes || [])].sort((a, b) => a.priority - b.priority),
255
+ });
256
+ }
257
+ const resolveArgs = async () => {
258
+ const args = [];
259
+ const { restoreCtx } = eventCore.useEventContext();
260
+ for (let i = 0; i < argsPipes.length; i++) {
261
+ const { pipes, meta: paramMeta } = argsPipes[i];
262
+ args[i] = await runPipes(pipes, undefined, {
263
+ classMeta: meta,
264
+ methodMeta,
265
+ paramMeta,
266
+ type: classConstructor,
267
+ key: method,
268
+ index: i,
269
+ targetMeta: paramMeta,
270
+ }, 'PARAM', restoreCtx);
271
+ }
272
+ return args;
273
+ };
274
+ const wm = new WeakMap();
275
+ controllerOverview.handlers.push(...methodMeta.handlers.map(h => {
276
+ const data = {
277
+ meta: methodMeta,
278
+ path: h.path,
279
+ type: h.type,
280
+ method,
281
+ handler: h,
282
+ registeredAs: [],
283
+ };
284
+ wm.set(h, data);
285
+ return data;
286
+ }));
287
+ for (const adapter of adapters) {
288
+ await adapter.bindHandler({
289
+ prefix,
290
+ fakeInstance,
291
+ getInstance,
292
+ method,
293
+ handlers: methodMeta.handlers,
294
+ getIterceptorHandler,
295
+ resolveArgs,
296
+ logHandler: (eventName) => options.logger.info(`• ${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`),
297
+ register(h, path, args) {
298
+ const data = wm.get(h);
299
+ if (data) {
300
+ data.registeredAs.push({
301
+ path,
302
+ args,
303
+ });
304
+ }
305
+ },
306
+ });
307
+ }
308
+ }
309
+ return controllerOverview;
354
310
  }
355
311
 
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
- }));
312
+ function Label(value) {
313
+ return getMoostMate().decorate('label', value);
314
+ }
315
+ function Description(value) {
316
+ return getMoostMate().decorate('description', value);
317
+ }
318
+ function Value(value) {
319
+ return getMoostMate().decorate('value', value);
320
+ }
321
+ function Id(value) {
322
+ return getMoostMate().decorate('id', value);
323
+ }
324
+ function Optional() {
325
+ return getMoostMate().decorate('optional', true);
326
+ }
327
+ function Required() {
328
+ const mate = getMoostMate();
329
+ return mate.apply(mate.decorate('required', true), mate.decorateClass((meta, level, key, index) => {
330
+ if (typeof index !== 'number' &&
331
+ meta &&
332
+ ['string', 'symbol'].includes(typeof key)) {
333
+ meta.requiredProps = meta.requiredProps || [];
334
+ meta.requiredProps.push(key);
335
+ }
336
+ return meta;
337
+ }));
428
338
  }
429
339
 
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
- }
340
+ function Resolve(resolver, label) {
341
+ return (target, key, index) => {
342
+ const i = typeof index === 'number' ? index : undefined;
343
+ getMoostMate().decorate('resolver', (metas, level) => {
344
+ let newLabel = label;
345
+ if (!newLabel && level === 'PROP' && typeof metas.key === 'string') {
346
+ newLabel = metas.key;
347
+ }
348
+ fillLabel(target, key || '', i, newLabel);
349
+ return resolver(metas, level);
350
+ })(target, key, i);
351
+ };
352
+ }
353
+ function Param(name) {
354
+ return getMoostMate().apply(getMoostMate().decorate('paramSource', 'ROUTE'), getMoostMate().decorate('paramName', name), Resolve(() => eventCore.useRouteParams().get(name), name));
355
+ }
356
+ function Params() {
357
+ return Resolve(() => eventCore.useRouteParams().params, 'params');
358
+ }
359
+ function Const(value, label) {
360
+ return Resolve(() => value, label);
361
+ }
362
+ function ConstFactory(factory, label) {
363
+ return Resolve(async () => await factory(), label);
364
+ }
365
+ function InjectEventLogger(topic) {
366
+ return Resolve(() => eventCore.useEventLogger(topic));
367
+ }
368
+ function fillLabel(target, key, index, name) {
369
+ if (name) {
370
+ const meta = getMoostMate().read(target, key);
371
+ if (typeof index === 'number') {
372
+ if (!meta?.params ||
373
+ !meta?.params[index] ||
374
+ !meta?.params[index].label) {
375
+ Label(name)(target, key, index);
376
+ }
377
+ }
378
+ else {
379
+ if (!meta?.label) {
380
+ Label(name)(target, key);
381
+ }
382
+ }
383
+ }
511
384
  }
512
385
 
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;
386
+ function Injectable(scope = true) {
387
+ return getMoostMate().decorate('injectable', scope);
388
+ }
389
+ const insureInjectable = getMoostMate().decorate((meta) => {
390
+ if (!meta.injectable)
391
+ meta.injectable = true;
392
+ return meta;
529
393
  });
530
394
 
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);
395
+ function Controller(prefix) {
396
+ const mate = getMoostMate();
397
+ return mate.apply(insureInjectable, mate.decorate('controller', { prefix: prefix || '' }));
398
+ }
399
+ function ImportController(prefix, controller, provide) {
400
+ return getMoostMate().decorate('importController', {
401
+ prefix: typeof prefix === 'string' ? prefix : undefined,
402
+ typeResolver: typeof prefix === 'string'
403
+ ? controller
404
+ : prefix,
405
+ provide: typeof prefix === 'string'
406
+ ? provide || undefined
407
+ : controller || undefined,
408
+ }, true);
551
409
  }
552
410
 
553
- function Circular(resolver) {
554
- return getMoostMate().decorate('circular', resolver);
411
+ function Circular(resolver) {
412
+ return getMoostMate().decorate('circular', resolver);
555
413
  }
556
414
 
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);
415
+ exports.TInterceptorPriority = void 0;
416
+ (function (TInterceptorPriority) {
417
+ TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
418
+ TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
419
+ TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
420
+ TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
421
+ TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
422
+ TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
423
+ TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
424
+ })(exports.TInterceptorPriority || (exports.TInterceptorPriority = {}));
425
+ function Intercept(handler, priority) {
426
+ return getMoostMate().decorate('interceptors', {
427
+ handler,
428
+ priority: priority ||
429
+ handler.priority ||
430
+ exports.TInterceptorPriority.INTERCEPTOR,
431
+ }, true);
582
432
  }
583
433
 
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);
434
+ function Provide(type, fn) {
435
+ return getMoostMate().decorate((meta) => {
436
+ meta.provide = meta.provide || {};
437
+ Object.assign(meta.provide, infact$1.createProvideRegistry([type, fn]));
438
+ return meta;
439
+ });
440
+ }
441
+ function Inject(type) {
442
+ return getMoostMate().decorate('inject', type);
607
443
  }
608
444
 
609
- /**
610
- * ## Inherit
611
- * ### @Decorator
612
- * Inherit metadata from super class
613
- * @returns
614
- */
615
445
  const Inherit = () => getMoostMate().decorate('inherit', true);
616
446
 
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";
447
+ exports.TPipePriority = void 0;
448
+ (function (TPipePriority) {
449
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
450
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
451
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
452
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
453
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
454
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
455
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
456
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
457
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
628
458
  })(exports.TPipePriority || (exports.TPipePriority = {}));
629
459
 
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);
460
+ function Pipe(handler, priority) {
461
+ if (typeof priority !== 'number') {
462
+ priority =
463
+ typeof handler.priority === 'number'
464
+ ? handler.priority
465
+ : exports.TPipePriority.TRANSFORM;
466
+ }
467
+ return getMoostMate().decorate('pipes', { handler, priority }, true);
646
468
  }
647
469
 
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;
470
+ function defineInterceptorFn(fn, priority = exports.TInterceptorPriority.INTERCEPTOR) {
471
+ fn.priority = priority;
472
+ return fn;
473
+ }
474
+ function definePipeFn(fn, priority = exports.TPipePriority.TRANSFORM) {
475
+ fn.priority = priority;
476
+ return fn;
695
477
  }
696
478
 
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;
479
+ const resolvePipe = definePipeFn((_value, metas, level) => {
480
+ const resolver = metas.targetMeta?.resolver;
481
+ if (resolver) {
482
+ return resolver(metas, level);
483
+ }
484
+ return undefined;
704
485
  }, exports.TPipePriority.RESOLVE);
705
486
 
706
- const sharedPipes = [
707
- {
708
- handler: resolvePipe,
709
- priority: exports.TPipePriority.RESOLVE,
710
- },
487
+ const sharedPipes = [
488
+ {
489
+ handler: resolvePipe,
490
+ priority: exports.TPipePriority.RESOLVE,
491
+ },
711
492
  ];
712
493
 
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);
494
+ function getDefaultLogger(topic) {
495
+ return new logger.ProstoLogger({
496
+ level: 4,
497
+ transports: [
498
+ logger.createConsoleTransort({
499
+ format: logger.coloredConsole,
500
+ }),
501
+ ],
502
+ }, topic);
722
503
  }
723
504
 
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
- }
505
+ class Moost {
506
+ constructor(options) {
507
+ this.options = options;
508
+ this.pipes = [...sharedPipes];
509
+ this.interceptors = [];
510
+ this.adapters = [];
511
+ this.controllersOverview = [];
512
+ this.provide = infact$1.createProvideRegistry([infact$1.Infact, getMoostInfact], [mate$1.Mate, getMoostMate]);
513
+ this.unregisteredControllers = [];
514
+ this.logger = options?.logger || getDefaultLogger('moost');
515
+ getMoostInfact().setLogger(this.getLogger('infact'));
516
+ const mate = getMoostMate();
517
+ Object.assign(mate, { logger: this.getLogger('mate') });
518
+ }
519
+ getLogger(topic) {
520
+ if (this.logger instanceof logger.ProstoLogger) {
521
+ return this.logger.createTopic(topic);
522
+ }
523
+ return this.logger;
524
+ }
525
+ adapter(a) {
526
+ this.adapters.push(a);
527
+ return a;
528
+ }
529
+ getControllersOverview() {
530
+ return this.controllersOverview;
531
+ }
532
+ async init() {
533
+ this.setProvideRegistry(infact$1.createProvideRegistry([Moost, () => this], [logger.ProstoLogger, () => this.logger], ['MOOST_LOGGER', () => this.logger]));
534
+ for (const a of this.adapters) {
535
+ const constructor = mate$1.getConstructor(a);
536
+ if (constructor) {
537
+ this.setProvideRegistry(infact$1.createProvideRegistry([
538
+ constructor,
539
+ () => a,
540
+ ]));
541
+ }
542
+ if (typeof a.getProvideRegistry === 'function') {
543
+ this.setProvideRegistry(a.getProvideRegistry());
544
+ }
545
+ }
546
+ this.unregisteredControllers.unshift(this);
547
+ await this.bindControllers();
548
+ for (const a of this.adapters) {
549
+ await (a.onInit && a.onInit(this));
550
+ }
551
+ }
552
+ async bindControllers() {
553
+ const infact = getMoostInfact();
554
+ infact.setLogger(this.logger);
555
+ const meta = getMoostMate();
556
+ const thisMeta = meta.read(this);
557
+ const provide = { ...(thisMeta?.provide || {}), ...this.provide };
558
+ for (const _controller of this.unregisteredControllers) {
559
+ let newPrefix = undefined;
560
+ let controller = _controller;
561
+ if (Array.isArray(_controller) && typeof _controller[0] === 'string') {
562
+ newPrefix = _controller[0];
563
+ controller = _controller[1];
564
+ }
565
+ await this.bindController(controller, provide, this.options?.globalPrefix || '', newPrefix);
566
+ }
567
+ this.unregisteredControllers = [];
568
+ }
569
+ async bindController(controller, provide, globalPrefix, replaceOwnPrefix) {
570
+ const mate = getMoostMate();
571
+ const classMeta = mate.read(controller);
572
+ const infact = getMoostInfact();
573
+ const isControllerConsructor = mate$1.isConstructor(controller);
574
+ const pipes = [...this.pipes, ...(classMeta?.pipes || [])].sort((a, b) => a.priority - b.priority);
575
+ let instance;
576
+ const infactOpts = { provide, customData: { pipes } };
577
+ if (isControllerConsructor &&
578
+ (classMeta?.injectable === 'SINGLETON' ||
579
+ classMeta?.injectable === true)) {
580
+ instance = (await infact.get(controller, infactOpts));
581
+ }
582
+ else if (!isControllerConsructor) {
583
+ instance = controller;
584
+ infact.setProvideRegByInstance(instance, provide);
585
+ }
586
+ const getInstance = instance
587
+ ? () => Promise.resolve(instance)
588
+ : async () => {
589
+ infact.silent(true);
590
+ const { restoreCtx } = eventCore.useEventContext();
591
+ const instance = (await infact.get(controller, { ...infactOpts, syncContextFn: restoreCtx }));
592
+ infact.silent(false);
593
+ return instance;
594
+ };
595
+ const classConstructor = mate$1.isConstructor(controller)
596
+ ? controller
597
+ : mate$1.getConstructor(controller);
598
+ this.controllersOverview.push(await bindControllerMethods({
599
+ getInstance,
600
+ classConstructor,
601
+ adapters: this.adapters,
602
+ globalPrefix,
603
+ replaceOwnPrefix,
604
+ interceptors: [...this.interceptors],
605
+ pipes,
606
+ provide: classMeta?.provide || {},
607
+ logger: this.logger,
608
+ }));
609
+ if (classMeta && classMeta.importController) {
610
+ const prefix = typeof replaceOwnPrefix === 'string'
611
+ ? replaceOwnPrefix
612
+ : classMeta?.controller?.prefix;
613
+ const mergedProvide = { ...provide, ...(classMeta?.provide || {}) };
614
+ for (const ic of classMeta.importController) {
615
+ if (ic.typeResolver) {
616
+ const isConstr = mate$1.isConstructor(ic.typeResolver);
617
+ const isFunc = typeof ic.typeResolver === 'function';
618
+ await this.bindController(isConstr
619
+ ? ic.typeResolver
620
+ : isFunc
621
+ ? await ic.typeResolver()
622
+ : ic.typeResolver, ic.provide
623
+ ? { ...mergedProvide, ...ic.provide }
624
+ : mergedProvide, `${globalPrefix}/${prefix || ''}`, ic.prefix);
625
+ }
626
+ }
627
+ }
628
+ }
629
+ applyGlobalPipes(...items) {
630
+ for (const item of items) {
631
+ if (typeof item === 'function') {
632
+ this.pipes.push({
633
+ handler: item,
634
+ priority: typeof item.priority === 'number'
635
+ ? item.priority
636
+ : exports.TPipePriority.TRANSFORM,
637
+ });
638
+ }
639
+ else {
640
+ this.pipes.push({
641
+ handler: item.handler,
642
+ priority: item.priority,
643
+ });
644
+ }
645
+ }
646
+ this.globalInterceptorHandler = undefined;
647
+ return this;
648
+ }
649
+ getGlobalInterceptorHandler() {
650
+ if (!this.globalInterceptorHandler) {
651
+ const mate = getMoostMate();
652
+ const thisMeta = mate.read(this);
653
+ const pipes = [...(this.pipes || []), ...(thisMeta?.pipes || [])].sort((a, b) => a.priority - b.priority);
654
+ const interceptors = [...this.interceptors, ...(thisMeta?.interceptors || [])]
655
+ .sort((a, b) => a.priority - b.priority);
656
+ this.globalInterceptorHandler = getIterceptorHandlerFactory(interceptors, () => Promise.resolve(this), pipes, this.logger);
657
+ }
658
+ return this.globalInterceptorHandler();
659
+ }
660
+ applyGlobalInterceptors(...items) {
661
+ for (const item of items) {
662
+ if (typeof item === 'function') {
663
+ this.interceptors.push({
664
+ handler: item,
665
+ priority: typeof item.priority === 'number'
666
+ ? item
667
+ .priority
668
+ : exports.TInterceptorPriority.INTERCEPTOR,
669
+ });
670
+ }
671
+ else {
672
+ this.interceptors.push({
673
+ handler: item.handler,
674
+ priority: item.priority,
675
+ });
676
+ }
677
+ }
678
+ this.globalInterceptorHandler = undefined;
679
+ return this;
680
+ }
681
+ setProvideRegistry(provide) {
682
+ this.provide = { ...this.provide, ...provide };
683
+ return this;
684
+ }
685
+ registerControllers(...controllers) {
686
+ this.unregisteredControllers.push(...controllers);
687
+ return this;
688
+ }
1001
689
  }
1002
690
 
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
- };
691
+ function setControllerContext(controller, method) {
692
+ const { store } = eventCore.useEventContext();
693
+ const { set } = store('controller');
694
+ set('instance', controller);
695
+ set('method', method);
696
+ }
697
+ function useControllerContext() {
698
+ const { store } = eventCore.useEventContext();
699
+ const { get } = store('controller');
700
+ const getController = () => get('instance');
701
+ const getMethod = () => get('method');
702
+ const getControllerMeta = () => getMoostMate().read(getController());
703
+ const getMethodMeta = (name) => getMoostMate().read(getController(), name || getMethod());
704
+ function instantiate(c) {
705
+ return getMoostInfact().getForInstance(getController(), c);
706
+ }
707
+ return {
708
+ instantiate,
709
+ getController,
710
+ getMethod,
711
+ getControllerMeta,
712
+ getMethodMeta,
713
+ getPropertiesList: () => getControllerMeta()?.properties || [],
714
+ getScope: () => getControllerMeta()?.injectable || 'SINGLETON',
715
+ getParamsMeta: () => getMethodMeta()?.params || [],
716
+ getPropMeta: (name) => getMethodMeta(name),
717
+ };
1032
718
  }
1033
719
 
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
- });
720
+ const infact = getMoostInfact();
721
+ function registerEventScope(scopeId) {
722
+ infact.registerScope(scopeId);
723
+ return () => infact.unregisterScope(scopeId);
724
+ }
725
+ function defineMoostEventHandler(options) {
726
+ return async () => {
727
+ const { restoreCtx } = eventCore.useEventContext(options.contextType);
728
+ const scopeId = eventCore.useEventId().getId();
729
+ const logger = eventCore.useEventLogger(options.loggerTitle);
730
+ const unscope = registerEventScope(scopeId);
731
+ let response;
732
+ const hookOptions = {
733
+ restoreCtx,
734
+ scopeId,
735
+ logger,
736
+ unscope,
737
+ method: options.controllerMethod,
738
+ getResponse: () => response,
739
+ reply: (r) => response = r,
740
+ };
741
+ if (options.hooks?.init) {
742
+ await options.hooks.init(hookOptions);
743
+ restoreCtx();
744
+ }
745
+ const instance = await options.getControllerInstance();
746
+ restoreCtx();
747
+ if (instance) {
748
+ setControllerContext(instance, options.controllerMethod || '');
749
+ }
750
+ const interceptorHandler = await options.getIterceptorHandler();
751
+ if (interceptorHandler) {
752
+ restoreCtx();
753
+ try {
754
+ response = await interceptorHandler.init();
755
+ if (typeof response !== 'undefined')
756
+ return endWithResponse();
757
+ }
758
+ catch (e) {
759
+ options.logErrors && logger.error(e);
760
+ response = e;
761
+ return endWithResponse(true);
762
+ }
763
+ }
764
+ let args = [];
765
+ if (options.resolveArgs) {
766
+ restoreCtx();
767
+ try {
768
+ args = await options.resolveArgs();
769
+ }
770
+ catch (e) {
771
+ options.logErrors && logger.error(e);
772
+ response = e;
773
+ return endWithResponse(true);
774
+ }
775
+ }
776
+ if (interceptorHandler) {
777
+ restoreCtx();
778
+ response = await interceptorHandler.fireBefore(response);
779
+ if (typeof response !== 'undefined')
780
+ return endWithResponse();
781
+ }
782
+ const callControllerMethod = () => {
783
+ restoreCtx();
784
+ if (options.callControllerMethod) {
785
+ return options.callControllerMethod(args);
786
+ }
787
+ else if (instance && options.controllerMethod && typeof instance[options.controllerMethod] === 'function') {
788
+ return instance[options.controllerMethod](...args);
789
+ }
790
+ };
791
+ try {
792
+ response = callControllerMethod();
793
+ }
794
+ catch (e) {
795
+ options.logErrors && logger.error(e);
796
+ response = e;
797
+ return endWithResponse(true);
798
+ }
799
+ async function endWithResponse(raise = false) {
800
+ if (interceptorHandler) {
801
+ restoreCtx();
802
+ try {
803
+ response = await interceptorHandler.fireAfter(response);
804
+ }
805
+ catch (e) {
806
+ options.logErrors && logger.error(e);
807
+ if (!options.manualUnscope) {
808
+ unscope();
809
+ }
810
+ throw e;
811
+ }
812
+ }
813
+ if (!options.manualUnscope) {
814
+ unscope();
815
+ }
816
+ if (options.hooks?.end) {
817
+ await options.hooks.end(hookOptions);
818
+ }
819
+ if (raise) {
820
+ throw response;
821
+ }
822
+ return response;
823
+ }
824
+ return await endWithResponse();
825
+ };
1150
826
  }
1151
827
 
1152
- Object.defineProperty(exports, 'createProvideRegistry', {
828
+ Object.defineProperty(exports, "createProvideRegistry", {
1153
829
  enumerable: true,
1154
830
  get: function () { return infact$1.createProvideRegistry; }
1155
831
  });
1156
- Object.defineProperty(exports, 'EventLogger', {
832
+ Object.defineProperty(exports, "EventLogger", {
1157
833
  enumerable: true,
1158
834
  get: function () { return eventCore.EventLogger; }
1159
835
  });
1160
- Object.defineProperty(exports, 'useEventContext', {
836
+ Object.defineProperty(exports, "useEventContext", {
1161
837
  enumerable: true,
1162
838
  get: function () { return eventCore.useEventContext; }
1163
839
  });
1164
- Object.defineProperty(exports, 'useEventLogger', {
840
+ Object.defineProperty(exports, "useEventLogger", {
1165
841
  enumerable: true,
1166
842
  get: function () { return eventCore.useEventLogger; }
1167
843
  });