@sentry/node 10.54.0 → 10.56.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.
Files changed (166) hide show
  1. package/build/cjs/integrations/node-fetch/vendored/undici.js +2 -3
  2. package/build/cjs/integrations/node-fetch/vendored/undici.js.map +1 -1
  3. package/build/cjs/integrations/tracing/InstrumentationNodeModuleFile.js +15 -0
  4. package/build/cjs/integrations/tracing/InstrumentationNodeModuleFile.js.map +1 -0
  5. package/build/cjs/integrations/tracing/amqplib/vendored/amqplib.js +9 -9
  6. package/build/cjs/integrations/tracing/amqplib/vendored/amqplib.js.map +1 -1
  7. package/build/cjs/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
  8. package/build/cjs/integrations/tracing/anthropic-ai/index.js.map +1 -1
  9. package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js +3 -5
  10. package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
  11. package/build/cjs/integrations/tracing/express.js +3 -5
  12. package/build/cjs/integrations/tracing/express.js.map +1 -1
  13. package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js +10 -11
  14. package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
  15. package/build/cjs/integrations/tracing/fastify/vendored/instrumentation.js +3 -4
  16. package/build/cjs/integrations/tracing/fastify/vendored/instrumentation.js.map +1 -1
  17. package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js +2 -1
  18. package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
  19. package/build/cjs/integrations/tracing/firebase/otel/patches/functions.js +2 -1
  20. package/build/cjs/integrations/tracing/firebase/otel/patches/functions.js.map +1 -1
  21. package/build/cjs/integrations/tracing/google-genai/instrumentation.js +2 -1
  22. package/build/cjs/integrations/tracing/google-genai/instrumentation.js.map +1 -1
  23. package/build/cjs/integrations/tracing/graphql/vendored/instrumentation.js +4 -3
  24. package/build/cjs/integrations/tracing/graphql/vendored/instrumentation.js.map +1 -1
  25. package/build/cjs/integrations/tracing/hapi/vendored/instrumentation.js +2 -5
  26. package/build/cjs/integrations/tracing/hapi/vendored/instrumentation.js.map +1 -1
  27. package/build/cjs/integrations/tracing/hono/index.js.map +1 -1
  28. package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js +3 -2
  29. package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
  30. package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js +3 -4
  31. package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
  32. package/build/cjs/integrations/tracing/langchain/instrumentation.js +3 -2
  33. package/build/cjs/integrations/tracing/langchain/instrumentation.js.map +1 -1
  34. package/build/cjs/integrations/tracing/langgraph/index.js.map +1 -1
  35. package/build/cjs/integrations/tracing/langgraph/instrumentation.js +7 -5
  36. package/build/cjs/integrations/tracing/langgraph/instrumentation.js.map +1 -1
  37. package/build/cjs/integrations/tracing/mongo/vendored/instrumentation.js +7 -6
  38. package/build/cjs/integrations/tracing/mongo/vendored/instrumentation.js.map +1 -1
  39. package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js +3 -2
  40. package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
  41. package/build/cjs/integrations/tracing/openai/index.js.map +1 -1
  42. package/build/cjs/integrations/tracing/postgres/vendored/instrumentation.js +5 -5
  43. package/build/cjs/integrations/tracing/postgres/vendored/instrumentation.js.map +1 -1
  44. package/build/cjs/integrations/tracing/postgresjs.js +2 -1
  45. package/build/cjs/integrations/tracing/postgresjs.js.map +1 -1
  46. package/build/cjs/integrations/tracing/redis/index.js +3 -2
  47. package/build/cjs/integrations/tracing/redis/index.js.map +1 -1
  48. package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js +1 -1
  49. package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
  50. package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js +4 -3
  51. package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
  52. package/build/cjs/integrations/tracing/vercelai/instrumentation.js +6 -5
  53. package/build/cjs/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  54. package/build/cjs/utils/setHttpServerSpanRouteAttribute.js +21 -0
  55. package/build/cjs/utils/setHttpServerSpanRouteAttribute.js.map +1 -0
  56. package/build/esm/integrations/node-fetch/vendored/undici.js +3 -4
  57. package/build/esm/integrations/node-fetch/vendored/undici.js.map +1 -1
  58. package/build/esm/integrations/tracing/InstrumentationNodeModuleFile.js +13 -0
  59. package/build/esm/integrations/tracing/InstrumentationNodeModuleFile.js.map +1 -0
  60. package/build/esm/integrations/tracing/amqplib/vendored/amqplib.js +7 -7
  61. package/build/esm/integrations/tracing/amqplib/vendored/amqplib.js.map +1 -1
  62. package/build/esm/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
  63. package/build/esm/integrations/tracing/anthropic-ai/index.js.map +1 -1
  64. package/build/esm/integrations/tracing/connect/vendored/instrumentation.js +3 -5
  65. package/build/esm/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
  66. package/build/esm/integrations/tracing/express.js +3 -5
  67. package/build/esm/integrations/tracing/express.js.map +1 -1
  68. package/build/esm/integrations/tracing/fastify/v3/instrumentation.js +3 -4
  69. package/build/esm/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
  70. package/build/esm/integrations/tracing/fastify/vendored/instrumentation.js +3 -4
  71. package/build/esm/integrations/tracing/fastify/vendored/instrumentation.js.map +1 -1
  72. package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js +2 -1
  73. package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
  74. package/build/esm/integrations/tracing/firebase/otel/patches/functions.js +2 -1
  75. package/build/esm/integrations/tracing/firebase/otel/patches/functions.js.map +1 -1
  76. package/build/esm/integrations/tracing/google-genai/instrumentation.js +2 -1
  77. package/build/esm/integrations/tracing/google-genai/instrumentation.js.map +1 -1
  78. package/build/esm/integrations/tracing/graphql/vendored/instrumentation.js +2 -1
  79. package/build/esm/integrations/tracing/graphql/vendored/instrumentation.js.map +1 -1
  80. package/build/esm/integrations/tracing/hapi/vendored/instrumentation.js +2 -5
  81. package/build/esm/integrations/tracing/hapi/vendored/instrumentation.js.map +1 -1
  82. package/build/esm/integrations/tracing/hono/index.js.map +1 -1
  83. package/build/esm/integrations/tracing/knex/vendored/instrumentation.js +2 -1
  84. package/build/esm/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
  85. package/build/esm/integrations/tracing/koa/vendored/instrumentation.js +3 -4
  86. package/build/esm/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
  87. package/build/esm/integrations/tracing/langchain/instrumentation.js +2 -1
  88. package/build/esm/integrations/tracing/langchain/instrumentation.js.map +1 -1
  89. package/build/esm/integrations/tracing/langgraph/index.js.map +1 -1
  90. package/build/esm/integrations/tracing/langgraph/instrumentation.js +5 -3
  91. package/build/esm/integrations/tracing/langgraph/instrumentation.js.map +1 -1
  92. package/build/esm/integrations/tracing/mongo/vendored/instrumentation.js +2 -1
  93. package/build/esm/integrations/tracing/mongo/vendored/instrumentation.js.map +1 -1
  94. package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js +2 -1
  95. package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
  96. package/build/esm/integrations/tracing/openai/index.js.map +1 -1
  97. package/build/esm/integrations/tracing/postgres/vendored/instrumentation.js +5 -5
  98. package/build/esm/integrations/tracing/postgres/vendored/instrumentation.js.map +1 -1
  99. package/build/esm/integrations/tracing/postgresjs.js +2 -1
  100. package/build/esm/integrations/tracing/postgresjs.js.map +1 -1
  101. package/build/esm/integrations/tracing/redis/index.js +3 -2
  102. package/build/esm/integrations/tracing/redis/index.js.map +1 -1
  103. package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js +1 -1
  104. package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
  105. package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js +2 -1
  106. package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
  107. package/build/esm/integrations/tracing/vercelai/instrumentation.js +6 -5
  108. package/build/esm/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  109. package/build/esm/package.json +1 -1
  110. package/build/esm/utils/setHttpServerSpanRouteAttribute.js +19 -0
  111. package/build/esm/utils/setHttpServerSpanRouteAttribute.js.map +1 -0
  112. package/build/types/integrations/node-fetch/vendored/undici.d.ts.map +1 -1
  113. package/build/types/integrations/tracing/InstrumentationNodeModuleFile.d.ts +9 -0
  114. package/build/types/integrations/tracing/InstrumentationNodeModuleFile.d.ts.map +1 -0
  115. package/build/types/integrations/tracing/amqplib/vendored/amqplib.d.ts.map +1 -1
  116. package/build/types/integrations/tracing/amqplib/vendored/utils.d.ts +2 -2
  117. package/build/types/integrations/tracing/amqplib/vendored/utils.d.ts.map +1 -1
  118. package/build/types/integrations/tracing/anthropic-ai/index.d.ts +7 -7
  119. package/build/types/integrations/tracing/connect/vendored/instrumentation.d.ts.map +1 -1
  120. package/build/types/integrations/tracing/express.d.ts.map +1 -1
  121. package/build/types/integrations/tracing/fastify/v3/instrumentation.d.ts.map +1 -1
  122. package/build/types/integrations/tracing/fastify/vendored/instrumentation.d.ts.map +1 -1
  123. package/build/types/integrations/tracing/firebase/otel/patches/firestore.d.ts.map +1 -1
  124. package/build/types/integrations/tracing/firebase/otel/patches/functions.d.ts.map +1 -1
  125. package/build/types/integrations/tracing/google-genai/instrumentation.d.ts.map +1 -1
  126. package/build/types/integrations/tracing/graphql/vendored/instrumentation.d.ts.map +1 -1
  127. package/build/types/integrations/tracing/hapi/vendored/instrumentation.d.ts.map +1 -1
  128. package/build/types/integrations/tracing/hono/index.d.ts +6 -0
  129. package/build/types/integrations/tracing/hono/index.d.ts.map +1 -1
  130. package/build/types/integrations/tracing/knex/vendored/instrumentation.d.ts.map +1 -1
  131. package/build/types/integrations/tracing/koa/vendored/instrumentation.d.ts.map +1 -1
  132. package/build/types/integrations/tracing/langchain/instrumentation.d.ts.map +1 -1
  133. package/build/types/integrations/tracing/langgraph/index.d.ts +7 -7
  134. package/build/types/integrations/tracing/langgraph/instrumentation.d.ts.map +1 -1
  135. package/build/types/integrations/tracing/mongo/vendored/instrumentation.d.ts.map +1 -1
  136. package/build/types/integrations/tracing/mysql2/vendored/instrumentation.d.ts.map +1 -1
  137. package/build/types/integrations/tracing/openai/index.d.ts +7 -7
  138. package/build/types/integrations/tracing/postgres/vendored/instrumentation.d.ts.map +1 -1
  139. package/build/types/integrations/tracing/postgresjs.d.ts.map +1 -1
  140. package/build/types/integrations/tracing/redis/index.d.ts +4 -1
  141. package/build/types/integrations/tracing/redis/index.d.ts.map +1 -1
  142. package/build/types/integrations/tracing/redis/vendored/redis-instrumentation.d.ts.map +1 -1
  143. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts +2 -2
  144. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts.map +1 -1
  145. package/build/types/integrations/tracing/vercelai/types.d.ts +6 -4
  146. package/build/types/integrations/tracing/vercelai/types.d.ts.map +1 -1
  147. package/build/types/utils/setHttpServerSpanRouteAttribute.d.ts +9 -0
  148. package/build/types/utils/setHttpServerSpanRouteAttribute.d.ts.map +1 -0
  149. package/build/types-ts3.8/integrations/tracing/InstrumentationNodeModuleFile.d.ts +9 -0
  150. package/build/types-ts3.8/integrations/tracing/amqplib/vendored/utils.d.ts +2 -2
  151. package/build/types-ts3.8/integrations/tracing/anthropic-ai/index.d.ts +7 -7
  152. package/build/types-ts3.8/integrations/tracing/hono/index.d.ts +6 -0
  153. package/build/types-ts3.8/integrations/tracing/langgraph/index.d.ts +7 -7
  154. package/build/types-ts3.8/integrations/tracing/openai/index.d.ts +7 -7
  155. package/build/types-ts3.8/integrations/tracing/redis/index.d.ts +4 -1
  156. package/build/types-ts3.8/integrations/tracing/vercelai/instrumentation.d.ts +2 -2
  157. package/build/types-ts3.8/integrations/tracing/vercelai/types.d.ts +6 -4
  158. package/build/types-ts3.8/utils/setHttpServerSpanRouteAttribute.d.ts +9 -0
  159. package/package.json +5 -4
  160. package/build/cjs/integrations/tracing/redis/redis-dc-subscriber.js +0 -151
  161. package/build/cjs/integrations/tracing/redis/redis-dc-subscriber.js.map +0 -1
  162. package/build/esm/integrations/tracing/redis/redis-dc-subscriber.js +0 -149
  163. package/build/esm/integrations/tracing/redis/redis-dc-subscriber.js.map +0 -1
  164. package/build/types/integrations/tracing/redis/redis-dc-subscriber.d.ts +0 -17
  165. package/build/types/integrations/tracing/redis/redis-dc-subscriber.d.ts.map +0 -1
  166. package/build/types-ts3.8/integrations/tracing/redis/redis-dc-subscriber.d.ts +0 -17
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/graphql/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-graphql\n * - Upstream version: @opentelemetry/instrumentation-graphql@0.66.0\n * - Types from `graphql` package inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments\n */\n/* eslint-disable */\n\nimport { context, trace } from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n DefinitionNode,\n DocumentNode,\n ExecutionArgs,\n ExecutionResult,\n GraphQLError,\n GraphQLFieldResolver,\n GraphQLSchema,\n GraphQLTypeResolver,\n OperationDefinitionNode,\n ParseOptions,\n PromiseOrValue,\n Source,\n TypeInfo,\n ValidationRule,\n} from './graphql-types';\nimport type { Maybe } from './graphql-types';\nimport { SpanNames } from './enum';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { OTEL_GRAPHQL_DATA_SYMBOL } from './symbols';\n\nimport {\n executeFunctionWithObj,\n executeArgumentsArray,\n executeType,\n parseType,\n validateType,\n OtelExecutionArgs,\n ObjectWithGraphQLData,\n OPERATION_NOT_SUPPORTED,\n} from './internal-types';\nimport {\n addInputVariableAttributes,\n addSpanSource,\n endSpan,\n getOperation,\n isPromise,\n wrapFieldResolver,\n wrapFields,\n} from './utils';\n\nimport { SDK_VERSION } from '@sentry/core';\nimport * as api from '@opentelemetry/api';\nimport { GraphQLInstrumentationConfig, GraphQLInstrumentationParsedConfig } from './types';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-graphql';\n\nconst DEFAULT_CONFIG: GraphQLInstrumentationParsedConfig = {\n mergeItems: false,\n depth: -1,\n allowValues: false,\n ignoreResolveSpans: false,\n};\n\nconst supportedVersions = ['>=14.0.0 <17'];\n\nexport class GraphQLInstrumentation extends InstrumentationBase<GraphQLInstrumentationParsedConfig> {\n constructor(config: GraphQLInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, { ...DEFAULT_CONFIG, ...config });\n }\n\n override setConfig(config: GraphQLInstrumentationConfig = {}) {\n super.setConfig({ ...DEFAULT_CONFIG, ...config });\n }\n\n protected init() {\n const module = new InstrumentationNodeModuleDefinition('graphql', supportedVersions);\n module.files.push(this._addPatchingExecute());\n module.files.push(this._addPatchingParser());\n module.files.push(this._addPatchingValidate());\n\n return module;\n }\n\n private _addPatchingExecute(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/execution/execute.js',\n supportedVersions,\n // cannot make it work with appropriate type as execute function has 2\n //types and/cannot import function but only types\n (moduleExports: any) => {\n if (isWrapped(moduleExports.execute)) {\n this._unwrap(moduleExports, 'execute');\n }\n this._wrap(moduleExports, 'execute', this._patchExecute(moduleExports.defaultFieldResolver));\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'execute');\n }\n },\n );\n }\n\n private _addPatchingParser(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/language/parser.js',\n supportedVersions,\n (moduleExports: { parse: parseType; [key: string]: any }) => {\n if (isWrapped(moduleExports.parse)) {\n this._unwrap(moduleExports, 'parse');\n }\n this._wrap(moduleExports, 'parse', this._patchParse());\n return moduleExports;\n },\n (moduleExports: { parse: parseType; [key: string]: any }) => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'parse');\n }\n },\n );\n }\n\n private _addPatchingValidate(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/validation/validate.js',\n supportedVersions,\n moduleExports => {\n if (isWrapped(moduleExports.validate)) {\n this._unwrap(moduleExports, 'validate');\n }\n this._wrap(moduleExports, 'validate', this._patchValidate());\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'validate');\n }\n },\n );\n }\n\n private _patchExecute(defaultFieldResolved: GraphQLFieldResolver<any, any>): (original: executeType) => executeType {\n const instrumentation = this;\n return function execute(original) {\n return function patchExecute(this: executeType): PromiseOrValue<ExecutionResult> {\n let processedArgs: OtelExecutionArgs;\n\n // case when apollo server is used for example\n if (arguments.length >= 2) {\n const args = arguments as unknown as executeArgumentsArray;\n processedArgs = instrumentation._wrapExecuteArgs(\n args[0],\n args[1],\n args[2],\n args[3],\n args[4],\n args[5],\n args[6],\n args[7],\n defaultFieldResolved,\n );\n } else {\n const args = arguments[0] as ExecutionArgs;\n processedArgs = instrumentation._wrapExecuteArgs(\n args.schema,\n args.document,\n args.rootValue,\n args.contextValue,\n args.variableValues,\n args.operationName,\n args.fieldResolver,\n args.typeResolver,\n defaultFieldResolved,\n );\n }\n\n const operation = getOperation(processedArgs.document, processedArgs.operationName);\n\n const span = instrumentation._createExecuteSpan(operation, processedArgs);\n\n processedArgs.contextValue[OTEL_GRAPHQL_DATA_SYMBOL] = {\n source: processedArgs.document\n ? processedArgs.document || (processedArgs.document as ObjectWithGraphQLData)[OTEL_GRAPHQL_DATA_SYMBOL]\n : undefined,\n span,\n fields: {},\n };\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<PromiseOrValue<ExecutionResult>>(\n () => {\n return (original as executeFunctionWithObj).apply(this, [processedArgs]);\n },\n (err, result) => {\n instrumentation._handleExecutionResult(span, err, result);\n },\n );\n });\n };\n };\n }\n\n private _handleExecutionResult(span: api.Span, err?: Error, result?: PromiseOrValue<ExecutionResult>) {\n const config = this.getConfig();\n if (result === undefined || err) {\n endSpan(span, err);\n return;\n }\n\n if (isPromise(result)) {\n (result as Promise<ExecutionResult>).then(\n resultData => {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, resultData);\n },\n error => {\n endSpan(span, error);\n },\n );\n } else {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, result as ExecutionResult);\n }\n }\n\n private _executeResponseHook(span: api.Span, result: ExecutionResult) {\n const { responseHook } = this.getConfig();\n if (!responseHook) {\n return;\n }\n\n safeExecuteInTheMiddle(\n () => {\n responseHook(span, result);\n },\n err => {\n if (err) {\n this._diag.error('Error running response hook', err);\n }\n\n endSpan(span, undefined);\n },\n true,\n );\n }\n\n private _patchParse(): (original: parseType) => parseType {\n const instrumentation = this;\n return function parse(original) {\n return function patchParse(this: parseType, source: string | Source, options?: ParseOptions): DocumentNode {\n return instrumentation._parse(this, original, source, options);\n };\n };\n }\n\n private _patchValidate(): (original: validateType) => validateType {\n const instrumentation = this;\n return function validate(original: validateType) {\n return function patchValidate(\n this: validateType,\n schema: GraphQLSchema,\n documentAST: DocumentNode,\n rules?: ReadonlyArray<ValidationRule>,\n options?: { maxErrors?: number },\n typeInfo?: TypeInfo,\n ): ReadonlyArray<GraphQLError> {\n return instrumentation._validate(this, original, schema, documentAST, rules, typeInfo, options);\n };\n };\n }\n\n private _parse(obj: parseType, original: parseType, source: string | Source, options?: ParseOptions): DocumentNode {\n const config = this.getConfig();\n const span = this.tracer.startSpan(SpanNames.PARSE);\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<DocumentNode & ObjectWithGraphQLData>(\n () => {\n return original.call(obj, source, options);\n },\n (err, result) => {\n if (result) {\n const operation = getOperation(result);\n if (!operation) {\n span.updateName(SpanNames.SCHEMA_PARSE);\n } else if (result.loc) {\n addSpanSource(span, result.loc, config.allowValues);\n }\n }\n endSpan(span, err);\n },\n );\n });\n }\n\n private _validate(\n obj: validateType,\n original: validateType,\n schema: GraphQLSchema,\n documentAST: DocumentNode,\n rules?: ReadonlyArray<ValidationRule>,\n typeInfo?: TypeInfo,\n options?: { maxErrors?: number },\n ): ReadonlyArray<GraphQLError> {\n const span = this.tracer.startSpan(SpanNames.VALIDATE, {});\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<ReadonlyArray<GraphQLError>>(\n () => {\n return original.call(obj, schema, documentAST, rules, options, typeInfo);\n },\n (err, errors) => {\n if (!documentAST.loc) {\n span.updateName(SpanNames.SCHEMA_VALIDATE);\n }\n if (errors && errors.length) {\n span.recordException({\n name: AttributeNames.ERROR_VALIDATION_NAME,\n message: JSON.stringify(errors),\n });\n }\n endSpan(span, err);\n },\n );\n });\n }\n\n private _createExecuteSpan(operation: DefinitionNode | undefined, processedArgs: ExecutionArgs): api.Span {\n const config = this.getConfig();\n\n const span = this.tracer.startSpan(SpanNames.EXECUTE, {});\n if (operation) {\n const { operation: operationType, name: nameNode } = operation as OperationDefinitionNode;\n\n span.setAttribute(AttributeNames.OPERATION_TYPE, operationType);\n\n const operationName = nameNode?.value;\n\n // https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/instrumentation/graphql/\n // > The span name MUST be of the format <graphql.operation.type> <graphql.operation.name> provided that graphql.operation.type and graphql.operation.name are available.\n // > If graphql.operation.name is not available, the span SHOULD be named <graphql.operation.type>.\n if (operationName) {\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n span.updateName(`${operationType} ${operationName}`);\n } else {\n span.updateName(operationType);\n }\n } else {\n let operationName = ' ';\n if (processedArgs.operationName) {\n operationName = ` \"${processedArgs.operationName}\" `;\n }\n operationName = OPERATION_NOT_SUPPORTED.replace('$operationName$', operationName);\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n }\n\n if (processedArgs.document?.loc) {\n addSpanSource(span, processedArgs.document.loc, config.allowValues);\n }\n\n if (processedArgs.variableValues && config.allowValues) {\n addInputVariableAttributes(span, processedArgs.variableValues);\n }\n\n return span;\n }\n\n private _wrapExecuteArgs(\n schema: GraphQLSchema,\n document: DocumentNode,\n rootValue: any,\n contextValue: any,\n variableValues: Maybe<{ [key: string]: any }>,\n operationName: Maybe<string>,\n fieldResolver: Maybe<GraphQLFieldResolver<any, any>>,\n typeResolver: Maybe<GraphQLTypeResolver<any, any>>,\n defaultFieldResolved: GraphQLFieldResolver<any, any>,\n ): OtelExecutionArgs {\n if (!contextValue) {\n contextValue = {};\n }\n\n if (contextValue[OTEL_GRAPHQL_DATA_SYMBOL] || this.getConfig().ignoreResolveSpans) {\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n };\n }\n\n const isUsingDefaultResolver = fieldResolver == null;\n // follows graphql implementation here:\n // https://github.com/graphql/graphql-js/blob/0b7daed9811731362c71900e12e5ea0d1ecc7f1f/src/execution/execute.ts#L494\n const fieldResolverForExecute = fieldResolver ?? defaultFieldResolved;\n fieldResolver = wrapFieldResolver(\n this.tracer,\n () => this.getConfig(),\n fieldResolverForExecute,\n isUsingDefaultResolver,\n );\n\n if (schema) {\n wrapFields(schema.getQueryType() as any, this.tracer, () => this.getConfig());\n wrapFields(schema.getMutationType() as any, this.tracer, () => this.getConfig());\n }\n\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AA4EA,MAAM,YAAA,GAAe,iCAAA;AAErB,MAAM,cAAA,GAAqD;AAAA,EACzD,UAAA,EAAY,KAAA;AAAA,EACZ,KAAA,EAAO,EAAA;AAAA,EACP,WAAA,EAAa,KAAA;AAAA,EACb,kBAAA,EAAoB;AACtB,CAAA;AAEA,MAAM,iBAAA,GAAoB,CAAC,cAAc,CAAA;AAElC,MAAM,+BAA+B,mBAAA,CAAwD;AAAA,EAClG,WAAA,CAAY,MAAA,GAAuC,EAAC,EAAG;AACrD,IAAA,KAAA,CAAM,cAAc,WAAA,EAAa,EAAE,GAAG,cAAA,EAAgB,GAAG,QAAQ,CAAA;AAAA,EACnE;AAAA,EAES,SAAA,CAAU,MAAA,GAAuC,EAAC,EAAG;AAC5D,IAAA,KAAA,CAAM,UAAU,EAAE,GAAG,cAAA,EAAgB,GAAG,QAAQ,CAAA;AAAA,EAClD;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,MAAM,MAAA,GAAS,IAAI,mCAAA,CAAoC,SAAA,EAAW,iBAAiB,CAAA;AACnF,IAAA,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,mBAAA,EAAqB,CAAA;AAC5C,IAAA,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,kBAAA,EAAoB,CAAA;AAC3C,IAAA,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,oBAAA,EAAsB,CAAA;AAE7C,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEQ,mBAAA,GAAqD;AAC3D,IAAA,OAAO,IAAI,6BAAA;AAAA,MACT,8BAAA;AAAA,MACA,iBAAA;AAA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,YAAA,EACA,oBAAA,EACmB;AACnB,IAAA,IAAI,CAAC,YAAA,EAAc;AACjB,MAAA,YAAA,GAAe,EAAC;AAAA,IAClB;AAEA,IAAA,IAAI,aAAa,wBAAwB,CAAA,IAAK,IAAA,CAAK,SAAA,GAAY,kBAAA,EAAoB;AACjF,MAAA,OAAO;AAAA,QACL,MAAA;AAAA,QACA,QAAA;AAAA,QACA,SAAA;AAAA,QACA,YAAA;AAAA,QACA,cAAA;AAAA,QACA,aAAA;AAAA,QACA,aAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,MAAM,yBAAyB,aAAA,IAAiB,IAAA;AAGhD,IAAA,MAAM,0BAA0B,aAAA,IAAiB,oBAAA;AACjD,IAAA,aAAA,GAAgB,iBAAA;AAAA,MACd,IAAA,CAAK,MAAA;AAAA,MACL,MAAM,KAAK,SAAA,EAAU;AAAA,MACrB,uBAAA;AAAA,MACA;AAAA,KACF;AAEA,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,UAAA,CAAW,MAAA,CAAO,cAAa,EAAU,IAAA,CAAK,QAAQ,MAAM,IAAA,CAAK,WAAW,CAAA;AAC5E,MAAA,UAAA,CAAW,MAAA,CAAO,iBAAgB,EAAU,IAAA,CAAK,QAAQ,MAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IACjF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA;AAAA,MACA,QAAA;AAAA,MACA,SAAA;AAAA,MACA,YAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,aAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/graphql/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-graphql\n * - Upstream version: @opentelemetry/instrumentation-graphql@0.66.0\n * - Types from `graphql` package inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments\n */\n/* eslint-disable */\n\nimport { context, trace } from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from '../../InstrumentationNodeModuleFile';\nimport type {\n DefinitionNode,\n DocumentNode,\n ExecutionArgs,\n ExecutionResult,\n GraphQLError,\n GraphQLFieldResolver,\n GraphQLSchema,\n GraphQLTypeResolver,\n OperationDefinitionNode,\n ParseOptions,\n PromiseOrValue,\n Source,\n TypeInfo,\n ValidationRule,\n} from './graphql-types';\nimport type { Maybe } from './graphql-types';\nimport { SpanNames } from './enum';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { OTEL_GRAPHQL_DATA_SYMBOL } from './symbols';\n\nimport {\n executeFunctionWithObj,\n executeArgumentsArray,\n executeType,\n parseType,\n validateType,\n OtelExecutionArgs,\n ObjectWithGraphQLData,\n OPERATION_NOT_SUPPORTED,\n} from './internal-types';\nimport {\n addInputVariableAttributes,\n addSpanSource,\n endSpan,\n getOperation,\n isPromise,\n wrapFieldResolver,\n wrapFields,\n} from './utils';\n\nimport { SDK_VERSION } from '@sentry/core';\nimport * as api from '@opentelemetry/api';\nimport { GraphQLInstrumentationConfig, GraphQLInstrumentationParsedConfig } from './types';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-graphql';\n\nconst DEFAULT_CONFIG: GraphQLInstrumentationParsedConfig = {\n mergeItems: false,\n depth: -1,\n allowValues: false,\n ignoreResolveSpans: false,\n};\n\nconst supportedVersions = ['>=14.0.0 <17'];\n\nexport class GraphQLInstrumentation extends InstrumentationBase<GraphQLInstrumentationParsedConfig> {\n constructor(config: GraphQLInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, { ...DEFAULT_CONFIG, ...config });\n }\n\n override setConfig(config: GraphQLInstrumentationConfig = {}) {\n super.setConfig({ ...DEFAULT_CONFIG, ...config });\n }\n\n protected init() {\n const module = new InstrumentationNodeModuleDefinition('graphql', supportedVersions);\n module.files.push(this._addPatchingExecute());\n module.files.push(this._addPatchingParser());\n module.files.push(this._addPatchingValidate());\n\n return module;\n }\n\n private _addPatchingExecute(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/execution/execute.js',\n supportedVersions,\n // cannot make it work with appropriate type as execute function has 2\n //types and/cannot import function but only types\n (moduleExports: any) => {\n if (isWrapped(moduleExports.execute)) {\n this._unwrap(moduleExports, 'execute');\n }\n this._wrap(moduleExports, 'execute', this._patchExecute(moduleExports.defaultFieldResolver));\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'execute');\n }\n },\n );\n }\n\n private _addPatchingParser(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/language/parser.js',\n supportedVersions,\n (moduleExports: { parse: parseType; [key: string]: any }) => {\n if (isWrapped(moduleExports.parse)) {\n this._unwrap(moduleExports, 'parse');\n }\n this._wrap(moduleExports, 'parse', this._patchParse());\n return moduleExports;\n },\n (moduleExports: { parse: parseType; [key: string]: any }) => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'parse');\n }\n },\n );\n }\n\n private _addPatchingValidate(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/validation/validate.js',\n supportedVersions,\n moduleExports => {\n if (isWrapped(moduleExports.validate)) {\n this._unwrap(moduleExports, 'validate');\n }\n this._wrap(moduleExports, 'validate', this._patchValidate());\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'validate');\n }\n },\n );\n }\n\n private _patchExecute(defaultFieldResolved: GraphQLFieldResolver<any, any>): (original: executeType) => executeType {\n const instrumentation = this;\n return function execute(original) {\n return function patchExecute(this: executeType): PromiseOrValue<ExecutionResult> {\n let processedArgs: OtelExecutionArgs;\n\n // case when apollo server is used for example\n if (arguments.length >= 2) {\n const args = arguments as unknown as executeArgumentsArray;\n processedArgs = instrumentation._wrapExecuteArgs(\n args[0],\n args[1],\n args[2],\n args[3],\n args[4],\n args[5],\n args[6],\n args[7],\n defaultFieldResolved,\n );\n } else {\n const args = arguments[0] as ExecutionArgs;\n processedArgs = instrumentation._wrapExecuteArgs(\n args.schema,\n args.document,\n args.rootValue,\n args.contextValue,\n args.variableValues,\n args.operationName,\n args.fieldResolver,\n args.typeResolver,\n defaultFieldResolved,\n );\n }\n\n const operation = getOperation(processedArgs.document, processedArgs.operationName);\n\n const span = instrumentation._createExecuteSpan(operation, processedArgs);\n\n processedArgs.contextValue[OTEL_GRAPHQL_DATA_SYMBOL] = {\n source: processedArgs.document\n ? processedArgs.document || (processedArgs.document as ObjectWithGraphQLData)[OTEL_GRAPHQL_DATA_SYMBOL]\n : undefined,\n span,\n fields: {},\n };\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<PromiseOrValue<ExecutionResult>>(\n () => {\n return (original as executeFunctionWithObj).apply(this, [processedArgs]);\n },\n (err, result) => {\n instrumentation._handleExecutionResult(span, err, result);\n },\n );\n });\n };\n };\n }\n\n private _handleExecutionResult(span: api.Span, err?: Error, result?: PromiseOrValue<ExecutionResult>) {\n const config = this.getConfig();\n if (result === undefined || err) {\n endSpan(span, err);\n return;\n }\n\n if (isPromise(result)) {\n (result as Promise<ExecutionResult>).then(\n resultData => {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, resultData);\n },\n error => {\n endSpan(span, error);\n },\n );\n } else {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, result as ExecutionResult);\n }\n }\n\n private _executeResponseHook(span: api.Span, result: ExecutionResult) {\n const { responseHook } = this.getConfig();\n if (!responseHook) {\n return;\n }\n\n safeExecuteInTheMiddle(\n () => {\n responseHook(span, result);\n },\n err => {\n if (err) {\n this._diag.error('Error running response hook', err);\n }\n\n endSpan(span, undefined);\n },\n true,\n );\n }\n\n private _patchParse(): (original: parseType) => parseType {\n const instrumentation = this;\n return function parse(original) {\n return function patchParse(this: parseType, source: string | Source, options?: ParseOptions): DocumentNode {\n return instrumentation._parse(this, original, source, options);\n };\n };\n }\n\n private _patchValidate(): (original: validateType) => validateType {\n const instrumentation = this;\n return function validate(original: validateType) {\n return function patchValidate(\n this: validateType,\n schema: GraphQLSchema,\n documentAST: DocumentNode,\n rules?: ReadonlyArray<ValidationRule>,\n options?: { maxErrors?: number },\n typeInfo?: TypeInfo,\n ): ReadonlyArray<GraphQLError> {\n return instrumentation._validate(this, original, schema, documentAST, rules, typeInfo, options);\n };\n };\n }\n\n private _parse(obj: parseType, original: parseType, source: string | Source, options?: ParseOptions): DocumentNode {\n const config = this.getConfig();\n const span = this.tracer.startSpan(SpanNames.PARSE);\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<DocumentNode & ObjectWithGraphQLData>(\n () => {\n return original.call(obj, source, options);\n },\n (err, result) => {\n if (result) {\n const operation = getOperation(result);\n if (!operation) {\n span.updateName(SpanNames.SCHEMA_PARSE);\n } else if (result.loc) {\n addSpanSource(span, result.loc, config.allowValues);\n }\n }\n endSpan(span, err);\n },\n );\n });\n }\n\n private _validate(\n obj: validateType,\n original: validateType,\n schema: GraphQLSchema,\n documentAST: DocumentNode,\n rules?: ReadonlyArray<ValidationRule>,\n typeInfo?: TypeInfo,\n options?: { maxErrors?: number },\n ): ReadonlyArray<GraphQLError> {\n const span = this.tracer.startSpan(SpanNames.VALIDATE, {});\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<ReadonlyArray<GraphQLError>>(\n () => {\n return original.call(obj, schema, documentAST, rules, options, typeInfo);\n },\n (err, errors) => {\n if (!documentAST.loc) {\n span.updateName(SpanNames.SCHEMA_VALIDATE);\n }\n if (errors && errors.length) {\n span.recordException({\n name: AttributeNames.ERROR_VALIDATION_NAME,\n message: JSON.stringify(errors),\n });\n }\n endSpan(span, err);\n },\n );\n });\n }\n\n private _createExecuteSpan(operation: DefinitionNode | undefined, processedArgs: ExecutionArgs): api.Span {\n const config = this.getConfig();\n\n const span = this.tracer.startSpan(SpanNames.EXECUTE, {});\n if (operation) {\n const { operation: operationType, name: nameNode } = operation as OperationDefinitionNode;\n\n span.setAttribute(AttributeNames.OPERATION_TYPE, operationType);\n\n const operationName = nameNode?.value;\n\n // https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/instrumentation/graphql/\n // > The span name MUST be of the format <graphql.operation.type> <graphql.operation.name> provided that graphql.operation.type and graphql.operation.name are available.\n // > If graphql.operation.name is not available, the span SHOULD be named <graphql.operation.type>.\n if (operationName) {\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n span.updateName(`${operationType} ${operationName}`);\n } else {\n span.updateName(operationType);\n }\n } else {\n let operationName = ' ';\n if (processedArgs.operationName) {\n operationName = ` \"${processedArgs.operationName}\" `;\n }\n operationName = OPERATION_NOT_SUPPORTED.replace('$operationName$', operationName);\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n }\n\n if (processedArgs.document?.loc) {\n addSpanSource(span, processedArgs.document.loc, config.allowValues);\n }\n\n if (processedArgs.variableValues && config.allowValues) {\n addInputVariableAttributes(span, processedArgs.variableValues);\n }\n\n return span;\n }\n\n private _wrapExecuteArgs(\n schema: GraphQLSchema,\n document: DocumentNode,\n rootValue: any,\n contextValue: any,\n variableValues: Maybe<{ [key: string]: any }>,\n operationName: Maybe<string>,\n fieldResolver: Maybe<GraphQLFieldResolver<any, any>>,\n typeResolver: Maybe<GraphQLTypeResolver<any, any>>,\n defaultFieldResolved: GraphQLFieldResolver<any, any>,\n ): OtelExecutionArgs {\n if (!contextValue) {\n contextValue = {};\n }\n\n if (contextValue[OTEL_GRAPHQL_DATA_SYMBOL] || this.getConfig().ignoreResolveSpans) {\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n };\n }\n\n const isUsingDefaultResolver = fieldResolver == null;\n // follows graphql implementation here:\n // https://github.com/graphql/graphql-js/blob/0b7daed9811731362c71900e12e5ea0d1ecc7f1f/src/execution/execute.ts#L494\n const fieldResolverForExecute = fieldResolver ?? defaultFieldResolved;\n fieldResolver = wrapFieldResolver(\n this.tracer,\n () => this.getConfig(),\n fieldResolverForExecute,\n isUsingDefaultResolver,\n );\n\n if (schema) {\n wrapFields(schema.getQueryType() as any, this.tracer, () => this.getConfig());\n wrapFields(schema.getMutationType() as any, this.tracer, () => this.getConfig());\n }\n\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AA4EA,MAAM,YAAA,GAAe,iCAAA;AAErB,MAAM,cAAA,GAAqD;AAAA,EACzD,UAAA,EAAY,KAAA;AAAA,EACZ,KAAA,EAAO,EAAA;AAAA,EACP,WAAA,EAAa,KAAA;AAAA,EACb,kBAAA,EAAoB;AACtB,CAAA;AAEA,MAAM,iBAAA,GAAoB,CAAC,cAAc,CAAA;AAElC,MAAM,+BAA+B,mBAAA,CAAwD;AAAA,EAClG,WAAA,CAAY,MAAA,GAAuC,EAAC,EAAG;AACrD,IAAA,KAAA,CAAM,cAAc,WAAA,EAAa,EAAE,GAAG,cAAA,EAAgB,GAAG,QAAQ,CAAA;AAAA,EACnE;AAAA,EAES,SAAA,CAAU,MAAA,GAAuC,EAAC,E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AAU,IAAA,CAAK,QAAQ,MAAM,IAAA,CAAK,WAAW,CAAA;AAC5E,MAAA,UAAA,CAAW,MAAA,CAAO,iBAAgB,EAAU,IAAA,CAAK,QAAQ,MAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IACjF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA;AAAA,MACA,QAAA;AAAA,MACA,SAAA;AAAA,MACA,YAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,aAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;"}
@@ -1,5 +1,5 @@
1
1
  import * as api from '@opentelemetry/api';
2
- import { getRPCMetadata, RPCType } from '@opentelemetry/core';
2
+ import { setHttpServerSpanRouteAttribute } from '../../../../utils/setHttpServerSpanRouteAttribute.js';
3
3
  import { InstrumentationBase, semconvStabilityFromStr, InstrumentationNodeModuleDefinition, isWrapped } from '@opentelemetry/instrumentation';
4
4
  import { SDK_VERSION } from '@sentry/core';
5
5
  import { HapiComponentName, handlerPatched } from './internal-types.js';
@@ -226,10 +226,7 @@ class HapiInstrumentation extends InstrumentationBase {
226
226
  if (api.trace.getSpan(api.context.active()) === void 0) {
227
227
  return await oldHandler.call(this, ...params);
228
228
  }
229
- const rpcMetadata = getRPCMetadata(api.context.active());
230
- if (rpcMetadata?.type === RPCType.HTTP) {
231
- rpcMetadata.route = route.path;
232
- }
229
+ setHttpServerSpanRouteAttribute(route.path);
233
230
  const metadata = getRouteMetadata(route, instrumentation._semconvStability, pluginName);
234
231
  const span = instrumentation.tracer.startSpan(metadata.name, {
235
232
  attributes: metadata.attributes
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/hapi/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-hapi\n * - Upstream version: @opentelemetry/instrumentation-hapi@0.64.0\n * - Types vendored from @hapi/hapi as simplified interfaces\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n InstrumentationBase,\n InstrumentationConfig,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\n\nimport type * as Hapi from './hapi-types';\nimport { SDK_VERSION } from '@sentry/core';\nimport {\n HapiComponentName,\n HapiServerRouteInput,\n handlerPatched,\n PatchableServerRoute,\n HapiServerRouteInputMethod,\n HapiPluginInput,\n RegisterFunction,\n PatchableExtMethod,\n ServerExtDirectInput,\n} from './internal-types';\nimport {\n getRouteMetadata,\n getPluginName,\n isLifecycleExtType,\n isLifecycleExtEventObj,\n getExtMetadata,\n isDirectExtInput,\n isPatchableExtMethod,\n getPluginFromInput,\n} from './utils';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-hapi';\n\n/** Hapi instrumentation for OpenTelemetry */\nexport class HapiInstrumentation extends InstrumentationBase {\n private _semconvStability: SemconvStability;\n\n constructor(config: InstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._semconvStability = semconvStabilityFromStr('http', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n HapiComponentName,\n ['>=17.0.0 <22'],\n (module: any) => {\n const moduleExports: typeof Hapi = module[Symbol.toStringTag] === 'Module' ? module.default : module;\n if (!isWrapped(moduleExports.server)) {\n this._wrap(moduleExports, 'server', this._getServerPatch.bind(this) as any);\n }\n\n if (!isWrapped(moduleExports.Server)) {\n this._wrap(moduleExports, 'Server', this._getServerPatch.bind(this) as any);\n }\n return moduleExports;\n },\n (module: any) => {\n const moduleExports: typeof Hapi = module[Symbol.toStringTag] === 'Module' ? module.default : module;\n this._massUnwrap([moduleExports], ['server', 'Server']);\n },\n );\n }\n\n /**\n * Patches the Hapi.server and Hapi.Server functions in order to instrument\n * the server.route, server.ext, and server.register functions via calls to the\n * @function _getServerRoutePatch, @function _getServerExtPatch, and\n * @function _getServerRegisterPatch functions\n * @param original - the original Hapi Server creation function\n */\n private _getServerPatch(original: (options?: Hapi.ServerOptions) => Hapi.Server) {\n const instrumentation: HapiInstrumentation = this;\n const self = this;\n return function server(this: Hapi.Server, opts?: Hapi.ServerOptions) {\n const newServer: Hapi.Server = original.apply(this, [opts]);\n\n self._wrap(newServer, 'route', originalRouter => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(originalRouter);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(newServer, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(originalExtHandler as any);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.Server.register\n // function, which requires supporting a variety of different types of Plugin inputs\n self._wrap(newServer, 'register', instrumentation._getServerRegisterPatch.bind(instrumentation) as any);\n return newServer;\n };\n }\n\n /**\n * Patches the plugin register function used by the Hapi Server. This function\n * goes through each plugin that is being registered and adds instrumentation\n * via a call to the @function _wrapRegisterHandler function.\n * @param {RegisterFunction<T>} original - the original register function which\n * registers each plugin on the server\n */\n private _getServerRegisterPatch<T>(original: RegisterFunction<T>): RegisterFunction<T> {\n const instrumentation: HapiInstrumentation = this;\n return function register(this: Hapi.Server, pluginInput: HapiPluginInput<T>, options?: Hapi.ServerRegisterOptions) {\n if (Array.isArray(pluginInput)) {\n for (const pluginObj of pluginInput) {\n const plugin = getPluginFromInput(pluginObj);\n instrumentation._wrapRegisterHandler(plugin);\n }\n } else {\n const plugin = getPluginFromInput(pluginInput);\n instrumentation._wrapRegisterHandler(plugin);\n }\n return original.apply(this, [pluginInput, options]);\n };\n }\n\n /**\n * Patches the Server.ext function which adds extension methods to the specified\n * point along the request lifecycle. This function accepts the full range of\n * accepted input into the standard Hapi `server.ext` function. For each extension,\n * it adds instrumentation to the handler via a call to the @function _wrapExtMethods\n * function.\n * @param original - the original ext function which adds the extension method to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server extension. Else, signifies that the extension was added directly\n */\n private _getServerExtPatch(original: (...args: unknown[]) => unknown, pluginName?: string) {\n const instrumentation: HapiInstrumentation = this;\n\n return function ext(this: ThisParameterType<typeof original>, ...args: Parameters<typeof original>) {\n if (Array.isArray(args[0])) {\n const eventsList: Hapi.ServerExtEventsObject[] | Hapi.ServerExtEventsRequestObject[] = args[0];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i]!;\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as Hapi.ServerExtEventsRequestObject;\n const handler = instrumentation._wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return original.apply(this, args);\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = instrumentation._wrapExtMethods(method, extInput[0], pluginName);\n return original.apply(this, [extInput[0], handler, extInput[2]]);\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = instrumentation._wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n return original.call(this, lifecycleEventObj);\n }\n return original.apply(this, args);\n };\n }\n\n /**\n * Patches the Server.route function. This function accepts either one or an array\n * of Hapi.ServerRoute objects and adds instrumentation on each route via a call to\n * the @function _wrapRouteHandler function.\n * @param {HapiServerRouteInputMethod} original - the original route function which adds\n * the route to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _getServerRoutePatch(original: HapiServerRouteInputMethod, pluginName?: string) {\n const instrumentation: HapiInstrumentation = this;\n return function route(this: Hapi.Server, route: HapiServerRouteInput): void {\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n const newRoute = instrumentation._wrapRouteHandler.call(instrumentation, route[i]!, pluginName);\n route[i] = newRoute;\n }\n } else {\n route = instrumentation._wrapRouteHandler.call(instrumentation, route, pluginName);\n }\n return original.apply(this, [route]);\n };\n }\n\n /**\n * Wraps newly registered plugins to add instrumentation to the plugin's clone of\n * the original server. Specifically, wraps the server.route and server.ext functions\n * via calls to @function _getServerRoutePatch and @function _getServerExtPatch\n * @param {Hapi.Plugin<T>} plugin - the new plugin which is being instrumented\n */\n private _wrapRegisterHandler<T>(plugin: Hapi.Plugin<T>): void {\n const instrumentation: HapiInstrumentation = this;\n const pluginName = getPluginName(plugin);\n const oldRegister = plugin.register;\n const self = this;\n const newRegisterHandler = function (this: typeof plugin, server: Hapi.Server, options: T) {\n self._wrap(server, 'route', original => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(original, pluginName);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(server, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(originalExtHandler as any, pluginName);\n });\n return oldRegister.call(this, server, options);\n };\n plugin.register = newRegisterHandler;\n }\n\n /**\n * Wraps request extension methods to add instrumentation to each new extension handler.\n * Patches each individual extension in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableExtMethod | PatchableExtMethod[]} method - the request extension\n * handler which is being instrumented\n * @param {Hapi.ServerRequestExtType} extPoint - the point in the Hapi request lifecycle\n * which this extension targets\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: Hapi.ServerRequestExtType,\n pluginName?: string,\n ): T {\n const instrumentation: HapiInstrumentation = this;\n if (method instanceof Array) {\n for (let i = 0; i < method.length; i++) {\n method[i] = instrumentation._wrapExtMethods(method[i]!, extPoint) as PatchableExtMethod;\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = async function (this: any, ...params: Parameters<Hapi.Lifecycle.Method>) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with<Parameters<Hapi.Lifecycle.Method>, Hapi.Lifecycle.Method>(\n api.trace.setSpan(api.context.active(), span),\n method,\n undefined,\n ...params,\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n return newHandler as T;\n }\n return method;\n }\n\n /**\n * Patches each individual route handler method in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableServerRoute} route - the route handler which is being instrumented\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n const instrumentation: HapiInstrumentation = this;\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: Hapi.Lifecycle.Method) => Hapi.Lifecycle.Method = oldHandler => {\n return async function (this: any, ...params: Parameters<Hapi.Lifecycle.Method>) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await oldHandler.call(this, ...params);\n }\n const rpcMetadata = getRPCMetadata(api.context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route.path;\n }\n const metadata = getRouteMetadata(route, instrumentation._semconvStability, pluginName);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with(api.trace.setSpan(api.context.active(), span), () =>\n oldHandler.call(this, ...params),\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as Hapi.Lifecycle.Method);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server) {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as Hapi.Lifecycle.Method);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as Hapi.Lifecycle.Method);\n }\n return route;\n }\n}\n"],"names":[],"mappings":";;;;;;;AA0DA,MAAM,YAAA,GAAe,8BAAA;AAGd,MAAM,4BAA4B,mBAAA,CAAoB;AAAA,EAG3D,WAAA,CAAY,MAAA,GAAgC,EAAC,EAAG;AAC9C,IAAA,KAAA,CAAM,YAAA,EAAc,aAAa,MAAM,CAAA;AACvC,IAAA,IAAA,CAAK,iBAAA,GAAoB,uBAAA,CAAwB,MAAA,EAAQ,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,EACpG;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,OAAO,IAAI,mCAAA;AAAA,MACT,iBAAA;AAAA,MACA,CAAC,cAAc,CAAA;AAAA,MACf,CAAC,MAAA,KAAgB;AACf,QAAA,MAAM,gBAA6B,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA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A,IACF,CAAA;AAEA,IAAA,IAAI,OAAO,KAAA,CAAM,OAAA,KAAY,UAAA,EAAY;AACvC,MAAA,KAAA,CAAM,OAAA,GAAU,WAAA,CAAY,KAAA,CAAM,OAAgC,CAAA;AAAA,IACpE,CAAA,MAAA,IAAW,OAAO,KAAA,CAAM,OAAA,KAAY,UAAA,EAAY;AAC9C,MAAA,MAAM,aAAa,KAAA,CAAM,OAAA;AACzB,MAAA,KAAA,CAAM,OAAA,GAAU,SAAU,MAAA,EAAQ;AAChC,QAAA,MAAM,OAAA,GAAU,WAAW,MAAM,CAAA;AACjC,QAAA,IAAI,OAAO,OAAA,CAAQ,OAAA,KAAY,UAAA,EAAY;AACzC,UAAA,OAAA,CAAQ,OAAA,GAAU,WAAA,CAAY,OAAA,CAAQ,OAAgC,CAAA;AAAA,QACxE;AACA,QAAA,OAAO,OAAA;AAAA,MACT,CAAA;AAAA,IACF,CAAA,MAAA,IAAW,OAAO,KAAA,CAAM,OAAA,EAAS,YAAY,UAAA,EAAY;AACvD,MAAA,KAAA,CAAM,OAAA,CAAQ,OAAA,GAAU,WAAA,CAAY,KAAA,CAAM,QAAQ,OAAgC,CAAA;AAAA,IACpF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/hapi/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-hapi\n * - Upstream version: @opentelemetry/instrumentation-hapi@0.64.0\n * - Types vendored from @hapi/hapi as simplified interfaces\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { setHttpServerSpanRouteAttribute } from '../../../../utils/setHttpServerSpanRouteAttribute';\nimport {\n InstrumentationBase,\n InstrumentationConfig,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\n\nimport type * as Hapi from './hapi-types';\nimport { SDK_VERSION } from '@sentry/core';\nimport {\n HapiComponentName,\n HapiServerRouteInput,\n handlerPatched,\n PatchableServerRoute,\n HapiServerRouteInputMethod,\n HapiPluginInput,\n RegisterFunction,\n PatchableExtMethod,\n ServerExtDirectInput,\n} from './internal-types';\nimport {\n getRouteMetadata,\n getPluginName,\n isLifecycleExtType,\n isLifecycleExtEventObj,\n getExtMetadata,\n isDirectExtInput,\n isPatchableExtMethod,\n getPluginFromInput,\n} from './utils';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-hapi';\n\n/** Hapi instrumentation for OpenTelemetry */\nexport class HapiInstrumentation extends InstrumentationBase {\n private _semconvStability: SemconvStability;\n\n constructor(config: InstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._semconvStability = semconvStabilityFromStr('http', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n HapiComponentName,\n ['>=17.0.0 <22'],\n (module: any) => {\n const moduleExports: typeof Hapi = module[Symbol.toStringTag] === 'Module' ? module.default : module;\n if (!isWrapped(moduleExports.server)) {\n this._wrap(moduleExports, 'server', this._getServerPatch.bind(this) as any);\n }\n\n if (!isWrapped(moduleExports.Server)) {\n this._wrap(moduleExports, 'Server', this._getServerPatch.bind(this) as any);\n }\n return moduleExports;\n },\n (module: any) => {\n const moduleExports: typeof Hapi = module[Symbol.toStringTag] === 'Module' ? module.default : module;\n this._massUnwrap([moduleExports], ['server', 'Server']);\n },\n );\n }\n\n /**\n * Patches the Hapi.server and Hapi.Server functions in order to instrument\n * the server.route, server.ext, and server.register functions via calls to the\n * @function _getServerRoutePatch, @function _getServerExtPatch, and\n * @function _getServerRegisterPatch functions\n * @param original - the original Hapi Server creation function\n */\n private _getServerPatch(original: (options?: Hapi.ServerOptions) => Hapi.Server) {\n const instrumentation: HapiInstrumentation = this;\n const self = this;\n return function server(this: Hapi.Server, opts?: Hapi.ServerOptions) {\n const newServer: Hapi.Server = original.apply(this, [opts]);\n\n self._wrap(newServer, 'route', originalRouter => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(originalRouter);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(newServer, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(originalExtHandler as any);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.Server.register\n // function, which requires supporting a variety of different types of Plugin inputs\n self._wrap(newServer, 'register', instrumentation._getServerRegisterPatch.bind(instrumentation) as any);\n return newServer;\n };\n }\n\n /**\n * Patches the plugin register function used by the Hapi Server. This function\n * goes through each plugin that is being registered and adds instrumentation\n * via a call to the @function _wrapRegisterHandler function.\n * @param {RegisterFunction<T>} original - the original register function which\n * registers each plugin on the server\n */\n private _getServerRegisterPatch<T>(original: RegisterFunction<T>): RegisterFunction<T> {\n const instrumentation: HapiInstrumentation = this;\n return function register(this: Hapi.Server, pluginInput: HapiPluginInput<T>, options?: Hapi.ServerRegisterOptions) {\n if (Array.isArray(pluginInput)) {\n for (const pluginObj of pluginInput) {\n const plugin = getPluginFromInput(pluginObj);\n instrumentation._wrapRegisterHandler(plugin);\n }\n } else {\n const plugin = getPluginFromInput(pluginInput);\n instrumentation._wrapRegisterHandler(plugin);\n }\n return original.apply(this, [pluginInput, options]);\n };\n }\n\n /**\n * Patches the Server.ext function which adds extension methods to the specified\n * point along the request lifecycle. This function accepts the full range of\n * accepted input into the standard Hapi `server.ext` function. For each extension,\n * it adds instrumentation to the handler via a call to the @function _wrapExtMethods\n * function.\n * @param original - the original ext function which adds the extension method to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server extension. Else, signifies that the extension was added directly\n */\n private _getServerExtPatch(original: (...args: unknown[]) => unknown, pluginName?: string) {\n const instrumentation: HapiInstrumentation = this;\n\n return function ext(this: ThisParameterType<typeof original>, ...args: Parameters<typeof original>) {\n if (Array.isArray(args[0])) {\n const eventsList: Hapi.ServerExtEventsObject[] | Hapi.ServerExtEventsRequestObject[] = args[0];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i]!;\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as Hapi.ServerExtEventsRequestObject;\n const handler = instrumentation._wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return original.apply(this, args);\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = instrumentation._wrapExtMethods(method, extInput[0], pluginName);\n return original.apply(this, [extInput[0], handler, extInput[2]]);\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = instrumentation._wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n return original.call(this, lifecycleEventObj);\n }\n return original.apply(this, args);\n };\n }\n\n /**\n * Patches the Server.route function. This function accepts either one or an array\n * of Hapi.ServerRoute objects and adds instrumentation on each route via a call to\n * the @function _wrapRouteHandler function.\n * @param {HapiServerRouteInputMethod} original - the original route function which adds\n * the route to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _getServerRoutePatch(original: HapiServerRouteInputMethod, pluginName?: string) {\n const instrumentation: HapiInstrumentation = this;\n return function route(this: Hapi.Server, route: HapiServerRouteInput): void {\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n const newRoute = instrumentation._wrapRouteHandler.call(instrumentation, route[i]!, pluginName);\n route[i] = newRoute;\n }\n } else {\n route = instrumentation._wrapRouteHandler.call(instrumentation, route, pluginName);\n }\n return original.apply(this, [route]);\n };\n }\n\n /**\n * Wraps newly registered plugins to add instrumentation to the plugin's clone of\n * the original server. Specifically, wraps the server.route and server.ext functions\n * via calls to @function _getServerRoutePatch and @function _getServerExtPatch\n * @param {Hapi.Plugin<T>} plugin - the new plugin which is being instrumented\n */\n private _wrapRegisterHandler<T>(plugin: Hapi.Plugin<T>): void {\n const instrumentation: HapiInstrumentation = this;\n const pluginName = getPluginName(plugin);\n const oldRegister = plugin.register;\n const self = this;\n const newRegisterHandler = function (this: typeof plugin, server: Hapi.Server, options: T) {\n self._wrap(server, 'route', original => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(original, pluginName);\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(server, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(originalExtHandler as any, pluginName);\n });\n return oldRegister.call(this, server, options);\n };\n plugin.register = newRegisterHandler;\n }\n\n /**\n * Wraps request extension methods to add instrumentation to each new extension handler.\n * Patches each individual extension in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableExtMethod | PatchableExtMethod[]} method - the request extension\n * handler which is being instrumented\n * @param {Hapi.ServerRequestExtType} extPoint - the point in the Hapi request lifecycle\n * which this extension targets\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: Hapi.ServerRequestExtType,\n pluginName?: string,\n ): T {\n const instrumentation: HapiInstrumentation = this;\n if (method instanceof Array) {\n for (let i = 0; i < method.length; i++) {\n method[i] = instrumentation._wrapExtMethods(method[i]!, extPoint) as PatchableExtMethod;\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = async function (this: any, ...params: Parameters<Hapi.Lifecycle.Method>) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with<Parameters<Hapi.Lifecycle.Method>, Hapi.Lifecycle.Method>(\n api.trace.setSpan(api.context.active(), span),\n method,\n undefined,\n ...params,\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n return newHandler as T;\n }\n return method;\n }\n\n /**\n * Patches each individual route handler method in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableServerRoute} route - the route handler which is being instrumented\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n const instrumentation: HapiInstrumentation = this;\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: Hapi.Lifecycle.Method) => Hapi.Lifecycle.Method = oldHandler => {\n return async function (this: any, ...params: Parameters<Hapi.Lifecycle.Method>) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata(route, instrumentation._semconvStability, pluginName);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with(api.trace.setSpan(api.context.active(), span), () =>\n oldHandler.call(this, ...params),\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as Hapi.Lifecycle.Method);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server) {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as Hapi.Lifecycle.Method);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as Hapi.Lifecycle.Method);\n }\n return route;\n }\n}\n"],"names":[],"mappings":";;;;;;;AA0DA,MAAM,YAAA,GAAe,8BAAA;AAGd,MAAM,4BAA4B,mBAAA,CAAoB;AAAA,EAG3D,WAAA,CAAY,MAAA,GAAgC,EAAC,EAAG;AAC9C,IAAA,KAAA,CAAM,YAAA,EAAc,aAAa,MAAM,CAAA;AACvC,IAAA,IAAA,CAAK,iBAAA,GAAoB,uBAAA,CAAwB,MAAA,EAAQ,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,EACpG;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,OAAO,IAAI,mCAAA;AAAA,MACT,iBAAA;AAAA,MACA,CAAC,cAAc,CAAA;AAAA,MACf,CAAC,MAAA,KAAgB;AACf,QAAA,MAAM,gBAA6B,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA,GAAW,OAAO,OAAA,GAAU,MAAA;AAC9F,QAAA,IAAI,CAAC,SAAA,CAAU,aAAA,CAAc,MAAM,CAAA,EAAG;AACpC,UAAA,IAAA,CAAK,MAAM,aAAA,EAAe,QAAA,EAAU,KAAK,eAAA,CAAgB,IAAA,CAAK,IAAI,CAAQ,CAAA;AAAA,QAC5E;AAEA,QAAA,IAAI,CAAC,SAAA,CAAU,aAAA,CAA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;AACzC,UAAA,OAAA,CAAQ,OAAA,GAAU,WAAA,CAAY,OAAA,CAAQ,OAAgC,CAAA;AAAA,QACxE;AACA,QAAA,OAAO,OAAA;AAAA,MACT,CAAA;AAAA,IACF,CAAA,MAAA,IAAW,OAAO,KAAA,CAAM,OAAA,EAAS,YAAY,UAAA,EAAY;AACvD,MAAA,KAAA,CAAM,OAAA,CAAQ,OAAA,GAAU,WAAA,CAAY,KAAA,CAAM,QAAQ,OAAgC,CAAA;AAAA,IACpF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/hono/index.ts"],"sourcesContent":["import { ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n defineIntegration,\n getDefaultIsolationScope,\n getIsolationScope,\n httpRequestToRequestData,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n spanToJSON,\n} from '@sentry/core';\nimport { ensureIsWrapped, generateInstrumentOnce } from '@sentry/node-core';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport { AttributeNames } from './constants';\nimport { HonoInstrumentation } from './instrumentation';\nimport type { Context, MiddlewareHandler, MiddlewareHandlerInterface, Next } from './types';\n\nconst INTEGRATION_NAME = 'Hono';\n\nfunction addHonoSpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data;\n const type = attributes[AttributeNames.HONO_TYPE];\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.hono',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.hono`,\n });\n\n const name = attributes[AttributeNames.HONO_NAME];\n if (typeof name === 'string') {\n span.updateName(name);\n }\n\n if (getIsolationScope() === getDefaultIsolationScope()) {\n DEBUG_BUILD && debug.warn('Isolation scope is default isolation scope - skipping setting transactionName');\n return;\n }\n\n const route = attributes[ATTR_HTTP_ROUTE];\n const method = attributes[ATTR_HTTP_REQUEST_METHOD];\n if (typeof route === 'string' && typeof method === 'string') {\n getIsolationScope().setTransactionName(`${method} ${route}`);\n }\n}\n\nexport const instrumentHono = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new HonoInstrumentation({\n responseHook: span => {\n addHonoSpanAttributes(span);\n },\n }),\n);\n\nconst _honoIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentHono();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for [Hono](https://hono.dev/).\n *\n * If you also want to capture errors, you need to call `setupHonoErrorHandler(app)` after you set up your Hono server.\n *\n * For more information, see the [hono documentation](https://docs.sentry.io/platforms/javascript/guides/hono/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.honoIntegration()],\n * })\n * ```\n */\nexport const honoIntegration = defineIntegration(_honoIntegration);\n\ninterface HonoHandlerOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured Hono error\n */\n shouldHandleError: (context: Context) => boolean;\n}\n\nfunction honoRequestHandler(): MiddlewareHandler {\n return async function sentryRequestMiddleware(context: Context, next: Next): Promise<void> {\n const normalizedRequest = httpRequestToRequestData(context.req);\n getIsolationScope().setSDKProcessingMetadata({ normalizedRequest });\n await next();\n };\n}\n\nfunction defaultShouldHandleError(context: Context): boolean {\n const statusCode = context.res.status;\n return statusCode >= 500;\n}\n\nfunction honoErrorHandler(options?: Partial<HonoHandlerOptions>): MiddlewareHandler {\n return async function sentryErrorMiddleware(context: Context, next: Next): Promise<void> {\n await next();\n\n const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError;\n if (shouldHandleError(context)) {\n (context.res as { sentry?: string }).sentry = captureException(context.error, {\n mechanism: {\n type: 'auto.middleware.hono',\n handled: false,\n },\n });\n }\n };\n}\n\n/**\n * Add a Hono error handler to capture errors to Sentry.\n *\n * @param app The Hono instances\n * @param options Configuration options for the handler\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n * const { Hono } = require(\"hono\");\n *\n * const app = new Hono();\n *\n * Sentry.setupHonoErrorHandler(app);\n *\n * // Add your routes, etc.\n * ```\n */\nexport function setupHonoErrorHandler(\n app: { use: MiddlewareHandlerInterface },\n options?: Partial<HonoHandlerOptions>,\n): void {\n app.use(honoRequestHandler());\n app.use(honoErrorHandler(options));\n ensureIsWrapped(app.use, 'hono');\n}\n"],"names":[],"mappings":";;;;;;;AAmBA,MAAM,gBAAA,GAAmB,MAAA;AAEzB,SAAS,sBAAsB,IAAA,EAAkB;AAC/C,EAAA,MAAM,UAAA,GAAa,UAAA,CAAW,IAAI,CAAA,CAAE,IAAA;AACpC,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,cAAA,CAAe,SAAS,CAAA;AAChD,EAAA,IAAI,UAAA,CAAW,4BAA4B,CAAA,IAAK,CAAC,IAAA,EAAM;AACrD,IAAA;AAAA,EACF;AAEA,EAAA,IAAA,CAAK,aAAA,CAAc;AAAA,IACjB,CAAC,gCAAgC,GAAG,qBAAA;AAAA,IACpC,CAAC,4BAA4B,GAAG,CAAA,EAAG,IAAI,CAAA,KAAA;AAAA,GACxC,CAAA;AAED,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,cAAA,CAAe,SAAS,CAAA;AAChD,EAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,IAAA,IAAA,CAAK,WAAW,IAAI,CAAA;AAAA,EACtB;AAEA,EAAA,IAAI,iBAAA,EAAkB,KAAM,wBAAA,EAAyB,EAAG;AACtD,IAAA,WAAA,IAAe,KAAA,CAAM,KAAK,+EAA+E,CAAA;AACzG,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,KAAA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A,MAAM,iBAAA,GAAoB,SAAS,iBAAA,IAAqB,wBAAA;AACxD,IAAA,IAAI,iBAAA,CAAkB,OAAO,CAAA,EAAG;AAC9B,MAAC,OAAA,CAAQ,GAAA,CAA4B,MAAA,GAAS,gBAAA,CAAiB,QAAQ,KAAA,EAAO;AAAA,QAC5E,SAAA,EAAW;AAAA,UACT,IAAA,EAAM,sBAAA;AAAA,UACN,OAAA,EAAS;AAAA;AACX,OACD,CAAA;AAAA,IACH;AAAA,EACF,CAAA;AACF;AAoBO,SAAS,qBAAA,CACd,KACA,OAAA,EACM;AACN,EAAA,GAAA,CAAI,GAAA,CAAI,oBAAoB,CAAA;AAC5B,EAAA,GAAA,CAAI,GAAA,CAAI,gBAAA,CAAiB,OAAO,CAAC,CAAA;AACjC,EAAA,eAAA,CAAgB,GAAA,CAAI,KAAK,MAAM,CAAA;AACjC;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/hono/index.ts"],"sourcesContent":["import { ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n defineIntegration,\n getDefaultIsolationScope,\n getIsolationScope,\n httpRequestToRequestData,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n spanToJSON,\n} from '@sentry/core';\nimport { ensureIsWrapped, generateInstrumentOnce } from '@sentry/node-core';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport { AttributeNames } from './constants';\nimport { HonoInstrumentation } from './instrumentation';\nimport type { Context, MiddlewareHandler, MiddlewareHandlerInterface, Next } from './types';\n\nconst INTEGRATION_NAME = 'Hono';\n\nfunction addHonoSpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data;\n const type = attributes[AttributeNames.HONO_TYPE];\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.hono',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.hono`,\n });\n\n const name = attributes[AttributeNames.HONO_NAME];\n if (typeof name === 'string') {\n span.updateName(name);\n }\n\n if (getIsolationScope() === getDefaultIsolationScope()) {\n DEBUG_BUILD && debug.warn('Isolation scope is default isolation scope - skipping setting transactionName');\n return;\n }\n\n const route = attributes[ATTR_HTTP_ROUTE];\n const method = attributes[ATTR_HTTP_REQUEST_METHOD];\n if (typeof route === 'string' && typeof method === 'string') {\n getIsolationScope().setTransactionName(`${method} ${route}`);\n }\n}\n\nexport const instrumentHono = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new HonoInstrumentation({\n responseHook: span => {\n addHonoSpanAttributes(span);\n },\n }),\n);\n\nconst _honoIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentHono();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for [Hono](https://hono.dev/).\n *\n * If you also want to capture errors, you need to call `setupHonoErrorHandler(app)` after you set up your Hono server.\n *\n * For more information, see the [hono documentation](https://docs.sentry.io/platforms/javascript/guides/hono/).\n *\n * @deprecated Use the `@sentry/hono` package instead. The `sentry()` middleware from `@sentry/hono/node` handles\n * tracing and error capturing automatically without needing this integration or `setupHonoErrorHandler`.\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.honoIntegration()],\n * })\n * ```\n */\nexport const honoIntegration = defineIntegration(_honoIntegration);\n\ninterface HonoHandlerOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured Hono error\n */\n shouldHandleError: (context: Context) => boolean;\n}\n\nfunction honoRequestHandler(): MiddlewareHandler {\n return async function sentryRequestMiddleware(context: Context, next: Next): Promise<void> {\n const normalizedRequest = httpRequestToRequestData(context.req);\n getIsolationScope().setSDKProcessingMetadata({ normalizedRequest });\n await next();\n };\n}\n\nfunction defaultShouldHandleError(context: Context): boolean {\n const statusCode = context.res.status;\n return statusCode >= 500;\n}\n\nfunction honoErrorHandler(options?: Partial<HonoHandlerOptions>): MiddlewareHandler {\n return async function sentryErrorMiddleware(context: Context, next: Next): Promise<void> {\n await next();\n\n const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError;\n if (shouldHandleError(context)) {\n (context.res as { sentry?: string }).sentry = captureException(context.error, {\n mechanism: {\n type: 'auto.middleware.hono',\n handled: false,\n },\n });\n }\n };\n}\n\n/**\n * Add a Hono error handler to capture errors to Sentry.\n *\n * @param app The Hono instances\n * @param options Configuration options for the handler\n *\n * @deprecated Use the `@sentry/hono` package instead. The `sentry()` middleware from `@sentry/hono/node` handles\n * error capturing automatically without needing this function or `honoIntegration`.\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n * const { Hono } = require(\"hono\");\n *\n * const app = new Hono();\n *\n * Sentry.setupHonoErrorHandler(app);\n *\n * // Add your routes, etc.\n * ```\n */\nexport function setupHonoErrorHandler(\n app: { use: MiddlewareHandlerInterface },\n options?: Partial<HonoHandlerOptions>,\n): void {\n app.use(honoRequestHandler());\n app.use(honoErrorHandler(options));\n ensureIsWrapped(app.use, 'hono');\n}\n"],"names":[],"mappings":";;;;;;;AAmBA,MAAM,gBAAA,GAAmB,MAAA;AAEzB,SAAS,sBAAsB,IAAA,EAAkB;AAC/C,EAAA,MAAM,UAAA,GAAa,UAAA,CAAW,IAAI,CAAA,CAAE,IAAA;AACpC,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,cAAA,CAAe,SAAS,CAAA;AAChD,EAAA,IAAI,UAAA,CAAW,4BAA4B,CAAA,IAAK,CAAC,IAAA,EAAM;AACrD,IAAA;AAAA,EACF;AAEA,EAAA,IAAA,CAAK,aAAA,CAAc;AAAA,IACjB,CAAC,gCAAgC,GAAG,qBAAA;AAAA,IACpC,CAAC,4BAA4B,GAAG,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,CAAE,wBAAA,CAAyB,EAAE,iBAAA,EAAmB,CAAA;AAClE,IAAA,MAAM,IAAA,EAAK;AAAA,EACb,CAAA;AACF;AAEA,SAAS,yBAAyB,OAAA,EAA2B;AAC3D,EAAA,MAAM,UAAA,GAAa,QAAQ,GAAA,CAAI,MAAA;AAC/B,EAAA,OAAO,UAAA,IAAc,GAAA;AACvB;AAEA,SAAS,iBAAiB,OAAA,EAA0D;AAClF,EAAA,OAAO,eAAe,qBAAA,CAAsB,OAAA,EAAkB,IAAA,EAA2B;AACvF,IAAA,MAAM,IAAA,EAAK;AAEX,IAAA,MAAM,iBAAA,GAAoB,SAAS,iBAAA,IAAqB,wBAAA;AACxD,IAAA,IAAI,iBAAA,CAAkB,OAAO,CAAA,EAAG;AAC9B,MAAC,OAAA,CAAQ,GAAA,CAA4B,MAAA,GAAS,gBAAA,CAAiB,QAAQ,KAAA,EAAO;AAAA,QAC5E,SAAA,EAAW;AAAA,UACT,IAAA,EAAM,sBAAA;AAAA,UACN,OAAA,EAAS;AAAA;AACX,OACD,CAAA;AAAA,IACH;AAAA,EACF,CAAA;AACF;AAuBO,SAAS,qBAAA,CACd,KACA,OAAA,EACM;AACN,EAAA,GAAA,CAAI,GAAA,CAAI,oBAAoB,CAAA;AAC5B,EAAA,GAAA,CAAI,GAAA,CAAI,gBAAA,CAAiB,OAAO,CAAC,CAAA;AACjC,EAAA,eAAA,CAAgB,GAAA,CAAI,KAAK,MAAM,CAAA;AACjC;;;;"}
@@ -1,7 +1,8 @@
1
1
  import * as api from '@opentelemetry/api';
2
2
  import { SDK_VERSION } from '@sentry/core';
3
3
  import { MODULE_NAME, SUPPORTED_VERSIONS } from './constants.js';
4
- import { InstrumentationBase, semconvStabilityFromStr, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile, SemconvStability, isWrapped } from '@opentelemetry/instrumentation';
4
+ import { InstrumentationBase, semconvStabilityFromStr, InstrumentationNodeModuleDefinition, SemconvStability, isWrapped } from '@opentelemetry/instrumentation';
5
+ import { InstrumentationNodeModuleFile } from '../../InstrumentationNodeModuleFile.js';
5
6
  import { extractTableName, extractDatabaseFromConnectionString, extractPortFromConnectionString, extractHostFromConnectionString, mapSystem, limitLength, getName, getFormatter, otelExceptionFromKnexError } from './utils.js';
6
7
  import { ATTR_SERVER_PORT, ATTR_SERVER_ADDRESS, ATTR_DB_NAMESPACE, ATTR_DB_OPERATION_NAME, ATTR_DB_COLLECTION_NAME, ATTR_DB_SYSTEM_NAME, ATTR_DB_QUERY_TEXT } from '@opentelemetry/semantic-conventions';
7
8
  import { ATTR_NET_TRANSPORT, ATTR_NET_PEER_PORT, ATTR_NET_PEER_NAME, ATTR_DB_NAME, ATTR_DB_USER, ATTR_DB_OPERATION, ATTR_DB_SQL_TABLE, ATTR_DB_SYSTEM, ATTR_DB_STATEMENT } from './semconv.js';
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/knex/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-knex\n * - Upstream version: @opentelemetry/instrumentation-knex@0.62.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { SDK_VERSION } from '@sentry/core';\nimport * as constants from './constants';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport * as utils from './utils';\nimport { KnexInstrumentationConfig } from './types';\nimport {\n ATTR_DB_COLLECTION_NAME,\n ATTR_DB_NAMESPACE,\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_SYSTEM_NAME,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_DB_NAME,\n ATTR_DB_OPERATION,\n ATTR_DB_SQL_TABLE,\n ATTR_DB_STATEMENT,\n ATTR_DB_SYSTEM,\n ATTR_DB_USER,\n ATTR_NET_PEER_NAME,\n ATTR_NET_PEER_PORT,\n ATTR_NET_TRANSPORT,\n} from './semconv';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-knex';\n\nconst contextSymbol = Symbol('opentelemetry.instrumentation-knex.context');\nconst DEFAULT_CONFIG: KnexInstrumentationConfig = {\n maxQueryLength: 1022,\n requireParentSpan: false,\n};\n\nexport class KnexInstrumentation extends InstrumentationBase<KnexInstrumentationConfig> {\n private _semconvStability: SemconvStability;\n\n constructor(config: KnexInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, { ...DEFAULT_CONFIG, ...config });\n\n this._semconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n override setConfig(config: KnexInstrumentationConfig = {}) {\n super.setConfig({ ...DEFAULT_CONFIG, ...config });\n }\n\n init() {\n const module = new InstrumentationNodeModuleDefinition(constants.MODULE_NAME, constants.SUPPORTED_VERSIONS);\n\n module.files.push(\n this.getClientNodeModuleFileInstrumentation('src'),\n this.getClientNodeModuleFileInstrumentation('lib'),\n this.getRunnerNodeModuleFileInstrumentation('src'),\n this.getRunnerNodeModuleFileInstrumentation('lib'),\n this.getRunnerNodeModuleFileInstrumentation('lib/execution'),\n );\n\n return module;\n }\n\n private getRunnerNodeModuleFileInstrumentation(basePath: string) {\n return new InstrumentationNodeModuleFile(\n `knex/${basePath}/runner.js`,\n constants.SUPPORTED_VERSIONS,\n (Runner: any, moduleVersion?: string) => {\n this.ensureWrapped(Runner.prototype, 'query', this.createQueryWrapper(moduleVersion));\n return Runner;\n },\n (Runner: any, _moduleVersion?: string) => {\n this._unwrap(Runner.prototype, 'query');\n return Runner;\n },\n );\n }\n\n private getClientNodeModuleFileInstrumentation(basePath: string) {\n return new InstrumentationNodeModuleFile(\n `knex/${basePath}/client.js`,\n constants.SUPPORTED_VERSIONS,\n (Client: any) => {\n this.ensureWrapped(Client.prototype, 'queryBuilder', this.storeContext.bind(this));\n this.ensureWrapped(Client.prototype, 'schemaBuilder', this.storeContext.bind(this));\n this.ensureWrapped(Client.prototype, 'raw', this.storeContext.bind(this));\n return Client;\n },\n (Client: any) => {\n this._unwrap(Client.prototype, 'queryBuilder');\n this._unwrap(Client.prototype, 'schemaBuilder');\n this._unwrap(Client.prototype, 'raw');\n return Client;\n },\n );\n }\n\n private createQueryWrapper(moduleVersion?: string) {\n const instrumentation = this;\n\n return function wrapQuery(original: (...args: any[]) => any) {\n return function wrapped_logging_method(this: any, query: any) {\n const config = this.client.config;\n\n const table = utils.extractTableName(this.builder);\n const operation = query?.method;\n const connectionString = config?.connection?.connectionString;\n const name =\n config?.connection?.filename ||\n config?.connection?.database ||\n utils.extractDatabaseFromConnectionString(connectionString);\n const { maxQueryLength } = instrumentation.getConfig();\n\n const attributes: api.Attributes = {\n 'knex.version': moduleVersion,\n };\n const transport = config?.connection?.filename === ':memory:' ? 'inproc' : undefined;\n\n if (instrumentation._semconvStability & SemconvStability.OLD) {\n Object.assign(attributes, {\n [ATTR_DB_SYSTEM]: utils.mapSystem(this.client.driverName),\n [ATTR_DB_SQL_TABLE]: table,\n [ATTR_DB_OPERATION]: operation,\n [ATTR_DB_USER]: config?.connection?.user,\n [ATTR_DB_NAME]: name,\n [ATTR_NET_PEER_NAME]: config?.connection?.host ?? utils.extractHostFromConnectionString(connectionString),\n [ATTR_NET_PEER_PORT]: config?.connection?.port ?? utils.extractPortFromConnectionString(connectionString),\n [ATTR_NET_TRANSPORT]: transport,\n });\n }\n if (instrumentation._semconvStability & SemconvStability.STABLE) {\n Object.assign(attributes, {\n [ATTR_DB_SYSTEM_NAME]: utils.mapSystem(this.client.driverName),\n [ATTR_DB_COLLECTION_NAME]: table,\n [ATTR_DB_OPERATION_NAME]: operation,\n [ATTR_DB_NAMESPACE]: name,\n [ATTR_SERVER_ADDRESS]: config?.connection?.host ?? utils.extractHostFromConnectionString(connectionString),\n [ATTR_SERVER_PORT]: config?.connection?.port ?? utils.extractPortFromConnectionString(connectionString),\n });\n }\n if (maxQueryLength) {\n const queryText = utils.limitLength(query?.sql, maxQueryLength);\n if (instrumentation._semconvStability & SemconvStability.STABLE) {\n attributes[ATTR_DB_QUERY_TEXT] = queryText;\n }\n if (instrumentation._semconvStability & SemconvStability.OLD) {\n attributes[ATTR_DB_STATEMENT] = queryText;\n }\n }\n\n const parentContext = this.builder[contextSymbol] || api.context.active();\n const parentSpan = api.trace.getSpan(parentContext);\n const hasActiveParent = parentSpan && api.trace.isSpanContextValid(parentSpan.spanContext());\n if (instrumentation._config.requireParentSpan && !hasActiveParent) {\n return original.bind(this)(...arguments);\n }\n\n const span = instrumentation.tracer.startSpan(\n utils.getName(name, operation, table),\n {\n kind: api.SpanKind.CLIENT,\n attributes,\n },\n parentContext,\n );\n const spanContext = api.trace.setSpan(api.context.active(), span);\n\n return api.context\n .with(spanContext, original, this, ...arguments)\n .then((result: unknown) => {\n span.end();\n return result;\n })\n .catch((err: any) => {\n const formatter = utils.getFormatter(this);\n const fullQuery = formatter(query.sql, query.bindings || []);\n const message = err.message.replace(fullQuery + ' - ', '');\n const exc = utils.otelExceptionFromKnexError(err, message);\n span.recordException(exc);\n span.setStatus({ code: api.SpanStatusCode.ERROR, message });\n span.end();\n throw err;\n });\n };\n };\n }\n\n private storeContext(original: Function) {\n return function wrapped_logging_method(this: any) {\n const builder = original.apply(this, arguments);\n Object.defineProperty(builder, contextSymbol, {\n value: api.context.active(),\n });\n return builder;\n };\n }\n\n ensureWrapped(obj: any, methodName: string, wrapper: (original: any) => any) {\n if (isWrapped(obj[methodName])) {\n this._unwrap(obj, methodName);\n }\n this._wrap(obj, methodName, wrapper);\n }\n}\n"],"names":["constants.MODULE_NAME","constants.SUPPORTED_VERSIONS","utils.extractTableName","utils.extractDatabaseFromConnectionString","utils.mapSystem","utils.extractHostFromConnectionString","utils.extractPortFromConnectionString","utils.limitLength","utils.getName","utils.getFormatter","utils.otelExceptionFromKnexError"],"mappings":";;;;;;;;AAwDA,MAAM,YAAA,GAAe,8BAAA;AAErB,MAAM,aAAA,0BAAuB,4CAA4C,CAAA;AACzE,MAAM,cAAA,GAA4C;AAAA,EAChD,cAAA,EAAgB,IAAA;AAAA,EAChB,iBAAA,EAAmB;AACrB,CAAA;AAEO,MAAM,4BAA4B,mBAAA,CAA+C;AAAA,EAGtF,WAAA,CAAY,MAAA,GAAoC,EAAC,EAAG;AAClD,IAAA,KAAA,CAAM,cAAc,WAAA,EAAa,EAAE,GAAG,cAAA,EAAgB,GAAG,QAAQ,CAAA;AAEjE,IAAA,IAAA,CAAK,iBAAA,GAAoB,uBAAA,CAAwB,UAAA,EAAY,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,EACxG;AAAA,EAES,SAAA,CAAU,MAAA,GAAoC,EAAC,EAAG;AACzD,IAAA,KAAA,CAAM,UAAU,EAAE,GAAG,cAAA,EAAgB,GAAG,QAAQ,CAAA;AAAA,EAClD;AAAA,EAEA,IAAA,GAAO;AACL,IAAA,MAAM,SAAS,IAAI,mCAAA,CAAoCA,WAAU,EAAaC,kBAA4B,CAAA;AAE1G,IAAA,MAAA,CAAO,KAAA,CAAM,IAAA;AAAA,MACX,IAAA,CAAK,uCAAuC,KAAK,CAAA;AAAA,MACjD,IAAA,CAAK,uCAAuC,KAAK,CAAA;AAAA,MACjD,IAAA,CA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AU,GAAA,CAAI,OAAA,CAAQ,OAAA,CAAQ,SAAA,GAAY,OAAO,EAAE,CAAA;AACzD,UAAA,MAAM,GAAA,GAAMC,0BAAM,CAA2B,GAAA,EAAK,OAAO,CAAA;AACzD,UAAA,IAAA,CAAK,gBAAgB,GAAG,CAAA;AACxB,UAAA,IAAA,CAAK,UAAU,EAAE,IAAA,EAAM,IAAI,cAAA,CAAe,KAAA,EAAO,SAAS,CAAA;AAC1D,UAAA,IAAA,CAAK,GAAA,EAAI;AACT,UAAA,MAAM,GAAA;AAAA,QACR,CAAC,CAAA;AAAA,MACL,CAAA;AAAA,IACF,CAAA;AAAA,EACF;AAAA,EAEQ,aAAa,QAAA,EAAoB;AACvC,IAAA,OAAO,SAAS,sBAAA,GAAkC;AAChD,MAAA,MAAM,OAAA,GAAU,QAAA,CAAS,KAAA,CAAM,IAAA,EAAM,SAAS,CAAA;AAC9C,MAAA,MAAA,CAAO,cAAA,CAAe,SAAS,aAAA,EAAe;AAAA,QAC5C,KAAA,EAAO,GAAA,CAAI,OAAA,CAAQ,MAAA;AAAO,OAC3B,CAAA;AACD,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,EACF;AAAA,EAEA,aAAA,CAAc,GAAA,EAAU,UAAA,EAAoB,OAAA,EAAiC;AAC3E,IAAA,IAAI,SAAA,CAAU,GAAA,CAAI,UAAU,CAAC,CAAA,EAAG;AAC9B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAK,UAAU,CAAA;AAAA,IAC9B;AACA,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,EAAK,UAAA,EAAY,OAAO,CAAA;AAAA,EACrC;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/knex/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-knex\n * - Upstream version: @opentelemetry/instrumentation-knex@0.62.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { SDK_VERSION } from '@sentry/core';\nimport * as constants from './constants';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from '../../InstrumentationNodeModuleFile';\nimport * as utils from './utils';\nimport { KnexInstrumentationConfig } from './types';\nimport {\n ATTR_DB_COLLECTION_NAME,\n ATTR_DB_NAMESPACE,\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_SYSTEM_NAME,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_DB_NAME,\n ATTR_DB_OPERATION,\n ATTR_DB_SQL_TABLE,\n ATTR_DB_STATEMENT,\n ATTR_DB_SYSTEM,\n ATTR_DB_USER,\n ATTR_NET_PEER_NAME,\n ATTR_NET_PEER_PORT,\n ATTR_NET_TRANSPORT,\n} from './semconv';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-knex';\n\nconst contextSymbol = Symbol('opentelemetry.instrumentation-knex.context');\nconst DEFAULT_CONFIG: KnexInstrumentationConfig = {\n maxQueryLength: 1022,\n requireParentSpan: false,\n};\n\nexport class KnexInstrumentation extends InstrumentationBase<KnexInstrumentationConfig> {\n private _semconvStability: SemconvStability;\n\n constructor(config: KnexInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, { ...DEFAULT_CONFIG, ...config });\n\n this._semconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n override setConfig(config: KnexInstrumentationConfig = {}) {\n super.setConfig({ ...DEFAULT_CONFIG, ...config });\n }\n\n init() {\n const module = new InstrumentationNodeModuleDefinition(constants.MODULE_NAME, constants.SUPPORTED_VERSIONS);\n\n module.files.push(\n this.getClientNodeModuleFileInstrumentation('src'),\n this.getClientNodeModuleFileInstrumentation('lib'),\n this.getRunnerNodeModuleFileInstrumentation('src'),\n this.getRunnerNodeModuleFileInstrumentation('lib'),\n this.getRunnerNodeModuleFileInstrumentation('lib/execution'),\n );\n\n return module;\n }\n\n private getRunnerNodeModuleFileInstrumentation(basePath: string) {\n return new InstrumentationNodeModuleFile(\n `knex/${basePath}/runner.js`,\n constants.SUPPORTED_VERSIONS,\n (Runner: any, moduleVersion?: string) => {\n this.ensureWrapped(Runner.prototype, 'query', this.createQueryWrapper(moduleVersion));\n return Runner;\n },\n (Runner: any, _moduleVersion?: string) => {\n this._unwrap(Runner.prototype, 'query');\n return Runner;\n },\n );\n }\n\n private getClientNodeModuleFileInstrumentation(basePath: string) {\n return new InstrumentationNodeModuleFile(\n `knex/${basePath}/client.js`,\n constants.SUPPORTED_VERSIONS,\n (Client: any) => {\n this.ensureWrapped(Client.prototype, 'queryBuilder', this.storeContext.bind(this));\n this.ensureWrapped(Client.prototype, 'schemaBuilder', this.storeContext.bind(this));\n this.ensureWrapped(Client.prototype, 'raw', this.storeContext.bind(this));\n return Client;\n },\n (Client: any) => {\n this._unwrap(Client.prototype, 'queryBuilder');\n this._unwrap(Client.prototype, 'schemaBuilder');\n this._unwrap(Client.prototype, 'raw');\n return Client;\n },\n );\n }\n\n private createQueryWrapper(moduleVersion?: string) {\n const instrumentation = this;\n\n return function wrapQuery(original: (...args: any[]) => any) {\n return function wrapped_logging_method(this: any, query: any) {\n const config = this.client.config;\n\n const table = utils.extractTableName(this.builder);\n const operation = query?.method;\n const connectionString = config?.connection?.connectionString;\n const name =\n config?.connection?.filename ||\n config?.connection?.database ||\n utils.extractDatabaseFromConnectionString(connectionString);\n const { maxQueryLength } = instrumentation.getConfig();\n\n const attributes: api.Attributes = {\n 'knex.version': moduleVersion,\n };\n const transport = config?.connection?.filename === ':memory:' ? 'inproc' : undefined;\n\n if (instrumentation._semconvStability & SemconvStability.OLD) {\n Object.assign(attributes, {\n [ATTR_DB_SYSTEM]: utils.mapSystem(this.client.driverName),\n [ATTR_DB_SQL_TABLE]: table,\n [ATTR_DB_OPERATION]: operation,\n [ATTR_DB_USER]: config?.connection?.user,\n [ATTR_DB_NAME]: name,\n [ATTR_NET_PEER_NAME]: config?.connection?.host ?? utils.extractHostFromConnectionString(connectionString),\n [ATTR_NET_PEER_PORT]: config?.connection?.port ?? utils.extractPortFromConnectionString(connectionString),\n [ATTR_NET_TRANSPORT]: transport,\n });\n }\n if (instrumentation._semconvStability & SemconvStability.STABLE) {\n Object.assign(attributes, {\n [ATTR_DB_SYSTEM_NAME]: utils.mapSystem(this.client.driverName),\n [ATTR_DB_COLLECTION_NAME]: table,\n [ATTR_DB_OPERATION_NAME]: operation,\n [ATTR_DB_NAMESPACE]: name,\n [ATTR_SERVER_ADDRESS]: config?.connection?.host ?? utils.extractHostFromConnectionString(connectionString),\n [ATTR_SERVER_PORT]: config?.connection?.port ?? utils.extractPortFromConnectionString(connectionString),\n });\n }\n if (maxQueryLength) {\n const queryText = utils.limitLength(query?.sql, maxQueryLength);\n if (instrumentation._semconvStability & SemconvStability.STABLE) {\n attributes[ATTR_DB_QUERY_TEXT] = queryText;\n }\n if (instrumentation._semconvStability & SemconvStability.OLD) {\n attributes[ATTR_DB_STATEMENT] = queryText;\n }\n }\n\n const parentContext = this.builder[contextSymbol] || api.context.active();\n const parentSpan = api.trace.getSpan(parentContext);\n const hasActiveParent = parentSpan && api.trace.isSpanContextValid(parentSpan.spanContext());\n if (instrumentation._config.requireParentSpan && !hasActiveParent) {\n return original.bind(this)(...arguments);\n }\n\n const span = instrumentation.tracer.startSpan(\n utils.getName(name, operation, table),\n {\n kind: api.SpanKind.CLIENT,\n attributes,\n },\n parentContext,\n );\n const spanContext = api.trace.setSpan(api.context.active(), span);\n\n return api.context\n .with(spanContext, original, this, ...arguments)\n .then((result: unknown) => {\n span.end();\n return result;\n })\n .catch((err: any) => {\n const formatter = utils.getFormatter(this);\n const fullQuery = formatter(query.sql, query.bindings || []);\n const message = err.message.replace(fullQuery + ' - ', '');\n const exc = utils.otelExceptionFromKnexError(err, message);\n span.recordException(exc);\n span.setStatus({ code: api.SpanStatusCode.ERROR, message });\n span.end();\n throw err;\n });\n };\n };\n }\n\n private storeContext(original: Function) {\n return function wrapped_logging_method(this: any) {\n const builder = original.apply(this, arguments);\n Object.defineProperty(builder, contextSymbol, {\n value: api.context.active(),\n });\n return builder;\n };\n }\n\n ensureWrapped(obj: any, methodName: string, wrapper: (original: any) => any) {\n if (isWrapped(obj[methodName])) {\n this._unwrap(obj, methodName);\n }\n this._wrap(obj, methodName, wrapper);\n }\n}\n"],"names":["constants.MODULE_NAME","constants.SUPPORTED_VERSIONS","utils.extractTableName","utils.extractDatabaseFromConnectionString","utils.mapSystem","utils.extractHostFromConnectionString","utils.extractPortFromConnectionString","utils.limitLength","utils.getName","utils.getFormatter","utils.otelExceptionFromKnexError"],"mappings":";;;;;;;;;AAwDA,MAAM,YAAA,GAAe,8BAAA;AAErB,MAAM,aAAA,0BAAuB,4CAA4C,CAAA;AACzE,MAAM,cAAA,GAA4C;AAAA,EAChD,cAAA,EAAgB,IAAA;AAAA,EAChB,iBAAA,EAAmB;AACrB,CAAA;AAEO,MAAM,4BAA4B,mBAAA,CAA+C;AAAA,EAGtF,WAAA,CAAY,MAAA,GAAoC,EAAC,EAAG;AAClD,IAAA,KAAA,CAAM,cAAc,WAAA,EAAa,EAAE,GAAG,cAAA,E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,IACT,CAAA;AAAA,EACF;AAAA,EAEA,aAAA,CAAc,GAAA,EAAU,UAAA,EAAoB,OAAA,EAAiC;AAC3E,IAAA,IAAI,SAAA,CAAU,GAAA,CAAI,UAAU,CAAC,CAAA,EAAG;AAC9B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAK,UAAU,CAAA;AAAA,IAC9B;AACA,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,EAAK,UAAA,EAAY,OAAO,CAAA;AAAA,EACrC;AACF;;;;"}
@@ -3,7 +3,7 @@ import { InstrumentationBase, InstrumentationNodeModuleDefinition, isWrapped, sa
3
3
  import { KoaLayerType } from './types.js';
4
4
  import { SDK_VERSION } from '@sentry/core';
5
5
  import { isLayerIgnored, getMiddlewareMetadata } from './utils.js';
6
- import { getRPCMetadata, RPCType } from '@opentelemetry/core';
6
+ import { setHttpServerSpanRouteAttribute } from '../../../../utils/setHttpServerSpanRouteAttribute.js';
7
7
  import { kLayerPatched } from './internal-types.js';
8
8
 
9
9
  const PACKAGE_NAME = "@sentry/instrumentation-koa";
@@ -99,9 +99,8 @@ class KoaInstrumentation extends InstrumentationBase {
99
99
  const span = this.tracer.startSpan(metadata.name, {
100
100
  attributes: metadata.attributes
101
101
  });
102
- const rpcMetadata = getRPCMetadata(api.context.active());
103
- if (rpcMetadata?.type === RPCType.HTTP && context._matchedRoute) {
104
- rpcMetadata.route = context._matchedRoute.toString();
102
+ if (context._matchedRoute) {
103
+ setHttpServerSpanRouteAttribute(context._matchedRoute.toString());
105
104
  }
106
105
  const { requestHook } = this.getConfig();
107
106
  if (requestHook) {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/koa/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-koa\n * - Upstream version: @opentelemetry/instrumentation-koa@0.66.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\n\nimport { KoaLayerType, KoaInstrumentationConfig } from './types';\nimport { SDK_VERSION } from '@sentry/core';\nimport { getMiddlewareMetadata, isLayerIgnored } from './utils';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport { Next, kLayerPatched, KoaContext, KoaMiddleware, KoaPatchedMiddleware } from './internal-types';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-koa';\n\n/** Koa instrumentation for OpenTelemetry */\nexport class KoaInstrumentation extends InstrumentationBase<KoaInstrumentationConfig> {\n constructor(config: KoaInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n 'koa',\n ['>=2.0.0 <4'],\n (module: any) => {\n const moduleExports: any =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (moduleExports == null) {\n return moduleExports;\n }\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n this._wrap(moduleExports.prototype, 'use', this._getKoaUsePatch.bind(this));\n return module;\n },\n (module: any) => {\n const moduleExports: any =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n },\n );\n }\n\n /**\n * Patches the Koa.use function in order to instrument each original\n * middleware layer which is introduced\n * @param {KoaMiddleware} middleware - the original middleware function\n */\n private _getKoaUsePatch(original: (middleware: KoaMiddleware) => any) {\n const plugin = this;\n return function use(this: any, middlewareFunction: KoaMiddleware) {\n let patchedFunction: KoaMiddleware;\n if (middlewareFunction.router) {\n patchedFunction = plugin._patchRouterDispatch(middlewareFunction);\n } else {\n patchedFunction = plugin._patchLayer(middlewareFunction, false);\n }\n return original.apply(this, [patchedFunction]);\n };\n }\n\n /**\n * Patches the dispatch function used by @koa/router. This function\n * goes through each routed middleware and adds instrumentation via a call\n * to the @function _patchLayer function.\n * @param {KoaMiddleware} dispatchLayer - the original dispatch function which dispatches\n * routed middleware\n */\n private _patchRouterDispatch(dispatchLayer: KoaMiddleware): KoaMiddleware {\n api.diag.debug('Patching @koa/router dispatch');\n\n const router = dispatchLayer.router;\n\n const routesStack = router?.stack ?? [];\n for (const pathLayer of routesStack) {\n const path = pathLayer.path;\n // Type cast needed: router.stack comes from @types/koa@2.x but we use @types/koa@3.x\n // See internal-types.ts for full explanation\n const pathStack = pathLayer.stack as any;\n for (let j = 0; j < pathStack.length; j++) {\n const routedMiddleware: KoaMiddleware = pathStack[j];\n pathStack[j] = this._patchLayer(routedMiddleware, true, path);\n }\n }\n\n return dispatchLayer;\n }\n\n /**\n * Patches each individual @param middlewareLayer function in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {KoaMiddleware} middlewareLayer - the original middleware function.\n * @param {boolean} isRouter - tracks whether the original middleware function\n * was dispatched by the router originally\n * @param {string?} layerPath - if present, provides additional data from the\n * router about the routed path which the middleware is attached to\n */\n private _patchLayer(\n middlewareLayer: KoaPatchedMiddleware,\n isRouter: boolean,\n layerPath?: string | RegExp,\n ): KoaMiddleware {\n const layerType = isRouter ? KoaLayerType.ROUTER : KoaLayerType.MIDDLEWARE;\n // Skip patching layer if its ignored in the config\n if (middlewareLayer[kLayerPatched] === true || isLayerIgnored(layerType, this.getConfig())) return middlewareLayer;\n\n if (\n middlewareLayer.constructor.name === 'GeneratorFunction' ||\n middlewareLayer.constructor.name === 'AsyncGeneratorFunction'\n ) {\n api.diag.debug('ignoring generator-based Koa middleware layer');\n return middlewareLayer;\n }\n\n middlewareLayer[kLayerPatched] = true;\n\n api.diag.debug('patching Koa middleware layer');\n return async (context: KoaContext, next: Next) => {\n const parent = api.trace.getSpan(api.context.active());\n if (parent === undefined) {\n return middlewareLayer(context, next);\n }\n const metadata = getMiddlewareMetadata(context, middlewareLayer, isRouter, layerPath);\n const span = this.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n\n const rpcMetadata = getRPCMetadata(api.context.active());\n\n if (rpcMetadata?.type === RPCType.HTTP && context._matchedRoute) {\n rpcMetadata.route = context._matchedRoute.toString();\n }\n\n const { requestHook } = this.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n context,\n middlewareLayer,\n layerType,\n }),\n e => {\n if (e) {\n api.diag.error('koa instrumentation: request hook failed', e);\n }\n },\n true,\n );\n }\n\n const newContext = api.trace.setSpan(api.context.active(), span);\n return api.context.with(newContext, async () => {\n try {\n return await middlewareLayer(context, next);\n } catch (err: any) {\n span.recordException(err);\n throw err;\n } finally {\n span.end();\n }\n });\n };\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAoCA,MAAM,YAAA,GAAe,6BAAA;AAGd,MAAM,2BAA2B,mBAAA,CAA8C;AAAA,EACpF,WAAA,CAAY,MAAA,GAAmC,EAAC,EAAG;AACjD,IAAA,KAAA,CAAM,YAAA,EAAc,aAAa,MAAM,CAAA;AAAA,EACzC;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,OAAO,IAAI,mCAAA;AAAA,MACT,KAAA;AAAA,MACA,CAAC,YAAY,CAAA;AAAA,MACb,CAAC,MAAA,KAAgB;AACf,QAAA,MAAM,gBACJ,MAAA,CAAO,MAAA,CAA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,IAAI,KAAA,CAAM,OAAA,CAAQ,IAAI,OAAA,CAAQ,MAAA,IAAU,IAAI,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,IAAA,CAAK,UAAA,EAAY,YAAY;AAC9C,QAAA,IAAI;AACF,UAAA,OAAO,MAAM,eAAA,CAAgB,OAAA,EAAS,IAAI,CAAA;AAAA,QAC5C,SAAS,GAAA,EAAU;AACjB,UAAA,IAAA,CAAK,gBAAgB,GAAG,CAAA;AACxB,UAAA,MAAM,GAAA;AAAA,QACR,CAAA,SAAE;AACA,UAAA,IAAA,CAAK,GAAA,EAAI;AAAA,QACX;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/koa/vendored/instrumentation.ts"],"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 * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-koa\n * - Upstream version: @opentelemetry/instrumentation-koa@0.66.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\n\nimport { KoaLayerType, KoaInstrumentationConfig } from './types';\nimport { SDK_VERSION } from '@sentry/core';\nimport { getMiddlewareMetadata, isLayerIgnored } from './utils';\nimport { setHttpServerSpanRouteAttribute } from '../../../../utils/setHttpServerSpanRouteAttribute';\nimport { Next, kLayerPatched, KoaContext, KoaMiddleware, KoaPatchedMiddleware } from './internal-types';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-koa';\n\n/** Koa instrumentation for OpenTelemetry */\nexport class KoaInstrumentation extends InstrumentationBase<KoaInstrumentationConfig> {\n constructor(config: KoaInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n 'koa',\n ['>=2.0.0 <4'],\n (module: any) => {\n const moduleExports: any =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (moduleExports == null) {\n return moduleExports;\n }\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n this._wrap(moduleExports.prototype, 'use', this._getKoaUsePatch.bind(this));\n return module;\n },\n (module: any) => {\n const moduleExports: any =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n },\n );\n }\n\n /**\n * Patches the Koa.use function in order to instrument each original\n * middleware layer which is introduced\n * @param {KoaMiddleware} middleware - the original middleware function\n */\n private _getKoaUsePatch(original: (middleware: KoaMiddleware) => any) {\n const plugin = this;\n return function use(this: any, middlewareFunction: KoaMiddleware) {\n let patchedFunction: KoaMiddleware;\n if (middlewareFunction.router) {\n patchedFunction = plugin._patchRouterDispatch(middlewareFunction);\n } else {\n patchedFunction = plugin._patchLayer(middlewareFunction, false);\n }\n return original.apply(this, [patchedFunction]);\n };\n }\n\n /**\n * Patches the dispatch function used by @koa/router. This function\n * goes through each routed middleware and adds instrumentation via a call\n * to the @function _patchLayer function.\n * @param {KoaMiddleware} dispatchLayer - the original dispatch function which dispatches\n * routed middleware\n */\n private _patchRouterDispatch(dispatchLayer: KoaMiddleware): KoaMiddleware {\n api.diag.debug('Patching @koa/router dispatch');\n\n const router = dispatchLayer.router;\n\n const routesStack = router?.stack ?? [];\n for (const pathLayer of routesStack) {\n const path = pathLayer.path;\n // Type cast needed: router.stack comes from @types/koa@2.x but we use @types/koa@3.x\n // See internal-types.ts for full explanation\n const pathStack = pathLayer.stack as any;\n for (let j = 0; j < pathStack.length; j++) {\n const routedMiddleware: KoaMiddleware = pathStack[j];\n pathStack[j] = this._patchLayer(routedMiddleware, true, path);\n }\n }\n\n return dispatchLayer;\n }\n\n /**\n * Patches each individual @param middlewareLayer function in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {KoaMiddleware} middlewareLayer - the original middleware function.\n * @param {boolean} isRouter - tracks whether the original middleware function\n * was dispatched by the router originally\n * @param {string?} layerPath - if present, provides additional data from the\n * router about the routed path which the middleware is attached to\n */\n private _patchLayer(\n middlewareLayer: KoaPatchedMiddleware,\n isRouter: boolean,\n layerPath?: string | RegExp,\n ): KoaMiddleware {\n const layerType = isRouter ? KoaLayerType.ROUTER : KoaLayerType.MIDDLEWARE;\n // Skip patching layer if its ignored in the config\n if (middlewareLayer[kLayerPatched] === true || isLayerIgnored(layerType, this.getConfig())) return middlewareLayer;\n\n if (\n middlewareLayer.constructor.name === 'GeneratorFunction' ||\n middlewareLayer.constructor.name === 'AsyncGeneratorFunction'\n ) {\n api.diag.debug('ignoring generator-based Koa middleware layer');\n return middlewareLayer;\n }\n\n middlewareLayer[kLayerPatched] = true;\n\n api.diag.debug('patching Koa middleware layer');\n return async (context: KoaContext, next: Next) => {\n const parent = api.trace.getSpan(api.context.active());\n if (parent === undefined) {\n return middlewareLayer(context, next);\n }\n const metadata = getMiddlewareMetadata(context, middlewareLayer, isRouter, layerPath);\n const span = this.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n\n if (context._matchedRoute) {\n setHttpServerSpanRouteAttribute(context._matchedRoute.toString());\n }\n\n const { requestHook } = this.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n context,\n middlewareLayer,\n layerType,\n }),\n e => {\n if (e) {\n api.diag.error('koa instrumentation: request hook failed', e);\n }\n },\n true,\n );\n }\n\n const newContext = api.trace.setSpan(api.context.active(), span);\n return api.context.with(newContext, async () => {\n try {\n return await middlewareLayer(context, next);\n } catch (err: any) {\n span.recordException(err);\n throw err;\n } finally {\n span.end();\n }\n });\n };\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAoCA,MAAM,YAAA,GAAe,6BAAA;AAGd,MAAM,2BAA2B,mBAAA,CAA8C;AAAA,EACpF,WAAA,CAAY,MAAA,GAAmC,EAAC,EAAG;AACjD,IAAA,KAAA,CAAM,YAAA,EAAc,aAAa,MAAM,CAAA;AAAA,EACzC;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,OAAO,IAAI,mCAAA;AAAA,MACT,KAAA;AAAA,MACA,CAAC,YAAY,CAAA;AAAA,MACb,CAAC,MAAA,KAAgB;AACf,QAAA,MAAM,gBACJ,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA,GAC3B,OAAO,OAAA,GACP,MAAA;AACN,QAAA,IAAI,iBAAiB,IAAA,EAAM;AACzB,UAAA,OAAO,aAAA;AAAA,QACT;AACA,QAAA,IAAI,SAAA,CAAU,aAAA,CAAc,SAAA,CAAU,GAAG,CAAA,EAAG;AAC1C,UAAA,IAAA,CAAK,OAAA,CAAQ,aAAA,CAAc,SAAA,EAAW,KAAK,CAAA;AAAA,QAC7C;AACA,QAAA,IAAA,CAAK,KAAA,CAAM,cAAc,SAAA,EAAW,KAAA,EAAO,KAAK,eAAA,CAAgB,IAAA,CAAK,IAAI,CAAC,CAAA;AAC1E,QAAA,OAAO,MAAA;AAAA,MACT,CAAA;AAAA,MACA,CAAC,MAAA,KAAgB;AACf,QAAA,MAAM,gBACJ,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA,GAC3B,OAAO,OAAA,GACP,M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,EAAe;AACzB,QAAA,+BAAA,CAAgC,OAAA,CAAQ,aAAA,CAAc,QAAA,EAAU,CAAA;AAAA,MAClE;AAEA,MAAA,MAAM,EAAE,WAAA,EAAY,GAAI,IAAA,CAAK,SAAA,EAAU;AACvC,MAAA,IAAI,WAAA,EAAa;AACf,QAAA,sBAAA;AAAA,UACE,MACE,YAAY,IAAA,EAAM;AAAA,YAChB,OAAA;AAAA,YACA,eAAA;AAAA,YACA;AAAA,WACD,CAAA;AAAA,UACH,CAAA,CAAA,KAAK;AACH,YAAA,IAAI,CAAA,EAAG;AACL,cAAA,GAAA,CAAI,IAAA,CAAK,KAAA,CAAM,0CAAA,EAA4C,CAAC,CAAA;AAAA,YAC9D;AAAA,UACF,CAAA;AAAA,UACA;AAAA,SACF;AAAA,MACF;AAEA,MAAA,MAAM,UAAA,GAAa,IAAI,KAAA,CAAM,OAAA,CAAQ,IAAI,OAAA,CAAQ,MAAA,IAAU,IAAI,CAAA;AAC/D,MAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,IAAA,CAAK,UAAA,EAAY,YAAY;AAC9C,QAAA,IAAI;AACF,UAAA,OAAO,MAAM,eAAA,CAAgB,OAAA,EAAS,IAAI,CAAA;AAAA,QAC5C,SAAS,GAAA,EAAU;AACjB,UAAA,IAAA,CAAK,gBAAgB,GAAG,CAAA;AACxB,UAAA,MAAM,GAAA;AAAA,QACR,CAAA,SAAE;AACA,UAAA,IAAA,CAAK,GAAA,EAAI;AAAA,QACX;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,EACF;AACF;;;;"}
@@ -1,4 +1,5 @@
1
- import { InstrumentationBase, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile } from '@opentelemetry/instrumentation';
1
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
2
+ import { InstrumentationNodeModuleFile } from '../InstrumentationNodeModuleFile.js';
2
3
  import { SDK_VERSION, _INTERNAL_skipAiProviderWrapping, OPENAI_INTEGRATION_NAME, ANTHROPIC_AI_INTEGRATION_NAME, GOOGLE_GENAI_INTEGRATION_NAME, createLangChainCallbackHandler, instrumentLangChainEmbeddings, _INTERNAL_mergeLangChainCallbackHandler } from '@sentry/core';
3
4
 
4
5
  const supportedVersions = [">=0.1.0 <2.0.0"];
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/tracing/langchain/instrumentation.ts"],"sourcesContent":["import {\n InstrumentationBase,\n type InstrumentationConfig,\n type InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n} from '@opentelemetry/instrumentation';\nimport type { LangChainOptions } from '@sentry/core';\nimport {\n _INTERNAL_mergeLangChainCallbackHandler,\n _INTERNAL_skipAiProviderWrapping,\n ANTHROPIC_AI_INTEGRATION_NAME,\n createLangChainCallbackHandler,\n GOOGLE_GENAI_INTEGRATION_NAME,\n instrumentLangChainEmbeddings,\n OPENAI_INTEGRATION_NAME,\n SDK_VERSION,\n} from '@sentry/core';\n\nconst supportedVersions = ['>=0.1.0 <2.0.0'];\n\ntype LangChainInstrumentationOptions = InstrumentationConfig & LangChainOptions;\n\n/**\n * Represents the patched shape of LangChain provider package exports\n */\ninterface PatchedLangChainExports {\n [key: string]: unknown;\n}\n\n/**\n * Wraps Runnable methods (invoke, stream, batch) to inject Sentry callbacks at request time\n * Uses a Proxy to intercept method calls and augment the options.callbacks\n */\nfunction wrapRunnableMethod(\n originalMethod: (...args: unknown[]) => unknown,\n sentryHandler: unknown,\n _methodName: string,\n): (...args: unknown[]) => unknown {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): unknown {\n // LangChain Runnable method signatures:\n // invoke(input, options?) - options contains callbacks\n // stream(input, options?) - options contains callbacks\n // batch(inputs, options?) - options contains callbacks\n\n // Options is typically the second argument\n const optionsIndex = 1;\n let options = args[optionsIndex] as Record<string, unknown> | undefined;\n\n // If options don't exist or aren't an object, create them\n if (!options || typeof options !== 'object' || Array.isArray(options)) {\n options = {};\n args[optionsIndex] = options;\n }\n\n // Inject our callback handler into options.callbacks (request time callbacks)\n options.callbacks = _INTERNAL_mergeLangChainCallbackHandler(options.callbacks, sentryHandler);\n\n // Call original method with augmented options\n return Reflect.apply(target, thisArg, args);\n },\n }) as (...args: unknown[]) => unknown;\n}\n\n/**\n * Sentry LangChain instrumentation using OpenTelemetry.\n */\nexport class SentryLangChainInstrumentation extends InstrumentationBase<LangChainInstrumentationOptions> {\n public constructor(config: LangChainInstrumentationOptions = {}) {\n super('@sentry/instrumentation-langchain', SDK_VERSION, config);\n }\n\n /**\n * Initializes the instrumentation by defining the modules to be patched.\n * We patch the BaseChatModel class methods to inject callbacks\n *\n * We hook into provider packages (@langchain/anthropic, @langchain/openai, etc.)\n * because @langchain/core is often bundled and not loaded as a separate module\n */\n public init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {\n const modules: InstrumentationModuleDefinition[] = [];\n\n // Hook into common LangChain provider packages\n const providerPackages = [\n '@langchain/anthropic',\n '@langchain/openai',\n '@langchain/google-genai',\n '@langchain/mistralai',\n '@langchain/google-vertexai',\n '@langchain/groq',\n ];\n\n for (const packageName of providerPackages) {\n // In CJS, LangChain packages re-export from dist/index.cjs files.\n // Patching only the root module sometimes misses the real implementation or\n // gets overwritten when that file is loaded. We add a file-level patch so that\n // _patch runs again on the concrete implementation\n modules.push(\n new InstrumentationNodeModuleDefinition(\n packageName,\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n [\n new InstrumentationNodeModuleFile(\n `${packageName}/dist/index.cjs`,\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n ),\n ],\n ),\n );\n }\n\n // Hook into main 'langchain' package to catch initChatModel (v1+)\n modules.push(\n new InstrumentationNodeModuleDefinition(\n 'langchain',\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n [\n // To catch the CJS build that contains ConfigurableModel / initChatModel for v1\n new InstrumentationNodeModuleFile(\n 'langchain/dist/chat_models/universal.cjs',\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n ),\n ],\n ),\n );\n\n return modules;\n }\n\n /**\n * Core patch logic - patches chat model and embedding methods\n * This is called when a LangChain provider package is loaded\n */\n private _patch(exports: PatchedLangChainExports): PatchedLangChainExports | void {\n // Skip AI provider wrapping now that LangChain is actually being used\n // This prevents duplicate spans from Anthropic/OpenAI/GoogleGenAI standalone integrations\n _INTERNAL_skipAiProviderWrapping([\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n ]);\n\n const config = this.getConfig();\n\n // Create a shared handler instance for chat model callbacks\n const sentryHandler = createLangChainCallbackHandler(config);\n\n // Patch Runnable methods to inject callbacks at request time\n // This directly manipulates options.callbacks that LangChain uses\n this._patchRunnableMethods(exports, sentryHandler);\n\n // Patch embedding methods to create spans directly\n // Embeddings don't use the callback system, so we wrap the methods themselves\n this._patchEmbeddingsMethods(exports, config);\n\n return exports;\n }\n\n /**\n * Patches chat model methods (invoke, stream, batch) to inject Sentry callbacks\n * Finds a chat model class from the provider package exports and patches its prototype methods\n */\n private _patchRunnableMethods(exports: PatchedLangChainExports, sentryHandler: unknown): void {\n // Known chat model class names for each provider\n const knownChatModelNames = [\n 'ChatAnthropic',\n 'ChatOpenAI',\n 'ChatGoogleGenerativeAI',\n 'ChatMistralAI',\n 'ChatVertexAI',\n 'ChatGroq',\n 'ConfigurableModel',\n ];\n\n const exportsToPatch = (exports.universal_exports ?? exports) as Record<string, unknown>;\n\n const chatModelClass = Object.values(exportsToPatch).find(exp => {\n return typeof exp === 'function' && knownChatModelNames.includes(exp.name);\n }) as { prototype: unknown; name: string } | undefined;\n\n if (!chatModelClass) {\n return;\n }\n\n // Patch directly on chatModelClass.prototype\n const targetProto = chatModelClass.prototype as Record<string, unknown>;\n\n // Skip if already patched (both file-level and module-level hooks resolve to the same prototype)\n if (targetProto.__sentry_patched__) {\n return;\n }\n targetProto.__sentry_patched__ = true;\n\n // Patch the methods (invoke, stream, batch)\n // All chat model instances will inherit these patched methods\n const methodsToPatch = ['invoke', 'stream', 'batch'] as const;\n\n for (const methodName of methodsToPatch) {\n const method = targetProto[methodName];\n if (typeof method === 'function') {\n targetProto[methodName] = wrapRunnableMethod(\n method as (...args: unknown[]) => unknown,\n sentryHandler,\n methodName,\n );\n }\n }\n }\n\n /**\n * Patches embedding class methods (embedQuery, embedDocuments) to create Sentry spans.\n *\n * Unlike chat models which use LangChain's callback system, the Embeddings base class\n * has no callback support. We wrap the methods directly on the prototype.\n *\n * Instruments any exported class whose prototype has both embedQuery and embedDocuments as functions.\n */\n private _patchEmbeddingsMethods(exports: PatchedLangChainExports, options: LangChainOptions): void {\n const exportsToPatch = (exports.universal_exports ?? exports) as Record<string, unknown>;\n\n for (const exp of Object.values(exportsToPatch)) {\n if (typeof exp !== 'function' || !exp.prototype) {\n continue;\n }\n const proto = exp.prototype as Record<string, unknown>;\n if (typeof proto.embedQuery !== 'function' || typeof proto.embedDocuments !== 'function') {\n continue;\n }\n if (proto.__sentry_patched__) {\n continue;\n }\n proto.__sentry_patched__ = true;\n\n instrumentLangChainEmbeddings(proto, options);\n }\n }\n}\n"],"names":[],"mappings":";;;AAmBA,MAAM,iBAAA,GAAoB,CAAC,gBAAgB,CAAA;AAe3C,SAAS,kBAAA,CACP,cAAA,EACA,aAAA,EACA,WAAA,EACiC;AACjC,EAAA,OAAO,IAAI,MAAM,cAAA,EAAgB;AAAA,IAC/B,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAA0B;AAO/C,MAAA,MAAM,YAAA,GAAe,CAAA;AACrB,MAAA,IAAI,OAAA,GAAU,KAAK,YAAY,CAAA;AAG/B,MAAA,IAAI,CAAC,WAAW,OAAO,OAAA,KAAY,YAAY,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG;AACrE,QAAA,OAAA,GAAU,EAAC;AACX,QAAA,IAAA,CAAK,YAAY,CAAA,GAAI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AAM,cAAc,cAAA,CAAe,SAAA;AAGnC,IAAA,IAAI,YAAY,kBAAA,EAAoB;AAClC,MAAA;AAAA,IACF;AACA,IAAA,WAAA,CAAY,kBAAA,GAAqB,IAAA;AAIjC,IAAA,MAAM,cAAA,GAAiB,CAAC,QAAA,EAAU,QAAA,EAAU,OAAO,CAAA;AAEnD,IAAA,KAAA,MAAW,cAAc,cAAA,EAAgB;AACvC,MAAA,MAAM,MAAA,GAAS,YAAY,UAAU,CAAA;AACrC,MAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,QAAA,WAAA,CAAY,UAAU,CAAA,GAAI,kBAAA;AAAA,UACxB,MAAA;AAAA,UACA,aAEF,CAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,uBAAA,CAAwB,SAAkC,OAAA,EAAiC;AACjG,IAAA,MAAM,cAAA,GAAkB,QAAQ,iBAAA,IAAqB,OAAA;AAErD,IAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,MAAA,CAAO,cAAc,CAAA,EAAG;AAC/C,MAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,IAAc,CAAC,IAAI,SAAA,EAAW;AAC/C,QAAA;AAAA,MACF;AACA,MAAA,MAAM,QAAQ,GAAA,CAAI,SAAA;AAClB,MAAA,IAAI,OAAO,KAAA,CAAM,UAAA,KAAe,cAAc,OAAO,KAAA,CAAM,mBAAmB,UAAA,EAAY;AACxF,QAAA;AAAA,MACF;AACA,MAAA,IAAI,MAAM,kBAAA,EAAoB;AAC5B,QAAA;AAAA,MACF;AACA,MAAA,KAAA,CAAM,kBAAA,GAAqB,IAAA;AAE3B,MAAA,6BAAA,CAA8B,OAAO,OAAO,CAAA;AAAA,IAC9C;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/tracing/langchain/instrumentation.ts"],"sourcesContent":["import {\n InstrumentationBase,\n type InstrumentationConfig,\n type InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from '../InstrumentationNodeModuleFile';\nimport type { LangChainOptions } from '@sentry/core';\nimport {\n _INTERNAL_mergeLangChainCallbackHandler,\n _INTERNAL_skipAiProviderWrapping,\n ANTHROPIC_AI_INTEGRATION_NAME,\n createLangChainCallbackHandler,\n GOOGLE_GENAI_INTEGRATION_NAME,\n instrumentLangChainEmbeddings,\n OPENAI_INTEGRATION_NAME,\n SDK_VERSION,\n} from '@sentry/core';\n\nconst supportedVersions = ['>=0.1.0 <2.0.0'];\n\ntype LangChainInstrumentationOptions = InstrumentationConfig & LangChainOptions;\n\n/**\n * Represents the patched shape of LangChain provider package exports\n */\ninterface PatchedLangChainExports {\n [key: string]: unknown;\n}\n\n/**\n * Wraps Runnable methods (invoke, stream, batch) to inject Sentry callbacks at request time\n * Uses a Proxy to intercept method calls and augment the options.callbacks\n */\nfunction wrapRunnableMethod(\n originalMethod: (...args: unknown[]) => unknown,\n sentryHandler: unknown,\n _methodName: string,\n): (...args: unknown[]) => unknown {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args: unknown[]): unknown {\n // LangChain Runnable method signatures:\n // invoke(input, options?) - options contains callbacks\n // stream(input, options?) - options contains callbacks\n // batch(inputs, options?) - options contains callbacks\n\n // Options is typically the second argument\n const optionsIndex = 1;\n let options = args[optionsIndex] as Record<string, unknown> | undefined;\n\n // If options don't exist or aren't an object, create them\n if (!options || typeof options !== 'object' || Array.isArray(options)) {\n options = {};\n args[optionsIndex] = options;\n }\n\n // Inject our callback handler into options.callbacks (request time callbacks)\n options.callbacks = _INTERNAL_mergeLangChainCallbackHandler(options.callbacks, sentryHandler);\n\n // Call original method with augmented options\n return Reflect.apply(target, thisArg, args);\n },\n }) as (...args: unknown[]) => unknown;\n}\n\n/**\n * Sentry LangChain instrumentation using OpenTelemetry.\n */\nexport class SentryLangChainInstrumentation extends InstrumentationBase<LangChainInstrumentationOptions> {\n public constructor(config: LangChainInstrumentationOptions = {}) {\n super('@sentry/instrumentation-langchain', SDK_VERSION, config);\n }\n\n /**\n * Initializes the instrumentation by defining the modules to be patched.\n * We patch the BaseChatModel class methods to inject callbacks\n *\n * We hook into provider packages (@langchain/anthropic, @langchain/openai, etc.)\n * because @langchain/core is often bundled and not loaded as a separate module\n */\n public init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {\n const modules: InstrumentationModuleDefinition[] = [];\n\n // Hook into common LangChain provider packages\n const providerPackages = [\n '@langchain/anthropic',\n '@langchain/openai',\n '@langchain/google-genai',\n '@langchain/mistralai',\n '@langchain/google-vertexai',\n '@langchain/groq',\n ];\n\n for (const packageName of providerPackages) {\n // In CJS, LangChain packages re-export from dist/index.cjs files.\n // Patching only the root module sometimes misses the real implementation or\n // gets overwritten when that file is loaded. We add a file-level patch so that\n // _patch runs again on the concrete implementation\n modules.push(\n new InstrumentationNodeModuleDefinition(\n packageName,\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n [\n new InstrumentationNodeModuleFile(\n `${packageName}/dist/index.cjs`,\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n ),\n ],\n ),\n );\n }\n\n // Hook into main 'langchain' package to catch initChatModel (v1+)\n modules.push(\n new InstrumentationNodeModuleDefinition(\n 'langchain',\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n [\n // To catch the CJS build that contains ConfigurableModel / initChatModel for v1\n new InstrumentationNodeModuleFile(\n 'langchain/dist/chat_models/universal.cjs',\n supportedVersions,\n this._patch.bind(this),\n exports => exports,\n ),\n ],\n ),\n );\n\n return modules;\n }\n\n /**\n * Core patch logic - patches chat model and embedding methods\n * This is called when a LangChain provider package is loaded\n */\n private _patch(exports: PatchedLangChainExports): PatchedLangChainExports | void {\n // Skip AI provider wrapping now that LangChain is actually being used\n // This prevents duplicate spans from Anthropic/OpenAI/GoogleGenAI standalone integrations\n _INTERNAL_skipAiProviderWrapping([\n OPENAI_INTEGRATION_NAME,\n ANTHROPIC_AI_INTEGRATION_NAME,\n GOOGLE_GENAI_INTEGRATION_NAME,\n ]);\n\n const config = this.getConfig();\n\n // Create a shared handler instance for chat model callbacks\n const sentryHandler = createLangChainCallbackHandler(config);\n\n // Patch Runnable methods to inject callbacks at request time\n // This directly manipulates options.callbacks that LangChain uses\n this._patchRunnableMethods(exports, sentryHandler);\n\n // Patch embedding methods to create spans directly\n // Embeddings don't use the callback system, so we wrap the methods themselves\n this._patchEmbeddingsMethods(exports, config);\n\n return exports;\n }\n\n /**\n * Patches chat model methods (invoke, stream, batch) to inject Sentry callbacks\n * Finds a chat model class from the provider package exports and patches its prototype methods\n */\n private _patchRunnableMethods(exports: PatchedLangChainExports, sentryHandler: unknown): void {\n // Known chat model class names for each provider\n const knownChatModelNames = [\n 'ChatAnthropic',\n 'ChatOpenAI',\n 'ChatGoogleGenerativeAI',\n 'ChatMistralAI',\n 'ChatVertexAI',\n 'ChatGroq',\n 'ConfigurableModel',\n ];\n\n const exportsToPatch = (exports.universal_exports ?? exports) as Record<string, unknown>;\n\n const chatModelClass = Object.values(exportsToPatch).find(exp => {\n return typeof exp === 'function' && knownChatModelNames.includes(exp.name);\n }) as { prototype: unknown; name: string } | undefined;\n\n if (!chatModelClass) {\n return;\n }\n\n // Patch directly on chatModelClass.prototype\n const targetProto = chatModelClass.prototype as Record<string, unknown>;\n\n // Skip if already patched (both file-level and module-level hooks resolve to the same prototype)\n if (targetProto.__sentry_patched__) {\n return;\n }\n targetProto.__sentry_patched__ = true;\n\n // Patch the methods (invoke, stream, batch)\n // All chat model instances will inherit these patched methods\n const methodsToPatch = ['invoke', 'stream', 'batch'] as const;\n\n for (const methodName of methodsToPatch) {\n const method = targetProto[methodName];\n if (typeof method === 'function') {\n targetProto[methodName] = wrapRunnableMethod(\n method as (...args: unknown[]) => unknown,\n sentryHandler,\n methodName,\n );\n }\n }\n }\n\n /**\n * Patches embedding class methods (embedQuery, embedDocuments) to create Sentry spans.\n *\n * Unlike chat models which use LangChain's callback system, the Embeddings base class\n * has no callback support. We wrap the methods directly on the prototype.\n *\n * Instruments any exported class whose prototype has both embedQuery and embedDocuments as functions.\n */\n private _patchEmbeddingsMethods(exports: PatchedLangChainExports, options: LangChainOptions): void {\n const exportsToPatch = (exports.universal_exports ?? exports) as Record<string, unknown>;\n\n for (const exp of Object.values(exportsToPatch)) {\n if (typeof exp !== 'function' || !exp.prototype) {\n continue;\n }\n const proto = exp.prototype as Record<string, unknown>;\n if (typeof proto.embedQuery !== 'function' || typeof proto.embedDocuments !== 'function') {\n continue;\n }\n if (proto.__sentry_patched__) {\n continue;\n }\n proto.__sentry_patched__ = true;\n\n instrumentLangChainEmbeddings(proto, options);\n }\n }\n}\n"],"names":[],"mappings":";;;;AAmBA,MAAM,iBAAA,GAAoB,CAAC,gBAAgB,CAAA;AAe3C,SAAS,kBAAA,CACP,cAAA,EACA,aAAA,EACA,WAAA,EACiC;AACjC,EAAA,OAAO,IAAI,MAAM,cAAA,EAAgB;AAAA,IAC/B,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAA0B;AAO/C,MAAA,MAAM,YAAA,GAAe,CAAA;AACrB,MAAA,IAAI,OAAA,GAAU,KAAK,YAAY,CAAA;AAG/B,MAAA,IAAI,CAAC,WAAW,OAAO,OAAA,KAAY,YAAY,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG;AACrE,QAAA,OAAA,GAAU,EAAC;AACX,QAAA,IAAA,CAAK,YAAY,CAAA,GAAI,OAAA;AAAA,MACvB;AAGA,MAAA,OAAA,CAAQ,SAAA,GAAY,uCAAA,CAAwC,OAAA,CAAQ,SAAA,EAAW,aAAa,CAAA;AAG5F,MAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,IAC5C;AAAA,GACD,CAAA;AACH;AAKO,MAAM,uCAAuC,mBAAA,CAAqD;AAAA,EAChG,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MAAA,GAAS,YAAY,UAAU,CAAA;AACrC,MAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,QAAA,WAAA,CAAY,UAAU,CAAA,GAAI,kBAAA;AAAA,UACxB,MAAA;AAAA,UACA,aAEF,CAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,uBAAA,CAAwB,SAAkC,OAAA,EAAiC;AACjG,IAAA,MAAM,cAAA,GAAkB,QAAQ,iBAAA,IAAqB,OAAA;AAErD,IAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,MAAA,CAAO,cAAc,CAAA,EAAG;AAC/C,MAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,IAAc,CAAC,IAAI,SAAA,EAAW;AAC/C,QAAA;AAAA,MACF;AACA,MAAA,MAAM,QAAQ,GAAA,CAAI,SAAA;AAClB,MAAA,IAAI,OAAO,KAAA,CAAM,UAAA,KAAe,cAAc,OAAO,KAAA,CAAM,mBAAmB,UAAA,EAAY;AACxF,QAAA;AAAA,MACF;AACA,MAAA,IAAI,MAAM,kBAAA,EAAoB;AAC5B,QAAA;AAAA,MACF;AACA,MAAA,KAAA,CAAM,kBAAA,GAAqB,IAAA;AAE3B,MAAA,6BAAA,CAA8B,OAAO,OAAO,CAAA;AAAA,IAC9C;AAAA,EACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/langgraph/index.ts"],"sourcesContent":["import type { IntegrationFn, LangGraphOptions } from '@sentry/core';\nimport { defineIntegration, LANGGRAPH_INTEGRATION_NAME } from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { SentryLangGraphInstrumentation } from './instrumentation';\n\nexport const instrumentLangGraph = generateInstrumentOnce<LangGraphOptions>(\n LANGGRAPH_INTEGRATION_NAME,\n options => new SentryLangGraphInstrumentation(options),\n);\n\nconst _langGraphIntegration = ((options: LangGraphOptions = {}) => {\n return {\n name: LANGGRAPH_INTEGRATION_NAME,\n setupOnce() {\n instrumentLangGraph(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for LangGraph.\n *\n * This integration is enabled by default.\n *\n * When configured, this integration automatically instruments LangGraph StateGraph and compiled graph instances\n * to capture telemetry data following OpenTelemetry Semantic Conventions for Generative AI.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/node';\n *\n * Sentry.init({\n * integrations: [Sentry.langGraphIntegration()],\n * });\n * ```\n *\n * ## Options\n *\n * - `recordInputs`: Whether to record input messages (default: respects `sendDefaultPii` client option)\n * - `recordOutputs`: Whether to record response text (default: respects `sendDefaultPii` client option)\n *\n * ### Default Behavior\n *\n * By default, the integration will:\n * - Record inputs and outputs ONLY if `sendDefaultPii` is set to `true` in your Sentry client options\n * - Otherwise, inputs and outputs are NOT recorded unless explicitly enabled\n *\n * @example\n * ```javascript\n * // Record inputs and outputs when sendDefaultPii is false\n * Sentry.init({\n * integrations: [\n * Sentry.langGraphIntegration({\n * recordInputs: true,\n * recordOutputs: true\n * })\n * ],\n * });\n *\n * // Never record inputs/outputs regardless of sendDefaultPii\n * Sentry.init({\n * sendDefaultPii: true,\n * integrations: [\n * Sentry.langGraphIntegration({\n * recordInputs: false,\n * recordOutputs: false\n * })\n * ],\n * });\n * ```\n *\n * ## Captured Operations\n *\n * The integration captures the following LangGraph operations:\n * - **Agent Creation** (`StateGraph.compile()`) - Creates a `gen_ai.create_agent` span\n * - **Agent Invocation** (`CompiledGraph.invoke()`) - Creates a `gen_ai.invoke_agent` span\n *\n * ## Captured Data\n *\n * When `recordInputs` and `recordOutputs` are enabled, the integration captures:\n * - Input messages from the graph state\n * - Output messages and LLM responses\n * - Tool calls made during agent execution\n * - Agent and graph names\n * - Available tools configured in the graph\n *\n */\nexport const langGraphIntegration = defineIntegration(_langGraphIntegration);\n"],"names":[],"mappings":";;;;AAKO,MAAM,mBAAA,GAAsB,sBAAA;AAAA,EACjC,0BAAA;AAAA,EACA,CAAA,OAAA,KAAW,IAAI,8BAAA,CAA+B,OAAO;AACvD;AAEA,MAAM,qBAAA,IAAyB,CAAC,OAAA,GAA4B,EAAC,KAAM;AACjE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,0BAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,mBAAA,CAAoB,OAAO,CAAA;AAAA,IAC7B;AAAA,GACF;AACF,CAAA,CAAA;AAsEO,MAAM,oBAAA,GAAuB,kBAAkB,qBAAqB;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/langgraph/index.ts"],"sourcesContent":["import type { IntegrationFn, LangGraphOptions } from '@sentry/core';\nimport { defineIntegration, LANGGRAPH_INTEGRATION_NAME } from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { SentryLangGraphInstrumentation } from './instrumentation';\n\nexport const instrumentLangGraph = generateInstrumentOnce<LangGraphOptions>(\n LANGGRAPH_INTEGRATION_NAME,\n options => new SentryLangGraphInstrumentation(options),\n);\n\nconst _langGraphIntegration = ((options: LangGraphOptions = {}) => {\n return {\n name: LANGGRAPH_INTEGRATION_NAME,\n setupOnce() {\n instrumentLangGraph(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for LangGraph.\n *\n * This integration is enabled by default.\n *\n * When configured, this integration automatically instruments LangGraph StateGraph and compiled graph instances\n * to capture telemetry data following OpenTelemetry Semantic Conventions for Generative AI.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/node';\n *\n * Sentry.init({\n * integrations: [Sentry.langGraphIntegration()],\n * });\n * ```\n *\n * ## Options\n *\n * - `recordInputs`: Whether to record prompt messages (default: follows `sendDefaultPii` or `dataCollection.genAI.inputs`)\n * - `recordOutputs`: Whether to record response text (default: follows `sendDefaultPii` or `dataCollection.genAI.outputs`)\n *\n * ### Default Behavior\n *\n * By default, the integration will:\n * - Record inputs and outputs based on `sendDefaultPii` or `dataCollection.genAI` in your Sentry client options\n * - Integration-level `recordInputs`/`recordOutputs` options take precedence over global config\n *\n * @example\n * ```javascript\n * // Always record inputs and outputs regardless of global dataCollection config\n * Sentry.init({\n * integrations: [\n * Sentry.langGraphIntegration({\n * recordInputs: true,\n * recordOutputs: true\n * })\n * ],\n * });\n *\n * // Never record inputs/outputs regardless of global dataCollection config\n * Sentry.init({\n * dataCollection: { genAI: { inputs: true, outputs: true } },\n * integrations: [\n * Sentry.langGraphIntegration({\n * recordInputs: false,\n * recordOutputs: false\n * })\n * ],\n * });\n * ```\n *\n * ## Captured Operations\n *\n * The integration captures the following LangGraph operations:\n * - **Agent Creation** (`StateGraph.compile()`) - Creates a `gen_ai.create_agent` span\n * - **Agent Invocation** (`CompiledGraph.invoke()`) - Creates a `gen_ai.invoke_agent` span\n *\n * ## Captured Data\n *\n * When `recordInputs` and `recordOutputs` are enabled, the integration captures:\n * - Input messages from the graph state\n * - Output messages and LLM responses\n * - Tool calls made during agent execution\n * - Agent and graph names\n * - Available tools configured in the graph\n *\n */\nexport const langGraphIntegration = defineIntegration(_langGraphIntegration);\n"],"names":[],"mappings":";;;;AAKO,MAAM,mBAAA,GAAsB,sBAAA;AAAA,EACjC,0BAAA;AAAA,EACA,CAAA,OAAA,KAAW,IAAI,8BAAA,CAA+B,OAAO;AACvD;AAEA,MAAM,qBAAA,IAAyB,CAAC,OAAA,GAA4B,EAAC,KAAM;AACjE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,0BAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,mBAAA,CAAoB,OAAO,CAAA;AAAA,IAC7B;AAAA,GACF;AACF,CAAA,CAAA;AAsEO,MAAM,oBAAA,GAAuB,kBAAkB,qBAAqB;;;;"}
@@ -1,4 +1,5 @@
1
- import { InstrumentationBase, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile } from '@opentelemetry/instrumentation';
1
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
2
+ import { InstrumentationNodeModuleFile } from '../InstrumentationNodeModuleFile.js';
2
3
  import { SDK_VERSION, getClient, instrumentLangGraph, instrumentCreateReactAgent } from '@sentry/core';
3
4
 
4
5
  const supportedVersions = [">=0.0.0 <2.0.0"];
@@ -67,10 +68,11 @@ class SentryLangGraphInstrumentation extends InstrumentationBase {
67
68
  */
68
69
  _patch(exports) {
69
70
  const client = getClient();
71
+ const genAI = client?.getDataCollectionOptions().genAI;
70
72
  const options = {
71
73
  ...this.getConfig(),
72
- recordInputs: this.getConfig().recordInputs ?? client?.getOptions().sendDefaultPii,
73
- recordOutputs: this.getConfig().recordOutputs ?? client?.getOptions().sendDefaultPii
74
+ recordInputs: this.getConfig().recordInputs ?? genAI?.inputs ?? false,
75
+ recordOutputs: this.getConfig().recordOutputs ?? genAI?.outputs ?? false
74
76
  };
75
77
  if (exports.StateGraph && typeof exports.StateGraph === "function") {
76
78
  instrumentLangGraph(exports.StateGraph.prototype, options);