@opentelemetry/instrumentation-express 0.33.2 → 0.34.0

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
@@ -79,6 +79,13 @@ Express instrumentation has few options available to choose from. You can set th
79
79
  - `info: ExpressRequestInfo` containing the incoming Express.js request, the current route handler creating a span and `ExpressLayerType` - the type of the handling layer.
80
80
  - `defaultName: string` - original name proposed by the instrumentation.
81
81
 
82
+ `requestHook` is invoked with 2 arguments:
83
+
84
+ - `span: Span` - the span associated with the express request.
85
+ - `info: ExpressRequestInfo` containing the incoming Express.js request, the current route handler creating a span and `ExpressLayerType` - the type of the handling layer.
86
+
87
+ NOTE: `ExpressRequestInfo.request` is typed as `any`. If you want type support make sure you have `@types/express` installed then you can use `ExpressRequestInfo<express.Request>`
88
+
82
89
  #### Ignore a whole Express route
83
90
 
84
91
  In order to ignore whole traces that represent a given Express route, use
@@ -121,6 +121,7 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
121
121
  return;
122
122
  layer[internal_types_1.kLayerPatched] = true;
123
123
  this._wrap(layer, 'handle', (original) => {
124
+ // TODO: instrument error handlers
124
125
  if (original.length === 4)
125
126
  return original;
126
127
  return function (req, res) {
@@ -185,29 +186,53 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
185
186
  if (callbackIdx >= 0) {
186
187
  arguments[callbackIdx] = function () {
187
188
  var _a;
189
+ // express considers anything but an empty value, "route" or "router"
190
+ // passed to its callback to be an error
191
+ const maybeError = arguments[0];
192
+ const isError = ![undefined, null, 'route', 'router'].includes(maybeError);
193
+ if (isError) {
194
+ const [error, message] = (0, utils_1.asErrorAndMessage)(maybeError);
195
+ span.recordException(error);
196
+ span.setStatus({
197
+ code: api_1.SpanStatusCode.ERROR,
198
+ message,
199
+ });
200
+ }
188
201
  if (spanHasEnded === false) {
189
202
  spanHasEnded = true;
190
203
  (_a = req.res) === null || _a === void 0 ? void 0 : _a.removeListener('finish', onResponseFinish);
191
204
  span.end();
192
205
  }
193
- if (!(req.route && arguments[0] instanceof Error)) {
206
+ if (!(req.route && isError)) {
194
207
  req[internal_types_1._LAYERS_STORE_PROPERTY].pop();
195
208
  }
196
209
  const callback = args[callbackIdx];
197
210
  return callback.apply(this, arguments);
198
211
  };
199
212
  }
200
- const result = original.apply(this, arguments);
201
- /**
202
- * At this point if the callback wasn't called, that means either the
203
- * layer is asynchronous (so it will call the callback later on) or that
204
- * the layer directly end the http response, so we'll hook into the "finish"
205
- * event to handle the later case.
206
- */
207
- if (!spanHasEnded) {
208
- res.once('finish', onResponseFinish);
213
+ try {
214
+ return original.apply(this, arguments);
215
+ }
216
+ catch (anyError) {
217
+ const [error, message] = (0, utils_1.asErrorAndMessage)(anyError);
218
+ span.recordException(error);
219
+ span.setStatus({
220
+ code: api_1.SpanStatusCode.ERROR,
221
+ message,
222
+ });
223
+ throw anyError;
224
+ }
225
+ finally {
226
+ /**
227
+ * At this point if the callback wasn't called, that means either the
228
+ * layer is asynchronous (so it will call the callback later on) or that
229
+ * the layer directly end the http response, so we'll hook into the "finish"
230
+ * event to handle the later case.
231
+ */
232
+ if (!spanHasEnded) {
233
+ res.once('finish', onResponseFinish);
234
+ }
209
235
  }
210
- return result;
211
236
  };
212
237
  });
213
238
  }
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAA8D;AAC9D,4CAA0E;AAG1E,+DAA4D;AAC5D,2DAAwD;AACxD,mCAA2E;AAC3E,uCAAoC;AACpC,oEAKwC;AACxC,8EAAyE;AACzE,qDAM0B;AAE1B,gDAAgD;AAChD,MAAa,sBAAuB,SAAQ,qCAE3C;IACC,YAAY,SAAuC,EAAE;QACnD,KAAK,CACH,wCAAwC,EACxC,iBAAO,EACP,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAC1B,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I,YAAY,QAAQ,CAAC,EAAE;YAC/B,OAAO,WAAW,CAAC;SACpB;QAED,IAAI;YACF,OAAO,MAAA,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,mCAAI,WAAW,CAAC;SAC/C;QAAC,OAAO,GAAG,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AA5QD,wDA4QC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport { trace, context, diag, SpanAttributes } from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { getLayerMetadata, storeLayerPath, isLayerIgnored } from './utils';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<\n typeof express\n> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(\n '@opentelemetry/instrumentation-express',\n VERSION,\n Object.assign({}, config)\n );\n }\n\n override setConfig(config: ExpressInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): ExpressInstrumentationConfig {\n return this._config as ExpressInstrumentationConfig;\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition<typeof express>(\n 'express',\n ['^4.0.0'],\n (moduleExports, moduleVersion) => {\n diag.debug(`Applying patch for express@${moduleVersion}`);\n const routerProto = moduleExports.Router as unknown as express.Router;\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch() as any\n );\n return moduleExports;\n },\n (moduleExports, moduleVersion) => {\n if (moduleExports === undefined) return;\n diag.debug(`Removing patch for express@${moduleVersion}`);\n const routerProto = moduleExports.Router as unknown as express.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch() {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n this: { _router: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this._router.stack[this._router.stack.length - 1];\n instrumentation._applyPatch.call(\n instrumentation,\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', (original: Function) => {\n if (original.length === 4) return original;\n return function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('');\n\n const attributes: SpanAttributes = {\n [SemanticAttributes.HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation._config)) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n if (instrumentation.getConfig().requestHook) {\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().requestHook!(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] !==\n ExpressLayerType.MIDDLEWARE\n ) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && arguments[0] instanceof Error)) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return callback.apply(this, arguments);\n };\n }\n const result = original.apply(this, arguments);\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly end the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n return result;\n };\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const hook = this.getConfig().spanNameHook;\n\n if (!(hook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return hook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;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G,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AAvSD,wDAuSC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n isLayerIgnored,\n storeLayerPath,\n} from './utils';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<\n typeof express\n> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(\n '@opentelemetry/instrumentation-express',\n VERSION,\n Object.assign({}, config)\n );\n }\n\n override setConfig(config: ExpressInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): ExpressInstrumentationConfig {\n return this._config as ExpressInstrumentationConfig;\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition<typeof express>(\n 'express',\n ['^4.0.0'],\n (moduleExports, moduleVersion) => {\n diag.debug(`Applying patch for express@${moduleVersion}`);\n const routerProto = moduleExports.Router as unknown as express.Router;\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch() as any\n );\n return moduleExports;\n },\n (moduleExports, moduleVersion) => {\n if (moduleExports === undefined) return;\n diag.debug(`Removing patch for express@${moduleVersion}`);\n const routerProto = moduleExports.Router as unknown as express.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch() {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n this: { _router: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this._router.stack[this._router.stack.length - 1];\n instrumentation._applyPatch.call(\n instrumentation,\n layer,\n typeof args[0] === 'string' ? args[0] : undefined\n );\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', (original: Function) => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n return function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('');\n\n const attributes: Attributes = {\n [SemanticAttributes.HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation._config)) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n if (instrumentation.getConfig().requestHook) {\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().requestHook!(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] !==\n ExpressLayerType.MIDDLEWARE\n ) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError)) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return callback.apply(this, arguments);\n };\n }\n\n try {\n return original.apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly end the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const hook = this.getConfig().spanNameHook;\n\n if (!(hook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return hook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { Request } from 'express';
2
- import { SpanAttributes } from '@opentelemetry/api';
2
+ import { Attributes } from '@opentelemetry/api';
3
3
  /**
4
4
  * This symbol is used to mark express layer as being already instrumented
5
5
  * since its possible to use a given layer multiple times (ex: middlewares)
@@ -47,7 +47,7 @@ export declare type ExpressLayer = {
47
47
  regexp: RegExp;
48
48
  };
49
49
  export declare type LayerMetadata = {
50
- attributes: SpanAttributes;
50
+ attributes: Attributes;
51
51
  name: string;
52
52
  };
53
53
  //# sourceMappingURL=internal-types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH;;;GAGG;AACU,QAAA,aAAa,GAAkB,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAE5E;;;;;;;;;;;;;;;GAeG;AACU,QAAA,sBAAsB,GAAG,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Request } from 'express';\nimport { SpanAttributes } from '@opentelemetry/api';\n\n/**\n * This symbol is used to mark express layer as being already instrumented\n * since its possible to use a given layer multiple times (ex: middlewares)\n */\nexport const kLayerPatched: unique symbol = Symbol('express-layer-patched');\n\n/**\n * This const define where on the `request` object the Instrumentation will mount the\n * current stack of express layer.\n *\n * It is necessary because express doesnt store the different layers\n * (ie: middleware, router etc) that it called to get to the current layer.\n * Given that, the only way to know the route of a given layer is to\n * store the path of where each previous layer has been mounted.\n *\n * ex: bodyParser > auth middleware > /users router > get /:id\n * in this case the stack would be: [\"/users\", \"/:id\"]\n *\n * ex2: bodyParser > /api router > /v1 router > /users router > get /:id\n * stack: [\"/api\", \"/v1\", \"/users\", \":id\"]\n *\n */\nexport const _LAYERS_STORE_PROPERTY = '__ot_middlewares';\n\nexport type PatchedRequest = {\n [_LAYERS_STORE_PROPERTY]?: string[];\n} & Request;\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\n// https://github.com/expressjs/express/blob/main/lib/router/index.js#L53\nexport type ExpressRouter = {\n params: { [key: string]: string };\n _params: string[];\n caseSensitive: boolean;\n mergeParams: boolean;\n strict: boolean;\n stack: ExpressLayer[];\n};\n\n// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33\nexport type ExpressLayer = {\n handle: Function;\n [kLayerPatched]?: boolean;\n name: string;\n params: { [key: string]: string };\n path: string;\n regexp: RegExp;\n};\n\nexport type LayerMetadata = {\n attributes: SpanAttributes;\n name: string;\n};\n"]}
1
+ {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAKH;;;GAGG;AACU,QAAA,aAAa,GAAkB,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAE5E;;;;;;;;;;;;;;;GAeG;AACU,QAAA,sBAAsB,GAAG,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Request } from 'express';\nimport { Attributes } from '@opentelemetry/api';\n\n/**\n * This symbol is used to mark express layer as being already instrumented\n * since its possible to use a given layer multiple times (ex: middlewares)\n */\nexport const kLayerPatched: unique symbol = Symbol('express-layer-patched');\n\n/**\n * This const define where on the `request` object the Instrumentation will mount the\n * current stack of express layer.\n *\n * It is necessary because express doesnt store the different layers\n * (ie: middleware, router etc) that it called to get to the current layer.\n * Given that, the only way to know the route of a given layer is to\n * store the path of where each previous layer has been mounted.\n *\n * ex: bodyParser > auth middleware > /users router > get /:id\n * in this case the stack would be: [\"/users\", \"/:id\"]\n *\n * ex2: bodyParser > /api router > /v1 router > /users router > get /:id\n * stack: [\"/api\", \"/v1\", \"/users\", \":id\"]\n *\n */\nexport const _LAYERS_STORE_PROPERTY = '__ot_middlewares';\n\nexport type PatchedRequest = {\n [_LAYERS_STORE_PROPERTY]?: string[];\n} & Request;\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\n// https://github.com/expressjs/express/blob/main/lib/router/index.js#L53\nexport type ExpressRouter = {\n params: { [key: string]: string };\n _params: string[];\n caseSensitive: boolean;\n mergeParams: boolean;\n strict: boolean;\n stack: ExpressLayer[];\n};\n\n// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33\nexport type ExpressLayer = {\n handle: Function;\n [kLayerPatched]?: boolean;\n name: string;\n params: { [key: string]: string };\n path: string;\n regexp: RegExp;\n};\n\nexport type LayerMetadata = {\n attributes: Attributes;\n name: string;\n};\n"]}
@@ -1,10 +1,10 @@
1
- import type { Request } from 'express';
2
1
  import { Span } from '@opentelemetry/api';
3
2
  import { InstrumentationConfig } from '@opentelemetry/instrumentation';
4
3
  import { ExpressLayerType } from './enums/ExpressLayerType';
5
4
  export declare type IgnoreMatcher = string | RegExp | ((name: string) => boolean);
6
- export declare type ExpressRequestInfo = {
7
- request: Request;
5
+ export declare type ExpressRequestInfo<T = any> = {
6
+ /** An express request object */
7
+ request: T;
8
8
  route: string;
9
9
  layerType: ExpressLayerType;
10
10
  };
@@ -24,7 +24,7 @@ export interface ExpressRequestCustomAttributeFunction {
24
24
  (span: Span, info: ExpressRequestInfo): void;
25
25
  }
26
26
  /**
27
- * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-Instrumentation-express#express-Instrumentation-options))
27
+ * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express#express-instrumentation-options))
28
28
  */
29
29
  export interface ExpressInstrumentationConfig extends InstrumentationConfig {
30
30
  /** Ignore specific based on their name */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Request } from 'express';\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressRequestInfo = {\n request: Request;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type SpanNameHook = (\n info: ExpressRequestInfo,\n /**\n * If no decision is taken based on RequestInfo, the default name\n * supplied by the instrumentation can be used instead.\n */\n defaultName: string\n) => string;\n\n/**\n * Function that can be used to add custom attributes to the current span or the root span on\n * a Express request\n * @param span - The Express middleware layer span.\n * @param info - An instance of ExpressRequestInfo that contains info about the request such as the route, and the layer type.\n */\nexport interface ExpressRequestCustomAttributeFunction {\n (span: Span, info: ExpressRequestInfo): void;\n}\n\n/**\n * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-Instrumentation-express#express-Instrumentation-options))\n */\nexport interface ExpressInstrumentationConfig extends InstrumentationConfig {\n /** Ignore specific based on their name */\n ignoreLayers?: IgnoreMatcher[];\n /** Ignore specific layers based on their type */\n ignoreLayersType?: ExpressLayerType[];\n spanNameHook?: SpanNameHook;\n\n /** Function for adding custom attributes on Express request */\n requestHook?: ExpressRequestCustomAttributeFunction;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressRequestInfo<T = any> = {\n /** An express request object */\n request: T;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type SpanNameHook = (\n info: ExpressRequestInfo,\n /**\n * If no decision is taken based on RequestInfo, the default name\n * supplied by the instrumentation can be used instead.\n */\n defaultName: string\n) => string;\n\n/**\n * Function that can be used to add custom attributes to the current span or the root span on\n * a Express request\n * @param span - The Express middleware layer span.\n * @param info - An instance of ExpressRequestInfo that contains info about the request such as the route, and the layer type.\n */\nexport interface ExpressRequestCustomAttributeFunction {\n (span: Span, info: ExpressRequestInfo): void;\n}\n\n/**\n * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express#express-instrumentation-options))\n */\nexport interface ExpressInstrumentationConfig extends InstrumentationConfig {\n /** Ignore specific based on their name */\n ignoreLayers?: IgnoreMatcher[];\n /** Ignore specific layers based on their type */\n ignoreLayersType?: ExpressLayerType[];\n spanNameHook?: SpanNameHook;\n\n /** Function for adding custom attributes on Express request */\n requestHook?: ExpressRequestCustomAttributeFunction;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { SpanAttributes } from '@opentelemetry/api';
1
+ import { Attributes } from '@opentelemetry/api';
2
2
  import { ExpressInstrumentationConfig } from './types';
3
3
  import { ExpressLayerType } from './enums/ExpressLayerType';
4
4
  import { ExpressLayer, PatchedRequest } from './internal-types';
@@ -14,7 +14,7 @@ export declare const storeLayerPath: (request: PatchedRequest, value?: string |
14
14
  * @param [layerPath] if present, the path on which the layer has been mounted
15
15
  */
16
16
  export declare const getLayerMetadata: (layer: ExpressLayer, layerPath?: string | undefined) => {
17
- attributes: SpanAttributes;
17
+ attributes: Attributes;
18
18
  name: string;
19
19
  };
20
20
  /**
@@ -26,4 +26,11 @@ export declare const getLayerMetadata: (layer: ExpressLayer, layerPath?: string
26
26
  * occurred
27
27
  */
28
28
  export declare const isLayerIgnored: (name: string, type: ExpressLayerType, config?: ExpressInstrumentationConfig | undefined) => boolean;
29
+ /**
30
+ * Converts a user-provided error value into an error and error message pair
31
+ *
32
+ * @param error - User-provided error value
33
+ * @returns Both an Error or string representation of the value and an error message
34
+ */
35
+ export declare const asErrorAndMessage: (error: unknown) => [error: string | Error, message: string];
29
36
  //# sourceMappingURL=utils.d.ts.map
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.isLayerIgnored = exports.getLayerMetadata = exports.storeLayerPath = void 0;
18
+ exports.asErrorAndMessage = exports.isLayerIgnored = exports.getLayerMetadata = exports.storeLayerPath = void 0;
19
19
  const ExpressLayerType_1 = require("./enums/ExpressLayerType");
20
20
  const AttributeNames_1 = require("./enums/AttributeNames");
21
21
  const internal_types_1 = require("./internal-types");
@@ -120,4 +120,14 @@ const isLayerIgnored = (name, type, config) => {
120
120
  return false;
121
121
  };
122
122
  exports.isLayerIgnored = isLayerIgnored;
123
+ /**
124
+ * Converts a user-provided error value into an error and error message pair
125
+ *
126
+ * @param error - User-provided error value
127
+ * @returns Both an Error or string representation of the value and an error message
128
+ */
129
+ const asErrorAndMessage = (error) => error instanceof Error
130
+ ? [error, error.message]
131
+ : [String(error), String(error)];
132
+ exports.asErrorAndMessage = asErrorAndMessage;
123
133
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,+DAA4D;AAC5D,2DAAwD;AACxD,qDAI0B;AAE1B;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAAC,OAAuB,EAAE,KAAc,EAAE,EAAE;IACxE,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,uCAAsB,CAAC,CAAC,KAAK,KAAK,EAAE;QAC5D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,uCAAsB,EAAE;YACrD,UAAU,EAAE,KAAK;YACjB,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;KACJ;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO;IAC/B,OAAO,CAAC,uCAAsB,CAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC,CAAC;AATW,QAAA,cAAc,kBASzB;AAEF;;;;GAIG;AACI,MAAM,gBAAgB,GAAG,CAC9B,KAAmB,EACnB,SAAkB,EAIlB,EAAE;IACF,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,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M,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;KAC3D;AACH,CAAC,CAAC;AAEF;;;;;;;GAOG;AACI,MAAM,cAAc,GAAG,CAC5B,IAAY,EACZ,IAAsB,EACtB,MAAqC,EAC5B,EAAE;;IACX,IACE,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,CAAC;SACvC,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,0CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EACxC;QACA,OAAO,IAAI,CAAC;KACb;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAC,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAChE,IAAI;QACF,KAAK,MAAM,OAAO,IAAI,MAAO,CAAC,YAAa,EAAE;YAC3C,IAAI,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;gBACnC,OAAO,IAAI,CAAC;aACb;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,gBAAgB;KACjB;IAED,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAvBW,QAAA,cAAc,kBAuBzB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanAttributes } from '@opentelemetry/api';\nimport { IgnoreMatcher, ExpressInstrumentationConfig } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (request: PatchedRequest, value?: string) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return;\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: SpanAttributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${layerPath}`,\n };\n } else if (layer.name === 'bound dispatch') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,+DAA4D;AAC5D,2DAAwD;AACxD,qDAI0B;AAE1B;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAAC,OAAuB,EAAE,KAAc,EAAE,EAAE;IACxE,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,uCAAsB,CAAC,CAAC,KAAK,KAAK,EAAE;QAC5D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,uCAAsB,EAAE;YACrD,UAAU,EAAE,KAAK;YACjB,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;KACJ;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO;IAC/B,OAAO,CAAC,uCAAsB,CAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC,CAAC;AATW,QAAA,cAAc,kBASzB;AAEF;;;;GAIG;AACI,MAAM,gBAAgB,GAAG,CAC9B,KAAmB,EACnB,SAAkB,EAIlB,EAAE;IACF,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC3B,OAAO;YACL,UAAU,EAAE;gBACV,CAAC,+BAAc,CAAC,YAAY,CAAC,EAAE,SAAS;gBACxC,CAAC,+BAAc,CAAC,YAAY,CAAC,EAAE,mCAAgB,CAAC,MAAM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C5B,EAAE;;IACX,IACE,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,CAAC;SACvC,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,0CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EACxC;QACA,OAAO,IAAI,CAAC;KACb;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAC,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAChE,IAAI;QACF,KAAK,MAAM,OAAO,IAAI,MAAO,CAAC,YAAa,EAAE;YAC3C,IAAI,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;gBACnC,OAAO,IAAI,CAAC;aACb;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,gBAAgB;KACjB;IAED,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAvBW,QAAA,cAAc,kBAuBzB;AAEF;;;;;GAKG;AACI,MAAM,iBAAiB,GAAG,CAC/B,KAAc,EAC4B,EAAE,CAC5C,KAAK,YAAY,KAAK;IACpB,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;IACxB,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AALxB,QAAA,iBAAiB,qBAKO","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes } from '@opentelemetry/api';\nimport { IgnoreMatcher, ExpressInstrumentationConfig } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (request: PatchedRequest, value?: string) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return;\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${layerPath}`,\n };\n } else if (layer.name === 'bound dispatch') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.33.2";
1
+ export declare const VERSION = "0.34.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -17,5 +17,5 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.VERSION = void 0;
19
19
  // this is autogenerated file, see scripts/version-update.js
20
- exports.VERSION = '0.33.2';
20
+ exports.VERSION = '0.34.0';
21
21
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.33.2';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.34.0';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/instrumentation-express",
3
- "version": "0.33.2",
3
+ "version": "0.34.0",
4
4
  "description": "OpenTelemetry express automatic instrumentation package.",
5
5
  "main": "build/src/index.js",
6
6
  "types": "build/src/index.d.ts",
@@ -17,7 +17,7 @@
17
17
  "version:update": "node ../../../scripts/version-update.js",
18
18
  "compile": "tsc -p .",
19
19
  "compile:examples": "cd examples && npm run compile",
20
- "prepare": "npm run compile",
20
+ "prepublishOnly": "npm run compile",
21
21
  "watch": "tsc -w"
22
22
  },
23
23
  "keywords": [
@@ -36,10 +36,7 @@
36
36
  "files": [
37
37
  "build/src/**/*.js",
38
38
  "build/src/**/*.js.map",
39
- "build/src/**/*.d.ts",
40
- "doc",
41
- "LICENSE",
42
- "README.md"
39
+ "build/src/**/*.d.ts"
43
40
  ],
44
41
  "publishConfig": {
45
42
  "access": "public"
@@ -52,6 +49,7 @@
52
49
  "@opentelemetry/context-async-hooks": "^1.8.0",
53
50
  "@opentelemetry/sdk-trace-base": "^1.8.0",
54
51
  "@opentelemetry/sdk-trace-node": "^1.8.0",
52
+ "@types/express": "4.17.18",
55
53
  "@types/mocha": "7.0.2",
56
54
  "@types/node": "18.6.5",
57
55
  "@types/sinon": "10.0.18",
@@ -66,10 +64,9 @@
66
64
  },
67
65
  "dependencies": {
68
66
  "@opentelemetry/core": "^1.8.0",
69
- "@opentelemetry/instrumentation": "^0.44.0",
70
- "@opentelemetry/semantic-conventions": "^1.0.0",
71
- "@types/express": "4.17.18"
67
+ "@opentelemetry/instrumentation": "^0.45.1",
68
+ "@opentelemetry/semantic-conventions": "^1.0.0"
72
69
  },
73
70
  "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-express#readme",
74
- "gitHead": "a8c225d2febcac561a70ca586d3efd5a84f9f3fa"
71
+ "gitHead": "c7e7000b7bf79b0b107c448b403c2613a9b9e2c1"
75
72
  }