@sentry/node 9.13.0 → 9.15.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 (140) hide show
  1. package/build/cjs/index.js +5 -2
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/cjs/integrations/anr/index.js +1 -1
  4. package/build/cjs/integrations/anr/index.js.map +1 -1
  5. package/build/cjs/integrations/context.js.map +1 -1
  6. package/build/cjs/integrations/contextlines.js.map +1 -1
  7. package/build/cjs/integrations/fs.js.map +1 -1
  8. package/build/cjs/integrations/http/SentryHttpInstrumentation.js +36 -37
  9. package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  10. package/build/cjs/integrations/http/SentryHttpInstrumentationBeforeOtel.js.map +1 -1
  11. package/build/cjs/integrations/http/vendor/getRequestInfo.js.map +1 -1
  12. package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  13. package/build/cjs/integrations/local-variables/local-variables-async.js.map +1 -1
  14. package/build/cjs/integrations/local-variables/local-variables-sync.js.map +1 -1
  15. package/build/cjs/integrations/node-fetch/SentryNodeFetchInstrumentation.js.map +1 -1
  16. package/build/cjs/integrations/node-fetch/index.js.map +1 -1
  17. package/build/cjs/integrations/tracing/amqplib.js.map +1 -1
  18. package/build/cjs/integrations/tracing/connect.js.map +1 -1
  19. package/build/cjs/integrations/tracing/dataloader.js.map +1 -1
  20. package/build/cjs/integrations/tracing/express-v5/instrumentation.js.map +1 -1
  21. package/build/cjs/integrations/tracing/express.js.map +1 -1
  22. package/build/cjs/integrations/tracing/fastify.js.map +1 -1
  23. package/build/cjs/integrations/tracing/genericPool.js.map +1 -1
  24. package/build/cjs/integrations/tracing/graphql.js.map +1 -1
  25. package/build/cjs/integrations/tracing/hapi/index.js.map +1 -1
  26. package/build/cjs/integrations/tracing/index.js.map +1 -1
  27. package/build/cjs/integrations/tracing/knex.js.map +1 -1
  28. package/build/cjs/integrations/tracing/koa.js.map +1 -1
  29. package/build/cjs/integrations/tracing/lrumemoizer.js.map +1 -1
  30. package/build/cjs/integrations/tracing/mongo.js.map +1 -1
  31. package/build/cjs/integrations/tracing/mongoose.js.map +1 -1
  32. package/build/cjs/integrations/tracing/mysql.js.map +1 -1
  33. package/build/cjs/integrations/tracing/mysql2.js.map +1 -1
  34. package/build/cjs/integrations/tracing/postgres.js.map +1 -1
  35. package/build/cjs/integrations/tracing/prisma.js.map +1 -1
  36. package/build/cjs/integrations/tracing/redis.js.map +1 -1
  37. package/build/cjs/integrations/tracing/tedious.js.map +1 -1
  38. package/build/cjs/integrations/tracing/vercelai/index.js +0 -2
  39. package/build/cjs/integrations/tracing/vercelai/index.js.map +1 -1
  40. package/build/cjs/integrations/tracing/vercelai/instrumentation.js +20 -7
  41. package/build/cjs/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  42. package/build/cjs/logs/capture.js.map +1 -1
  43. package/build/cjs/logs/exports.js.map +1 -1
  44. package/build/cjs/proxy/index.js.map +1 -1
  45. package/build/cjs/sdk/api.js.map +1 -1
  46. package/build/cjs/sdk/client.js.map +1 -1
  47. package/build/cjs/sdk/index.js.map +1 -1
  48. package/build/cjs/sdk/initOtel.js +2 -2
  49. package/build/cjs/sdk/initOtel.js.map +1 -1
  50. package/build/cjs/utils/addOriginToSpan.js.map +1 -1
  51. package/build/esm/index.js +3 -3
  52. package/build/esm/integrations/anr/index.js +1 -1
  53. package/build/esm/integrations/anr/index.js.map +1 -1
  54. package/build/esm/integrations/anr/worker-script.js +2 -2
  55. package/build/esm/integrations/context.js.map +1 -1
  56. package/build/esm/integrations/contextlines.js.map +1 -1
  57. package/build/esm/integrations/fs.js.map +1 -1
  58. package/build/esm/integrations/http/SentryHttpInstrumentation.js +36 -37
  59. package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
  60. package/build/esm/integrations/http/SentryHttpInstrumentationBeforeOtel.js.map +1 -1
  61. package/build/esm/integrations/http/vendor/getRequestInfo.js.map +1 -1
  62. package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  63. package/build/esm/integrations/local-variables/local-variables-async.js.map +1 -1
  64. package/build/esm/integrations/local-variables/local-variables-sync.js.map +1 -1
  65. package/build/esm/integrations/local-variables/worker-script.js +2 -2
  66. package/build/esm/integrations/node-fetch/SentryNodeFetchInstrumentation.js.map +1 -1
  67. package/build/esm/integrations/node-fetch/index.js.map +1 -1
  68. package/build/esm/integrations/tracing/amqplib.js.map +1 -1
  69. package/build/esm/integrations/tracing/connect.js.map +1 -1
  70. package/build/esm/integrations/tracing/dataloader.js.map +1 -1
  71. package/build/esm/integrations/tracing/express-v5/instrumentation.js.map +1 -1
  72. package/build/esm/integrations/tracing/express.js.map +1 -1
  73. package/build/esm/integrations/tracing/fastify.js.map +1 -1
  74. package/build/esm/integrations/tracing/genericPool.js.map +1 -1
  75. package/build/esm/integrations/tracing/graphql.js.map +1 -1
  76. package/build/esm/integrations/tracing/hapi/index.js.map +1 -1
  77. package/build/esm/integrations/tracing/index.js.map +1 -1
  78. package/build/esm/integrations/tracing/knex.js.map +1 -1
  79. package/build/esm/integrations/tracing/koa.js.map +1 -1
  80. package/build/esm/integrations/tracing/lrumemoizer.js.map +1 -1
  81. package/build/esm/integrations/tracing/mongo.js.map +1 -1
  82. package/build/esm/integrations/tracing/mongoose.js.map +1 -1
  83. package/build/esm/integrations/tracing/mysql.js.map +1 -1
  84. package/build/esm/integrations/tracing/mysql2.js.map +1 -1
  85. package/build/esm/integrations/tracing/postgres.js.map +1 -1
  86. package/build/esm/integrations/tracing/prisma.js.map +1 -1
  87. package/build/esm/integrations/tracing/redis.js.map +1 -1
  88. package/build/esm/integrations/tracing/tedious.js.map +1 -1
  89. package/build/esm/integrations/tracing/vercelai/index.js +0 -2
  90. package/build/esm/integrations/tracing/vercelai/index.js.map +1 -1
  91. package/build/esm/integrations/tracing/vercelai/instrumentation.js +20 -7
  92. package/build/esm/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  93. package/build/esm/logs/capture.js.map +1 -1
  94. package/build/esm/logs/exports.js.map +1 -1
  95. package/build/esm/package.json +1 -1
  96. package/build/esm/proxy/index.js.map +1 -1
  97. package/build/esm/sdk/api.js.map +1 -1
  98. package/build/esm/sdk/client.js.map +1 -1
  99. package/build/esm/sdk/index.js.map +1 -1
  100. package/build/esm/sdk/initOtel.js +2 -2
  101. package/build/esm/sdk/initOtel.js.map +1 -1
  102. package/build/esm/utils/addOriginToSpan.js.map +1 -1
  103. package/build/types/index.d.ts +2 -2
  104. package/build/types/index.d.ts.map +1 -1
  105. package/build/types/integrations/context.d.ts +1 -1
  106. package/build/types/integrations/context.d.ts.map +1 -1
  107. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +2 -2
  108. package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
  109. package/build/types/integrations/http/SentryHttpInstrumentationBeforeOtel.d.ts.map +1 -1
  110. package/build/types/integrations/http/vendor/getRequestInfo.d.ts +1 -1
  111. package/build/types/integrations/http/vendor/getRequestInfo.d.ts.map +1 -1
  112. package/build/types/integrations/node-fetch/SentryNodeFetchInstrumentation.d.ts.map +1 -1
  113. package/build/types/integrations/tracing/amqplib.d.ts.map +1 -1
  114. package/build/types/integrations/tracing/graphql.d.ts.map +1 -1
  115. package/build/types/integrations/tracing/index.d.ts.map +1 -1
  116. package/build/types/integrations/tracing/lrumemoizer.d.ts.map +1 -1
  117. package/build/types/integrations/tracing/mongo.d.ts.map +1 -1
  118. package/build/types/integrations/tracing/mongoose.d.ts.map +1 -1
  119. package/build/types/integrations/tracing/mysql2.d.ts.map +1 -1
  120. package/build/types/integrations/tracing/postgres.d.ts.map +1 -1
  121. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts +1 -1
  122. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts.map +1 -1
  123. package/build/types/logs/capture.d.ts +1 -1
  124. package/build/types/logs/capture.d.ts.map +1 -1
  125. package/build/types/logs/exports.d.ts.map +1 -1
  126. package/build/types/proxy/index.d.ts +1 -1
  127. package/build/types/proxy/index.d.ts.map +1 -1
  128. package/build/types/sdk/client.d.ts.map +1 -1
  129. package/build/types/sdk/initOtel.d.ts.map +1 -1
  130. package/build/types/types.d.ts.map +1 -1
  131. package/build/types/utils/addOriginToSpan.d.ts.map +1 -1
  132. package/build/types/utils/prepareEvent.d.ts.map +1 -1
  133. package/build/types-ts3.8/index.d.ts +2 -2
  134. package/build/types-ts3.8/integrations/context.d.ts +1 -1
  135. package/build/types-ts3.8/integrations/http/SentryHttpInstrumentation.d.ts +2 -2
  136. package/build/types-ts3.8/integrations/http/vendor/getRequestInfo.d.ts +1 -1
  137. package/build/types-ts3.8/integrations/tracing/vercelai/instrumentation.d.ts +1 -1
  138. package/build/types-ts3.8/logs/capture.d.ts +1 -1
  139. package/build/types-ts3.8/proxy/index.d.ts +1 -1
  140. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/integrations/anr/index.ts"],"sourcesContent":["import { types } from 'node:util';\nimport { Worker } from 'node:worker_threads';\nimport type { Contexts, Event, EventHint, Integration, IntegrationFn, ScopeData } from '@sentry/core';\nimport {\n GLOBAL_OBJ,\n defineIntegration,\n getClient,\n getCurrentScope,\n getFilenameToDebugIdMap,\n getGlobalScope,\n getIsolationScope,\n logger,\n mergeScopeData,\n} from '@sentry/core';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport type { NodeClient } from '../../sdk/client';\nimport { isDebuggerEnabled } from '../../utils/debug';\nimport type { AnrIntegrationOptions, WorkerStartData } from './common';\n\nconst { isPromise } = types;\n\n// This string is a placeholder that gets overwritten with the worker code.\nexport const base64WorkerScript = '###AnrWorkerScript###';\n\nconst DEFAULT_INTERVAL = 50;\nconst DEFAULT_HANG_THRESHOLD = 5000;\n\nfunction log(message: string, ...args: unknown[]): void {\n logger.log(`[ANR] ${message}`, ...args);\n}\n\nfunction globalWithScopeFetchFn(): typeof GLOBAL_OBJ & { __SENTRY_GET_SCOPES__?: () => ScopeData } {\n return GLOBAL_OBJ;\n}\n\n/** Fetches merged scope data */\nfunction getScopeData(): ScopeData {\n const scope = getGlobalScope().getScopeData();\n mergeScopeData(scope, getIsolationScope().getScopeData());\n mergeScopeData(scope, getCurrentScope().getScopeData());\n\n // We remove attachments because they likely won't serialize well as json\n scope.attachments = [];\n // We can't serialize event processor functions\n scope.eventProcessors = [];\n\n return scope;\n}\n\n/**\n * Gets contexts by calling all event processors. This shouldn't be called until all integrations are setup\n */\nasync function getContexts(client: NodeClient): Promise<Contexts> {\n let event: Event | null = { message: 'ANR' };\n const eventHint: EventHint = {};\n\n for (const processor of client.getEventProcessors()) {\n if (event === null) break;\n event = await processor(event, eventHint);\n }\n\n return event?.contexts || {};\n}\n\nconst INTEGRATION_NAME = 'Anr';\n\ntype AnrInternal = { startWorker: () => void; stopWorker: () => void };\n\nconst _anrIntegration = ((options: Partial<AnrIntegrationOptions> = {}) => {\n if (NODE_VERSION.major < 16 || (NODE_VERSION.major === 16 && NODE_VERSION.minor < 17)) {\n throw new Error('ANR detection requires Node 16.17.0 or later');\n }\n\n let worker: Promise<() => void> | undefined;\n let client: NodeClient | undefined;\n\n // Hookup the scope fetch function to the global object so that it can be called from the worker thread via the\n // debugger when it pauses\n const gbl = globalWithScopeFetchFn();\n gbl.__SENTRY_GET_SCOPES__ = getScopeData;\n\n return {\n name: INTEGRATION_NAME,\n startWorker: () => {\n if (worker) {\n return;\n }\n\n if (client) {\n worker = _startWorker(client, options);\n }\n },\n stopWorker: () => {\n if (worker) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.then(stop => {\n stop();\n worker = undefined;\n });\n }\n },\n async setup(initClient: NodeClient) {\n client = initClient;\n\n if (options.captureStackTrace && (await isDebuggerEnabled())) {\n logger.warn('ANR captureStackTrace has been disabled because the debugger was already enabled');\n options.captureStackTrace = false;\n }\n\n // setImmediate is used to ensure that all other integrations have had their setup called first.\n // This allows us to call into all integrations to fetch the full context\n setImmediate(() => this.startWorker());\n },\n } as Integration & AnrInternal;\n}) satisfies IntegrationFn;\n\ntype AnrReturn = (options?: Partial<AnrIntegrationOptions>) => Integration & AnrInternal;\n\nexport const anrIntegration = defineIntegration(_anrIntegration) as AnrReturn;\n\n/**\n * Starts the ANR worker thread\n *\n * @returns A function to stop the worker\n */\nasync function _startWorker(\n client: NodeClient,\n integrationOptions: Partial<AnrIntegrationOptions>,\n): Promise<() => void> {\n const dsn = client.getDsn();\n\n if (!dsn) {\n return () => {\n //\n };\n }\n\n const contexts = await getContexts(client);\n\n // These will not be accurate if sent later from the worker thread\n delete contexts.app?.app_memory;\n delete contexts.device?.free_memory;\n\n const initOptions = client.getOptions();\n\n const sdkMetadata = client.getSdkMetadata() || {};\n if (sdkMetadata.sdk) {\n sdkMetadata.sdk.integrations = initOptions.integrations.map(i => i.name);\n }\n\n const options: WorkerStartData = {\n debug: logger.isEnabled(),\n dsn,\n tunnel: initOptions.tunnel,\n environment: initOptions.environment || 'production',\n release: initOptions.release,\n dist: initOptions.dist,\n sdkMetadata,\n appRootPath: integrationOptions.appRootPath,\n pollInterval: integrationOptions.pollInterval || DEFAULT_INTERVAL,\n anrThreshold: integrationOptions.anrThreshold || DEFAULT_HANG_THRESHOLD,\n captureStackTrace: !!integrationOptions.captureStackTrace,\n maxAnrEvents: integrationOptions.maxAnrEvents || 1,\n staticTags: integrationOptions.staticTags || {},\n contexts,\n };\n\n if (options.captureStackTrace) {\n const inspector = await import('node:inspector');\n if (!inspector.url()) {\n inspector.open(0);\n }\n }\n\n const worker = new Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), {\n workerData: options,\n // We don't want any Node args to be passed to the worker\n execArgv: [],\n env: { ...process.env, NODE_OPTIONS: undefined },\n });\n\n process.on('exit', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n });\n\n const timer = setInterval(() => {\n try {\n const currentSession = getIsolationScope().getSession();\n // We need to copy the session object and remove the toJSON method so it can be sent to the worker\n // serialized without making it a SerializedSession\n const session = currentSession ? { ...currentSession, toJSON: undefined } : undefined;\n // message the worker to tell it the main event loop is still running\n worker.postMessage({ session, debugImages: getFilenameToDebugIdMap(initOptions.stackParser) });\n } catch (_) {\n //\n }\n }, options.pollInterval);\n // Timer should not block exit\n timer.unref();\n\n worker.on('message', (msg: string) => {\n if (msg === 'session-ended') {\n log('ANR event sent from ANR worker. Clearing session in this thread.');\n getIsolationScope().setSession(undefined);\n }\n });\n\n worker.once('error', (err: Error) => {\n clearInterval(timer);\n log('ANR worker error', err);\n });\n\n worker.once('exit', (code: number) => {\n clearInterval(timer);\n log('ANR worker exit', code);\n });\n\n // Ensure this thread can't block app exit\n worker.unref();\n\n return () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n clearInterval(timer);\n };\n}\n\nexport function disableAnrDetectionForCallback<T>(callback: () => T): T;\nexport function disableAnrDetectionForCallback<T>(callback: () => Promise<T>): Promise<T>;\n/**\n * Disables ANR detection for the duration of the callback\n */\nexport function disableAnrDetectionForCallback<T>(callback: () => T | Promise<T>): T | Promise<T> {\n const integration = getClient()?.getIntegrationByName(INTEGRATION_NAME) as AnrInternal | undefined;\n\n if (!integration) {\n return callback();\n }\n\n integration.stopWorker();\n\n const result = callback();\n if (isPromise(result)) {\n return result.finally(() => integration.startWorker());\n }\n\n integration.startWorker();\n return result;\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,EAAE,SAAA,EAAY,GAAE,KAAK;;AAE3B;AACO,MAAM,kBAAmB,GAAE;;AAElC,MAAM,gBAAA,GAAmB,EAAE;AAC3B,MAAM,sBAAA,GAAyB,IAAI;;AAEnC,SAAS,GAAG,CAAC,OAAO,EAAU,GAAG,IAAI,EAAmB;AACxD,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA,EAAA,GAAA,IAAA,CAAA;AACA;;AAEA,SAAA,sBAAA,GAAA;AACA,EAAA,OAAA,UAAA;AACA;;AAEA;AACA,SAAA,YAAA,GAAA;A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AAEA,EAAA,OAAA,MAAA;AACA;AACA,IAAA,MAAA,CAAA,SAAA,EAAA;AACA,IAAA,aAAA,CAAA,KAAA,CAAA;AACA,GAAA;AACA;;AAIA;AACA;AACA;AACA,SAAA,8BAAA,CAAA,QAAA,EAAA;AACA,EAAA,MAAA,WAAA,GAAA,SAAA,EAAA,EAAA,oBAAA,CAAA,gBAAA,CAAA;;AAEA,EAAA,IAAA,CAAA,WAAA,EAAA;AACA,IAAA,OAAA,QAAA,EAAA;AACA;;AAEA,EAAA,WAAA,CAAA,UAAA,EAAA;;AAEA,EAAA,MAAA,MAAA,GAAA,QAAA,EAAA;AACA,EAAA,IAAA,SAAA,CAAA,MAAA,CAAA,EAAA;AACA,IAAA,OAAA,MAAA,CAAA,OAAA,CAAA,MAAA,WAAA,CAAA,WAAA,EAAA,CAAA;AACA;;AAEA,EAAA,WAAA,CAAA,WAAA,EAAA;AACA,EAAA,OAAA,MAAA;AACA;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/integrations/anr/index.ts"],"sourcesContent":["import { types } from 'node:util';\nimport { Worker } from 'node:worker_threads';\nimport type { Contexts, Event, EventHint, Integration, IntegrationFn, ScopeData } from '@sentry/core';\nimport {\n defineIntegration,\n getClient,\n getCurrentScope,\n getFilenameToDebugIdMap,\n getGlobalScope,\n getIsolationScope,\n GLOBAL_OBJ,\n logger,\n mergeScopeData,\n} from '@sentry/core';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport type { NodeClient } from '../../sdk/client';\nimport { isDebuggerEnabled } from '../../utils/debug';\nimport type { AnrIntegrationOptions, WorkerStartData } from './common';\n\nconst { isPromise } = types;\n\n// This string is a placeholder that gets overwritten with the worker code.\nexport const base64WorkerScript = '###AnrWorkerScript###';\n\nconst DEFAULT_INTERVAL = 50;\nconst DEFAULT_HANG_THRESHOLD = 5000;\n\nfunction log(message: string, ...args: unknown[]): void {\n logger.log(`[ANR] ${message}`, ...args);\n}\n\nfunction globalWithScopeFetchFn(): typeof GLOBAL_OBJ & { __SENTRY_GET_SCOPES__?: () => ScopeData } {\n return GLOBAL_OBJ;\n}\n\n/** Fetches merged scope data */\nfunction getScopeData(): ScopeData {\n const scope = getGlobalScope().getScopeData();\n mergeScopeData(scope, getIsolationScope().getScopeData());\n mergeScopeData(scope, getCurrentScope().getScopeData());\n\n // We remove attachments because they likely won't serialize well as json\n scope.attachments = [];\n // We can't serialize event processor functions\n scope.eventProcessors = [];\n\n return scope;\n}\n\n/**\n * Gets contexts by calling all event processors. This shouldn't be called until all integrations are setup\n */\nasync function getContexts(client: NodeClient): Promise<Contexts> {\n let event: Event | null = { message: 'ANR' };\n const eventHint: EventHint = {};\n\n for (const processor of client.getEventProcessors()) {\n if (event === null) break;\n event = await processor(event, eventHint);\n }\n\n return event?.contexts || {};\n}\n\nconst INTEGRATION_NAME = 'Anr';\n\ntype AnrInternal = { startWorker: () => void; stopWorker: () => void };\n\nconst _anrIntegration = ((options: Partial<AnrIntegrationOptions> = {}) => {\n if (NODE_VERSION.major < 16 || (NODE_VERSION.major === 16 && NODE_VERSION.minor < 17)) {\n throw new Error('ANR detection requires Node 16.17.0 or later');\n }\n\n let worker: Promise<() => void> | undefined;\n let client: NodeClient | undefined;\n\n // Hookup the scope fetch function to the global object so that it can be called from the worker thread via the\n // debugger when it pauses\n const gbl = globalWithScopeFetchFn();\n gbl.__SENTRY_GET_SCOPES__ = getScopeData;\n\n return {\n name: INTEGRATION_NAME,\n startWorker: () => {\n if (worker) {\n return;\n }\n\n if (client) {\n worker = _startWorker(client, options);\n }\n },\n stopWorker: () => {\n if (worker) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.then(stop => {\n stop();\n worker = undefined;\n });\n }\n },\n async setup(initClient: NodeClient) {\n client = initClient;\n\n if (options.captureStackTrace && (await isDebuggerEnabled())) {\n logger.warn('ANR captureStackTrace has been disabled because the debugger was already enabled');\n options.captureStackTrace = false;\n }\n\n // setImmediate is used to ensure that all other integrations have had their setup called first.\n // This allows us to call into all integrations to fetch the full context\n setImmediate(() => this.startWorker());\n },\n } as Integration & AnrInternal;\n}) satisfies IntegrationFn;\n\ntype AnrReturn = (options?: Partial<AnrIntegrationOptions>) => Integration & AnrInternal;\n\nexport const anrIntegration = defineIntegration(_anrIntegration) as AnrReturn;\n\n/**\n * Starts the ANR worker thread\n *\n * @returns A function to stop the worker\n */\nasync function _startWorker(\n client: NodeClient,\n integrationOptions: Partial<AnrIntegrationOptions>,\n): Promise<() => void> {\n const dsn = client.getDsn();\n\n if (!dsn) {\n return () => {\n //\n };\n }\n\n const contexts = await getContexts(client);\n\n // These will not be accurate if sent later from the worker thread\n delete contexts.app?.app_memory;\n delete contexts.device?.free_memory;\n\n const initOptions = client.getOptions();\n\n const sdkMetadata = client.getSdkMetadata() || {};\n if (sdkMetadata.sdk) {\n sdkMetadata.sdk.integrations = initOptions.integrations.map(i => i.name);\n }\n\n const options: WorkerStartData = {\n debug: logger.isEnabled(),\n dsn,\n tunnel: initOptions.tunnel,\n environment: initOptions.environment || 'production',\n release: initOptions.release,\n dist: initOptions.dist,\n sdkMetadata,\n appRootPath: integrationOptions.appRootPath,\n pollInterval: integrationOptions.pollInterval || DEFAULT_INTERVAL,\n anrThreshold: integrationOptions.anrThreshold || DEFAULT_HANG_THRESHOLD,\n captureStackTrace: !!integrationOptions.captureStackTrace,\n maxAnrEvents: integrationOptions.maxAnrEvents || 1,\n staticTags: integrationOptions.staticTags || {},\n contexts,\n };\n\n if (options.captureStackTrace) {\n const inspector = await import('node:inspector');\n if (!inspector.url()) {\n inspector.open(0);\n }\n }\n\n const worker = new Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), {\n workerData: options,\n // We don't want any Node args to be passed to the worker\n execArgv: [],\n env: { ...process.env, NODE_OPTIONS: undefined },\n });\n\n process.on('exit', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n });\n\n const timer = setInterval(() => {\n try {\n const currentSession = getIsolationScope().getSession();\n // We need to copy the session object and remove the toJSON method so it can be sent to the worker\n // serialized without making it a SerializedSession\n const session = currentSession ? { ...currentSession, toJSON: undefined } : undefined;\n // message the worker to tell it the main event loop is still running\n worker.postMessage({ session, debugImages: getFilenameToDebugIdMap(initOptions.stackParser) });\n } catch (_) {\n //\n }\n }, options.pollInterval);\n // Timer should not block exit\n timer.unref();\n\n worker.on('message', (msg: string) => {\n if (msg === 'session-ended') {\n log('ANR event sent from ANR worker. Clearing session in this thread.');\n getIsolationScope().setSession(undefined);\n }\n });\n\n worker.once('error', (err: Error) => {\n clearInterval(timer);\n log('ANR worker error', err);\n });\n\n worker.once('exit', (code: number) => {\n clearInterval(timer);\n log('ANR worker exit', code);\n });\n\n // Ensure this thread can't block app exit\n worker.unref();\n\n return () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n clearInterval(timer);\n };\n}\n\nexport function disableAnrDetectionForCallback<T>(callback: () => T): T;\nexport function disableAnrDetectionForCallback<T>(callback: () => Promise<T>): Promise<T>;\n/**\n * Disables ANR detection for the duration of the callback\n */\nexport function disableAnrDetectionForCallback<T>(callback: () => T | Promise<T>): T | Promise<T> {\n const integration = getClient()?.getIntegrationByName(INTEGRATION_NAME) as AnrInternal | undefined;\n\n if (!integration) {\n return callback();\n }\n\n integration.stopWorker();\n\n const result = callback();\n if (isPromise(result)) {\n return result.finally(() => integration.startWorker());\n }\n\n integration.startWorker();\n return result;\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,EAAE,SAAA,EAAY,GAAE,KAAK;;AAE3B;AACO,MAAM,kBAAmB,GAAE;;AAElC,MAAM,gBAAA,GAAmB,EAAE;AAC3B,MAAM,sBAAA,GAAyB,IAAI;;AAEnC,SAAS,GAAG,CAAC,OAAO,EAAU,GAAG,IAAI,EAAmB;AACxD,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA,EAAA,GAAA,IAAA,CAAA;AACA;;AAEA,SAAA,sBAAA,GAAA;A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A,GAAA,CAAA;;AAEA;AACA,EAAA,MAAA,CAAA,KAAA,EAAA;;AAEA,EAAA,OAAA,MAAA;AACA;AACA,IAAA,MAAA,CAAA,SAAA,EAAA;AACA,IAAA,aAAA,CAAA,KAAA,CAAA;AACA,GAAA;AACA;;AAIA;AACA;AACA;AACA,SAAA,8BAAA,CAAA,QAAA,EAAA;AACA,EAAA,MAAA,WAAA,GAAA,SAAA,EAAA,EAAA,oBAAA,CAAA,gBAAA,CAAA;;AAEA,EAAA,IAAA,CAAA,WAAA,EAAA;AACA,IAAA,OAAA,QAAA,EAAA;AACA;;AAEA,EAAA,WAAA,CAAA,UAAA,EAAA;;AAEA,EAAA,MAAA,MAAA,GAAA,QAAA,EAAA;AACA,EAAA,IAAA,SAAA,CAAA,MAAA,CAAA,EAAA;AACA,IAAA,OAAA,MAAA,CAAA,OAAA,CAAA,MAAA,WAAA,CAAA,WAAA,EAAA,CAAA;AACA;;AAEA,EAAA,WAAA,CAAA,WAAA,EAAA;AACA,EAAA,OAAA,MAAA;AACA;;;;"}
@@ -1,2 +1,2 @@
1
- /*! @sentry/node 9.13.0 (6e775c6) | https://github.com/getsentry/sentry-javascript */
2
- import{Session as t}from"node:inspector";import{workerData as n,parentPort as e}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,p=globalThis,l="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,d="9.13.0";function m(){return g(p),p}function g(t){const n=t.__SENTRY__=t.__SENTRY__||{};return n.version=n.version||d,n[d]=n[d]||{}}function y(t,n,e=p){const r=e.__SENTRY__=e.__SENTRY__||{},o=r[d]=r[d]||{};return o[t]||(o[t]=n())}const b=["debug","info","warn","error","log","assert","trace"],_={};function v(t){if(!("console"in p))return t();const n=p.console,e={},r=Object.keys(_);r.forEach((t=>{const r=_[t];e[t]=n[t],n[t]=r}));try{return t()}finally{r.forEach((t=>{n[t]=e[t]}))}}const w=y("logger",(function(){let t=!1;const n={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return l?b.forEach((e=>{n[e]=(...n)=>{t&&v((()=>{p.console[e](`Sentry Logger [${e}]:`,...n)}))}})):b.forEach((t=>{n[t]=()=>{}})),n})),S=50,$="?",E=/captureMessage|captureException/;function x(t){return t[t.length-1]||{}}const N="<anonymous>";const T=1e3;function C(){return Date.now()/T}const R=function(){const{performance:t}=p;if(!t?.now)return C;const n=Date.now()-t.now(),e=null==t.timeOrigin?n:t.timeOrigin;return()=>(e+t.now())/T}(),k=Object.prototype.toString;function j(t,n){return k.call(t)===`[object ${n}]`}function D(t){return j(t,"String")}function I(t){return j(t,"Object")}function O(t){return Boolean(t?.then&&"function"==typeof t.then)}function A(t,n){try{return t instanceof n}catch(t){return!1}}const P=p,U=80;function M(t,n){const e=t,r=[];if(!e?.tagName)return"";if(P.HTMLElement&&e instanceof HTMLElement&&e.dataset){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}r.push(e.tagName.toLowerCase());const o=n?.length?n.filter((t=>e.getAttribute(t))).map((t=>[t,e.getAttribute(t)])):null;if(o?.length)o.forEach((t=>{r.push(`[${t[0]}="${t[1]}"]`)}));else{e.id&&r.push(`#${e.id}`);const t=e.className;if(t&&D(t)){const n=t.split(/\s+/);for(const t of n)r.push(`.${t}`)}}const s=["aria-label","type","name","title","alt"];for(const t of s){const n=e.getAttribute(t);n&&r.push(`[${t}="${n}"]`)}return r.join("")}function L(t,n=0){return"string"!=typeof t||0===n||t.length<=n?t:`${t.slice(0,n)}...`}function B(t){if(function(t){switch(k.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return A(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...J(t)};if(n=t,"undefined"!=typeof Event&&A(n,Event)){const n={type:t.type,target:G(t.target),currentTarget:G(t.currentTarget),...J(t)};return"undefined"!=typeof CustomEvent&&A(t,CustomEvent)&&(n.detail=t.detail),n}return t;var n}function G(t){try{return n=t,"undefined"!=typeof Element&&A(n,Element)?function(t,n={}){if(!t)return"<unknown>";try{let e=t;const r=5,o=[];let s=0,i=0;const c=" > ",u=c.length;let a;const f=Array.isArray(n)?n:n.keyAttrs,h=!Array.isArray(n)&&n.maxStringLength||U;for(;e&&s++<r&&(a=M(e,f),!("html"===a||s>1&&i+o.length*u+a.length>=h));)o.push(a),i+=a.length,e=e.parentNode;return o.reverse().join(c)}catch(t){return"<unknown>"}}(t):Object.prototype.toString.call(t)}catch(t){return"<unknown>"}var n}function J(t){if("object"==typeof t&&null!==t){const n={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}return{}}function Y(t=function(){const t=p;return t.crypto||t.msCrypto}()){let n=()=>16*Math.random();try{if(t?.randomUUID)return t.randomUUID().replace(/-/g,"");t?.getRandomValues&&(n=()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&n())>>t/4).toString(16)))}var z;function H(t){return new F((n=>{n(t)}))}!function(t){t[t.PENDING=0]="PENDING";t[t.RESOLVED=1]="RESOLVED";t[t.REJECTED=2]="REJECTED"}(z||(z={}));class F{constructor(t){this.t=z.PENDING,this.o=[],this.i(t)}then(t,n){return new F(((e,r)=>{this.o.push([!1,n=>{if(t)try{e(t(n))}catch(t){r(t)}else e(n)},t=>{if(n)try{e(n(t))}catch(t){r(t)}else r(t)}]),this.u()}))}catch(t){return this.then((t=>t),t)}finally(t){return new F(((n,e)=>{let r,o;return this.then((n=>{o=!1,r=n,t&&t()}),(n=>{o=!0,r=n,t&&t()})).then((()=>{o?e(r):n(r)}))}))}u(){if(this.t===z.PENDING)return;const t=this.o.slice();this.o=[],t.forEach((t=>{t[0]||(this.t===z.RESOLVED&&t[1](this.h),this.t===z.REJECTED&&t[2](this.h),t[0]=!0)}))}i(t){const n=(t,n)=>{this.t===z.PENDING&&(O(n)?n.then(e,r):(this.t=t,this.h=n,this.u()))},e=t=>{n(z.RESOLVED,t)},r=t=>{n(z.REJECTED,t)};try{t(e,r)}catch(t){r(t)}}}function W(t){const n=R(),e={sid:Y(),init:!0,timestamp:n,started:n,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}(e)};return t&&K(e,t),e}function K(t,n={}){if(n.user&&(!t.ipAddress&&n.user.ip_address&&(t.ipAddress=n.user.ip_address),t.did||n.did||(t.did=n.user.id||n.user.email||n.user.username)),t.timestamp=n.timestamp||R(),n.abnormal_mechanism&&(t.abnormal_mechanism=n.abnormal_mechanism),n.ignoreDuration&&(t.ignoreDuration=n.ignoreDuration),n.sid&&(t.sid=32===n.sid.length?n.sid:Y()),void 0!==n.init&&(t.init=n.init),!t.did&&n.did&&(t.did=`${n.did}`),"number"==typeof n.started&&(t.started=n.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof n.duration)t.duration=n.duration;else{const n=t.timestamp-t.started;t.duration=n>=0?n:0}n.release&&(t.release=n.release),n.environment&&(t.environment=n.environment),!t.ipAddress&&n.ipAddress&&(t.ipAddress=n.ipAddress),!t.userAgent&&n.userAgent&&(t.userAgent=n.userAgent),"number"==typeof n.errors&&(t.errors=n.errors),n.status&&(t.status=n.status)}function V(){return Y()}function Z(){return Y().substring(16)}function q(t,n,e=2){if(!n||"object"!=typeof n||e<=0)return n;if(t&&0===Object.keys(n).length)return t;const r={...t};for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=q(r[t],n[t],e-1));return r}const Q="_sentrySpan";function X(t,n){n?function(t,n,e){try{Object.defineProperty(t,n,{value:e,writable:!0,configurable:!0})}catch(e){l&&w.log(`Failed to add non-enumerable property "${n}" to object`,t)}}(t,Q,n):delete t[Q]}function tt(t){return t[Q]}class nt{constructor(){this.p=!1,this.l=[],this.m=[],this._=[],this.v=[],this.S={},this.N={},this.T={},this.C={},this.R={},this.k={traceId:V(),sampleRand:Math.random()}}clone(){const t=new nt;return t._=[...this._],t.N={...this.N},t.T={...this.T},t.C={...this.C},this.C.flags&&(t.C.flags={values:[...this.C.flags.values]}),t.S=this.S,t.j=this.j,t.D=this.D,t.I=this.I,t.O=this.O,t.m=[...this.m],t.v=[...this.v],t.R={...this.R},t.k={...this.k},t.A=this.A,t.P=this.P,X(t,tt(this)),t}setClient(t){this.A=t}setLastEventId(t){this.P=t}getClient(){return this.A}lastEventId(){return this.P}addScopeListener(t){this.l.push(t)}addEventProcessor(t){return this.m.push(t),this}setUser(t){return this.S=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.D&&K(this.D,{user:t}),this.U(),this}getUser(){return this.S}setTags(t){return this.N={...this.N,...t},this.U(),this}setTag(t,n){return this.N={...this.N,[t]:n},this.U(),this}setExtras(t){return this.T={...this.T,...t},this.U(),this}setExtra(t,n){return this.T={...this.T,[t]:n},this.U(),this}setFingerprint(t){return this.O=t,this.U(),this}setLevel(t){return this.j=t,this.U(),this}setTransactionName(t){return this.I=t,this.U(),this}setContext(t,n){return null===n?delete this.C[t]:this.C[t]=n,this.U(),this}setSession(t){return t?this.D=t:delete this.D,this.U(),this}getSession(){return this.D}update(t){if(!t)return this;const n="function"==typeof t?t(this):t,e=n instanceof nt?n.getScopeData():I(n)?t:void 0,{tags:r,extra:o,user:s,contexts:i,level:c,fingerprint:u=[],propagationContext:a}=e||{};return this.N={...this.N,...r},this.T={...this.T,...o},this.C={...this.C,...i},s&&Object.keys(s).length&&(this.S=s),c&&(this.j=c),u.length&&(this.O=u),a&&(this.k=a),this}clear(){return this._=[],this.N={},this.T={},this.S={},this.C={},this.j=void 0,this.I=void 0,this.O=void 0,this.D=void 0,X(this,void 0),this.v=[],this.setPropagationContext({traceId:V(),sampleRand:Math.random()}),this.U(),this}addBreadcrumb(t,n){const e="number"==typeof n?n:100;if(e<=0)return this;const r={timestamp:C(),...t,message:t.message?L(t.message,2048):t.message};return this._.push(r),this._.length>e&&(this._=this._.slice(-e),this.A?.recordDroppedEvent("buffer_overflow","log_item")),this.U(),this}getLastBreadcrumb(){return this._[this._.length-1]}clearBreadcrumbs(){return this._=[],this.U(),this}addAttachment(t){return this.v.push(t),this}clearAttachments(){return this.v=[],this}getScopeData(){return{breadcrumbs:this._,attachments:this.v,contexts:this.C,tags:this.N,extra:this.T,user:this.S,level:this.j,fingerprint:this.O||[],eventProcessors:this.m,propagationContext:this.k,sdkProcessingMetadata:this.R,transactionName:this.I,span:tt(this)}}setSDKProcessingMetadata(t){return this.R=q(this.R,t,2),this}setPropagationContext(t){return this.k=t,this}getPropagationContext(){return this.k}captureException(t,n){const e=n?.event_id||Y();if(!this.A)return w.warn("No client configured on scope - will not capture exception!"),e;const r=new Error("Sentry syntheticException");return this.A.captureException(t,{originalException:t,syntheticException:r,...n,event_id:e},this),e}captureMessage(t,n,e){const r=e?.event_id||Y();if(!this.A)return w.warn("No client configured on scope - will not capture message!"),r;const o=new Error(t);return this.A.captureMessage(t,n,{originalException:t,syntheticException:o,...e,event_id:r},this),r}captureEvent(t,n){const e=n?.event_id||Y();return this.A?(this.A.captureEvent(t,{...n,event_id:e},this),e):(w.warn("No client configured on scope - will not capture event!"),e)}U(){this.p||(this.p=!0,this.l.forEach((t=>{t(this)})),this.p=!1)}}class et{constructor(t,n){let e,r;e=t||new nt,r=n||new nt,this.M=[{scope:e}],this.L=r}withScope(t){const n=this.B();let e;try{e=t(n)}catch(t){throw this.G(),t}return O(e)?e.then((t=>(this.G(),t)),(t=>{throw this.G(),t})):(this.G(),e)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.L}getStackTop(){return this.M[this.M.length-1]}B(){const t=this.getScope().clone();return this.M.push({client:this.getClient(),scope:t}),t}G(){return!(this.M.length<=1)&&!!this.M.pop()}}function rt(){const t=g(m());return t.stack=t.stack||new et(y("defaultCurrentScope",(()=>new nt)),y("defaultIsolationScope",(()=>new nt)))}function ot(t){return rt().withScope(t)}function st(t,n){const e=rt();return e.withScope((()=>(e.getStackTop().scope=t,n(t))))}function it(t){return rt().withScope((()=>t(rt().getIsolationScope())))}function ct(t){const n=g(t);return n.acs?n.acs:{withIsolationScope:it,withScope:ot,withSetScope:st,withSetIsolationScope:(t,n)=>it(n),getCurrentScope:()=>rt().getScope(),getIsolationScope:()=>rt().getIsolationScope()}}function ut(){return ct(m()).getCurrentScope().getClient()}const at="sentry.source",ft="sentry.sample_rate",ht="sentry.op",pt="sentry.origin",lt=0,dt=1,mt="_sentryScope",gt="_sentryIsolationScope";function yt(t){return{scope:t[mt],isolationScope:t[gt]}}const bt="sentry-",_t=/^sentry-/;function vt(t){const n=function(t){if(!t||!D(t)&&!Array.isArray(t))return;if(Array.isArray(t))return t.reduce(((t,n)=>{const e=wt(n);return Object.entries(e).forEach((([n,e])=>{t[n]=e})),t}),{});return wt(t)}(t);if(!n)return;const e=Object.entries(n).reduce(((t,[n,e])=>{if(n.match(_t)){t[n.slice(bt.length)]=e}return t}),{});return Object.keys(e).length>0?e:void 0}function wt(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[n,e])=>(n&&e&&(t[n]=e),t)),{})}const St=1;function $t(t){const{spanId:n,traceId:e,isRemote:r}=t.spanContext(),o=r?n:Tt(t).parent_span_id,s=yt(t).scope;return{parent_span_id:o,span_id:r?s?.getPropagationContext().propagationSpanId||Z():n,trace_id:e}}function Et(t){return t&&t.length>0?t.map((({context:{spanId:t,traceId:n,traceFlags:e,...r},attributes:o})=>({span_id:t,trace_id:n,sampled:e===St,attributes:o,...r}))):void 0}function xt(t){return"number"==typeof t?Nt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?Nt(t.getTime()):R()}function Nt(t){return t>9999999999?t/1e3:t}function Tt(t){if(function(t){return"function"==typeof t.getSpanJSON}(t))return t.getSpanJSON();const{spanId:n,traceId:e}=t.spanContext();if(function(t){const n=t;return!!(n.attributes&&n.startTime&&n.name&&n.endTime&&n.status)}(t)){const{attributes:r,startTime:o,name:s,endTime:i,parentSpanId:c,status:u,links:a}=t;return{span_id:n,trace_id:e,data:r,description:s,parent_span_id:c,start_timestamp:xt(o),timestamp:xt(i)||void 0,status:Ct(u),op:r[ht],origin:r[pt],links:Et(a)}}return{span_id:n,trace_id:e,start_timestamp:0,data:{}}}function Ct(t){if(t&&t.code!==lt)return t.code===dt?"ok":t.message||"unknown_error"}const Rt="_sentryRootSpan";function kt(t){return t[Rt]||t}const jt="production",Dt="_frozenDsc";function It(t){const n=ut();if(!n)return{};const e=kt(t),r=Tt(e),o=r.data,s=e.spanContext().traceState,i=s?.get("sentry.sample_rate")??o[ft];function c(t){return"number"!=typeof i&&"string"!=typeof i||(t.sample_rate=`${i}`),t}const u=e[Dt];if(u)return c(u);const a=s?.get("sentry.dsc"),f=a&&vt(a);if(f)return c(f);const h=function(t,n){const e=n.getOptions(),{publicKey:r}=n.getDsn()||{},o={environment:e.environment||jt,release:e.release,public_key:r,trace_id:t};return n.emit("createDsc",o),o}(t.spanContext().traceId,n),p=o[at],l=r.description;return"url"!==p&&l&&(h.transaction=l),function(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const n=t||ut()?.getOptions();return!(!n||null==n.tracesSampleRate&&!n.tracesSampler)}()&&(h.sampled=String(function(t){const{traceFlags:n}=t.spanContext();return n===St}(e)),h.sample_rand=s?.get("sentry.sample_rand")??yt(e).scope?.getPropagationContext().sampleRand.toString()),c(h),n.emit("createDsc",h,e),h}function Ot(t,n=!1){const{host:e,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${n&&o?`:${o}`:""}@${e}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}function At(t,n=100,e=1/0){try{return Pt("",t,n,e)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function Pt(t,n,e=1/0,r=1/0,o=function(){const t=new WeakSet;function n(n){return!!t.has(n)||(t.add(n),!1)}function e(n){t.delete(n)}return[n,e]}()){const[s,i]=o;if(null==n||["boolean","string"].includes(typeof n)||"number"==typeof n&&Number.isFinite(n))return n;const c=function(t,n){try{if("domain"===t&&n&&"object"==typeof n&&n.J)return"[Domain]";if("domainEmitter"===t)return"[DomainEmitter]";if("undefined"!=typeof global&&n===global)return"[Global]";if("undefined"!=typeof window&&n===window)return"[Window]";if("undefined"!=typeof document&&n===document)return"[Document]";if("object"==typeof(e=n)&&null!==e&&(e.__isVue||e.Y))return"[VueViewModel]";if(function(t){return I(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}(n))return"[SyntheticEvent]";if("number"==typeof n&&!Number.isFinite(n))return`[${n}]`;if("function"==typeof n)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||N}catch(t){return N}}(n)}]`;if("symbol"==typeof n)return`[${String(n)}]`;if("bigint"==typeof n)return`[BigInt: ${String(n)}]`;const r=function(t){const n=Object.getPrototypeOf(t);return n?.constructor?n.constructor.name:"null prototype"}(n);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(t){return`**non-serializable** (${t})`}var e}(t,n);if(!c.startsWith("[object "))return c;if(n.__sentry_skip_normalization__)return n;const u="number"==typeof n.__sentry_override_normalization_depth__?n.__sentry_override_normalization_depth__:e;if(0===u)return c.replace("object ","");if(s(n))return"[Circular ~]";const a=n;if(a&&"function"==typeof a.toJSON)try{return Pt("",a.toJSON(),u-1,r,o)}catch(t){}const f=Array.isArray(n)?[]:{};let h=0;const p=B(n);for(const t in p){if(!Object.prototype.hasOwnProperty.call(p,t))continue;if(h>=r){f[t]="[MaxProperties ~]";break}const n=p[t];f[t]=Pt(t,n,u-1,r,o),h++}return i(n),f}function Ut(t,n){const e=n.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch(t){}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${e}/*`,"ig"),"app:///")}function Mt(t,n=[]){return[t,n]}function Lt(t,n){const e=t[1];for(const t of e){if(n(t,t[0].type))return!0}return!1}function Bt(t){const n=g(p);return n.encodePolyfill?n.encodePolyfill(t):(new TextEncoder).encode(t)}function Gt(t){const[n,e]=t;let r=JSON.stringify(n);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[Bt(r),t]:r.push("string"==typeof t?Bt(t):t)}for(const t of e){const[n,e]=t;if(o(`\n${JSON.stringify(n)}\n`),"string"==typeof e||e instanceof Uint8Array)o(e);else{let t;try{t=JSON.stringify(e)}catch(n){t=JSON.stringify(At(e))}o(t)}}return"string"==typeof r?r:function(t){const n=t.reduce(((t,n)=>t+n.length),0),e=new Uint8Array(n);let r=0;for(const n of t)e.set(n,r),r+=n.length;return e}(r)}const Jt={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",otel_log:"log_item"};function Yt(t){if(!t?.sdk)return;const{name:n,version:e}=t.sdk;return{name:n,version:e}}function zt(t,n,e,r){const o=Yt(e),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,n){n&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||n.name,t.sdk.version=t.sdk.version||n.version,t.sdk.integrations=[...t.sdk.integrations||[],...n.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...n.packages||[]])}(t,e?.sdk);const i=function(t,n,e,r){const o=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:(new Date).toISOString(),...n&&{sdk:n},...!!e&&r&&{dsn:Ot(r)},...o&&{trace:o}}}(t,o,r,n);delete t.sdkProcessingMetadata;return Mt(i,[[{type:s},t]])}const Ht="__SENTRY_SUPPRESS_TRACING__";function Ft(t){const n=ct(m());return n.suppressTracing?n.suppressTracing(t):function(...t){const n=ct(m());if(2===t.length){const[e,r]=t;return e?n.withSetScope(e,r):n.withScope(r)}return n.withScope(t[0])}((n=>(n.setSDKProcessingMetadata({[Ht]:!0}),t())))}function Wt(t,n){const{fingerprint:e,span:r,breadcrumbs:o,sdkProcessingMetadata:s}=n;!function(t,n){const{extra:e,tags:r,user:o,contexts:s,level:i,transactionName:c}=n;Object.keys(e).length&&(t.extra={...e,...t.extra});Object.keys(r).length&&(t.tags={...r,...t.tags});Object.keys(o).length&&(t.user={...o,...t.user});Object.keys(s).length&&(t.contexts={...s,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,n),r&&function(t,n){t.contexts={trace:$t(n),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:It(n),...t.sdkProcessingMetadata};const e=kt(n),r=Tt(e).description;r&&!t.transaction&&"transaction"===t.type&&(t.transaction=r)}(t,r),function(t,n){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],n&&(t.fingerprint=t.fingerprint.concat(n));t.fingerprint.length||delete t.fingerprint}(t,e),function(t,n){const e=[...t.breadcrumbs||[],...n];t.breadcrumbs=e.length?e:void 0}(t,o),function(t,n){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...n}}(t,s)}const Kt="7";const Vt=Symbol.for("SentryBufferFullError");function Zt(t){const n=[];function e(t){return n.splice(n.indexOf(t),1)[0]||Promise.resolve(void 0)}return{$:n,add:function(r){if(!(void 0===t||n.length<t))return o=Vt,new F(((t,n)=>{n(o)}));var o;const s=r();return-1===n.indexOf(s)&&n.push(s),s.then((()=>e(s))).then(null,(()=>e(s).then(null,(()=>{})))),s},drain:function(t){return new F(((e,r)=>{let o=n.length;if(!o)return e(!0);const s=setTimeout((()=>{t&&t>0&&e(!1)}),t);n.forEach((t=>{H(t).then((()=>{--o||(clearTimeout(s),e(!0))}),r)}))}))}}}const qt=6e4;function Qt(t,{statusCode:n,headers:e},r=Date.now()){const o={...t},s=e?.["x-sentry-rate-limits"],i=e?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[n,e,,,s]=t.split(":",5),i=parseInt(n,10),c=1e3*(isNaN(i)?60:i);if(e)for(const t of e.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,n=Date.now()){const e=parseInt(`${t}`,10);if(!isNaN(e))return 1e3*e;const r=Date.parse(`${t}`);return isNaN(r)?qt:r-n}(i,r):429===n&&(o.all=r+6e4);return o}const Xt=64;function tn(t,n,e=Zt(t.bufferSize||Xt)){let r={};return{send:function(t){const o=[];if(Lt(t,((t,n)=>{const e=function(t){return Jt[t]}(n);(function(t,n,e=Date.now()){return function(t,n){return t[n]||t.all||0}(t,n)>e})(r,e)||o.push(t)})),0===o.length)return H({});const s=Mt(t[0],o),i=t=>{Lt(s,((t,n)=>{}))};return e.add((()=>n({body:Gt(s)}).then((t=>(void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&h&&w.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=Qt(r,t),t)),(t=>{throw i(),h&&w.error("Encountered error running transport request:",t),t})))).then((t=>t),(t=>{if(t===Vt)return h&&w.error("Skipped sending event because buffer is full."),i(),H({});throw t}))},flush:t=>e.drain(t)}}const nn=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function en(t){const n=function(t){const n=t.length>1024?`<truncated>${t.slice(-1024)}`:t,e=nn.exec(n);return e?e.slice(1):[]}(t),e=n[0]||"";let r=n[1];return e||r?(r&&(r=r.slice(0,r.length-1)),e+r):"."}function rn(t,n=!1){return!(n||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}const on=Symbol("AgentBaseInternalState");class sn extends s.Agent{constructor(t){super(t),this[on]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:n}=new Error;return"string"==typeof n&&n.split("\n").some((t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:")))}createSocket(t,n,e){const r={...n,secureEndpoint:this.isSecureEndpoint(n)};Promise.resolve().then((()=>this.connect(t,r))).then((o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[on].currentSocket=o,super.createSocket(t,n,e)}),e)}createConnection(){const t=this[on].currentSocket;if(this[on].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[on].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[on]&&(this[on].defaultPort=t)}get protocol(){return this[on].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[on]&&(this[on].protocol=t)}}function cn(...t){w.log("[https-proxy-agent:parse-proxy-response]",...t)}function un(t){return new Promise(((n,e)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return cn("have not received end of HTTP headers yet..."),void s();const f=u.subarray(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),e(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),m={};for(const n of f){if(!n)continue;const r=n.indexOf(":");if(-1===r)return t.destroy(),e(new Error(`Invalid header from proxy CONNECT response: "${n}"`));const o=n.slice(0,r).toLowerCase(),s=n.slice(r+1).trimStart(),i=m[o];"string"==typeof i?m[o]=[i,s]:Array.isArray(i)?i.push(s):m[o]=s}cn("got proxy server response: %o %o",h,m),i(),n({connect:{statusCode:l,statusText:d,headers:m},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),cn("onend"),e(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),cn("onerror %o",t),e(t)}t.on("error",u),t.on("end",c),s()}))}function an(...t){w.log("[https-proxy-agent]",...t)}class fn extends sn{static __initStatic(){this.protocols=["http","https"]}constructor(t,n){super(n),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=n?.headers??{},an("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const e=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?pn(n,"headers"):null,host:e,port:r}}async connect(t,n){const{proxy:e}=this;if(!n.host)throw new TypeError('No "host" provided');let r;if("https:"===e.protocol){an("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else an("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(n.host)?`[${n.host}]`:n.host;let i=`CONNECT ${s}:${n.port} HTTP/1.1\r\n`;if(e.username||e.password){const t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${n.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=un(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",hn),n.secureEndpoint){an("Upgrading socket connection to TLS");const t=n.servername||n.host;return f.connect({...pn(n,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",(t=>{an("Replaying proxy buffer for failed request"),t.push(h),t.push(null)})),p}}function hn(t){t.resume()}function pn(t,...n){const e={};let r;for(r in t)n.includes(r)||(e[r]=t[r]);return e}fn.__initStatic();const ln=32768;function dn(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const mn=n;let gn,yn=0,bn={};function _n(t){mn.debug&&console.log(`[ANR Worker] ${t}`)}var vn,wn,Sn;const $n=function(t){let n;try{n=new URL(t.url)}catch(n){return v((()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")})),tn(t,(()=>Promise.resolve({})))}const e="https:"===n.protocol,r=function(t,n){const{no_proxy:e}=process.env,r=e?.split(",").some((n=>t.host.endsWith(n)||t.hostname.endsWith(n)));return r?void 0:n}(n,t.proxy||(e?process.env.https_proxy:void 0)||process.env.http_proxy),o=e?i:s,a=void 0!==t.keepAlive&&t.keepAlive,f=r?new fn(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,n,e){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){return new Promise(((h,p)=>{Ft((()=>{let l=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const d={...t.headers};f.body.length>ln&&(d["content-encoding"]="gzip",l=l.pipe(u()));const m=n.request({method:"POST",agent:e,headers:d,hostname:r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8");const n=t.headers["retry-after"]??null,e=t.headers["x-sentry-rate-limits"]??null;h({statusCode:t.statusCode,headers:{"retry-after":n,"x-sentry-rate-limits":Array.isArray(e)?e[0]||null:e}})}));m.on("error",p),l.pipe(m)}))}))}}(t,t.httpModule??o,f);return tn(t,h)}({url:(vn=mn.dsn,wn=mn.tunnel,Sn=mn.sdkMetadata.sdk,wn||`${function(t){return`${function(t){const n=t.protocol?`${t.protocol}:`:"",e=t.port?`:${t.port}`:"";return`${n}//${t.host}${e}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(vn)}?${function(t,n){const e={sentry_version:Kt};return t.publicKey&&(e.sentry_key=t.publicKey),n&&(e.sentry_client=`${n.name}/${n.version}`),new URLSearchParams(e).toString()}(vn,Sn)}`)});async function En(){if(gn){_n("Sending abnormal session"),K(gn,{status:"abnormal",abnormal_mechanism:"anr_foreground",release:mn.release,environment:mn.environment});const t=function(t,n,e,r){const o=Yt(e);return Mt({sent_at:(new Date).toISOString(),...o&&{sdk:o},...!!r&&n&&{dsn:Ot(n)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(gn,mn.dsn,mn.sdkMetadata,mn.tunnel);_n(JSON.stringify(t)),await $n.send(t);try{e?.postMessage("session-ended")}catch(t){}}}function xn(t){if(!t)return;const n=function(t){if(!t.length)return[];const n=Array.from(t);return/sentryWrapped/.test(x(n).function||"")&&n.pop(),n.reverse(),E.test(x(n).function||"")&&(n.pop(),E.test(x(n).function||"")&&n.pop()),n.slice(0,S).map((t=>({...t,filename:t.filename||x(n).filename,function:t.function||$})))}(t);if(mn.appRootPath)for(const t of n)t.filename&&(t.filename=Ut(t.filename,mn.appRootPath));return n}async function Nn(t,n){if(yn>=mn.maxAnrEvents)return;yn+=1,await En(),_n("Sending event");const e={event_id:Y(),contexts:mn.contexts,release:mn.release,environment:mn.environment,dist:mn.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${mn.anrThreshold} ms`,stacktrace:{frames:xn(t)},mechanism:{type:"ANR"}}]},tags:mn.staticTags};n&&function(t,n){if(Wt(t,n),!t.contexts?.trace){const{traceId:e,parentSpanId:r,propagationSpanId:o}=n.propagationContext;t.contexts={trace:{trace_id:e,span_id:o||Z(),parent_span_id:r},...t.contexts}}}(e,n),function(t){if(0===Object.keys(bn).length)return;const n=mn.appRootPath?{}:bn;if(mn.appRootPath)for(const[t,e]of Object.entries(bn))n[Ut(t,mn.appRootPath)]=e;const e=new Map;for(const r of t.exception?.values||[])for(const t of r.stacktrace?.frames||[]){const r=t.abs_path||t.filename;r&&n[r]&&e.set(r,n[r])}if(e.size>0){const n=[];for(const[t,r]of e.entries())n.push({type:"sourcemap",code_file:t,debug_id:r});t.debug_meta={images:n}}}(e);const r=zt(e,mn.dsn,mn.sdkMetadata,mn.tunnel);_n(JSON.stringify(r)),await $n.send(r),await $n.flush(2e3),yn>=mn.maxAnrEvents&&setTimeout((()=>{process.exit(0)}),5e3)}let Tn;if(_n("Started"),mn.captureStackTrace){_n("Connecting to debugger");const n=new t;n.connectToMainThread(),_n("Connected to debugger");const e=new Map;n.on("Debugger.scriptParsed",(t=>{e.set(t.params.scriptId,t.params.url)})),n.on("Debugger.paused",(t=>{if("other"===t.params.reason)try{_n("Debugger paused");const s=[...t.params.callFrames],i=mn.appRootPath?function(t=(process.argv[1]?en(process.argv[1]):process.cwd()),n="\\"===o){const e=n?dn(t):t;return t=>{if(!t)return;const o=n?dn(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length));const u=decodeURIComponent(i);s||(s=".");const a=s.lastIndexOf("/node_modules");if(a>-1)return`${s.slice(a+14).replace(/\//g,".")}:${u}`;if(s.startsWith(e)){const t=s.slice(e.length+1).replace(/\//g,".");return t?`${t}:${u}`:u}return u}}(mn.appRootPath):()=>{},c=s.map((t=>function(t,n,e){const r=n?n.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return{filename:r,module:e(r),function:t.functionName||$,colno:o,lineno:s,in_app:r?rn(r):void 0}}(t,e.get(t.location.scriptId),i))),u=setTimeout((()=>{Nn(c).then(null,(()=>{_n("Sending ANR event failed.")}))}),5e3);n.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},((t,e)=>{t&&_n(`Error executing script: '${t.message}'`),clearTimeout(u);const r=e?.result?e.result.value:void 0;n.post("Debugger.resume"),n.post("Debugger.disable"),Nn(c,r).then(null,(()=>{_n("Sending ANR event failed.")}))}))}catch(t){throw n.post("Debugger.resume"),n.post("Debugger.disable"),t}})),Tn=()=>{try{n.post("Debugger.enable",(()=>{n.post("Debugger.pause")}))}catch(t){}}}const{poll:Cn}=function(t,n,e,r){const o=t();let s=!1,i=!0;return setInterval((()=>{const t=o.getTimeMs();!1===s&&t>n+e&&(s=!0,i&&r()),t<n+e&&(s=!1)}),20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}((function(){let t=process.hrtime();return{getTimeMs:()=>{const[n,e]=process.hrtime(t);return Math.floor(1e3*n+e/1e6)},reset:()=>{t=process.hrtime()}}}),mn.pollInterval,mn.anrThreshold,(function(){_n("Watchdog timeout"),Tn?(_n("Pausing debugger to capture stack trace"),Tn()):(_n("Capturing event without a stack trace"),Nn().then(null,(()=>{_n("Sending ANR event failed on watchdog timeout.")})))}));e?.on("message",(t=>{t.session&&(gn=W(t.session)),t.debugImages&&(bn=t.debugImages),Cn()}));
1
+ /*! @sentry/node 9.15.0 (b4ea653) | https://github.com/getsentry/sentry-javascript */
2
+ import{Session as t}from"node:inspector";import{workerData as n,parentPort as e}from"node:worker_threads";import{posix as r,sep as o}from"node:path";import*as s from"node:http";import*as i from"node:https";import{Readable as c}from"node:stream";import{createGzip as u}from"node:zlib";import*as a from"node:net";import*as f from"node:tls";const h="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,p="9.15.0",l=globalThis;function d(){return m(l),l}function m(t){const n=t.__SENTRY__=t.__SENTRY__||{};return n.version=n.version||p,n[p]=n[p]||{}}function g(t,n,e=l){const r=e.__SENTRY__=e.__SENTRY__||{},o=r[p]=r[p]||{};return o[t]||(o[t]=n())}const y=Object.prototype.toString;function b(t,n){return y.call(t)===`[object ${n}]`}function _(t){return b(t,"String")}function v(t){return b(t,"Object")}function w(t){return Boolean(t?.then&&"function"==typeof t.then)}function S(t,n){try{return t instanceof n}catch(t){return!1}}const $=l,E=80;function x(t,n){const e=t,r=[];if(!e?.tagName)return"";if($.HTMLElement&&e instanceof HTMLElement&&e.dataset){if(e.dataset.sentryComponent)return e.dataset.sentryComponent;if(e.dataset.sentryElement)return e.dataset.sentryElement}r.push(e.tagName.toLowerCase());const o=n?.length?n.filter((t=>e.getAttribute(t))).map((t=>[t,e.getAttribute(t)])):null;if(o?.length)o.forEach((t=>{r.push(`[${t[0]}="${t[1]}"]`)}));else{e.id&&r.push(`#${e.id}`);const t=e.className;if(t&&_(t)){const n=t.split(/\s+/);for(const t of n)r.push(`.${t}`)}}const s=["aria-label","type","name","title","alt"];for(const t of s){const n=e.getAttribute(t);n&&r.push(`[${t}="${n}"]`)}return r.join("")}const N="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,T=["debug","info","warn","error","log","assert","trace"],C={};function R(t){if(!("console"in l))return t();const n=l.console,e={},r=Object.keys(C);r.forEach((t=>{const r=C[t];e[t]=n[t],n[t]=r}));try{return t()}finally{r.forEach((t=>{n[t]=e[t]}))}}const k=g("logger",(function(){let t=!1;const n={enable:()=>{t=!0},disable:()=>{t=!1},isEnabled:()=>t};return N?T.forEach((e=>{n[e]=(...n)=>{t&&R((()=>{l.console[e](`Sentry Logger [${e}]:`,...n)}))}})):T.forEach((t=>{n[t]=()=>{}})),n}));function j(t,n=0){return"string"!=typeof t||0===n||t.length<=n?t:`${t.slice(0,n)}...`}function D(t){if(function(t){switch(y.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return S(t,Error)}}(t))return{message:t.message,name:t.name,stack:t.stack,...O(t)};if(n=t,"undefined"!=typeof Event&&S(n,Event)){const n={type:t.type,target:I(t.target),currentTarget:I(t.currentTarget),...O(t)};return"undefined"!=typeof CustomEvent&&S(t,CustomEvent)&&(n.detail=t.detail),n}return t;var n}function I(t){try{return n=t,"undefined"!=typeof Element&&S(n,Element)?function(t,n={}){if(!t)return"<unknown>";try{let e=t;const r=5,o=[];let s=0,i=0;const c=" > ",u=c.length;let a;const f=Array.isArray(n)?n:n.keyAttrs,h=!Array.isArray(n)&&n.maxStringLength||E;for(;e&&s++<r&&(a=x(e,f),!("html"===a||s>1&&i+o.length*u+a.length>=h));)o.push(a),i+=a.length,e=e.parentNode;return o.reverse().join(c)}catch(t){return"<unknown>"}}(t):Object.prototype.toString.call(t)}catch(t){return"<unknown>"}var n}function O(t){if("object"==typeof t&&null!==t){const n={};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}return{}}function A(t=function(){const t=l;return t.crypto||t.msCrypto}()){let n=()=>16*Math.random();try{if(t?.randomUUID)return t.randomUUID().replace(/-/g,"");t?.getRandomValues&&(n=()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch(t){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(t=>(t^(15&n())>>t/4).toString(16)))}const P=1e3;function U(){return Date.now()/P}const M=function(){const{performance:t}=l;if(!t?.now)return U;const n=Date.now()-t.now(),e=null==t.timeOrigin?n:t.timeOrigin;return()=>(e+t.now())/P}();function L(t){const n=M(),e={sid:A(),init:!0,timestamp:n,started:n,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(t){return{sid:`${t.sid}`,init:t.init,started:new Date(1e3*t.started).toISOString(),timestamp:new Date(1e3*t.timestamp).toISOString(),status:t.status,errors:t.errors,did:"number"==typeof t.did||"string"==typeof t.did?`${t.did}`:void 0,duration:t.duration,abnormal_mechanism:t.abnormal_mechanism,attrs:{release:t.release,environment:t.environment,ip_address:t.ipAddress,user_agent:t.userAgent}}}(e)};return t&&B(e,t),e}function B(t,n={}){if(n.user&&(!t.ipAddress&&n.user.ip_address&&(t.ipAddress=n.user.ip_address),t.did||n.did||(t.did=n.user.id||n.user.email||n.user.username)),t.timestamp=n.timestamp||M(),n.abnormal_mechanism&&(t.abnormal_mechanism=n.abnormal_mechanism),n.ignoreDuration&&(t.ignoreDuration=n.ignoreDuration),n.sid&&(t.sid=32===n.sid.length?n.sid:A()),void 0!==n.init&&(t.init=n.init),!t.did&&n.did&&(t.did=`${n.did}`),"number"==typeof n.started&&(t.started=n.started),t.ignoreDuration)t.duration=void 0;else if("number"==typeof n.duration)t.duration=n.duration;else{const n=t.timestamp-t.started;t.duration=n>=0?n:0}n.release&&(t.release=n.release),n.environment&&(t.environment=n.environment),!t.ipAddress&&n.ipAddress&&(t.ipAddress=n.ipAddress),!t.userAgent&&n.userAgent&&(t.userAgent=n.userAgent),"number"==typeof n.errors&&(t.errors=n.errors),n.status&&(t.status=n.status)}function G(t,n,e=2){if(!n||"object"!=typeof n||e<=0)return n;if(t&&0===Object.keys(n).length)return t;const r={...t};for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=G(r[t],n[t],e-1));return r}const J="_sentrySpan";function Y(t,n){n?function(t,n,e){try{Object.defineProperty(t,n,{value:e,writable:!0,configurable:!0})}catch(e){N&&k.log(`Failed to add non-enumerable property "${n}" to object`,t)}}(t,J,n):delete t[J]}function z(t){return t[J]}function H(){return A()}function F(){return A().substring(16)}class W{constructor(){this.t=!1,this.o=[],this.i=[],this.u=[],this.h=[],this.p={},this.l={},this.m={},this._={},this.v={},this.S={traceId:H(),sampleRand:Math.random()}}clone(){const t=new W;return t.u=[...this.u],t.l={...this.l},t.m={...this.m},t._={...this._},this._.flags&&(t._.flags={values:[...this._.flags.values]}),t.p=this.p,t.N=this.N,t.T=this.T,t.C=this.C,t.R=this.R,t.i=[...this.i],t.h=[...this.h],t.v={...this.v},t.S={...this.S},t.k=this.k,t.j=this.j,Y(t,z(this)),t}setClient(t){this.k=t}setLastEventId(t){this.j=t}getClient(){return this.k}lastEventId(){return this.j}addScopeListener(t){this.o.push(t)}addEventProcessor(t){return this.i.push(t),this}setUser(t){return this.p=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this.T&&B(this.T,{user:t}),this.D(),this}getUser(){return this.p}setTags(t){return this.l={...this.l,...t},this.D(),this}setTag(t,n){return this.l={...this.l,[t]:n},this.D(),this}setExtras(t){return this.m={...this.m,...t},this.D(),this}setExtra(t,n){return this.m={...this.m,[t]:n},this.D(),this}setFingerprint(t){return this.R=t,this.D(),this}setLevel(t){return this.N=t,this.D(),this}setTransactionName(t){return this.C=t,this.D(),this}setContext(t,n){return null===n?delete this._[t]:this._[t]=n,this.D(),this}setSession(t){return t?this.T=t:delete this.T,this.D(),this}getSession(){return this.T}update(t){if(!t)return this;const n="function"==typeof t?t(this):t,e=n instanceof W?n.getScopeData():v(n)?t:void 0,{tags:r,extra:o,user:s,contexts:i,level:c,fingerprint:u=[],propagationContext:a}=e||{};return this.l={...this.l,...r},this.m={...this.m,...o},this._={...this._,...i},s&&Object.keys(s).length&&(this.p=s),c&&(this.N=c),u.length&&(this.R=u),a&&(this.S=a),this}clear(){return this.u=[],this.l={},this.m={},this.p={},this._={},this.N=void 0,this.C=void 0,this.R=void 0,this.T=void 0,Y(this,void 0),this.h=[],this.setPropagationContext({traceId:H(),sampleRand:Math.random()}),this.D(),this}addBreadcrumb(t,n){const e="number"==typeof n?n:100;if(e<=0)return this;const r={timestamp:U(),...t,message:t.message?j(t.message,2048):t.message};return this.u.push(r),this.u.length>e&&(this.u=this.u.slice(-e),this.k?.recordDroppedEvent("buffer_overflow","log_item")),this.D(),this}getLastBreadcrumb(){return this.u[this.u.length-1]}clearBreadcrumbs(){return this.u=[],this.D(),this}addAttachment(t){return this.h.push(t),this}clearAttachments(){return this.h=[],this}getScopeData(){return{breadcrumbs:this.u,attachments:this.h,contexts:this._,tags:this.l,extra:this.m,user:this.p,level:this.N,fingerprint:this.R||[],eventProcessors:this.i,propagationContext:this.S,sdkProcessingMetadata:this.v,transactionName:this.C,span:z(this)}}setSDKProcessingMetadata(t){return this.v=G(this.v,t,2),this}setPropagationContext(t){return this.S=t,this}getPropagationContext(){return this.S}captureException(t,n){const e=n?.event_id||A();if(!this.k)return k.warn("No client configured on scope - will not capture exception!"),e;const r=new Error("Sentry syntheticException");return this.k.captureException(t,{originalException:t,syntheticException:r,...n,event_id:e},this),e}captureMessage(t,n,e){const r=e?.event_id||A();if(!this.k)return k.warn("No client configured on scope - will not capture message!"),r;const o=new Error(t);return this.k.captureMessage(t,n,{originalException:t,syntheticException:o,...e,event_id:r},this),r}captureEvent(t,n){const e=n?.event_id||A();return this.k?(this.k.captureEvent(t,{...n,event_id:e},this),e):(k.warn("No client configured on scope - will not capture event!"),e)}D(){this.t||(this.t=!0,this.o.forEach((t=>{t(this)})),this.t=!1)}}class K{constructor(t,n){let e,r;e=t||new W,r=n||new W,this.I=[{scope:e}],this.O=r}withScope(t){const n=this.A();let e;try{e=t(n)}catch(t){throw this.P(),t}return w(e)?e.then((t=>(this.P(),t)),(t=>{throw this.P(),t})):(this.P(),e)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this.O}getStackTop(){return this.I[this.I.length-1]}A(){const t=this.getScope().clone();return this.I.push({client:this.getClient(),scope:t}),t}P(){return!(this.I.length<=1)&&!!this.I.pop()}}function V(){const t=m(d());return t.stack=t.stack||new K(g("defaultCurrentScope",(()=>new W)),g("defaultIsolationScope",(()=>new W)))}function Z(t){return V().withScope(t)}function q(t,n){const e=V();return e.withScope((()=>(e.getStackTop().scope=t,n(t))))}function Q(t){return V().withScope((()=>t(V().getIsolationScope())))}function X(t){const n=m(t);return n.acs?n.acs:{withIsolationScope:Q,withScope:Z,withSetScope:q,withSetIsolationScope:(t,n)=>Q(n),getCurrentScope:()=>V().getScope(),getIsolationScope:()=>V().getIsolationScope()}}function tt(){return X(d()).getCurrentScope().getClient()}const nt="sentry.source",et="sentry.sample_rate",rt="sentry.op",ot="sentry.origin",st=0,it=1,ct="_sentryScope",ut="_sentryIsolationScope";function at(t){return{scope:t[ct],isolationScope:t[ut]}}const ft="sentry-",ht=/^sentry-/;function pt(t){const n=function(t){if(!t||!_(t)&&!Array.isArray(t))return;if(Array.isArray(t))return t.reduce(((t,n)=>{const e=lt(n);return Object.entries(e).forEach((([n,e])=>{t[n]=e})),t}),{});return lt(t)}(t);if(!n)return;const e=Object.entries(n).reduce(((t,[n,e])=>{if(n.match(ht)){t[n.slice(ft.length)]=e}return t}),{});return Object.keys(e).length>0?e:void 0}function lt(t){return t.split(",").map((t=>t.split("=").map((t=>decodeURIComponent(t.trim()))))).reduce(((t,[n,e])=>(n&&e&&(t[n]=e),t)),{})}const dt=1;function mt(t){const{spanId:n,traceId:e,isRemote:r}=t.spanContext(),o=r?n:_t(t).parent_span_id,s=at(t).scope;return{parent_span_id:o,span_id:r?s?.getPropagationContext().propagationSpanId||F():n,trace_id:e}}function gt(t){return t&&t.length>0?t.map((({context:{spanId:t,traceId:n,traceFlags:e,...r},attributes:o})=>({span_id:t,trace_id:n,sampled:e===dt,attributes:o,...r}))):void 0}function yt(t){return"number"==typeof t?bt(t):Array.isArray(t)?t[0]+t[1]/1e9:t instanceof Date?bt(t.getTime()):M()}function bt(t){return t>9999999999?t/1e3:t}function _t(t){if(function(t){return"function"==typeof t.getSpanJSON}(t))return t.getSpanJSON();const{spanId:n,traceId:e}=t.spanContext();if(function(t){const n=t;return!!(n.attributes&&n.startTime&&n.name&&n.endTime&&n.status)}(t)){const{attributes:r,startTime:o,name:s,endTime:i,parentSpanId:c,status:u,links:a}=t;return{span_id:n,trace_id:e,data:r,description:s,parent_span_id:c,start_timestamp:yt(o),timestamp:yt(i)||void 0,status:vt(u),op:r[rt],origin:r[ot],links:gt(a)}}return{span_id:n,trace_id:e,start_timestamp:0,data:{}}}function vt(t){if(t&&t.code!==st)return t.code===it?"ok":t.message||"unknown_error"}const wt="_sentryRootSpan";function St(t){return t[wt]||t}const $t=50,Et="?",xt=/captureMessage|captureException/;function Nt(t){return t[t.length-1]||{}}const Tt="<anonymous>";const Ct="production",Rt="_frozenDsc";function kt(t){const n=tt();if(!n)return{};const e=St(t),r=_t(e),o=r.data,s=e.spanContext().traceState,i=s?.get("sentry.sample_rate")??o[et];function c(t){return"number"!=typeof i&&"string"!=typeof i||(t.sample_rate=`${i}`),t}const u=e[Rt];if(u)return c(u);const a=s?.get("sentry.dsc"),f=a&&pt(a);if(f)return c(f);const h=function(t,n){const e=n.getOptions(),{publicKey:r}=n.getDsn()||{},o={environment:e.environment||Ct,release:e.release,public_key:r,trace_id:t};return n.emit("createDsc",o),o}(t.spanContext().traceId,n),p=o[nt],l=r.description;return"url"!==p&&l&&(h.transaction=l),function(t){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const n=t||tt()?.getOptions();return!(!n||null==n.tracesSampleRate&&!n.tracesSampler)}()&&(h.sampled=String(function(t){const{traceFlags:n}=t.spanContext();return n===dt}(e)),h.sample_rand=s?.get("sentry.sample_rand")??at(e).scope?.getPropagationContext().sampleRand.toString()),c(h),n.emit("createDsc",h,e),h}function jt(t,n=!1){const{host:e,path:r,pass:o,port:s,projectId:i,protocol:c,publicKey:u}=t;return`${c}://${u}${n&&o?`:${o}`:""}@${e}${s?`:${s}`:""}/${r?`${r}/`:r}${i}`}function Dt(t,n=100,e=1/0){try{return It("",t,n,e)}catch(t){return{ERROR:`**non-serializable** (${t})`}}}function It(t,n,e=1/0,r=1/0,o=function(){const t=new WeakSet;function n(n){return!!t.has(n)||(t.add(n),!1)}function e(n){t.delete(n)}return[n,e]}()){const[s,i]=o;if(null==n||["boolean","string"].includes(typeof n)||"number"==typeof n&&Number.isFinite(n))return n;const c=function(t,n){try{if("domain"===t&&n&&"object"==typeof n&&n.U)return"[Domain]";if("domainEmitter"===t)return"[DomainEmitter]";if("undefined"!=typeof global&&n===global)return"[Global]";if("undefined"!=typeof window&&n===window)return"[Window]";if("undefined"!=typeof document&&n===document)return"[Document]";if("object"==typeof(e=n)&&null!==e&&(e.__isVue||e.M))return"[VueViewModel]";if(function(t){return v(t)&&"nativeEvent"in t&&"preventDefault"in t&&"stopPropagation"in t}(n))return"[SyntheticEvent]";if("number"==typeof n&&!Number.isFinite(n))return`[${n}]`;if("function"==typeof n)return`[Function: ${function(t){try{return t&&"function"==typeof t&&t.name||Tt}catch(t){return Tt}}(n)}]`;if("symbol"==typeof n)return`[${String(n)}]`;if("bigint"==typeof n)return`[BigInt: ${String(n)}]`;const r=function(t){const n=Object.getPrototypeOf(t);return n?.constructor?n.constructor.name:"null prototype"}(n);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(t){return`**non-serializable** (${t})`}var e}(t,n);if(!c.startsWith("[object "))return c;if(n.__sentry_skip_normalization__)return n;const u="number"==typeof n.__sentry_override_normalization_depth__?n.__sentry_override_normalization_depth__:e;if(0===u)return c.replace("object ","");if(s(n))return"[Circular ~]";const a=n;if(a&&"function"==typeof a.toJSON)try{return It("",a.toJSON(),u-1,r,o)}catch(t){}const f=Array.isArray(n)?[]:{};let h=0;const p=D(n);for(const t in p){if(!Object.prototype.hasOwnProperty.call(p,t))continue;if(h>=r){f[t]="[MaxProperties ~]";break}const n=p[t];f[t]=It(t,n,u-1,r,o),h++}return i(n),f}function Ot(t,n){const e=n.replace(/\\/g,"/").replace(/[|\\{}()[\]^$+*?.]/g,"\\$&");let r=t;try{r=decodeURI(t)}catch(t){}return r.replace(/\\/g,"/").replace(/webpack:\/?/g,"").replace(new RegExp(`(file://)?/*${e}/*`,"ig"),"app:///")}function At(t,n=[]){return[t,n]}function Pt(t,n){const e=t[1];for(const t of e){if(n(t,t[0].type))return!0}return!1}function Ut(t){const n=m(l);return n.encodePolyfill?n.encodePolyfill(t):(new TextEncoder).encode(t)}function Mt(t){const[n,e]=t;let r=JSON.stringify(n);function o(t){"string"==typeof r?r="string"==typeof t?r+t:[Ut(r),t]:r.push("string"==typeof t?Ut(t):t)}for(const t of e){const[n,e]=t;if(o(`\n${JSON.stringify(n)}\n`),"string"==typeof e||e instanceof Uint8Array)o(e);else{let t;try{t=JSON.stringify(e)}catch(n){t=JSON.stringify(Dt(e))}o(t)}}return"string"==typeof r?r:function(t){const n=t.reduce(((t,n)=>t+n.length),0),e=new Uint8Array(n);let r=0;for(const n of t)e.set(n,r),r+=n.length;return e}(r)}const Lt={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",otel_log:"log_item"};function Bt(t){if(!t?.sdk)return;const{name:n,version:e}=t.sdk;return{name:n,version:e}}function Gt(t,n,e,r){const o=Bt(e),s=t.type&&"replay_event"!==t.type?t.type:"event";!function(t,n){n&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||n.name,t.sdk.version=t.sdk.version||n.version,t.sdk.integrations=[...t.sdk.integrations||[],...n.integrations||[]],t.sdk.packages=[...t.sdk.packages||[],...n.packages||[]])}(t,e?.sdk);const i=function(t,n,e,r){const o=t.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:t.event_id,sent_at:(new Date).toISOString(),...n&&{sdk:n},...!!e&&r&&{dsn:jt(r)},...o&&{trace:o}}}(t,o,r,n);delete t.sdkProcessingMetadata;return At(i,[[{type:s},t]])}const Jt="__SENTRY_SUPPRESS_TRACING__";function Yt(t){const n=X(d());return n.suppressTracing?n.suppressTracing(t):function(...t){const n=X(d());if(2===t.length){const[e,r]=t;return e?n.withSetScope(e,r):n.withScope(r)}return n.withScope(t[0])}((n=>(n.setSDKProcessingMetadata({[Jt]:!0}),t())))}var zt;function Ht(t){return new Ft((n=>{n(t)}))}!function(t){t[t.PENDING=0]="PENDING";t[t.RESOLVED=1]="RESOLVED";t[t.REJECTED=2]="REJECTED"}(zt||(zt={}));class Ft{constructor(t){this.L=zt.PENDING,this.B=[],this.G(t)}then(t,n){return new Ft(((e,r)=>{this.B.push([!1,n=>{if(t)try{e(t(n))}catch(t){r(t)}else e(n)},t=>{if(n)try{e(n(t))}catch(t){r(t)}else r(t)}]),this.J()}))}catch(t){return this.then((t=>t),t)}finally(t){return new Ft(((n,e)=>{let r,o;return this.then((n=>{o=!1,r=n,t&&t()}),(n=>{o=!0,r=n,t&&t()})).then((()=>{o?e(r):n(r)}))}))}J(){if(this.L===zt.PENDING)return;const t=this.B.slice();this.B=[],t.forEach((t=>{t[0]||(this.L===zt.RESOLVED&&t[1](this.Y),this.L===zt.REJECTED&&t[2](this.Y),t[0]=!0)}))}G(t){const n=(t,n)=>{this.L===zt.PENDING&&(w(n)?n.then(e,r):(this.L=t,this.Y=n,this.J()))},e=t=>{n(zt.RESOLVED,t)},r=t=>{n(zt.REJECTED,t)};try{t(e,r)}catch(t){r(t)}}}function Wt(t,n){const{fingerprint:e,span:r,breadcrumbs:o,sdkProcessingMetadata:s}=n;!function(t,n){const{extra:e,tags:r,user:o,contexts:s,level:i,transactionName:c}=n;Object.keys(e).length&&(t.extra={...e,...t.extra});Object.keys(r).length&&(t.tags={...r,...t.tags});Object.keys(o).length&&(t.user={...o,...t.user});Object.keys(s).length&&(t.contexts={...s,...t.contexts});i&&(t.level=i);c&&"transaction"!==t.type&&(t.transaction=c)}(t,n),r&&function(t,n){t.contexts={trace:mt(n),...t.contexts},t.sdkProcessingMetadata={dynamicSamplingContext:kt(n),...t.sdkProcessingMetadata};const e=St(n),r=_t(e).description;r&&!t.transaction&&"transaction"===t.type&&(t.transaction=r)}(t,r),function(t,n){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],n&&(t.fingerprint=t.fingerprint.concat(n));t.fingerprint.length||delete t.fingerprint}(t,e),function(t,n){const e=[...t.breadcrumbs||[],...n];t.breadcrumbs=e.length?e:void 0}(t,o),function(t,n){t.sdkProcessingMetadata={...t.sdkProcessingMetadata,...n}}(t,s)}const Kt="7";const Vt=Symbol.for("SentryBufferFullError");function Zt(t){const n=[];function e(t){return n.splice(n.indexOf(t),1)[0]||Promise.resolve(void 0)}return{$:n,add:function(r){if(!(void 0===t||n.length<t))return o=Vt,new Ft(((t,n)=>{n(o)}));var o;const s=r();return-1===n.indexOf(s)&&n.push(s),s.then((()=>e(s))).then(null,(()=>e(s).then(null,(()=>{})))),s},drain:function(t){return new Ft(((e,r)=>{let o=n.length;if(!o)return e(!0);const s=setTimeout((()=>{t&&t>0&&e(!1)}),t);n.forEach((t=>{Ht(t).then((()=>{--o||(clearTimeout(s),e(!0))}),r)}))}))}}}const qt=6e4;function Qt(t,{statusCode:n,headers:e},r=Date.now()){const o={...t},s=e?.["x-sentry-rate-limits"],i=e?.["retry-after"];if(s)for(const t of s.trim().split(",")){const[n,e,,,s]=t.split(":",5),i=parseInt(n,10),c=1e3*(isNaN(i)?60:i);if(e)for(const t of e.split(";"))"metric_bucket"===t&&s&&!s.split(";").includes("custom")||(o[t]=r+c);else o.all=r+c}else i?o.all=r+function(t,n=Date.now()){const e=parseInt(`${t}`,10);if(!isNaN(e))return 1e3*e;const r=Date.parse(`${t}`);return isNaN(r)?qt:r-n}(i,r):429===n&&(o.all=r+6e4);return o}const Xt=64;function tn(t,n,e=Zt(t.bufferSize||Xt)){let r={};return{send:function(t){const o=[];if(Pt(t,((t,n)=>{const e=function(t){return Lt[t]}(n);(function(t,n,e=Date.now()){return function(t,n){return t[n]||t.all||0}(t,n)>e})(r,e)||o.push(t)})),0===o.length)return Ht({});const s=At(t[0],o),i=t=>{Pt(s,((t,n)=>{}))};return e.add((()=>n({body:Mt(s)}).then((t=>(void 0!==t.statusCode&&(t.statusCode<200||t.statusCode>=300)&&h&&k.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),r=Qt(r,t),t)),(t=>{throw i(),h&&k.error("Encountered error running transport request:",t),t})))).then((t=>t),(t=>{if(t===Vt)return h&&k.error("Skipped sending event because buffer is full."),i(),Ht({});throw t}))},flush:t=>e.drain(t)}}const nn=/^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;function en(t){const n=function(t){const n=t.length>1024?`<truncated>${t.slice(-1024)}`:t,e=nn.exec(n);return e?e.slice(1):[]}(t),e=n[0]||"";let r=n[1];return e||r?(r&&(r=r.slice(0,r.length-1)),e+r):"."}function rn(t,n=!1){return!(n||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==t&&!t.includes("node_modules/")}const on=Symbol("AgentBaseInternalState");class sn extends s.Agent{constructor(t){super(t),this[on]={}}isSecureEndpoint(t){if(t){if("boolean"==typeof t.secureEndpoint)return t.secureEndpoint;if("string"==typeof t.protocol)return"https:"===t.protocol}const{stack:n}=new Error;return"string"==typeof n&&n.split("\n").some((t=>-1!==t.indexOf("(https.js:")||-1!==t.indexOf("node:https:")))}createSocket(t,n,e){const r={...n,secureEndpoint:this.isSecureEndpoint(n)};Promise.resolve().then((()=>this.connect(t,r))).then((o=>{if(o instanceof s.Agent)return o.addRequest(t,r);this[on].currentSocket=o,super.createSocket(t,n,e)}),e)}createConnection(){const t=this[on].currentSocket;if(this[on].currentSocket=void 0,!t)throw new Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[on].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(t){this[on]&&(this[on].defaultPort=t)}get protocol(){return this[on].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){this[on]&&(this[on].protocol=t)}}function cn(...t){k.log("[https-proxy-agent:parse-proxy-response]",...t)}function un(t){return new Promise(((n,e)=>{let r=0;const o=[];function s(){const c=t.read();c?function(c){o.push(c),r+=c.length;const u=Buffer.concat(o,r),a=u.indexOf("\r\n\r\n");if(-1===a)return cn("have not received end of HTTP headers yet..."),void s();const f=u.subarray(0,a).toString("ascii").split("\r\n"),h=f.shift();if(!h)return t.destroy(),e(new Error("No header received from proxy CONNECT response"));const p=h.split(" "),l=+(p[1]||0),d=p.slice(2).join(" "),m={};for(const n of f){if(!n)continue;const r=n.indexOf(":");if(-1===r)return t.destroy(),e(new Error(`Invalid header from proxy CONNECT response: "${n}"`));const o=n.slice(0,r).toLowerCase(),s=n.slice(r+1).trimStart(),i=m[o];"string"==typeof i?m[o]=[i,s]:Array.isArray(i)?i.push(s):m[o]=s}cn("got proxy server response: %o %o",h,m),i(),n({connect:{statusCode:l,statusText:d,headers:m},buffered:u})}(c):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),cn("onend"),e(new Error("Proxy connection ended before receiving CONNECT response"))}function u(t){i(),cn("onerror %o",t),e(t)}t.on("error",u),t.on("end",c),s()}))}function an(...t){k.log("[https-proxy-agent]",...t)}class fn extends sn{static __initStatic(){this.protocols=["http","https"]}constructor(t,n){super(n),this.options={},this.proxy="string"==typeof t?new URL(t):t,this.proxyHeaders=n?.headers??{},an("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const e=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?pn(n,"headers"):null,host:e,port:r}}async connect(t,n){const{proxy:e}=this;if(!n.host)throw new TypeError('No "host" provided');let r;if("https:"===e.protocol){an("Creating `tls.Socket`: %o",this.connectOpts);const t=this.connectOpts.servername||this.connectOpts.host;r=f.connect({...this.connectOpts,servername:t&&a.isIP(t)?void 0:t})}else an("Creating `net.Socket`: %o",this.connectOpts),r=a.connect(this.connectOpts);const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},s=a.isIPv6(n.host)?`[${n.host}]`:n.host;let i=`CONNECT ${s}:${n.port} HTTP/1.1\r\n`;if(e.username||e.password){const t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(t).toString("base64")}`}o.Host=`${s}:${n.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(o))i+=`${t}: ${o[t]}\r\n`;const c=un(r);r.write(`${i}\r\n`);const{connect:u,buffered:h}=await c;if(t.emit("proxyConnect",u),this.emit("proxyConnect",u,t),200===u.statusCode){if(t.once("socket",hn),n.secureEndpoint){an("Upgrading socket connection to TLS");const t=n.servername||n.host;return f.connect({...pn(n,"host","path","port"),socket:r,servername:a.isIP(t)?void 0:t})}return r}r.destroy();const p=new a.Socket({writable:!1});return p.readable=!0,t.once("socket",(t=>{an("Replaying proxy buffer for failed request"),t.push(h),t.push(null)})),p}}function hn(t){t.resume()}function pn(t,...n){const e={};let r;for(r in t)n.includes(r)||(e[r]=t[r]);return e}fn.__initStatic();const ln=32768;function dn(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}const mn=n;let gn,yn=0,bn={};function _n(t){mn.debug&&console.log(`[ANR Worker] ${t}`)}var vn,wn,Sn;const $n=function(t){let n;try{n=new URL(t.url)}catch(n){return R((()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")})),tn(t,(()=>Promise.resolve({})))}const e="https:"===n.protocol,r=function(t,n){const{no_proxy:e}=process.env,r=e?.split(",").some((n=>t.host.endsWith(n)||t.hostname.endsWith(n)));return r?void 0:n}(n,t.proxy||(e?process.env.https_proxy:void 0)||process.env.http_proxy),o=e?i:s,a=void 0!==t.keepAlive&&t.keepAlive,f=r?new fn(r):new o.Agent({keepAlive:a,maxSockets:30,timeout:2e3}),h=function(t,n,e){const{hostname:r,pathname:o,port:s,protocol:i,search:a}=new URL(t.url);return function(f){return new Promise(((h,p)=>{Yt((()=>{let l=function(t){return new c({read(){this.push(t),this.push(null)}})}(f.body);const d={...t.headers};f.body.length>ln&&(d["content-encoding"]="gzip",l=l.pipe(u()));const m=n.request({method:"POST",agent:e,headers:d,hostname:r,path:`${o}${a}`,port:s,protocol:i,ca:t.caCerts},(t=>{t.on("data",(()=>{})),t.on("end",(()=>{})),t.setEncoding("utf8");const n=t.headers["retry-after"]??null,e=t.headers["x-sentry-rate-limits"]??null;h({statusCode:t.statusCode,headers:{"retry-after":n,"x-sentry-rate-limits":Array.isArray(e)?e[0]||null:e}})}));m.on("error",p),l.pipe(m)}))}))}}(t,t.httpModule??o,f);return tn(t,h)}({url:(vn=mn.dsn,wn=mn.tunnel,Sn=mn.sdkMetadata.sdk,wn||`${function(t){return`${function(t){const n=t.protocol?`${t.protocol}:`:"",e=t.port?`:${t.port}`:"";return`${n}//${t.host}${e}${t.path?`/${t.path}`:""}/api/`}(t)}${t.projectId}/envelope/`}(vn)}?${function(t,n){const e={sentry_version:Kt};return t.publicKey&&(e.sentry_key=t.publicKey),n&&(e.sentry_client=`${n.name}/${n.version}`),new URLSearchParams(e).toString()}(vn,Sn)}`)});async function En(){if(gn){_n("Sending abnormal session"),B(gn,{status:"abnormal",abnormal_mechanism:"anr_foreground",release:mn.release,environment:mn.environment});const t=function(t,n,e,r){const o=Bt(e);return At({sent_at:(new Date).toISOString(),...o&&{sdk:o},...!!r&&n&&{dsn:jt(n)}},["aggregates"in t?[{type:"sessions"},t]:[{type:"session"},t.toJSON()]])}(gn,mn.dsn,mn.sdkMetadata,mn.tunnel);_n(JSON.stringify(t)),await $n.send(t);try{e?.postMessage("session-ended")}catch(t){}}}function xn(t){if(!t)return;const n=function(t){if(!t.length)return[];const n=Array.from(t);return/sentryWrapped/.test(Nt(n).function||"")&&n.pop(),n.reverse(),xt.test(Nt(n).function||"")&&(n.pop(),xt.test(Nt(n).function||"")&&n.pop()),n.slice(0,$t).map((t=>({...t,filename:t.filename||Nt(n).filename,function:t.function||Et})))}(t);if(mn.appRootPath)for(const t of n)t.filename&&(t.filename=Ot(t.filename,mn.appRootPath));return n}async function Nn(t,n){if(yn>=mn.maxAnrEvents)return;yn+=1,await En(),_n("Sending event");const e={event_id:A(),contexts:mn.contexts,release:mn.release,environment:mn.environment,dist:mn.dist,platform:"node",level:"error",exception:{values:[{type:"ApplicationNotResponding",value:`Application Not Responding for at least ${mn.anrThreshold} ms`,stacktrace:{frames:xn(t)},mechanism:{type:"ANR"}}]},tags:mn.staticTags};n&&function(t,n){if(Wt(t,n),!t.contexts?.trace){const{traceId:e,parentSpanId:r,propagationSpanId:o}=n.propagationContext;t.contexts={trace:{trace_id:e,span_id:o||F(),parent_span_id:r},...t.contexts}}}(e,n),function(t){if(0===Object.keys(bn).length)return;const n=mn.appRootPath?{}:bn;if(mn.appRootPath)for(const[t,e]of Object.entries(bn))n[Ot(t,mn.appRootPath)]=e;const e=new Map;for(const r of t.exception?.values||[])for(const t of r.stacktrace?.frames||[]){const r=t.abs_path||t.filename;r&&n[r]&&e.set(r,n[r])}if(e.size>0){const n=[];for(const[t,r]of e.entries())n.push({type:"sourcemap",code_file:t,debug_id:r});t.debug_meta={images:n}}}(e);const r=Gt(e,mn.dsn,mn.sdkMetadata,mn.tunnel);_n(JSON.stringify(r)),await $n.send(r),await $n.flush(2e3),yn>=mn.maxAnrEvents&&setTimeout((()=>{process.exit(0)}),5e3)}let Tn;if(_n("Started"),mn.captureStackTrace){_n("Connecting to debugger");const n=new t;n.connectToMainThread(),_n("Connected to debugger");const e=new Map;n.on("Debugger.scriptParsed",(t=>{e.set(t.params.scriptId,t.params.url)})),n.on("Debugger.paused",(t=>{if("other"===t.params.reason)try{_n("Debugger paused");const s=[...t.params.callFrames],i=mn.appRootPath?function(t=(process.argv[1]?en(process.argv[1]):process.cwd()),n="\\"===o){const e=n?dn(t):t;return t=>{if(!t)return;const o=n?dn(t):t;let{dir:s,base:i,ext:c}=r.parse(o);".js"!==c&&".mjs"!==c&&".cjs"!==c||(i=i.slice(0,-1*c.length));const u=decodeURIComponent(i);s||(s=".");const a=s.lastIndexOf("/node_modules");if(a>-1)return`${s.slice(a+14).replace(/\//g,".")}:${u}`;if(s.startsWith(e)){const t=s.slice(e.length+1).replace(/\//g,".");return t?`${t}:${u}`:u}return u}}(mn.appRootPath):()=>{},c=s.map((t=>function(t,n,e){const r=n?n.replace(/^file:\/\//,""):void 0,o=t.location.columnNumber?t.location.columnNumber+1:void 0,s=t.location.lineNumber?t.location.lineNumber+1:void 0;return{filename:r,module:e(r),function:t.functionName||Et,colno:o,lineno:s,in_app:r?rn(r):void 0}}(t,e.get(t.location.scriptId),i))),u=setTimeout((()=>{Nn(c).then(null,(()=>{_n("Sending ANR event failed.")}))}),5e3);n.post("Runtime.evaluate",{expression:"global.__SENTRY_GET_SCOPES__();",silent:!0,returnByValue:!0},((t,e)=>{t&&_n(`Error executing script: '${t.message}'`),clearTimeout(u);const r=e?.result?e.result.value:void 0;n.post("Debugger.resume"),n.post("Debugger.disable"),Nn(c,r).then(null,(()=>{_n("Sending ANR event failed.")}))}))}catch(t){throw n.post("Debugger.resume"),n.post("Debugger.disable"),t}})),Tn=()=>{try{n.post("Debugger.enable",(()=>{n.post("Debugger.pause")}))}catch(t){}}}const{poll:Cn}=function(t,n,e,r){const o=t();let s=!1,i=!0;return setInterval((()=>{const t=o.getTimeMs();!1===s&&t>n+e&&(s=!0,i&&r()),t<n+e&&(s=!1)}),20),{poll:()=>{o.reset()},enabled:t=>{i=t}}}((function(){let t=process.hrtime();return{getTimeMs:()=>{const[n,e]=process.hrtime(t);return Math.floor(1e3*n+e/1e6)},reset:()=>{t=process.hrtime()}}}),mn.pollInterval,mn.anrThreshold,(function(){_n("Watchdog timeout"),Tn?(_n("Pausing debugger to capture stack trace"),Tn()):(_n("Capturing event without a stack trace"),Nn().then(null,(()=>{_n("Sending ANR event failed on watchdog timeout.")})))}));e?.on("message",(t=>{t.session&&(gn=L(t.session)),t.debugImages&&(bn=t.debugImages),Cn()}));
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sources":["../../../src/integrations/context.ts"],"sourcesContent":["/* eslint-disable max-lines */\n\nimport { execFile } from 'node:child_process';\nimport { readFile, readdir } from 'node:fs';\nimport * as os from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AppContext,\n CloudResourceContext,\n Contexts,\n CultureContext,\n DeviceContext,\n Event,\n IntegrationFn,\n OsContext,\n} from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\n\nexport const readFileAsync = promisify(readFile);\nexport const readDirAsync = promisify(readdir);\n\n// Process enhanced with methods from Node 18, 20, 22 as @types/node\n// is on `14.18.0` to match minimum version requirements of the SDK\ninterface ProcessWithCurrentValues extends NodeJS.Process {\n availableMemory?(): number;\n}\n\nconst INTEGRATION_NAME = 'Context';\n\ninterface DeviceContextOptions {\n cpu?: boolean;\n memory?: boolean;\n}\n\ninterface ContextOptions {\n app?: boolean;\n os?: boolean;\n device?: DeviceContextOptions | boolean;\n culture?: boolean;\n cloudResource?: boolean;\n}\n\nconst _nodeContextIntegration = ((options: ContextOptions = {}) => {\n let cachedContext: Promise<Contexts> | undefined;\n\n const _options = {\n app: true,\n os: true,\n device: true,\n culture: true,\n cloudResource: true,\n ...options,\n };\n\n /** Add contexts to the event. Caches the context so we only look it up once. */\n async function addContext(event: Event): Promise<Event> {\n if (cachedContext === undefined) {\n cachedContext = _getContexts();\n }\n\n const updatedContext = _updateContext(await cachedContext);\n\n event.contexts = {\n ...event.contexts,\n app: { ...updatedContext.app, ...event.contexts?.app },\n os: { ...updatedContext.os, ...event.contexts?.os },\n device: { ...updatedContext.device, ...event.contexts?.device },\n culture: { ...updatedContext.culture, ...event.contexts?.culture },\n cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource },\n };\n\n return event;\n }\n\n /** Get the contexts from node. */\n async function _getContexts(): Promise<Contexts> {\n const contexts: Contexts = {};\n\n if (_options.os) {\n contexts.os = await getOsContext();\n }\n\n if (_options.app) {\n contexts.app = getAppContext();\n }\n\n if (_options.device) {\n contexts.device = getDeviceContext(_options.device);\n }\n\n if (_options.culture) {\n const culture = getCultureContext();\n\n if (culture) {\n contexts.culture = culture;\n }\n }\n\n if (_options.cloudResource) {\n contexts.cloud_resource = getCloudResourceContext();\n }\n\n return contexts;\n }\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addContext(event);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture context about the environment and the device that the client is running on, to events.\n */\nexport const nodeContextIntegration = defineIntegration(_nodeContextIntegration);\n\n/**\n * Updates the context with dynamic values that can change\n */\nfunction _updateContext(contexts: Contexts): Contexts {\n // Only update properties if they exist\n\n if (contexts.app?.app_memory) {\n contexts.app.app_memory = process.memoryUsage().rss;\n }\n\n if (contexts.app?.free_memory && typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n contexts.app.free_memory = freeMemory;\n }\n }\n\n if (contexts.device?.free_memory) {\n contexts.device.free_memory = os.freemem();\n }\n\n return contexts;\n}\n\n/**\n * Returns the operating system context.\n *\n * Based on the current platform, this uses a different strategy to provide the\n * most accurate OS information. Since this might involve spawning subprocesses\n * or accessing the file system, this should only be executed lazily and cached.\n *\n * - On macOS (Darwin), this will execute the `sw_vers` utility. The context\n * has a `name`, `version`, `build` and `kernel_version` set.\n * - On Linux, this will try to load a distribution release from `/etc` and set\n * the `name`, `version` and `kernel_version` fields.\n * - On all other platforms, only a `name` and `version` will be returned. Note\n * that `version` might actually be the kernel version.\n */\nasync function getOsContext(): Promise<OsContext> {\n const platformId = os.platform();\n switch (platformId) {\n case 'darwin':\n return getDarwinInfo();\n case 'linux':\n return getLinuxInfo();\n default:\n return {\n name: PLATFORM_NAMES[platformId] || platformId,\n version: os.release(),\n };\n }\n}\n\nfunction getCultureContext(): CultureContext | undefined {\n try {\n if (typeof process.versions.icu !== 'string') {\n // Node was built without ICU support\n return;\n }\n\n // Check that node was built with full Intl support. Its possible it was built without support for non-English\n // locales which will make resolvedOptions inaccurate\n //\n // https://nodejs.org/api/intl.html#detecting-internationalization-support\n const january = new Date(9e8);\n const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n if (spanish.format(january) === 'enero') {\n const options = Intl.DateTimeFormat().resolvedOptions();\n\n return {\n locale: options.locale,\n timezone: options.timeZone,\n };\n }\n } catch (err) {\n //\n }\n\n return;\n}\n\n/**\n * Get app context information from process\n */\nexport function getAppContext(): AppContext {\n const app_memory = process.memoryUsage().rss;\n const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();\n // https://nodejs.org/api/process.html#processavailablememory\n const appContext: AppContext = { app_start_time, app_memory };\n\n if (typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n appContext.free_memory = freeMemory;\n }\n }\n\n return appContext;\n}\n\n/**\n * Gets device information from os\n */\nexport function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext {\n const device: DeviceContext = {};\n\n // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202\n let uptime;\n try {\n uptime = os.uptime();\n } catch (e) {\n // noop\n }\n\n // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).\n // Hence, we only set boot time, if we get a valid uptime value.\n // @see https://github.com/getsentry/sentry-javascript/issues/5856\n if (typeof uptime === 'number') {\n device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();\n }\n\n device.arch = os.arch();\n\n if (deviceOpt === true || deviceOpt.memory) {\n device.memory_size = os.totalmem();\n device.free_memory = os.freemem();\n }\n\n if (deviceOpt === true || deviceOpt.cpu) {\n const cpuInfo = os.cpus() as os.CpuInfo[] | undefined;\n const firstCpu = cpuInfo?.[0];\n if (firstCpu) {\n device.processor_count = cpuInfo.length;\n device.cpu_description = firstCpu.model;\n device.processor_frequency = firstCpu.speed;\n }\n }\n\n return device;\n}\n\n/** Mapping of Node's platform names to actual OS names. */\nconst PLATFORM_NAMES: { [platform: string]: string } = {\n aix: 'IBM AIX',\n freebsd: 'FreeBSD',\n openbsd: 'OpenBSD',\n sunos: 'SunOS',\n win32: 'Windows',\n};\n\n/** Linux version file to check for a distribution. */\ninterface DistroFile {\n /** The file name, located in `/etc`. */\n name: string;\n /** Potential distributions to check. */\n distros: [string, ...string[]];\n}\n\n/** Mapping of linux release files located in /etc to distributions. */\nconst LINUX_DISTROS: DistroFile[] = [\n { name: 'fedora-release', distros: ['Fedora'] },\n { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },\n { name: 'redhat_version', distros: ['Red Hat Linux'] },\n { name: 'SuSE-release', distros: ['SUSE Linux'] },\n { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },\n { name: 'debian_version', distros: ['Debian'] },\n { name: 'debian_release', distros: ['Debian'] },\n { name: 'arch-release', distros: ['Arch Linux'] },\n { name: 'gentoo-release', distros: ['Gentoo Linux'] },\n { name: 'novell-release', distros: ['SUSE Linux'] },\n { name: 'alpine-release', distros: ['Alpine Linux'] },\n];\n\n/** Functions to extract the OS version from Linux release files. */\nconst LINUX_VERSIONS: {\n [identifier: string]: (content: string) => string | undefined;\n} = {\n alpine: content => content,\n arch: content => matchFirst(/distrib_release=(.*)/, content),\n centos: content => matchFirst(/release ([^ ]+)/, content),\n debian: content => content,\n fedora: content => matchFirst(/release (..)/, content),\n mint: content => matchFirst(/distrib_release=(.*)/, content),\n red: content => matchFirst(/release ([^ ]+)/, content),\n suse: content => matchFirst(/VERSION = (.*)\\n/, content),\n ubuntu: content => matchFirst(/distrib_release=(.*)/, content),\n};\n\n/**\n * Executes a regular expression with one capture group.\n *\n * @param regex A regular expression to execute.\n * @param text Content to execute the RegEx on.\n * @returns The captured string if matched; otherwise undefined.\n */\nfunction matchFirst(regex: RegExp, text: string): string | undefined {\n const match = regex.exec(text);\n return match ? match[1] : undefined;\n}\n\n/** Loads the macOS operating system context. */\nasync function getDarwinInfo(): Promise<OsContext> {\n // Default values that will be used in case no operating system information\n // can be loaded. The default version is computed via heuristics from the\n // kernel version, but the build ID is missing.\n const darwinInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Mac OS X',\n version: `10.${Number(os.release().split('.')[0]) - 4}`,\n };\n\n try {\n // We try to load the actual macOS version by executing the `sw_vers` tool.\n // This tool should be available on every standard macOS installation. In\n // case this fails, we stick with the values computed above.\n\n const output = await new Promise<string>((resolve, reject) => {\n execFile('/usr/bin/sw_vers', (error: Error | null, stdout: string) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n\n darwinInfo.name = matchFirst(/^ProductName:\\s+(.*)$/m, output);\n darwinInfo.version = matchFirst(/^ProductVersion:\\s+(.*)$/m, output);\n darwinInfo.build = matchFirst(/^BuildVersion:\\s+(.*)$/m, output);\n } catch (e) {\n // ignore\n }\n\n return darwinInfo;\n}\n\n/** Returns a distribution identifier to look up version callbacks. */\nfunction getLinuxDistroId(name: string): string {\n return (name.split(' ') as [string])[0].toLowerCase();\n}\n\n/** Loads the Linux operating system context. */\nasync function getLinuxInfo(): Promise<OsContext> {\n // By default, we cannot assume anything about the distribution or Linux\n // version. `os.release()` returns the kernel version and we assume a generic\n // \"Linux\" name, which will be replaced down below.\n const linuxInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Linux',\n };\n\n try {\n // We start guessing the distribution by listing files in the /etc\n // directory. This is were most Linux distributions (except Knoppix) store\n // release files with certain distribution-dependent meta data. We search\n // for exactly one known file defined in `LINUX_DISTROS` and exit if none\n // are found. In case there are more than one file, we just stick with the\n // first one.\n const etcFiles = await readDirAsync('/etc');\n const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));\n if (!distroFile) {\n return linuxInfo;\n }\n\n // Once that file is known, load its contents. To make searching in those\n // files easier, we lowercase the file contents. Since these files are\n // usually quite small, this should not allocate too much memory and we only\n // hold on to it for a very short amount of time.\n const distroPath = join('/etc', distroFile.name);\n const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) as string).toLowerCase();\n\n // Some Linux distributions store their release information in the same file\n // (e.g. RHEL and Centos). In those cases, we scan the file for an\n // identifier, that basically consists of the first word of the linux\n // distribution name (e.g. \"red\" for Red Hat). In case there is no match, we\n // just assume the first distribution in our list.\n const { distros } = distroFile;\n linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];\n\n // Based on the found distribution, we can now compute the actual version\n // number. This is different for every distribution, so several strategies\n // are computed in `LINUX_VERSIONS`.\n const id = getLinuxDistroId(linuxInfo.name);\n linuxInfo.version = LINUX_VERSIONS[id]?.(contents);\n } catch (e) {\n // ignore\n }\n\n return linuxInfo;\n}\n\n/**\n * Grabs some information about hosting provider based on best effort.\n */\nfunction getCloudResourceContext(): CloudResourceContext | undefined {\n if (process.env.VERCEL) {\n // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables\n return {\n 'cloud.provider': 'vercel',\n 'cloud.region': process.env.VERCEL_REGION,\n };\n } else if (process.env.AWS_REGION) {\n // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html\n return {\n 'cloud.provider': 'aws',\n 'cloud.region': process.env.AWS_REGION,\n 'cloud.platform': process.env.AWS_EXECUTION_ENV,\n };\n } else if (process.env.GCP_PROJECT) {\n // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables\n return {\n 'cloud.provider': 'gcp',\n };\n } else if (process.env.ALIYUN_REGION_ID) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'alibaba_cloud',\n 'cloud.region': process.env.ALIYUN_REGION_ID,\n };\n } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {\n // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment\n return {\n 'cloud.provider': 'azure',\n 'cloud.region': process.env.REGION_NAME,\n };\n } else if (process.env.IBM_CLOUD_REGION) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'ibm_cloud',\n 'cloud.region': process.env.IBM_CLOUD_REGION,\n };\n } else if (process.env.TENCENTCLOUD_REGION) {\n // https://www.tencentcloud.com/document/product/583/32748\n return {\n 'cloud.provider': 'tencent_cloud',\n 'cloud.region': process.env.TENCENTCLOUD_REGION,\n 'cloud.account.id': process.env.TENCENTCLOUD_APPID,\n 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE,\n };\n } else if (process.env.NETLIFY) {\n // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables\n return {\n 'cloud.provider': 'netlify',\n };\n } else if (process.env.FLY_REGION) {\n // https://fly.io/docs/reference/runtime-environment/\n return {\n 'cloud.provider': 'fly.io',\n 'cloud.region': process.env.FLY_REGION,\n };\n } else if (process.env.DYNO) {\n // https://devcenter.heroku.com/articles/dynos#local-environment-variables\n return {\n 'cloud.provider': 'heroku',\n };\n } else {\n return undefined;\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;MAmBa,aAAc,GAAE,SAAS,CAAC,QAAQ;MAClC,YAAa,GAAE,SAAS,CAAC,OAAO;;AAE7C;AACA;;AAKA,MAAM,gBAAA,GAAmB,SAAS;;AAelC,MAAM,uBAAA,IAA2B,CAAC,OAAO,GAAmB,EAAE,KAAK;AACnE,EAAE,IAAI,aAAa;;AAEnB,EAAE,MAAM,WAAW;AACnB,IAAI,GAAG,EAAE,IAAI;AACb,IAAI,EAAE,EAAE,IAAI;AACZ,IAAI,MAAM,EAAE,IAAI;AAChB,IAAI,OAAO,EAAE,IAAI;AACjB,IAAI,aAAa,EAAE,IAAI;AACvB,IAAI,GAAG,OAAO;AACd,GAAG;;AAEH;AACA,EAAE,eAAe,UAAU,CAAC,KAAK,EAAyB;AAC1D,IAAI,IAAI,aAAc,KAAI,SAAS,EAAE;AACrC,MAAM,aAAc,GAAE,YAAY,EAAE;AACpC;;AAEA,IAAI,MAAM,cAAe,GAA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BAAA,EAAA,QAAA;AACA,KAAA;AACA,GAAA,MAAA;AACA,IAAA,OAAA,SAAA;AACA;AACA;;;;"}
1
+ {"version":3,"file":"context.js","sources":["../../../src/integrations/context.ts"],"sourcesContent":["/* eslint-disable max-lines */\n\nimport { execFile } from 'node:child_process';\nimport { readdir, readFile } from 'node:fs';\nimport * as os from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type {\n AppContext,\n CloudResourceContext,\n Contexts,\n CultureContext,\n DeviceContext,\n Event,\n IntegrationFn,\n OsContext,\n} from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\n\nexport const readFileAsync = promisify(readFile);\nexport const readDirAsync = promisify(readdir);\n\n// Process enhanced with methods from Node 18, 20, 22 as @types/node\n// is on `14.18.0` to match minimum version requirements of the SDK\ninterface ProcessWithCurrentValues extends NodeJS.Process {\n availableMemory?(): number;\n}\n\nconst INTEGRATION_NAME = 'Context';\n\ninterface DeviceContextOptions {\n cpu?: boolean;\n memory?: boolean;\n}\n\ninterface ContextOptions {\n app?: boolean;\n os?: boolean;\n device?: DeviceContextOptions | boolean;\n culture?: boolean;\n cloudResource?: boolean;\n}\n\nconst _nodeContextIntegration = ((options: ContextOptions = {}) => {\n let cachedContext: Promise<Contexts> | undefined;\n\n const _options = {\n app: true,\n os: true,\n device: true,\n culture: true,\n cloudResource: true,\n ...options,\n };\n\n /** Add contexts to the event. Caches the context so we only look it up once. */\n async function addContext(event: Event): Promise<Event> {\n if (cachedContext === undefined) {\n cachedContext = _getContexts();\n }\n\n const updatedContext = _updateContext(await cachedContext);\n\n event.contexts = {\n ...event.contexts,\n app: { ...updatedContext.app, ...event.contexts?.app },\n os: { ...updatedContext.os, ...event.contexts?.os },\n device: { ...updatedContext.device, ...event.contexts?.device },\n culture: { ...updatedContext.culture, ...event.contexts?.culture },\n cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource },\n };\n\n return event;\n }\n\n /** Get the contexts from node. */\n async function _getContexts(): Promise<Contexts> {\n const contexts: Contexts = {};\n\n if (_options.os) {\n contexts.os = await getOsContext();\n }\n\n if (_options.app) {\n contexts.app = getAppContext();\n }\n\n if (_options.device) {\n contexts.device = getDeviceContext(_options.device);\n }\n\n if (_options.culture) {\n const culture = getCultureContext();\n\n if (culture) {\n contexts.culture = culture;\n }\n }\n\n if (_options.cloudResource) {\n contexts.cloud_resource = getCloudResourceContext();\n }\n\n return contexts;\n }\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addContext(event);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture context about the environment and the device that the client is running on, to events.\n */\nexport const nodeContextIntegration = defineIntegration(_nodeContextIntegration);\n\n/**\n * Updates the context with dynamic values that can change\n */\nfunction _updateContext(contexts: Contexts): Contexts {\n // Only update properties if they exist\n\n if (contexts.app?.app_memory) {\n contexts.app.app_memory = process.memoryUsage().rss;\n }\n\n if (contexts.app?.free_memory && typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n contexts.app.free_memory = freeMemory;\n }\n }\n\n if (contexts.device?.free_memory) {\n contexts.device.free_memory = os.freemem();\n }\n\n return contexts;\n}\n\n/**\n * Returns the operating system context.\n *\n * Based on the current platform, this uses a different strategy to provide the\n * most accurate OS information. Since this might involve spawning subprocesses\n * or accessing the file system, this should only be executed lazily and cached.\n *\n * - On macOS (Darwin), this will execute the `sw_vers` utility. The context\n * has a `name`, `version`, `build` and `kernel_version` set.\n * - On Linux, this will try to load a distribution release from `/etc` and set\n * the `name`, `version` and `kernel_version` fields.\n * - On all other platforms, only a `name` and `version` will be returned. Note\n * that `version` might actually be the kernel version.\n */\nasync function getOsContext(): Promise<OsContext> {\n const platformId = os.platform();\n switch (platformId) {\n case 'darwin':\n return getDarwinInfo();\n case 'linux':\n return getLinuxInfo();\n default:\n return {\n name: PLATFORM_NAMES[platformId] || platformId,\n version: os.release(),\n };\n }\n}\n\nfunction getCultureContext(): CultureContext | undefined {\n try {\n if (typeof process.versions.icu !== 'string') {\n // Node was built without ICU support\n return;\n }\n\n // Check that node was built with full Intl support. Its possible it was built without support for non-English\n // locales which will make resolvedOptions inaccurate\n //\n // https://nodejs.org/api/intl.html#detecting-internationalization-support\n const january = new Date(9e8);\n const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n if (spanish.format(january) === 'enero') {\n const options = Intl.DateTimeFormat().resolvedOptions();\n\n return {\n locale: options.locale,\n timezone: options.timeZone,\n };\n }\n } catch (err) {\n //\n }\n\n return;\n}\n\n/**\n * Get app context information from process\n */\nexport function getAppContext(): AppContext {\n const app_memory = process.memoryUsage().rss;\n const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();\n // https://nodejs.org/api/process.html#processavailablememory\n const appContext: AppContext = { app_start_time, app_memory };\n\n if (typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n appContext.free_memory = freeMemory;\n }\n }\n\n return appContext;\n}\n\n/**\n * Gets device information from os\n */\nexport function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext {\n const device: DeviceContext = {};\n\n // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202\n let uptime;\n try {\n uptime = os.uptime();\n } catch (e) {\n // noop\n }\n\n // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).\n // Hence, we only set boot time, if we get a valid uptime value.\n // @see https://github.com/getsentry/sentry-javascript/issues/5856\n if (typeof uptime === 'number') {\n device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();\n }\n\n device.arch = os.arch();\n\n if (deviceOpt === true || deviceOpt.memory) {\n device.memory_size = os.totalmem();\n device.free_memory = os.freemem();\n }\n\n if (deviceOpt === true || deviceOpt.cpu) {\n const cpuInfo = os.cpus() as os.CpuInfo[] | undefined;\n const firstCpu = cpuInfo?.[0];\n if (firstCpu) {\n device.processor_count = cpuInfo.length;\n device.cpu_description = firstCpu.model;\n device.processor_frequency = firstCpu.speed;\n }\n }\n\n return device;\n}\n\n/** Mapping of Node's platform names to actual OS names. */\nconst PLATFORM_NAMES: { [platform: string]: string } = {\n aix: 'IBM AIX',\n freebsd: 'FreeBSD',\n openbsd: 'OpenBSD',\n sunos: 'SunOS',\n win32: 'Windows',\n};\n\n/** Linux version file to check for a distribution. */\ninterface DistroFile {\n /** The file name, located in `/etc`. */\n name: string;\n /** Potential distributions to check. */\n distros: [string, ...string[]];\n}\n\n/** Mapping of linux release files located in /etc to distributions. */\nconst LINUX_DISTROS: DistroFile[] = [\n { name: 'fedora-release', distros: ['Fedora'] },\n { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },\n { name: 'redhat_version', distros: ['Red Hat Linux'] },\n { name: 'SuSE-release', distros: ['SUSE Linux'] },\n { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },\n { name: 'debian_version', distros: ['Debian'] },\n { name: 'debian_release', distros: ['Debian'] },\n { name: 'arch-release', distros: ['Arch Linux'] },\n { name: 'gentoo-release', distros: ['Gentoo Linux'] },\n { name: 'novell-release', distros: ['SUSE Linux'] },\n { name: 'alpine-release', distros: ['Alpine Linux'] },\n];\n\n/** Functions to extract the OS version from Linux release files. */\nconst LINUX_VERSIONS: {\n [identifier: string]: (content: string) => string | undefined;\n} = {\n alpine: content => content,\n arch: content => matchFirst(/distrib_release=(.*)/, content),\n centos: content => matchFirst(/release ([^ ]+)/, content),\n debian: content => content,\n fedora: content => matchFirst(/release (..)/, content),\n mint: content => matchFirst(/distrib_release=(.*)/, content),\n red: content => matchFirst(/release ([^ ]+)/, content),\n suse: content => matchFirst(/VERSION = (.*)\\n/, content),\n ubuntu: content => matchFirst(/distrib_release=(.*)/, content),\n};\n\n/**\n * Executes a regular expression with one capture group.\n *\n * @param regex A regular expression to execute.\n * @param text Content to execute the RegEx on.\n * @returns The captured string if matched; otherwise undefined.\n */\nfunction matchFirst(regex: RegExp, text: string): string | undefined {\n const match = regex.exec(text);\n return match ? match[1] : undefined;\n}\n\n/** Loads the macOS operating system context. */\nasync function getDarwinInfo(): Promise<OsContext> {\n // Default values that will be used in case no operating system information\n // can be loaded. The default version is computed via heuristics from the\n // kernel version, but the build ID is missing.\n const darwinInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Mac OS X',\n version: `10.${Number(os.release().split('.')[0]) - 4}`,\n };\n\n try {\n // We try to load the actual macOS version by executing the `sw_vers` tool.\n // This tool should be available on every standard macOS installation. In\n // case this fails, we stick with the values computed above.\n\n const output = await new Promise<string>((resolve, reject) => {\n execFile('/usr/bin/sw_vers', (error: Error | null, stdout: string) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n\n darwinInfo.name = matchFirst(/^ProductName:\\s+(.*)$/m, output);\n darwinInfo.version = matchFirst(/^ProductVersion:\\s+(.*)$/m, output);\n darwinInfo.build = matchFirst(/^BuildVersion:\\s+(.*)$/m, output);\n } catch (e) {\n // ignore\n }\n\n return darwinInfo;\n}\n\n/** Returns a distribution identifier to look up version callbacks. */\nfunction getLinuxDistroId(name: string): string {\n return (name.split(' ') as [string])[0].toLowerCase();\n}\n\n/** Loads the Linux operating system context. */\nasync function getLinuxInfo(): Promise<OsContext> {\n // By default, we cannot assume anything about the distribution or Linux\n // version. `os.release()` returns the kernel version and we assume a generic\n // \"Linux\" name, which will be replaced down below.\n const linuxInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Linux',\n };\n\n try {\n // We start guessing the distribution by listing files in the /etc\n // directory. This is were most Linux distributions (except Knoppix) store\n // release files with certain distribution-dependent meta data. We search\n // for exactly one known file defined in `LINUX_DISTROS` and exit if none\n // are found. In case there are more than one file, we just stick with the\n // first one.\n const etcFiles = await readDirAsync('/etc');\n const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));\n if (!distroFile) {\n return linuxInfo;\n }\n\n // Once that file is known, load its contents. To make searching in those\n // files easier, we lowercase the file contents. Since these files are\n // usually quite small, this should not allocate too much memory and we only\n // hold on to it for a very short amount of time.\n const distroPath = join('/etc', distroFile.name);\n const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) as string).toLowerCase();\n\n // Some Linux distributions store their release information in the same file\n // (e.g. RHEL and Centos). In those cases, we scan the file for an\n // identifier, that basically consists of the first word of the linux\n // distribution name (e.g. \"red\" for Red Hat). In case there is no match, we\n // just assume the first distribution in our list.\n const { distros } = distroFile;\n linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];\n\n // Based on the found distribution, we can now compute the actual version\n // number. This is different for every distribution, so several strategies\n // are computed in `LINUX_VERSIONS`.\n const id = getLinuxDistroId(linuxInfo.name);\n linuxInfo.version = LINUX_VERSIONS[id]?.(contents);\n } catch (e) {\n // ignore\n }\n\n return linuxInfo;\n}\n\n/**\n * Grabs some information about hosting provider based on best effort.\n */\nfunction getCloudResourceContext(): CloudResourceContext | undefined {\n if (process.env.VERCEL) {\n // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables\n return {\n 'cloud.provider': 'vercel',\n 'cloud.region': process.env.VERCEL_REGION,\n };\n } else if (process.env.AWS_REGION) {\n // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html\n return {\n 'cloud.provider': 'aws',\n 'cloud.region': process.env.AWS_REGION,\n 'cloud.platform': process.env.AWS_EXECUTION_ENV,\n };\n } else if (process.env.GCP_PROJECT) {\n // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables\n return {\n 'cloud.provider': 'gcp',\n };\n } else if (process.env.ALIYUN_REGION_ID) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'alibaba_cloud',\n 'cloud.region': process.env.ALIYUN_REGION_ID,\n };\n } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {\n // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment\n return {\n 'cloud.provider': 'azure',\n 'cloud.region': process.env.REGION_NAME,\n };\n } else if (process.env.IBM_CLOUD_REGION) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'ibm_cloud',\n 'cloud.region': process.env.IBM_CLOUD_REGION,\n };\n } else if (process.env.TENCENTCLOUD_REGION) {\n // https://www.tencentcloud.com/document/product/583/32748\n return {\n 'cloud.provider': 'tencent_cloud',\n 'cloud.region': process.env.TENCENTCLOUD_REGION,\n 'cloud.account.id': process.env.TENCENTCLOUD_APPID,\n 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE,\n };\n } else if (process.env.NETLIFY) {\n // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables\n return {\n 'cloud.provider': 'netlify',\n };\n } else if (process.env.FLY_REGION) {\n // https://fly.io/docs/reference/runtime-environment/\n return {\n 'cloud.provider': 'fly.io',\n 'cloud.region': process.env.FLY_REGION,\n };\n } else if (process.env.DYNO) {\n // https://devcenter.heroku.com/articles/dynos#local-environment-variables\n return {\n 'cloud.provider': 'heroku',\n };\n } else {\n return undefined;\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;;;MAmBa,aAAc,GAAE,SAAS,CAAC,QAAQ;MAClC,YAAa,GAAE,SAAS,CAAC,OAAO;;AAE7C;AACA;;AAKA,MAAM,gBAAA,GAAmB,SAAS;;AAelC,MAAM,uBAAA,IAA2B,CAAC,OAAO,GAAmB,EAAE,KAAK;AACnE,EAAE,IAAI,aAAa;;AAEnB,EAAE,MAAM,WAAW;AACnB,IAAI,GAAG,EAAE,IAAI;AACb,IAAI,EAAE,EAAE,IAAI;AACZ,IAAI,MAAM,EAAE,IAAI;AAChB,IAAI,OAAO,EAAE,IAAI;AACjB,IAAI,aAAa,EAAE,IAAI;AACvB,IAAI,GAAG,OAAO;AACd,GAAG;;AAEH;AACA,EAAE,eAAe,UAAU,CAAC,KAAK,EAAyB;AAC1D,IAAI,IAAI,aAAc,KAAI,SA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AAA,IAAA,OAAA,CAAA,GAAA,CAAA,IAAA,EAAA;AACA;AACA,IAAA,OAAA;AACA,MAAA,gBAAA,EAAA,QAAA;AACA,KAAA;AACA,GAAA,MAAA;AACA,IAAA,OAAA,SAAA;AACA;AACA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"contextlines.js","sources":["../../../src/integrations/contextlines.ts"],"sourcesContent":["import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { LRUMap, defineIntegration, logger, snipLine } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap<string, 1>(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst INTEGRATION_NAME = 'ContextLines';\n// Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be\n// minified code while large lineno values are likely to be bundled code.\n// Exported for testing purposes.\nexport const MAX_CONTEXTLINES_COLNO: number = 1000;\nexport const MAX_CONTEXTLINES_LINENO: number = 10000;\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to 7.\n *\n * Set to 0 to disable loading and inclusion of source files.\n **/\n frameContextLines?: number;\n}\n\n/**\n * Exported for testing purposes.\n */\nexport function resetFileContentCache(): void {\n LRU_FILE_CONTENTS_CACHE.clear();\n}\n\n/**\n * Get or init map value\n */\nfunction emplace<T extends LRUMap<K, V>, K extends string, V>(map: T, key: K, contents: V): V {\n const value = map.get(key);\n\n if (value === undefined) {\n map.set(key, contents);\n return contents;\n }\n\n return value;\n}\n\n/**\n * Determines if context lines should be skipped for a file.\n * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source\n * - node: prefixed modules are part of the runtime and cannot be resolved to a file\n * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports\n */\nfunction shouldSkipContextLinesForFile(path: string): boolean {\n // Test the most common prefix and extension first. These are the ones we\n // are most likely to see in user applications and are the ones we can break out of first.\n if (path.startsWith('node:')) return true;\n if (path.endsWith('.min.js')) return true;\n if (path.endsWith('.min.cjs')) return true;\n if (path.endsWith('.min.mjs')) return true;\n if (path.startsWith('data:')) return true;\n return false;\n}\n\n/**\n * Determines if we should skip contextlines based off the max lineno and colno values.\n */\nfunction shouldSkipContextLinesForFrame(frame: StackFrame): boolean {\n if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\n/**\n * Checks if we have all the contents that we need in the cache.\n */\nfunction rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (contents === undefined) return false;\n\n for (let i = range[0]; i <= range[1]; i++) {\n if (contents[i] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,\n * the ranges are merged to create a single range.\n */\nfunction makeLineReaderRanges(lines: number[], linecontext: number): ReadlineRange[] {\n if (!lines.length) {\n return [];\n }\n\n let i = 0;\n const line = lines[0];\n\n if (typeof line !== 'number') {\n return [];\n }\n\n let current = makeContextRange(line, linecontext);\n const out: ReadlineRange[] = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n\n // If the next line falls into the current range, extend the current range to lineno + linecontext.\n const next = lines[i + 1];\n if (typeof next !== 'number') {\n break;\n }\n if (next <= current[1]) {\n current[1] = next + linecontext;\n } else {\n out.push(current);\n current = makeContextRange(next, linecontext);\n }\n\n i++;\n }\n\n return out;\n}\n\n/**\n * Extracts lines from a file and stores them in a cache.\n */\nfunction getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {\n return new Promise((resolve, _reject) => {\n // It is important *not* to have any async code between createInterface and the 'line' event listener\n // as it will cause the 'line' event to\n // be emitted before the listener is attached.\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream,\n });\n\n // We need to explicitly destroy the stream to prevent memory leaks,\n // removing the listeners on the readline interface is not enough.\n // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892\n function destroyStreamAndResolve(): void {\n stream.destroy();\n resolve();\n }\n\n // Init at zero and increment at the start of the loop because lines are 1 indexed.\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.\n destroyStreamAndResolve();\n return;\n }\n let rangeStart = range[0];\n let rangeEnd = range[1];\n\n // We use this inside Promise.all, so we need to resolve the promise even if there is an error\n // to prevent Promise.all from short circuiting the rest.\n function onStreamError(e: Error): void {\n // Mark file path as failed to read and prevent multiple read attempts.\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n DEBUG_BUILD && logger.error(`Failed to read file: ${path}. Error: ${e}`);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n\n // We need to handle the error event to prevent the process from crashing in < Node 16\n // https://github.com/nodejs/node/pull/31603\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n\n lineReaded.on('line', line => {\n lineNumber++;\n if (lineNumber < rangeStart) return;\n\n // !Warning: This mutates the cache by storing the snipped line into the cache.\n output[lineNumber] = snipLine(line, 0);\n\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n // We need to close the file stream and remove listeners, else the reader will continue to run our listener;\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // This should never happen as it means we have a bug in the context.\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\n\n/**\n * Adds surrounding (context) lines of the line that an exception occurred on to the event.\n * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in\n * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple\n * failing reads from happening.\n */\n/* eslint-disable complexity */\nasync function addSourceContext(event: Event, contextLines: number): Promise<Event> {\n // keep a lookup map of which files we've already enqueued to read,\n // so we don't enqueue the same file multiple times which would cause multiple i/o reads\n const filesToLines: Record<string, number[]> = {};\n\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (!exception.stacktrace?.frames?.length) {\n continue;\n }\n\n // Maps preserve insertion order, so we iterate in reverse, starting at the\n // outermost frame and closer to where the exception has occurred (poor mans priority)\n for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {\n const frame: StackFrame | undefined = exception.stacktrace.frames[i];\n const filename = frame?.filename;\n\n if (\n !frame ||\n typeof filename !== 'string' ||\n typeof frame.lineno !== 'number' ||\n shouldSkipContextLinesForFile(filename) ||\n shouldSkipContextLinesForFrame(frame)\n ) {\n continue;\n }\n\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n // @ts-expect-error this is defined above\n filesToLines[filename].push(frame.lineno);\n }\n }\n }\n\n const files = Object.keys(filesToLines);\n if (files.length == 0) {\n return event;\n }\n\n const readlinePromises: Promise<void>[] = [];\n for (const file of files) {\n // If we failed to read this before, dont try reading it again.\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {\n continue;\n }\n\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) {\n continue;\n }\n\n // Sort ranges so that they are sorted by line increasing order and match how the file is read.\n filesToLineRanges.sort((a, b) => a - b);\n // Check if the contents are already in the cache and if we can avoid reading the file again.\n const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);\n if (ranges.every(r => rangeExistsInContentCache(file, r))) {\n continue;\n }\n\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n\n // The promise rejections are caught in order to prevent them from short circuiting Promise.all\n await Promise.all(readlinePromises).catch(() => {\n DEBUG_BUILD && logger.log('Failed to read one or more source files and resolve context lines');\n });\n\n // Perform the same loop as above, but this time we can assume all files are in the cache\n // and attempt to add source context to frames.\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) {\n addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);\n }\n }\n }\n\n return event;\n}\n/* eslint-enable complexity */\n\n/** Adds context lines to frames */\nfunction addSourceContextToFrames(\n frames: StackFrame[],\n contextLines: number,\n cache: LRUMap<string, Record<number, string>>,\n): void {\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {\n const contents = cache.get(frame.filename);\n if (contents === undefined) {\n continue;\n }\n\n addContextToFrame(frame.lineno, frame, contextLines, contents);\n }\n }\n}\n\n/**\n * Clears the context lines from a frame, used to reset a frame to its original state\n * if we fail to resolve all context lines for it.\n */\nfunction clearLineContext(frame: StackFrame): void {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\n\n/**\n * Resolves context lines before and after the given line number and appends them to the frame;\n */\nexport function addContextToFrame(\n lineno: number,\n frame: StackFrame,\n contextLines: number,\n contents: Record<number, string> | undefined,\n): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.\n // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.\n if (frame.lineno === undefined || contents === undefined) {\n DEBUG_BUILD && logger.error('Cannot resolve context for frame with no lineno or file contents');\n return;\n }\n\n frame.pre_context = [];\n for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {\n // We always expect the start context as line numbers cannot be negative. If we dont find a line, then\n // something went wrong somewhere. Clear the context and return without adding any linecontext.\n const line = contents[i];\n if (line === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${i} in file ${frame.filename}`);\n return;\n }\n\n frame.pre_context.push(line);\n }\n\n // We should always have the context line. If we dont, something went wrong, so we clear the context and return\n // without adding any linecontext.\n if (contents[lineno] === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${lineno} in file ${frame.filename}`);\n return;\n }\n\n frame.context_line = contents[lineno];\n\n const end = makeRangeEnd(lineno, contextLines);\n frame.post_context = [];\n for (let i = lineno + 1; i <= end; i++) {\n // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could\n // just be that we reached the end of the file.\n const line = contents[i];\n if (line === undefined) {\n break;\n }\n frame.post_context.push(line);\n }\n}\n\n// Helper functions for generating line context ranges. They take a line number and the number of lines of context to\n// include before and after the line and generate an inclusive range of indices.\ntype ReadlineRange = [start: number, end: number];\n// Compute inclusive end context range\nfunction makeRangeStart(line: number, linecontext: number): number {\n return Math.max(1, line - linecontext);\n}\n// Compute inclusive start context range\nfunction makeRangeEnd(line: number, linecontext: number): number {\n return line + linecontext;\n}\n// Determine start and end indices for context range (inclusive);\nfunction makeContextRange(line: number, linecontext: number): [start: number, end: number] {\n return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];\n}\n\n/** Exported only for tests, as a type-safe variant. */\nexport const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture the lines before and after the frame's context.\n */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\n"],"names":[],"mappings":";;;;;AAMA,MAAM,0BAA0B,IAAI,MAAM,CAAiC,EAAE,CAAC;AAC9E,MAAM,mCAAmC,IAAI,MAAM,CAAY,EAAE,CAAC;AAClE,MAAM,wBAAA,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AAA,GAAA,OAAA,CAAA,iBAAA,KAAA,SAAA,GAAA,OAAA,CAAA,iBAAA,GAAA,wBAAA;;AAEA,EAAA,OAAA;AACA,IAAA,IAAA,EAAA,gBAAA;AACA,IAAA,YAAA,CAAA,KAAA,EAAA;AACA,MAAA,OAAA,gBAAA,CAAA,KAAA,EAAA,YAAA,CAAA;AACA,KAAA;AACA,GAAA;AACA,CAAA,CAAA;;AAEA;AACA;AACA;AACA,MAAA,uBAAA,GAAA,iBAAA,CAAA,wBAAA;;;;"}
1
+ {"version":3,"file":"contextlines.js","sources":["../../../src/integrations/contextlines.ts"],"sourcesContent":["import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport type { Event, IntegrationFn, StackFrame } from '@sentry/core';\nimport { defineIntegration, logger, LRUMap, snipLine } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap<string, 1>(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst INTEGRATION_NAME = 'ContextLines';\n// Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be\n// minified code while large lineno values are likely to be bundled code.\n// Exported for testing purposes.\nexport const MAX_CONTEXTLINES_COLNO: number = 1000;\nexport const MAX_CONTEXTLINES_LINENO: number = 10000;\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to 7.\n *\n * Set to 0 to disable loading and inclusion of source files.\n **/\n frameContextLines?: number;\n}\n\n/**\n * Exported for testing purposes.\n */\nexport function resetFileContentCache(): void {\n LRU_FILE_CONTENTS_CACHE.clear();\n}\n\n/**\n * Get or init map value\n */\nfunction emplace<T extends LRUMap<K, V>, K extends string, V>(map: T, key: K, contents: V): V {\n const value = map.get(key);\n\n if (value === undefined) {\n map.set(key, contents);\n return contents;\n }\n\n return value;\n}\n\n/**\n * Determines if context lines should be skipped for a file.\n * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source\n * - node: prefixed modules are part of the runtime and cannot be resolved to a file\n * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports\n */\nfunction shouldSkipContextLinesForFile(path: string): boolean {\n // Test the most common prefix and extension first. These are the ones we\n // are most likely to see in user applications and are the ones we can break out of first.\n if (path.startsWith('node:')) return true;\n if (path.endsWith('.min.js')) return true;\n if (path.endsWith('.min.cjs')) return true;\n if (path.endsWith('.min.mjs')) return true;\n if (path.startsWith('data:')) return true;\n return false;\n}\n\n/**\n * Determines if we should skip contextlines based off the max lineno and colno values.\n */\nfunction shouldSkipContextLinesForFrame(frame: StackFrame): boolean {\n if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\n/**\n * Checks if we have all the contents that we need in the cache.\n */\nfunction rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (contents === undefined) return false;\n\n for (let i = range[0]; i <= range[1]; i++) {\n if (contents[i] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,\n * the ranges are merged to create a single range.\n */\nfunction makeLineReaderRanges(lines: number[], linecontext: number): ReadlineRange[] {\n if (!lines.length) {\n return [];\n }\n\n let i = 0;\n const line = lines[0];\n\n if (typeof line !== 'number') {\n return [];\n }\n\n let current = makeContextRange(line, linecontext);\n const out: ReadlineRange[] = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n\n // If the next line falls into the current range, extend the current range to lineno + linecontext.\n const next = lines[i + 1];\n if (typeof next !== 'number') {\n break;\n }\n if (next <= current[1]) {\n current[1] = next + linecontext;\n } else {\n out.push(current);\n current = makeContextRange(next, linecontext);\n }\n\n i++;\n }\n\n return out;\n}\n\n/**\n * Extracts lines from a file and stores them in a cache.\n */\nfunction getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {\n return new Promise((resolve, _reject) => {\n // It is important *not* to have any async code between createInterface and the 'line' event listener\n // as it will cause the 'line' event to\n // be emitted before the listener is attached.\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream,\n });\n\n // We need to explicitly destroy the stream to prevent memory leaks,\n // removing the listeners on the readline interface is not enough.\n // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892\n function destroyStreamAndResolve(): void {\n stream.destroy();\n resolve();\n }\n\n // Init at zero and increment at the start of the loop because lines are 1 indexed.\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.\n destroyStreamAndResolve();\n return;\n }\n let rangeStart = range[0];\n let rangeEnd = range[1];\n\n // We use this inside Promise.all, so we need to resolve the promise even if there is an error\n // to prevent Promise.all from short circuiting the rest.\n function onStreamError(e: Error): void {\n // Mark file path as failed to read and prevent multiple read attempts.\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n DEBUG_BUILD && logger.error(`Failed to read file: ${path}. Error: ${e}`);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n\n // We need to handle the error event to prevent the process from crashing in < Node 16\n // https://github.com/nodejs/node/pull/31603\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n\n lineReaded.on('line', line => {\n lineNumber++;\n if (lineNumber < rangeStart) return;\n\n // !Warning: This mutates the cache by storing the snipped line into the cache.\n output[lineNumber] = snipLine(line, 0);\n\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n // We need to close the file stream and remove listeners, else the reader will continue to run our listener;\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // This should never happen as it means we have a bug in the context.\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\n\n/**\n * Adds surrounding (context) lines of the line that an exception occurred on to the event.\n * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in\n * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple\n * failing reads from happening.\n */\n/* eslint-disable complexity */\nasync function addSourceContext(event: Event, contextLines: number): Promise<Event> {\n // keep a lookup map of which files we've already enqueued to read,\n // so we don't enqueue the same file multiple times which would cause multiple i/o reads\n const filesToLines: Record<string, number[]> = {};\n\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (!exception.stacktrace?.frames?.length) {\n continue;\n }\n\n // Maps preserve insertion order, so we iterate in reverse, starting at the\n // outermost frame and closer to where the exception has occurred (poor mans priority)\n for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {\n const frame: StackFrame | undefined = exception.stacktrace.frames[i];\n const filename = frame?.filename;\n\n if (\n !frame ||\n typeof filename !== 'string' ||\n typeof frame.lineno !== 'number' ||\n shouldSkipContextLinesForFile(filename) ||\n shouldSkipContextLinesForFrame(frame)\n ) {\n continue;\n }\n\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n // @ts-expect-error this is defined above\n filesToLines[filename].push(frame.lineno);\n }\n }\n }\n\n const files = Object.keys(filesToLines);\n if (files.length == 0) {\n return event;\n }\n\n const readlinePromises: Promise<void>[] = [];\n for (const file of files) {\n // If we failed to read this before, dont try reading it again.\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {\n continue;\n }\n\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) {\n continue;\n }\n\n // Sort ranges so that they are sorted by line increasing order and match how the file is read.\n filesToLineRanges.sort((a, b) => a - b);\n // Check if the contents are already in the cache and if we can avoid reading the file again.\n const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);\n if (ranges.every(r => rangeExistsInContentCache(file, r))) {\n continue;\n }\n\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n\n // The promise rejections are caught in order to prevent them from short circuiting Promise.all\n await Promise.all(readlinePromises).catch(() => {\n DEBUG_BUILD && logger.log('Failed to read one or more source files and resolve context lines');\n });\n\n // Perform the same loop as above, but this time we can assume all files are in the cache\n // and attempt to add source context to frames.\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) {\n addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);\n }\n }\n }\n\n return event;\n}\n/* eslint-enable complexity */\n\n/** Adds context lines to frames */\nfunction addSourceContextToFrames(\n frames: StackFrame[],\n contextLines: number,\n cache: LRUMap<string, Record<number, string>>,\n): void {\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {\n const contents = cache.get(frame.filename);\n if (contents === undefined) {\n continue;\n }\n\n addContextToFrame(frame.lineno, frame, contextLines, contents);\n }\n }\n}\n\n/**\n * Clears the context lines from a frame, used to reset a frame to its original state\n * if we fail to resolve all context lines for it.\n */\nfunction clearLineContext(frame: StackFrame): void {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\n\n/**\n * Resolves context lines before and after the given line number and appends them to the frame;\n */\nexport function addContextToFrame(\n lineno: number,\n frame: StackFrame,\n contextLines: number,\n contents: Record<number, string> | undefined,\n): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.\n // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.\n if (frame.lineno === undefined || contents === undefined) {\n DEBUG_BUILD && logger.error('Cannot resolve context for frame with no lineno or file contents');\n return;\n }\n\n frame.pre_context = [];\n for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {\n // We always expect the start context as line numbers cannot be negative. If we dont find a line, then\n // something went wrong somewhere. Clear the context and return without adding any linecontext.\n const line = contents[i];\n if (line === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${i} in file ${frame.filename}`);\n return;\n }\n\n frame.pre_context.push(line);\n }\n\n // We should always have the context line. If we dont, something went wrong, so we clear the context and return\n // without adding any linecontext.\n if (contents[lineno] === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${lineno} in file ${frame.filename}`);\n return;\n }\n\n frame.context_line = contents[lineno];\n\n const end = makeRangeEnd(lineno, contextLines);\n frame.post_context = [];\n for (let i = lineno + 1; i <= end; i++) {\n // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could\n // just be that we reached the end of the file.\n const line = contents[i];\n if (line === undefined) {\n break;\n }\n frame.post_context.push(line);\n }\n}\n\n// Helper functions for generating line context ranges. They take a line number and the number of lines of context to\n// include before and after the line and generate an inclusive range of indices.\ntype ReadlineRange = [start: number, end: number];\n// Compute inclusive end context range\nfunction makeRangeStart(line: number, linecontext: number): number {\n return Math.max(1, line - linecontext);\n}\n// Compute inclusive start context range\nfunction makeRangeEnd(line: number, linecontext: number): number {\n return line + linecontext;\n}\n// Determine start and end indices for context range (inclusive);\nfunction makeContextRange(line: number, linecontext: number): [start: number, end: number] {\n return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];\n}\n\n/** Exported only for tests, as a type-safe variant. */\nexport const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture the lines before and after the frame's context.\n */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration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A,WAAA,CAAA,EAAA,YAAA,CAAA,IAAA,EAAA,WAAA,CAAA,CAAA;AACA;;AAEA;AACA,MAAA,wBAAA,IAAA,CAAA,OAAA,GAAA,EAAA,KAAA;AACA,EAAA,MAAA,YAAA,GAAA,OAAA,CAAA,iBAAA,KAAA,SAAA,GAAA,OAAA,CAAA,iBAAA,GAAA,wBAAA;;AAEA,EAAA,OAAA;AACA,IAAA,IAAA,EAAA,gBAAA;AACA,IAAA,YAAA,CAAA,KAAA,EAAA;AACA,MAAA,OAAA,gBAAA,CAAA,KAAA,EAAA,YAAA,CAAA;AACA,KAAA;AACA,GAAA;AACA,CAAA,CAAA;;AAEA;AACA;AACA;AACA,MAAA,uBAAA,GAAA,iBAAA,CAAA,wBAAA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"fs.js","sources":["../../../src/integrations/fs.ts"],"sourcesContent":["import { FsInstrumentation } from '@opentelemetry/instrumentation-fs';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, defineIntegration } from '@sentry/core';\nimport { generateInstrumentOnce } from '../otel/instrument';\n\nconst INTEGRATION_NAME = 'FileSystem';\n\n/**\n * This integration will create spans for `fs` API operations, like reading and writing files.\n *\n * **WARNING:** This integration may add significant overhead to your application. Especially in scenarios with a lot of\n * file I/O, like for example when running a framework dev server, including this integration can massively slow down\n * your application.\n *\n * @param options Configuration for this integration.\n */\nexport const fsIntegration = defineIntegration(\n (\n options: {\n /**\n * Setting this option to `true` will include any filepath arguments from your `fs` API calls as span attributes.\n *\n * Defaults to `false`.\n */\n recordFilePaths?: boolean;\n\n /**\n * Setting this option to `true` will include the error messages of failed `fs` API calls as a span attribute.\n *\n * Defaults to `false`.\n */\n recordErrorMessagesAsSpanAttributes?: boolean;\n } = {},\n ) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new FsInstrumentation({\n requireParentSpan: true,\n endHook(functionName, { args, span, error }) {\n span.updateName(`fs.${functionName}`);\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'file',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.file.fs',\n });\n\n if (options.recordErrorMessagesAsSpanAttributes) {\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n span.setAttribute('path_argument', args[0]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)\n ) {\n span.setAttribute('target_argument', args[0]);\n span.setAttribute('path_argument', args[1]);\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n span.setAttribute('prefix_argument', args[0]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)\n ) {\n span.setAttribute('existing_path_argument', args[0]);\n span.setAttribute('new_path_argument', args[1]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)\n ) {\n span.setAttribute('src_argument', args[0]);\n span.setAttribute('dest_argument', args[1]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)\n ) {\n span.setAttribute('old_path_argument', args[0]);\n span.setAttribute('new_path_argument', args[1]);\n }\n }\n\n if (error && options.recordErrorMessagesAsSpanAttributes) {\n span.setAttribute('fs_error', error.message);\n }\n },\n }),\n )();\n },\n };\n },\n);\n\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n"],"names":[],"mappings":";;;;AAIA,MAAM,gBAAA,GAAmB,YAAY;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAc,GAAE,iBAAiB;AAC9C,EAAE;AACF,IAAI;;AAcA,GAAI,EAAE;AACV,OAAO;AACP,IAAI,OAAO;AACX,MAAM,IAAI,EAAE,gBAAgB;AAC5B,MAAM,SAAS,GAAG;AAClB,QAAQ,sBAAsB;AAC9B,UAAU,gBAAgB;AAC1B,UAAU;AACV,YAAY,IAAI,iBAAiB,CAAC;AAClC,cAAc,iBAAiB,EAAE,IAAI;AACrC,cAAc,OAAO,CAAC,YAAY,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,KAAM,EAAC,EAAE;AAC3D,gBAAgB,IAAI,CAAC,UAAU,CAAC,CAAC,GAAG,EAAE,YAAY,CAAC,CAAA,CAAA;;AAEA,gBAAA,IAAA,CAAA,aAAA,CAAA;AAC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AAA,OAAA;AACA,EAAA,OAAA;AACA,EAAA,QAAA;AACA,EAAA,OAAA;AACA,EAAA,QAAA;AACA,EAAA,OAAA;AACA,EAAA,SAAA;AACA,EAAA,MAAA;AACA,EAAA,SAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA,UAAA;AACA,EAAA,UAAA;AACA,EAAA,iBAAA;AACA,EAAA,IAAA;AACA,EAAA,OAAA;AACA,EAAA,MAAA;AACA,EAAA,UAAA;AACA,EAAA,QAAA;AACA,EAAA,QAAA;AACA,EAAA,WAAA;AACA,EAAA,YAAA;AACA,EAAA,gBAAA;AACA,EAAA,WAAA;AACA,EAAA,WAAA;AACA,EAAA,YAAA;AACA,EAAA,YAAA;AACA,EAAA,WAAA;AACA,EAAA,aAAA;AACA,EAAA,aAAA;AACA,EAAA,WAAA;AACA,EAAA,UAAA;AACA,EAAA,aAAA;AACA,EAAA,cAAA;AACA,EAAA,cAAA;AACA,EAAA,cAAA;AACA,EAAA,qBAAA;AACA,EAAA,WAAA;AACA,EAAA,QAAA;AACA,EAAA,UAAA;AACA,EAAA,cAAA;AACA,EAAA,YAAA;AACA,EAAA,YAAA;AACA,EAAA,eAAA;AACA,CAAA;;;;"}
1
+ {"version":3,"file":"fs.js","sources":["../../../src/integrations/fs.ts"],"sourcesContent":["import { FsInstrumentation } from '@opentelemetry/instrumentation-fs';\nimport { defineIntegration, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';\nimport { generateInstrumentOnce } from '../otel/instrument';\n\nconst INTEGRATION_NAME = 'FileSystem';\n\n/**\n * This integration will create spans for `fs` API operations, like reading and writing files.\n *\n * **WARNING:** This integration may add significant overhead to your application. Especially in scenarios with a lot of\n * file I/O, like for example when running a framework dev server, including this integration can massively slow down\n * your application.\n *\n * @param options Configuration for this integration.\n */\nexport const fsIntegration = defineIntegration(\n (\n options: {\n /**\n * Setting this option to `true` will include any filepath arguments from your `fs` API calls as span attributes.\n *\n * Defaults to `false`.\n */\n recordFilePaths?: boolean;\n\n /**\n * Setting this option to `true` will include the error messages of failed `fs` API calls as a span attribute.\n *\n * Defaults to `false`.\n */\n recordErrorMessagesAsSpanAttributes?: boolean;\n } = {},\n ) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new FsInstrumentation({\n requireParentSpan: true,\n endHook(functionName, { args, span, error }) {\n span.updateName(`fs.${functionName}`);\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'file',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.file.fs',\n });\n\n if (options.recordErrorMessagesAsSpanAttributes) {\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n span.setAttribute('path_argument', args[0]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)\n ) {\n span.setAttribute('target_argument', args[0]);\n span.setAttribute('path_argument', args[1]);\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n span.setAttribute('prefix_argument', args[0]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)\n ) {\n span.setAttribute('existing_path_argument', args[0]);\n span.setAttribute('new_path_argument', args[1]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)\n ) {\n span.setAttribute('src_argument', args[0]);\n span.setAttribute('dest_argument', args[1]);\n } else if (\n typeof args[0] === 'string' &&\n typeof args[1] === 'string' &&\n FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)\n ) {\n span.setAttribute('old_path_argument', args[0]);\n span.setAttribute('new_path_argument', args[1]);\n }\n }\n\n if (error && options.recordErrorMessagesAsSpanAttributes) {\n span.setAttribute('fs_error', error.message);\n }\n },\n }),\n )();\n },\n };\n },\n);\n\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n"],"names":[],"mappings":";;;;AAIA,MAAM,gBAAA,GAAmB,YAAY;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAc,GAAE,iBAAiB;AAC9C,EAAE;AACF,IAAI;;AAcA,GAAI,EAAE;AACV,OAAO;AACP,IAAI,OAAO;AACX,MAAM,IAAI,EAAE,gBAAgB;AAC5B,MAAM,SAAS,GAAG;AAClB,QAAQ,sBAAsB;AAC9B,UAAU,gBAAgB;AAC1B,UAAU;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