@moostjs/otel 0.5.21 → 0.5.23

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,2622 +1,332 @@
1
- import { trace, context, metrics, SpanStatusCode, SpanKind } from '@opentelemetry/api';
2
- import { useAsyncEventContext, ContextInjector, useControllerContext, getConstructor as getConstructor$1, replaceContextInjector } from 'moost';
3
- import 'crypto';
4
- import { AsyncLocalStorage } from 'node:async_hooks';
5
- import { BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
1
+ import { SpanKind, SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
2
+ import { ContextInjector, getConstructor, getMoostMate, replaceContextInjector, useAsyncEventContext, useControllerContext } from "moost";
3
+ import { BatchSpanProcessor, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
6
4
 
5
+ //#region packages/otel/src/context.ts
7
6
  const spanStack = [];
8
7
  function useOtelContext() {
9
- const eventContext = useAsyncEventContext();
10
- const store = eventContext.store('otel');
11
- const csa = eventContext.store('customSpanAttrs');
12
- const cma = eventContext.store('customMetricAttrs');
13
- const customSpanAttr = (name, value) => csa.set(name, value);
14
- const customMetricAttr = (name, value) => cma.set(name, value);
15
- const getSpan = () => store.get('span');
16
- const getSpanContext = () => {
17
- const span = getSpan();
18
- if (span) {
19
- return span.spanContext();
20
- }
21
- };
22
- const getPropagationHeaders = () => {
23
- const c = getSpanContext();
24
- if (c) {
25
- return {
26
- traceparent: `00-${c.traceId}-${c.spanId}-${c.traceFlags}`,
27
- tracestate: c.traceState,
28
- };
29
- }
30
- return {};
31
- };
32
- const pushSpan = (span) => {
33
- const activeSpan = trace.getActiveSpan();
34
- if (activeSpan) {
35
- const origEnd = activeSpan.end;
36
- Object.assign(activeSpan, {
37
- end: (t) => {
38
- popSpan();
39
- const i = spanStack.indexOf(activeSpan);
40
- if (i >= 0) {
41
- spanStack.splice(i, 1);
42
- }
43
- origEnd.apply(span, [t]);
44
- },
45
- });
46
- spanStack.push(activeSpan);
47
- }
48
- trace.setSpan(context.active(), span);
49
- };
50
- const popSpan = () => {
51
- const span = spanStack.pop();
52
- if (span) {
53
- trace.setSpan(context.active(), span);
54
- }
55
- };
56
- return {
57
- trace,
58
- withChildSpan: (name, cb, opts) => {
59
- const tracer = trace.getTracer('moost-tracer');
60
- const span = tracer.startSpan(name, opts);
61
- return () => context.with(trace.setSpan(context.active(), span), cb);
62
- },
63
- getSpan,
64
- getSpanContext,
65
- getPropagationHeaders,
66
- registerSpan: (span) => store.set('span', span),
67
- pushSpan,
68
- customSpanAttr,
69
- customMetricAttr,
70
- };
8
+ const eventContext = useAsyncEventContext();
9
+ const store = eventContext.store("otel");
10
+ const csa = eventContext.store("customSpanAttrs");
11
+ const cma = eventContext.store("customMetricAttrs");
12
+ const customSpanAttr = (name, value) => csa.set(name, value);
13
+ const customMetricAttr = (name, value) => cma.set(name, value);
14
+ const getSpan = () => store.get("span");
15
+ const getSpanContext = () => {
16
+ const span = getSpan();
17
+ if (span) return span.spanContext();
18
+ };
19
+ const getPropagationHeaders = () => {
20
+ const c = getSpanContext();
21
+ if (c) return {
22
+ traceparent: `00-${c.traceId}-${c.spanId}-${c.traceFlags}`,
23
+ tracestate: c.traceState
24
+ };
25
+ return {};
26
+ };
27
+ const pushSpan = (span) => {
28
+ const activeSpan = trace.getActiveSpan();
29
+ if (activeSpan) {
30
+ const origEnd = activeSpan.end;
31
+ Object.assign(activeSpan, { end: (t) => {
32
+ popSpan();
33
+ const i = spanStack.indexOf(activeSpan);
34
+ if (i >= 0) spanStack.splice(i, 1);
35
+ origEnd.apply(span, [t]);
36
+ } });
37
+ spanStack.push(activeSpan);
38
+ }
39
+ trace.setSpan(context.active(), span);
40
+ };
41
+ const popSpan = () => {
42
+ const span = spanStack.pop();
43
+ if (span) trace.setSpan(context.active(), span);
44
+ };
45
+ return {
46
+ trace,
47
+ withChildSpan: (name, cb, opts) => {
48
+ const tracer$1 = trace.getTracer("moost-tracer");
49
+ const span = tracer$1.startSpan(name, opts);
50
+ return () => context.with(trace.setSpan(context.active(), span), cb);
51
+ },
52
+ getSpan,
53
+ getSpanContext,
54
+ getPropagationHeaders,
55
+ registerSpan: (span) => store.set("span", span),
56
+ pushSpan,
57
+ customSpanAttr,
58
+ customMetricAttr
59
+ };
71
60
  }
72
61
  function useTrace() {
73
- return trace;
62
+ return trace;
74
63
  }
75
64
  function useSpan() {
76
- return useOtelContext().getSpan();
65
+ return useOtelContext().getSpan();
77
66
  }
78
67
  function useOtelPropagation() {
79
- const { getPropagationHeaders, getSpanContext } = useOtelContext();
80
- return {
81
- ...getSpanContext(),
82
- headers: getPropagationHeaders(),
83
- };
68
+ const { getPropagationHeaders, getSpanContext } = useOtelContext();
69
+ return {
70
+ ...getSpanContext(),
71
+ headers: getPropagationHeaders()
72
+ };
84
73
  }
85
74
 
75
+ //#endregion
76
+ //#region packages/otel/src/metrics.ts
86
77
  let moostMetrics;
87
78
  function getMoostMetrics() {
88
- if (!moostMetrics) {
89
- const meter = metrics.getMeter('moost-meter');
90
- moostMetrics = {
91
- moostEventDuration: meter.createHistogram('moost.event.duration', {
92
- description: 'Moost Event Duration Histogram',
93
- unit: 'ms',
94
- }),
95
- };
96
- }
97
- return moostMetrics;
79
+ if (!moostMetrics) {
80
+ const meter = metrics.getMeter("moost-meter");
81
+ moostMetrics = { moostEventDuration: meter.createHistogram("moost.event.duration", {
82
+ description: "Moost Event Duration Histogram",
83
+ unit: "ms"
84
+ }) };
85
+ }
86
+ return moostMetrics;
98
87
  }
99
88
 
89
+ //#endregion
90
+ //#region packages/otel/src/utils.ts
100
91
  function withSpan(span, cb, postProcess) {
101
- const _span = typeof span.name === 'string' && !span.spanContext
102
- ? trace
103
- .getTracer('default')
104
- .startSpan(span.name, span.options)
105
- : span;
106
- let result = undefined;
107
- const finalizeSpan = (e, r) => {
108
- if (e) {
109
- _span.recordException(e);
110
- _span.setStatus({
111
- code: SpanStatusCode.ERROR,
112
- message: e.message || 'Unknown Error',
113
- });
114
- }
115
- if (postProcess) {
116
- postProcess(_span, e, r);
117
- }
118
- else {
119
- _span.end();
120
- }
121
- };
122
- context.with(trace.setSpan(context.active(), _span), () => {
123
- try {
124
- result = cb();
125
- }
126
- catch (error) {
127
- finalizeSpan(error, undefined);
128
- throw error;
129
- }
130
- if (result instanceof Promise) {
131
- result
132
- .then(r => {
133
- finalizeSpan(undefined, r);
134
- return r;
135
- })
136
- .catch(error => {
137
- finalizeSpan(error, undefined);
138
- });
139
- }
140
- else {
141
- finalizeSpan(undefined, result);
142
- }
143
- });
144
- return result;
145
- }
146
-
147
- const tracer = trace.getTracer('moost-tracer');
148
- class SpanInjector extends ContextInjector {
149
- constructor() {
150
- super(...arguments);
151
- this.metrics = getMoostMetrics();
152
- }
153
- with(name, attributes, cb) {
154
- const fn = typeof attributes === 'function' ? attributes : cb;
155
- const attrs = typeof attributes === 'object' ? attributes : undefined;
156
- if (name === 'Event:start' && attrs?.eventType) {
157
- return this.startEvent(attrs.eventType, fn);
158
- }
159
- else if (name !== 'Event:start') {
160
- if (this.getIgnoreSpan()) {
161
- return fn();
162
- }
163
- else {
164
- const span = tracer.startSpan(name, {
165
- kind: SpanKind.INTERNAL,
166
- attributes: attrs,
167
- });
168
- return this.withSpan(span, fn, {
169
- withMetrics: false,
170
- endSpan: true,
171
- });
172
- }
173
- }
174
- return fn();
175
- }
176
- patchRsponse() {
177
- const res = this.getResponse();
178
- if (res) {
179
- const originalWriteHead = res.writeHead;
180
- Object.assign(res, {
181
- writeHead: (arg0, arg1, arg2) => {
182
- res._statusCode = arg0;
183
- const headers = typeof arg2 === 'object' ? arg2 : typeof arg1 === 'object' ? arg1 : undefined;
184
- res._contentLength = headers?.['content-length'] ? Number(headers['content-length']) : 0;
185
- return originalWriteHead.apply(res, [arg0, arg1, arg2]);
186
- },
187
- });
188
- }
189
- }
190
- startEvent(eventType, cb) {
191
- if (eventType === 'init') {
192
- return cb();
193
- }
194
- const { registerSpan } = useOtelContext();
195
- let span = trace.getActiveSpan();
196
- if (eventType === 'HTTP') {
197
- this.patchRsponse();
198
- }
199
- else {
200
- span = tracer.startSpan(`${eventType} Event`);
201
- }
202
- if (span) {
203
- registerSpan(span);
204
- return this.withSpan(span, cb, {
205
- withMetrics: true,
206
- endSpan: eventType !== 'HTTP',
207
- });
208
- }
209
- return cb();
210
- }
211
- getEventType() {
212
- return useAsyncEventContext().getCtx().event.type;
213
- }
214
- getIgnoreSpan() {
215
- const { getMethodMeta, getControllerMeta } = useControllerContext();
216
- const cMeta = getControllerMeta();
217
- const mMeta = getMethodMeta();
218
- return cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan;
219
- }
220
- getControllerHandlerMeta() {
221
- const { getMethod, getMethodMeta, getController, getControllerMeta, getRoute } = useControllerContext();
222
- const methodName = getMethod();
223
- const controller = getController();
224
- const cMeta = controller ? getControllerMeta() : undefined;
225
- const mMeta = controller ? getMethodMeta() : undefined;
226
- return {
227
- ignoreMeter: cMeta?.otelIgnoreMeter || mMeta?.otelIgnoreMeter,
228
- ignoreSpan: cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
229
- attrs: {
230
- 'moost.controller': controller ? getConstructor$1(controller).name : undefined,
231
- 'moost.handler': methodName,
232
- 'moost.handler_description': mMeta?.description,
233
- 'moost.handler_label': mMeta?.label,
234
- 'moost.handler_id': mMeta?.id,
235
- 'moost.ignore': cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
236
- 'moost.route': getRoute(),
237
- 'moost.event_type': this.getEventType(),
238
- },
239
- };
240
- }
241
- hook(method, name, route) {
242
- if (method === 'WF_STEP') {
243
- return;
244
- }
245
- if (method === '__SYSTEM__') {
246
- return;
247
- }
248
- const { getSpan } = useOtelContext();
249
- if (name === 'Handler:not_found') {
250
- const chm = this.getControllerHandlerMeta();
251
- const span = getSpan();
252
- if (span) {
253
- const eventType = this.getEventType();
254
- if (eventType === 'HTTP') {
255
- const req = this.getRequest();
256
- span.updateName(`${req?.method || ''} ${req?.url}`);
257
- }
258
- }
259
- this.startEventMetrics(chm.attrs, route);
260
- }
261
- else if (name === 'Controller:registered') {
262
- const _route = useAsyncEventContext().store('otel').get('route');
263
- const chm = this.getControllerHandlerMeta();
264
- if (!chm.ignoreMeter) {
265
- this.startEventMetrics(chm.attrs, _route);
266
- }
267
- const span = getSpan();
268
- if (span) {
269
- span.setAttributes(chm.attrs);
270
- if (chm.attrs['moost.event_type'] === 'HTTP') {
271
- span.updateName(`${this.getRequest()?.method || ''} ${_route || '<unresolved>'}`);
272
- }
273
- else {
274
- span.updateName(`${chm.attrs['moost.event_type']} ${_route || '<unresolved>'}`);
275
- }
276
- }
277
- }
278
- if (name !== 'Controller:registered') {
279
- useAsyncEventContext().store('otel').set('route', route);
280
- }
281
- }
282
- withSpan(span, cb, opts) {
283
- return withSpan(span, cb, (_span, exception, result) => {
284
- if (result instanceof Error) {
285
- _span.recordException(result);
286
- }
287
- if (opts.withMetrics) {
288
- const chm = this.getControllerHandlerMeta();
289
- if (!chm.ignoreMeter) {
290
- this.endEventMetrics(chm.attrs, result instanceof Error ? result : exception);
291
- }
292
- }
293
- if (opts.endSpan) {
294
- const customAttrs = useAsyncEventContext().store('customSpanAttrs').value;
295
- if (customAttrs) {
296
- _span.setAttributes(customAttrs);
297
- }
298
- _span.end();
299
- }
300
- });
301
- }
302
- startEventMetrics(a, route) {
303
- useAsyncEventContext().store('otel').set('startTime', Date.now());
304
- }
305
- endEventMetrics(a, error) {
306
- const otelStore = useAsyncEventContext().store('otel');
307
- const route = otelStore.get('route');
308
- const duration = Date.now() - (otelStore.get('startTime') || Date.now() - 1);
309
- const customAttrs = useAsyncEventContext().store('customMetricAttrs').value || {};
310
- const attrs = {
311
- ...customAttrs,
312
- route,
313
- 'moost.event_type': a['moost.event_type'],
314
- 'moost.is_error': error ? 1 : 0,
315
- };
316
- if (a['moost.event_type'] === 'HTTP') {
317
- if (!attrs.route) {
318
- attrs.route = this.getRequest()?.url || '';
319
- }
320
- attrs['http.status_code'] = this.getResponse()?._statusCode || 0;
321
- attrs['moost.is_error'] = attrs['moost.is_error'] || attrs['http.status_code'] > 399 ? 1 : 0;
322
- }
323
- this.metrics.moostEventDuration.record(duration, attrs);
324
- }
325
- getRequest() {
326
- return useAsyncEventContext().store('event').get('req');
327
- }
328
- getResponse() {
329
- return useAsyncEventContext()
330
- .store('event')
331
- .get('res');
332
- }
333
- }
334
-
335
- function enableOtelForMoost() {
336
- replaceContextInjector(new SpanInjector());
337
- }
338
-
339
- function getConstructor(instance) {
340
- return isConstructor(instance) ?
341
- instance : instance.constructor ?
342
- instance.constructor : Object.getPrototypeOf(instance).constructor;
343
- }
344
- function isConstructor(v) {
345
- return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
346
- }
347
-
348
- let classMetadata = new WeakMap();
349
- let paramMetadata = new WeakMap();
350
- const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
351
- function getMetaObject(target, prop) {
352
- const isParam = typeof prop !== 'undefined';
353
- const metadata = isParam ? paramMetadata : classMetadata;
354
- const targetKey = getConstructor(target);
355
- let meta = metadata.get(targetKey);
356
- if (!meta) {
357
- meta = {};
358
- metadata.set(targetKey, meta);
359
- }
360
- if (isParam) {
361
- meta = (meta[prop] =
362
- meta[prop] || {});
363
- }
364
- return meta;
365
- }
366
- const _reflect = {
367
- getOwnMetadata(key, target, prop) {
368
- return getMetaObject(target, prop)[key];
369
- },
370
- defineMetadata(key, data, target, prop) {
371
- const meta = getMetaObject(target, prop);
372
- meta[key] = data;
373
- },
374
- metadata(key, data) {
375
- return ((target, propKey) => {
376
- Reflect$1.defineMetadata(key, data, target, propKey);
377
- });
378
- },
379
- _cleanup: (() => {
380
- classMetadata = new WeakMap();
381
- paramMetadata = new WeakMap();
382
- }),
383
- };
384
- if (!root.Reflect) {
385
- root.Reflect = _reflect;
386
- }
387
- else {
388
- const funcs = [
389
- 'getOwnMetadata',
390
- 'defineMetadata',
391
- 'metadata',
392
- ];
393
- const target = root.Reflect;
394
- for (const func of funcs) {
395
- if (typeof target[func] !== 'function') {
396
- Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
397
- }
398
- }
399
- }
400
- const Reflect$1 = _reflect;
401
-
402
- const Reflect$2 = ((global === null || global === void 0 ? void 0 : global.Reflect) ||
403
- (self === null || self === void 0 ? void 0 : self.Reflect) ||
404
- Reflect$1);
405
- class Mate {
406
- constructor(workspace, options = {}) {
407
- this.workspace = workspace;
408
- this.options = options;
409
- this.logger = options.logger || console;
410
- }
411
- _cleanup() {
412
- var _a;
413
- (_a = Reflect$2._cleanup) === null || _a === void 0 ? void 0 : _a.call(Reflect$2);
414
- }
415
- set(args, key, value, isArray) {
416
- var _a;
417
- let level = 'CLASS';
418
- const newArgs = args.level === 'CLASS'
419
- ? { target: args.target }
420
- : args.level === 'PROP'
421
- ? { target: args.target, propKey: args.propKey }
422
- : args;
423
- let meta = (Reflect$2.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
424
- if (newArgs.propKey &&
425
- this.options.readReturnType &&
426
- !meta.returnType &&
427
- args.descriptor) {
428
- meta.returnType = Reflect$2.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
429
- }
430
- if (newArgs.propKey && this.options.readType && !meta.type) {
431
- meta.type = Reflect$2.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
432
- }
433
- const { index } = newArgs;
434
- const cb = typeof key === 'function' ? key : undefined;
435
- let data = meta;
436
- if (!data.params) {
437
- data.params = (_a = Reflect$2.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
438
- }
439
- if (typeof index === 'number') {
440
- level = 'PARAM';
441
- data.params = data.params || [];
442
- data.params[index] = data.params[index] || {
443
- type: undefined,
444
- };
445
- if (cb) {
446
- data.params[index] = cb(data.params[index], level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
447
- }
448
- else {
449
- data = data.params[index];
450
- }
451
- }
452
- else if (!index &&
453
- !args.descriptor &&
454
- args.propKey &&
455
- this.options.collectPropKeys &&
456
- args.level !== 'CLASS') {
457
- this.set({ ...args, level: 'CLASS' }, (meta) => {
458
- if (!meta.properties) {
459
- meta.properties = [args.propKey];
460
- }
461
- else if (!meta.properties.includes(args.propKey)) {
462
- meta.properties.push(args.propKey);
463
- }
464
- return meta;
465
- });
466
- }
467
- level =
468
- typeof index === 'number'
469
- ? 'PARAM'
470
- : newArgs.propKey && newArgs.descriptor
471
- ? 'METHOD'
472
- : newArgs.propKey
473
- ? 'PROP'
474
- : 'CLASS';
475
- if (typeof key !== 'function') {
476
- if (isArray) {
477
- const newArray = (data[key] || []);
478
- if (!Array.isArray(newArray)) {
479
- this.logger.error('Mate.add (isArray=true) called for non-array metadata');
480
- }
481
- newArray.unshift(value);
482
- data[key] = newArray;
483
- }
484
- else {
485
- data[key] = value;
486
- }
487
- }
488
- else if (cb && typeof index !== 'number') {
489
- meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
490
- }
491
- Reflect$2.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
492
- }
493
- read(target, propKey) {
494
- var _a;
495
- const isConstr = isConstructor(target);
496
- const constructor = isConstr ? target : getConstructor(target);
497
- const proto = constructor.prototype;
498
- let ownMeta = Reflect$2.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
499
- if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
500
- const parent = Object.getPrototypeOf(constructor);
501
- if (typeof parent === 'function' &&
502
- parent !== fnProto &&
503
- parent !== constructor) {
504
- ownMeta.params = (_a = this.read(parent)) === null || _a === void 0 ? void 0 : _a.params;
505
- }
506
- }
507
- if (this.options.inherit) {
508
- const inheritFn = typeof this.options.inherit === 'function'
509
- ? this.options.inherit
510
- : undefined;
511
- let shouldInherit = this.options.inherit;
512
- if (inheritFn) {
513
- if (typeof propKey === 'string') {
514
- const classMeta = Reflect$2.getOwnMetadata(this.workspace, constructor);
515
- shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
516
- }
517
- else {
518
- shouldInherit = inheritFn(ownMeta, ownMeta, 'CLASS');
519
- }
520
- }
521
- if (shouldInherit) {
522
- const parent = Object.getPrototypeOf(constructor);
523
- if (typeof parent === 'function' &&
524
- parent !== fnProto &&
525
- parent !== constructor) {
526
- const inheritedMeta = (this.read(parent, propKey) ||
527
- {});
528
- const ownParams = ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params;
529
- ownMeta = { ...inheritedMeta, ...ownMeta };
530
- if (typeof propKey === 'string' &&
531
- ownParams &&
532
- (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
533
- for (let i = 0; i < ownParams.length; i++) {
534
- if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !== 'undefined') {
535
- const ownParam = ownParams[i];
536
- if (ownMeta.params &&
537
- inheritFn &&
538
- inheritFn(ownMeta, ownParam, 'PARAM', typeof propKey === 'string'
539
- ? propKey
540
- : undefined)) {
541
- ownMeta.params[i] = {
542
- ...inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i],
543
- ...ownParams[i],
544
- };
545
- }
546
- }
547
- }
548
- }
549
- }
550
- }
551
- }
552
- return ownMeta;
553
- }
554
- apply(...decorators) {
555
- return ((target, propKey, descriptor) => {
556
- for (const d of decorators) {
557
- d(target, propKey, descriptor);
558
- }
559
- });
560
- }
561
- decorate(key, value, isArray, level) {
562
- return ((target, propKey, descriptor) => {
563
- const args = {
564
- target,
565
- propKey,
566
- descriptor: typeof descriptor === 'number' ? undefined : descriptor,
567
- index: typeof descriptor === 'number' ? descriptor : undefined,
568
- level,
569
- };
570
- this.set(args, key, value, isArray);
571
- });
572
- }
573
- decorateConditional(ccb) {
574
- return ((target, propKey, descriptor) => {
575
- const hasIndex = typeof descriptor === 'number';
576
- const decoratorLevel = hasIndex
577
- ? 'PARAM'
578
- : propKey && descriptor
579
- ? 'METHOD'
580
- : propKey
581
- ? 'PROP'
582
- : 'CLASS';
583
- const d = ccb(decoratorLevel);
584
- if (d) {
585
- d(target, propKey, descriptor);
586
- }
587
- });
588
- }
589
- decorateClass(key, value, isArray) {
590
- return this.decorate(key, value, isArray, 'CLASS');
591
- }
592
- }
593
- const fnProto = Object.getPrototypeOf(Function);
594
-
595
- const defaultLevels = [
596
- 'fatal',
597
- 'error',
598
- 'warn',
599
- 'log',
600
- 'info',
601
- 'debug',
602
- 'trace',
603
- ];
604
- const defaultMappedLevels = new Map();
605
- defaultLevels.forEach((type, level) => defaultMappedLevels.set(type, level));
606
-
607
- new AsyncLocalStorage();
608
-
609
- const METADATA_WORKSPACE = 'moost';
610
- const moostMate = new Mate(METADATA_WORKSPACE, {
611
- readType: true,
612
- readReturnType: true,
613
- collectPropKeys: true,
614
- inherit(classMeta, targetMeta, level) {
615
- if (level === 'CLASS') {
616
- return !!classMeta?.inherit;
617
- }
618
- if (level === 'PROP') {
619
- return !!targetMeta?.inherit || !!(classMeta?.inherit && !targetMeta);
620
- }
621
- return !!targetMeta?.inherit;
622
- },
623
- });
624
- function getMoostMate() {
625
- return moostMate;
92
+ const _span = typeof span.name === "string" && !span.spanContext ? trace.getTracer("default").startSpan(span.name, span.options) : span;
93
+ let result = undefined;
94
+ const finalizeSpan = (e, r) => {
95
+ if (e) {
96
+ _span.recordException(e);
97
+ _span.setStatus({
98
+ code: SpanStatusCode.ERROR,
99
+ message: e.message || "Unknown Error"
100
+ });
101
+ }
102
+ if (postProcess) postProcess(_span, e, r);
103
+ else _span.end();
104
+ };
105
+ context.with(trace.setSpan(context.active(), _span), () => {
106
+ try {
107
+ result = cb();
108
+ } catch (error) {
109
+ finalizeSpan(error, undefined);
110
+ throw error;
111
+ }
112
+ if (result instanceof Promise) result.then((r) => {
113
+ finalizeSpan(undefined, r);
114
+ return r;
115
+ }).catch((error) => {
116
+ finalizeSpan(error, undefined);
117
+ });
118
+ else finalizeSpan(undefined, result);
119
+ });
120
+ return result;
626
121
  }
627
122
 
628
- getMoostMate().decorate(meta => {
629
- if (!meta.injectable) {
630
- meta.injectable = true;
631
- }
632
- return meta;
633
- });
634
-
635
- var TInterceptorPriority;
636
- (function (TInterceptorPriority) {
637
- TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
638
- TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
639
- TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
640
- TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
641
- TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
642
- TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
643
- TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
644
- })(TInterceptorPriority || (TInterceptorPriority = {}));
645
-
646
- var TPipePriority;
647
- (function (TPipePriority) {
648
- TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
649
- TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
650
- TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
651
- TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
652
- TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
653
- TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
654
- TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
655
- TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
656
- TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
657
- })(TPipePriority || (TPipePriority = {}));
658
-
659
- function definePipeFn(fn, priority = TPipePriority.TRANSFORM) {
660
- fn.priority = priority;
661
- return fn;
123
+ //#endregion
124
+ //#region packages/otel/src/span-injector.ts
125
+ function _define_property(obj, key, value) {
126
+ if (key in obj) Object.defineProperty(obj, key, {
127
+ value,
128
+ enumerable: true,
129
+ configurable: true,
130
+ writable: true
131
+ });
132
+ else obj[key] = value;
133
+ return obj;
662
134
  }
663
-
664
- const resolvePipe = definePipeFn((_value, metas, level) => {
665
- const resolver = metas.targetMeta?.resolver;
666
- if (resolver) {
667
- return resolver(metas, level);
668
- }
669
- return undefined;
670
- }, TPipePriority.RESOLVE);
671
-
672
- [
673
- {
674
- handler: resolvePipe,
675
- priority: TPipePriority.RESOLVE,
676
- },
677
- ];
678
-
679
- function getAugmentedNamespace(n) {
680
- if (n.__esModule) return n;
681
- var f = n.default;
682
- if (typeof f == "function") {
683
- var a = function a () {
684
- if (this instanceof a) {
685
- return Reflect.construct(f, arguments, this.constructor);
135
+ const tracer = trace.getTracer("moost-tracer");
136
+ var SpanInjector = class extends ContextInjector {
137
+ with(name, attributes, cb) {
138
+ const fn = typeof attributes === "function" ? attributes : cb;
139
+ const attrs = typeof attributes === "object" ? attributes : undefined;
140
+ if (name === "Event:start" && attrs?.eventType) return this.startEvent(attrs.eventType, fn);
141
+ else if (name !== "Event:start") if (this.getIgnoreSpan()) return fn();
142
+ else {
143
+ const span = tracer.startSpan(name, {
144
+ kind: SpanKind.INTERNAL,
145
+ attributes: attrs
146
+ });
147
+ return this.withSpan(span, fn, {
148
+ withMetrics: false,
149
+ endSpan: true
150
+ });
151
+ }
152
+ return fn();
153
+ }
154
+ patchRsponse() {
155
+ const res = this.getResponse();
156
+ if (res) {
157
+ const originalWriteHead = res.writeHead;
158
+ Object.assign(res, { writeHead: (arg0, arg1, arg2) => {
159
+ res._statusCode = arg0;
160
+ const headers = typeof arg2 === "object" ? arg2 : typeof arg1 === "object" ? arg1 : undefined;
161
+ res._contentLength = headers?.["content-length"] ? Number(headers["content-length"]) : 0;
162
+ return originalWriteHead.apply(res, [
163
+ arg0,
164
+ arg1,
165
+ arg2
166
+ ]);
167
+ } });
168
+ }
169
+ }
170
+ startEvent(eventType, cb) {
171
+ if (eventType === "init") return cb();
172
+ const { registerSpan } = useOtelContext();
173
+ let span = trace.getActiveSpan();
174
+ if (eventType === "HTTP") this.patchRsponse();
175
+ else span = tracer.startSpan(`${eventType} Event`);
176
+ if (span) {
177
+ registerSpan(span);
178
+ return this.withSpan(span, cb, {
179
+ withMetrics: true,
180
+ endSpan: eventType !== "HTTP"
181
+ });
182
+ }
183
+ return cb();
184
+ }
185
+ getEventType() {
186
+ return useAsyncEventContext().getCtx().event.type;
187
+ }
188
+ getIgnoreSpan() {
189
+ const { getMethodMeta, getControllerMeta } = useControllerContext();
190
+ const cMeta = getControllerMeta();
191
+ const mMeta = getMethodMeta();
192
+ return cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan;
193
+ }
194
+ getControllerHandlerMeta() {
195
+ const { getMethod, getMethodMeta, getController, getControllerMeta, getRoute } = useControllerContext();
196
+ const methodName = getMethod();
197
+ const controller = getController();
198
+ const cMeta = controller ? getControllerMeta() : undefined;
199
+ const mMeta = controller ? getMethodMeta() : undefined;
200
+ return {
201
+ ignoreMeter: cMeta?.otelIgnoreMeter || mMeta?.otelIgnoreMeter,
202
+ ignoreSpan: cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
203
+ attrs: {
204
+ "moost.controller": controller ? getConstructor(controller).name : undefined,
205
+ "moost.handler": methodName,
206
+ "moost.handler_description": mMeta?.description,
207
+ "moost.handler_label": mMeta?.label,
208
+ "moost.handler_id": mMeta?.id,
209
+ "moost.ignore": cMeta?.otelIgnoreSpan || mMeta?.otelIgnoreSpan,
210
+ "moost.route": getRoute(),
211
+ "moost.event_type": this.getEventType()
686
212
  }
687
- return f.apply(this, arguments);
688
213
  };
689
- a.prototype = f.prototype;
690
- } else a = {};
691
- Object.defineProperty(a, '__esModule', {value: true});
692
- Object.keys(n).forEach(function (k) {
693
- var d = Object.getOwnPropertyDescriptor(n, k);
694
- Object.defineProperty(a, k, d.get ? d : {
695
- enumerable: true,
696
- get: function () {
697
- return n[k];
214
+ }
215
+ hook(method, name, route) {
216
+ if (method === "WF_STEP") return;
217
+ if (method === "__SYSTEM__") return;
218
+ const { getSpan } = useOtelContext();
219
+ if (name === "Handler:not_found") {
220
+ const chm = this.getControllerHandlerMeta();
221
+ const span = getSpan();
222
+ if (span) {
223
+ const eventType = this.getEventType();
224
+ if (eventType === "HTTP") {
225
+ const req = this.getRequest();
226
+ span.updateName(`${req?.method || ""} ${req?.url}`);
227
+ }
228
+ }
229
+ this.startEventMetrics(chm.attrs, route);
230
+ } else if (name === "Controller:registered") {
231
+ const _route = useAsyncEventContext().store("otel").get("route");
232
+ const chm = this.getControllerHandlerMeta();
233
+ if (!chm.ignoreMeter) this.startEventMetrics(chm.attrs, _route);
234
+ const span = getSpan();
235
+ if (span) {
236
+ span.setAttributes(chm.attrs);
237
+ if (chm.attrs["moost.event_type"] === "HTTP") span.updateName(`${this.getRequest()?.method || ""} ${_route || "<unresolved>"}`);
238
+ else span.updateName(`${chm.attrs["moost.event_type"]} ${_route || "<unresolved>"}`);
239
+ }
240
+ }
241
+ if (name !== "Controller:registered") useAsyncEventContext().store("otel").set("route", route);
242
+ }
243
+ withSpan(span, cb, opts) {
244
+ return withSpan(span, cb, (_span, exception, result) => {
245
+ if (result instanceof Error) _span.recordException(result);
246
+ if (opts.withMetrics) {
247
+ const chm = this.getControllerHandlerMeta();
248
+ if (!chm.ignoreMeter) this.endEventMetrics(chm.attrs, result instanceof Error ? result : exception);
249
+ }
250
+ if (opts.endSpan) {
251
+ const customAttrs = useAsyncEventContext().store("customSpanAttrs").value;
252
+ if (customAttrs) _span.setAttributes(customAttrs);
253
+ _span.end();
698
254
  }
699
255
  });
700
- });
701
- return a;
702
- }
703
-
704
- var router_cjs_prod = {};
705
-
706
- class ProstoCache {
707
- constructor(options) {
708
- this.data = {};
709
- this.limits = [];
710
- this.expireOrder = [];
711
- this.expireSeries = {};
712
- this.options = {
713
- limit: 1000,
714
- ...options,
715
- };
716
- }
717
- set(key, value) {
718
- var _a, _b, _c;
719
- if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.limit) === 0)
720
- return;
721
- const expires = ((_b = this.options) === null || _b === void 0 ? void 0 : _b.ttl) ? Math.round(new Date().getTime() / 1) + ((_c = this.options) === null || _c === void 0 ? void 0 : _c.ttl) : null;
722
- if (expires) {
723
- this.del(key);
724
- }
725
- this.data[key] = {
726
- value: value,
727
- expires,
728
- };
729
- if (expires) {
730
- this.pushExpires(key, expires);
731
- }
732
- this.pushLimit(key);
733
- }
734
- get(key) {
735
- var _a;
736
- return (_a = this.data[key]) === null || _a === void 0 ? void 0 : _a.value;
737
- }
738
- del(key) {
739
- const entry = this.data[key];
740
- if (entry) {
741
- delete this.data[key];
742
- if (entry.expires) {
743
- let es = this.expireSeries[entry.expires];
744
- if (es) {
745
- es = this.expireSeries[entry.expires] = es.filter(k => k !== key);
746
- }
747
- if (!es || !es.length) {
748
- delete this.expireSeries[entry.expires];
749
- const { found, index } = this.searchExpireOrder(entry.expires);
750
- if (found) {
751
- this.expireOrder.splice(index, 1);
752
- if (index === 0) {
753
- console.log('calling prepareTimeout');
754
- this.prepareTimeout();
755
- }
756
- }
757
- }
758
- }
759
- }
760
- }
761
- reset() {
762
- this.data = {};
763
- if (this.nextTimeout) {
764
- clearTimeout(this.nextTimeout);
765
- }
766
- this.expireOrder = [];
767
- this.expireSeries = {};
768
- this.limits = [];
769
- }
770
- searchExpireOrder(time) {
771
- return binarySearch(this.expireOrder, time);
772
- }
773
- pushLimit(key) {
774
- var _a;
775
- const limit = (_a = this.options) === null || _a === void 0 ? void 0 : _a.limit;
776
- if (limit) {
777
- const newObj = [key, ...(this.limits.filter(item => item !== key && this.data[item]))];
778
- const tail = newObj.slice(limit);
779
- this.limits = newObj.slice(0, limit);
780
- if (tail.length) {
781
- tail.forEach(tailItem => {
782
- this.del(tailItem);
783
- });
784
- }
785
- }
786
- }
787
- prepareTimeout() {
788
- if (this.nextTimeout) {
789
- clearTimeout(this.nextTimeout);
790
- }
791
- const time = this.expireOrder[0];
792
- const del = (time) => {
793
- for (const key of (this.expireSeries[time] || [])) {
794
- delete this.data[key];
795
- }
796
- delete this.expireSeries[time];
797
- this.expireOrder = this.expireOrder.slice(1);
798
- this.prepareTimeout();
799
- };
800
- if (time) {
801
- const delta = time - Math.round(new Date().getTime() / 1);
802
- if (delta > 0) {
803
- this.nextTimeout = setTimeout(() => {
804
- del(time);
805
- }, delta);
806
- }
807
- else {
808
- del(time);
809
- }
810
- }
811
- }
812
- pushExpires(key, time) {
813
- const { found, index } = this.searchExpireOrder(time);
814
- if (!found) {
815
- this.expireOrder.splice(index, 0, time);
816
- }
817
- const e = this.expireSeries[time] = this.expireSeries[time] || [];
818
- e.push(key);
819
- if (!found && index === 0) {
820
- this.prepareTimeout();
821
- }
822
- }
823
- }
824
- function binarySearch(a, n) {
825
- let start = 0;
826
- let end = a.length - 1;
827
- let mid = 0;
828
- while (start <= end) {
829
- mid = Math.floor((start + end) / 2);
830
- if (a[mid] === n) {
831
- return {
832
- found: true,
833
- index: mid,
834
- };
835
- }
836
- if (n < a[mid]) {
837
- end = mid - 1;
838
- mid--;
839
- }
840
- else {
841
- start = mid + 1;
842
- mid++;
843
- }
844
- }
845
- return {
846
- found: false,
847
- index: mid,
848
- };
849
- }
850
-
851
- var cache_esmBundler = /*#__PURE__*/Object.freeze({
852
- __proto__: null,
853
- ProstoCache: ProstoCache
854
- });
855
-
856
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(cache_esmBundler);
857
-
858
- const dim = '';
859
- const reset = '';
860
- class ProstoTree {
861
- constructor(options) {
862
- var _a, _b, _c, _d;
863
- const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
864
- const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
865
- const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
866
- const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
867
- const branches = {
868
- end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
869
- middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
870
- vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
871
- hLine,
872
- };
873
- this.options = {
874
- label: label,
875
- children: children,
876
- renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
877
- branches,
878
- branchWidth,
879
- };
880
- }
881
- _render(root, opts) {
882
- const { children, renderLabel } = this.options;
883
- let s = `${renderLabel(root, '')}\n`;
884
- const { end, middle, vLine, hLine } = this.options.branches;
885
- const endBranch = end + hLine + reset + ' ';
886
- const middleBranch = middle + hLine + reset + ' ';
887
- const { branchWidth } = this.options;
888
- if (root) {
889
- treeNode(root);
890
- }
891
- function treeNode(node, behind = '', level = 1) {
892
- const items = (node && node[children]);
893
- const count = items && items.length || 0;
894
- if (items) {
895
- if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
896
- s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
897
- }
898
- else {
899
- let itemsToRender = items;
900
- const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
901
- if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
902
- itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
903
- }
904
- if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
905
- s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
906
- itemsToRender.forEach((childNode, i) => {
907
- const last = i + 1 === count;
908
- const branch = last ? endBranch : middleBranch;
909
- const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
910
- s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
911
- if (typeof childNode === 'object') {
912
- treeNode(childNode, nextBehind, level + 1);
913
- }
914
- });
915
- if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
916
- s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
917
- }
918
- }
919
- }
920
- return s;
921
- }
922
- render(root, opts) {
923
- return this._render(root, opts);
924
- }
925
- print(root, opts) {
926
- const s = this.render(root, opts);
927
- console.log(s);
928
- return s;
929
- }
930
- }
931
- function renderCollapsedChildren(count) {
932
- return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
933
- }
934
-
935
- var tree_esmBundler = /*#__PURE__*/Object.freeze({
936
- __proto__: null,
937
- ProstoTree: ProstoTree
938
- });
939
-
940
- function renderCodeFragment(lines, options) {
941
- const row = (options.row || 1) - 1;
942
- const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
943
- const limit = Math.min(options.limit || 6, lines.length);
944
- const offset = Math.min(options.offset || 3, lines.length);
945
- const error = options.error;
946
- const errorEnd = options.errorEnd;
947
- let output = '';
948
- const delta = rowEnd - row;
949
- const maxIndex = lines.length;
950
- if (delta > limit) {
951
- let longestLine = 0;
952
- const newLimit = Math.floor(limit / 2);
953
- for (let i = 0; i < newLimit + offset; i++) {
954
- const index = row + i - offset;
955
- const line = lines[index] || '';
956
- longestLine = Math.max(line.length, longestLine);
957
- output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
958
- }
959
- let output2 = '';
960
- for (let i = newLimit + offset; i > 0; i--) {
961
- const index = rowEnd - i + offset;
962
- const line = lines[index] || '';
963
- longestLine = Math.max(line.length, longestLine);
964
- output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
965
- }
966
- output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
967
- }
968
- else {
969
- for (let i = 0; i < limit + offset; i++) {
970
- const index = row + i - offset;
971
- if (index <= lines.length + 1) {
972
- const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
973
- output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
974
- }
975
- }
976
- }
977
- return output;
978
- }
979
- function lineStyles(s) {
980
- return '' + (s || '')
981
- .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
982
- .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
983
- }
984
- function lineStylesError(s) {
985
- return '' + (s || '') + '';
986
- }
987
- function renderLine(line, index, error, style = '') {
988
- const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
989
- if (typeof error === 'number') {
990
- const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
991
- return renderLineNumber(index, true) +
992
- st +
993
- lineStyles(line.slice(0, error)) +
994
- lineStylesError(line.slice(error, error + errorLength)) +
995
- lineStyles(line.slice(error + errorLength)) +
996
- renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
997
- }
998
- return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
999
- }
1000
- function renderLineNumber(i, isError = false, bold = false) {
1001
- let s = ' ';
1002
- const sep = i === '———';
1003
- if (i && i > 0 || typeof i === 'string') {
1004
- s = ' ' + String(i);
1005
- }
1006
- s = s.slice(s.length - 5);
1007
- return '\n' + '' + (sep ? '' : '') +
1008
- (isError ? '' + '' : (bold ? '' : '')) +
1009
- s + (sep ? i : ' | ') + '';
1010
- }
1011
-
1012
- function escapeRegex(s) {
1013
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1014
- }
1015
-
1016
- class ProstoParserNodeBase {
1017
- addRecognizes(...args) {
1018
- for (const node of args) {
1019
- if (!this.options.recognizes)
1020
- this.options.recognizes = [];
1021
- if (!this.options.recognizes.includes(node)) {
1022
- this.options.recognizes.push(node);
1023
- }
1024
- }
1025
- return this;
1026
- }
1027
- addAbsorbs(node, rule = 'append') {
1028
- this.options.absorbs = this.options.absorbs || {};
1029
- if (Array.isArray(node)) {
1030
- node.forEach(n => {
1031
- this.options.absorbs[n.id] = rule;
1032
- this.addRecognizes(n);
1033
- });
1034
- }
1035
- else {
1036
- this.options.absorbs[node.id] = rule;
1037
- this.addRecognizes(node);
1038
- }
1039
- return this;
1040
- }
1041
- addPopsAfterNode(...args) {
1042
- for (const node of args) {
1043
- if (!this.options.popsAfterNode)
1044
- this.options.popsAfterNode = [];
1045
- if (!this.options.popsAfterNode.includes(node)) {
1046
- this.options.popsAfterNode.push(node);
1047
- }
1048
- }
1049
- this.addRecognizes(...args);
1050
- return this;
1051
- }
1052
- addHoistChildren(...args) {
1053
- if (!this.options.hoistChildren)
1054
- this.options.hoistChildren = [];
1055
- this.options.hoistChildren.push(...args);
1056
- return this;
1057
- }
1058
- set icon(value) {
1059
- this.options.icon = value;
1060
- }
1061
- set label(value) {
1062
- this.options.label = value;
1063
- }
1064
- get startsWith() {
1065
- return this.options.startsWith;
1066
- }
1067
- set startsWith(value) {
1068
- this.options.startsWith = value;
1069
- }
1070
- get endsWith() {
1071
- return this.options.endsWith;
1072
- }
1073
- set endsWith(value) {
1074
- this.options.endsWith = value;
1075
- }
1076
- getPopsAtEOFSource() {
1077
- return this.options.popsAtEOFSource;
1078
- }
1079
- popsAtEOFSource(value) {
1080
- this.options.popsAtEOFSource = value;
1081
- return this;
1082
- }
1083
- get absorbs() {
1084
- return this.options.absorbs;
1085
- }
1086
- get badToken() {
1087
- return this.options.badToken;
1088
- }
1089
- set badToken(value) {
1090
- this.options.badToken = value;
1091
- }
1092
- get skipToken() {
1093
- return this.options.skipToken;
1094
- }
1095
- set skipToken(value) {
1096
- this.options.skipToken = value;
1097
- }
1098
- get recognizes() {
1099
- return this.options.recognizes || [];
1100
- }
1101
- set recognizes(value) {
1102
- this.options.recognizes = value;
1103
- }
1104
- get hoistChildren() {
1105
- return this.options.hoistChildren || [];
1106
- }
1107
- set hoistChildren(value) {
1108
- this.options.hoistChildren = value;
1109
- }
1110
- getMapContent() {
1111
- return this.options.mapContent;
1112
- }
1113
- mapContent(key, value = 'copy') {
1114
- this.options.mapContent = this.options.mapContent || {};
1115
- this.options.mapContent[key] = value;
1116
- return this;
1117
- }
1118
- onMatch(value) {
1119
- this.options.onMatch = value;
1120
- return this;
1121
- }
1122
- onAppendContent(value) {
1123
- this.options.onAppendContent = value;
1124
- return this;
1125
- }
1126
- onAfterChildParse(value) {
1127
- this.options.onAfterChildParse = value;
1128
- return this;
1129
- }
1130
- onBeforeChildParse(value) {
1131
- this.options.onBeforeChildParse = value;
1132
- return this;
1133
- }
1134
- onMatchStartToken(value) {
1135
- if (this.options.startsWith) {
1136
- this.options.startsWith.onMatchToken = value;
1137
- }
1138
- return this;
1139
- }
1140
- onMatchEndToken(value) {
1141
- if (this.options.endsWith) {
1142
- this.options.endsWith.onMatchToken = value;
1143
- }
1144
- return this;
1145
- }
1146
- initCustomData(value) {
1147
- this.options.initCustomData = value;
1148
- return this;
1149
- }
1150
- onPop(value) {
1151
- this.options.onPop = value;
1152
- return this;
1153
- }
1154
- get popsAfterNode() {
1155
- return this.options.popsAfterNode || [];
1156
- }
1157
- set popsAfterNode(nodes) {
1158
- this.options.popsAfterNode = nodes;
1159
- }
1160
- clearStartsWith() {
1161
- delete this.options.startsWith;
1162
- return this;
1163
- }
1164
- clearEndsWith() {
1165
- delete this.options.endsWith;
1166
- return this;
1167
- }
1168
- clearPopsAtEOFSource() {
1169
- delete this.options.popsAtEOFSource;
1170
- return this;
1171
- }
1172
- clearBadToken() {
1173
- delete this.options.badToken;
1174
- return this;
1175
- }
1176
- clearSkipToken() {
1177
- delete this.options.skipToken;
1178
- return this;
1179
- }
1180
- clearAbsorbs(node) {
1181
- if (this.options.absorbs) {
1182
- if (node && Array.isArray(node)) {
1183
- for (const n of node) {
1184
- delete this.options.absorbs[n.id];
1185
- }
1186
- }
1187
- else if (node) {
1188
- delete this.options.absorbs[node.id];
1189
- }
1190
- else {
1191
- this.options.absorbs = {};
1192
- }
1193
- }
1194
- return this;
1195
- }
1196
- clearRecognizes(...args) {
1197
- var _a;
1198
- if (args.length) {
1199
- this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
1200
- }
1201
- else {
1202
- this.options.recognizes = [];
1203
- }
1204
- return this;
1205
- }
1206
- clearHoistChildren() {
1207
- delete this.options.hoistChildren;
1208
- return this;
1209
- }
1210
- clearMapContent() {
1211
- delete this.options.mapContent;
1212
- return this;
1213
- }
1214
- removeOnPop() {
1215
- delete this.options.onPop;
1216
- return this;
1217
- }
1218
- removeOnMatch() {
1219
- delete this.options.onMatch;
1220
- return this;
1221
- }
1222
- removeOnAppendContent() {
1223
- delete this.options.onAppendContent;
1224
- return this;
1225
- }
1226
- removeOnBeforeChildParse() {
1227
- delete this.options.onBeforeChildParse;
1228
- return this;
1229
- }
1230
- removeOnAfterChildParse() {
1231
- delete this.options.onAfterChildParse;
1232
- return this;
1233
- }
1234
- fireNodeMatched(matched, cbData) {
1235
- return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
1236
- }
1237
- fireNodeEndMatched(matched, cbData) {
1238
- return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
1239
- }
1240
- fireMatched(descr, matched, cbData) {
1241
- const { omit, eject, onMatchToken } = descr;
1242
- let cbResult = true;
1243
- if (onMatchToken) {
1244
- cbResult = onMatchToken({
1245
- ...cbData,
1246
- matched,
1247
- });
1248
- }
1249
- const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
1250
- const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
1251
- return {
1252
- omit: cbOmit !== undefined ? cbOmit : omit,
1253
- eject: cbEject !== undefined ? cbEject : eject,
1254
- confirmed: cbResult !== false,
1255
- };
1256
- }
1257
- getStartTokenRg() {
1258
- return this.getRgOutOfTokenDescriptor(this.options.startsWith);
1259
- }
1260
- getEndTokenRg() {
1261
- return this.getRgOutOfTokenDescriptor(this.options.endsWith);
1262
- }
1263
- getConstraintTokens() {
1264
- return {
1265
- skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
1266
- bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
1267
- };
1268
- }
1269
- getRgOutOfTokenDescriptor(descr) {
1270
- if (descr) {
1271
- const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
1272
- let token;
1273
- if (typeof descr.token === 'function') {
1274
- token = descr.token(this);
1275
- }
1276
- else {
1277
- token = descr.token;
1278
- }
1279
- if (token instanceof RegExp) {
1280
- return new RegExp(prefix + token.source, token.flags);
1281
- }
1282
- else {
1283
- return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex(t)).join('|')})`);
1284
- }
1285
- }
1286
- }
1287
- }
1288
-
1289
- class ProstoHoistManager {
1290
- constructor() {
1291
- this.data = {};
1292
- }
1293
- addHoistOptions(ctx) {
1294
- if (ctx.hoistChildren) {
1295
- ctx.hoistChildren.forEach(options => {
1296
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1297
- const hoist = this.data[nodeId] = (this.data[nodeId] || {});
1298
- if (hoist) {
1299
- hoist[ctx.index] = {
1300
- options,
1301
- context: ctx,
1302
- };
1303
- }
1304
- });
1305
- }
1306
- }
1307
- removeHoistOptions(ctx) {
1308
- if (ctx.hoistChildren) {
1309
- ctx.hoistChildren.forEach(options => {
1310
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1311
- const hoist = this.data[nodeId];
1312
- if (hoist) {
1313
- delete hoist[ctx.index];
1314
- }
1315
- });
1316
- }
1317
- }
1318
- processHoistOptions(ctx) {
1319
- const id = ctx.node.id;
1320
- const hoist = this.data[id];
1321
- if (hoist) {
1322
- Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
1323
- const customData = context.getCustomData();
1324
- if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
1325
- if (options.asArray) {
1326
- const hoisted = customData[options.as] = (customData[options.as] || []);
1327
- if (!Array.isArray(hoisted)) {
1328
- if (!options.onConflict || options.onConflict === 'error') {
1329
- throw new Error(`Can not hoist "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists and it is not an Array Type.`);
1330
- }
1331
- else if (options.onConflict === 'overwrite') {
1332
- customData[options.as] = [doTheMapRule(options, ctx)];
1333
- }
1334
- else if (options.onConflict !== 'ignore') {
1335
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1336
- }
1337
- }
1338
- else {
1339
- hoisted.push(doTheMapRule(options, ctx));
1340
- }
1341
- }
1342
- else {
1343
- if (customData[options.as]) {
1344
- if (!options.onConflict || options.onConflict === 'error') {
1345
- throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
1346
- }
1347
- else if (options.onConflict === 'overwrite') {
1348
- customData[options.as] = doTheMapRule(options, ctx);
1349
- }
1350
- else if (options.onConflict !== 'ignore') {
1351
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1352
- }
1353
- }
1354
- else {
1355
- customData[options.as] = doTheMapRule(options, ctx);
1356
- }
1357
- }
1358
- if (options.removeChildFromContent) {
1359
- context.content = context.content.filter(c => c !== ctx);
1360
- }
1361
- }
1362
- });
1363
- }
1364
- function doTheMapRule(options, ctx) {
1365
- var _a;
1366
- if (typeof options.mapRule === 'function') {
1367
- return options.mapRule(ctx);
1368
- }
1369
- if (options.mapRule === 'content.join') {
1370
- return ctx.content.join('');
1371
- }
1372
- if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
1373
- const key = options.mapRule.slice(11);
1374
- if (key) {
1375
- return ctx.getCustomData()[key];
1376
- }
1377
- else {
1378
- return ctx.getCustomData();
1379
- }
1380
- }
1381
- return ctx;
1382
- }
1383
- }
1384
- }
1385
-
1386
- const banner = '' + '[parser]' + '';
1387
- class ProstoParserContext {
1388
- constructor(root) {
1389
- this.root = root;
1390
- this.nodes = {};
1391
- this.pos = 0;
1392
- this.index = 0;
1393
- this.behind = '';
1394
- this.here = '';
1395
- this.src = '';
1396
- this.stack = [];
1397
- this.l = 0;
1398
- this.hoistManager = new ProstoHoistManager();
1399
- this.context = root;
1400
- }
1401
- parse(src) {
1402
- this.src = src,
1403
- this.here = src,
1404
- this.l = src.length;
1405
- const cache = {};
1406
- while (this.pos < this.l) {
1407
- const searchTokens = this.context.getSearchTokens();
1408
- let closestIndex = Number.MAX_SAFE_INTEGER;
1409
- let closestToken;
1410
- let matched;
1411
- for (const t of searchTokens) {
1412
- const key = t.g.source;
1413
- t.g.lastIndex = this.pos;
1414
- let cached = cache[key];
1415
- if (cached === null)
1416
- continue;
1417
- if (cached && cached.index < this.pos) {
1418
- cached = null;
1419
- delete cache[key];
1420
- }
1421
- if (!cached) {
1422
- cached = t.g.exec(this.src);
1423
- if (cached || (this.pos === 0 && !cached)) {
1424
- cache[key] = cached;
1425
- }
1426
- }
1427
- if (cached && cached.index < closestIndex) {
1428
- closestIndex = cached.index;
1429
- matched = cached;
1430
- closestToken = t;
1431
- if (closestIndex === this.pos)
1432
- break;
1433
- }
1434
- }
1435
- if (closestToken && matched) {
1436
- const toAppend = this.src.slice(this.pos, closestIndex);
1437
- if (toAppend) {
1438
- this.context.appendContent(toAppend);
1439
- this.jump(toAppend.length);
1440
- }
1441
- const matchedToken = matched[0];
1442
- if (closestToken.node) {
1443
- const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
1444
- if (!confirmed)
1445
- continue;
1446
- let toAppend = '';
1447
- if (eject) {
1448
- this.context.appendContent(matchedToken);
1449
- }
1450
- else if (!omit) {
1451
- toAppend = matchedToken;
1452
- }
1453
- this.jump(matchedToken.length);
1454
- this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
1455
- this.context.fireOnMatch(matched);
1456
- continue;
1457
- }
1458
- else {
1459
- const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
1460
- if (!confirmed)
1461
- continue;
1462
- if (!eject && !omit) {
1463
- this.context.appendContent(matchedToken);
1464
- }
1465
- if (!eject) {
1466
- this.jump(matchedToken.length);
1467
- }
1468
- this.context.mapNamedGroups(matched);
1469
- this.pop();
1470
- continue;
1471
- }
1472
- }
1473
- else {
1474
- this.context.appendContent(this.here);
1475
- this.jump(this.here.length);
1476
- }
1477
- }
1478
- if (this.context !== this.root) {
1479
- while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
1480
- this.pop();
1481
- }
1482
- if (this.context !== this.root) {
1483
- this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
1484
- }
1485
- return this.root;
1486
- }
1487
- pop() {
1488
- const parentContext = this.stack.pop();
1489
- this.context.fireOnPop();
1490
- if (parentContext) {
1491
- parentContext.fireAfterChildParse(this.context);
1492
- parentContext.fireAbsorb(this.context);
1493
- this.context.cleanup();
1494
- const node = this.context.node;
1495
- this.context = parentContext;
1496
- if (parentContext.popsAfterNode.includes(node)) {
1497
- this.pop();
1498
- }
1499
- }
1500
- else {
1501
- this.context.cleanup();
1502
- }
1503
- }
1504
- pushNewContext(newNode, content) {
1505
- this.index++;
1506
- const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
1507
- ctx.content = content;
1508
- this.context.fireBeforeChildParse(ctx);
1509
- this.context.pushChild(ctx);
1510
- this.stack.push(this.context);
1511
- this.hoistManager.addHoistOptions(this.context);
1512
- this.context = ctx;
1513
- return ctx;
1514
- }
1515
- fromStack(depth = 0) {
1516
- return this.stack[this.stack.length - depth - 1];
1517
- }
1518
- jump(n = 1) {
1519
- this.pos += n;
1520
- this.behind = this.src.slice(0, this.pos);
1521
- this.here = this.src.slice(this.pos, this.l);
1522
- return this.pos;
1523
- }
1524
- getCallbackData(matched) {
1525
- return {
1526
- parserContext: this,
1527
- context: this.context,
1528
- matched,
1529
- customData: this.context.getCustomData(),
1530
- };
1531
- }
1532
- getPosition(offset = 0) {
1533
- var _a;
1534
- const past = this.src.slice(0, this.pos + offset).split('\n');
1535
- const row = past.length;
1536
- const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
1537
- return {
1538
- row, col, pos: this.pos,
1539
- };
1540
- }
1541
- panic(message, errorBackOffset = 0) {
1542
- if (this.pos > 0) {
1543
- const { row, col } = this.getPosition(-errorBackOffset);
1544
- console.error(banner + '', message, '');
1545
- console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
1546
- console.error(renderCodeFragment(this.src.split('\n'), {
1547
- row: row,
1548
- error: col,
1549
- }));
1550
- }
1551
- throw new Error(message);
1552
- }
1553
- panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
1554
- if (this.pos > 0) {
1555
- const { row, col } = this.getPosition(-bottomBackOffset);
1556
- console.error(banner + '', message, '');
1557
- console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
1558
- console.error(renderCodeFragment(this.src.split('\n'), {
1559
- row: this.context.startPos.row,
1560
- error: this.context.startPos.col - topBackOffset,
1561
- rowEnd: row,
1562
- errorEnd: col,
1563
- }));
1564
- }
1565
- throw new Error(message);
1566
- }
1567
- }
1568
-
1569
- const styles = {
1570
- banner: (s) => '' + s + '',
1571
- text: (s) => '' + s + '',
1572
- valuesDim: (s) => '' + '' + s + '' + '',
1573
- boolean: (s) => '' + s + '',
1574
- booleanDim: (s) => '' + '' + s + '' + '',
1575
- underscore: (s) => '' + s + '',
1576
- values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
1577
- nodeDim: (s) => '' + '' + s + '' + '',
1578
- node: (s) => '' + s + '',
1579
- };
1580
- const stringOutputLimit = 70;
1581
- const parserTree = new ProstoTree({
1582
- children: 'content',
1583
- renderLabel: (context) => {
1584
- if (typeof context === 'string') {
1585
- return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
1586
- }
1587
- else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
1588
- let keys = '';
1589
- const data = context.getCustomData();
1590
- Object.keys(data).forEach(key => {
1591
- const val = data[key];
1592
- if (typeof val === 'string' || typeof val === 'number') {
1593
- keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
1594
- }
1595
- else if (Array.isArray(val)) {
1596
- keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
1597
- }
1598
- else if (typeof val === 'object') {
1599
- keys += ' ' + styles.valuesDim(`{ ${key} }`);
1600
- }
1601
- else if (typeof val === 'boolean' && val) {
1602
- const st = key ? styles.boolean : styles.booleanDim;
1603
- keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
1604
- }
1605
- });
1606
- return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
1607
- }
1608
- return '';
1609
- },
1610
- });
1611
- function cut(s, n) {
1612
- const c = s.replace(/\n/g, '\\n');
1613
- if (c.length <= n)
1614
- return c;
1615
- return c.slice(0, n) + '' + '…';
1616
- }
1617
-
1618
- class ProstoParserNodeContext extends ProstoParserNodeBase {
1619
- constructor(_node, index, level, parserContext) {
1620
- super();
1621
- this._node = _node;
1622
- this.index = index;
1623
- this.level = level;
1624
- this.content = [];
1625
- this._customData = {};
1626
- this.hasNodes = [];
1627
- this.count = {};
1628
- this.mapContentRules = {
1629
- 'first': (content) => content[0],
1630
- 'shift': (content) => content.shift(),
1631
- 'pop': (content) => content.pop(),
1632
- 'last': (content) => content[content.length - 1],
1633
- 'join': (content) => content.join(''),
1634
- 'join-clear': (content) => content.splice(0).join(''),
1635
- 'copy': (content) => content,
1636
- };
1637
- this.options = _node.getOptions();
1638
- if (this.options.initCustomData) {
1639
- this._customData = this.options.initCustomData();
1640
- }
1641
- this._label = this.options.label || '';
1642
- this._icon = this.options.icon || '◦';
1643
- this.parserContext = parserContext || new ProstoParserContext(this);
1644
- if (parserContext) {
1645
- this.parent = parserContext.context || parserContext.root;
1646
- }
1647
- this.startPos = this.parserContext.getPosition();
1648
- this.endPos = this.parserContext.getPosition();
1649
- }
1650
- getOptions() {
1651
- return this.options;
1652
- }
1653
- extractCustomDataTree() {
1654
- let content = this.content;
1655
- if (this.contentCopiedTo) {
1656
- content = this.customData[this.contentCopiedTo];
1657
- }
1658
- if (Array.isArray(content)) {
1659
- return content.map(c => {
1660
- if (typeof c === 'string') {
1661
- return c;
1662
- }
1663
- else {
1664
- return extract(c);
1665
- }
1666
- });
1667
- }
1668
- else {
1669
- const c = content;
1670
- if (c instanceof ProstoParserNodeContext) {
1671
- return extract(c);
1672
- }
1673
- else {
1674
- return content;
1675
- }
1676
- }
1677
- function extract(c) {
1678
- const cd = { ...c.getCustomData() };
1679
- if (c.contentCopiedTo) {
1680
- cd[c.contentCopiedTo] = c.extractCustomDataTree();
1681
- }
1682
- return cd;
1683
- }
1684
- }
1685
- getPrevNode(n = 1) {
1686
- if (this.parent) {
1687
- const index = this.parent.content.findIndex(n => n === this) - n;
1688
- if (index >= 0)
1689
- return this.parent.content[index];
1690
- }
1691
- }
1692
- getPrevContext(n = 1) {
1693
- if (this.parent) {
1694
- const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
1695
- const index = contexts.findIndex(n => n === this) - n;
1696
- if (index >= 0)
1697
- return contexts[index];
1698
- }
1699
- }
1700
- set icon(value) {
1701
- this._icon = value;
1702
- }
1703
- get icon() {
1704
- return this._icon;
1705
- }
1706
- set label(value) {
1707
- this._label = value;
1708
- }
1709
- get label() {
1710
- return this._label;
1711
- }
1712
- getCustomData() {
1713
- return this._customData;
1714
- }
1715
- get customData() {
1716
- return this._customData;
1717
- }
1718
- get nodeId() {
1719
- return this._node.id;
1720
- }
1721
- get node() {
1722
- return this._node;
1723
- }
1724
- toTree(options) {
1725
- return parserTree.render(this, options);
1726
- }
1727
- getSearchTokens() {
1728
- var _a;
1729
- const rg = this.getEndTokenRg();
1730
- const tokens = rg ? [{
1731
- rg,
1732
- y: addFlag(rg, 'y'),
1733
- g: addFlag(rg, 'g'),
1734
- }] : [];
1735
- (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
1736
- const rg = node.getStartTokenRg();
1737
- if (rg) {
1738
- tokens.push({
1739
- rg,
1740
- y: addFlag(rg, 'y'),
1741
- g: addFlag(rg, 'g'),
1742
- node,
1743
- });
1744
- }
1745
- });
1746
- function addFlag(rg, f) {
1747
- return new RegExp(rg.source, rg.flags + f);
1748
- }
1749
- return tokens;
1750
- }
1751
- appendContent(input) {
1752
- let s = input;
1753
- this.endPos = this.parserContext.getPosition();
1754
- let { skip, bad } = this.getConstraintTokens();
1755
- skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
1756
- bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
1757
- if (skip) {
1758
- s = s.replace(skip, '');
1759
- }
1760
- if (bad) {
1761
- const m = bad.exec(s);
1762
- if (m) {
1763
- this.parserContext.jump(m.index);
1764
- this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
1765
- }
1766
- }
1767
- s = this.fireOnAppendContent(s);
1768
- if (s) {
1769
- this.content.push(s);
1770
- }
1771
- }
1772
- cleanup() {
1773
- this.options = null;
1774
- }
1775
- pushChild(child) {
1776
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1777
- if (!absorbRule) {
1778
- this.content.push(child);
1779
- }
1780
- }
1781
- fireAbsorb(child) {
1782
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1783
- if (absorbRule) {
1784
- switch (absorbRule) {
1785
- case 'append':
1786
- this.content.push(...child.content);
1787
- break;
1788
- case 'join':
1789
- this.appendContent(child.content.join(''));
1790
- break;
1791
- default:
1792
- const [action, target] = absorbRule.split('->');
1793
- const cd = this.getCustomData();
1794
- if (action === 'copy') {
1795
- cd[target] = child.content;
1796
- }
1797
- else if (action === 'join') {
1798
- cd[target] = child.content.join('');
1799
- }
1800
- else {
1801
- this.parserContext.panic(`Absorb action "${action}" is not supported.`);
1802
- }
1803
- }
1804
- }
1805
- }
1806
- has(node) {
1807
- return this.hasNodes.includes(node);
1808
- }
1809
- countOf(node) {
1810
- return this.count[node.id] || 0;
1811
- }
1812
- mapNamedGroups(matched) {
1813
- if (matched.groups) {
1814
- const cd = this.getCustomData();
1815
- for (const [key, value] of Object.entries(matched.groups)) {
1816
- if (key === 'content') {
1817
- this.appendContent(value);
1818
- }
1819
- else {
1820
- cd[key] = value;
1821
- }
1822
- }
1823
- }
1824
- }
1825
- fireOnPop() {
1826
- this.endPos = this.parserContext.getPosition();
1827
- this.processMappings();
1828
- const data = this.parserContext.getCallbackData();
1829
- this.node.beforeOnPop(data);
1830
- if (this.options.onPop) {
1831
- this.options.onPop(data);
1832
- }
1833
- }
1834
- fireOnMatch(matched) {
1835
- this.mapNamedGroups(matched);
1836
- const data = this.parserContext.getCallbackData(matched);
1837
- this.node.beforeOnMatch(data);
1838
- if (this.options.onMatch) {
1839
- return this.options.onMatch(data);
1840
- }
1841
- }
1842
- fireBeforeChildParse(child) {
1843
- const data = this.parserContext.getCallbackData();
1844
- this.node.beforeOnBeforeChildParse(child, data);
1845
- if (this.options.onBeforeChildParse) {
1846
- return this.options.onBeforeChildParse(child, data);
1847
- }
1848
- }
1849
- fireAfterChildParse(child) {
1850
- if (!this.hasNodes.includes(child.node)) {
1851
- this.hasNodes.push(child.node);
1852
- }
1853
- this.count[child.node.id] = this.count[child.node.id] || 0;
1854
- this.count[child.node.id]++;
1855
- const data = this.parserContext.getCallbackData();
1856
- this.node.beforeOnAfterChildParse(child, data);
1857
- if (this.options.onAfterChildParse) {
1858
- return this.options.onAfterChildParse(child, data);
1859
- }
1860
- }
1861
- fireOnAppendContent(s) {
1862
- let _s = s;
1863
- const data = this.parserContext.getCallbackData();
1864
- _s = this.node.beforeOnAppendContent(_s, data);
1865
- if (this.options.onAppendContent) {
1866
- _s = this.options.onAppendContent(_s, data);
1867
- }
1868
- return _s;
1869
- }
1870
- processMappings() {
1871
- this.parserContext.hoistManager.removeHoistOptions(this);
1872
- this.parserContext.hoistManager.processHoistOptions(this);
1873
- this.processMapContent();
1874
- }
1875
- processMapContent() {
1876
- const targetNodeOptions = this.options;
1877
- if (targetNodeOptions.mapContent) {
1878
- Object.keys(targetNodeOptions.mapContent).forEach((key) => {
1879
- const keyOfT = key;
1880
- if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
1881
- const mapRule = targetNodeOptions.mapContent[keyOfT];
1882
- if (typeof mapRule === 'function') {
1883
- this._customData[keyOfT] = mapRule(this.content);
1884
- }
1885
- else {
1886
- const ruleKey = mapRule;
1887
- if (ruleKey === 'copy')
1888
- this.contentCopiedTo = keyOfT;
1889
- this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
1890
- }
1891
- if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
1892
- this.contentCopiedTo = keyOfT;
1893
- }
1894
- }
1895
- });
1896
- }
1897
- }
1898
- }
1899
-
1900
- let idCounter = 0;
1901
- class ProstoParserNode extends ProstoParserNodeBase {
1902
- constructor(options) {
1903
- super();
1904
- this.options = options;
1905
- this.id = idCounter++;
1906
- }
1907
- getOptions() {
1908
- return {
1909
- label: this.options.label || '',
1910
- icon: this.options.icon || '',
1911
- startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
1912
- endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
1913
- popsAfterNode: [...(this.options.popsAfterNode || [])],
1914
- popsAtEOFSource: this.options.popsAtEOFSource || false,
1915
- badToken: this.options.badToken || '',
1916
- skipToken: this.options.skipToken || '',
1917
- recognizes: [...(this.options.recognizes || [])],
1918
- hoistChildren: [...(this.options.hoistChildren || [])],
1919
- mapContent: {
1920
- ...this.options.mapContent,
1921
- },
1922
- onPop: this.options.onPop,
1923
- onMatch: this.options.onMatch,
1924
- onAppendContent: this.options.onAppendContent,
1925
- onAfterChildParse: this.options.onAfterChildParse,
1926
- onBeforeChildParse: this.options.onBeforeChildParse,
1927
- initCustomData: this.options.initCustomData,
1928
- absorbs: this.options.absorbs,
1929
- };
1930
- }
1931
- createContext(index, level, rootContext) {
1932
- return new ProstoParserNodeContext(this, index, level, rootContext);
1933
- }
1934
- get name() {
1935
- return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
1936
- }
1937
- parse(source) {
1938
- return this.createContext(0, 0).parserContext.parse(source);
1939
- }
1940
- beforeOnPop(data) {
1941
- }
1942
- beforeOnMatch(data) {
1943
- }
1944
- beforeOnAppendContent(s, data) {
1945
- return s;
1946
- }
1947
- beforeOnAfterChildParse(child, data) {
1948
- }
1949
- beforeOnBeforeChildParse(child, data) {
1950
- }
1951
- }
1952
-
1953
- class BasicNode extends ProstoParserNode {
1954
- constructor(options) {
1955
- var _a, _b;
1956
- const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
1957
- const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
1958
- const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
1959
- const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
1960
- if (startsWith) {
1961
- startsWith.omit = startOption === 'omit';
1962
- startsWith.eject = startOption === 'eject';
1963
- startsWith.ignoreBackSlashed = startBSlash === 'ignore';
1964
- }
1965
- if (endsWith) {
1966
- endsWith.omit = endOption === 'omit';
1967
- endsWith.eject = endOption === 'eject';
1968
- endsWith.ignoreBackSlashed = endBSlash === 'ignore';
1969
- }
1970
- super({
1971
- icon: options.icon || '',
1972
- label: typeof options.label === 'string' ? options.label : '',
1973
- startsWith,
1974
- endsWith,
1975
- badToken: options.badToken,
1976
- skipToken: options.skipToken,
1977
- });
1978
- if (options.recursive) {
1979
- this.addAbsorbs(this, 'join');
1980
- }
1981
- }
1982
- }
1983
-
1984
- var parser_esmBundler = /*#__PURE__*/Object.freeze({
1985
- __proto__: null,
1986
- BasicNode: BasicNode,
1987
- ProstoParserContext: ProstoParserContext,
1988
- ProstoParserNode: ProstoParserNode,
1989
- ProstoParserNodeContext: ProstoParserNodeContext,
1990
- renderCodeFragment: renderCodeFragment
1991
- });
1992
-
1993
- var require$$1 = /*@__PURE__*/getAugmentedNamespace(parser_esmBundler);
1994
-
1995
- var require$$2 = /*@__PURE__*/getAugmentedNamespace(tree_esmBundler);
1996
-
1997
- (function (exports) {
1998
-
1999
- Object.defineProperty(exports, '__esModule', { value: true });
2000
-
2001
- var cache = require$$0;
2002
- var parser$1 = require$$1;
2003
- var tree = require$$2;
2004
-
2005
- function parsePath(expr) {
2006
- return parser.parse(expr).extractCustomDataTree();
2007
- }
2008
- class ParametricNodeWithRegex extends parser$1.BasicNode {
2009
- constructor(options, rgNode) {
2010
- super(options);
2011
- const hoistRegex = {
2012
- as: 'regex',
2013
- node: regexNode,
2014
- onConflict: 'overwrite',
2015
- removeChildFromContent: true,
2016
- deep: 1,
2017
- mapRule: ({ content }) => content.join('').replace(/^\(\^/, '(').replace(/\$\)$/, ')'),
2018
- };
2019
- this.mapContent('name', 'join')
2020
- .mapContent('value', content => content.shift())
2021
- .popsAtEOFSource(true)
2022
- .addRecognizes(rgNode)
2023
- .addPopsAfterNode(rgNode)
2024
- .addHoistChildren(hoistRegex);
2025
- }
2026
- beforeOnPop(data) {
2027
- if (data.customData.name.endsWith('?')) {
2028
- data.customData.name = data.customData.name.slice(0, -1);
2029
- data.customData.value = data.customData.name;
2030
- data.customData.optional = true;
2031
- }
2032
- else if (data.parserContext.here[0] === '?') {
2033
- data.customData.optional = true;
2034
- data.parserContext.jump();
2035
- }
2036
- }
2037
- }
2038
- const regexNode = new parser$1.BasicNode({
2039
- label: 'RegEx',
2040
- tokens: ['(', ')'],
2041
- backSlash: 'ignore-ignore',
2042
- recursive: true,
2043
- }).onMatch(({ parserContext, context }) => {
2044
- var _a;
2045
- if (((_a = parserContext.fromStack()) === null || _a === void 0 ? void 0 : _a.node) === context.node) {
2046
- if (!parserContext.here.startsWith('?:')) {
2047
- context.content[0] += '?:';
2048
- }
2049
- }
2050
- });
2051
- const paramNode = new ParametricNodeWithRegex({
2052
- label: 'Parameter',
2053
- tokens: [':', /[\/\-]/],
2054
- tokenOE: 'omit-eject',
2055
- backSlash: 'ignore-',
2056
- }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.VARIABLE, value: '', regex: '([^\\/]*)', name: '' }));
2057
- const wildcardNode = new ParametricNodeWithRegex({
2058
- label: 'Wildcard',
2059
- tokens: ['*', /[^*\()]/],
2060
- tokenOE: '-eject',
2061
- }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.WILDCARD, value: '*', regex: '(.*)', name: '' }));
2062
- const staticNode = new parser$1.BasicNode({
2063
- label: 'Static',
2064
- tokens: [/[^:\*]/, /[:\*]/],
2065
- backSlash: '-ignore',
2066
- tokenOE: '-eject',
2067
- }).initCustomData(() => ({ type: exports.EPathSegmentType.STATIC, value: '' }))
2068
- .mapContent('value', content => content.splice(0).join('').replace(/\\:/g, ':'))
2069
- .popsAtEOFSource(true);
2070
- const parser = new parser$1.BasicNode({}).addRecognizes(staticNode, paramNode, wildcardNode);
2071
-
2072
- exports.EPathSegmentType = void 0;
2073
- (function (EPathSegmentType) {
2074
- EPathSegmentType[EPathSegmentType["STATIC"] = 0] = "STATIC";
2075
- EPathSegmentType[EPathSegmentType["VARIABLE"] = 1] = "VARIABLE";
2076
- EPathSegmentType[EPathSegmentType["REGEX"] = 2] = "REGEX";
2077
- EPathSegmentType[EPathSegmentType["WILDCARD"] = 3] = "WILDCARD";
2078
- })(exports.EPathSegmentType || (exports.EPathSegmentType = {}));
2079
-
2080
- function safeDecode(f, v) {
2081
- try {
2082
- return f(v);
2083
- }
2084
- catch (e) {
2085
- return v;
2086
- }
2087
- }
2088
- function safeDecodeURIComponent(uri) {
2089
- if (!uri || uri.indexOf('%') < 0)
2090
- return uri;
2091
- return safeDecode(decodeURIComponent, uri);
2092
- }
2093
- function safeDecodeURI(uri) {
2094
- if (!uri || uri.indexOf('%') < 0)
2095
- return uri;
2096
- return safeDecode(decodeURI, uri);
2097
256
  }
2098
-
2099
- function countOfSlashes(s) {
2100
- let last = 0;
2101
- let count = 0;
2102
- let index = s.indexOf('/');
2103
- last = index + 1;
2104
- while (index >= 0) {
2105
- count++;
2106
- index = s.indexOf('/', last);
2107
- last = index + 1;
2108
- }
2109
- return count;
257
+ startEventMetrics(a, route) {
258
+ useAsyncEventContext().store("otel").set("startTime", Date.now());
2110
259
  }
2111
-
2112
- class CodeString {
2113
- constructor() {
2114
- this.code = '';
2115
- }
2116
- append(s, newLine = false) {
2117
- this.code += ['', s].flat().join(newLine ? '\n' : '');
2118
- }
2119
- prepend(s, newLine = false) {
2120
- this.code = [s, ''].flat().join(newLine ? '\n' : '') + this.code;
2121
- }
2122
- generateFunction(...args) {
2123
- return new Function(args.join(','), this.code);
2124
- }
2125
- toString() {
2126
- return this.code;
2127
- }
260
+ endEventMetrics(a, error) {
261
+ const otelStore = useAsyncEventContext().store("otel");
262
+ const route = otelStore.get("route");
263
+ const duration = Date.now() - (otelStore.get("startTime") || Date.now() - 1);
264
+ const customAttrs = useAsyncEventContext().store("customMetricAttrs").value || {};
265
+ const attrs = {
266
+ ...customAttrs,
267
+ route,
268
+ "moost.event_type": a["moost.event_type"],
269
+ "moost.is_error": error ? 1 : 0
270
+ };
271
+ if (a["moost.event_type"] === "HTTP") {
272
+ if (!attrs.route) attrs.route = this.getRequest()?.url || "";
273
+ attrs["http.status_code"] = this.getResponse()?._statusCode || 0;
274
+ attrs["moost.is_error"] = attrs["moost.is_error"] || attrs["http.status_code"] > 399 ? 1 : 0;
275
+ }
276
+ this.metrics.moostEventDuration.record(duration, attrs);
2128
277
  }
2129
-
2130
- function escapeRegex(s) {
2131
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
278
+ getRequest() {
279
+ return useAsyncEventContext().store("event").get("req");
2132
280
  }
2133
-
2134
- function generateFullMatchRegex(segments, nonCapturing = false) {
2135
- let regex = '';
2136
- let optional = false;
2137
- segments.forEach(segment => {
2138
- switch (segment.type) {
2139
- case exports.EPathSegmentType.STATIC:
2140
- if (optional) {
2141
- if (['-', '/'].includes(segment.value)) {
2142
- regex += escapeRegex(segment.value) + '?';
2143
- }
2144
- else {
2145
- throw new Error(`Static route segment "${segment.value}" is not allowed after optional parameters.`);
2146
- }
2147
- }
2148
- else {
2149
- regex += escapeRegex(segment.value);
2150
- }
2151
- break;
2152
- case exports.EPathSegmentType.VARIABLE:
2153
- case exports.EPathSegmentType.WILDCARD:
2154
- if (optional && !segment.optional)
2155
- throw new Error('Obligatory route parameters are not allowed after optional parameters. Use "?" to mark it as an optional route parameter.');
2156
- if (segment.optional && !optional) {
2157
- if (regex.endsWith('/')) {
2158
- regex += '?';
2159
- }
2160
- }
2161
- regex += nonCapturing ? segment.regex.replace(/^\(/, '(?:') : segment.regex;
2162
- if (segment.optional) {
2163
- optional = true;
2164
- regex += '?';
2165
- }
2166
- }
2167
- });
2168
- return regex;
2169
- }
2170
- function generateFullMatchFunc(segments, ignoreCase = false) {
2171
- const str = new CodeString();
2172
- const regex = generateFullMatchRegex(segments);
2173
- let index = 0;
2174
- const obj = {};
2175
- segments.forEach(segment => {
2176
- switch (segment.type) {
2177
- case exports.EPathSegmentType.VARIABLE:
2178
- case exports.EPathSegmentType.WILDCARD:
2179
- index++;
2180
- obj[segment.value] = obj[segment.value] || [];
2181
- obj[segment.value].push(index);
2182
- }
2183
- });
2184
- Object.keys(obj).forEach(key => {
2185
- str.append(obj[key].length > 1
2186
- ? `\tparams['${key}'] = [${obj[key].map(i => `utils.safeDecodeURIComponent(a[${i}])`).join(', ')}]`
2187
- : `\tparams['${key}'] = utils.safeDecodeURIComponent(a[${obj[key][0]}])`, true);
2188
- });
2189
- str.prepend([`const a = path.match(/^${regex}$/${ignoreCase ? 'i' : ''})`, 'if (a) {'], true);
2190
- str.append(['}', 'return a'], true);
2191
- return str.generateFunction('path', 'params', 'utils');
2192
- }
2193
- function generatePathBuilder(segments) {
2194
- const str = new CodeString();
2195
- const obj = {};
2196
- const index = {};
2197
- segments.forEach(segment => {
2198
- switch (segment.type) {
2199
- case exports.EPathSegmentType.VARIABLE:
2200
- case exports.EPathSegmentType.WILDCARD:
2201
- obj[segment.value] = obj[segment.value] || 0;
2202
- obj[segment.value]++;
2203
- index[segment.value] = 0;
2204
- }
2205
- });
2206
- str.append('return `');
2207
- segments.forEach(segment => {
2208
- switch (segment.type) {
2209
- case exports.EPathSegmentType.STATIC:
2210
- str.append(segment.value.replace(/`/g, '\\`'));
2211
- break;
2212
- case exports.EPathSegmentType.VARIABLE:
2213
- case exports.EPathSegmentType.WILDCARD:
2214
- if (obj[segment.value] > 1) {
2215
- str.append('${ params[\'' + segment.value + `\'][${index[segment.value]}] }`);
2216
- index[segment.value]++;
2217
- }
2218
- else {
2219
- str.append('${ params[\'' + segment.value + '\'] }');
2220
- }
2221
- }
2222
- });
2223
- str.append('`');
2224
- return str.generateFunction('params');
281
+ getResponse() {
282
+ return useAsyncEventContext().store("event").get("res");
2225
283
  }
2226
-
2227
- const banner = () => `[prostojs/router][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
2228
-
2229
- const methods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
2230
- const matcherFuncUtils = {
2231
- safeDecodeURIComponent,
2232
- };
2233
- class ProstoRouter {
2234
- constructor(_options) {
2235
- this.root = {};
2236
- this.routes = [];
2237
- this.routesRegistry = {};
2238
- this._options = {
2239
- ..._options,
2240
- };
2241
- if (!this._options.silent) {
2242
- consoleInfo('The Router Initialized');
2243
- }
2244
- const cacheOpts = {
2245
- limit: (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) || 0,
2246
- };
2247
- if (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) {
2248
- this.cache = {
2249
- GET: new cache.ProstoCache(cacheOpts),
2250
- PUT: new cache.ProstoCache(cacheOpts),
2251
- POST: new cache.ProstoCache(cacheOpts),
2252
- PATCH: new cache.ProstoCache(cacheOpts),
2253
- DELETE: new cache.ProstoCache(cacheOpts),
2254
- HEAD: new cache.ProstoCache(cacheOpts),
2255
- OPTIONS: new cache.ProstoCache(cacheOpts),
2256
- };
2257
- }
2258
- }
2259
- refreshCache(method) {
2260
- if (this._options.cacheLimit && this.cache) {
2261
- if (method === '*') {
2262
- this.cache.GET.reset();
2263
- this.cache.PUT.reset();
2264
- this.cache.POST.reset();
2265
- this.cache.PATCH.reset();
2266
- this.cache.DELETE.reset();
2267
- this.cache.HEAD.reset();
2268
- this.cache.OPTIONS.reset();
2269
- }
2270
- else if (this.cache && this.cache[method]) {
2271
- this.cache[method].reset();
2272
- }
2273
- }
2274
- }
2275
- registerRoute(method, path, options, handler) {
2276
- this.refreshCache(method);
2277
- const opts = this.mergeOptions(options);
2278
- const normalPath = ('/' + path)
2279
- .replace(/^\/\//, '/')
2280
- .replace(/\/$/, '')
2281
- .replace(/%/g, '%25');
2282
- const { root } = this;
2283
- const segments = parsePath(normalPath);
2284
- if (!root[method]) {
2285
- root[method] = {
2286
- statics: {},
2287
- parametrics: {
2288
- byParts: [],
2289
- },
2290
- wildcards: [],
2291
- };
2292
- }
2293
- const rootMethod = root[method];
2294
- const generalized = method + ':' + segments.map(s => {
2295
- switch (s.type) {
2296
- case exports.EPathSegmentType.STATIC: return s.value;
2297
- case exports.EPathSegmentType.VARIABLE: return '<VAR' + (s.regex === '([^-\\/]*)' ? '' : s.regex) + '>';
2298
- case exports.EPathSegmentType.WILDCARD: return s.value;
2299
- }
2300
- }).join('');
2301
- let route = this.routesRegistry[generalized];
2302
- if (route) {
2303
- if (this._options.disableDuplicatePath) {
2304
- const error = `Attempt to register duplicated path: "${path}". Duplicate paths are disabled.\nYou can enable duplicated paths removing 'disableDuplicatePath' option.`;
2305
- consoleError(error);
2306
- throw new Error(error);
2307
- }
2308
- if (route.handlers.includes(handler)) {
2309
- consoleError('Duplicate route with same handler ignored ' + generalized);
2310
- }
2311
- else {
2312
- consoleWarn('Duplicate route registered ' + generalized);
2313
- route.handlers.push(handler);
2314
- }
2315
- }
2316
- else {
2317
- const isStatic = segments.length === 1 && segments[0].type === exports.EPathSegmentType.STATIC || segments.length === 0;
2318
- const isParametric = !!segments.find(p => p.type === exports.EPathSegmentType.VARIABLE);
2319
- const firstOptional = segments.findIndex(p => p.optional);
2320
- const isOptional = firstOptional >= 0;
2321
- const isWildcard = !!segments.find(p => p.type === exports.EPathSegmentType.WILDCARD);
2322
- const lengths = segments.slice(0, firstOptional >= 0 ? firstOptional : undefined).map(s => s.type === exports.EPathSegmentType.STATIC ? s.value.length : 0);
2323
- const normalPathCase = segments[0] ? (this._options.ignoreCase ? segments[0].value.toLowerCase() : segments[0].value) : '/';
2324
- this.routesRegistry[generalized] = route = {
2325
- method,
2326
- options: opts,
2327
- path: normalPath,
2328
- handlers: [handler],
2329
- isStatic,
2330
- isParametric,
2331
- isOptional,
2332
- isWildcard,
2333
- segments,
2334
- lengths,
2335
- minLength: lengths.reduce((a, b) => a + b, 0),
2336
- firstLength: lengths[0],
2337
- firstStatic: normalPathCase.slice(0, lengths[0]),
2338
- generalized,
2339
- fullMatch: generateFullMatchFunc(segments, this._options.ignoreCase),
2340
- pathBuilder: generatePathBuilder(segments),
2341
- };
2342
- this.routes.push(route);
2343
- if (route.isStatic) {
2344
- rootMethod.statics[normalPathCase] = route;
2345
- }
2346
- else {
2347
- if (route.isParametric && !route.isWildcard && !route.isOptional) {
2348
- const countOfParts = route.segments
2349
- .filter(s => s.type === exports.EPathSegmentType.STATIC)
2350
- .map(s => countOfSlashes(s.value)).reduce((a, b) => a + b, 1);
2351
- const byParts = rootMethod.parametrics.byParts[countOfParts] = rootMethod.parametrics.byParts[countOfParts] || [];
2352
- byParts.push(route);
2353
- rootMethod.parametrics.byParts[countOfParts] = byParts.sort(routeSorter);
2354
- }
2355
- else if (route.isWildcard || route.isOptional) {
2356
- if (route.isOptional && route.firstStatic.endsWith('/')) {
2357
- route.firstStatic = route.firstStatic.slice(0, -1);
2358
- route.firstLength--;
2359
- route.minLength = Math.min(route.minLength, route.firstLength);
2360
- }
2361
- rootMethod.wildcards.push(route);
2362
- rootMethod.wildcards = rootMethod.wildcards.sort(routeSorter);
2363
- }
2364
- }
2365
- }
2366
- return {
2367
- getPath: route.pathBuilder,
2368
- getArgs: () => route.segments.filter(p => p.type === exports.EPathSegmentType.VARIABLE || p.type === exports.EPathSegmentType.WILDCARD).map(s => s.name),
2369
- getStaticPart: () => route.firstStatic,
2370
- test: route.fullMatch,
2371
- isStatic: route.isStatic,
2372
- isParametric: route.isParametric,
2373
- isWildcard: route.isWildcard,
2374
- generalized,
2375
- };
2376
- }
2377
- mergeOptions(options) {
2378
- return {
2379
- ...options,
2380
- };
2381
- }
2382
- sanitizePath(path, ignoreTrailingSlash) {
2383
- const end = path.indexOf('?');
2384
- let slicedPath = end >= 0 ? path.slice(0, end) : path;
2385
- if ((ignoreTrailingSlash || this._options.ignoreTrailingSlash) && slicedPath[slicedPath.length - 1] === '/') {
2386
- slicedPath = slicedPath.slice(0, slicedPath.length - 1);
2387
- }
2388
- const normalPath = safeDecodeURI(slicedPath
2389
- .replace(/%25/g, '%2525'));
2390
- return {
2391
- normalPath,
2392
- normalPathWithCase: this._options.ignoreCase ? normalPath.toLowerCase() : normalPath,
2393
- };
2394
- }
2395
- lookup(method, path, ignoreTrailingSlash) {
2396
- if (this._options.cacheLimit && this.cache && this.cache[method]) {
2397
- const cached = this.cache[method].get(path);
2398
- if (cached)
2399
- return cached;
2400
- }
2401
- const { normalPath, normalPathWithCase } = this.sanitizePath(path, ignoreTrailingSlash);
2402
- const rootMethod = this.root[method];
2403
- const lookupResult = {
2404
- route: null,
2405
- ctx: { params: {} },
2406
- };
2407
- const cache = (result) => {
2408
- if (this._options.cacheLimit && this.cache && this.cache[method]) {
2409
- this.cache[method].set(path, result);
2410
- }
2411
- return result;
2412
- };
2413
- if (rootMethod) {
2414
- lookupResult.route = rootMethod.statics[normalPathWithCase];
2415
- if (lookupResult.route)
2416
- return cache(lookupResult);
2417
- const pathSegmentsCount = countOfSlashes(normalPath) + 1;
2418
- const pathLength = normalPath.length;
2419
- const { parametrics } = rootMethod;
2420
- const bySegments = parametrics.byParts[pathSegmentsCount];
2421
- if (bySegments) {
2422
- for (let i = 0; i < bySegments.length; i++) {
2423
- lookupResult.route = bySegments[i];
2424
- if (pathLength >= lookupResult.route.minLength) {
2425
- if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2426
- && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2427
- return cache(lookupResult);
2428
- }
2429
- }
2430
- }
2431
- }
2432
- const { wildcards } = rootMethod;
2433
- for (let i = 0; i < wildcards.length; i++) {
2434
- lookupResult.route = wildcards[i];
2435
- if (pathLength >= lookupResult.route.minLength) {
2436
- if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2437
- && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2438
- return cache(lookupResult);
2439
- }
2440
- }
2441
- }
2442
- }
2443
- }
2444
- find(method, path) {
2445
- return this.lookup(method, path);
2446
- }
2447
- on(method, path, options, handler) {
2448
- const { opts, func } = extractOptionsAndHandler(options, handler);
2449
- if (method === '*') {
2450
- return methods.map(m => this.registerRoute(m, path, opts, func))[0];
2451
- }
2452
- return this.registerRoute(method, path, opts, func);
2453
- }
2454
- all(path, options, handler) {
2455
- const { opts, func } = extractOptionsAndHandler(options, handler);
2456
- return this.on('*', path, opts, func);
2457
- }
2458
- get(path, options, handler) {
2459
- const { opts, func } = extractOptionsAndHandler(options, handler);
2460
- return this.on('GET', path, opts, func);
2461
- }
2462
- put(path, options, handler) {
2463
- const { opts, func } = extractOptionsAndHandler(options, handler);
2464
- return this.on('PUT', path, opts, func);
2465
- }
2466
- post(path, options, handler) {
2467
- const { opts, func } = extractOptionsAndHandler(options, handler);
2468
- return this.on('POST', path, opts, func);
2469
- }
2470
- patch(path, options, handler) {
2471
- const { opts, func } = extractOptionsAndHandler(options, handler);
2472
- return this.on('PATCH', path, opts, func);
2473
- }
2474
- delete(path, options, handler) {
2475
- const { opts, func } = extractOptionsAndHandler(options, handler);
2476
- return this.on('DELETE', path, opts, func);
2477
- }
2478
- options(path, options, handler) {
2479
- const { opts, func } = extractOptionsAndHandler(options, handler);
2480
- return this.on('OPTIONS', path, opts, func);
2481
- }
2482
- head(path, options, handler) {
2483
- const { opts, func } = extractOptionsAndHandler(options, handler);
2484
- return this.on('HEAD', path, opts, func);
2485
- }
2486
- getRoutes() {
2487
- return this.routes;
2488
- }
2489
- toTree() {
2490
- const rootStyle = (v) => '' + v + '';
2491
- const paramStyle = (v) => '' + '' + ':' + v + '' + '';
2492
- const regexStyle = (v) => '' + '' + v + '' + '';
2493
- const handlerStyle = (v) => '' + '' + '→ ' + '' + '' + v;
2494
- const methodStyle = (v) => '' + '' + '• (' + v + ') ' + '';
2495
- const data = {
2496
- label: '⁕ Router',
2497
- stylist: rootStyle,
2498
- methods: [],
2499
- children: [],
2500
- };
2501
- function toChild(d, label, stylist) {
2502
- let found = d.children.find(c => c.label === label);
2503
- if (!found) {
2504
- found = {
2505
- label,
2506
- stylist,
2507
- methods: [],
2508
- children: [],
2509
- };
2510
- d.children.push(found);
2511
- }
2512
- return found;
2513
- }
2514
- this.routes.sort((a, b) => a.path > b.path ? 1 : -1).forEach(route => {
2515
- let cur = data;
2516
- let last = '';
2517
- route.segments.forEach(s => {
2518
- let parts;
2519
- switch (s.type) {
2520
- case exports.EPathSegmentType.STATIC:
2521
- parts = s.value.split('/');
2522
- last += parts.shift();
2523
- for (let i = 0; i < parts.length; i++) {
2524
- if (last) {
2525
- cur = toChild(cur, last);
2526
- }
2527
- last = '/' + parts[i];
2528
- }
2529
- break;
2530
- case exports.EPathSegmentType.VARIABLE:
2531
- case exports.EPathSegmentType.WILDCARD:
2532
- last += `${paramStyle(s.value)}${regexStyle(s.regex)}`;
2533
- }
2534
- });
2535
- if (last) {
2536
- cur = toChild(cur, last, handlerStyle);
2537
- cur.methods.push(route.method);
2538
- }
2539
- });
2540
- new tree.ProstoTree({
2541
- renderLabel: (node, behind) => {
2542
- const styledLabel = node.stylist ? node.stylist(node.label) : node.label;
2543
- if (node.methods.length) {
2544
- return styledLabel + '\n' + behind + node.methods.map(m => methodStyle(m)).join('\n' + behind);
2545
- }
2546
- return styledLabel;
2547
- },
2548
- }).print(data);
2549
- }
2550
- }
2551
- function extractOptionsAndHandler(options, handler) {
2552
- let opts = {};
2553
- let func = handler;
2554
- if (typeof options === 'function') {
2555
- func = options;
2556
- }
2557
- else {
2558
- opts = options;
2559
- }
2560
- return { opts, func };
2561
- }
2562
- function routeSorter(a, b) {
2563
- if (a.isWildcard !== b.isWildcard) {
2564
- return a.isWildcard ? 1 : -1;
2565
- }
2566
- const len = b.minLength - a.minLength;
2567
- if (len)
2568
- return len;
2569
- for (let i = 0; i < a.lengths.length; i++) {
2570
- const len = b.lengths[i] - a.lengths[i];
2571
- if (len)
2572
- return len;
2573
- }
2574
- return 0;
2575
- }
2576
- function consoleError(v) {
2577
- console.info('' + banner() + v + '');
2578
- }
2579
- function consoleWarn(v) {
2580
- console.info('' + banner() + v + '');
2581
- }
2582
- function consoleInfo(v) {
2583
- console.info('' + '' + banner() + v + '' + '');
284
+ constructor(...args) {
285
+ super(...args), _define_property(this, "metrics", getMoostMetrics());
2584
286
  }
287
+ };
2585
288
 
2586
- exports.ProstoRouter = ProstoRouter;
2587
- exports.escapeRegex = escapeRegex;
2588
- exports.safeDecodeURI = safeDecodeURI;
2589
- exports.safeDecodeURIComponent = safeDecodeURIComponent;
2590
- } (router_cjs_prod));
289
+ //#endregion
290
+ //#region packages/otel/src/init.ts
291
+ function enableOtelForMoost() {
292
+ replaceContextInjector(new SpanInjector());
293
+ }
2591
294
 
295
+ //#endregion
296
+ //#region packages/otel/src/otel.mate.ts
2592
297
  function getOtelMate() {
2593
- return getMoostMate();
298
+ return getMoostMate();
2594
299
  }
2595
300
 
301
+ //#endregion
302
+ //#region packages/otel/src/otel.decorators.ts
2596
303
  const mate = getOtelMate();
2597
- const OtelIgnoreSpan = () => mate.decorate('otelIgnoreSpan', true);
2598
- const OtelIgnoreMeter = () => mate.decorate('otelIgnoreMeter', true);
304
+ const OtelIgnoreSpan = () => mate.decorate("otelIgnoreSpan", true);
305
+ const OtelIgnoreMeter = () => mate.decorate("otelIgnoreMeter", true);
2599
306
 
307
+ //#endregion
308
+ //#region packages/otel/src/processors/span-filter.ts
2600
309
  function shouldSpanBeIgnored(span) {
2601
- return span.attributes['moost.ignore'] === true;
310
+ return span.attributes["moost.ignore"] === true;
2602
311
  }
2603
312
 
2604
- class MoostBatchSpanProcessor extends BatchSpanProcessor {
2605
- onEnd(span) {
2606
- if (shouldSpanBeIgnored(span)) {
2607
- return;
2608
- }
2609
- super.onEnd(span);
2610
- }
2611
- }
2612
-
2613
- class MoostSimpleSpanProcessor extends SimpleSpanProcessor {
2614
- onEnd(span) {
2615
- if (shouldSpanBeIgnored(span)) {
2616
- return;
2617
- }
2618
- super.onEnd(span);
2619
- }
2620
- }
313
+ //#endregion
314
+ //#region packages/otel/src/processors/batch-processor.ts
315
+ var MoostBatchSpanProcessor = class extends BatchSpanProcessor {
316
+ onEnd(span) {
317
+ if (shouldSpanBeIgnored(span)) return;
318
+ super.onEnd(span);
319
+ }
320
+ };
321
+
322
+ //#endregion
323
+ //#region packages/otel/src/processors/simple-processor.ts
324
+ var MoostSimpleSpanProcessor = class extends SimpleSpanProcessor {
325
+ onEnd(span) {
326
+ if (shouldSpanBeIgnored(span)) return;
327
+ super.onEnd(span);
328
+ }
329
+ };
2621
330
 
2622
- export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreMeter, OtelIgnoreSpan, SpanInjector, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace, withSpan };
331
+ //#endregion
332
+ export { MoostBatchSpanProcessor, MoostSimpleSpanProcessor, OtelIgnoreMeter, OtelIgnoreSpan, SpanInjector, enableOtelForMoost, getOtelMate, shouldSpanBeIgnored, useOtelContext, useOtelPropagation, useSpan, useTrace, withSpan };