@treatwell/moleculer-essentials 2.0.0-beta.2 → 2.0.0-beta.5

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/README.md CHANGED
@@ -16,6 +16,9 @@
16
16
  - [License](#license)
17
17
  <!-- TOC -->
18
18
 
19
+ > [!WARNING]
20
+ > Starting v2.0.0-beta.4, this package is only compatible with moleculer v0.15+
21
+
19
22
  ## Purpose
20
23
 
21
24
  `@treatwell/moleculer-essentials` is a collection of essential utilities and helpers for building
@@ -354,4 +354,4 @@ function createOpenAPIResponses(model, description = "") {
354
354
  };
355
355
  }
356
356
 
357
- export { COERCE_ARRAY_ATTRIBUTE as C, DATE_TYPE as D, EMPTY_OBJECT_SCHEMA as E, FileTooBigSchema as F, GetOpenApiParamsSchema as G, OBJECTID_TYPE as O, SCHEMA_REF_NAME as S, UnauthorizedErrorSchema as U, ValidationErrorSchema as V, FileNotExistSchema as a, ServerErrorSchema as b, addFieldsToSchema as c, optionalFields as d, optionalExceptFields as e, composeSchemas as f, zodDate as g, zodObjectId as h, isZodSchema as i, zodCoerceArray as j, createOpenAPIResponses as k, omitFields as o, pickFields as p, toPartialSchema as t, zodToOpenAPISchema as z };
357
+ export { COERCE_ARRAY_ATTRIBUTE as C, DATE_TYPE as D, EMPTY_OBJECT_SCHEMA as E, FileTooBigSchema as F, GetOpenApiParamsSchema as G, OBJECTID_TYPE as O, SCHEMA_REF_NAME as S, UnauthorizedErrorSchema as U, ValidationErrorSchema as V, FileNotExistSchema as a, ServerErrorSchema as b, addFieldsToSchema as c, composeSchemas as d, createOpenAPIResponses as e, optionalExceptFields as f, optionalFields as g, zodCoerceArray as h, isZodSchema as i, zodDate as j, zodObjectId as k, omitFields as o, pickFields as p, toPartialSchema as t, zodToOpenAPISchema as z };
package/dist/index.cjs CHANGED
@@ -30,6 +30,16 @@ function getSchemaFromMoleculer(schema) {
30
30
  }
31
31
  return void 0;
32
32
  }
33
+ function getContextSchemaField(ctx, prop) {
34
+ if (!ctx) {
35
+ return;
36
+ }
37
+ const schema = ctx.action ?? ctx.event;
38
+ if (!schema) {
39
+ return;
40
+ }
41
+ return schema[prop];
42
+ }
33
43
 
34
44
  class RefExtractor {
35
45
  refs = /* @__PURE__ */ new Map();
@@ -730,8 +740,6 @@ class AjvExtractor extends RefExtractor {
730
740
  class AjvValidator extends moleculer.Validators.Base {
731
741
  modes;
732
742
  defaultMode;
733
- // broker is a property of the base class
734
- broker;
735
743
  zodValidator;
736
744
  /**
737
745
  * Cache of compiled validation functions.
@@ -739,7 +747,7 @@ class AjvValidator extends moleculer.Validators.Base {
739
747
  */
740
748
  compiledFns = /* @__PURE__ */ new WeakMap();
741
749
  constructor(opts, defaultMode, zodValidator) {
742
- super();
750
+ super({});
743
751
  this.defaultMode = defaultMode;
744
752
  this.zodValidator = zodValidator;
745
753
  this.modes = /* @__PURE__ */ new Map();
@@ -795,8 +803,10 @@ class AjvValidator extends moleculer.Validators.Base {
795
803
  }
796
804
  const { validator, extractor } = validatorMode;
797
805
  const refSchema = extractor.extract(schema);
798
- const fn = (params, ctx) => {
799
- if (!ctx?.action?.disableTransforms) {
806
+ const fn = (params, opts) => {
807
+ const ctx = opts?.meta.ctx;
808
+ const disableTransforms = getContextSchemaField(ctx, "disableTransforms");
809
+ if (!disableTransforms) {
800
810
  applyBeforeTransforms(schema, params);
801
811
  }
802
812
  const validate = validator.compile(refSchema);
@@ -812,7 +822,7 @@ class AjvValidator extends moleculer.Validators.Base {
812
822
  validate.errors || []
813
823
  );
814
824
  }
815
- if (!ctx?.action?.disableTransforms) {
825
+ if (!disableTransforms) {
816
826
  applyAfterTransforms(schema, params);
817
827
  }
818
828
  return true;
@@ -868,7 +878,7 @@ ${(errors || []).map(
868
878
  }
869
879
  const validate = this.compile(schema, action.validatorMode);
870
880
  return async (ctx) => {
871
- validate(ctx.params != null ? ctx.params : {}, ctx);
881
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
872
882
  return handler(ctx);
873
883
  };
874
884
  },
@@ -885,15 +895,21 @@ ${(errors || []).map(
885
895
  }
886
896
  const validate = this.compile(schema, event.validatorMode);
887
897
  return async (ctx) => {
888
- validate(ctx.params != null ? ctx.params : {}, ctx);
898
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
889
899
  return handler(ctx);
890
900
  };
891
901
  }
892
902
  };
893
903
  }
904
+ convertSchemaToMoleculer() {
905
+ throw new Error("Not implemented");
906
+ }
894
907
  }
895
908
 
896
909
  class ZodValidator extends moleculer.Validators.Base {
910
+ constructor() {
911
+ super({});
912
+ }
897
913
  compile() {
898
914
  throw new Error("compile should not be used, use validate instead");
899
915
  }
@@ -916,6 +932,7 @@ ${v4.z.prettifyError(res.error)}`,
916
932
  middleware() {
917
933
  return {
918
934
  name: "Validator",
935
+ // @ts-expect-error Moleculer wants action.params to be an object
919
936
  localAction: (handler, action) => {
920
937
  const schema = getSchemaFromMoleculer(action.params);
921
938
  if (!schema) {
@@ -926,6 +943,7 @@ ${v4.z.prettifyError(res.error)}`,
926
943
  return handler(ctx);
927
944
  };
928
945
  },
946
+ // @ts-expect-error Moleculer wants action.params to be an object
929
947
  localEvent: (handler, event) => {
930
948
  const schema = getSchemaFromMoleculer(event.params);
931
949
  if (!schema) {
@@ -938,6 +956,9 @@ ${v4.z.prettifyError(res.error)}`,
938
956
  }
939
957
  };
940
958
  }
959
+ convertSchemaToMoleculer() {
960
+ throw new Error("Not implemented");
961
+ }
941
962
  }
942
963
 
943
964
  class ContextFactory extends moleculer.Context {
@@ -1316,18 +1337,18 @@ function HealthCheckMiddleware(_opts) {
1316
1337
  });
1317
1338
  },
1318
1339
  // After broker started
1319
- started() {
1340
+ async started() {
1320
1341
  const timeout = setTimeout(() => {
1321
1342
  state = "up";
1322
1343
  }, opts.startDebounce);
1323
1344
  timeout.unref();
1324
1345
  },
1325
1346
  // Before broker stopping
1326
- stopping() {
1347
+ async stopping() {
1327
1348
  state = "stopping";
1328
1349
  },
1329
1350
  // After broker stopped
1330
- stopped() {
1351
+ async stopped() {
1331
1352
  state = "down";
1332
1353
  server.close();
1333
1354
  }
@@ -1336,23 +1357,27 @@ function HealthCheckMiddleware(_opts) {
1336
1357
 
1337
1358
  function flattenTags(obj, convertToString = false, path = "") {
1338
1359
  if (!obj) return null;
1339
- return Object.keys(obj).reduce((res, k) => {
1340
- const o = obj[k];
1341
- const pp = (path ? `${path}.` : "") + k;
1342
- if (compat.isObject(o)) {
1343
- if ("toHexString" in o) {
1344
- res[pp] = o.toString();
1345
- } else {
1346
- Object.assign(res, flattenTags(o, convertToString, pp));
1360
+ return Object.keys(obj).reduce(
1361
+ (res, k) => {
1362
+ const o = obj[k];
1363
+ const pp = (path ? `${path}.` : "") + k;
1364
+ if (compat.isObject(o)) {
1365
+ if ("toHexString" in o) {
1366
+ res[pp] = o.toString();
1367
+ } else {
1368
+ Object.assign(res, flattenTags(o, convertToString, pp));
1369
+ }
1370
+ } else if (o !== void 0 && o !== null) {
1371
+ res[pp] = convertToString ? String(o) : o;
1347
1372
  }
1348
- } else if (o !== void 0 && o !== null) {
1349
- res[pp] = convertToString ? String(o) : o;
1350
- }
1351
- return res;
1352
- }, {});
1373
+ return res;
1374
+ },
1375
+ {}
1376
+ );
1353
1377
  }
1354
1378
 
1355
1379
  class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1380
+ opts = {};
1356
1381
  queue;
1357
1382
  timer = null;
1358
1383
  defaultTags = {};
@@ -1372,11 +1397,11 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1372
1397
  */
1373
1398
  init(tracer) {
1374
1399
  super.init(tracer);
1375
- if (this.opts.interval > 0) {
1400
+ if (this.opts.interval && this.opts.interval > 0) {
1376
1401
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1377
1402
  this.timer.unref();
1378
1403
  }
1379
- this.defaultTags = typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags;
1404
+ this.defaultTags = (typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags) || null;
1380
1405
  if (this.defaultTags) {
1381
1406
  this.defaultTags = flattenTags(this.defaultTags, true);
1382
1407
  }
@@ -1459,7 +1484,6 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1459
1484
  "duration.ms": span.duration,
1460
1485
  name: span.name,
1461
1486
  "parent.id": span.parentID,
1462
- // @ts-expect-error fullName isn't declared on span yet
1463
1487
  "service.name": span.service?.fullName || null,
1464
1488
  ...flattenTags(span.tags, true),
1465
1489
  ...flattenTags(this.errorToObject(span.error), true, "error") || {}
@@ -1469,9 +1493,7 @@ class NewrelicTraceExporter extends moleculer.TracerExporters.Base {
1469
1493
  }
1470
1494
 
1471
1495
  class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1472
- // Those fields are not declared on the Base class.
1473
- registry;
1474
- logger;
1496
+ opts = {};
1475
1497
  timer = null;
1476
1498
  defaultTags = {};
1477
1499
  constructor(opts) {
@@ -1487,7 +1509,7 @@ class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1487
1509
  */
1488
1510
  init(registry) {
1489
1511
  super.init(registry);
1490
- if (this.opts.interval > 0) {
1512
+ if (this.opts.interval && this.opts.interval > 0) {
1491
1513
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1492
1514
  this.timer.unref();
1493
1515
  }
@@ -1589,7 +1611,7 @@ class NewrelicMetricsReporter extends moleculer.MetricReporters.Base {
1589
1611
  attributes: labels,
1590
1612
  timestamp,
1591
1613
  value: { count, sum, min: min || 0, max: max || 0 },
1592
- "interval.ms": this.opts.interval * 1e3
1614
+ "interval.ms": (this.opts.interval || 0) * 1e3
1593
1615
  });
1594
1616
  if (buckets) {
1595
1617
  Object.entries(buckets).forEach(([key, val]) => {
package/dist/index.d.cts CHANGED
@@ -1,10 +1,9 @@
1
- import { J as JSONSchemaType, S as SomeJSONSchema, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-BEknQmfU.cjs';
2
- export { e as AjvValidator, z as ApiKeySecurityScheme, K as CallbackObject, N as ComponentsObject, k as ContactObject, j as ContextFactory, r as EncodingObject, q as ExampleObject, E as ExternalDocumentationObject, H as HeaderObject, y as HttpSecurityScheme, I as InfoObject, X as InternalCallbackServiceThis, W as InternalObjectServiceThis, L as LicenseObject, u as LinkObject, s as MediaTypeObject, B as OAuth2SecurityScheme, F as OpenIdSecurityScheme, p as ParameterBaseObject, o as ParameterObject, U as PathItemObject, n as PathsObject, P as PropertiesSchema, t as RequestBodyObject, d as RequiredMembers, v as ResponseObject, w as ResponsesObject, x as SecurityRequirementObject, G as SecuritySchemeObject, m as ServerObject, l as ServerVariableObject, Q as TagObject, f as Transform, i as TransformField, g as TransformLevel, h as TransformMap, T as Transformer, V as ValidationSchema, Z as ZodValidator } from './types-BEknQmfU.cjs';
1
+ import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-DLBNHgt4.cjs';
2
+ export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-DLBNHgt4.cjs';
3
3
  import { ObjectId } from 'bson';
4
4
  import { z, ZodType } from 'zod/v4';
5
5
  import { Ajv2019 } from 'ajv/dist/2019.js';
6
- import * as Moleculer from 'moleculer';
7
- import { Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, LoggerInstance, Tracer, Span, MetricReporters, MetricRegistry, MetricReporterOptions } from 'moleculer';
6
+ import { Errors, Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, Logger as Logger$1, Tracer, Span, MetricReporters, MetricRegistry } from 'moleculer';
8
7
  import { Logger } from 'pino';
9
8
  import 'pino-pretty';
10
9
 
@@ -60,7 +59,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
60
59
  description: string;
61
60
  content: {
62
61
  'application/json': {
63
- schema: JSONSchemaType<Omit<Moleculer.Errors.MoleculerServerError, "cause">>;
62
+ schema: JSONSchemaType<Omit<Errors.MoleculerServerError, "cause">>;
64
63
  };
65
64
  };
66
65
  };
@@ -92,7 +91,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
92
91
  description: string;
93
92
  content: {
94
93
  'application/json': {
95
- schema: JSONSchemaType<Omit<Moleculer.Errors.ValidationError, "cause">>;
94
+ schema: JSONSchemaType<Omit<Errors.ValidationError, "cause">>;
96
95
  };
97
96
  };
98
97
  };
@@ -271,7 +270,7 @@ declare function createLogger(opts?: CreateLoggerOptions): Logger;
271
270
  declare function createLoggerConfig(opts?: MoleculerLoggerConfigOptions): LoggerConfig;
272
271
 
273
272
  type NewrelicTraceExporterOptions = {
274
- logger?: LoggerInstance;
273
+ logger?: Logger$1;
275
274
  safetyTags?: boolean;
276
275
  /**
277
276
  * Base URL for NewRelic server.
@@ -292,7 +291,7 @@ type NewrelicTraceExporterOptions = {
292
291
  /**
293
292
  * Default span tags.
294
293
  */
295
- defaultTags?: Record<string, unknown> | (() => Record<string, unknown>);
294
+ defaultTags?: Record<string, unknown> | ((tracer?: unknown) => Record<string, unknown>);
296
295
  };
297
296
  /**
298
297
  * >>> Hard copy of the moleculer NewRelic provider. It didn't handle errors correctly
@@ -303,6 +302,7 @@ type NewrelicTraceExporterOptions = {
303
302
  * API v2: https://zipkin.io/zipkin-api/#/
304
303
  */
305
304
  declare class NewrelicTraceExporter extends TracerExporters.Base {
305
+ private readonly opts;
306
306
  private queue;
307
307
  private timer;
308
308
  private defaultTags;
@@ -334,7 +334,7 @@ declare class NewrelicTraceExporter extends TracerExporters.Base {
334
334
  }
335
335
 
336
336
  type DefaultTags = Record<string, unknown> | ((registry: MetricRegistry) => Record<string, unknown>);
337
- type NewrelicMetricsOptions = MetricReporterOptions & {
337
+ type NewrelicMetricsOptions = MetricReporters.Base.MetricReporterOptions & {
338
338
  /**
339
339
  * Base URL for NewRelic server.
340
340
  */
@@ -358,8 +358,7 @@ type NewrelicMetricsOptions = MetricReporterOptions & {
358
358
  * NewRelic API: https://docs.newrelic.com/docs/data-apis/understand-data/metric-data/metric-data-type/
359
359
  */
360
360
  declare class NewrelicMetricsReporter extends MetricReporters.Base {
361
- registry: MetricRegistry;
362
- logger: LoggerInstance;
361
+ private readonly opts;
363
362
  private timer;
364
363
  private defaultTags;
365
364
  constructor(opts: NewrelicMetricsOptions);
package/dist/index.d.mts CHANGED
@@ -1,10 +1,9 @@
1
- import { J as JSONSchemaType, S as SomeJSONSchema, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-BEknQmfU.mjs';
2
- export { e as AjvValidator, z as ApiKeySecurityScheme, K as CallbackObject, N as ComponentsObject, k as ContactObject, j as ContextFactory, r as EncodingObject, q as ExampleObject, E as ExternalDocumentationObject, H as HeaderObject, y as HttpSecurityScheme, I as InfoObject, X as InternalCallbackServiceThis, W as InternalObjectServiceThis, L as LicenseObject, u as LinkObject, s as MediaTypeObject, B as OAuth2SecurityScheme, F as OpenIdSecurityScheme, p as ParameterBaseObject, o as ParameterObject, U as PathItemObject, n as PathsObject, P as PropertiesSchema, t as RequestBodyObject, d as RequiredMembers, v as ResponseObject, w as ResponsesObject, x as SecurityRequirementObject, G as SecuritySchemeObject, m as ServerObject, l as ServerVariableObject, Q as TagObject, f as Transform, i as TransformField, g as TransformLevel, h as TransformMap, T as Transformer, V as ValidationSchema, Z as ZodValidator } from './types-BEknQmfU.mjs';
1
+ import { S as SomeJSONSchema, J as JSONSchemaType, C as CustomActionSchema, A as Alias, a as CustomServiceSchema, D as Document, b as SchemaObject, O as OperationObject, R as ReferenceObject, c as CreateLoggerOptions, M as MoleculerLoggerConfigOptions } from './types-DLBNHgt4.mjs';
2
+ export { d as AjvValidator, e as ApiKeySecurityScheme, f as CallbackObject, g as ComponentsObject, h as ContactObject, i as ContextFactory, E as EncodingObject, j as ExampleObject, k as ExternalDocumentationObject, H as HeaderObject, l as HttpSecurityScheme, I as InfoObject, m as InternalCallbackServiceThis, n as InternalObjectServiceThis, L as LicenseObject, o as LinkObject, p as MediaTypeObject, q as OAuth2SecurityScheme, r as OpenIdSecurityScheme, P as ParameterBaseObject, s as ParameterObject, t as PathItemObject, u as PathsObject, v as PropertiesSchema, w as RequestBodyObject, x as RequiredMembers, y as ResponseObject, z as ResponsesObject, B as SecurityRequirementObject, F as SecuritySchemeObject, G as ServerObject, K as ServerVariableObject, T as TagObject, N as Transform, Q as TransformField, U as TransformLevel, V as TransformMap, W as Transformer, X as ValidationSchema, Z as ZodValidator } from './types-DLBNHgt4.mjs';
3
3
  import { ObjectId } from 'bson';
4
4
  import { z, ZodType } from 'zod/v4';
5
5
  import { Ajv2019 } from 'ajv/dist/2019.js';
6
- import * as Moleculer from 'moleculer';
7
- import { Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, LoggerInstance, Tracer, Span, MetricReporters, MetricRegistry, MetricReporterOptions } from 'moleculer';
6
+ import { Errors, Context, ServiceSchema, ServiceSettingSchema, Service, ServiceBroker, BrokerOptions, Middleware, LoggerConfig, TracerExporters, Logger as Logger$1, Tracer, Span, MetricReporters, MetricRegistry } from 'moleculer';
8
7
  import { Logger } from 'pino';
9
8
  import 'pino-pretty';
10
9
 
@@ -60,7 +59,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
60
59
  description: string;
61
60
  content: {
62
61
  'application/json': {
63
- schema: JSONSchemaType<Omit<Moleculer.Errors.MoleculerServerError, "cause">>;
62
+ schema: JSONSchemaType<Omit<Errors.MoleculerServerError, "cause">>;
64
63
  };
65
64
  };
66
65
  };
@@ -92,7 +91,7 @@ declare function OpenAPIMixin(options: OpenAPIMixinOptions): Partial<CustomServi
92
91
  description: string;
93
92
  content: {
94
93
  'application/json': {
95
- schema: JSONSchemaType<Omit<Moleculer.Errors.ValidationError, "cause">>;
94
+ schema: JSONSchemaType<Omit<Errors.ValidationError, "cause">>;
96
95
  };
97
96
  };
98
97
  };
@@ -271,7 +270,7 @@ declare function createLogger(opts?: CreateLoggerOptions): Logger;
271
270
  declare function createLoggerConfig(opts?: MoleculerLoggerConfigOptions): LoggerConfig;
272
271
 
273
272
  type NewrelicTraceExporterOptions = {
274
- logger?: LoggerInstance;
273
+ logger?: Logger$1;
275
274
  safetyTags?: boolean;
276
275
  /**
277
276
  * Base URL for NewRelic server.
@@ -292,7 +291,7 @@ type NewrelicTraceExporterOptions = {
292
291
  /**
293
292
  * Default span tags.
294
293
  */
295
- defaultTags?: Record<string, unknown> | (() => Record<string, unknown>);
294
+ defaultTags?: Record<string, unknown> | ((tracer?: unknown) => Record<string, unknown>);
296
295
  };
297
296
  /**
298
297
  * >>> Hard copy of the moleculer NewRelic provider. It didn't handle errors correctly
@@ -303,6 +302,7 @@ type NewrelicTraceExporterOptions = {
303
302
  * API v2: https://zipkin.io/zipkin-api/#/
304
303
  */
305
304
  declare class NewrelicTraceExporter extends TracerExporters.Base {
305
+ private readonly opts;
306
306
  private queue;
307
307
  private timer;
308
308
  private defaultTags;
@@ -334,7 +334,7 @@ declare class NewrelicTraceExporter extends TracerExporters.Base {
334
334
  }
335
335
 
336
336
  type DefaultTags = Record<string, unknown> | ((registry: MetricRegistry) => Record<string, unknown>);
337
- type NewrelicMetricsOptions = MetricReporterOptions & {
337
+ type NewrelicMetricsOptions = MetricReporters.Base.MetricReporterOptions & {
338
338
  /**
339
339
  * Base URL for NewRelic server.
340
340
  */
@@ -358,8 +358,7 @@ type NewrelicMetricsOptions = MetricReporterOptions & {
358
358
  * NewRelic API: https://docs.newrelic.com/docs/data-apis/understand-data/metric-data/metric-data-type/
359
359
  */
360
360
  declare class NewrelicMetricsReporter extends MetricReporters.Base {
361
- registry: MetricRegistry;
362
- logger: LoggerInstance;
361
+ private readonly opts;
363
362
  private timer;
364
363
  private defaultTags;
365
364
  constructor(opts: NewrelicMetricsOptions);
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SCHEMA_REF_NAME, i as isZodSchema, z as zodToOpenAPISchema, o as omitFields, G as GetOpenApiParamsSchema, V as ValidationErrorSchema, F as FileTooBigSchema, a as FileNotExistSchema, U as UnauthorizedErrorSchema, b as ServerErrorSchema, C as COERCE_ARRAY_ATTRIBUTE } from './index-B6AujuxZ.mjs';
2
- export { D as DATE_TYPE, E as EMPTY_OBJECT_SCHEMA, O as OBJECTID_TYPE, c as addFieldsToSchema, f as composeSchemas, k as createOpenAPIResponses, e as optionalExceptFields, d as optionalFields, p as pickFields, t as toPartialSchema, j as zodCoerceArray, g as zodDate, h as zodObjectId } from './index-B6AujuxZ.mjs';
1
+ import { S as SCHEMA_REF_NAME, i as isZodSchema, z as zodToOpenAPISchema, o as omitFields, G as GetOpenApiParamsSchema, V as ValidationErrorSchema, F as FileTooBigSchema, a as FileNotExistSchema, U as UnauthorizedErrorSchema, b as ServerErrorSchema, C as COERCE_ARRAY_ATTRIBUTE } from './index-DNiA_V_T.mjs';
2
+ export { D as DATE_TYPE, E as EMPTY_OBJECT_SCHEMA, O as OBJECTID_TYPE, c as addFieldsToSchema, d as composeSchemas, e as createOpenAPIResponses, f as optionalExceptFields, g as optionalFields, p as pickFields, t as toPartialSchema, h as zodCoerceArray, j as zodDate, k as zodObjectId } from './index-DNiA_V_T.mjs';
3
3
  import { Ajv2019 } from 'ajv/dist/2019.js';
4
4
  import { Validators, Errors, Context, ServiceBroker, Service, TracerExporters, MetricReporters } from 'moleculer';
5
5
  import addFormats from 'ajv-formats';
@@ -30,6 +30,16 @@ function getSchemaFromMoleculer(schema) {
30
30
  }
31
31
  return void 0;
32
32
  }
33
+ function getContextSchemaField(ctx, prop) {
34
+ if (!ctx) {
35
+ return;
36
+ }
37
+ const schema = ctx.action ?? ctx.event;
38
+ if (!schema) {
39
+ return;
40
+ }
41
+ return schema[prop];
42
+ }
33
43
 
34
44
  class RefExtractor {
35
45
  refs = /* @__PURE__ */ new Map();
@@ -730,8 +740,6 @@ class AjvExtractor extends RefExtractor {
730
740
  class AjvValidator extends Validators.Base {
731
741
  modes;
732
742
  defaultMode;
733
- // broker is a property of the base class
734
- broker;
735
743
  zodValidator;
736
744
  /**
737
745
  * Cache of compiled validation functions.
@@ -739,7 +747,7 @@ class AjvValidator extends Validators.Base {
739
747
  */
740
748
  compiledFns = /* @__PURE__ */ new WeakMap();
741
749
  constructor(opts, defaultMode, zodValidator) {
742
- super();
750
+ super({});
743
751
  this.defaultMode = defaultMode;
744
752
  this.zodValidator = zodValidator;
745
753
  this.modes = /* @__PURE__ */ new Map();
@@ -795,8 +803,10 @@ class AjvValidator extends Validators.Base {
795
803
  }
796
804
  const { validator, extractor } = validatorMode;
797
805
  const refSchema = extractor.extract(schema);
798
- const fn = (params, ctx) => {
799
- if (!ctx?.action?.disableTransforms) {
806
+ const fn = (params, opts) => {
807
+ const ctx = opts?.meta.ctx;
808
+ const disableTransforms = getContextSchemaField(ctx, "disableTransforms");
809
+ if (!disableTransforms) {
800
810
  applyBeforeTransforms(schema, params);
801
811
  }
802
812
  const validate = validator.compile(refSchema);
@@ -812,7 +822,7 @@ class AjvValidator extends Validators.Base {
812
822
  validate.errors || []
813
823
  );
814
824
  }
815
- if (!ctx?.action?.disableTransforms) {
825
+ if (!disableTransforms) {
816
826
  applyAfterTransforms(schema, params);
817
827
  }
818
828
  return true;
@@ -868,7 +878,7 @@ ${(errors || []).map(
868
878
  }
869
879
  const validate = this.compile(schema, action.validatorMode);
870
880
  return async (ctx) => {
871
- validate(ctx.params != null ? ctx.params : {}, ctx);
881
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
872
882
  return handler(ctx);
873
883
  };
874
884
  },
@@ -885,15 +895,21 @@ ${(errors || []).map(
885
895
  }
886
896
  const validate = this.compile(schema, event.validatorMode);
887
897
  return async (ctx) => {
888
- validate(ctx.params != null ? ctx.params : {}, ctx);
898
+ validate(ctx.params != null ? ctx.params : {}, { meta: { ctx } });
889
899
  return handler(ctx);
890
900
  };
891
901
  }
892
902
  };
893
903
  }
904
+ convertSchemaToMoleculer() {
905
+ throw new Error("Not implemented");
906
+ }
894
907
  }
895
908
 
896
909
  class ZodValidator extends Validators.Base {
910
+ constructor() {
911
+ super({});
912
+ }
897
913
  compile() {
898
914
  throw new Error("compile should not be used, use validate instead");
899
915
  }
@@ -916,6 +932,7 @@ ${z.prettifyError(res.error)}`,
916
932
  middleware() {
917
933
  return {
918
934
  name: "Validator",
935
+ // @ts-expect-error Moleculer wants action.params to be an object
919
936
  localAction: (handler, action) => {
920
937
  const schema = getSchemaFromMoleculer(action.params);
921
938
  if (!schema) {
@@ -926,6 +943,7 @@ ${z.prettifyError(res.error)}`,
926
943
  return handler(ctx);
927
944
  };
928
945
  },
946
+ // @ts-expect-error Moleculer wants action.params to be an object
929
947
  localEvent: (handler, event) => {
930
948
  const schema = getSchemaFromMoleculer(event.params);
931
949
  if (!schema) {
@@ -938,6 +956,9 @@ ${z.prettifyError(res.error)}`,
938
956
  }
939
957
  };
940
958
  }
959
+ convertSchemaToMoleculer() {
960
+ throw new Error("Not implemented");
961
+ }
941
962
  }
942
963
 
943
964
  class ContextFactory extends Context {
@@ -1316,18 +1337,18 @@ function HealthCheckMiddleware(_opts) {
1316
1337
  });
1317
1338
  },
1318
1339
  // After broker started
1319
- started() {
1340
+ async started() {
1320
1341
  const timeout = setTimeout(() => {
1321
1342
  state = "up";
1322
1343
  }, opts.startDebounce);
1323
1344
  timeout.unref();
1324
1345
  },
1325
1346
  // Before broker stopping
1326
- stopping() {
1347
+ async stopping() {
1327
1348
  state = "stopping";
1328
1349
  },
1329
1350
  // After broker stopped
1330
- stopped() {
1351
+ async stopped() {
1331
1352
  state = "down";
1332
1353
  server.close();
1333
1354
  }
@@ -1336,23 +1357,27 @@ function HealthCheckMiddleware(_opts) {
1336
1357
 
1337
1358
  function flattenTags(obj, convertToString = false, path = "") {
1338
1359
  if (!obj) return null;
1339
- return Object.keys(obj).reduce((res, k) => {
1340
- const o = obj[k];
1341
- const pp = (path ? `${path}.` : "") + k;
1342
- if (isObject(o)) {
1343
- if ("toHexString" in o) {
1344
- res[pp] = o.toString();
1345
- } else {
1346
- Object.assign(res, flattenTags(o, convertToString, pp));
1360
+ return Object.keys(obj).reduce(
1361
+ (res, k) => {
1362
+ const o = obj[k];
1363
+ const pp = (path ? `${path}.` : "") + k;
1364
+ if (isObject(o)) {
1365
+ if ("toHexString" in o) {
1366
+ res[pp] = o.toString();
1367
+ } else {
1368
+ Object.assign(res, flattenTags(o, convertToString, pp));
1369
+ }
1370
+ } else if (o !== void 0 && o !== null) {
1371
+ res[pp] = convertToString ? String(o) : o;
1347
1372
  }
1348
- } else if (o !== void 0 && o !== null) {
1349
- res[pp] = convertToString ? String(o) : o;
1350
- }
1351
- return res;
1352
- }, {});
1373
+ return res;
1374
+ },
1375
+ {}
1376
+ );
1353
1377
  }
1354
1378
 
1355
1379
  class NewrelicTraceExporter extends TracerExporters.Base {
1380
+ opts = {};
1356
1381
  queue;
1357
1382
  timer = null;
1358
1383
  defaultTags = {};
@@ -1372,11 +1397,11 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1372
1397
  */
1373
1398
  init(tracer) {
1374
1399
  super.init(tracer);
1375
- if (this.opts.interval > 0) {
1400
+ if (this.opts.interval && this.opts.interval > 0) {
1376
1401
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1377
1402
  this.timer.unref();
1378
1403
  }
1379
- this.defaultTags = typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags;
1404
+ this.defaultTags = (typeof this.opts.defaultTags === "function" ? this.opts.defaultTags.call(this, tracer) : this.opts.defaultTags) || null;
1380
1405
  if (this.defaultTags) {
1381
1406
  this.defaultTags = flattenTags(this.defaultTags, true);
1382
1407
  }
@@ -1459,7 +1484,6 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1459
1484
  "duration.ms": span.duration,
1460
1485
  name: span.name,
1461
1486
  "parent.id": span.parentID,
1462
- // @ts-expect-error fullName isn't declared on span yet
1463
1487
  "service.name": span.service?.fullName || null,
1464
1488
  ...flattenTags(span.tags, true),
1465
1489
  ...flattenTags(this.errorToObject(span.error), true, "error") || {}
@@ -1469,9 +1493,7 @@ class NewrelicTraceExporter extends TracerExporters.Base {
1469
1493
  }
1470
1494
 
1471
1495
  class NewrelicMetricsReporter extends MetricReporters.Base {
1472
- // Those fields are not declared on the Base class.
1473
- registry;
1474
- logger;
1496
+ opts = {};
1475
1497
  timer = null;
1476
1498
  defaultTags = {};
1477
1499
  constructor(opts) {
@@ -1487,7 +1509,7 @@ class NewrelicMetricsReporter extends MetricReporters.Base {
1487
1509
  */
1488
1510
  init(registry) {
1489
1511
  super.init(registry);
1490
- if (this.opts.interval > 0) {
1512
+ if (this.opts.interval && this.opts.interval > 0) {
1491
1513
  this.timer = setInterval(() => this.flush(), this.opts.interval * 1e3);
1492
1514
  this.timer.unref();
1493
1515
  }
@@ -1589,7 +1611,7 @@ class NewrelicMetricsReporter extends MetricReporters.Base {
1589
1611
  attributes: labels,
1590
1612
  timestamp,
1591
1613
  value: { count, sum, min: min || 0, max: max || 0 },
1592
- "interval.ms": this.opts.interval * 1e3
1614
+ "interval.ms": (this.opts.interval || 0) * 1e3
1593
1615
  });
1594
1616
  if (buckets) {
1595
1617
  Object.entries(buckets).forEach(([key, val]) => {
@@ -2,8 +2,8 @@
2
2
 
3
3
  var require$$0 = require('pino-pretty');
4
4
 
5
- function getDefaultExportFromCjs (x) {
6
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5
+ function getDefaultExportFromCjs(x) {
6
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
7
7
  }
8
8
 
9
9
  var pinoPrettyTransport$1;
@@ -310,7 +310,7 @@ function parseStringifiedQuery(sQuery) {
310
310
  if (!sQuery) {
311
311
  return {};
312
312
  }
313
- let query = {};
313
+ let query;
314
314
  try {
315
315
  query = JSON.parse(sQuery || "{}");
316
316
  } catch {