@moostjs/otel 0.4.6 → 0.4.7

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.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  import { trace, context, SpanStatusCode } from '@opentelemetry/api';
2
- import { useAsyncEventContext, eventContextHooks, useControllerContext, getConstructor } from 'moost';
2
+ import { useAsyncEventContext as useAsyncEventContext$1, eventContextHooks as eventContextHooks$1, useControllerContext, getConstructor as getConstructor$2 } from 'moost';
3
+ import { randomUUID } from 'crypto';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
3
6
 
4
7
  function useOtelContext() {
5
- const store = useAsyncEventContext().store('otel');
8
+ const store = useAsyncEventContext$1().store('otel');
6
9
  const getSpan = () => store.get('span');
7
10
  const getSpanContext = () => {
8
11
  const span = getSpan();
@@ -54,7 +57,7 @@ function useOtelPropagation() {
54
57
  }
55
58
 
56
59
  function enableOtelForMoost() {
57
- eventContextHooks.onStartEvent((eventType) => {
60
+ eventContextHooks$1.onStartEvent((eventType) => {
58
61
  if (eventType === 'init') {
59
62
  return;
60
63
  }
@@ -71,28 +74,30 @@ function enableOtelForMoost() {
71
74
  registerSpan(span);
72
75
  }
73
76
  });
74
- eventContextHooks.onEndEvent((eventType, abortReason) => {
77
+ eventContextHooks$1.onEndEvent((eventType, abortReason) => {
75
78
  if (eventType === 'init') {
76
79
  return;
77
80
  }
78
81
  const { getSpan } = useOtelContext();
79
82
  const span = getSpan();
80
83
  if (span) {
81
- const { getMethod, getMethodMeta, getController } = useControllerContext();
84
+ const { getMethod, getMethodMeta, getController, getControllerMeta } = useControllerContext();
82
85
  const methodName = getMethod();
83
86
  const methodMeta = getMethodMeta();
87
+ const cMeta = getControllerMeta();
84
88
  span.setAttributes({
85
89
  'custom.event_type': eventType,
86
90
  'custom.event_description': methodMeta?.description || methodMeta?.label || methodName,
87
- 'moost.controller': getConstructor(getController()).name,
91
+ 'moost.controller': getConstructor$2(getController()).name,
88
92
  'moost.handler': methodName,
93
+ 'moost.ignore': cMeta?.otelIgnoreSpan || methodMeta?.otelIgnoreSpan,
89
94
  });
90
95
  if (abortReason) {
91
96
  span.recordException(new Error(abortReason));
92
97
  span.setStatus({ code: SpanStatusCode.ERROR, message: abortReason });
93
98
  }
94
99
  if (eventType === 'HTTP') {
95
- const req = useAsyncEventContext()
100
+ const req = useAsyncEventContext$1()
96
101
  .store('event')
97
102
  .get('req');
98
103
  span.updateName(`${req?.method || ''} ${methodMeta?.id || methodMeta?.label || methodName}`);
@@ -105,4 +110,913 @@ function enableOtelForMoost() {
105
110
  });
106
111
  }
107
112
 
108
- export { enableOtelForMoost, useOtelContext, useOtelPropagation, useSpan, useTrace };
113
+ const defaultLevels = [
114
+ 'fatal',
115
+ 'error',
116
+ 'warn',
117
+ 'log',
118
+ 'info',
119
+ 'debug',
120
+ 'trace',
121
+ ];
122
+ const defaultMappedLevels = new Map();
123
+ defaultLevels.forEach((type, level) => defaultMappedLevels.set(type, level));
124
+
125
+ class Hookable {
126
+ constructor() {
127
+ this.hooks = {};
128
+ }
129
+ hook(name, cb) {
130
+ if (!this.hooks[name]) {
131
+ this.hooks[name] = [];
132
+ }
133
+ this.hooks[name].push(cb);
134
+ return () => {
135
+ this.unhook(name, cb);
136
+ };
137
+ }
138
+ callHook(name, ...args) {
139
+ if (this.hooks[name]) {
140
+ for (const cb of this.hooks[name]) {
141
+ try {
142
+ cb(...args);
143
+ }
144
+ catch (error) {
145
+ console.error(`Error in hook ${name}:`, error);
146
+ }
147
+ }
148
+ }
149
+ }
150
+ unhook(name, cb) {
151
+ if (this.hooks[name]) {
152
+ this.hooks[name] = this.hooks[name].filter(hookCb => hookCb !== cb);
153
+ }
154
+ }
155
+ }
156
+
157
+ class EventContextHooks extends Hookable {
158
+ fireStartEvent(eventType) {
159
+ this.callHook('start-event', eventType);
160
+ }
161
+ fireEndEvent(eventType, abortReason) {
162
+ this.callHook('end-event', eventType, abortReason);
163
+ }
164
+ onStartEvent(cb) {
165
+ return this.hook('start-event', cb);
166
+ }
167
+ onEndEvent(cb) {
168
+ return this.hook('end-event', cb);
169
+ }
170
+ }
171
+ const eventContextHooks = new EventContextHooks();
172
+
173
+ function attachHook(target, opts, name) {
174
+ Object.defineProperty(target, name || 'value', {
175
+ get: opts.get,
176
+ set: opts.set,
177
+ });
178
+ return target;
179
+ }
180
+
181
+ const asyncStorage = new AsyncLocalStorage();
182
+ function useAsyncEventContext(expectedTypes) {
183
+ let cc = asyncStorage.getStore();
184
+ if (!cc) {
185
+ throw new Error('Event context does not exist at this point.');
186
+ }
187
+ if (expectedTypes || typeof expectedTypes === 'string') {
188
+ const type = cc.event.type;
189
+ const types = typeof expectedTypes === 'string' ? [expectedTypes] : expectedTypes;
190
+ if (!types.includes(type)) {
191
+ if (cc.parentCtx?.event.type && types.includes(cc.parentCtx.event.type)) {
192
+ cc = cc.parentCtx;
193
+ }
194
+ else {
195
+ throw new Error(`Event context type mismatch: expected ${types
196
+ .map(t => `"${t}"`)
197
+ .join(', ')}, received "${type}"`);
198
+ }
199
+ }
200
+ }
201
+ return _getCtxHelpers(cc);
202
+ }
203
+ function _getCtxHelpers(cc) {
204
+ function store(key) {
205
+ const obj = {
206
+ value: null,
207
+ hook,
208
+ init,
209
+ set: setNested,
210
+ get: getNested,
211
+ has: hasNested,
212
+ del: delNested,
213
+ entries,
214
+ clear,
215
+ };
216
+ attachHook(obj, {
217
+ set: v => {
218
+ set(key, v);
219
+ },
220
+ get: () => get(key),
221
+ });
222
+ function init(key2, getter) {
223
+ if (hasNested(key2)) {
224
+ return getNested(key2);
225
+ }
226
+ return setNested(key2, getter());
227
+ }
228
+ function hook(key2) {
229
+ const obj = {
230
+ value: null,
231
+ isDefined: null,
232
+ };
233
+ attachHook(obj, {
234
+ set: v => setNested(key2, v),
235
+ get: () => getNested(key2),
236
+ });
237
+ attachHook(obj, {
238
+ get: () => hasNested(key2),
239
+ }, 'isDefined');
240
+ return obj;
241
+ }
242
+ function setNested(key2, v) {
243
+ if (obj.value === undefined) {
244
+ obj.value = {};
245
+ }
246
+ obj.value[key2] = v;
247
+ return v;
248
+ }
249
+ function delNested(key2) {
250
+ setNested(key2, undefined);
251
+ }
252
+ function getNested(key2) {
253
+ return (obj.value || {})[key2];
254
+ }
255
+ function hasNested(key2) {
256
+ return (obj.value || {})[key2] !== undefined;
257
+ }
258
+ function entries() {
259
+ return Object.entries(obj.value || {});
260
+ }
261
+ function clear() {
262
+ obj.value = {};
263
+ }
264
+ return obj;
265
+ }
266
+ function getCtx() {
267
+ return cc;
268
+ }
269
+ function get(key) {
270
+ return getCtx()[key];
271
+ }
272
+ function set(key, v) {
273
+ getCtx()[key] = v;
274
+ }
275
+ const hasParentCtx = () => !!cc.parentCtx;
276
+ return {
277
+ getCtx,
278
+ endEvent: (abortReason) => {
279
+ if (cc && !cc._ended) {
280
+ cc._ended = true;
281
+ eventContextHooks.fireEndEvent(cc.event.type, abortReason);
282
+ }
283
+ },
284
+ store,
285
+ getStore: get,
286
+ setStore: set,
287
+ setParentCtx: (parentCtx) => {
288
+ cc.parentCtx = parentCtx;
289
+ },
290
+ hasParentCtx,
291
+ getParentCtx: () => {
292
+ if (!hasParentCtx()) {
293
+ throw new Error('Parent context is not available');
294
+ }
295
+ return _getCtxHelpers(cc.parentCtx);
296
+ },
297
+ };
298
+ }
299
+
300
+ function useEventId() {
301
+ const { store } = useAsyncEventContext();
302
+ const { init } = store('event');
303
+ const getId = () => init('id', () => randomUUID());
304
+ return { getId };
305
+ }
306
+
307
+ function getConstructor$1(instance) {
308
+ return Object.getPrototypeOf(instance).constructor;
309
+ }
310
+
311
+ const globalRegistry = {};
312
+ const UNDEFINED = Symbol('undefined');
313
+ class Infact {
314
+ constructor(options) {
315
+ this.options = options;
316
+ this.registry = {};
317
+ this.instanceRegistries = new WeakMap();
318
+ this.scopes = {};
319
+ this._silent = false;
320
+ this.logger = options.logger || console;
321
+ }
322
+ setLogger(logger) {
323
+ this.logger = logger;
324
+ }
325
+ silent(value = 'logs') {
326
+ this._silent = value;
327
+ }
328
+ registerScope(scopeId) {
329
+ if (!this.scopes[scopeId]) {
330
+ this.scopes[scopeId] = {};
331
+ }
332
+ }
333
+ unregisterScope(scopeId) {
334
+ delete this.scopes[scopeId];
335
+ }
336
+ getForInstance(instance, classConstructor, opts) {
337
+ const registries = this.getInstanceRegistries(instance);
338
+ return this.get(classConstructor, {
339
+ ...opts,
340
+ provide: registries.provide || {},
341
+ replace: registries.replace,
342
+ customData: registries.customData,
343
+ });
344
+ }
345
+ async get(classConstructor, opts, optional = false) {
346
+ const result = await this._get(classConstructor, opts, optional);
347
+ if (result) {
348
+ const { instance, mergedProvide, replace } = result;
349
+ if (this.options.storeProvideRegByInstance) {
350
+ this.setInstanceRegistries(instance, mergedProvide, replace, opts === null || opts === void 0 ? void 0 : opts.customData);
351
+ }
352
+ return instance;
353
+ }
354
+ return undefined;
355
+ }
356
+ setInstanceRegistries(instance, provide, replace, customData) {
357
+ this.instanceRegistries.set(instance, { provide, replace, customData });
358
+ }
359
+ getInstanceRegistries(instance) {
360
+ return this.instanceRegistries.get(instance) || {};
361
+ }
362
+ async _get(classConstructor, opts, optional) {
363
+ const hierarchy = (opts === null || opts === void 0 ? void 0 : opts.hierarchy) || [];
364
+ const provide = opts === null || opts === void 0 ? void 0 : opts.provide;
365
+ const replace = opts === null || opts === void 0 ? void 0 : opts.replace;
366
+ const syncContextFn = opts === null || opts === void 0 ? void 0 : opts.syncContextFn;
367
+ hierarchy.push(classConstructor.name);
368
+ let classMeta;
369
+ let instanceKey = Symbol.for(classConstructor);
370
+ if (replace && replace[instanceKey]) {
371
+ classConstructor = replace === null || replace === void 0 ? void 0 : replace[instanceKey];
372
+ instanceKey = Symbol.for(classConstructor);
373
+ }
374
+ try {
375
+ classMeta = this.options.describeClass(classConstructor);
376
+ }
377
+ catch (e) {
378
+ throw this.panicOwnError(`Could not instantiate "${classConstructor.name}". ` +
379
+ `An error occored on "describeClass" function.\n${e.message}`, hierarchy);
380
+ }
381
+ if (!classMeta || !classMeta.injectable) {
382
+ if (provide && provide[instanceKey]) {
383
+ syncContextFn && syncContextFn(classMeta);
384
+ return {
385
+ instance: await getProvidedValue(provide[instanceKey]),
386
+ mergedProvide: provide,
387
+ replace,
388
+ };
389
+ }
390
+ if (!optional) {
391
+ throw this.panicOwnError(`Could not instantiate Injectable "${classConstructor.name}". ` +
392
+ 'Please check if the class is injectable or if you properly typed arguments.', hierarchy);
393
+ }
394
+ else {
395
+ return undefined;
396
+ }
397
+ }
398
+ if (classMeta.scopeId && classMeta.global) {
399
+ throw this.panicOwnError(`Could not instantiate scoped Injectable "${classConstructor.name}" for scope "${classMeta.scopeId}". ` +
400
+ 'The scoped Injectable is not supported for Global scope.', hierarchy);
401
+ }
402
+ if (classMeta.scopeId && !this.scopes[classMeta.scopeId]) {
403
+ throw this.panicOwnError(`Could not instantiate scoped Injectable "${classConstructor.name}" for scope "${classMeta.scopeId}". ` +
404
+ 'The requested scope isn\'t registered.', hierarchy);
405
+ }
406
+ const scope = classMeta.scopeId
407
+ ? this.scopes[classMeta.scopeId]
408
+ : {};
409
+ const mergedProvide = {
410
+ ...(provide || {}),
411
+ ...(classMeta.provide || {}),
412
+ };
413
+ if (mergedProvide[instanceKey]) {
414
+ syncContextFn && syncContextFn(classMeta);
415
+ return {
416
+ instance: await getProvidedValue(mergedProvide[instanceKey]),
417
+ mergedProvide,
418
+ replace,
419
+ };
420
+ }
421
+ if (!this.registry[instanceKey] &&
422
+ !globalRegistry[instanceKey] &&
423
+ !scope[instanceKey]) {
424
+ const registry = classMeta.scopeId
425
+ ? scope
426
+ : classMeta.global
427
+ ? globalRegistry
428
+ : this.registry;
429
+ const params = classMeta.constructorParams || [];
430
+ const isCircular = !!params.find((p) => !!p.circular);
431
+ if (isCircular) {
432
+ registry[instanceKey] = Object.create(classConstructor.prototype);
433
+ }
434
+ const resolvedParams = [];
435
+ for (let i = 0; i < params.length; i++) {
436
+ const param = params[i];
437
+ if (param.inject) {
438
+ if (mergedProvide && mergedProvide[param.inject]) {
439
+ resolvedParams[i] = getProvidedValue(mergedProvide[param.inject]);
440
+ }
441
+ else if (param.nullable || param.optional) {
442
+ resolvedParams[i] = UNDEFINED;
443
+ }
444
+ else {
445
+ throw this.panicOwnError(`Could not inject ${JSON.stringify(param.inject)} to "${classConstructor.name}" to argument ${param.label
446
+ ? `labeled as "${param.label}"`
447
+ : `with index ${i}`}`, hierarchy);
448
+ }
449
+ }
450
+ else if (this.options.resolveParam) {
451
+ resolvedParams[i] = this.options.resolveParam({
452
+ classMeta,
453
+ classConstructor,
454
+ index: i,
455
+ paramMeta: param,
456
+ customData: opts === null || opts === void 0 ? void 0 : opts.customData,
457
+ });
458
+ }
459
+ }
460
+ for (let i = 0; i < resolvedParams.length; i++) {
461
+ const rp = resolvedParams[i];
462
+ if (rp &&
463
+ rp !== UNDEFINED &&
464
+ typeof rp.then === 'function') {
465
+ try {
466
+ syncContextFn && syncContextFn(classMeta);
467
+ resolvedParams[i] = await rp;
468
+ }
469
+ catch (e) {
470
+ const param = params[i];
471
+ throw this.panic(e, `Could not inject "${param.type.name}" to "${classConstructor.name}" ` +
472
+ `constructor at index ${i}${param.label ? ` (${param.label})` : ''}. An exception occured.`, hierarchy);
473
+ }
474
+ }
475
+ }
476
+ for (let i = 0; i < params.length; i++) {
477
+ const param = params[i];
478
+ if (typeof resolvedParams[i] === 'undefined') {
479
+ if (param.type === undefined && !param.circular) {
480
+ if (this._silent === false) {
481
+ this.logger.warn(`${classConstructor.name}.constructor() expects argument ${param.label
482
+ ? `labeled as "${param.label}"`
483
+ : `#${i}`} that is undefined. This might happen when Circular Dependency occurs. To handle Circular Dependencies please specify circular meta for param.`);
484
+ }
485
+ }
486
+ else if (param.type === undefined && param.circular) {
487
+ param.type = param.circular();
488
+ }
489
+ if (typeof param.type === 'function') {
490
+ if ([String, Number, Date, Array].includes(param.type)) {
491
+ if (!param.nullable && !param.optional) {
492
+ throw this.panicOwnError(`Could not inject "${param.type
493
+ .name}" to "${classConstructor.name}" ` +
494
+ `constructor at index ${i}${param.label
495
+ ? ` (${param.label})`
496
+ : ''}. The param was not resolved to a value.`, hierarchy);
497
+ }
498
+ }
499
+ resolvedParams[i] = this.get(param.type, {
500
+ provide: mergedProvide,
501
+ replace,
502
+ hierarchy,
503
+ syncContextFn,
504
+ customData: opts === null || opts === void 0 ? void 0 : opts.customData,
505
+ }, param.optional || param.nullable);
506
+ }
507
+ }
508
+ if (resolvedParams[i] === UNDEFINED) {
509
+ resolvedParams[i] = undefined;
510
+ }
511
+ }
512
+ for (let i = 0; i < resolvedParams.length; i++) {
513
+ const rp = resolvedParams[i];
514
+ if (rp && typeof rp.then === 'function') {
515
+ try {
516
+ syncContextFn && syncContextFn(classMeta);
517
+ resolvedParams[i] = await rp;
518
+ }
519
+ catch (e) {
520
+ const param = params[i];
521
+ throw this.panic(e, `Could not inject "${param.type.name}" to "${classConstructor.name}" ` +
522
+ `constructor at index ${i}${param.label ? ` (${param.label})` : ''}. An exception occured.`, hierarchy);
523
+ }
524
+ }
525
+ }
526
+ const instance = new classConstructor(...resolvedParams);
527
+ if (isCircular) {
528
+ Object.assign(registry[instanceKey], instance);
529
+ }
530
+ else {
531
+ registry[instanceKey] = instance;
532
+ }
533
+ if (this.options.describeProp &&
534
+ this.options.resolveProp &&
535
+ classMeta.properties &&
536
+ classMeta.properties.length) {
537
+ const resolvedProps = {};
538
+ for (const prop of classMeta.properties) {
539
+ const initialValue = instance[prop];
540
+ let propMeta;
541
+ try {
542
+ propMeta = this.options.describeProp(classConstructor, prop);
543
+ }
544
+ catch (e) {
545
+ throw this.panic(e, `Could not process prop "${prop}" of "${classConstructor.name}". ` +
546
+ `An error occored on "describeProp" function.\n${e.message}`, hierarchy);
547
+ }
548
+ if (propMeta) {
549
+ try {
550
+ resolvedProps[prop] = this.options.resolveProp({
551
+ classMeta,
552
+ classConstructor,
553
+ initialValue,
554
+ key: prop,
555
+ instance,
556
+ propMeta,
557
+ customData: opts === null || opts === void 0 ? void 0 : opts.customData,
558
+ });
559
+ }
560
+ catch (e) {
561
+ throw this.panic(e, `Could not inject prop "${prop}" to "${classConstructor.name}". ` +
562
+ 'An exception occured: ' +
563
+ e.message, hierarchy);
564
+ }
565
+ }
566
+ }
567
+ for (const [prop, value] of Object.entries(resolvedProps)) {
568
+ try {
569
+ syncContextFn && syncContextFn(classMeta);
570
+ resolvedProps[prop] = value
571
+ ? await value
572
+ : value;
573
+ }
574
+ catch (e) {
575
+ throw this.panic(e, `Could not inject prop "${prop}" to "${classConstructor.name}". ` +
576
+ 'An exception occured: ' +
577
+ e.message, hierarchy);
578
+ }
579
+ }
580
+ Object.assign(instance, resolvedProps);
581
+ }
582
+ if (this._silent === false) {
583
+ this.logger.info(`Class "${'' +
584
+ classConstructor.name +
585
+ '' +
586
+ ''}" instantiated with: ${''}[${resolvedParams
587
+ .map((p) => {
588
+ switch (typeof p) {
589
+ case 'number':
590
+ case 'boolean':
591
+ return p;
592
+ case 'string':
593
+ return `"${''}...${''}"`;
594
+ case 'object':
595
+ if (getConstructor$1(p))
596
+ return getConstructor$1(p).name;
597
+ return '{}';
598
+ default:
599
+ return '*';
600
+ }
601
+ })
602
+ .join(', ')}]`);
603
+ }
604
+ }
605
+ hierarchy.pop();
606
+ syncContextFn && syncContextFn(classMeta);
607
+ return {
608
+ instance: await (scope[instanceKey] ||
609
+ this.registry[instanceKey] ||
610
+ globalRegistry[instanceKey]),
611
+ mergedProvide,
612
+ replace,
613
+ };
614
+ }
615
+ panic(origError, text, hierarchy) {
616
+ if (this._silent === true) ;
617
+ else {
618
+ this.logger.error(text +
619
+ (hierarchy
620
+ ? '\nHierarchy:\n' + hierarchy.join(' -> ')
621
+ : ''));
622
+ }
623
+ return origError;
624
+ }
625
+ panicOwnError(text, hierarchy) {
626
+ const e = new Error(text + (hierarchy ? '\nHierarchy:\n' + hierarchy.join(' -> ') : ''));
627
+ if (this._silent === true) {
628
+ return e;
629
+ }
630
+ else {
631
+ this.logger.error(e);
632
+ return e;
633
+ }
634
+ }
635
+ }
636
+ function getProvidedValue(meta) {
637
+ if (!meta.resolved) {
638
+ meta.resolved = true;
639
+ meta.value = meta.fn();
640
+ }
641
+ return meta.value;
642
+ }
643
+
644
+ async function runPipes(pipes, initialValue, metas, level) {
645
+ let v = initialValue;
646
+ for (const pipe of pipes) {
647
+ v = await pipe.handler(v, metas, level);
648
+ }
649
+ return v;
650
+ }
651
+
652
+ function getConstructor(instance) {
653
+ return isConstructor(instance) ?
654
+ instance : instance.constructor ?
655
+ instance.constructor : Object.getPrototypeOf(instance).constructor;
656
+ }
657
+ function isConstructor(v) {
658
+ return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
659
+ }
660
+
661
+ const classMetadata = new WeakMap();
662
+ const paramMetadata = new WeakMap();
663
+ const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
664
+ function getMetaObject(target, prop) {
665
+ const isParam = typeof prop !== 'undefined';
666
+ const metadata = isParam ? paramMetadata : classMetadata;
667
+ const targetKey = getConstructor(target);
668
+ let meta = metadata.get(targetKey);
669
+ if (!meta) {
670
+ meta = {};
671
+ metadata.set(targetKey, meta);
672
+ }
673
+ if (isParam) {
674
+ meta = (meta[prop] =
675
+ meta[prop] || {});
676
+ }
677
+ return meta;
678
+ }
679
+ const _reflect = {
680
+ getOwnMetadata(key, target, prop) {
681
+ return getMetaObject(target, prop)[key];
682
+ },
683
+ defineMetadata(key, data, target, prop) {
684
+ const meta = getMetaObject(target, prop);
685
+ meta[key] = data;
686
+ },
687
+ metadata(key, data) {
688
+ return ((target, propKey) => {
689
+ Reflect$1.defineMetadata(key, data, target, propKey);
690
+ });
691
+ },
692
+ };
693
+ if (!root.Reflect) {
694
+ root.Reflect = _reflect;
695
+ }
696
+ else {
697
+ const funcs = [
698
+ 'getOwnMetadata',
699
+ 'defineMetadata',
700
+ 'metadata',
701
+ ];
702
+ const target = root.Reflect;
703
+ for (const func of funcs) {
704
+ if (typeof target[func] !== 'function') {
705
+ Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
706
+ }
707
+ }
708
+ }
709
+ const Reflect$1 = _reflect;
710
+
711
+ const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
712
+ class Mate {
713
+ constructor(workspace, options = {}) {
714
+ this.workspace = workspace;
715
+ this.options = options;
716
+ this.logger = options.logger || console;
717
+ }
718
+ set(args, key, value, isArray) {
719
+ var _a;
720
+ let level = 'CLASS';
721
+ const newArgs = args.level === 'CLASS' ? { target: args.target }
722
+ : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
723
+ : args;
724
+ let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
725
+ if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
726
+ meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
727
+ }
728
+ if (newArgs.propKey && this.options.readType && !meta.type) {
729
+ meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
730
+ }
731
+ const { index } = newArgs;
732
+ const cb = typeof key === 'function' ? key : undefined;
733
+ let data = meta;
734
+ if (!data.params) {
735
+ data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
736
+ }
737
+ if (typeof index === 'number') {
738
+ level = 'PARAM';
739
+ data.params = data.params || [];
740
+ data.params[index] = data.params[index] || {
741
+ type: undefined,
742
+ };
743
+ if (cb) {
744
+ data.params[index] = cb(data.params[index], level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
745
+ }
746
+ else {
747
+ data = data.params[index];
748
+ }
749
+ }
750
+ else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
751
+ this.set({ ...args, level: 'CLASS' }, (meta) => {
752
+ if (!meta.properties) {
753
+ meta.properties = [args.propKey];
754
+ }
755
+ else if (!meta.properties.includes(args.propKey)) {
756
+ meta.properties.push(args.propKey);
757
+ }
758
+ return meta;
759
+ });
760
+ }
761
+ level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
762
+ if (typeof key !== 'function') {
763
+ if (isArray) {
764
+ const newArray = (data[key] || []);
765
+ if (!Array.isArray(newArray)) {
766
+ this.logger.error('Mate.add (isArray=true) called for non-array metadata');
767
+ }
768
+ newArray.unshift(value);
769
+ data[key] = newArray;
770
+ }
771
+ else {
772
+ data[key] = value;
773
+ }
774
+ }
775
+ else if (cb && typeof index !== 'number') {
776
+ meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
777
+ }
778
+ Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
779
+ }
780
+ read(target, propKey) {
781
+ var _a;
782
+ const isConstr = isConstructor(target);
783
+ const constructor = isConstr ? target : getConstructor(target);
784
+ const proto = constructor.prototype;
785
+ let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
786
+ if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
787
+ const parent = Object.getPrototypeOf(constructor);
788
+ if (typeof parent === 'function' &&
789
+ parent !== fnProto &&
790
+ parent !== constructor) {
791
+ ownMeta.params = (_a = this.read(parent)) === null || _a === void 0 ? void 0 : _a.params;
792
+ }
793
+ }
794
+ if (this.options.inherit) {
795
+ const inheritFn = typeof this.options.inherit === 'function'
796
+ ? this.options.inherit
797
+ : undefined;
798
+ let shouldInherit = this.options.inherit;
799
+ if (inheritFn) {
800
+ if (typeof propKey === 'string') {
801
+ const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
802
+ shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
803
+ }
804
+ else {
805
+ shouldInherit = inheritFn(ownMeta, ownMeta, 'CLASS');
806
+ }
807
+ }
808
+ if (shouldInherit) {
809
+ const parent = Object.getPrototypeOf(constructor);
810
+ if (typeof parent === 'function' &&
811
+ parent !== fnProto &&
812
+ parent !== constructor) {
813
+ const inheritedMeta = (this.read(parent, propKey) ||
814
+ {});
815
+ const ownParams = ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params;
816
+ ownMeta = { ...inheritedMeta, ...ownMeta };
817
+ if (typeof propKey === 'string' &&
818
+ ownParams &&
819
+ (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
820
+ for (let i = 0; i < ownParams.length; i++) {
821
+ if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
822
+ 'undefined') {
823
+ const ownParam = ownParams[i];
824
+ if (ownMeta.params &&
825
+ inheritFn &&
826
+ inheritFn(ownMeta, ownParam, 'PARAM', typeof propKey === 'string'
827
+ ? propKey
828
+ : undefined)) {
829
+ ownMeta.params[i] = {
830
+ ...inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i],
831
+ ...ownParams[i],
832
+ };
833
+ }
834
+ }
835
+ }
836
+ }
837
+ }
838
+ }
839
+ }
840
+ return ownMeta;
841
+ }
842
+ apply(...decorators) {
843
+ return ((target, propKey, descriptor) => {
844
+ for (const d of decorators) {
845
+ d(target, propKey, descriptor);
846
+ }
847
+ });
848
+ }
849
+ decorate(key, value, isArray, level) {
850
+ return ((target, propKey, descriptor) => {
851
+ const args = {
852
+ target,
853
+ propKey,
854
+ descriptor: typeof descriptor === 'number' ? undefined : descriptor,
855
+ index: typeof descriptor === 'number' ? descriptor : undefined,
856
+ level,
857
+ };
858
+ this.set(args, key, value, isArray);
859
+ });
860
+ }
861
+ decorateConditional(ccb) {
862
+ return ((target, propKey, descriptor) => {
863
+ const hasIndex = typeof descriptor === 'number';
864
+ const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
865
+ const d = ccb(decoratorLevel);
866
+ if (d) {
867
+ d(target, propKey, descriptor);
868
+ }
869
+ });
870
+ }
871
+ decorateClass(key, value, isArray) {
872
+ return this.decorate(key, value, isArray, 'CLASS');
873
+ }
874
+ }
875
+ const fnProto = Object.getPrototypeOf(Function);
876
+
877
+ const METADATA_WORKSPACE = 'moost';
878
+ const moostMate = new Mate(METADATA_WORKSPACE, {
879
+ readType: true,
880
+ readReturnType: true,
881
+ collectPropKeys: true,
882
+ inherit(classMeta, targetMeta, level) {
883
+ if (level === 'CLASS') {
884
+ return !!classMeta?.inherit;
885
+ }
886
+ if (level === 'PROP') {
887
+ return !!targetMeta?.inherit || !!(classMeta?.inherit && !targetMeta);
888
+ }
889
+ return !!targetMeta?.inherit;
890
+ },
891
+ });
892
+ function getMoostMate() {
893
+ return moostMate;
894
+ }
895
+
896
+ getNewMoostInfact();
897
+ function getNewMoostInfact() {
898
+ return new Infact({
899
+ describeClass(classConstructor) {
900
+ const meta = getMoostMate().read(classConstructor);
901
+ return {
902
+ injectable: !!meta?.injectable,
903
+ global: false,
904
+ constructorParams: meta?.params || [],
905
+ provide: meta?.provide,
906
+ properties: meta?.properties || [],
907
+ scopeId: meta?.injectable === 'FOR_EVENT' ? useEventId().getId() : undefined,
908
+ };
909
+ },
910
+ resolveParam({ paramMeta, classMeta, customData, classConstructor, index }) {
911
+ if (paramMeta && customData?.pipes) {
912
+ return runPipes(customData.pipes, undefined, {
913
+ paramMeta,
914
+ type: classConstructor,
915
+ key: 'constructor',
916
+ classMeta: classMeta,
917
+ index,
918
+ targetMeta: paramMeta,
919
+ }, 'PARAM');
920
+ }
921
+ },
922
+ describeProp(classConstructor, key) {
923
+ const meta = getMoostMate().read(classConstructor, key);
924
+ return meta;
925
+ },
926
+ resolveProp({ instance, key, initialValue, propMeta, classMeta, customData, classConstructor, }) {
927
+ if (propMeta && customData?.pipes) {
928
+ return runPipes(customData.pipes, initialValue, {
929
+ instance,
930
+ type: classConstructor,
931
+ key,
932
+ propMeta,
933
+ targetMeta: propMeta,
934
+ classMeta: classMeta,
935
+ }, 'PROP');
936
+ }
937
+ },
938
+ storeProvideRegByInstance: true,
939
+ });
940
+ }
941
+
942
+ getMoostMate().decorate(meta => {
943
+ if (!meta.injectable) {
944
+ meta.injectable = true;
945
+ }
946
+ return meta;
947
+ });
948
+
949
+ var TInterceptorPriority;
950
+ (function (TInterceptorPriority) {
951
+ TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
952
+ TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
953
+ TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
954
+ TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
955
+ TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
956
+ TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
957
+ TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
958
+ })(TInterceptorPriority || (TInterceptorPriority = {}));
959
+
960
+ var TPipePriority;
961
+ (function (TPipePriority) {
962
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
963
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
964
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
965
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
966
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
967
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
968
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
969
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
970
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
971
+ })(TPipePriority || (TPipePriority = {}));
972
+
973
+ function definePipeFn(fn, priority = TPipePriority.TRANSFORM) {
974
+ fn.priority = priority;
975
+ return fn;
976
+ }
977
+
978
+ const resolvePipe = definePipeFn((_value, metas, level) => {
979
+ const resolver = metas.targetMeta?.resolver;
980
+ if (resolver) {
981
+ return resolver(metas, level);
982
+ }
983
+ return undefined;
984
+ }, TPipePriority.RESOLVE);
985
+
986
+ [
987
+ {
988
+ handler: resolvePipe,
989
+ priority: TPipePriority.RESOLVE,
990
+ },
991
+ ];
992
+
993
+ function getOtelMate() {
994
+ return getMoostMate();
995
+ }
996
+
997
+ const mate = getOtelMate();
998
+ const OtelIgnoreSpan = () => mate.decorate('otelIgnoreSpan', true);
999
+
1000
+ function shouldSpanBeIgnored(span) {
1001
+ return span.attributes['moost.ignore'] === true;
1002
+ }
1003
+
1004
+ class MoostBatchSpanProcessor extends BatchSpanProcessor {
1005
+ onEnd(span) {
1006
+ if (shouldSpanBeIgnored(span)) {
1007
+ return;
1008
+ }
1009
+ super.onEnd(span);
1010
+ }
1011
+ }
1012
+
1013
+ class MoostSimpleSpanProcessor extends SimpleSpanProcessor {
1014
+ onEnd(span) {
1015
+ if (shouldSpanBeIgnored(span)) {
1016
+ return;
1017
+ }
1018
+ super.onEnd(span);
1019
+ }
1020
+ }
1021
+
1022
+ export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreSpan, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace };