{"version":3,"file":"instrumentation.cjs","names":["InstrumentationBase","PACKAGE_NAME","PACKAGE_VERSION","InstrumentationNodeModuleDefinition","InstrumentationNodeModuleFile","isWrapped","api","ATTR_HTTP_ROUTE","ATTR_HTTP_REQUEST_METHOD","ATTR_URL_FULL"],"sources":["../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n  InstrumentationBase,\n  InstrumentationConfig,\n  InstrumentationNodeModuleDefinition,\n  InstrumentationNodeModuleFile,\n  isWrapped,\n} from '@opentelemetry/instrumentation';\nimport {\n  ATTR_HTTP_REQUEST_METHOD,\n  ATTR_HTTP_ROUTE,\n  ATTR_URL_FULL,\n} from '@opentelemetry/semantic-conventions';\nimport type { NestFactory } from '@nestjs/core/nest-factory.js';\nimport type { RouterExecutionContext } from '@nestjs/core/router/router-execution-context.js';\nimport type { Controller } from '@nestjs/common/interfaces';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { AttributeNames, NestType } from './enums';\n\nconst supportedVersions = ['>=4.0.0 <12'];\n\nexport class NestInstrumentation extends InstrumentationBase {\n  static readonly COMPONENT = '@nestjs/core';\n  static readonly COMMON_ATTRIBUTES = {\n    component: NestInstrumentation.COMPONENT,\n  };\n\n  constructor(config: InstrumentationConfig = {}) {\n    super(PACKAGE_NAME, PACKAGE_VERSION, config);\n  }\n\n  init() {\n    const module = new InstrumentationNodeModuleDefinition(\n      NestInstrumentation.COMPONENT,\n      supportedVersions\n    );\n\n    module.files.push(\n      this.getNestFactoryFileInstrumentation(supportedVersions),\n      this.getRouterExecutionContextFileInstrumentation(supportedVersions)\n    );\n\n    return module;\n  }\n\n  getNestFactoryFileInstrumentation(versions: string[]) {\n    return new InstrumentationNodeModuleFile(\n      '@nestjs/core/nest-factory.js',\n      versions,\n      (NestFactoryStatic: any, moduleVersion?: string) => {\n        this.ensureWrapped(\n          NestFactoryStatic.NestFactoryStatic.prototype,\n          'create',\n          createWrapNestFactoryCreate(this.tracer, moduleVersion)\n        );\n        return NestFactoryStatic;\n      },\n      (NestFactoryStatic: any) => {\n        this._unwrap(NestFactoryStatic.NestFactoryStatic.prototype, 'create');\n      }\n    );\n  }\n\n  getRouterExecutionContextFileInstrumentation(versions: string[]) {\n    return new InstrumentationNodeModuleFile(\n      '@nestjs/core/router/router-execution-context.js',\n      versions,\n      (RouterExecutionContext: any, moduleVersion?: string) => {\n        this.ensureWrapped(\n          RouterExecutionContext.RouterExecutionContext.prototype,\n          'create',\n          createWrapCreateHandler(this.tracer, moduleVersion)\n        );\n        return RouterExecutionContext;\n      },\n      (RouterExecutionContext: any) => {\n        this._unwrap(\n          RouterExecutionContext.RouterExecutionContext.prototype,\n          'create'\n        );\n      }\n    );\n  }\n\n  private ensureWrapped(\n    obj: any,\n    methodName: string,\n    wrapper: (original: any) => any\n  ) {\n    if (isWrapped(obj[methodName])) {\n      this._unwrap(obj, methodName);\n    }\n    this._wrap(obj, methodName, wrapper);\n  }\n}\n\nfunction createWrapNestFactoryCreate(\n  tracer: api.Tracer,\n  moduleVersion?: string\n) {\n  return function wrapCreate(original: typeof NestFactory.create) {\n    return function createWithTrace(\n      this: typeof NestFactory,\n      nestModule: any\n      /* serverOrOptions */\n    ) {\n      const span = tracer.startSpan('Create Nest App', {\n        attributes: {\n          ...NestInstrumentation.COMMON_ATTRIBUTES,\n          [AttributeNames.TYPE]: NestType.APP_CREATION,\n          [AttributeNames.VERSION]: moduleVersion,\n          [AttributeNames.MODULE]: nestModule.name,\n        },\n      });\n      const spanContext = api.trace.setSpan(api.context.active(), span);\n\n      return api.context.with(spanContext, async () => {\n        try {\n          return await original.apply(this, arguments as any);\n        } catch (e: any) {\n          throw addError(span, e);\n        } finally {\n          span.end();\n        }\n      });\n    };\n  };\n}\n\nfunction createWrapCreateHandler(\n  tracer: api.Tracer,\n  moduleVersion: string | undefined\n) {\n  return function wrapCreateHandler(\n    original: RouterExecutionContext['create']\n  ) {\n    return function createHandlerWithTrace(\n      this: RouterExecutionContext,\n      instance: Controller,\n      callback: (...args: any[]) => unknown\n    ) {\n      arguments[1] = createWrapHandler(tracer, moduleVersion, callback);\n      const handler = original.apply(this, arguments as any);\n      const callbackName = callback.name;\n      const instanceName =\n        instance.constructor && instance.constructor.name\n          ? instance.constructor.name\n          : 'UnnamedInstance';\n      const spanName = callbackName\n        ? `${instanceName}.${callbackName}`\n        : instanceName;\n\n      return function (\n        this: any,\n        req: any,\n        res: any,\n        next: (...args: any[]) => unknown\n      ) {\n        const attributes: api.Attributes = {\n          ...NestInstrumentation.COMMON_ATTRIBUTES,\n          [AttributeNames.VERSION]: moduleVersion,\n          [AttributeNames.TYPE]: NestType.REQUEST_CONTEXT,\n          [ATTR_HTTP_ROUTE]:\n            req.route?.path || req.routeOptions?.url || req.routerPath,\n          [AttributeNames.CONTROLLER]: instanceName,\n          [AttributeNames.CALLBACK]: callbackName,\n        };\n        attributes[ATTR_HTTP_REQUEST_METHOD] = req.method;\n        attributes[ATTR_URL_FULL] = req.originalUrl || req.url;\n        const span = tracer.startSpan(spanName, { attributes });\n        const spanContext = api.trace.setSpan(api.context.active(), span);\n\n        return api.context.with(spanContext, async () => {\n          try {\n            return await handler.apply(this, arguments as any);\n          } catch (e: any) {\n            throw addError(span, e);\n          } finally {\n            span.end();\n          }\n        });\n      };\n    };\n  };\n}\n\nfunction createWrapHandler(\n  tracer: api.Tracer,\n  moduleVersion: string | undefined,\n  handler: Function\n) {\n  const spanName = handler.name || 'anonymous nest handler';\n  const options = {\n    attributes: {\n      ...NestInstrumentation.COMMON_ATTRIBUTES,\n      [AttributeNames.VERSION]: moduleVersion,\n      [AttributeNames.TYPE]: NestType.REQUEST_HANDLER,\n      [AttributeNames.CALLBACK]: handler.name,\n    },\n  };\n  const wrappedHandler = function (this: RouterExecutionContext) {\n    const span = tracer.startSpan(spanName, options);\n    const spanContext = api.trace.setSpan(api.context.active(), span);\n\n    return api.context.with(spanContext, async () => {\n      try {\n        return await handler.apply(this, arguments);\n      } catch (e: any) {\n        throw addError(span, e);\n      } finally {\n        span.end();\n      }\n    });\n  };\n\n  if (handler.name) {\n    Object.defineProperty(wrappedHandler, 'name', { value: handler.name });\n  }\n\n  // Get the current metadata and set onto the wrapper to ensure other decorators ( ie: NestJS EventPattern / RolesGuard )\n  // won't be affected by the use of this instrumentation\n  Reflect.getMetadataKeys(handler).forEach(metadataKey => {\n    Reflect.defineMetadata(\n      metadataKey,\n      Reflect.getMetadata(metadataKey, handler),\n      wrappedHandler\n    );\n  });\n  return wrappedHandler;\n}\n\nconst addError = (span: api.Span, error: Error) => {\n  span.recordException(error);\n  span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n  return error;\n};\n"],"mappings":";;;;;;;;;AAyBA,MAAM,oBAAoB,CAAC,aAAa;AAExC,IAAa,sBAAb,MAAa,4BAA4BA,+BAAAA,oBAAoB;CAC3D,OAAgB,YAAY;CAC5B,OAAgB,oBAAoB,EAClC,WAAW,oBAAoB,UACjC;CAEA,YAAY,SAAgC,CAAC,GAAG;EAC9C,MAAMC,gBAAAA,cAAcC,gBAAAA,iBAAiB,MAAM;CAC7C;CAEA,OAAO;EACL,MAAM,SAAS,IAAIC,+BAAAA,oCACjB,oBAAoB,WACpB,iBACF;EAEA,OAAO,MAAM,KACX,KAAK,kCAAkC,iBAAiB,GACxD,KAAK,6CAA6C,iBAAiB,CACrE;EAEA,OAAO;CACT;CAEA,kCAAkC,UAAoB;EACpD,OAAO,IAAIC,+BAAAA,8BACT,gCACA,WACC,mBAAwB,kBAA2B;GAClD,KAAK,cACH,kBAAkB,kBAAkB,WACpC,UACA,4BAA4B,KAAK,QAAQ,aAAa,CACxD;GACA,OAAO;EACT,IACC,sBAA2B;GAC1B,KAAK,QAAQ,kBAAkB,kBAAkB,WAAW,QAAQ;EACtE,CACF;CACF;CAEA,6CAA6C,UAAoB;EAC/D,OAAO,IAAIA,+BAAAA,8BACT,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